@clickhouse/client 1.22.0 → 1.23.0-head.b25cda1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +2 -1
  2. package/dist/client.d.ts +2 -2
  3. package/dist/client.js +11 -4
  4. package/dist/client.js.map +1 -1
  5. package/dist/common/clickhouse_types.d.ts +98 -0
  6. package/dist/common/clickhouse_types.js +30 -0
  7. package/dist/common/clickhouse_types.js.map +1 -0
  8. package/dist/common/client.d.ts +233 -0
  9. package/dist/common/client.js +414 -0
  10. package/dist/common/client.js.map +1 -0
  11. package/dist/common/config.d.ts +234 -0
  12. package/dist/common/config.js +364 -0
  13. package/dist/common/config.js.map +1 -0
  14. package/dist/common/connection.d.ts +124 -0
  15. package/dist/common/connection.js +3 -0
  16. package/dist/common/connection.js.map +1 -0
  17. package/dist/common/data_formatter/format_query_params.d.ts +11 -0
  18. package/dist/common/data_formatter/format_query_params.js +128 -0
  19. package/dist/common/data_formatter/format_query_params.js.map +1 -0
  20. package/dist/common/data_formatter/format_query_settings.d.ts +2 -0
  21. package/dist/common/data_formatter/format_query_settings.js +20 -0
  22. package/dist/common/data_formatter/format_query_settings.js.map +1 -0
  23. package/dist/common/data_formatter/formatter.d.ts +41 -0
  24. package/dist/common/data_formatter/formatter.js +78 -0
  25. package/dist/common/data_formatter/formatter.js.map +1 -0
  26. package/dist/common/data_formatter/index.d.ts +3 -0
  27. package/dist/common/data_formatter/index.js +24 -0
  28. package/dist/common/data_formatter/index.js.map +1 -0
  29. package/dist/common/error/error.d.ts +20 -0
  30. package/dist/common/error/error.js +73 -0
  31. package/dist/common/error/error.js.map +1 -0
  32. package/dist/common/error/index.d.ts +1 -0
  33. package/dist/common/error/index.js +18 -0
  34. package/dist/common/error/index.js.map +1 -0
  35. package/dist/common/index.d.ts +67 -0
  36. package/dist/common/index.js +97 -0
  37. package/dist/common/index.js.map +1 -0
  38. package/dist/common/logger.d.ts +80 -0
  39. package/dist/common/logger.js +154 -0
  40. package/dist/common/logger.js.map +1 -0
  41. package/dist/common/parse/column_types.d.ts +127 -0
  42. package/dist/common/parse/column_types.js +586 -0
  43. package/dist/common/parse/column_types.js.map +1 -0
  44. package/dist/common/parse/index.d.ts +2 -0
  45. package/dist/common/parse/index.js +19 -0
  46. package/dist/common/parse/index.js.map +1 -0
  47. package/dist/common/parse/json_handling.d.ts +19 -0
  48. package/dist/common/parse/json_handling.js +8 -0
  49. package/dist/common/parse/json_handling.js.map +1 -0
  50. package/dist/common/result.d.ts +90 -0
  51. package/dist/common/result.js +3 -0
  52. package/dist/common/result.js.map +1 -0
  53. package/dist/common/settings.d.ts +1990 -0
  54. package/dist/common/settings.js +19 -0
  55. package/dist/common/settings.js.map +1 -0
  56. package/dist/common/tracing.d.ts +146 -0
  57. package/dist/common/tracing.js +76 -0
  58. package/dist/common/tracing.js.map +1 -0
  59. package/dist/common/ts_utils.d.ts +4 -0
  60. package/dist/common/ts_utils.js +3 -0
  61. package/dist/common/ts_utils.js.map +1 -0
  62. package/dist/common/utils/connection.d.ts +21 -0
  63. package/dist/common/utils/connection.js +43 -0
  64. package/dist/common/utils/connection.js.map +1 -0
  65. package/dist/common/utils/index.d.ts +5 -0
  66. package/dist/common/utils/index.js +22 -0
  67. package/dist/common/utils/index.js.map +1 -0
  68. package/dist/common/utils/multipart.d.ts +34 -0
  69. package/dist/common/utils/multipart.js +81 -0
  70. package/dist/common/utils/multipart.js.map +1 -0
  71. package/dist/common/utils/sleep.d.ts +4 -0
  72. package/dist/common/utils/sleep.js +12 -0
  73. package/dist/common/utils/sleep.js.map +1 -0
  74. package/dist/common/utils/stream.d.ts +15 -0
  75. package/dist/common/utils/stream.js +50 -0
  76. package/dist/common/utils/stream.js.map +1 -0
  77. package/dist/common/utils/url.d.ts +20 -0
  78. package/dist/common/utils/url.js +67 -0
  79. package/dist/common/utils/url.js.map +1 -0
  80. package/dist/common/version.d.ts +2 -0
  81. package/dist/common/version.js +4 -0
  82. package/dist/common/version.js.map +1 -0
  83. package/dist/config.d.ts +22 -2
  84. package/dist/config.js +2 -2
  85. package/dist/config.js.map +1 -1
  86. package/dist/connection/compression.d.ts +2 -2
  87. package/dist/connection/compression.js +4 -4
  88. package/dist/connection/compression.js.map +1 -1
  89. package/dist/connection/create_connection.d.ts +1 -1
  90. package/dist/connection/node_base_connection.d.ts +3 -3
  91. package/dist/connection/node_base_connection.js +22 -22
  92. package/dist/connection/node_base_connection.js.map +1 -1
  93. package/dist/connection/node_custom_agent_connection.js +2 -2
  94. package/dist/connection/node_custom_agent_connection.js.map +1 -1
  95. package/dist/connection/node_http_connection.js +2 -2
  96. package/dist/connection/node_http_connection.js.map +1 -1
  97. package/dist/connection/node_https_connection.d.ts +1 -1
  98. package/dist/connection/node_https_connection.js +3 -3
  99. package/dist/connection/node_https_connection.js.map +1 -1
  100. package/dist/connection/socket_pool.d.ts +1 -1
  101. package/dist/connection/socket_pool.js +30 -30
  102. package/dist/connection/socket_pool.js.map +1 -1
  103. package/dist/connection/stream.d.ts +1 -1
  104. package/dist/connection/stream.js +9 -9
  105. package/dist/connection/stream.js.map +1 -1
  106. package/dist/index.d.ts +7 -7
  107. package/dist/index.js +24 -24
  108. package/dist/index.js.map +1 -1
  109. package/dist/result_set.d.ts +1 -1
  110. package/dist/result_set.js +10 -10
  111. package/dist/result_set.js.map +1 -1
  112. package/dist/utils/encoder.d.ts +1 -1
  113. package/dist/utils/encoder.js +5 -5
  114. package/dist/utils/encoder.js.map +1 -1
  115. package/dist/version.d.ts +1 -1
  116. package/dist/version.js +1 -1
  117. package/dist/version.js.map +1 -1
  118. package/package.json +7 -5
  119. package/skills/clickhouse-js-node-rowbinary-parser/EXAMPLES.md +48 -0
  120. package/skills/clickhouse-js-node-rowbinary-parser/README.md +248 -0
  121. package/skills/clickhouse-js-node-rowbinary-parser/SKILL.md +190 -0
  122. package/skills/clickhouse-js-node-rowbinary-parser/case-studies/iot-rowbinary-vs-json.md +83 -0
  123. package/skills/clickhouse-js-node-rowbinary-parser/case-studies/ledger-rowbinary-vs-json.md +103 -0
  124. package/skills/clickhouse-js-node-rowbinary-parser/case-studies/logs-json-wins.md +86 -0
  125. package/skills/clickhouse-js-node-rowbinary-parser/case-studies/wasm-vs-js.md +172 -0
  126. package/skills/clickhouse-js-node-rowbinary-parser/src/aggregateFunction.ts +34 -0
  127. package/skills/clickhouse-js-node-rowbinary-parser/src/bool.ts +10 -0
  128. package/skills/clickhouse-js-node-rowbinary-parser/src/columnar.ts +125 -0
  129. package/skills/clickhouse-js-node-rowbinary-parser/src/composite.ts +181 -0
  130. package/skills/clickhouse-js-node-rowbinary-parser/src/core.ts +77 -0
  131. package/skills/clickhouse-js-node-rowbinary-parser/src/datetime.ts +113 -0
  132. package/skills/clickhouse-js-node-rowbinary-parser/src/decimals.ts +57 -0
  133. package/skills/clickhouse-js-node-rowbinary-parser/src/dynamic.ts +328 -0
  134. package/skills/clickhouse-js-node-rowbinary-parser/src/enums.ts +28 -0
  135. package/skills/clickhouse-js-node-rowbinary-parser/src/examples/carts.ts +71 -0
  136. package/skills/clickhouse-js-node-rowbinary-parser/src/examples/events.ts +51 -0
  137. package/skills/clickhouse-js-node-rowbinary-parser/src/examples/iot.ts +158 -0
  138. package/skills/clickhouse-js-node-rowbinary-parser/src/examples/ledger.ts +98 -0
  139. package/skills/clickhouse-js-node-rowbinary-parser/src/examples/logs.ts +73 -0
  140. package/skills/clickhouse-js-node-rowbinary-parser/src/examples/observability.ts +142 -0
  141. package/skills/clickhouse-js-node-rowbinary-parser/src/examples/orders.ts +65 -0
  142. package/skills/clickhouse-js-node-rowbinary-parser/src/examples/profiles.ts +60 -0
  143. package/skills/clickhouse-js-node-rowbinary-parser/src/examples/telemetry.ts +102 -0
  144. package/skills/clickhouse-js-node-rowbinary-parser/src/floats.ts +32 -0
  145. package/skills/clickhouse-js-node-rowbinary-parser/src/geo.ts +109 -0
  146. package/skills/clickhouse-js-node-rowbinary-parser/src/integers.ts +95 -0
  147. package/skills/clickhouse-js-node-rowbinary-parser/src/interval.ts +54 -0
  148. package/skills/clickhouse-js-node-rowbinary-parser/src/ip.ts +93 -0
  149. package/skills/clickhouse-js-node-rowbinary-parser/src/json.ts +33 -0
  150. package/skills/clickhouse-js-node-rowbinary-parser/src/lowCardinality.ts +18 -0
  151. package/skills/clickhouse-js-node-rowbinary-parser/src/nested.ts +23 -0
  152. package/skills/clickhouse-js-node-rowbinary-parser/src/nothing.ts +29 -0
  153. package/skills/clickhouse-js-node-rowbinary-parser/src/reader.ts +51 -0
  154. package/skills/clickhouse-js-node-rowbinary-parser/src/rows.ts +58 -0
  155. package/skills/clickhouse-js-node-rowbinary-parser/src/simpleAggregateFunction.ts +20 -0
  156. package/skills/clickhouse-js-node-rowbinary-parser/src/stream.ts +276 -0
  157. package/skills/clickhouse-js-node-rowbinary-parser/src/strings.ts +55 -0
  158. package/skills/clickhouse-js-node-rowbinary-parser/src/time.ts +61 -0
  159. package/skills/clickhouse-js-node-rowbinary-parser/src/uuid.ts +153 -0
  160. package/skills/clickhouse-js-node-rowbinary-parser/src/varint.ts +70 -0
@@ -0,0 +1,414 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ClickHouseClient = void 0;
4
+ const parse_1 = require("./parse");
5
+ const logger_1 = require("./logger");
6
+ const config_1 = require("./config");
7
+ const tracing_1 = require("./tracing");
8
+ class ClickHouseClient {
9
+ clientClickHouseSettings;
10
+ connectionParams;
11
+ connection;
12
+ makeResultSet;
13
+ valuesEncoder;
14
+ sessionId;
15
+ role;
16
+ jsonHandling;
17
+ tracer;
18
+ constructor(config) {
19
+ const logger = config?.log?.LoggerClass
20
+ ? new config.log.LoggerClass()
21
+ : new logger_1.DefaultLogger();
22
+ const configWithURL = (0, config_1.prepareConfigWithURL)(config, logger, config.impl.handle_specific_url_params ?? null);
23
+ this.connectionParams = (0, config_1.getConnectionParams)(configWithURL, logger);
24
+ this.clientClickHouseSettings = this.connectionParams.clickhouse_settings;
25
+ this.sessionId = config.session_id;
26
+ this.role = config.role;
27
+ this.connection = config.impl.make_connection(configWithURL, this.connectionParams);
28
+ // Using the connection params log level as it does the parsing.
29
+ // TODO: it would be better to parse the log level in the client itself.
30
+ this.makeResultSet = config.impl.make_result_set;
31
+ this.jsonHandling = {
32
+ ...parse_1.defaultJSONHandling,
33
+ ...config.json,
34
+ };
35
+ this.valuesEncoder = config.impl.values_encoder(this.jsonHandling);
36
+ // Assigned once at client creation: when no tracer is configured, the
37
+ // shared no-op tracer keeps the hot path branch-free.
38
+ this.tracer = config.tracer ?? tracing_1.NoopClickHouseTracer;
39
+ }
40
+ /**
41
+ * Used for most statements that can have a response, such as `SELECT`.
42
+ * Returns an implementation of {@link BaseResultSet}.
43
+ *
44
+ * The `FORMAT` clause should be specified separately via {@link QueryParams.format} (default is `JSON`);
45
+ * this method will always append `FORMAT <format>` to the end of {@link QueryParams.query}.
46
+ * If the query already contains a `FORMAT` clause, ClickHouse will return a syntax error due to a duplicate `FORMAT`.
47
+ * This is intended behavior.
48
+ * Use {@link ClickHouseClient.insert} for data insertion, {@link ClickHouseClient.command} for DDLs,
49
+ * or {@link ClickHouseClient.exec} for queries where you need to provide the full SQL (including `FORMAT`) yourself or where the `FORMAT` suffix is not supported.
50
+ *
51
+ * @note For `SHOW [ROW] POLICIES`, use the full syntax `SHOW POLICIES ON *`,
52
+ * as the short version does not support appending `FORMAT` at the server SQL parser level.
53
+ * See https://github.com/ClickHouse/ClickHouse/issues/105899
54
+ *
55
+ * See {@link DataFormat} for the formats supported by the client.
56
+ */
57
+ async query(params) {
58
+ const format = params.format ?? "JSON";
59
+ const query = formatQuery(params.query, format);
60
+ const queryParams = this.withClientQueryParams(params);
61
+ const { log_writer, log_level } = this.connectionParams;
62
+ return this.tracer.startActiveSpan(tracing_1.ClickHouseSpanNames.query, {
63
+ kind: tracing_1.ClickHouseSpanKind.CLIENT,
64
+ attributes: this.withBaseSpanAttributes({
65
+ "clickhouse.response.format": format,
66
+ "clickhouse.request.query_id": queryParams.query_id,
67
+ "clickhouse.request.session_id": queryParams.session_id,
68
+ }),
69
+ }, async (span) => {
70
+ let queryResult;
71
+ try {
72
+ queryResult = await this.connection.query({
73
+ query,
74
+ ...queryParams,
75
+ });
76
+ }
77
+ catch (err) {
78
+ (0, tracing_1.recordSpanError)(span, err);
79
+ span.end();
80
+ throw err;
81
+ }
82
+ const { stream, query_id, response_headers, http_status_code } = queryResult;
83
+ // The query_id may have been generated by the connection layer.
84
+ span.setAttributes({ "clickhouse.request.query_id": query_id });
85
+ setResponseSpanAttributes(span, { http_status_code });
86
+ // The clickhouse.query span covers the HTTP request lifetime only:
87
+ // it ends here, once response headers are received. A separate
88
+ // clickhouse.query.stream child span is started and handed to the
89
+ // ResultSet to track the response stream consumption (decoded bytes,
90
+ // returned rows, streaming errors). Separating the two spans makes
91
+ // it easy to distinguish the original request duration from a stream
92
+ // that may never end (e.g. tailing a live table).
93
+ span.end();
94
+ return this.tracer.startActiveSpan(tracing_1.ClickHouseSpanNames.query_stream, { kind: tracing_1.ClickHouseSpanKind.CLIENT }, (streamSpan) => {
95
+ try {
96
+ return this.makeResultSet(stream, format, query_id, (err) => {
97
+ if (log_level <= logger_1.ClickHouseLogLevel.ERROR) {
98
+ log_writer.error({
99
+ err,
100
+ module: "Client",
101
+ message: "Error while processing the ResultSet.",
102
+ args: {
103
+ session_id: queryParams.session_id,
104
+ role: queryParams.role,
105
+ query_id,
106
+ },
107
+ });
108
+ }
109
+ }, response_headers, this.jsonHandling, streamSpan);
110
+ }
111
+ catch (err) {
112
+ (0, tracing_1.recordSpanError)(streamSpan, err);
113
+ streamSpan.end();
114
+ throw err;
115
+ }
116
+ // streamSpan is NOT ended here - the ResultSet owns its lifetime.
117
+ });
118
+ });
119
+ }
120
+ /**
121
+ * It should be used for statements that do not have any output,
122
+ * when the format clause is not applicable, or when you are not interested in the response at all.
123
+ * The response stream is destroyed immediately as we do not expect useful information there.
124
+ * Examples of such statements are DDLs or custom inserts.
125
+ *
126
+ * @note if you have a custom query that does not work with {@link ClickHouseClient.query},
127
+ * and you are interested in the response data, consider using {@link ClickHouseClient.exec}.
128
+ */
129
+ async command(params) {
130
+ const query = removeTrailingSemi(params.query.trim());
131
+ const ignore_error_response = params.ignore_error_response ?? false;
132
+ const queryParams = this.withClientQueryParams(params);
133
+ return this.tracer.startActiveSpan(tracing_1.ClickHouseSpanNames.command, {
134
+ kind: tracing_1.ClickHouseSpanKind.CLIENT,
135
+ attributes: this.withBaseSpanAttributes({
136
+ "clickhouse.request.query_id": queryParams.query_id,
137
+ "clickhouse.request.session_id": queryParams.session_id,
138
+ }),
139
+ }, async (span) => {
140
+ try {
141
+ const result = await this.connection.command({
142
+ query,
143
+ ignore_error_response,
144
+ ...queryParams,
145
+ });
146
+ span.setAttributes({
147
+ "clickhouse.request.query_id": result.query_id,
148
+ });
149
+ setResponseSpanAttributes(span, result);
150
+ return result;
151
+ }
152
+ catch (err) {
153
+ (0, tracing_1.recordSpanError)(span, err);
154
+ throw err;
155
+ }
156
+ finally {
157
+ span.end();
158
+ }
159
+ });
160
+ }
161
+ /**
162
+ * Similar to {@link ClickHouseClient.command}, but for the cases where the output _is expected_,
163
+ * but format clause is not applicable. The caller of this method _must_ consume the stream,
164
+ * as the underlying socket will not be released until then, and the request will eventually be timed out.
165
+ *
166
+ * @note it is not intended to use this method to execute the DDLs, such as `CREATE TABLE` or similar;
167
+ * use {@link ClickHouseClient.command} instead.
168
+ */
169
+ async exec(params) {
170
+ const query = removeTrailingSemi(params.query.trim());
171
+ const values = "values" in params ? params.values : undefined;
172
+ const decompress_response_stream = params.decompress_response_stream ?? true;
173
+ const ignore_error_response = params.ignore_error_response ?? false;
174
+ const queryParams = this.withClientQueryParams(params);
175
+ return this.tracer.startActiveSpan(tracing_1.ClickHouseSpanNames.exec, {
176
+ kind: tracing_1.ClickHouseSpanKind.CLIENT,
177
+ attributes: this.withBaseSpanAttributes({
178
+ "clickhouse.request.query_id": queryParams.query_id,
179
+ "clickhouse.request.session_id": queryParams.session_id,
180
+ }),
181
+ }, async (span) => {
182
+ try {
183
+ const result = await this.connection.exec({
184
+ query,
185
+ values,
186
+ decompress_response_stream,
187
+ ignore_error_response,
188
+ ...queryParams,
189
+ });
190
+ span.setAttributes({
191
+ "clickhouse.request.query_id": result.query_id,
192
+ });
193
+ setResponseSpanAttributes(span, result);
194
+ return result;
195
+ }
196
+ catch (err) {
197
+ (0, tracing_1.recordSpanError)(span, err);
198
+ throw err;
199
+ }
200
+ finally {
201
+ span.end();
202
+ }
203
+ });
204
+ }
205
+ /**
206
+ * The primary method for data insertion. It is recommended to avoid arrays in case of large inserts
207
+ * to reduce application memory consumption and consider streaming for most of such use cases.
208
+ * As the insert operation does not provide any output, the response stream is immediately destroyed.
209
+ *
210
+ * @note in case of a custom insert operation (e.g., `INSERT FROM SELECT`),
211
+ * consider using {@link ClickHouseClient.command}, passing the entire raw query there
212
+ * (including the `FORMAT` clause).
213
+ */
214
+ async insert(params) {
215
+ if (Array.isArray(params.values) && params.values.length === 0) {
216
+ return { executed: false, query_id: "", response_headers: {} };
217
+ }
218
+ const format = params.format || "JSONCompactEachRow";
219
+ this.valuesEncoder.validateInsertValues(params.values, format);
220
+ const query = getInsertQuery(params, format);
221
+ const queryParams = this.withClientQueryParams(params);
222
+ return this.tracer.startActiveSpan(tracing_1.ClickHouseSpanNames.insert, {
223
+ kind: tracing_1.ClickHouseSpanKind.CLIENT,
224
+ attributes: this.withBaseSpanAttributes({
225
+ "db.operation.name": "INSERT",
226
+ "db.collection.name": params.table,
227
+ "clickhouse.request.format": format,
228
+ "clickhouse.request.query_id": queryParams.query_id,
229
+ "clickhouse.request.session_id": queryParams.session_id,
230
+ // Only known up front for array-based inserts; for streamed
231
+ // inserts, the row count is not observable by the client.
232
+ "clickhouse.request.sent_rows": Array.isArray(params.values)
233
+ ? params.values.length
234
+ : undefined,
235
+ }),
236
+ }, async (span) => {
237
+ try {
238
+ const values = this.valuesEncoder.encodeValues(params.values, format);
239
+ // TODO: record `clickhouse.request.encoded_bytes` (the
240
+ // pre-compression request body size) here. This is a
241
+ // post-common-deprecation feature: once `client-common` is
242
+ // deprecated and the Node.js / Web clients are fully independent,
243
+ // each client can measure the encoded payload using its own
244
+ // platform-native byte-length primitive (e.g. `Buffer.byteLength`)
245
+ // instead of a hand-rolled common implementation.
246
+ const result = await this.connection.insert({
247
+ query,
248
+ values,
249
+ ...queryParams,
250
+ });
251
+ span.setAttributes({
252
+ "clickhouse.request.query_id": result.query_id,
253
+ });
254
+ setResponseSpanAttributes(span, result);
255
+ return { ...result, executed: true };
256
+ }
257
+ catch (err) {
258
+ (0, tracing_1.recordSpanError)(span, err);
259
+ throw err;
260
+ }
261
+ finally {
262
+ span.end();
263
+ }
264
+ });
265
+ }
266
+ /**
267
+ * A health-check request. It does not throw if an error occurs - the error is returned inside the result object.
268
+ *
269
+ * By default, Node.js version uses the built-in `/ping` endpoint, which does not verify credentials.
270
+ * Optionally, it can be switched to a `SELECT` query (see {@link PingParamsWithSelectQuery}).
271
+ * In that case, the server will verify the credentials.
272
+ *
273
+ * **NOTE**: Since the `/ping` endpoint does not support CORS, the Web version always uses a `SELECT` query.
274
+ */
275
+ async ping(params) {
276
+ const select = params?.select ?? false;
277
+ return this.tracer.startActiveSpan(tracing_1.ClickHouseSpanNames.ping, {
278
+ kind: tracing_1.ClickHouseSpanKind.CLIENT,
279
+ attributes: this.withBaseSpanAttributes({
280
+ "clickhouse.ping.select": select,
281
+ }),
282
+ }, async (span) => {
283
+ try {
284
+ return await this.connection.ping(params ?? { select: false });
285
+ }
286
+ catch (err) {
287
+ (0, tracing_1.recordSpanError)(span, err);
288
+ throw err;
289
+ }
290
+ finally {
291
+ span.end();
292
+ }
293
+ });
294
+ }
295
+ /**
296
+ * Shuts down the underlying connection.
297
+ * This method should ideally be called only once per application lifecycle,
298
+ * for example, during the graceful shutdown phase.
299
+ */
300
+ async close() {
301
+ return await this.connection.close();
302
+ }
303
+ /**
304
+ * Closes the client connection.
305
+ *
306
+ * Automatically called when using `using` statement in supported environments.
307
+ * @see {@link ClickHouseClient.close}
308
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/using
309
+ */
310
+ async [Symbol.asyncDispose]() {
311
+ await this.close();
312
+ }
313
+ withBaseSpanAttributes(extra) {
314
+ const url = this.connectionParams.url;
315
+ const attrs = {
316
+ "db.system.name": "clickhouse",
317
+ "server.address": url.hostname,
318
+ "server.port": getServerPort(url),
319
+ "db.namespace": this.connectionParams.database,
320
+ };
321
+ if (this.connectionParams.application_id !== undefined) {
322
+ attrs["clickhouse.application"] = this.connectionParams.application_id;
323
+ }
324
+ for (const [k, v] of Object.entries(extra)) {
325
+ if (v !== undefined)
326
+ attrs[k] = v;
327
+ }
328
+ return attrs;
329
+ }
330
+ withClientQueryParams(params) {
331
+ return {
332
+ clickhouse_settings: {
333
+ ...this.clientClickHouseSettings,
334
+ ...params.clickhouse_settings,
335
+ },
336
+ query_params: params.query_params,
337
+ abort_signal: params.abort_signal,
338
+ query_id: params.query_id,
339
+ session_id: params.session_id ?? this.sessionId,
340
+ role: params.role ?? this.role,
341
+ auth: params.auth,
342
+ http_headers: params.http_headers,
343
+ use_multipart_params: params.use_multipart_params,
344
+ use_multipart_params_auto: params.use_multipart_params_auto,
345
+ };
346
+ }
347
+ }
348
+ exports.ClickHouseClient = ClickHouseClient;
349
+ function getServerPort(url) {
350
+ if (url.port !== "") {
351
+ return Number(url.port);
352
+ }
353
+ return url.protocol === "https:" ? 443 : 80;
354
+ }
355
+ /** Records HTTP status and `X-ClickHouse-Summary` counters on the span once
356
+ * the response (headers) arrived. The summary values are complete only when
357
+ * the query was executed with `wait_end_of_query=1`; see
358
+ * {@link ClickHouseSummary}. */
359
+ function setResponseSpanAttributes(span, result) {
360
+ const attributes = {};
361
+ if (result.http_status_code !== undefined) {
362
+ attributes["db.response.status_code"] = result.http_status_code;
363
+ }
364
+ const summary = result.summary;
365
+ if (summary !== undefined) {
366
+ attributes["clickhouse.summary.read_rows"] = summary.read_rows;
367
+ attributes["clickhouse.summary.read_bytes"] = summary.read_bytes;
368
+ attributes["clickhouse.summary.written_rows"] = summary.written_rows;
369
+ attributes["clickhouse.summary.written_bytes"] = summary.written_bytes;
370
+ attributes["clickhouse.summary.result_rows"] = summary.result_rows;
371
+ attributes["clickhouse.summary.result_bytes"] = summary.result_bytes;
372
+ attributes["clickhouse.summary.elapsed_ns"] = summary.elapsed_ns;
373
+ }
374
+ span.setAttributes(attributes);
375
+ }
376
+ function formatQuery(query, format) {
377
+ query = query.trim();
378
+ query = removeTrailingSemi(query);
379
+ return query + " \nFORMAT " + format;
380
+ }
381
+ function removeTrailingSemi(query) {
382
+ let lastNonSemiIdx = query.length;
383
+ for (let i = lastNonSemiIdx; i > 0; i--) {
384
+ if (query[i - 1] !== ";") {
385
+ lastNonSemiIdx = i;
386
+ break;
387
+ }
388
+ }
389
+ if (lastNonSemiIdx !== query.length) {
390
+ return query.slice(0, lastNonSemiIdx);
391
+ }
392
+ return query;
393
+ }
394
+ function isInsertColumnsExcept(obj) {
395
+ return (obj !== undefined &&
396
+ obj !== null &&
397
+ typeof obj === "object" &&
398
+ // Avoiding ESLint no-prototype-builtins error
399
+ Object.prototype.hasOwnProperty.call(obj, "except"));
400
+ }
401
+ function getInsertQuery(params, format) {
402
+ let columnsPart = "";
403
+ if (params.columns !== undefined) {
404
+ if (Array.isArray(params.columns) && params.columns.length > 0) {
405
+ columnsPart = ` (${params.columns.join(", ")})`;
406
+ }
407
+ else if (isInsertColumnsExcept(params.columns) &&
408
+ params.columns.except.length > 0) {
409
+ columnsPart = ` (* EXCEPT (${params.columns.except.join(", ")}))`;
410
+ }
411
+ }
412
+ return `INSERT INTO ${params.table.trim()}${columnsPart} FORMAT ${format}`;
413
+ }
414
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/common/client.ts"],"names":[],"mappings":";;;AAYA,mCAA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AC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC/D,WAAW,GAAG,KAAK,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC;QAClD,CAAC;aAAM,IACL,qBAAqB,CAAC,MAAM,CAAC,OAAO,CAAC;YACrC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,EAChC,CAAC;YACD,WAAW,GAAG,eAAe,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;QACpE,CAAC;IACH,CAAC;IACD,OAAO,eAAe,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,WAAW,WAAW,MAAM,EAAE,CAAC;AAC7E,CAAC"}
@@ -0,0 +1,234 @@
1
+ import type { InsertValues, ResponseHeaders } from "./clickhouse_types";
2
+ import type { CompressionMethod, Connection, ConnectionParams, RequestCompression } from "./connection";
3
+ import type { DataFormat } from "./data_formatter";
4
+ import type { Logger } from "./logger";
5
+ import { ClickHouseLogLevel } from "./logger";
6
+ import { type JSONHandling } from "./parse/json_handling";
7
+ import type { BaseResultSet } from "./result";
8
+ import type { ClickHouseSettings } from "./settings";
9
+ import type { ClickHouseSpan, ClickHouseTracer } from "./tracing";
10
+ export interface BaseClickHouseClientConfigOptions {
11
+ /** @deprecated since version 1.0.0. Use {@link url} instead. <br/>
12
+ * A ClickHouse instance URL.
13
+ * @default http://localhost:8123 */
14
+ host?: string;
15
+ /** A ClickHouse instance URL.
16
+ * @default http://localhost:8123 */
17
+ url?: string | URL;
18
+ /** An optional pathname to add to the ClickHouse URL after it is parsed by the client.
19
+ * For example, if you use a proxy, and your ClickHouse instance can be accessed as http://proxy:8123/clickhouse_server,
20
+ * specify `clickhouse_server` here (with or without a leading slash);
21
+ * otherwise, if provided directly in the {@link url}, it will be considered as the `database` option.<br/>
22
+ * Multiple segments are supported, e.g. `/my_proxy/db`.
23
+ * @default empty string */
24
+ pathname?: string;
25
+ /** The request timeout in milliseconds.
26
+ * @default 30_000 */
27
+ request_timeout?: number;
28
+ /** Maximum number of sockets to allow per host.
29
+ * @default 10 */
30
+ max_open_connections?: number;
31
+ /** Request and response compression settings. */
32
+ compression?: {
33
+ /** Instructs the ClickHouse server to respond with a compressed response body.
34
+ * `true` requests `gzip`; pass `{ codec }` to select the codec explicitly,
35
+ * e.g. `{ codec: "zstd" }` or `{ codec: "br" }`. This adds the matching
36
+ * `Accept-Encoding` header and the `enable_http_compression=1` ClickHouse HTTP
37
+ * setting. Decompression takes no codec options (the server chose them).
38
+ * `"zstd"` requires Node.js >= 22.15.0; `"br"` works on any supported Node.js.
39
+ * On `@clickhouse/client-web`, `zstd` is rejected at client creation; `gzip`
40
+ * and `br` responses are decompressed by the browser.
41
+ * <p><b>Warning</b>: Response compression can't be enabled for a user with readonly=1, as ClickHouse will not allow settings modifications for such user.</p>
42
+ * @default false */
43
+ response?: boolean | {
44
+ codec: CompressionMethod;
45
+ };
46
+ /** Enables compression of the outgoing request (insert) body.
47
+ * `true` uses `gzip` with defaults; pass a per-codec object to select the
48
+ * codec and tune it: `{ codec: "gzip", level }`, `{ codec: "zstd", level }`,
49
+ * or `{ codec: "br", quality }`. Each codec exposes its own option (a `level`
50
+ * for gzip/zstd, a `quality` for Brotli); when omitted, a sensible default is
51
+ * used (gzip/zstd use zlib's defaults, `br` defaults to quality 4 since
52
+ * zlib's brotli default of 11 is far too slow for a streaming insert body).
53
+ * `"zstd"` requires Node.js >= 22.15.0; `"br"` works on any supported Node.js.
54
+ * Request-body compression is performed only by `@clickhouse/client` (Node.js);
55
+ * `@clickhouse/client-web` sends request bodies uncompressed.
56
+ * @default false */
57
+ request?: boolean | RequestCompression;
58
+ };
59
+ /** The name of the user on whose behalf requests are made.
60
+ * Should not be set if {@link access_token} is provided.
61
+ * @default default */
62
+ username?: string;
63
+ /** The user password.
64
+ * Should not be set if {@link access_token} is provided.
65
+ * @default empty string */
66
+ password?: string;
67
+ /** A JWT access token to authenticate with ClickHouse.
68
+ * JWT token authentication is supported in ClickHouse Cloud only.
69
+ * Should not be set if {@link username} or {@link password} are provided.
70
+ * @default empty */
71
+ access_token?: string;
72
+ /** The name of the application using the JS client.
73
+ * @default empty string */
74
+ application?: string;
75
+ /** Database name to use.
76
+ * @default default */
77
+ database?: string;
78
+ /** ClickHouse settings to apply to all requests.
79
+ * @default empty object */
80
+ clickhouse_settings?: ClickHouseSettings;
81
+ log?: {
82
+ /** A class to instantiate a custom logger implementation.
83
+ * @default see {@link DefaultLogger} */
84
+ LoggerClass?: new () => Logger;
85
+ /** @default set to {@link ClickHouseLogLevel.WARN} */
86
+ level?: ClickHouseLogLevel;
87
+ };
88
+ /** ClickHouse Session id to attach to the outgoing requests.
89
+ * @default empty string (no session) */
90
+ session_id?: string;
91
+ /** ClickHouse role name(s) to attach to the outgoing requests.
92
+ * @default undefined string (no roles) */
93
+ role?: string | Array<string>;
94
+ /** @deprecated since version 1.0.0. Use {@link http_headers} instead. <br/>
95
+ * Additional HTTP headers to attach to the outgoing requests.
96
+ * @default empty object */
97
+ additional_headers?: Record<string, string>;
98
+ /** Additional HTTP headers to attach to the outgoing requests.
99
+ * @default empty object */
100
+ http_headers?: Record<string, string>;
101
+ /** HTTP Keep-Alive related settings. */
102
+ keep_alive?: {
103
+ /** Enable or disable HTTP Keep-Alive mechanism.
104
+ * @default true */
105
+ enabled?: boolean;
106
+ };
107
+ /**
108
+ * Custom parsing when handling with JSON objects
109
+ *
110
+ * Defaults to using standard `JSON.parse` and `JSON.stringify`
111
+ */
112
+ json?: Partial<JSONHandling>;
113
+ /**
114
+ * Optional tracer called by the client around key lifecycle operations
115
+ * (`query` / `command` / `exec` / `insert` / `ping`). The interface is a
116
+ * structural subset of the OpenTelemetry `Tracer`/`Span` APIs, so a raw
117
+ * OTEL tracer (`trace.getTracer(...)`) can be passed here as-is - but the
118
+ * client itself depends on no tracing library.
119
+ *
120
+ * Each operation runs inside `tracer.startActiveSpan(name, options, fn)`.
121
+ * For OpenTelemetry, active-span context propagation across the operation's
122
+ * `await` points requires the `AsyncLocalStorageContextManager` (from
123
+ * `@opentelemetry/context-async-hooks`) to be registered; this is the
124
+ * default context manager in the OpenTelemetry Node.js SDK.
125
+ *
126
+ * Tracer calls are inlined into the client's hot path with no defensive
127
+ * wrapper: exceptions thrown by the tracer or its spans propagate to the
128
+ * caller. Make sure your tracer doesn't throw.
129
+ *
130
+ * @see {@link ClickHouseTracer}
131
+ * @default undefined (no spans are emitted; the client uses a shared no-op tracer/span to keep call sites monomorphic,
132
+ * at the cost of a small fixed per-operation overhead)
133
+ */
134
+ tracer?: ClickHouseTracer;
135
+ /** When true, query() sends query_params as multipart/form-data parts
136
+ * instead of URL query string entries. This avoids HTTP URL length limits
137
+ * when query parameters contain large arrays (25K+ values).
138
+ * The SQL query is also moved into a multipart part named "query".
139
+ * All other URL search params (database, query_id, settings, etc.) remain in the URL.
140
+ * @default false */
141
+ use_multipart_params?: boolean;
142
+ /** When true, query() automatically sends query_params as multipart/form-data
143
+ * parts (see {@link use_multipart_params}) once their URL-encoded length
144
+ * exceeds a threshold (4096 characters), avoiding HTTP 414/400 errors from
145
+ * over-long URLs. Smaller parameter payloads remain in the URL query string.
146
+ * Has no effect when {@link use_multipart_params} is enabled, as that always
147
+ * sends the parameters as multipart/form-data parts.
148
+ * @default false */
149
+ use_multipart_params_auto?: boolean;
150
+ }
151
+ export type MakeConnection<Stream, Config = BaseClickHouseClientConfigOptionsWithURL> = (config: Config, params: ConnectionParams) => Connection<Stream>;
152
+ export type MakeResultSet<Stream> = <Format extends DataFormat, ResultSet extends BaseResultSet<Stream, Format>>(stream: Stream, format: Format, query_id: string, log_error: (err: Error) => void, response_headers: ResponseHeaders, jsonHandling: JSONHandling,
153
+ /** When the client was configured with a {@link ClickHouseTracer}, a
154
+ * `clickhouse.query.stream` child span is created and passed here. The
155
+ * result set tracks its own streaming progress (decoded bytes/rows) and
156
+ * must record the final response metrics on the span and end it when the
157
+ * stream is fully consumed, closed, or fails. */
158
+ span?: ClickHouseSpan) => ResultSet;
159
+ export type MakeValuesEncoder<Stream> = (jsonHandling: JSONHandling) => ValuesEncoder<Stream>;
160
+ export interface ValuesEncoder<Stream> {
161
+ validateInsertValues<T = unknown>(values: InsertValues<Stream, T>, format: DataFormat): void;
162
+ /**
163
+ * A function encodes an array or a stream of JSON objects to a format compatible with ClickHouse.
164
+ * If values are provided as an array of JSON objects, the function encodes it in place.
165
+ * If values are provided as a stream of JSON objects, the function sets up the encoding of each chunk.
166
+ * If values are provided as a raw non-object stream, the function does nothing.
167
+ *
168
+ * @param values a set of values to send to ClickHouse.
169
+ * @param format a format to encode value to.
170
+ */
171
+ encodeValues<T = unknown>(values: InsertValues<Stream, T>, format: DataFormat): string | Stream;
172
+ }
173
+ /**
174
+ * An implementation might have extra config parameters that we can parse from the connection URL.
175
+ * These are supposed to be processed after we finish parsing the base configuration.
176
+ * URL params handled in the common package will be deleted from the URL object.
177
+ * This way we ensure that only implementation-specific params are passed there,
178
+ * so we can indicate which URL parameters are unknown by both common and implementation packages.
179
+ */
180
+ export type HandleImplSpecificURLParams = (config: BaseClickHouseClientConfigOptions, url: URL) => {
181
+ config: BaseClickHouseClientConfigOptions;
182
+ handled_params: Set<string>;
183
+ unknown_params: Set<string>;
184
+ };
185
+ /** Things that may vary between Web/Node.js/etc client implementations. */
186
+ export interface ImplementationDetails<Stream> {
187
+ impl: {
188
+ make_connection: MakeConnection<Stream>;
189
+ make_result_set: MakeResultSet<Stream>;
190
+ values_encoder: MakeValuesEncoder<Stream>;
191
+ handle_specific_url_params?: HandleImplSpecificURLParams;
192
+ };
193
+ }
194
+ export type BaseClickHouseClientConfigOptionsWithURL = Omit<BaseClickHouseClientConfigOptions, "url"> & {
195
+ url: URL;
196
+ };
197
+ /**
198
+ * Validates and normalizes the provided "base" config.
199
+ * Warns about deprecated configuration parameters usage.
200
+ * Parses the common URL parameters into the configuration parameters (these are the same for all implementations).
201
+ * Parses implementation-specific URL parameters using the handler provided by that implementation.
202
+ * Merges these parameters with the base config and implementation-specific defaults.
203
+ * Enforces certain defaults in case of deprecated keys or readonly mode.
204
+ */
205
+ export declare function prepareConfigWithURL(baseConfigOptions: BaseClickHouseClientConfigOptions, logger: Logger, handleImplURLParams: HandleImplSpecificURLParams | null): BaseClickHouseClientConfigOptionsWithURL;
206
+ export declare function getConnectionParams(config: BaseClickHouseClientConfigOptionsWithURL, logger: Logger): ConnectionParams;
207
+ /**
208
+ * Merge two versions of the config: base (hardcoded) from the instance creation and the URL parsed one.
209
+ * URL config takes priority and overrides the base config parameters.
210
+ * If a value is overridden, then a warning will be logged (even if the log level is OFF).
211
+ */
212
+ export declare function mergeConfigs(baseConfig: BaseClickHouseClientConfigOptions, configFromURL: BaseClickHouseClientConfigOptions, logger: Logger): BaseClickHouseClientConfigOptions;
213
+ export declare function createUrl(configURL: string | URL | undefined): URL;
214
+ /**
215
+ * @param url potentially contains auth, database and URL params to parse the configuration from
216
+ * @param handleExtraURLParams some platform-specific URL params might be unknown by the common package;
217
+ * use this function defined in the implementation to handle them. Logs warnings in case of hardcode overrides.
218
+ */
219
+ export declare function loadConfigOptionsFromURL(url: URL, handleExtraURLParams: HandleImplSpecificURLParams | null): [URL, BaseClickHouseClientConfigOptions];
220
+ export declare function booleanConfigURLValue({ key, value, }: {
221
+ key: string;
222
+ value: string;
223
+ }): boolean;
224
+ export declare function numberConfigURLValue({ key, value, min, max, }: {
225
+ key: string;
226
+ value: string;
227
+ min?: number;
228
+ max?: number;
229
+ }): number;
230
+ export declare function enumConfigURLValue<Enum, Key extends string>({ key, value, enumObject, }: {
231
+ key: string;
232
+ value: string;
233
+ enumObject: Record<Key, Enum>;
234
+ }): Enum;