@openplait/adapter-clickhouse 0.1.0-alpha.0

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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,101 @@
1
+ # `@openplait/adapter-clickhouse`
2
+
3
+ The first OpenPlait datasource adapter. It compiles portable semantic queries
4
+ to parameterized ClickHouse SQL and normalizes ClickHouse responses into
5
+ `@openplait/core` dataframes.
6
+
7
+ The default mappings cover the standard OpenTelemetry ClickHouse tables:
8
+
9
+ | Logical dataset | Physical table |
10
+ | --- | --- |
11
+ | `otel.spans` | `otel_traces` |
12
+ | `otel.logs` | `otel_logs` |
13
+ | `otel.metrics.gauge` | `otel_metrics_gauge` |
14
+ | `otel.metrics.sum` | `otel_metrics_sum` |
15
+ | `otel.metrics.histogram` | `otel_metrics_histogram` |
16
+
17
+ Application-specific mappings are supplied through `config.datasets`. The
18
+ package exports `OPENLIT_CLICKHOUSE_DATASETS` as an optional preset for OpenLIT;
19
+ it is not part of the adapter's defaults.
20
+
21
+ ## Usage
22
+
23
+ ```ts
24
+ import {
25
+ ClickHouseAdapter,
26
+ } from "@openplait/adapter-clickhouse";
27
+
28
+ const adapter = new ClickHouseAdapter({
29
+ url: "https://clickhouse.example.com:8443",
30
+ username: process.env.CLICKHOUSE_USER,
31
+ password: process.env.CLICKHOUSE_PASSWORD,
32
+ database: "observability",
33
+ httpHeaders: { "X-ClickHouse-Quota": "openlit" },
34
+ maxResultRows: 10_000,
35
+ maxRowsToRead: 10_000_000,
36
+ maxTimeRangeMs: 31 * 24 * 60 * 60 * 1_000,
37
+ queryTimeoutMs: 30_000,
38
+ });
39
+
40
+ const compiled = await adapter.compile(query, {
41
+ variables: {
42
+ __from: "2026-08-05T00:00:00.000Z",
43
+ __to: "2026-08-05T01:00:00.000Z",
44
+ },
45
+ });
46
+
47
+ const result = await adapter.execute(compiled, {
48
+ audit: { requestId: "dashboard-request-123", actorId: "user-42" },
49
+ });
50
+
51
+ await adapter.close();
52
+ ```
53
+
54
+ OpenLIT can opt into its additional logical datasets without changing the
55
+ generic adapter contract:
56
+
57
+ ```ts
58
+ import {
59
+ ClickHouseAdapter,
60
+ OPENLIT_CLICKHOUSE_DATASETS,
61
+ } from "@openplait/adapter-clickhouse";
62
+
63
+ const adapter = new ClickHouseAdapter({
64
+ url: clickhouseUrl,
65
+ datasets: [...OPENLIT_CLICKHOUSE_DATASETS],
66
+ });
67
+ ```
68
+
69
+ Do not put credentials in dashboard resources. Resolve them on the server and
70
+ construct each named adapter instance behind the consuming application's
71
+ server-side datasource registry.
72
+
73
+ ## Safety defaults
74
+
75
+ - Canonical fields resolve only through the selected dataset's allowlist.
76
+ - Tables are selected only through registered logical datasets.
77
+ - Values use ClickHouse query parameters and are never interpolated into SQL.
78
+ - A time range is required by default and capped at 31 days.
79
+ - Results, rows read, and execution time are capped at both SQL and server
80
+ setting boundaries.
81
+ - Queries execute with ClickHouse `readonly=1`.
82
+ - Tenant predicates are adapter-owned and cannot be removed by a query.
83
+ - Compiled queries must originate from the executing adapter instance.
84
+ - Execution requires a safe audit request ID.
85
+ - Native SQL is disabled unless `allowNativeQueries: true` is set by the server
86
+ administrator. When enabled, it remains single-statement and read-only, and
87
+ every declared parameter must be referenced through ClickHouse bindings.
88
+
89
+ Native mode intentionally bypasses semantic field and table allowlists. Treat
90
+ it as a privileged server-side feature, never as an end-user SQL console.
91
+
92
+ ## Supported semantic operations
93
+
94
+ Select, recursive filters, aggregation, grouping, time buckets, ordering,
95
+ limits, percentiles, distinct count, rate, histogram, and arithmetic are
96
+ supported. Semantic joins are reported as unsupported because the current core
97
+ join expression cannot identify the left and right operands unambiguously.
98
+
99
+ `discoverSchema()` returns the canonical fields and types for all registered
100
+ datasets. `explain()` returns the generated SQL, bound parameters, output field
101
+ contract, and compilation steps without contacting ClickHouse.
@@ -0,0 +1,23 @@
1
+ import type { NativeQuery, QueryResult, SemanticQuery, SemanticSchema } from "@openplait/core";
2
+ import { type AdapterManifest, type AdapterValidationResult, type CompileContext, type CompiledQuery, type DatasourceAdapter, type DatasourceCapabilities, type DiscoveryContext, type ExecutionContext, type QueryExplanation } from "@openplait/adapter-sdk";
3
+ import type { ClickHouseAdapterConfig, ClickHouseAdapterOptions, ClickHouseCompiledStatement } from "./types.js";
4
+ export declare const CLICKHOUSE_ADAPTER_MANIFEST: AdapterManifest;
5
+ export declare const CLICKHOUSE_CAPABILITIES: DatasourceCapabilities;
6
+ export declare function validateClickHouseConfig(config: ClickHouseAdapterConfig): AdapterValidationResult<ClickHouseAdapterConfig>;
7
+ export declare class ClickHouseAdapter implements DatasourceAdapter<ClickHouseAdapterConfig, ClickHouseCompiledStatement> {
8
+ readonly manifest: AdapterManifest;
9
+ private readonly config;
10
+ private readonly client;
11
+ private readonly ownsClient;
12
+ private readonly now;
13
+ private readonly compiledQueries;
14
+ constructor(config: ClickHouseAdapterConfig, options?: ClickHouseAdapterOptions);
15
+ validateConfig(config: ClickHouseAdapterConfig): AdapterValidationResult<ClickHouseAdapterConfig>;
16
+ getCapabilities(config: ClickHouseAdapterConfig): Promise<DatasourceCapabilities>;
17
+ compile(query: SemanticQuery, context: CompileContext): Promise<CompiledQuery<ClickHouseCompiledStatement>>;
18
+ execute(query: CompiledQuery<ClickHouseCompiledStatement> | NativeQuery, context: ExecutionContext): Promise<QueryResult>;
19
+ explain(query: SemanticQuery, context: CompileContext): Promise<QueryExplanation<ClickHouseCompiledStatement>>;
20
+ discoverSchema(_context: DiscoveryContext): Promise<SemanticSchema>;
21
+ close(): Promise<void>;
22
+ }
23
+ //# sourceMappingURL=adapter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../../src/adapter.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EACV,WAAW,EACX,WAAW,EACX,aAAa,EACb,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AW,EAC/D,OAAO,EAAE,gBAAgB,GACxB,OAAO,CAAC,WAAW,CAAC;IAkFjB,OAAO,CACX,KAAK,EAAE,aAAa,EACpB,OAAO,EAAE,cAAc,GACtB,OAAO,CAAC,gBAAgB,CAAC,2BAA2B,CAAC,CAAC;IAoBnD,cAAc,CAAC,QAAQ,EAAE,gBAAgB,GAAG,OAAO,CAAC,cAAc,CAAC;IAInE,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAG7B"}
@@ -0,0 +1,319 @@
1
+ import { createClient, } from "@clickhouse/client";
2
+ import { AdapterError, isAbortError, isCompiledQuery, } from "@openplait/adapter-sdk";
3
+ import { compileClickHouseQuery } from "./compiler.js";
4
+ import { createDatasetRegistry, datasetsToSemanticSchema } from "./datasets.js";
5
+ import { compileNativeQuery } from "./native.js";
6
+ import { normalizeClickHouseResponse, } from "./normalization.js";
7
+ const ADAPTER_VERSION = "0.1.0-alpha.0";
8
+ const DEFAULT_QUERY_TIMEOUT_MS = 30_000;
9
+ const DEFAULT_MAX_RESULT_ROWS = 10_000;
10
+ const DEFAULT_MAX_ROWS_TO_READ = 10_000_000;
11
+ const SAFE_QUERY_ID = /^[A-Za-z0-9_.:-]{1,128}$/;
12
+ const SAFE_DATASET_NAME = /^[a-z][a-z0-9]*(?:\.[a-z0-9_]+)+$/;
13
+ const SAFE_TABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)?$/;
14
+ const UNSAFE_MAPPING_EXPRESSION = /;|--|\/\*|\*\/|\0/;
15
+ export const CLICKHOUSE_ADAPTER_MANIFEST = {
16
+ name: "clickhouse",
17
+ displayName: "ClickHouse",
18
+ version: ADAPTER_VERSION,
19
+ queryLanguages: ["openplait-semantic", "sql"],
20
+ signals: ["traces", "logs", "metrics", "tabular"],
21
+ };
22
+ export const CLICKHOUSE_CAPABILITIES = {
23
+ signals: ["traces", "logs", "metrics", "tabular"],
24
+ operations: [
25
+ "select",
26
+ "filter",
27
+ "aggregate",
28
+ "group",
29
+ "order",
30
+ "limit",
31
+ "timeBucket",
32
+ "rate",
33
+ "percentile",
34
+ "distinctCount",
35
+ "histogram",
36
+ "arithmetic",
37
+ ],
38
+ joins: { local: false, crossDatasource: false },
39
+ nativeQueryLanguages: ["sql"],
40
+ explain: true,
41
+ schemaDiscovery: true,
42
+ };
43
+ function positiveIntegerIssue(value, path) {
44
+ if (value === undefined || (Number.isInteger(value) && value > 0))
45
+ return undefined;
46
+ return { code: "CONFIG_INVALID", path, message: "Value must be a positive integer." };
47
+ }
48
+ function validateDataset(dataset, index) {
49
+ const path = `/datasets/${index}`;
50
+ const issues = [];
51
+ if (!SAFE_DATASET_NAME.test(dataset.name)) {
52
+ issues.push({
53
+ code: "CONFIG_INVALID",
54
+ path: `${path}/name`,
55
+ message: "Dataset names must be dot-separated lowercase identifiers.",
56
+ });
57
+ }
58
+ if (!SAFE_TABLE_NAME.test(dataset.table)) {
59
+ issues.push({
60
+ code: "CONFIG_INVALID",
61
+ path: `${path}/table`,
62
+ message: "Dataset table must be an allowlisted ClickHouse identifier.",
63
+ });
64
+ }
65
+ if (!(dataset.timeField in dataset.fields)) {
66
+ issues.push({
67
+ code: "CONFIG_INVALID",
68
+ path: `${path}/timeField`,
69
+ message: "Dataset timeField must reference one of its fields.",
70
+ });
71
+ }
72
+ if (dataset.arrayJoin && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(dataset.arrayJoin)) {
73
+ issues.push({
74
+ code: "CONFIG_INVALID",
75
+ path: `${path}/arrayJoin`,
76
+ message: "Dataset arrayJoin must be a single ClickHouse identifier.",
77
+ });
78
+ }
79
+ for (const [field, mapping] of Object.entries(dataset.fields)) {
80
+ if (!field || !mapping.expression || UNSAFE_MAPPING_EXPRESSION.test(mapping.expression)) {
81
+ issues.push({
82
+ code: "CONFIG_INVALID",
83
+ path: `${path}/fields/${field}/expression`,
84
+ message: "Field mapping expressions cannot be empty or contain statement/comment delimiters.",
85
+ });
86
+ }
87
+ }
88
+ return issues;
89
+ }
90
+ export function validateClickHouseConfig(config) {
91
+ const errors = [];
92
+ try {
93
+ const url = new URL(config.url);
94
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
95
+ errors.push({
96
+ code: "CONFIG_INVALID",
97
+ path: "/url",
98
+ message: "ClickHouse URL must use http or https.",
99
+ });
100
+ }
101
+ }
102
+ catch {
103
+ errors.push({
104
+ code: "CONFIG_INVALID",
105
+ path: "/url",
106
+ message: "ClickHouse URL is invalid.",
107
+ });
108
+ }
109
+ for (const issue of [
110
+ positiveIntegerIssue(config.requestTimeoutMs, "/requestTimeoutMs"),
111
+ positiveIntegerIssue(config.queryTimeoutMs, "/queryTimeoutMs"),
112
+ positiveIntegerIssue(config.maxResultRows, "/maxResultRows"),
113
+ positiveIntegerIssue(config.maxRowsToRead, "/maxRowsToRead"),
114
+ positiveIntegerIssue(config.maxTimeRangeMs, "/maxTimeRangeMs"),
115
+ ]) {
116
+ if (issue)
117
+ errors.push(issue);
118
+ }
119
+ for (const [index, dataset] of (config.datasets ?? []).entries()) {
120
+ errors.push(...validateDataset(dataset, index));
121
+ }
122
+ return errors.length ? { valid: false, errors } : { valid: true, value: config, errors: [] };
123
+ }
124
+ function abortScope(external, timeoutMs) {
125
+ const controller = new AbortController();
126
+ let didTimeOut = false;
127
+ const onAbort = () => controller.abort(external?.reason);
128
+ if (external?.aborted)
129
+ onAbort();
130
+ else
131
+ external?.addEventListener("abort", onAbort, { once: true });
132
+ const timeout = setTimeout(() => {
133
+ didTimeOut = true;
134
+ controller.abort(new DOMException("Query timed out.", "TimeoutError"));
135
+ }, timeoutMs);
136
+ return {
137
+ signal: controller.signal,
138
+ timedOut: () => didTimeOut,
139
+ dispose: () => {
140
+ clearTimeout(timeout);
141
+ external?.removeEventListener("abort", onAbort);
142
+ },
143
+ };
144
+ }
145
+ function queryId(context) {
146
+ const id = context.queryId ?? context.audit?.requestId;
147
+ if (!id || !SAFE_QUERY_ID.test(id)) {
148
+ throw new AdapterError("QUERY_VALIDATION_FAILED", "Execution requires a safe audit request ID or query ID.", { path: "/execution/audit/requestId" });
149
+ }
150
+ return id;
151
+ }
152
+ function deepFreeze(value) {
153
+ if (typeof value !== "object" || value === null || Object.isFrozen(value)) {
154
+ return value;
155
+ }
156
+ for (const child of Object.values(value))
157
+ deepFreeze(child);
158
+ return Object.freeze(value);
159
+ }
160
+ export class ClickHouseAdapter {
161
+ manifest = CLICKHOUSE_ADAPTER_MANIFEST;
162
+ config;
163
+ client;
164
+ ownsClient;
165
+ now;
166
+ compiledQueries = new WeakSet();
167
+ constructor(config, options = {}) {
168
+ const validation = validateClickHouseConfig(config);
169
+ if (!validation.valid) {
170
+ throw new AdapterError("CONFIG_INVALID", "ClickHouse adapter config is invalid.", {
171
+ details: { errors: validation.errors },
172
+ });
173
+ }
174
+ this.config = structuredClone(config);
175
+ this.client =
176
+ options.client ??
177
+ createClient({
178
+ url: this.config.url,
179
+ ...(this.config.username === undefined
180
+ ? {}
181
+ : { username: this.config.username }),
182
+ ...(this.config.password === undefined
183
+ ? {}
184
+ : { password: this.config.password }),
185
+ ...(this.config.database === undefined
186
+ ? {}
187
+ : { database: this.config.database }),
188
+ ...(this.config.httpHeaders === undefined
189
+ ? {}
190
+ : { http_headers: this.config.httpHeaders }),
191
+ application: this.config.applicationName ?? "openplait",
192
+ request_timeout: this.config.requestTimeoutMs ?? DEFAULT_QUERY_TIMEOUT_MS,
193
+ use_multipart_params_auto: true,
194
+ });
195
+ this.ownsClient = options.client === undefined;
196
+ this.now = options.now ?? Date.now;
197
+ }
198
+ validateConfig(config) {
199
+ return validateClickHouseConfig(config);
200
+ }
201
+ async getCapabilities(config) {
202
+ const validation = validateClickHouseConfig(config);
203
+ if (!validation.valid) {
204
+ throw new AdapterError("CONFIG_INVALID", "ClickHouse adapter config is invalid.", {
205
+ details: { errors: validation.errors },
206
+ });
207
+ }
208
+ return {
209
+ ...CLICKHOUSE_CAPABILITIES,
210
+ nativeQueryLanguages: config.allowNativeQueries ? ["sql"] : [],
211
+ };
212
+ }
213
+ async compile(query, context) {
214
+ const compiled = deepFreeze(compileClickHouseQuery(query, this.config, context));
215
+ this.compiledQueries.add(compiled);
216
+ return compiled;
217
+ }
218
+ async execute(query, context) {
219
+ let statement;
220
+ let parameters;
221
+ let fields;
222
+ let frameName;
223
+ if (isCompiledQuery(query)) {
224
+ if (!this.compiledQueries.has(query)) {
225
+ throw new AdapterError("QUERY_VALIDATION_FAILED", "Compiled query was not produced by this adapter instance.");
226
+ }
227
+ statement = query.compiled.statement;
228
+ parameters = query.parameters;
229
+ fields = query.fields;
230
+ frameName = query.source.resourceName;
231
+ }
232
+ else {
233
+ if (!this.config.allowNativeQueries) {
234
+ throw new AdapterError("NATIVE_QUERY_REJECTED", "Native SQL is disabled for this ClickHouse datasource.", { path: "/spec/native" });
235
+ }
236
+ const native = compileNativeQuery(query, context.variables);
237
+ statement = native.statement;
238
+ parameters = native.parameters;
239
+ frameName = query.metadata.name;
240
+ }
241
+ const timeoutMs = Math.min(context.timeoutMs ?? this.config.queryTimeoutMs ?? DEFAULT_QUERY_TIMEOUT_MS, this.config.queryTimeoutMs ?? DEFAULT_QUERY_TIMEOUT_MS);
242
+ const scope = abortScope(context.abortSignal, timeoutMs);
243
+ const started = this.now();
244
+ const settings = {
245
+ readonly: "1",
246
+ max_execution_time: Math.max(1, Math.ceil(timeoutMs / 1_000)),
247
+ max_result_rows: String(this.config.maxResultRows ?? DEFAULT_MAX_RESULT_ROWS),
248
+ result_overflow_mode: "throw",
249
+ max_rows_to_read: String(this.config.maxRowsToRead ?? DEFAULT_MAX_ROWS_TO_READ),
250
+ read_overflow_mode: "throw",
251
+ };
252
+ try {
253
+ const resultSet = await this.client.query({
254
+ query: statement,
255
+ format: "JSON",
256
+ query_params: parameters,
257
+ clickhouse_settings: settings,
258
+ abort_signal: scope.signal,
259
+ query_id: queryId(context),
260
+ });
261
+ const response = (await resultSet.json());
262
+ return normalizeClickHouseResponse(response, fields, {
263
+ frameName,
264
+ adapterVersion: ADAPTER_VERSION,
265
+ executionTimeMs: Math.max(0, this.now() - started),
266
+ });
267
+ }
268
+ catch (error) {
269
+ if (scope.timedOut()) {
270
+ throw new AdapterError("TIMEOUT", `ClickHouse query exceeded ${timeoutMs}ms.`, {
271
+ cause: error,
272
+ details: { timeoutMs },
273
+ });
274
+ }
275
+ if (context.abortSignal?.aborted || isAbortError(error)) {
276
+ throw new AdapterError("ABORTED", "ClickHouse query was cancelled.", {
277
+ cause: error,
278
+ });
279
+ }
280
+ throw new AdapterError("EXECUTION_FAILED", "ClickHouse query execution failed.", {
281
+ cause: error,
282
+ });
283
+ }
284
+ finally {
285
+ scope.dispose();
286
+ }
287
+ }
288
+ async explain(query, context) {
289
+ const compiledQuery = await this.compile(query, context);
290
+ const steps = [
291
+ `Resolve logical dataset '${query.spec.input.entity}'.`,
292
+ `Map ${query.spec.select.length} selected expression(s) to allowlisted ClickHouse expressions.`,
293
+ "Bind all values as ClickHouse query parameters.",
294
+ ];
295
+ if (query.spec.timeRange)
296
+ steps.push("Apply and validate the bounded time range.");
297
+ if (this.config.tenant)
298
+ steps.push("Apply the adapter-owned tenant predicate.");
299
+ if (query.spec.where)
300
+ steps.push("Compile the portable boolean filter tree.");
301
+ if (query.spec.groupBy?.length)
302
+ steps.push("Compile grouping and time buckets.");
303
+ steps.push("Apply the configured maximum result limit.");
304
+ return {
305
+ summary: `Compile '${query.metadata.name}' to a read-only ClickHouse SQL query.`,
306
+ steps,
307
+ compiledQuery,
308
+ warnings: compiledQuery.warnings,
309
+ };
310
+ }
311
+ async discoverSchema(_context) {
312
+ return datasetsToSemanticSchema(createDatasetRegistry(this.config.datasets ?? []));
313
+ }
314
+ async close() {
315
+ if (this.ownsClient)
316
+ await this.client.close();
317
+ }
318
+ }
319
+ //# sourceMappingURL=adapter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter.js","sourceRoot":"","sources":["../../src/adapter.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YA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