Skip to content

Latest commit

 

History

History
1370 lines (947 loc) · 75.3 KB

File metadata and controls

1370 lines (947 loc) · 75.3 KB

1.24.0

New features

  • OpenTelemetry: richer, more actionable spans (requested by Langfuse, #948). (#950)
    • The X-ClickHouse-Summary header is now parsed on the Web client and attached to the operation spans (query / command / exec / insert), including the outer clickhouse.query span. Previously the Web client did not parse the summary header at all.
    • Every key present in the summary header is recorded as clickhouse.summary.<key> (the set is not hardcoded). This surfaces total_rows_to_read and memory_usage (peak query memory, in bytes; sent by newer servers), and picks up future server-side additions (e.g. real_time_microseconds) automatically.
    • db.response.returned_rows is now recorded for non-streaming result consumption too (json() on JSON / JSONObjectEachRow / the other single-document JSON formats), not just row-streaming paths.
    • Added a span_attributes field to the per-request query params (query / command / exec / insert / ping). Use it to enrich the operation span with application-level context — e.g. mirroring the tags you also send via the log_comment setting (route, tenant, surface, etc.). Caller-provided attributes never override the client's own db.* / server.* / clickhouse.* attributes.
    • Added a dangerously_log_query_text client option (default false). When enabled, the raw SQL statement is attached to spans as the OpenTelemetry db.query.text attribute. The query text may contain sensitive literals, which is why it is off by default; bound query_params values and credentials are never traced regardless of this setting.

Bug fixes

  • Fixed Array(Date) / Array(Date32) query-parameter binding (and other temporal element types nested in arrays, tuples, and maps). A JS Date inside a container was serialized as a bare Unix timestamp (e.g. [1683244800]), which the server's Array(Date) element parser rejects (CANNOT_PARSE_INPUT_ASSERTION_FAILED). Container-nested Date values are now emitted as a quoted UTC date string (e.g. ['2023-05-05']), the one encoding every temporal element type accepts. Note: a Date used inside Array(DateTime) / Array(DateTime64) is now bound at day precision (the time-of-day is dropped), since date-only is the only form Array(Date) accepts; scalar Date / DateTime binding is unchanged. (#947)

1.23.1

Bug Fixes

  • Re-export EXCEPTION_TAG_HEADER_NAME and extractErrorAtTheEndOfChunk from @clickhouse/client-web. Both are part of the (now deprecated) @clickhouse/client-common public API but were missed when its surface was bundled into and re-exported from the client packages in 1.23.0 (#845). Reported downstream by Langfuse. (#935)

1.23.0

Migration Notes

  • Node.js 26.x was added to the CI matrix, and Node.js 18.x is no longer supported. The engines.node floor of @clickhouse/client (previously >=16) and @clickhouse/datatype-parser (previously >=18.0.0) was raised to >=20. Node.js 20.x, 22.x, 24.x, and 26.x are supported and exercised in CI.

  • The @clickhouse/client-common package is deprecated. @clickhouse/client (Node.js) and @clickhouse/client-web (Web) no longer depend on it; the shared code is now bundled into each client package. Everything previously importable from @clickhouse/client-common should be imported from @clickhouse/client or @clickhouse/client-web instead. The @clickhouse/client-common package itself will no longer receive updates. (#845)

  • The parseColumnType function and its SimpleColumnTypes companion (exported from @clickhouse/client, @clickhouse/client-web, and @clickhouse/client-common) are deprecated and slated for removal in a future major version. They are superseded by the new standalone @clickhouse/datatype-parser package (parseDataType plus its Node AST), which parses the full ClickHouse data-type grammar and emits an AST that mirrors the server's. (#893)

New features

  • (Node.js) Added a RowBinary reader library and agent skill under skills/clickhouse-js-node-rowbinary-parser. It ships type-specific, monomorphizable building blocks for decoding RowBinary / RowBinaryWithNames / RowBinaryWithNamesAndTypes streams (full-buffer and chunked), plus a skill that guides an agent to generate bespoke high-performance parsers from a query's column types. The skill is bundled into @clickhouse/client (registered in agents.skills) and is also published independently as the @clickhouse/rowbinary package. A matching RowBinary writer is planned. (#864)

  • Published the @clickhouse/datatype-parser package: a small, dependency-free standalone parser for ClickHouse data-type strings (the kind sent in the types row of RowBinaryWithNamesAndTypes, e.g. Array(Nullable(UInt64)), Tuple(a UInt8, b String), Enum8('a' = 1)). It is a faithful port of the server's ParserDataType and emits a JSON AST that is byte-identical to the server's EXPLAIN AST json = 1 data-type subtree. It supersedes the deprecated parseColumnType (see Migration Notes). (#893)

  • (Node.js, @experimental) Added an additive connection?: Connection<Stream.Readable> option to createClient that lets a caller plug an externally-built backend Connection-like object in place of the default HTTP(S) factory. Only supposed to be used for testing the chDB integration. ([#879])

  • Added ClickHouseSettingsInterface, a package-neutral structural counterpart to ClickHouseSettings, exported from @clickhouse/client, @clickhouse/client-web, and @clickhouse/client-common. It is identical to ClickHouseSettings except that its index signature omits SettingsMap (a class with a private member, which TypeScript compares nominally). Because each client package now bundles its own copy of the common module, their ClickHouseSettings types are mutually unassignable; ClickHouseSettingsInterface is structurally identical across all three packages and assignable into each package's ClickHouseSettings, so a consumer that shares a single settings-producing helper across both the Node.js and Web clients can type it against this one type without casts. Values typed as SettingsMap cannot be carried through it — use ClickHouseSettings if you need them. (#889)

1.22.0

New features

  • (Node.js) The compression.request / compression.response client options now accept an explicit codec via an object, in addition to the existing boolean: true keeps gzip (backwards compatible), and { codec: "zstd" } selects zstd. The object form is intentionally extensible for future codecs and codec-specific options. zstd typically yields a similar-or-better ratio than gzip at noticeably lower CPU cost (gzip/DEFLATE is comparatively CPU-heavy and decompressed single-threaded by the ClickHouse server), and it uses the built-in zlib zstd support, so it requires Node.js >= 22.15.0 (@clickhouse/client throws a clear error at client creation otherwise). Response decompression is driven by the server's actual Content-Encoding, so it degrades gracefully. The request object form also accepts an optional level ({ codec, level }) to set the codec-specific compression level (zlib level for gzip, zstd compression level for zstd); the response compression level is controlled by the server. Supported only by @clickhouse/client (Node.js); @clickhouse/client-web rejects the zstd codec at client creation.

  • (Node.js) Brotli ({ codec: "br" }) is now supported for compression.request / compression.response, alongside gzip and zstd. Unlike zstd, Brotli is available on every supported Node.js version (no minimum-version requirement). The compression.request option is a per-codec discriminated union, so each codec exposes its own tuning option: a level for gzip/zstd, a quality for Brotli ({ codec: "br", quality }). When omitted, Brotli defaults to quality 4 for request bodies, since zlib's brotli default of 11 (max) is far too slow for a streaming insert path. Response decompression follows the server's Content-Encoding. Supported only by @clickhouse/client (Node.js).

Internal changes (@clickhouse/client-common)

These only affect code that imports the low-level connection primitives from the deprecated @clickhouse/client-common package directly (e.g. a custom Connection implementation). The createClient compression option is unchanged and fully backwards compatible — if you only use @clickhouse/client or @clickhouse/client-web, you are not affected.

To carry the codec (and its optional compression level) instead of a bare on/off flag, the internal compression representation changed shape:

  • CompressionSettings.compress_request / decompress_response are no longer boolean. They are now a normalized codec object or undefined (disabled): { codec: "gzip" | "zstd"; level?: number } | { codec: "br"; quality?: number } for the request, { codec: "gzip" | "zstd" | "br" } for the response (response compression options are chosen by the server). getConnectionParams normalizes the public request option into this form (true{ codec: "gzip" }).
  • withCompressionHeaders now takes request_compression_codec / response_compression_codec (a CompressionMethod | undefined) instead of the boolean enable_request_compression / enable_response_compression; the codec value is also the Content-Encoding / Accept-Encoding it emits.
  • withHttpSettings now takes the response codec object ({ codec } | undefined) instead of a boolean.
  • New exported types: CompressionMethod, RequestCompression, ResponseCompression.

Why: a single boolean could not express which codec to use or its level, and a separate level field on CompressionSettings would have mixed a codec-specific option into the shared type. Discriminating by codec keeps each codec's options on the codec it belongs to.

Documentation

  • Added two tracer adapter recipes to docs/howto/tracing.md and examples/node/coding/otel_tracing.ts, demonstrating how common OpenTelemetry auto-instrumentation options compose as thin userland wrappers around the tracer API instead of being baked into the client: requireParentSpan (skip ClickHouse spans when there is no active parent span — e.g. background health checks) and suppressing the duplicate nested HTTP spans emitted by @opentelemetry/instrumentation-http (via suppressTracing from @opentelemetry/core).

1.21.0

New features

  • The tracer API (unreleased, introduced in #776) now follows the OpenTelemetry database semantic conventions and matches the attribute vocabulary of the Rust client (clickhouse-rs); see docs/howto/tracing.md for the documentation. In particular (#828):

    • Spans now carry db.system.name (instead of db.system), server.address + server.port (instead of a combined host:port), clickhouse.request.query_id / clickhouse.request.session_id (instead of clickhouse.query_id / clickhouse.session_id), clickhouse.response.format on query and clickhouse.request.format on insert (instead of clickhouse.format), and db.operation.name + db.collection.name on insert (instead of clickhouse.table).
    • The span status is left unset on success (per the OTEL spec recommendation for client spans, previously set to OK); on failure, the span gets the error.type attribute (the error class name) and, for server-side errors, clickhouse.error.code (the numeric ClickHouse error code).
    • Spans record response-side attributes: db.response.status_code (HTTP status) and, when the X-ClickHouse-Summary header is available, clickhouse.summary.* counters (read_rows, written_rows, etc.).
    • query() now emits two spans: clickhouse.query covers the HTTP request lifetime and ends as soon as the response headers are received; a child clickhouse.query.stream span is handed to the ResultSet and tracks the stream consumption, ending when the response is fully read, closed, or fails - with the final clickhouse.response.decoded_bytes and (for row-streaming) db.response.returned_rows metrics. This separation makes it easy to distinguish the original request duration from a stream that may never end (e.g. tailing a live table).
    • Fixed a span leak in the Web ResultSet.stream() path: if the underlying fetch response stream was aborted (e.g. due to a network error), the clickhouse.query.stream span was never ended. The TransformStream now handles both source-stream aborts and consumer-side cancellations via a cancel callback.
    • The insert span records clickhouse.request.sent_rows for array-based inserts.
  • Added a use_multipart_params_auto client option (default: false). When enabled, query() automatically sends query_params as multipart/form-data body parts (the same mechanism as use_multipart_params) once their URL-encoded length exceeds 4096 characters, avoiding HTTP 414/400 errors from HTTP intermediaries (nginx, AWS ALB, CloudFront) caused by over-long URLs - for example, a large IN list or a high-dimensional vector embedding. Smaller parameter payloads remain in the URL query string, so existing behavior is unchanged unless the threshold is crossed. use_multipart_params: true still forces multipart for all queries regardless of size. This does not change the server's per-value size limit, which is governed by http_max_field_value_size. Supported on both @clickhouse/client and @clickhouse/client-web, and overridable per request via use_multipart_params_auto on query(). Ported from clickhouse-connect#789. (#827)

const client = createClient({ use_multipart_params_auto: true });

await client.query({
  query: "SELECT * FROM events WHERE id IN {ids:Array(UInt64)}",
  // Sent in the URL when small, auto-promoted to the multipart body when large
  query_params: { ids: veryLargeArrayOfIds },
});
  • Added a use_multipart_params client option (default: false). When enabled, query() sends query_params as multipart/form-data body parts (with the SQL moved into a query part) instead of URL query-string entries, avoiding HTTP 400 errors caused by over-long URLs when parameters contain large arrays (25K+ values). All other URL search params (database, query_id, settings, session_id, role) remain in the URL. Supported on both @clickhouse/client and @clickhouse/client-web, and overridable per request via use_multipart_params on query(). (#825)
const client = createClient({ use_multipart_params: true });

await client.query({
  query: "SELECT * FROM events WHERE id IN {ids:Array(UInt64)}",
  query_params: { ids: veryLargeArrayOfIds },
  // Per-request override is also supported:
  // use_multipart_params: false,
});

Bug Fixes

  • The client now checks the X-ClickHouse-Exception-Code response header to detect server errors even when the HTTP status code indicates success. In some scenarios (for example, when an exception occurs while streaming the response progress in headers, or with certain proxy setups), ClickHouse responds with HTTP 200 but sets the X-ClickHouse-Exception-Code header. Previously, such responses were treated as successful, and the exception text could surface as malformed response data; now the request is rejected with a parsed ClickHouseError (with the proper code and type), consistent with non-2xx error responses. This applies to both the Node.js and Web clients. (#554, supersedes #350, related issue: #332)

1.20.0

New Features

  • Added an optional tracer API that the user can pass through the client config (tracer) and that gets called around key lifecycle operations (query, command, exec, insert, ping). The ClickHouseTracer interface is a structural subset of the OpenTelemetry Tracer/Span APIs, so a raw OTEL tracer (trace.getTracer(...)) can be passed to the client as-is - but the client itself ships no tracing dependency. Each operation runs inside tracer.startActiveSpan(...), so auto-instrumented child spans nest under the ClickHouse operation spans; for OpenTelemetry, this requires the AsyncLocalStorageContextManager to be registered (the default in the OpenTelemetry Node.js SDK). Tracer exceptions are NOT caught, so a broken tracer will break client operations. See docs/howto/tracing.md for the full surface description, and examples/node/coding/otel_tracing.ts for a runnable Node.js example. (#776)
import { createClient } from "@clickhouse/client";
import { trace } from "@opentelemetry/api";

// a raw OpenTelemetry tracer is structurally compatible - no adapter needed
const client = createClient({
  url: "http://localhost:8123",
  tracer: trace.getTracer("@clickhouse/client"),
});

Migration Notes

  • TypeScript: ClickHouseLogLevel is now exported as a literal numeric union type (0 | 1 | 2 | 3 | 4 | 127) instead of a TypeScript enum type. If you were assigning arbitrary number values to ClickHouseLogLevel, you may need to narrow/cast those values during migration.

Improvements

  • Added TypeScript typings for the remaining HTTP-specific ClickHouse settings, so they are now suggested by autocomplete when used in clickhouse_settings: buffer_size, compress, decompress, quota_key, and stacktrace (in addition to the existing wait_end_of_query, default_format, session_timeout, and session_check).
await client.query({
  query: "SELECT 1",
  clickhouse_settings: {
    // Buffer the entire response on the server before sending it to the client
    wait_end_of_query: 1,
    buffer_size: "1048576",
  },
});

Bug Fixes

  • (Node.js only) Fixed a race condition in ResultSet.json() and ResultSet.stream() on JSONEachRow (and other streamable) result sets where calling json() on a fast/small response could throw Stream has been already consumed if the underlying stream ended between internal readableEnded checks. The consumption guard has been hardened: the stream is now shielded through a single consume() path that marks the result set as consumed in the appropriate branches, after format validation, so a successful json() call no longer races against the stream finishing. (#603)

1.19.0

Improvements

  • Re-exported the ResponseHeaders type from @clickhouse/client and @clickhouse/client-web. Previously this type was only available from @clickhouse/client-common; it is now part of the public re-export surface of both flavored packages, alongside the other commonly used types. This is part of an ongoing effort to make @clickhouse/client-common an internal-only package so downstream consumers can depend solely on @clickhouse/client or @clickhouse/client-web. (#758)

Bug Fixes

  • Enum type parsing now correctly unescapes backslash escape sequences in enum names. Previously, parseEnumType returned enum names with raw escape sequences (e.g., f\' instead of f'). Now it properly decodes escape sequences including \' (single quote), \\ (backslash), \n (newline), \t (tab), and \r (carriage return). This matches the behavior of ClickHouse string literals and ensures consistency with how the client encodes strings when sending data to the server. If you were relying on the previous incorrect behavior where backslash escape sequences were preserved in enum names, you will need to update your code to handle properly unescaped values.

Example:

// Before (incorrect):
parseEnumType({
  columnType: "Enum8('f\\'' = 1)",
  sourceType: "Enum8('f\\'' = 1)",
});
// returned: { values: { 1: "f\\'" } }  // with backslash

// After (correct):
parseEnumType({
  columnType: "Enum8('f\\'' = 1)",
  sourceType: "Enum8('f\\'' = 1)",
});
// returns: { values: { 1: "f'" } }     // unescaped

1.18.5

Improvements

  • (Node.js only) Added max_response_headers_size client option that forwards the maxHeaderSize option to the underlying http(s).request call. This raises the per-request limit on the total size of HTTP response headers received from the server (Node.js default is ~16 KB). It is most useful when running long-running queries with send_progress_in_http_headers enabled — the X-ClickHouse-Progress headers accumulate over the lifetime of the request and can exceed the default limit, causing the request to fail with HPE_HEADER_OVERFLOW. Setting this option avoids the need to use the global --max-http-header-size Node.js CLI flag or the NODE_OPTIONS environment variable. Has no effect for the Web client (which uses fetch) and no effect when a custom http_agent is configured with a request implementation that does not honor the option.
const client = createClient({
  request_timeout: 400_000,
  max_response_headers_size: 1024 * 1024, // accept up to 1 MiB of response headers
  clickhouse_settings: {
    send_progress_in_http_headers: 1,
    http_headers_progress_interval_ms: "110000",
  },
});
  • The @clickhouse/client npm package now ships embedded AI-agent skills, clickhouse-js-node-coding and clickhouse-js-node-troubleshooting, under node_modules/@clickhouse/client/skills/. These skills are also declared in the agents.skills field of the package manifest for discovery tools that scan node_modules. This allows agentic coding tools to load focused, Node-client-specific coding and troubleshooting guidance without any additional setup. (#682)

1.18.4

A release-infrastructure-only version bump (no user-facing changes). See 1.18.5 for the next release with user-facing improvements.

1.18.3

Improvements

  • Added keep_alive.eagerly_destroy_stale_sockets option (Node.js only, default: false). When enabled, sockets that have been idle for longer than idle_socket_ttl are destroyed immediately before each request, rather than waiting for the idle timeout to fire. This helps reclaim stale sockets during event loop delays, where the timeout callback may not run on time.
const client = createClient({
  keep_alive: {
    enabled: true,
    idle_socket_ttl: 2500,
    eagerly_destroy_stale_sockets: true,
  },
});
  • Added auto-detection and warning when request_timeout is high (> 60 seconds) but progress headers are not configured. Long-running queries may fail with socket hang-up errors if they exceed the load balancer idle timeout. The client now warns users to enable send_progress_in_http_headers and http_headers_progress_interval_ms settings to prevent such issues.
// This will now trigger a warning
const client = createClient({
  request_timeout: 120_000, // 120 seconds
  // send_progress_in_http_headers is not configured
});

// ✓ Properly configured to avoid load balancer timeouts
const client = createClient({
  request_timeout: 400_000,
  clickhouse_settings: {
    send_progress_in_http_headers: 1,
    http_headers_progress_interval_ms: "110000", // ~10s below LB timeout
  },
});

1.18.2

Improvements

  • Added a helping WARN level log message with a suggestion to check the keep_alive configuration if the client receives an ECONNRESET error from the server, which can happen when the server closes idle connections after a certain timeout, and the client tries to reuse such a connection from the pool. This can be especially helpful for new users who might not be aware of this aspect of HTTP connection management. The log message is only emitted if the keep_alive option is enabled in the client configuration, and it includes the server's keep-alive timeout value (if available) to assist with troubleshooting. (#597)

How to reproduce the issue that triggers the log message:

const client = createClient({
  // ...
  keep_alive: {
    enabled: true,
    // ❌ DON'T SET THIS VALUE SO HIGH IN PRODUCTION
    idle_socket_ttl: 1_000_000,
  },
  log: {
    level: ClickHouseLogLevel.WARN, // to see the warning logs
  },
});

for (let i = 0; i < 1000; i++) {
  await client.ping({
    // To use a regular query instead of the /ping endpoint
    // which might be configured differently on the server side
    // and have different timeout settings.
    select: true,
  });

  // Wait long enough to let the server close the idle connection,
  // but not too long to let the client remove it from the pool,
  // in other words try to hit the scenario when the race condition
  // happens between the server closing the connection and the client
  // trying to reuse it.
  await sleep(SERVER_KEEP_ALIVE_TIMEOUT_MS - 100);
}

Example log message:

{
  "message": "Ping: idle socket TTL is greater than server keep-alive timeout, try setting idle socket TTL to a value lower than the server keep-alive timeout to prevent unexpected connection resets, see https://github.com/ClickHouse/clickhouse-js/blob/main/docs/howto/keep_alive_timeout.md for more details.",
  "args": {
    "operation": "Ping",
    "connection_id": "8dc1c9bd-7895-49b1-8a95-276470151c65",
    "query_id": "beee95af-2e83-4dcb-8e1e-045bd61f4985",
    "request_id": "8dc1c9bd-7895-49b1-8a95-276470151c65:2",
    "socket_id": "8dc1c9bd-7895-49b1-8a95-276470151c65:1",
    "server_keep_alive_timeout_ms": 10000,
    "idle_socket_ttl": 15000
  },
  "module": "HTTP Adapter"
}

1.18.1

Improvements

  • Setting log.level default value to ClickHouseLogLevel.WARN instead of ClickHouseLogLevel.OFF to provide better visibility into potential issues without overwhelming users with too much information by default.
const client = createClient({
  // ...
  log: {
    level: ClickHouseLogLevel.WARN, // default is now ClickHouseLogLevel.WARN instead of ClickHouseLogLevel.OFF
  },
});
  • Logging is now lazy, which means that the log messages will only be constructed if the log level is appropriate for the message. This can improve performance in cases where constructing the log message is expensive, and the log level is set to ignore such messages. See ClickHouseLogLevel enum for the complete list of log levels. (#520)
const client = createClient({
  // ...
  log: {
    level: ClickHouseLogLevel.TRACE, // to log everything available down to the network level events
  },
});
  • Enhanced the logging of the HTTP request / socket lifecycle with additional trace messages and context such as Connection ID (UUID) and Request ID and Socket ID that embed the connection ID for ease of tracing the logs of a particular request across the connection lifecycle. To enable such logs, set the log.level config option to ClickHouseLogLevel.TRACE. (#567)
[2026-02-25T09:19:13.511Z][TRACE][@clickhouse/client][Connection] Insert: received 'close' event, 'free' listener removed
Arguments: {
  operation: 'Insert',
  connection_id: 'da3c9796-5dc5-46ef-83b0-ed1f4422094c',
  query_id: '9dfda627-39a2-41a6-9fc9-8f8716574826',
  request_id: 'da3c9796-5dc5-46ef-83b0-ed1f4422094c:3',
  socket_id: 'da3c9796-5dc5-46ef-83b0-ed1f4422094c:2',
  event: 'close'
}
[2026-02-25T09:19:13.502Z][TRACE][@clickhouse/client][Connection] Query: reusing socket
Arguments: {
  operation: 'Query',
  connection_id: 'da3c9796-5dc5-46ef-83b0-ed1f4422094c',
  query_id: 'ad0127e8-b1c7-4ed6-9681-c0162f7a0ea9',
  request_id: 'da3c9796-5dc5-46ef-83b0-ed1f4422094c:4',
  socket_id: 'da3c9796-5dc5-46ef-83b0-ed1f4422094c:2',
  usage_count: 1
}
  • A step towards structured logging: the client now passes rich context to the logger args parameter (e.g. connection_id, query_id, request_id, socket_id). (#576)

Deprecated API

  • The drainStream utility function is now deprecated, as the client will handle draining the stream internally when needed. Use client.command() instead, which will handle draining the stream internally when needed. (#578)

  • The sleep utility function is now deprecated, as it is not intended to be used outside of the client implementation. Use setTimeout directly or a more full-featured utility library if you need additional features like cancellation or timers management. (#578)

1.18.0

A beta version. See 1.18.1 for the stable release.

1.17.0

New features

  • Added http_status_code to query, insert, and exec commands (#525, Kinzeng)
  • Fixed ignore_error_response not getting passed when using command (#536, Kinzeng)

1.16.0

New features

  • Added support for the new Disposable API (a.k.a the using keyword) (#500)
async function main() {
  using resultSet = await client.query();

  // some code that can throw
  // but thanks to `using` the resultSet will still get disposed

  // resultSet is also automatically disposed here by calling [Symbol.dispose]
}

Without the new using keyword it is required to wrap the code that might leak expensive resources like sockets and big buffers in try / finally

async function main() {
  let client
  try {
    client = await createClient();
    // some code that can throw
  } finally {
    if (client) {
      await client.close()
    }
  }
}

1.15.0

New features

  • Added support for BigInt values in query parameters. (#487, @dalechyn)

1.14.0

New features

  • It is now possible to specify custom parse and stringify functions that will be used instead of the standard JSON.parse and JSON.stringify methods for JSON serialization/deserialization when working with JSON* family formats. See ClickHouseClientConfigOptions.json, and a new custom_json_handling example for more details. (#481, looskie)
  • (Node.js only) Added an ignore_error_response param to ClickHouseClient.exec, which allows callers to manually handle request errors on the application side. (#483, Kinzeng)

1.13.0

New features

  • Server-side exceptions that occur in the middle of the HTTP stream are now handled correctly. This requires ClickHouse 25.11+. Previous ClickHouse versions are unaffected by this change. (#478)

Improvements

  • TupleParam constructor now accepts a readonly array to permit more usages. (#465, Malien)

Bug fixes

  • Fixed boolean value formatting in query parameters. Boolean values within Array, Tuple, and Map types are now correctly formatted as TRUE/FALSE instead of 1/0 to ensure proper type compatibility with ClickHouse. (#475, baseballyama)

1.12.1

Improvements

  • Improved performance of toSearchParams. (#449, twk)

Other

  • Added Node.js 24.x to the CI matrix. Node.js 18.x was removed from the CI due to EOL.

1.12.0

Types

  • Add missing allow_experimental_join_condition to ClickHouseSettings typing. (#430, looskie)
  • Fixed JSONEachRowWithProgress TypeScript flow after the breaking changes in ClickHouse 25.1. RowOrProgress<T> now has an additional variant: SpecialEventRow<T>. The library now additionally exports the parseError method, and newly added isRow / isException type guards. See the updated JSONEachRowWithProgress example (#443)
  • Added missing allow_experimental_variant_type (24.1+), allow_experimental_dynamic_type (24.5+), allow_experimental_json_type (24.8+), enable_json_type (25.3+), enable_time_time64_type (25.6+) to ClickHouseSettings typing. (#445)

Improvements

  • Add a warning on a socket closed without fully consuming the stream (e.g., when using query or exec method). (#441)
  • (Node.js only) An option to use a simple SELECT query for ping checks instead of /ping endpoint. See the new optional argument to the ClickHouseClient.ping method and PingParams typings. Note that the Web version always used a SELECT query by default, as the /ping endpoint does not support CORS, and that cannot be changed. (#442)

Other

  • The project now uses Codecov instead of SonarCloud for code coverage reports. (#444)

1.11.2 (Common, Node.js)

A minor release to allow further investigation regarding uncaught error issues with #410.

Types

Improvements (Node.js)

  • Added a new configuration option: capture_enhanced_stack_trace; see the JS doc in the Node.js client package. Note that it is disabled by default due to a possible performance impact. (#427)
  • Added more try-catch blocks to the Node.js connection layer. (#427)

1.11.1 (Common, Node.js, Web)

Bug fixes

  • Fixed an issue with URLEncoded special characters in the URL configuration for username or password. (#407)

Improvements

1.11.0 (Common, Node.js, Web)

New features

  • It is now possible to provide custom HTTP headers when calling the query/insert/command/exec methods using the http_headers option. NB: http_headers specified this way will override http_headers set on the client instance level. (#394, @DylanRJohnston)
  • (Web only) It is now possible to provide a custom fetch implementation to the client. (#315, @lucacasonato)

1.10.1 (Common, Node.js, Web)

Bug fixes

  • Fixed NULL parameter binding with Tuple, Array, and Map types. (#374)

Improvements

  • ClickHouseSettings typings now include session_timeout and session_check settings. (#370)

1.10.0 (Common, Node.js, Web)

New features

  • Added support for JWT authentication (ClickHouse Cloud feature) in both Node.js and Web API packages. JWT token can be set via access_token client configuration option.

    const client = createClient({
      // ...
      access_token: "<JWT access token>",
    });

    Access token can also be configured via the URL params, e.g., https://host:port?access_token=....

    It is also possible to override the access token for a particular request (see BaseQueryParams.auth for more details).

    NB: do not mix access token and username/password credentials in the configuration; the client will throw an error if both are set.

1.9.1 (Node.js only)

Bug fixes

  • Fixed an uncaught exception that could happen in case of malformed ClickHouse response when response compression is enabled (#363)

1.9.0 (Common, Node.js, Web)

New features

  • Added input_format_json_throw_on_bad_escape_sequence to the ClickhouseSettings type. (#355, @emmanuel-bonin)
  • The client now exports TupleParam wrapper class, allowing tuples to be properly used as query parameters. Added support for JS Map as a query parameter. (#359)

Improvements

  • The client will throw a more informative error if the buffered response is larger than the max allowed string length in V8, which is 2**29 - 24 bytes. (#357)

1.8.1 (Node.js)

Bug fixes

  • When a custom HTTP agent is used, the HTTP or HTTPS request implementation is now correctly chosen based on the URL protocol. (#352)

1.8.0 (Common, Node.js, Web)

New features

1.7.0 (Common, Node.js, Web)

Bug fixes

  • (Web only) Fixed an issue where streaming large datasets could provide corrupted results. See #333 (PR) for more details.

New features

  • Added JSONEachRowWithProgress format support, ProgressRow interface, and isProgressRow type guard. See this Node.js example for more details. It should work similarly with the Web version.

  • (Experimental) Exposed the parseColumnType function that takes a string representation of a ClickHouse type (e.g., FixedString(16), Nullable(Int32), etc.) and returns an AST-like object that represents the type. For example:

    for (const type of [
      "Int32",
      "Array(Nullable(String))",
      `Map(Int32, DateTime64(9, 'UTC'))`,
    ]) {
      console.log(`##### Source ClickHouse type: ${type}`);
      console.log(parseColumnType(type));
    }

    The above code will output:

    ##### Source ClickHouse type: Int32
    { type: 'Simple', columnType: 'Int32', sourceType: 'Int32' }
    ##### Source ClickHouse type: Array(Nullable(String))
    {
      type: 'Array',
      value: {
        type: 'Nullable',
        sourceType: 'Nullable(String)',
        value: { type: 'Simple', columnType: 'String', sourceType: 'String' }
      },
      dimensions: 1,
      sourceType: 'Array(Nullable(String))'
    }
    ##### Source ClickHouse type: Map(Int32, DateTime64(9, 'UTC'))
    {
      type: 'Map',
      key: { type: 'Simple', columnType: 'Int32', sourceType: 'Int32' },
      value: {
        type: 'DateTime64',
        timezone: 'UTC',
        precision: 9,
        sourceType: "DateTime64(9, 'UTC')"
      },
      sourceType: "Map(Int32, DateTime64(9, 'UTC'))"
    }
    

    While the original intention was to use this function internally for Native/RowBinaryWithNamesAndTypes data formats headers parsing, it can be useful for other purposes as well (e.g., interfaces generation, or custom JSON serializers).

    NB: currently unsupported source types to parse:

    • Geo
    • (Simple)AggregateFunction
    • Nested
    • Old/new experimental JSON
    • Dynamic
    • Variant

1.6.0 (Common, Node.js, Web)

New features

Bug fixes

  • Fixed unhandled exceptions produced when calling ResultSet.json if the response data was not in fact a valid JSON. (#311)

1.5.0 (Node.js)

New features

  • It is now possible to disable the automatic decompression of the response stream with the exec method. See ExecParams.decompress_response_stream for more details. (#298).

1.4.1 (Node.js, Web)

Improvements

  • ClickHouseClient is now exported as a value from @clickhouse/client and @clickhouse/client-web packages, allowing for better integration in dependency injection frameworks that rely on IoC (e.g., Nest.js, tsyringe) (@mathieu-bour, #292).

Bug fixes

  • Fixed a potential socket hang up issue that could happen under 100% CPU load (#294).

1.4.0 (Node.js)

New features

  • (Node.js only) The exec method now accepts an optional values parameter, which allows you to pass the request body as a Stream.Readable. This can be useful in case of custom insert streaming with arbitrary ClickHouse data formats (which might not be explicitly supported and allowed by the client in the insert method yet). NB: in this case, you are expected to serialize the data in the stream in the required input format yourself.

1.3.0 (Common, Node.js, Web)

New features

  • It is now possible to get the entire response headers object from the query/insert/command/exec methods. With query, you can access the ResultSet.response_headers property; other methods (insert/command/exec) return it as parts of their response objects as well. For example:

    const rs = await client.query({
      query: "SELECT * FROM system.numbers LIMIT 1",
      format: "JSONEachRow",
    });
    console.log(rs.response_headers["content-type"]);

    This will print: application/x-ndjson; charset=UTF-8. It can be used in a similar way with the other methods.

Improvements

  • Re-exported several constants from the @clickhouse/client-common package for convenience:
    • SupportedJSONFormats
    • SupportedRawFormats
    • StreamableFormats
    • StreamableJSONFormats
    • SingleDocumentJSONFormats
    • RecordsJSONFormats

1.2.0 (Node.js)

New features

  • (Experimental) Added an option to provide a custom HTTP Agent in the client configuration via the http_agent option (#283, related: #278). The following conditions apply if a custom HTTP Agent is provided:

    • The max_open_connections and tls options will have no effect and will be ignored by the client, as it is a part of the underlying HTTP Agent configuration.
    • keep_alive.enabled will only regulate the default value of the Connection header (true -> Connection: keep-alive, false -> Connection: close).
    • While the idle socket management will still work, it is now possible to disable it completely by setting the keep_alive.idle_socket_ttl value to 0.
  • (Experimental) Added a new client configuration option: set_basic_auth_header, which disables the Authorization header that is set by the client by default for every outgoing HTTP request. One of the possible scenarios when it is necessary to disable this header is when a custom HTTPS agent is used, and the server requires TLS authorization. For example:

    const agent = new https.Agent({
      ca: fs.readFileSync("./ca.crt"),
    });
    const client = createClient({
      url: "https://server.clickhouseconnect.test:8443",
      http_agent: agent,
      // With a custom HTTPS agent, the client won't use the default HTTPS connection implementation; the headers should be provided manually
      http_headers: {
        "X-ClickHouse-User": "default",
        "X-ClickHouse-Key": "",
      },
      // Authorization header conflicts with the TLS headers; disable it.
      set_basic_auth_header: false,
    });

NB: It is currently not possible to set the set_basic_auth_header option via the URL params.

If you have feedback on these experimental features, please let us know by creating an issue in the repository.

1.1.0 (Common, Node.js, Web)

New features

  • Added an option to override the credentials for a particular query/command/exec/insert request via the BaseQueryParams.auth setting; when set, the credentials will be taken from there instead of the username/password provided during the client instantiation (#278).
  • Added an option to override the session_id for a particular query/command/exec/insert request via the BaseQueryParams.session_id setting; when set, it will be used instead of the session id provided during the client instantiation (@holi0317, #271).

Bug fixes

  • Fixed the incorrect ResponseJSON<T>.totals TypeScript type. Now it correctly matches the shape of the data (T, default = unknown) instead of the former Record<string, number> definition (#274).

1.0.2 (Common, Node.js, Web)

Bug fixes

  • The command method now drains the response stream properly, as the previous implementation could cause the Keep-Alive socket to close after each request.
  • Removed an unnecessary error log in the ResultSet.stream method if the request was aborted or the result set was closed (#263).

Improvements

  • ResultSet.stream logs an error via the Logger instance, if the stream emits an error event instead of a simple console.error call.
  • Minor adjustments to the DefaultLogger log messages formatting.
  • Added missing rows_before_limit_at_least to the ResponseJSON type (@0237h, #267).

1.0.1 (Common, Node.js, Web)

Bug fixes

  • Fixed the regression where the default HTTP/HTTPS port numbers (80/443) could not be used with the URL configuration (#258).

1.0.0 (Common, Node.js, Web)

Formal stable release milestone with a lot of improvements and some breaking changes.

Major new features overview:

From now on, the client will follow the official semantic versioning guidelines.

Deprecated API

The following configuration parameters are marked as deprecated:

  • host configuration parameter is deprecated; use url instead.
  • additional_headers configuration parameter is deprecated; use http_headers instead.

The client will log a warning if any of these parameters are used. However, it is still allowed to use host instead of url and additional_headers instead of http_headers for now; this deprecation is not supposed to break the existing code.

These parameters will be removed in the next major release (2.0.0).

See "New features" section for more details.

Breaking changes in 1.0.0

  • compression.response is now disabled by default in the client configuration options, as it cannot be used with readonly=1 users, and it was not clear from the ClickHouse error message what exact client option was causing the failing query in this case. If you'd like to continue using response compression, you should explicitly enable it in the client configuration.
  • As the client now supports parsing URL configuration, you should specify pathname as a separate configuration option (as it would be considered as the database otherwise).
  • (TypeScript only) ResultSet and Row are now more strictly typed, according to the format used during the query call. See this section for more details.
  • (TypeScript only) Both Node.js and Web versions now uniformly export correct ClickHouseClient and ClickHouseClientConfigOptions types, specific to each implementation. Exported ClickHouseClient now does not have a Stream type parameter, as it was unintended to expose it there. NB: you should still use createClient factory function provided in the package.

New features in 1.0.0

Advanced TypeScript support for query + ResultSet

Client will now try its best to figure out the shape of the data based on the DataFormat literal specified to the query call, as well as which methods are allowed to be called on the ResultSet.

Live demo (see the full description below):

Screencast.from.2024-03-09.08-10-26.webm

Complete reference:

Format ResultSet.json<T>() ResultSet.stream<T>() Stream data Row.json<T>()
JSON ResponseJSON<T> never never never
JSONObjectEachRow Record<string, T> never never never
All other JSON*EachRow Array<T> Stream<Array<Row<T>>> Array<Row<T>> T
CSV/TSV/CustomSeparated/Parquet never Stream<Array<Row<T>>> Array<Row<T>> never

By default, T (which represents JSONType) is still unknown. However, considering JSONObjectsEachRow example: prior to 1.0.0, you had to specify the entire type hint, including the shape of the data, manually:

type Data = { foo: string };

const resultSet = await client.query({
  query: "SELECT * FROM my_table",
  format: "JSONObjectsEachRow",
});

// pre-1.0.0, `resultOld` has type Record<string, Data>
const resultOld = resultSet.json<Record<string, Data>>();
// const resultOld = resultSet.json<Data>() // incorrect! The type hint should've been `Record<string, Data>` here.

// 1.0.0, `resultNew` also has type Record<string, Data>; client inferred that it has to be a Record from the format literal.
const resultNew = resultSet.json<Data>();

This is even more handy in case of streaming on the Node.js platform:

const resultSet = await client.query({
  query: "SELECT * FROM my_table",
  format: "JSONEachRow",
});

// pre-1.0.0
// `streamOld` was just a regular Node.js Stream.Readable
const streamOld = resultSet.stream();
// `rows` were `any`, needed an explicit type hint
streamNew.on("data", (rows: Row[]) => {
  rows.forEach((row) => {
    // without an explicit type hint to `rows`, calling `forEach` and other array methods resulted in TS compiler errors
    const t = row.text;
    const j = row.json<Data>(); // `j` needed a type hint here, otherwise, it's `unknown`
  });
});

// 1.0.0
// `streamNew` is now StreamReadable<T> (Node.js Stream.Readable with a bit more type hints);
// type hint for the further `json` calls can be added here (and removed from the `json` calls)
const streamNew = resultSet.stream<Data>();
// `rows` are inferred as an Array<Row<Data, "JSONEachRow">> instead of `any`
streamNew.on("data", (rows) => {
  // `row` is inferred as Row<Data, "JSONEachRow">
  rows.forEach((row) => {
    // no explicit type hints required, you can use `forEach` straight away and TS compiler will be happy
    const t = row.text;
    const j = row.json(); // `j` will be of type Data
  });
});

// async iterator now also has type hints
// similarly to the `on(data)` example above, `rows` are inferred as Array<Row<Data, "JSONEachRow">>
for await (const rows of streamNew) {
  // `row` is inferred as Row<Data, "JSONEachRow">
  rows.forEach((row) => {
    const t = row.text;
    const j = row.json(); // `j` will be of type Data
  });
}

Calling ResultSet.stream is not allowed for certain data formats, such as JSON and JSONObjectsEachRow (unlike JSONEachRow and the rest of JSON*EachRow, these formats return a single object). In these cases, the client throws an error. However, it was previously not reflected on the type level; now, calling stream on these formats will result in a TS compiler error. For example:

const resultSet = await client.query("SELECT * FROM table", {
  format: "JSON",
});
const stream = resultSet.stream(); // `stream` is `never`

Calling ResultSet.json also does not make sense on CSV and similar "raw" formats, and the client throws. Again, now, it is typed properly:

const resultSet = await client.query("SELECT * FROM table", {
  format: "CSV",
});
// `json` is `never`; same if you stream CSV, and call `Row.json` - it will be `never`, too.
const json = resultSet.json();

Currently, there is one known limitation: as the general shape of the data and the methods allowed for calling are inferred from the format literal, there might be situations where it will fail to do so, for example:

// assuming that `queryParams` has `JSONObjectsEachRow` format inside
async function runQuery(
  queryParams: QueryParams,
): Promise<Record<string, Data>> {
  const resultSet = await client.query(queryParams);
  // type hint here will provide a union of all known shapes instead of a specific one
  // inferred shapes: Data[] | ResponseJSON<Data> | Record<string, Data>
  return resultSet.json<Data>();
}

In this case, as it is likely that you already know the desired format in advance (otherwise, returning a specific shape like Record<string, Data> would've been incorrect), consider helping the client a bit:

async function runQuery(
  queryParams: QueryParams,
): Promise<Record<string, Data>> {
  const resultSet = await client.query({
    ...queryParams,
    format: "JSONObjectsEachRow",
  });
  // TS understands that it is a Record<string, Data> now
  return resultSet.json<Data>();
}

If you are interested in more details, see the related test (featuring a great ESLint plugin expect-types) in the client package.

URL configuration

  • Added url configuration parameter. It is intended to replace the deprecated host, which was already supposed to be passed as a valid URL.
  • It is now possible to configure most of the client instance parameters with a URL. The URL format is http[s]://[username:password@]hostname:port[/database][?param1=value1&param2=value2]. In almost every case, the name of a particular parameter reflects its path in the config options interface, with a few exceptions. The following parameters are supported:
Parameter Type
pathname an arbitrary string.
application_id an arbitrary string.
session_id an arbitrary string.
request_timeout non-negative number.
max_open_connections non-negative number, greater than zero.
compression_request boolean. See below [1].
compression_response boolean.
log_level allowed values: OFF, TRACE, DEBUG, INFO, WARN, ERROR.
keep_alive_enabled boolean.
clickhouse_setting_* or ch_* see below [2].
http_header_* see below [3].
(Node.js only) keep_alive_idle_socket_ttl non-negative number.

[1] For booleans, valid values will be true/1 and false/0.

[2] Any parameter prefixed with clickhouse_setting_ or ch_ will have this prefix removed and the rest added to client's clickhouse_settings. For example, ?ch_async_insert=1&ch_wait_for_async_insert=1 will be the same as:

createClient({
  clickhouse_settings: {
    async_insert: 1,
    wait_for_async_insert: 1,
  },
});

Note: boolean values for clickhouse_settings should be passed as 1/0 in the URL.

[3] Similar to [2], but for http_header configuration. For example, ?http_header_x-clickhouse-auth=foobar will be an equivalent of:

createClient({
  http_headers: {
    "x-clickhouse-auth": "foobar",
  },
});

Important: URL will always overwrite the hardcoded values and a warning will be logged in this case.

Currently not supported via URL:

  • log.LoggerClass
  • (Node.js only) tls_ca_cert, tls_cert, tls_key.

See also: URL configuration example.

Performance

  • (Node.js only) Improved performance when decoding the entire set of rows with streamable JSON formats (such as JSONEachRow or JSONCompactEachRow) by calling the ResultSet.json() method. NB: The actual streaming performance when consuming the ResultSet.stream() hasn't changed. Only the ResultSet.json() method used a suboptimal stream processing in some instances, and now ResultSet.json() just consumes the same stream transformer provided by the ResultSet.stream() method (see #253 for more details).

Miscellaneous

  • Added http_headers configuration parameter as a direct replacement for additional_headers. Functionally, it is the same, and the change is purely cosmetic, as we'd like to leave an option to implement TCP connection in the future open.

0.3.1 (Common, Node.js, Web)

Bug fixes

  • Fixed an issue where query parameters containing tabs or newline characters were not encoded properly.

0.3.0 (Node.js only)

This release primarily focuses on improving the Keep-Alive mechanism's reliability on the client side.

New features

  • Idle sockets timeout rework; now, the client attaches internal timers to idling sockets, and forcefully removes them from the pool if it considers that a particular socket is idling for too long. The intention of this additional sockets housekeeping is to eliminate "Socket hang-up" errors that could previously still occur on certain configurations. Now, the client does not rely on KeepAlive agent when it comes to removing the idling sockets; in most cases, the server will not close the socket before the client does.
  • There is a new keep_alive.idle_socket_ttl configuration parameter. The default value is 2500 (milliseconds), which is considered to be safe, as ClickHouse versions prior to 23.11 had keep_alive_timeout set to 3 seconds by default, and keep_alive.idle_socket_ttl is supposed to be slightly less than that to allow the client to remove the sockets that are about to expire before the server does so.
  • Logging improvements: more internal logs on failing requests; all client methods except ping will log an error on failure now. A failed ping will log a warning, since the underlying error is returned as a part of its result. Client logging still needs to be enabled explicitly by specifying the desired log.level config option, as the log level is OFF by default. Currently, the client logs the following events, depending on the selected log.level value:
    • TRACE - low-level information about the Keep-Alive sockets lifecycle.
    • DEBUG - response information (without authorization headers and host info).
    • INFO - still mostly unused, will print the current log level when the client is initialized.
    • WARN - non-fatal errors; failed ping request is logged as a warning, as the underlying error is included in the returned result.
    • ERROR - fatal errors from query/insert/exec/command methods, such as a failed request.

Breaking changes

  • keep_alive.retry_on_expired_socket and keep_alive.socket_ttl configuration parameters are removed.
  • The max_open_connections configuration parameter is now 10 by default, as we should not rely on the KeepAlive agent's defaults.
  • Fixed the default request_timeout configuration value (now it is correctly set to 30_000, previously 300_000 (milliseconds)).

Bug fixes

  • Fixed a bug with Ping that could lead to an unhandled "Socket hang-up" propagation.
  • Ensure proper Connection header value considering Keep-Alive settings. If Keep-Alive is disabled, its value is now forced to "close".

0.3.0-beta.1 (Node.js only)

See 0.3.0.

0.2.10 (Common, Node.js, Web)

New features

  • If InsertParams.values is an empty array, no request is sent to the server and ClickHouseClient.insert short-circuits itself. In this scenario, the newly added InsertResult.executed flag will be false, and InsertResult.query_id will be an empty string.

Bug fixes

  • Client no longer produces Code: 354. inflate failed: buffer error exception if request compression is enabled and InsertParams.values is an empty array (see above).

0.2.9 (Common, Node.js, Web)

New features

  • It is now possible to set additional HTTP headers for outgoing ClickHouse requests. This might be useful if, for example, you use a reverse proxy with authorization. (@teawithfruit, #224)
const client = createClient({
  additional_headers: {
    "X-ClickHouse-User": "clickhouse_user",
    "X-ClickHouse-Key": "clickhouse_password",
  },
});

0.2.8 (Common, Node.js, Web)

New features

  • (Web only) Allow to modify Keep-Alive setting (previously always disabled). Keep-Alive setting is now enabled by default for the Web version.
import { createClient } from "@clickhouse/client-web";
const client = createClient({ keep_alive: { enabled: true } });
  • (Node.js & Web) It is now possible to either specify a list of columns to insert the data into or a list of excluded columns:
// Generated query: INSERT INTO mytable (message) FORMAT JSONEachRow
await client.insert({
  table: "mytable",
  format: "JSONEachRow",
  values: [{ message: "foo" }],
  columns: ["message"],
});

// Generated query: INSERT INTO mytable (* EXCEPT (message)) FORMAT JSONEachRow
await client.insert({
  table: "mytable",
  format: "JSONEachRow",
  values: [{ id: 42 }],
  columns: { except: ["message"] },
});

See also the new examples:

0.2.7 (Common, Node.js, Web)

New features

  • (Node.js only) X-ClickHouse-Summary response header is now parsed when working with insert/exec/command methods. See the related test for more details. NB: it is guaranteed to be correct only for non-streaming scenarios. Web version does not currently support this due to CORS limitations. (#210)

Bug fixes

  • Drain insert response stream in Web version - required to properly work with async_insert, especially in the Cloudflare Workers context.

0.2.6 (Common, Node.js)

New features

0.2.5 (Common, Node.js, Web)

Bug fixes

  • pathname segment from host client configuration parameter is now handled properly when making requests. See this comment for more details.

0.2.4 (Node.js only)

No changes in web/common modules.

Bug fixes

  • (Node.js only) Fixed an issue where streaming large datasets could provide corrupted results. See #171 (issue) and #204 (PR) for more details.

0.2.3 (Node.js only)

No changes in web/common modules.

Bug fixes

  • (Node.js only) Fixed an issue where the underlying socket was closed every time after using insert with a keep_alive option enabled, which led to performance limitations. See #202 for more details. (@varrocs)

0.2.2 (Common, Node.js & Web)

New features

  • Added default_format setting, which allows to perform exec calls without FORMAT clause.

0.2.1 (Common, Node.js & Web)

Breaking changes

Date objects in query parameters are now serialized as time-zone-agnostic Unix timestamps (NNNNNNNNNN[.NNN], optionally with millisecond-precision) instead of datetime strings without time zones (YYYY-MM-DD HH:MM:SS[.MMM]). This means the server will receive the same absolute timestamp the client sent even if the client's time zone and the database server's time zone differ. Previously, if the server used one time zone and the client used another, Date objects would be encoded in the client's time zone and decoded in the server's time zone and create a mismatch.

For instance, if the server used UTC (GMT) and the client used PST (GMT-8), a Date object for "2023-01-01 13:00:00 PST" would be encoded as "2023-01-01 13:00:00.000" and decoded as "2023-01-01 13:00:00 UTC" (which is 2023-01-01 05:00:00 PST). Now, "2023-01-01 13:00:00 PST" is encoded as "1672606800000" and decoded as "2023-01-01 21:00:00 UTC", the same time the client sent.

0.2.0 (web platform support)

Introduces web client (using native fetch and WebStream APIs) without Node.js modules in the common interfaces. No polyfills are required.

Web client is confirmed to work with Chrome/Firefox/CloudFlare workers.

It is now possible to implement new custom connections on top of @clickhouse/client-common.

The client was refactored into three packages:

  • @clickhouse/client-common: all possible platform-independent code, types and interfaces
  • @clickhouse/client-web: new web (or non-Node.js env) connection, uses native fetch.
  • @clickhouse/client: Node.js connection as it was before.

Node.js client breaking changes

  • Changed ping method behavior: it will not throw now. Instead, either { success: true } or { success: false, error: Error } is returned.
  • Log level configuration parameter is now explicit instead of CLICKHOUSE_LOG_LEVEL environment variable. Default is OFF.
  • query return type signature changed to is BaseResultSet<Stream.Readable> (no functional changes)
  • exec return type signature changed to ExecResult<Stream.Readable> (no functional changes)
  • insert<T> params argument type changed to InsertParams<Stream, T> (no functional changes)
  • Experimental schema module is removed

Web client known limitations

  • Streaming for select queries works, but it is disabled for inserts (on the type level as well).
  • KeepAlive is disabled and not configurable yet.
  • Request compression is disabled and configuration is ignored. Response compression works.
  • No logging support yet.

0.1.1

New features

  • Expired socket detection on the client side when using Keep-Alive. If a potentially expired socket is detected, and retry is enabled in the configuration, both socket and request will be immediately destroyed (before sending the data), and the client will recreate the request. See ClickHouseClientConfigOptions.keep_alive for more details. Disabled by default.
  • Allow disabling Keep-Alive feature entirely.
  • TRACE log level.

Examples

Disable Keep-Alive feature

const client = createClient({
  keep_alive: {
    enabled: false,
  },
});

Retry on expired socket

const client = createClient({
  keep_alive: {
    enabled: true,
    // should be slightly less than the `keep_alive_timeout` setting in server's `config.xml`
    // default is 3s there, so 2500 milliseconds seems to be a safe client value in this scenario
    // another example: if your configuration has `keep_alive_timeout` set to 60s, you could put 59_000 here
    socket_ttl: 2500,
    retry_on_expired_socket: true,
  },
});

0.1.0

Breaking changes

  • connect_timeout client setting is removed, as it was unused in the code.

New features

  • command method is introduced as an alternative to exec. command does not expect user to consume the response stream, and it is destroyed immediately. Essentially, this is a shortcut to exec that destroys the stream under the hood. Consider using command instead of exec for DDLs and other custom commands which do not provide any valuable output.

Example:

// incorrect: stream is not consumed and not destroyed, request will be timed out eventually
await client.exec("CREATE TABLE foo (id String) ENGINE Memory");

// correct: stream does not contain any information and just destroyed
const { stream } = await client.exec(
  "CREATE TABLE foo (id String) ENGINE Memory",
);
stream.destroy();

// correct: same as exec + stream.destroy()
await client.command("CREATE TABLE foo (id String) ENGINE Memory");

Bug fixes

  • Fixed delays on subsequent requests after calling insert that happened due to unclosed stream instance when using low number of max_open_connections. See #161 for more details.
  • Request timeouts internal logic rework (see #168)

0.0.16

  • Fix NULL parameter binding. As HTTP interface expects \N instead of 'NULL' string, it is now correctly handled for both null and explicitly undefined parameters. See the test scenarios for more details.

0.0.15

Bug fixes

  • Fix Node.JS 19.x/20.x timeout error (@olexiyb)

0.0.14

New features

  • Added support for JSONStrings, JSONCompact, JSONCompactStrings, JSONColumnsWithMetadata formats (@andrewzolotukhin).

0.0.13

New features

  • query_id can be now overridden for all main client's methods: query, exec, insert.

0.0.12

New features

  • ResultSet.query_id contains a unique query identifier that might be useful for retrieving query metrics from system.query_log
  • User-Agent HTTP header is set according to the language client spec. For example, for client version 0.0.12 and Node.js runtime v19.0.4 on Linux platform, it will be clickhouse-js/0.0.12 (lv:nodejs/19.0.4; os:linux). If ClickHouseClientConfigOptions.application is set, it will be prepended to the generated User-Agent.

Breaking changes

  • client.insert now returns { query_id: string } instead of void
  • client.exec now returns { stream: Stream.Readable, query_id: string } instead of just Stream.Readable

0.0.11, 2022-12-08

Breaking changes

  • log.enabled flag was removed from the client configuration.
  • Use CLICKHOUSE_LOG_LEVEL environment variable instead. Possible values: OFF, TRACE, DEBUG, INFO, WARN, ERROR. Currently, there are only debug messages, but we will log more in the future.

For more details, see PR #110

0.0.10, 2022-11-14

New features

  • Remove request listeners synchronously. #123

0.0.9, 2022-10-25

New features

  • Added ClickHouse session_id support. #121

0.0.8, 2022-10-18

New features

  • Added SSL/TLS support (basic and mutual). #52

0.0.7, 2022-10-18

Bug fixes

  • Allow semicolons in select clause. #116

0.0.6, 2022-10-07

New features

  • Add JSONObjectEachRow input/output and JSON input formats. #113

0.0.5, 2022-10-04

Breaking changes

  • Rows abstraction was renamed to ResultSet.
  • now, every iteration over ResultSet.stream() yields Row[] instead of a single Row. Please check out an example and this PR for more details. These changes allowed us to significantly reduce overhead on select result set streaming.

New features

  • split2 is no longer a package dependency.