@surfaces-ui/engine-datafusion 0.0.0-stage → 0.3.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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Surfaces UI
2
+ Copyright 2026 Josh Schoen
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
package/README.md CHANGED
@@ -1,3 +1,27 @@
1
- # Temporary Holding Version
1
+ <!-- Generated by scripts/package-readmes.mjs from package.json. Edit the script, not this file. -->
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # @surfaces-ui/engine-datafusion
4
+
5
+ DataFusion engine adapter for Surfaces UI: talks to a DataFusion server over HTTP and reads Arrow.
6
+
7
+ Apache DataFusion as an engine, over a server's HTTP SQL endpoint (ROAPI), reading Arrow.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm install @surfaces-ui/engine-datafusion
13
+ ```
14
+
15
+ ## Part of Surfaces UI
16
+
17
+ Surfaces UI is a UI library for data and analytics: exploring schemas, querying, charting, tables at scale, chat, and pages an agent can build.
18
+
19
+ Every Surfaces UI package is released at the same version; install them all at that one version, since mixing releases is not supported.
20
+
21
+ - [The guides on surfaces-ui.com](https://surfaces-ui.com/#docs)
22
+ - [Getting started](https://github.com/teradata-labs/surfaces-ui/blob/main/docs/getting-started.md)
23
+ - [Building with an agent](https://github.com/teradata-labs/surfaces-ui/blob/main/docs/agent-integration.md)
24
+ - [Styling](https://github.com/teradata-labs/surfaces-ui/blob/main/docs/styling.md)
25
+ - [Source for this package](https://github.com/teradata-labs/surfaces-ui/tree/main/packages/engine-datafusion)
26
+
27
+ Licensed under Apache-2.0. See LICENSE and NOTICE.
@@ -0,0 +1,39 @@
1
+ import { type Engine, EngineError, type Param } from "@surfaces-ui/engine";
2
+ export interface DataFusionEngineOptions {
3
+ /**
4
+ * Address of a DataFusion server's HTTP SQL endpoint, e.g.
5
+ * `http://localhost:8080`. The server must answer `POST /api/sql` with an
6
+ * Arrow stream and `GET /api/schema` with its tables, as ROAPI does.
7
+ */
8
+ baseUrl: string;
9
+ /** Extra headers, e.g. authorisation for a proxy in front of the server. */
10
+ headers?: Record<string, string>;
11
+ /** Uses this instead of the global `fetch`. */
12
+ fetch?: typeof fetch;
13
+ }
14
+ /**
15
+ * One value as SQL text. The server's HTTP endpoint takes a statement and
16
+ * nothing else, so values cannot be bound; they are written so that no value
17
+ * can change the statement. Numbers are checked to be numbers. Text never
18
+ * appears as a quoted literal at all: it is sent as hexadecimal and decoded
19
+ * by the engine, so quotes, backslashes and comment markers in it are only
20
+ * ever data.
21
+ */
22
+ export declare function literal(value: Param): string;
23
+ /**
24
+ * Replaces the numbered placeholders the SQL rewriter produced with values.
25
+ * Placeholders inside string literals, quoted names and comments are left
26
+ * alone, and every placeholder must have a value.
27
+ */
28
+ export declare function inlineParams(sql: string, params: Param[]): string;
29
+ /** Turns the server's error reply into an EngineError with a code the UI understands. */
30
+ export declare function dataFusionError(status: number, body: string): EngineError;
31
+ /**
32
+ * Apache DataFusion behind the Engine interface, reached over a server's
33
+ * HTTP SQL endpoint. Results arrive as an Arrow stream, so types are kept.
34
+ *
35
+ * It only reads: there is no `store` or `materialize`, so views of a query
36
+ * run it again and pipelines cannot use this engine. Time travel and
37
+ * positioned errors are not available over this endpoint.
38
+ */
39
+ export declare function createDataFusionEngine(options: DataFusionEngineOptions): Promise<Engine>;
package/dist/index.js ADDED
@@ -0,0 +1,194 @@
1
+ import { EngineError } from "@surfaces-ui/engine";
2
+ import { Engine as EngineKind, SqlDialect, TableKind } from "@surfaces-ui/proto";
3
+ import { blankLiterals } from "@surfaces-ui/sql";
4
+ import { RecordBatchReader } from "apache-arrow";
5
+ /**
6
+ * The endpoint names tables only, not the catalog and schema they sit in
7
+ * (those differ between servers and cannot be listed). Tables are therefore
8
+ * reported without them, so that nothing writes a qualified name the server
9
+ * would not recognise; these two are labels for the levels of a browser.
10
+ */
11
+ const CATALOG = "default";
12
+ const SCHEMA = "default";
13
+ const BARE = { catalog: "", schema: "" };
14
+ const ARROW = "application/vnd.apache.arrow.stream";
15
+ const hex = (text) => Array.from(new TextEncoder().encode(text), (byte) => byte.toString(16).padStart(2, "0")).join("");
16
+ /**
17
+ * One value as SQL text. The server's HTTP endpoint takes a statement and
18
+ * nothing else, so values cannot be bound; they are written so that no value
19
+ * can change the statement. Numbers are checked to be numbers. Text never
20
+ * appears as a quoted literal at all: it is sent as hexadecimal and decoded
21
+ * by the engine, so quotes, backslashes and comment markers in it are only
22
+ * ever data.
23
+ */
24
+ export function literal(value) {
25
+ if (typeof value === "bigint")
26
+ return value.toString();
27
+ if (typeof value === "number") {
28
+ if (!Number.isFinite(value))
29
+ throw new EngineError("UNSUPPORTED", "A filter value is not a finite number.");
30
+ return String(value);
31
+ }
32
+ if (typeof value === "boolean")
33
+ return value ? "TRUE" : "FALSE";
34
+ return `CAST(decode('${hex(value)}', 'hex') AS VARCHAR)`;
35
+ }
36
+ /**
37
+ * Replaces the numbered placeholders the SQL rewriter produced with values.
38
+ * Placeholders inside string literals, quoted names and comments are left
39
+ * alone, and every placeholder must have a value.
40
+ */
41
+ export function inlineParams(sql, params) {
42
+ if (params.length === 0)
43
+ return sql;
44
+ const bare = blankLiterals(sql);
45
+ let out = "";
46
+ let at = 0;
47
+ for (const match of bare.matchAll(/\$(\d+)/g)) {
48
+ const index = Number(match[1]) - 1;
49
+ if (index < 0 || index >= params.length)
50
+ throw new EngineError("ENGINE", `The query refers to parameter ${match[1]}, which was not given.`);
51
+ out += sql.slice(at, match.index) + literal(params[index]);
52
+ at = match.index + match[0].length;
53
+ }
54
+ return out + sql.slice(at);
55
+ }
56
+ /** Turns the server's error reply into an EngineError with a code the UI understands. */
57
+ export function dataFusionError(status, body) {
58
+ let message = body.trim();
59
+ try {
60
+ const parsed = JSON.parse(body);
61
+ message = parsed.message ?? parsed.error ?? message;
62
+ }
63
+ catch {
64
+ // Not JSON: use the text as it is.
65
+ }
66
+ const clean = message
67
+ .replace(/^Failed to (plan execution from SQL query|execute query): /, "")
68
+ .replace(/^(Error during planning|Schema error|SQL error|Execution error): /, "")
69
+ .replace(/^ParserError\("(.*)"\)$/s, "$1")
70
+ .trim();
71
+ const code = /ParserError|Expected .* found/i.test(message)
72
+ ? "SYNTAX"
73
+ : /No field named|column .* not found/i.test(message)
74
+ ? "UNKNOWN_COLUMN"
75
+ : /table .* not found|No table named/i.test(message)
76
+ ? "UNKNOWN_TABLE"
77
+ : /not implemented|Unsupported logical plan/i.test(message)
78
+ ? "UNSUPPORTED"
79
+ : "ENGINE";
80
+ return new EngineError(code, clean || `The server answered ${status}.`);
81
+ }
82
+ const typeName = (type) => (typeof type === "string" ? type : JSON.stringify(type));
83
+ /**
84
+ * Apache DataFusion behind the Engine interface, reached over a server's
85
+ * HTTP SQL endpoint. Results arrive as an Arrow stream, so types are kept.
86
+ *
87
+ * It only reads: there is no `store` or `materialize`, so views of a query
88
+ * run it again and pipelines cannot use this engine. Time travel and
89
+ * positioned errors are not available over this endpoint.
90
+ */
91
+ export async function createDataFusionEngine(options) {
92
+ const call = options.fetch ?? fetch;
93
+ const base = options.baseUrl.replace(/\/+$/, "");
94
+ const post = async (sql, accept, signal) => {
95
+ let response;
96
+ try {
97
+ response = await call(`${base}/api/sql`, { method: "POST", headers: { Accept: accept, "Content-Type": "text/plain", ...options.headers }, body: sql, signal });
98
+ }
99
+ catch (error) {
100
+ if (signal?.aborted)
101
+ throw new EngineError("CANCELLED", "The query was cancelled.");
102
+ throw new EngineError("ENGINE", `The DataFusion server could not be reached: ${error instanceof Error ? error.message : String(error)}`);
103
+ }
104
+ if (!response.ok)
105
+ throw dataFusionError(response.status, await response.text());
106
+ return response;
107
+ };
108
+ const rowsOf = async (sql) => (await (await post(sql, "application/json")).json());
109
+ const tables = async () => {
110
+ let response;
111
+ try {
112
+ response = await call(`${base}/api/schema`, { headers: options.headers });
113
+ }
114
+ catch (error) {
115
+ throw new EngineError("ENGINE", `The DataFusion server could not be reached: ${error instanceof Error ? error.message : String(error)}`);
116
+ }
117
+ if (!response.ok)
118
+ throw dataFusionError(response.status, await response.text());
119
+ return (await response.json());
120
+ };
121
+ const quoted = (name) => `"${name.replace(/"/g, '""')}"`;
122
+ const find = async (ref) => {
123
+ const all = await tables();
124
+ const name = Object.keys(all).find((t) => t.toLowerCase() === (ref?.table ?? "").toLowerCase());
125
+ if (!name)
126
+ throw new EngineError("UNKNOWN_TABLE", `Table not found: ${ref?.table ?? ""}`);
127
+ return { name, fields: all[name].fields };
128
+ };
129
+ return {
130
+ kind: EngineKind.DATAFUSION,
131
+ dialect: SqlDialect.DATAFUSION,
132
+ capabilities: { cancel: true, explain: true, explainJson: false, timeTravel: false, keysetPaging: false, exactCount: true, columnStats: false },
133
+ async execute(sql, params, executeOptions = {}) {
134
+ if (executeOptions.timeTravel?.at.case)
135
+ throw new EngineError("UNSUPPORTED", "This source cannot read tables as of an earlier time.");
136
+ const response = await post(inlineParams(sql, params), ARROW, executeOptions.signal);
137
+ const reader = await RecordBatchReader.from(response);
138
+ await reader.open();
139
+ const signal = executeOptions.signal;
140
+ async function* batches() {
141
+ try {
142
+ for await (const batch of reader) {
143
+ if (signal?.aborted)
144
+ throw new EngineError("CANCELLED", "The query was cancelled.");
145
+ yield batch;
146
+ }
147
+ }
148
+ finally {
149
+ await reader.cancel().catch(() => { });
150
+ }
151
+ }
152
+ return { schema: reader.schema, batches: batches() };
153
+ },
154
+ async explain(sql, params) {
155
+ const plan = await rowsOf(`EXPLAIN ${inlineParams(sql, params)}`);
156
+ return { planText: plan.map((row) => `${String(row.plan_type ?? "")}\n${String(row.plan ?? "")}`).join("\n\n"), planJson: "" };
157
+ },
158
+ async check() {
159
+ const names = Object.keys(await tables()).sort();
160
+ return Promise.all(names.map(async (name) => {
161
+ const started = Date.now();
162
+ try {
163
+ await rowsOf(`SELECT * FROM ${quoted(name)} LIMIT 0`);
164
+ return { name, ok: true, message: "Reachable", elapsedMs: Date.now() - started };
165
+ }
166
+ catch (error) {
167
+ return { name, ok: false, message: error instanceof Error ? error.message : String(error), elapsedMs: Date.now() - started };
168
+ }
169
+ }));
170
+ },
171
+ listCatalogs: async () => [{ name: CATALOG }],
172
+ listSchemas: async () => [{ catalog: CATALOG, name: SCHEMA }],
173
+ async listTables({ search }) {
174
+ const needle = search.toLowerCase();
175
+ return Object.keys(await tables())
176
+ .filter((name) => name.toLowerCase().includes(needle))
177
+ .sort()
178
+ .map((name) => ({ ref: { ...BARE, table: name }, kind: TableKind.TABLE }));
179
+ },
180
+ async describeTable(ref, includeStats) {
181
+ const { name, fields } = await find(ref);
182
+ const counted = includeStats ? (await rowsOf(`SELECT COUNT(*) AS n FROM ${quoted(name)}`))[0]?.n : undefined;
183
+ return {
184
+ summary: { ref: { ...BARE, table: name }, kind: TableKind.TABLE },
185
+ columns: fields.map((field, i) => ({ name: field.name, nativeType: typeName(field.data_type), arrowType: typeName(field.data_type), nullable: field.nullable !== false, ordinal: i + 1 })),
186
+ rowCount: counted === undefined ? undefined : BigInt(counted),
187
+ };
188
+ },
189
+ listSnapshots: async () => [],
190
+ version: async () => String((await rowsOf("SELECT version() AS v"))[0]?.v ?? ""),
191
+ close: async () => { },
192
+ };
193
+ }
194
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiC,WAAW,EAAsD,MAAM,qBAAqB,CAAC;AACrI,OAAO,EAAE,MAAM,IAAI,UAAU,EAAE,UAAU,EAAE,SAAS,EAAiB,MAAM,oBAAoB,CAAC;AAChG,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAoB,iBAAiB,EAAe,MAAM,cAAc,CAAC;AAehF;;;;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,MAAM,CAAC,uBAAuB,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC;QAChF,KAAK,EAAE,KAAK,IAAI,EAAE,GAAE,CAAC;KACtB,CAAC;AACJ,CAAC","sourcesContent":["import { type Engine, type EngineCheck, EngineError, type EngineResult, type ExecuteOptions, type Param } from \"@surfaces-ui/engine\";\nimport { Engine as EngineKind, SqlDialect, TableKind, type TableRef } from \"@surfaces-ui/proto\";\nimport { blankLiterals } from \"@surfaces-ui/sql\";\nimport { type RecordBatch, RecordBatchReader, type Schema } from \"apache-arrow\";\n\nexport interface DataFusionEngineOptions {\n /**\n * Address of a DataFusion server's HTTP SQL endpoint, e.g.\n * `http://localhost:8080`. The server must answer `POST /api/sql` with an\n * Arrow stream and `GET /api/schema` with its tables, as ROAPI does.\n */\n baseUrl: string;\n /** Extra headers, e.g. authorisation for a proxy in front of the server. */\n headers?: Record<string, string>;\n /** Uses this instead of the global `fetch`. */\n fetch?: typeof fetch;\n}\n\n/**\n * The endpoint names tables only, not the catalog and schema they sit in\n * (those differ between servers and cannot be listed). Tables are therefore\n * reported without them, so that nothing writes a qualified name the server\n * would not recognise; these two are labels for the levels of a browser.\n */\nconst CATALOG = \"default\";\nconst SCHEMA = \"default\";\nconst BARE = { catalog: \"\", schema: \"\" };\nconst ARROW = \"application/vnd.apache.arrow.stream\";\n\nconst hex = (text: string) => Array.from(new TextEncoder().encode(text), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\n/**\n * One value as SQL text. The server's HTTP endpoint takes a statement and\n * nothing else, so values cannot be bound; they are written so that no value\n * can change the statement. Numbers are checked to be numbers. Text never\n * appears as a quoted literal at all: it is sent as hexadecimal and decoded\n * by the engine, so quotes, backslashes and comment markers in it are only\n * ever data.\n */\nexport function literal(value: Param): string {\n if (typeof value === \"bigint\") return value.toString();\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) throw new EngineError(\"UNSUPPORTED\", \"A filter value is not a finite number.\");\n return String(value);\n }\n if (typeof value === \"boolean\") return value ? \"TRUE\" : \"FALSE\";\n return `CAST(decode('${hex(value)}', 'hex') AS VARCHAR)`;\n}\n\n/**\n * Replaces the numbered placeholders the SQL rewriter produced with values.\n * Placeholders inside string literals, quoted names and comments are left\n * alone, and every placeholder must have a value.\n */\nexport function inlineParams(sql: string, params: Param[]): string {\n if (params.length === 0) return sql;\n const bare = blankLiterals(sql);\n let out = \"\";\n let at = 0;\n for (const match of bare.matchAll(/\\$(\\d+)/g)) {\n const index = Number(match[1]) - 1;\n if (index < 0 || index >= params.length) throw new EngineError(\"ENGINE\", `The query refers to parameter ${match[1]}, which was not given.`);\n out += sql.slice(at, match.index) + literal(params[index]!);\n at = match.index + match[0].length;\n }\n return out + sql.slice(at);\n}\n\n/** Turns the server's error reply into an EngineError with a code the UI understands. */\nexport function dataFusionError(status: number, body: string): EngineError {\n let message = body.trim();\n try {\n const parsed = JSON.parse(body) as { message?: string; error?: string };\n message = parsed.message ?? parsed.error ?? message;\n } catch {\n // Not JSON: use the text as it is.\n }\n const clean = message\n .replace(/^Failed to (plan execution from SQL query|execute query): /, \"\")\n .replace(/^(Error during planning|Schema error|SQL error|Execution error): /, \"\")\n .replace(/^ParserError\\(\"(.*)\"\\)$/s, \"$1\")\n .trim();\n const code = /ParserError|Expected .* found/i.test(message)\n ? \"SYNTAX\"\n : /No field named|column .* not found/i.test(message)\n ? \"UNKNOWN_COLUMN\"\n : /table .* not found|No table named/i.test(message)\n ? \"UNKNOWN_TABLE\"\n : /not implemented|Unsupported logical plan/i.test(message)\n ? \"UNSUPPORTED\"\n : \"ENGINE\";\n return new EngineError(code, clean || `The server answered ${status}.`);\n}\n\ninterface SchemaField {\n name: string;\n data_type: unknown;\n nullable?: boolean;\n}\n\nconst typeName = (type: unknown): string => (typeof type === \"string\" ? type : JSON.stringify(type));\n\n/**\n * Apache DataFusion behind the Engine interface, reached over a server's\n * HTTP SQL endpoint. Results arrive as an Arrow stream, so types are kept.\n *\n * It only reads: there is no `store` or `materialize`, so views of a query\n * run it again and pipelines cannot use this engine. Time travel and\n * positioned errors are not available over this endpoint.\n */\nexport async function createDataFusionEngine(options: DataFusionEngineOptions): Promise<Engine> {\n const call = options.fetch ?? fetch;\n const base = options.baseUrl.replace(/\\/+$/, \"\");\n\n const post = async (sql: string, accept: string, signal?: AbortSignal): Promise<Response> => {\n let response: Response;\n try {\n response = await call(`${base}/api/sql`, { method: \"POST\", headers: { Accept: accept, \"Content-Type\": \"text/plain\", ...options.headers }, body: sql, signal });\n } catch (error) {\n if (signal?.aborted) throw new EngineError(\"CANCELLED\", \"The query was cancelled.\");\n throw new EngineError(\"ENGINE\", `The DataFusion server could not be reached: ${error instanceof Error ? error.message : String(error)}`);\n }\n if (!response.ok) throw dataFusionError(response.status, await response.text());\n return response;\n };\n\n const rowsOf = async (sql: string): Promise<Record<string, unknown>[]> => (await (await post(sql, \"application/json\")).json()) as Record<string, unknown>[];\n\n const tables = async (): Promise<Record<string, { fields: SchemaField[] }>> => {\n let response: Response;\n try {\n response = await call(`${base}/api/schema`, { headers: options.headers });\n } catch (error) {\n throw new EngineError(\"ENGINE\", `The DataFusion server could not be reached: ${error instanceof Error ? error.message : String(error)}`);\n }\n if (!response.ok) throw dataFusionError(response.status, await response.text());\n return (await response.json()) as Record<string, { fields: SchemaField[] }>;\n };\n\n const quoted = (name: string) => `\"${name.replace(/\"/g, '\"\"')}\"`;\n const find = async (ref: TableRef | undefined) => {\n const all = await tables();\n const name = Object.keys(all).find((t) => t.toLowerCase() === (ref?.table ?? \"\").toLowerCase());\n if (!name) throw new EngineError(\"UNKNOWN_TABLE\", `Table not found: ${ref?.table ?? \"\"}`);\n return { name, fields: all[name]!.fields };\n };\n\n return {\n kind: EngineKind.DATAFUSION,\n dialect: SqlDialect.DATAFUSION,\n capabilities: { cancel: true, explain: true, explainJson: false, timeTravel: false, keysetPaging: false, exactCount: true, columnStats: false },\n\n async execute(sql: string, params: Param[], executeOptions: ExecuteOptions = {}): Promise<EngineResult> {\n if (executeOptions.timeTravel?.at.case) throw new EngineError(\"UNSUPPORTED\", \"This source cannot read tables as of an earlier time.\");\n const response = await post(inlineParams(sql, params), ARROW, executeOptions.signal);\n const reader = await RecordBatchReader.from(response);\n await reader.open();\n const signal = executeOptions.signal;\n async function* batches(): AsyncGenerator<RecordBatch> {\n try {\n for await (const batch of reader) {\n if (signal?.aborted) throw new EngineError(\"CANCELLED\", \"The query was cancelled.\");\n yield batch;\n }\n } finally {\n await reader.cancel().catch(() => {});\n }\n }\n return { schema: reader.schema as Schema, batches: batches() };\n },\n\n async explain(sql, params) {\n const plan = await rowsOf(`EXPLAIN ${inlineParams(sql, params)}`);\n return { planText: plan.map((row) => `${String(row.plan_type ?? \"\")}\\n${String(row.plan ?? \"\")}`).join(\"\\n\\n\"), planJson: \"\" };\n },\n\n async check(): Promise<EngineCheck[]> {\n const names = Object.keys(await tables()).sort();\n return Promise.all(\n names.map(async (name) => {\n const started = Date.now();\n try {\n await rowsOf(`SELECT * FROM ${quoted(name)} LIMIT 0`);\n return { name, ok: true, message: \"Reachable\", elapsedMs: Date.now() - started };\n } catch (error) {\n return { name, ok: false, message: error instanceof Error ? error.message : String(error), elapsedMs: Date.now() - started };\n }\n }),\n );\n },\n\n listCatalogs: async () => [{ name: CATALOG }],\n listSchemas: async () => [{ catalog: CATALOG, name: SCHEMA }],\n\n async listTables({ search }) {\n const needle = search.toLowerCase();\n return Object.keys(await tables())\n .filter((name) => name.toLowerCase().includes(needle))\n .sort()\n .map((name) => ({ ref: { ...BARE, table: name }, kind: TableKind.TABLE }));\n },\n\n async describeTable(ref, includeStats) {\n const { name, fields } = await find(ref);\n const counted = includeStats ? (await rowsOf(`SELECT COUNT(*) AS n FROM ${quoted(name)}`))[0]?.n : undefined;\n return {\n summary: { ref: { ...BARE, table: name }, kind: TableKind.TABLE },\n columns: fields.map((field, i) => ({ name: field.name, nativeType: typeName(field.data_type), arrowType: typeName(field.data_type), nullable: field.nullable !== false, ordinal: i + 1 })),\n rowCount: counted === undefined ? undefined : BigInt(counted as number),\n };\n },\n\n listSnapshots: async () => [],\n version: async () => String((await rowsOf(\"SELECT version() AS v\"))[0]?.v ?? \"\"),\n close: async () => {},\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@surfaces-ui/engine-datafusion",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.0",
4
+ "description": "DataFusion engine adapter for Surfaces UI: talks to a DataFusion server over HTTP and reads Arrow",
5
+ "keywords": [
6
+ "surfaces-ui",
7
+ "analytics",
8
+ "data",
9
+ "datafusion",
10
+ "arrow"
11
+ ],
12
+ "license": "Apache-2.0",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/teradata-labs/surfaces-ui.git",
16
+ "directory": "packages/engine-datafusion"
17
+ },
18
+ "homepage": "https://github.com/teradata-labs/surfaces-ui#readme",
19
+ "bugs": {
20
+ "url": "https://github.com/teradata-labs/surfaces-ui/issues"
21
+ },
22
+ "type": "module",
23
+ "main": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "default": "./dist/index.js"
29
+ }
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "NOTICE"
34
+ ],
35
+ "dependencies": {
36
+ "@bufbuild/protobuf": "^2.17.0",
37
+ "apache-arrow": "^21.2.0",
38
+ "@surfaces-ui/engine": "0.3.0",
39
+ "@surfaces-ui/proto": "0.3.0",
40
+ "@surfaces-ui/sql": "0.3.0"
41
+ },
42
+ "devDependencies": {},
43
+ "publishConfig": {
44
+ "access": "public",
45
+ "provenance": true
46
+ },
47
+ "scripts": {
48
+ "build": "tsc -p tsconfig.build.json",
49
+ "typecheck": "tsc -p tsconfig.json --noEmit",
50
+ "test": "vitest run --passWithNoTests"
51
+ }
6
52
  }