@clickhouse/client-common 0.2.0-beta1

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 (57) hide show
  1. package/LICENSE +203 -0
  2. package/README.md +35 -0
  3. package/dist/clickhouse_types.d.ts +24 -0
  4. package/dist/clickhouse_types.js +3 -0
  5. package/dist/clickhouse_types.js.map +1 -0
  6. package/dist/client.d.ts +149 -0
  7. package/dist/client.js +187 -0
  8. package/dist/client.js.map +1 -0
  9. package/dist/connection.d.ts +44 -0
  10. package/dist/connection.js +3 -0
  11. package/dist/connection.js.map +1 -0
  12. package/dist/data_formatter/format_query_params.d.ts +1 -0
  13. package/dist/data_formatter/format_query_params.js +61 -0
  14. package/dist/data_formatter/format_query_params.js.map +1 -0
  15. package/dist/data_formatter/format_query_settings.d.ts +2 -0
  16. package/dist/data_formatter/format_query_settings.js +21 -0
  17. package/dist/data_formatter/format_query_settings.js.map +1 -0
  18. package/dist/data_formatter/formatter.d.ts +23 -0
  19. package/dist/data_formatter/formatter.js +96 -0
  20. package/dist/data_formatter/formatter.js.map +1 -0
  21. package/dist/data_formatter/index.d.ts +3 -0
  22. package/dist/data_formatter/index.js +23 -0
  23. package/dist/data_formatter/index.js.map +1 -0
  24. package/dist/error/index.d.ts +1 -0
  25. package/dist/error/index.js +18 -0
  26. package/dist/error/index.js.map +1 -0
  27. package/dist/error/parse_error.d.ts +12 -0
  28. package/dist/error/parse_error.js +41 -0
  29. package/dist/error/parse_error.js.map +1 -0
  30. package/dist/index.d.ts +16 -0
  31. package/dist/index.js +33 -0
  32. package/dist/index.js.map +1 -0
  33. package/dist/logger.d.ts +40 -0
  34. package/dist/logger.js +81 -0
  35. package/dist/logger.js.map +1 -0
  36. package/dist/result.d.ts +46 -0
  37. package/dist/result.js +3 -0
  38. package/dist/result.js.map +1 -0
  39. package/dist/settings.d.ts +1453 -0
  40. package/dist/settings.js +28 -0
  41. package/dist/settings.js.map +1 -0
  42. package/dist/utils/connection.d.ts +10 -0
  43. package/dist/utils/connection.js +27 -0
  44. package/dist/utils/connection.js.map +1 -0
  45. package/dist/utils/index.d.ts +3 -0
  46. package/dist/utils/index.js +20 -0
  47. package/dist/utils/index.js.map +1 -0
  48. package/dist/utils/string.d.ts +1 -0
  49. package/dist/utils/string.js +8 -0
  50. package/dist/utils/string.js.map +1 -0
  51. package/dist/utils/url.d.ts +16 -0
  52. package/dist/utils/url.js +53 -0
  53. package/dist/utils/url.js.map +1 -0
  54. package/dist/version.d.ts +2 -0
  55. package/dist/version.js +4 -0
  56. package/dist/version.js.map +1 -0
  57. package/package.json +24 -0
package/LICENSE ADDED
@@ -0,0 +1,203 @@
1
+ Copyright 2016-2023 ClickHouse, Inc.
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may choose to offer,
169
+ and charge a fee for, acceptance of support, warranty, indemnity,
170
+ or other liability obligations and/or rights consistent with this
171
+ License. However, in accepting such obligations, You may act only
172
+ on Your own behalf and on Your sole responsibility, not on behalf
173
+ of any other Contributor, and only if You agree to indemnify,
174
+ defend, and hold each Contributor harmless for any liability
175
+ incurred by, or claims asserted against, such Contributor by reason
176
+ of your accepting any such warranty or additional liability.
177
+
178
+ END OF TERMS AND CONDITIONS
179
+
180
+ APPENDIX: How to apply the Apache License to your work.
181
+
182
+ To apply the Apache License to your work, attach the following
183
+ boilerplate notice, with the fields enclosed by brackets "[]"
184
+ replaced with your own identifying information. (Don't include
185
+ the brackets!) The text should be enclosed in the appropriate
186
+ comment syntax for the file format. We also recommend that a
187
+ file or class name and description of purpose be included on the
188
+ same "printed page" as the copyright notice for easier
189
+ identification within third-party archives.
190
+
191
+ Copyright 2016-2023 ClickHouse, Inc.
192
+
193
+ Licensed under the Apache License, Version 2.0 (the "License");
194
+ you may not use this file except in compliance with the License.
195
+ You may obtain a copy of the License at
196
+
197
+ http://www.apache.org/licenses/LICENSE-2.0
198
+
199
+ Unless required by applicable law or agreed to in writing, software
200
+ distributed under the License is distributed on an "AS IS" BASIS,
201
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
+ See the License for the specific language governing permissions and
203
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,35 @@
1
+ <p align="center">
2
+ <img src=".static/logo.png" width="200px" align="center">
3
+ <h1 align="center">ClickHouse JS client</h1>
4
+ </p>
5
+ <br/>
6
+ <p align="center">
7
+ <a href="https://github.com/ClickHouse/clickhouse-js/actions/workflows/tests.yml">
8
+ <img src="https://github.com/ClickHouse/clickhouse-js/actions/workflows/tests.yml/badge.svg?branch=main">
9
+ </a>
10
+ </p>
11
+
12
+ ## About
13
+
14
+ Official JS client for [ClickHouse](https://clickhouse.com/), written purely in TypeScript,
15
+ thoroughly tested with actual ClickHouse versions.
16
+
17
+ The repository consists of three packages:
18
+
19
+ - `@clickhouse/client` - Node.js client, built on top of [HTTP](https://nodejs.org/api/http.html)
20
+ and [Stream](https://nodejs.org/api/stream.html) APIs; supports streaming for both selects and inserts.
21
+ - `@clickhouse/client-browser` - browser client, built on top of [Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)
22
+ and [Web Streams](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) APIs; supports streaming for selects.
23
+ - `@clickhouse/common` - shared common types and the base framework for building a custom client implementation.
24
+
25
+ ## Documentation
26
+
27
+ See the [ClickHouse website](https://clickhouse.com/docs/en/integrations/language-clients/nodejs) for the full documentation entry.
28
+
29
+ ## Usage examples
30
+
31
+ You can find code samples in the [examples](./examples) folder (with [README](./examples/README.md)).
32
+
33
+ ## Contributing
34
+
35
+ Check out our [contributing guide](./CONTRIBUTING.md).
@@ -0,0 +1,24 @@
1
+ export interface ResponseJSON<T = unknown> {
2
+ data: Array<T>;
3
+ query_id?: string;
4
+ totals?: Record<string, number>;
5
+ extremes?: Record<string, any>;
6
+ meta?: Array<{
7
+ name: string;
8
+ type: string;
9
+ }>;
10
+ statistics?: {
11
+ elapsed: number;
12
+ rows_read: number;
13
+ bytes_read: number;
14
+ };
15
+ rows?: number;
16
+ }
17
+ export interface InputJSON<T = unknown> {
18
+ meta: {
19
+ name: string;
20
+ type: string;
21
+ }[];
22
+ data: T[];
23
+ }
24
+ export type InputJSONObjectEachRow<T = unknown> = Record<string, T>;
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=clickhouse_types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clickhouse_types.js","sourceRoot":"","sources":["../../../packages/client-common/src/clickhouse_types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,149 @@
1
+ import type { ClickHouseLogLevel, ClickHouseSettings, Connection, ConnectionParams, ConnInsertResult, ConnQueryResult, Logger } from '@clickhouse/client-common';
2
+ import { type DataFormat } from '@clickhouse/client-common';
3
+ import type { InputJSON, InputJSONObjectEachRow } from './clickhouse_types';
4
+ import type { BaseResultSet } from './result';
5
+ export type MakeConnection<Stream> = (params: ConnectionParams) => Connection<Stream>;
6
+ export type MakeResultSet<Stream> = (stream: Stream, format: DataFormat, session_id: string) => BaseResultSet<Stream>;
7
+ export interface ValuesEncoder<Stream> {
8
+ validateInsertValues<T = unknown>(values: InsertValues<Stream, T>, format: DataFormat): void;
9
+ /**
10
+ * A function encodes an array or a stream of JSON objects to a format compatible with ClickHouse.
11
+ * If values are provided as an array of JSON objects, the function encodes it in place.
12
+ * If values are provided as a stream of JSON objects, the function sets up the encoding of each chunk.
13
+ * If values are provided as a raw non-object stream, the function does nothing.
14
+ *
15
+ * @param values a set of values to send to ClickHouse.
16
+ * @param format a format to encode value to.
17
+ */
18
+ encodeValues<T = unknown>(values: InsertValues<Stream, T>, format: DataFormat): string | Stream;
19
+ }
20
+ export type CloseStream<Stream> = (stream: Stream) => Promise<void>;
21
+ export interface ClickHouseClientConfigOptions<Stream> {
22
+ impl: {
23
+ make_connection: MakeConnection<Stream>;
24
+ make_result_set: MakeResultSet<Stream>;
25
+ values_encoder: ValuesEncoder<Stream>;
26
+ close_stream: CloseStream<Stream>;
27
+ };
28
+ /** A ClickHouse instance URL. Default value: `http://localhost:8123`. */
29
+ host?: string;
30
+ /** The request timeout in milliseconds. Default value: `30_000`. */
31
+ request_timeout?: number;
32
+ /** Maximum number of sockets to allow per host. Default value: `Infinity`. */
33
+ max_open_connections?: number;
34
+ compression?: {
35
+ /** `response: true` instructs ClickHouse server to respond with
36
+ * compressed response body. Default: true. */
37
+ response?: boolean;
38
+ /** `request: true` enabled compression on the client request body.
39
+ * Default: false. */
40
+ request?: boolean;
41
+ };
42
+ /** The name of the user on whose behalf requests are made.
43
+ * Default: 'default'. */
44
+ username?: string;
45
+ /** The user password. Default: ''. */
46
+ password?: string;
47
+ /** The name of the application using the nodejs client.
48
+ * Default: empty. */
49
+ application?: string;
50
+ /** Database name to use. Default value: `default`. */
51
+ database?: string;
52
+ /** ClickHouse settings to apply to all requests. Default value: {} */
53
+ clickhouse_settings?: ClickHouseSettings;
54
+ log?: {
55
+ /** A class to instantiate a custom logger implementation.
56
+ * Default: {@link DefaultLogger} */
57
+ LoggerClass?: new () => Logger;
58
+ /** Default: OFF */
59
+ level?: ClickHouseLogLevel;
60
+ };
61
+ session_id?: string;
62
+ }
63
+ export type BaseClickHouseClientConfigOptions<Stream> = Omit<ClickHouseClientConfigOptions<Stream>, 'impl'>;
64
+ export interface BaseQueryParams {
65
+ /** ClickHouse's settings that can be applied on query level. */
66
+ clickhouse_settings?: ClickHouseSettings;
67
+ /** Parameters for query binding. https://clickhouse.com/docs/en/interfaces/http/#cli-queries-with-parameters */
68
+ query_params?: Record<string, unknown>;
69
+ /** AbortSignal instance to cancel a request in progress. */
70
+ abort_signal?: AbortSignal;
71
+ /** A specific `query_id` that will be sent with this request.
72
+ * If it is not set, a random identifier will be generated automatically by the client. */
73
+ query_id?: string;
74
+ session_id?: string;
75
+ }
76
+ export interface QueryParams extends BaseQueryParams {
77
+ /** Statement to execute. */
78
+ query: string;
79
+ /** Format of the resulting dataset. */
80
+ format?: DataFormat;
81
+ }
82
+ export interface ExecParams extends BaseQueryParams {
83
+ /** Statement to execute. */
84
+ query: string;
85
+ }
86
+ export type CommandParams = ExecParams;
87
+ export interface CommandResult {
88
+ query_id: string;
89
+ }
90
+ export type InsertResult = ConnInsertResult;
91
+ export type ExecResult<Stream> = ConnQueryResult<Stream>;
92
+ export type InsertValues<Stream, T = unknown> = ReadonlyArray<T> | Stream | InputJSON<T> | InputJSONObjectEachRow<T>;
93
+ export interface InsertParams<Stream = unknown, T = unknown> extends BaseQueryParams {
94
+ /** Name of a table to insert into. */
95
+ table: string;
96
+ /** A dataset to insert. */
97
+ values: InsertValues<Stream, T>;
98
+ /** Format of the dataset to insert. */
99
+ format?: DataFormat;
100
+ }
101
+ export declare class ClickHouseClient<Stream = unknown> {
102
+ private readonly connectionParams;
103
+ private readonly connection;
104
+ private readonly makeResultSet;
105
+ private readonly valuesEncoder;
106
+ private readonly closeStream;
107
+ private readonly sessionId?;
108
+ constructor(config: ClickHouseClientConfigOptions<Stream>);
109
+ private getQueryParams;
110
+ /**
111
+ * Used for most statements that can have a response, such as SELECT.
112
+ * FORMAT clause should be specified separately via {@link QueryParams.format} (default is JSON)
113
+ * Consider using {@link ClickHouseClient.insert} for data insertion,
114
+ * or {@link ClickHouseClient.command} for DDLs.
115
+ */
116
+ query(params: QueryParams): Promise<BaseResultSet<Stream>>;
117
+ /**
118
+ * It should be used for statements that do not have any output,
119
+ * when the format clause is not applicable, or when you are not interested in the response at all.
120
+ * Response stream is destroyed immediately as we do not expect useful information there.
121
+ * Examples of such statements are DDLs or custom inserts.
122
+ * If you are interested in the response data, consider using {@link ClickHouseClient.exec}
123
+ */
124
+ command(params: CommandParams): Promise<CommandResult>;
125
+ /**
126
+ * Similar to {@link ClickHouseClient.command}, but for the cases where the output is expected,
127
+ * but format clause is not applicable. The caller of this method is expected to consume the stream,
128
+ * otherwise, the request will eventually be timed out.
129
+ */
130
+ exec(params: ExecParams): Promise<ExecResult<Stream>>;
131
+ /**
132
+ * The primary method for data insertion. It is recommended to avoid arrays in case of large inserts
133
+ * to reduce application memory consumption and consider streaming for most of such use cases.
134
+ * As the insert operation does not provide any output, the response stream is immediately destroyed.
135
+ * In case of a custom insert operation, such as, for example, INSERT FROM SELECT,
136
+ * consider using {@link ClickHouseClient.command}, passing the entire raw query there (including FORMAT clause).
137
+ */
138
+ insert<T>(params: InsertParams<Stream, T>): Promise<InsertResult>;
139
+ /**
140
+ * Health-check request. Can throw an error if the connection is refused.
141
+ */
142
+ ping(): Promise<boolean>;
143
+ /**
144
+ * Shuts down the underlying connection.
145
+ * This method should ideally be called only once per application lifecycle,
146
+ * for example, during the graceful shutdown phase.
147
+ */
148
+ close(): Promise<void>;
149
+ }
package/dist/client.js ADDED
@@ -0,0 +1,187 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ClickHouseClient = void 0;
4
+ const client_common_1 = require("@clickhouse/client-common");
5
+ function validateConnectionParams({ url }) {
6
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
7
+ throw new Error(`Only http(s) protocol is supported, but given: [${url.protocol}]`);
8
+ }
9
+ }
10
+ function createUrl(host) {
11
+ try {
12
+ return new URL(host);
13
+ }
14
+ catch (err) {
15
+ throw new Error('Configuration parameter "host" contains malformed url.');
16
+ }
17
+ }
18
+ function getConnectionParams(config) {
19
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
20
+ return {
21
+ application_id: config.application,
22
+ url: createUrl((_a = config.host) !== null && _a !== void 0 ? _a : 'http://localhost:8123'),
23
+ request_timeout: (_b = config.request_timeout) !== null && _b !== void 0 ? _b : 300000,
24
+ max_open_connections: (_c = config.max_open_connections) !== null && _c !== void 0 ? _c : Infinity,
25
+ compression: {
26
+ decompress_response: (_e = (_d = config.compression) === null || _d === void 0 ? void 0 : _d.response) !== null && _e !== void 0 ? _e : true,
27
+ compress_request: (_g = (_f = config.compression) === null || _f === void 0 ? void 0 : _f.request) !== null && _g !== void 0 ? _g : false,
28
+ },
29
+ username: (_h = config.username) !== null && _h !== void 0 ? _h : 'default',
30
+ password: (_j = config.password) !== null && _j !== void 0 ? _j : '',
31
+ database: (_k = config.database) !== null && _k !== void 0 ? _k : 'default',
32
+ clickhouse_settings: (_l = config.clickhouse_settings) !== null && _l !== void 0 ? _l : {},
33
+ logWriter: new client_common_1.LogWriter(((_m = config === null || config === void 0 ? void 0 : config.log) === null || _m === void 0 ? void 0 : _m.LoggerClass)
34
+ ? new config.log.LoggerClass()
35
+ : new client_common_1.DefaultLogger(), (_o = config.log) === null || _o === void 0 ? void 0 : _o.level),
36
+ };
37
+ }
38
+ class ClickHouseClient {
39
+ constructor(config) {
40
+ Object.defineProperty(this, "connectionParams", {
41
+ enumerable: true,
42
+ configurable: true,
43
+ writable: true,
44
+ value: void 0
45
+ });
46
+ Object.defineProperty(this, "connection", {
47
+ enumerable: true,
48
+ configurable: true,
49
+ writable: true,
50
+ value: void 0
51
+ });
52
+ Object.defineProperty(this, "makeResultSet", {
53
+ enumerable: true,
54
+ configurable: true,
55
+ writable: true,
56
+ value: void 0
57
+ });
58
+ Object.defineProperty(this, "valuesEncoder", {
59
+ enumerable: true,
60
+ configurable: true,
61
+ writable: true,
62
+ value: void 0
63
+ });
64
+ Object.defineProperty(this, "closeStream", {
65
+ enumerable: true,
66
+ configurable: true,
67
+ writable: true,
68
+ value: void 0
69
+ });
70
+ Object.defineProperty(this, "sessionId", {
71
+ enumerable: true,
72
+ configurable: true,
73
+ writable: true,
74
+ value: void 0
75
+ });
76
+ this.connectionParams = getConnectionParams(config);
77
+ this.sessionId = config.session_id;
78
+ validateConnectionParams(this.connectionParams);
79
+ this.connection = config.impl.make_connection(this.connectionParams);
80
+ this.makeResultSet = config.impl.make_result_set;
81
+ this.valuesEncoder = config.impl.values_encoder;
82
+ this.closeStream = config.impl.close_stream;
83
+ }
84
+ getQueryParams(params) {
85
+ return {
86
+ clickhouse_settings: {
87
+ ...this.connectionParams.clickhouse_settings,
88
+ ...params.clickhouse_settings,
89
+ },
90
+ query_params: params.query_params,
91
+ abort_signal: params.abort_signal,
92
+ query_id: params.query_id,
93
+ session_id: this.sessionId,
94
+ };
95
+ }
96
+ /**
97
+ * Used for most statements that can have a response, such as SELECT.
98
+ * FORMAT clause should be specified separately via {@link QueryParams.format} (default is JSON)
99
+ * Consider using {@link ClickHouseClient.insert} for data insertion,
100
+ * or {@link ClickHouseClient.command} for DDLs.
101
+ */
102
+ async query(params) {
103
+ var _a;
104
+ const format = (_a = params.format) !== null && _a !== void 0 ? _a : 'JSON';
105
+ const query = formatQuery(params.query, format);
106
+ const { stream, query_id } = await this.connection.query({
107
+ query,
108
+ ...this.getQueryParams(params),
109
+ });
110
+ return this.makeResultSet(stream, format, query_id);
111
+ }
112
+ /**
113
+ * It should be used for statements that do not have any output,
114
+ * when the format clause is not applicable, or when you are not interested in the response at all.
115
+ * Response stream is destroyed immediately as we do not expect useful information there.
116
+ * Examples of such statements are DDLs or custom inserts.
117
+ * If you are interested in the response data, consider using {@link ClickHouseClient.exec}
118
+ */
119
+ async command(params) {
120
+ const { stream, query_id } = await this.exec(params);
121
+ await this.closeStream(stream);
122
+ return { query_id };
123
+ }
124
+ /**
125
+ * Similar to {@link ClickHouseClient.command}, but for the cases where the output is expected,
126
+ * but format clause is not applicable. The caller of this method is expected to consume the stream,
127
+ * otherwise, the request will eventually be timed out.
128
+ */
129
+ async exec(params) {
130
+ const query = removeTrailingSemi(params.query.trim());
131
+ return await this.connection.exec({
132
+ query,
133
+ ...this.getQueryParams(params),
134
+ });
135
+ }
136
+ /**
137
+ * The primary method for data insertion. It is recommended to avoid arrays in case of large inserts
138
+ * to reduce application memory consumption and consider streaming for most of such use cases.
139
+ * As the insert operation does not provide any output, the response stream is immediately destroyed.
140
+ * In case of a custom insert operation, such as, for example, INSERT FROM SELECT,
141
+ * consider using {@link ClickHouseClient.command}, passing the entire raw query there (including FORMAT clause).
142
+ */
143
+ async insert(params) {
144
+ const format = params.format || 'JSONCompactEachRow';
145
+ this.valuesEncoder.validateInsertValues(params.values, format);
146
+ const query = `INSERT INTO ${params.table.trim()} FORMAT ${format}`;
147
+ return await this.connection.insert({
148
+ query,
149
+ values: this.valuesEncoder.encodeValues(params.values, format),
150
+ ...this.getQueryParams(params),
151
+ });
152
+ }
153
+ /**
154
+ * Health-check request. Can throw an error if the connection is refused.
155
+ */
156
+ async ping() {
157
+ return await this.connection.ping();
158
+ }
159
+ /**
160
+ * Shuts down the underlying connection.
161
+ * This method should ideally be called only once per application lifecycle,
162
+ * for example, during the graceful shutdown phase.
163
+ */
164
+ async close() {
165
+ return await this.connection.close();
166
+ }
167
+ }
168
+ exports.ClickHouseClient = ClickHouseClient;
169
+ function formatQuery(query, format) {
170
+ query = query.trim();
171
+ query = removeTrailingSemi(query);
172
+ return query + ' \nFORMAT ' + format;
173
+ }
174
+ function removeTrailingSemi(query) {
175
+ let lastNonSemiIdx = query.length;
176
+ for (let i = lastNonSemiIdx; i > 0; i--) {
177
+ if (query[i - 1] !== ';') {
178
+ lastNonSemiIdx = i;
179
+ break;
180
+ }
181
+ }
182
+ if (lastNonSemiIdx !== query.length) {
183
+ return query.slice(0, lastNonSemiIdx);
184
+ }
185
+ return query;
186
+ }
187
+ //# sourceMappingURL=client.js.map
@@ -0,0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AE,WAAW,MAAM,EAAE,CAAA;QAEnE,OAAO,MAAM,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC;YAClC,KAAK;YACL,MAAM,EAAE,IAAI,CAAC,aAAa,CAAC,YAAY,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;YAC9D,GAAG,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC;SAC/B,CAAC,CAAA;IACJ,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,IAAI;QACR,OAAO,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,CAAA;IACrC,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,KAAK;QACT,OAAO,MAAM,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAA;IACtC,CAAC;CACF;AA5GD,4CA4GC;AAED,SAAS,WAAW,CAAC,KAAa,EAAE,MAAkB;IACpD,KAAK,GAAG,KAAK,CAAC,IAAI,EAAE,CAAA;IACpB,KAAK,GAAG,kBAAkB,CAAC,KAAK,CAAC,CAAA;IACjC,OAAO,KAAK,GAAG,YAAY,GAAG,MAAM,CAAA;AACtC,CAAC;AAED,SAAS,kBAAkB,CAAC,KAAa;IACvC,IAAI,cAAc,GAAG,KAAK,CAAC,MAAM,CAAA;IACjC,KAAK,IAAI,CAAC,GAAG,cAAc,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;QACvC,IAAI,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,GAAG,EAAE;YACxB,cAAc,GAAG,CAAC,CAAA;YAClB,MAAK;SACN;KACF;IACD,IAAI,cAAc,KAAK,KAAK,CAAC,MAAM,EAAE;QACnC,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,cAAc,CAAC,CAAA;KACtC;IACD,OAAO,KAAK,CAAA;AACd,CAAC"}
@@ -0,0 +1,44 @@
1
+ import type { LogWriter } from './logger';
2
+ import type { ClickHouseSettings } from './settings';
3
+ export interface ConnectionParams {
4
+ url: URL;
5
+ request_timeout: number;
6
+ max_open_connections: number;
7
+ compression: {
8
+ decompress_response: boolean;
9
+ compress_request: boolean;
10
+ };
11
+ username: string;
12
+ password: string;
13
+ database: string;
14
+ clickhouse_settings: ClickHouseSettings;
15
+ logWriter: LogWriter;
16
+ application_id?: string;
17
+ }
18
+ export interface ConnBaseQueryParams {
19
+ query: string;
20
+ clickhouse_settings?: ClickHouseSettings;
21
+ query_params?: Record<string, unknown>;
22
+ abort_signal?: AbortSignal;
23
+ session_id?: string;
24
+ query_id?: string;
25
+ }
26
+ export interface ConnInsertParams<Stream> extends ConnBaseQueryParams {
27
+ values: string | Stream;
28
+ }
29
+ export interface ConnBaseResult {
30
+ query_id: string;
31
+ }
32
+ export interface ConnQueryResult<Stream> extends ConnBaseResult {
33
+ stream: Stream;
34
+ query_id: string;
35
+ }
36
+ export type ConnInsertResult = ConnBaseResult;
37
+ export type ConnExecResult<Stream> = ConnQueryResult<Stream>;
38
+ export interface Connection<Stream> {
39
+ ping(): Promise<boolean>;
40
+ close(): Promise<void>;
41
+ query(params: ConnBaseQueryParams): Promise<ConnQueryResult<Stream>>;
42
+ exec(params: ConnBaseQueryParams): Promise<ConnExecResult<Stream>>;
43
+ insert(params: ConnInsertParams<Stream>): Promise<ConnInsertResult>;
44
+ }
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=connection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connection.js","sourceRoot":"","sources":["../../../packages/client-common/src/connection.ts"],"names":[],"mappings":""}