Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Code of Conduct

## Our Pledge

We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.

We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.

## Our Standards

Examples of behavior that contributes to a positive environment include:

- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
- Focusing on what is best not just for us as individuals, but for the overall community

Examples of unacceptable behavior include:

- The use of sexualized language or imagery, and sexual attention or advances of any kind
- Trolling, insulting or derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or email address, without their explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional setting

## Enforcement Responsibilities

Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.

Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.

## Scope

This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at conduct@clickhouse.com. All complaints will be reviewed and investigated promptly and fairly.

All community leaders are obligated to respect the privacy and security of the reporter of any incident.

## Enforcement Guidelines

Community leaders will follow these guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:

### 1. Correction

**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.

**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.

### 2. Warning

**Community Impact**: A violation through a single incident or series of actions.

**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.

### 3. Temporary Ban

**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.

**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.

### 4. Permanent Ban

**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.

**Consequence**: A permanent ban from any sort of public interaction within the community.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 2.1, available at https://www.contributor-covenant.org/version/2/1/code_of_conduct.html.
76 changes: 72 additions & 4 deletions docs/howto/tracing.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,15 +114,25 @@ before talking to the server), the client invokes
`db.operation.name`, `db.collection.name` and `clickhouse.request.sent_rows`
(insert; the row count is recorded for array-based inserts only),
`clickhouse.request.query_id`, and
`clickhouse.request.session_id`.
`clickhouse.request.session_id`. Any per-request
[`span_attributes`](#enriching-spans-with-span_attributes) and, when
[`dangerously_log_query_text`](#logging-the-raw-query-text) is enabled, the
raw SQL as `db.query.text` are merged into this initial bag too.
2. Inside `fn`, the network operation runs with the span as the active span
(when the context manager supports it; see above).
3. `span.setAttributes({ 'clickhouse.request.query_id': <server-assigned id> })` -
so you always have the final `query_id`, even when the caller did not pass
one and the connection layer generated it. Once the response arrives, the
span also gets `db.response.status_code` (HTTP status) and, when the
`X-ClickHouse-Summary` header is present (e.g. with `wait_end_of_query`),
`clickhouse.summary.*` counters (`read_rows`, `written_rows`, …).
the `clickhouse.summary.*` counters. **Every** key present in the parsed
summary is recorded (the set is not hardcoded), so you get `read_rows`,
`read_bytes`, `written_rows`, `written_bytes`, `result_rows`,
`result_bytes`, `total_rows_to_read`, `elapsed_ns`, and — on servers that
report them — `memory_usage` (peak query memory, in bytes),
`real_time_microseconds`, and any future server-side additions for free.
These counters are attached to every operation span, including the outer
`clickhouse.query` span.
4. On success, the span status is left **unset**, per the OTEL span status
spec for client spans. On failure,
`span.setAttributes({ 'error.type': <error class name> })` (plus
Expand Down Expand Up @@ -150,15 +160,73 @@ propagates to the caller of `query` / `command` / `exec` / `insert` /
> ends when the result set is fully consumed (`text()`/`json()` resolve, or
> the `stream()` is read to completion), closed via `close()`, or fails
> (the error is recorded on this span). When it ends it carries the final
> `clickhouse.response.decoded_bytes` and, for row-streaming consumption,
> `db.response.returned_rows` metrics.
> `clickhouse.response.decoded_bytes` and `db.response.returned_rows`
> metrics. `returned_rows` is recorded both for row-streaming consumption
> (`stream()`, and `json()` on the streamable JSON formats) and for
> non-streaming `json()` on `JSON` / `JSONObjectEachRow` / the other
> single-document JSON formats.
>
> This split makes it easy to distinguish the original request round-trip from
> a stream that may never end (e.g. tailing a live materialized view). If the
> `ResultSet` is never consumed nor closed, the `clickhouse.query.stream` span
> is never ended. For `command`/`exec`/`insert`/`ping`, a single span ends
> when the method returns.

## Enriching spans with `span_attributes`

Every request method (`query` / `command` / `exec` / `insert` / `ping`)
accepts an optional `span_attributes` bag that is merged into the operation
span. This is the recommended way to attach application-level context to your
traces — for example, mirroring the tags you also send to ClickHouse via the
[`log_comment`](https://clickhouse.com/docs/operations/settings/settings#log_comment)
setting so the same context is visible both in `system.query_log` and in your
tracing backend:

```ts
const tag = {
route: "events.getAgentGraphData",
tenant: "acme",
surface: "api",
};

await client.query({
query: "SELECT * FROM events WHERE tenant = {tenant:String}",
query_params: { tenant: tag.tenant },
// Visible in ClickHouse's system.query_log
clickhouse_settings: { log_comment: JSON.stringify(tag) },
// Visible on the tracing span
span_attributes: {
"app.route": tag.route,
"app.tenant": tag.tenant,
"app.surface": tag.surface,
},
});
```

Values may be `string`, `number`, or `boolean`. Caller-provided attributes
**never override** the client's own semantic-convention attributes (`db.*`,
`server.*`, `clickhouse.*`) on a key collision. `span_attributes` are ignored
when no tracer is configured.

## Logging the raw query text

By default the client **never** attaches the raw SQL to spans or logs, because
a statement can contain sensitive data inlined as literals. Set
`dangerously_log_query_text: true` at client creation to opt in:

```ts
const client = createClient({
tracer: trace.getTracer("clickhouse-js"),
dangerously_log_query_text: true,
});
```

When enabled, the raw SQL is attached to every operation span as the OTEL
[`db.query.text`](https://opentelemetry.io/docs/specs/semconv/database/database-spans/#common-attributes)
attribute, and (Node.js) included in the `error`-level log emitted when a
request fails. Bound `query_params` values and credentials are **never** logged
or traced, regardless of this setting.

## Adapter recipes: `requireParentSpan` and suppressing nested HTTP spans

OpenTelemetry auto-instrumentation packages commonly expose two options that
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,35 @@ describe("select with query binding", () => {
const response = await rs.text();
expect(response).toBe('"2022-05-02 13:25:55.123456789"\n');
});

it("handles Array(Date) in a parameterized query", async () => {
const rs = await client.query({
query: "SELECT {dates: Array(Date)} AS dates",
format: "JSONEachRow",
query_params: {
dates: [
new Date(Date.UTC(2023, 4, 5)),
new Date(Date.UTC(2021, 0, 2)),
],
},
});

expect(await rs.json()).toEqual([
{ dates: ["2023-05-05", "2021-01-02"] },
]);
});

it("binds a Date inside Array(DateTime) at day precision (time is dropped)", async () => {
const rs = await client.query({
query: "SELECT {dates: Array(DateTime)} AS dates",
format: "JSONEachRow",
query_params: {
dates: [new Date(Date.UTC(2022, 4, 2, 13, 25, 55))],
},
});

expect(await rs.json()).toEqual([{ dates: ["2022-05-02 00:00:00"] }]);
});
});

it("handles an array of strings in a parameterized query", async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -249,4 +249,52 @@ describe("formatQueryParams", () => {
}),
).toBe("{'name':'test','flags':[TRUE,FALSE],'tuple':(FALSE,TRUE)}");
});

it("formats a Date inside an array as a quoted date string", () => {
expect(
formatQueryParams({
value: [new Date(Date.UTC(2022, 6, 29, 7, 52, 14))],
}),
).toBe("['2022-07-29']");
});

it("formats a Date inside a nested array as a quoted date string", () => {
expect(
formatQueryParams({
value: [[new Date(Date.UTC(2023, 4, 5))]],
}),
).toBe("[['2023-05-05']]");
});

it("formats a Date inside a tuple as a quoted date string", () => {
expect(
formatQueryParams({
value: new TupleParam([new Date(Date.UTC(2023, 4, 5))]),
}),
).toBe("('2023-05-05')");
});

it("formats a Date inside an object value as a quoted date string", () => {
expect(
formatQueryParams({
value: { d: new Date(Date.UTC(2023, 4, 5)) },
}),
).toBe("{'d':'2023-05-05'}");
});

it("uses the UTC date and drops the time for a Date inside an array", () => {
expect(
formatQueryParams({
value: [new Date(Date.UTC(2022, 6, 29, 23, 59, 59, 999))],
}),
).toBe("['2022-07-29']");
});

it("formats a Date alongside other types inside an array", () => {
expect(
formatQueryParams({
value: [new Date(Date.UTC(2023, 4, 5)), "foo", 42, null],
}),
).toBe("['2023-05-05','foo',42,NULL]");
});
});
Loading
Loading