import type { InsertValues, ResponseHeaders } from "./clickhouse_types";
import type { CompressionMethod, Connection, ConnectionParams, RequestCompression } from "./connection";
import type { DataFormat } from "./data_formatter";
import type { Logger } from "./logger";
import { ClickHouseLogLevel } from "./logger";
import { type JSONHandling } from "./parse/json_handling";
import type { BaseResultSet } from "./result";
import type { ClickHouseSettings } from "./settings";
import type { ClickHouseSpan, ClickHouseTracer } from "./tracing";
export interface BaseClickHouseClientConfigOptions {
/** @deprecated since version 1.0.0. Use {@link url} instead.
* A ClickHouse instance URL.
* @default http://localhost:8123 */
host?: string;
/** A ClickHouse instance URL.
* @default http://localhost:8123 */
url?: string | URL;
/** An optional pathname to add to the ClickHouse URL after it is parsed by the client.
* For example, if you use a proxy, and your ClickHouse instance can be accessed as http://proxy:8123/clickhouse_server,
* specify `clickhouse_server` here (with or without a leading slash);
* otherwise, if provided directly in the {@link url}, it will be considered as the `database` option.
* Multiple segments are supported, e.g. `/my_proxy/db`.
* @default empty string */
pathname?: string;
/** The request timeout in milliseconds.
* @default 30_000 */
request_timeout?: number;
/** Maximum number of sockets to allow per host.
* @default 10 */
max_open_connections?: number;
/** Request and response compression settings. */
compression?: {
/** Instructs the ClickHouse server to respond with a compressed response body.
* `true` requests `gzip`; pass `{ codec }` to select the codec explicitly,
* e.g. `{ codec: "zstd" }` or `{ codec: "br" }`. This adds the matching
* `Accept-Encoding` header and the `enable_http_compression=1` ClickHouse HTTP
* setting. Decompression takes no codec options (the server chose them).
* `"zstd"` requires Node.js >= 22.15.0; `"br"` works on any supported Node.js.
* On `@clickhouse/client-web`, `zstd` is rejected at client creation; `gzip`
* and `br` responses are decompressed by the browser.
*
Warning: Response compression can't be enabled for a user with readonly=1, as ClickHouse will not allow settings modifications for such user.
* @default false */
response?: boolean | {
codec: CompressionMethod;
};
/** Enables compression of the outgoing request (insert) body.
* `true` uses `gzip` with defaults; pass a per-codec object to select the
* codec and tune it: `{ codec: "gzip", level }`, `{ codec: "zstd", level }`,
* or `{ codec: "br", quality }`. Each codec exposes its own option (a `level`
* for gzip/zstd, a `quality` for Brotli); when omitted, a sensible default is
* used (gzip/zstd use zlib's defaults, `br` defaults to quality 4 since
* zlib's brotli default of 11 is far too slow for a streaming insert body).
* `"zstd"` requires Node.js >= 22.15.0; `"br"` works on any supported Node.js.
* Request-body compression is performed only by `@clickhouse/client` (Node.js);
* `@clickhouse/client-web` sends request bodies uncompressed.
* @default false */
request?: boolean | RequestCompression;
};
/** The name of the user on whose behalf requests are made.
* Should not be set if {@link access_token} is provided.
* @default default */
username?: string;
/** The user password.
* Should not be set if {@link access_token} is provided.
* @default empty string */
password?: string;
/** A JWT access token to authenticate with ClickHouse.
* JWT token authentication is supported in ClickHouse Cloud only.
* Should not be set if {@link username} or {@link password} are provided.
* @default empty */
access_token?: string;
/** The name of the application using the JS client.
* @default empty string */
application?: string;
/** Database name to use.
* @default default */
database?: string;
/** ClickHouse settings to apply to all requests.
* @default empty object */
clickhouse_settings?: ClickHouseSettings;
log?: {
/** A class to instantiate a custom logger implementation.
* @default see {@link DefaultLogger} */
LoggerClass?: new () => Logger;
/** @default set to {@link ClickHouseLogLevel.WARN} */
level?: ClickHouseLogLevel;
};
/** ClickHouse Session id to attach to the outgoing requests.
* @default empty string (no session) */
session_id?: string;
/** ClickHouse role name(s) to attach to the outgoing requests.
* @default undefined string (no roles) */
role?: string | Array;
/** @deprecated since version 1.0.0. Use {@link http_headers} instead.
* Additional HTTP headers to attach to the outgoing requests.
* @default empty object */
additional_headers?: Record;
/** Additional HTTP headers to attach to the outgoing requests.
* @default empty object */
http_headers?: Record;
/** HTTP Keep-Alive related settings. */
keep_alive?: {
/** Enable or disable HTTP Keep-Alive mechanism.
* @default true */
enabled?: boolean;
};
/**
* Custom parsing when handling with JSON objects
*
* Defaults to using standard `JSON.parse` and `JSON.stringify`
*/
json?: Partial;
/**
* Optional tracer called by the client around key lifecycle operations
* (`query` / `command` / `exec` / `insert` / `ping`). The interface is a
* structural subset of the OpenTelemetry `Tracer`/`Span` APIs, so a raw
* OTEL tracer (`trace.getTracer(...)`) can be passed here as-is - but the
* client itself depends on no tracing library.
*
* Each operation runs inside `tracer.startActiveSpan(name, options, fn)`.
* For OpenTelemetry, active-span context propagation across the operation's
* `await` points requires the `AsyncLocalStorageContextManager` (from
* `@opentelemetry/context-async-hooks`) to be registered; this is the
* default context manager in the OpenTelemetry Node.js SDK.
*
* Tracer calls are inlined into the client's hot path with no defensive
* wrapper: exceptions thrown by the tracer or its spans propagate to the
* caller. Make sure your tracer doesn't throw.
*
* @see {@link ClickHouseTracer}
* @default undefined (no spans are emitted; the client uses a shared no-op tracer/span to keep call sites monomorphic,
* at the cost of a small fixed per-operation overhead)
*/
tracer?: ClickHouseTracer;
/** When true, query() sends query_params as multipart/form-data parts
* instead of URL query string entries. This avoids HTTP URL length limits
* when query parameters contain large arrays (25K+ values).
* The SQL query is also moved into a multipart part named "query".
* All other URL search params (database, query_id, settings, etc.) remain in the URL.
* @default false */
use_multipart_params?: boolean;
/** When true, query() automatically sends query_params as multipart/form-data
* parts (see {@link use_multipart_params}) once their URL-encoded length
* exceeds a threshold (4096 characters), avoiding HTTP 414/400 errors from
* over-long URLs. Smaller parameter payloads remain in the URL query string.
* Has no effect when {@link use_multipart_params} is enabled, as that always
* sends the parameters as multipart/form-data parts.
* @default false */
use_multipart_params_auto?: boolean;
}
export type MakeConnection = (config: Config, params: ConnectionParams) => Connection;
export type MakeResultSet = >(stream: Stream, format: Format, query_id: string, log_error: (err: Error) => void, response_headers: ResponseHeaders, jsonHandling: JSONHandling,
/** When the client was configured with a {@link ClickHouseTracer}, a
* `clickhouse.query.stream` child span is created and passed here. The
* result set tracks its own streaming progress (decoded bytes/rows) and
* must record the final response metrics on the span and end it when the
* stream is fully consumed, closed, or fails. */
span?: ClickHouseSpan) => ResultSet;
export type MakeValuesEncoder = (jsonHandling: JSONHandling) => ValuesEncoder;
export interface ValuesEncoder {
validateInsertValues(values: InsertValues, format: DataFormat): void;
/**
* A function encodes an array or a stream of JSON objects to a format compatible with ClickHouse.
* If values are provided as an array of JSON objects, the function encodes it in place.
* If values are provided as a stream of JSON objects, the function sets up the encoding of each chunk.
* If values are provided as a raw non-object stream, the function does nothing.
*
* @param values a set of values to send to ClickHouse.
* @param format a format to encode value to.
*/
encodeValues(values: InsertValues, format: DataFormat): string | Stream;
}
/**
* An implementation might have extra config parameters that we can parse from the connection URL.
* These are supposed to be processed after we finish parsing the base configuration.
* URL params handled in the common package will be deleted from the URL object.
* This way we ensure that only implementation-specific params are passed there,
* so we can indicate which URL parameters are unknown by both common and implementation packages.
*/
export type HandleImplSpecificURLParams = (config: BaseClickHouseClientConfigOptions, url: URL) => {
config: BaseClickHouseClientConfigOptions;
handled_params: Set;
unknown_params: Set;
};
/** Things that may vary between Web/Node.js/etc client implementations. */
export interface ImplementationDetails {
impl: {
make_connection: MakeConnection;
make_result_set: MakeResultSet;
values_encoder: MakeValuesEncoder;
handle_specific_url_params?: HandleImplSpecificURLParams;
};
}
export type BaseClickHouseClientConfigOptionsWithURL = Omit & {
url: URL;
};
/**
* Validates and normalizes the provided "base" config.
* Warns about deprecated configuration parameters usage.
* Parses the common URL parameters into the configuration parameters (these are the same for all implementations).
* Parses implementation-specific URL parameters using the handler provided by that implementation.
* Merges these parameters with the base config and implementation-specific defaults.
* Enforces certain defaults in case of deprecated keys or readonly mode.
*/
export declare function prepareConfigWithURL(baseConfigOptions: BaseClickHouseClientConfigOptions, logger: Logger, handleImplURLParams: HandleImplSpecificURLParams | null): BaseClickHouseClientConfigOptionsWithURL;
export declare function getConnectionParams(config: BaseClickHouseClientConfigOptionsWithURL, logger: Logger): ConnectionParams;
/**
* Merge two versions of the config: base (hardcoded) from the instance creation and the URL parsed one.
* URL config takes priority and overrides the base config parameters.
* If a value is overridden, then a warning will be logged (even if the log level is OFF).
*/
export declare function mergeConfigs(baseConfig: BaseClickHouseClientConfigOptions, configFromURL: BaseClickHouseClientConfigOptions, logger: Logger): BaseClickHouseClientConfigOptions;
export declare function createUrl(configURL: string | URL | undefined): URL;
/**
* @param url potentially contains auth, database and URL params to parse the configuration from
* @param handleExtraURLParams some platform-specific URL params might be unknown by the common package;
* use this function defined in the implementation to handle them. Logs warnings in case of hardcode overrides.
*/
export declare function loadConfigOptionsFromURL(url: URL, handleExtraURLParams: HandleImplSpecificURLParams | null): [URL, BaseClickHouseClientConfigOptions];
export declare function booleanConfigURLValue({ key, value, }: {
key: string;
value: string;
}): boolean;
export declare function numberConfigURLValue({ key, value, min, max, }: {
key: string;
value: string;
min?: number;
max?: number;
}): number;
export declare function enumConfigURLValue({ key, value, enumObject, }: {
key: string;
value: string;
enumObject: Record;
}): Enum;