@loaders.gl/sql 5.0.0-alpha.1 → 5.0.0-alpha.3

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 (94) hide show
  1. package/LICENSE +14 -3
  2. package/README.md +107 -0
  3. package/dist/arrow-query.cjs +1373 -0
  4. package/dist/arrow-query.cjs.map +6 -0
  5. package/dist/arrow-query.d.ts +5 -0
  6. package/dist/arrow-query.d.ts.map +1 -0
  7. package/dist/arrow-query.js +6 -0
  8. package/dist/arrow-query.js.map +1 -0
  9. package/dist/arrow-table-source.d.ts +27 -0
  10. package/dist/arrow-table-source.d.ts.map +1 -0
  11. package/dist/arrow-table-source.js +79 -0
  12. package/dist/arrow-table-source.js.map +1 -0
  13. package/dist/bind-sql-predicate.d.ts +4 -0
  14. package/dist/bind-sql-predicate.d.ts.map +1 -0
  15. package/dist/bind-sql-predicate.js +11 -0
  16. package/dist/bind-sql-predicate.js.map +1 -0
  17. package/dist/compile-table-query.d.ts +55 -0
  18. package/dist/compile-table-query.d.ts.map +1 -0
  19. package/dist/compile-table-query.js +255 -0
  20. package/dist/compile-table-query.js.map +1 -0
  21. package/dist/duckdb-sql-source.d.ts.map +1 -1
  22. package/dist/duckdb-sql-source.js +21 -7
  23. package/dist/duckdb-sql-source.js.map +1 -1
  24. package/dist/index.cjs +3154 -35
  25. package/dist/index.cjs.map +3 -4
  26. package/dist/index.d.ts +16 -1
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +9 -0
  29. package/dist/index.js.map +1 -1
  30. package/dist/parse-sql-predicate.d.ts +10 -0
  31. package/dist/parse-sql-predicate.d.ts.map +1 -0
  32. package/dist/parse-sql-predicate.js +322 -0
  33. package/dist/parse-sql-predicate.js.map +1 -0
  34. package/dist/query-arrow-table.d.ts +83 -0
  35. package/dist/query-arrow-table.d.ts.map +1 -0
  36. package/dist/query-arrow-table.js +660 -0
  37. package/dist/query-arrow-table.js.map +1 -0
  38. package/dist/snowflake-sql-source.d.ts.map +1 -1
  39. package/dist/snowflake-sql-source.js +8 -5
  40. package/dist/snowflake-sql-source.js.map +1 -1
  41. package/dist/sql-predicate-schema.d.ts +156 -0
  42. package/dist/sql-predicate-schema.d.ts.map +1 -0
  43. package/dist/sql-predicate-schema.js +226 -0
  44. package/dist/sql-predicate-schema.js.map +1 -0
  45. package/dist/sql-predicate-types.d.ts +45 -0
  46. package/dist/sql-predicate-types.d.ts.map +1 -0
  47. package/dist/sql-predicate-types.js +9 -0
  48. package/dist/sql-predicate-types.js.map +1 -0
  49. package/dist/sql-predicate-zod.cjs +54 -0
  50. package/dist/sql-predicate-zod.cjs.map +6 -0
  51. package/dist/sql-predicate-zod.d.ts +11 -0
  52. package/dist/sql-predicate-zod.d.ts.map +1 -0
  53. package/dist/sql-predicate-zod.js +45 -0
  54. package/dist/sql-predicate-zod.js.map +1 -0
  55. package/dist/sql-predicate.cjs +607 -0
  56. package/dist/sql-predicate.cjs.map +6 -0
  57. package/dist/sql-predicate.d.ts +6 -0
  58. package/dist/sql-predicate.d.ts.map +1 -0
  59. package/dist/sql-predicate.js +8 -0
  60. package/dist/sql-predicate.js.map +1 -0
  61. package/dist/sql-source.d.ts +16 -3
  62. package/dist/sql-source.d.ts.map +1 -1
  63. package/dist/sql-source.js +34 -5
  64. package/dist/sql-source.js.map +1 -1
  65. package/dist/sql-types.d.ts +3 -0
  66. package/dist/sql-types.d.ts.map +1 -1
  67. package/dist/table-query-capabilities.d.ts +6 -0
  68. package/dist/table-query-capabilities.d.ts.map +1 -0
  69. package/dist/table-query-capabilities.js +26 -0
  70. package/dist/table-query-capabilities.js.map +1 -0
  71. package/dist/table-query.cjs +286 -0
  72. package/dist/table-query.cjs.map +6 -0
  73. package/dist/table-query.d.ts +29 -0
  74. package/dist/table-query.d.ts.map +1 -0
  75. package/dist/table-query.js +30 -0
  76. package/dist/table-query.js.map +1 -0
  77. package/package.json +45 -8
  78. package/src/arrow-query.ts +17 -0
  79. package/src/arrow-table-source.ts +111 -0
  80. package/src/bind-sql-predicate.ts +21 -0
  81. package/src/compile-table-query.ts +354 -0
  82. package/src/duckdb-sql-source.ts +30 -6
  83. package/src/index.ts +57 -0
  84. package/src/parse-sql-predicate.ts +381 -0
  85. package/src/query-arrow-table.ts +843 -0
  86. package/src/snowflake-sql-source.ts +7 -4
  87. package/src/sql-predicate-schema.ts +251 -0
  88. package/src/sql-predicate-types.ts +87 -0
  89. package/src/sql-predicate-zod.ts +52 -0
  90. package/src/sql-predicate.ts +28 -0
  91. package/src/sql-source.ts +40 -5
  92. package/src/sql-types.ts +4 -0
  93. package/src/table-query-capabilities.ts +29 -0
  94. package/src/table-query.ts +78 -0
package/dist/index.cjs CHANGED
@@ -28,24 +28,2130 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
29
 
30
30
  // dist/index.js
31
- var dist_exports = {};
32
- __export(dist_exports, {
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ ARROW_TABLE_QUERY_CAPABILITIES: () => ARROW_TABLE_QUERY_CAPABILITIES,
34
+ ArrowTableSource: () => ArrowTableSource,
33
35
  DuckDBSQLDataSource: () => DuckDBSQLDataSource,
34
36
  DuckDBSQLSource: () => DuckDBSQLSource,
35
37
  SQLDataSource: () => SQLDataSource,
38
+ SQL_DATA_SOURCE_TABLE_QUERY_CAPABILITIES: () => SQL_DATA_SOURCE_TABLE_QUERY_CAPABILITIES,
39
+ SQL_PREDICATE_JSON_SCHEMA: () => SQL_PREDICATE_JSON_SCHEMA,
36
40
  SnowflakeSQLDataSource: () => SnowflakeSQLDataSource,
37
41
  SnowflakeSQLSource: () => SnowflakeSQLSource,
42
+ bindSQLPredicate: () => bindSQLPredicate,
43
+ compileSQLTableQuery: () => compileSQLTableQuery,
44
+ explainArrowTableQuery: () => explainArrowTableQuery,
45
+ explainTableQuery: () => explainTableQuery2,
38
46
  getSQLAdapterFactory: () => getSQLAdapterFactory,
39
- registerSQLAdapter: () => registerSQLAdapter
47
+ getSQLPredicateColumnNames: () => getSQLPredicateColumnNames,
48
+ isSQLPredicate: () => isSQLPredicate,
49
+ isSQLPredicateParameter: () => isSQLPredicateParameter,
50
+ parseSQLPredicate: () => parseSQLPredicate,
51
+ planTableQuery: () => planTableQuery2,
52
+ queryArrowTable: () => queryArrowTable,
53
+ registerSQLAdapter: () => registerSQLAdapter,
54
+ validateSQLPredicate: () => validateSQLPredicate
40
55
  });
41
- module.exports = __toCommonJS(dist_exports);
56
+ module.exports = __toCommonJS(index_exports);
42
57
 
43
- // dist/sql-source.js
44
- var import_loader_utils = require("@loaders.gl/loader-utils");
58
+ // ../loader-utils/src/lib/log-utils/log.ts
59
+ var import_log = require("@probe.gl/log");
60
+ var VERSION = typeof __VERSION__ !== "undefined" ? __VERSION__ : "latest";
61
+ var version = VERSION[0] >= "0" && VERSION[0] <= "9" ? `v${VERSION}` : "";
62
+ function createLog() {
63
+ const log2 = new import_log.Log({ id: "loaders.gl" });
64
+ globalThis.loaders ||= {};
65
+ globalThis.loaders.log = log2;
66
+ globalThis.loaders.version = version;
67
+ globalThis.probe ||= {};
68
+ globalThis.probe.loaders = log2;
69
+ return log2;
70
+ }
71
+ var log = createLog();
72
+
73
+ // ../loader-utils/src/lib/javascript-utils/is-type.ts
74
+ var isObject = (value) => value !== null && typeof value === "object";
75
+ var isPureObject = (value) => isObject(value) && value.constructor === {}.constructor;
76
+
77
+ // ../loader-utils/src/lib/option-utils/merge-options.ts
78
+ function mergeOptions(baseOptions, newOptions) {
79
+ return mergeOptionsRecursively(baseOptions || {}, newOptions);
80
+ }
81
+ function mergeOptionsRecursively(baseOptions, newOptions, level = 0) {
82
+ if (level > 3) {
83
+ return newOptions;
84
+ }
85
+ const options = { ...baseOptions };
86
+ for (const [key, newValue] of Object.entries(newOptions)) {
87
+ if (isPureObject(newValue)) {
88
+ options[key] = mergeOptionsRecursively(
89
+ options[key] || {},
90
+ newOptions[key],
91
+ level + 1
92
+ );
93
+ } else {
94
+ options[key] = newOptions[key];
95
+ }
96
+ }
97
+ return options;
98
+ }
99
+
100
+ // ../loader-utils/src/lib/request-utils/request-credentials.ts
101
+ var AUTHENTICATED_FETCH = /* @__PURE__ */ Symbol("loaders.gl.authenticated-fetch");
102
+ var refreshPromises = /* @__PURE__ */ new WeakMap();
103
+ function createAuthenticatedFetch(options) {
104
+ const baseFetch = options.fetch || ((url, requestOptions) => fetch(url, requestOptions));
105
+ if (!options.credentials.length) return baseFetch;
106
+ const existingMetadata = baseFetch[AUTHENTICATED_FETCH];
107
+ if (existingMetadata === options.credentials) return baseFetch;
108
+ const authenticatedFetch = async (url, requestOptions = {}) => {
109
+ var _a, _b, _c;
110
+ const resolvedURL = parseHTTPURL(url);
111
+ if (!resolvedURL) return baseFetch(url, requestOptions);
112
+ const authorization = await authorizeRequest(resolvedURL, requestOptions, options.credentials);
113
+ const response = await baseFetch(authorization.url, authorization.options);
114
+ const refreshableCredentials = authorization.credentials.filter(
115
+ ({ credential }) => typeof credential.token === "function" && credential.refreshStatusCodes.includes(response.status)
116
+ );
117
+ if (!refreshableCredentials.length || !isReplayableRequest(requestOptions)) return response;
118
+ if ((_a = requestOptions.signal) == null ? void 0 : _a.aborted) throw createAbortError();
119
+ const refreshedTokens = /* @__PURE__ */ new Map();
120
+ await Promise.all(
121
+ refreshableCredentials.map(async ({ credential }) => {
122
+ const token = await refreshCredential(credential, url, response);
123
+ if (token) refreshedTokens.set(credential, token);
124
+ })
125
+ );
126
+ if (!refreshedTokens.size) return response;
127
+ await ((_b = response.body) == null ? void 0 : _b.cancel().catch(() => {
128
+ }));
129
+ if ((_c = requestOptions.signal) == null ? void 0 : _c.aborted) throw createAbortError();
130
+ const replayAuthorization = await authorizeRequest(
131
+ resolvedURL,
132
+ requestOptions,
133
+ options.credentials,
134
+ refreshedTokens,
135
+ authorization.credentials
136
+ );
137
+ return baseFetch(replayAuthorization.url, replayAuthorization.options);
138
+ };
139
+ Object.defineProperty(authenticatedFetch, AUTHENTICATED_FETCH, {
140
+ value: options.credentials
141
+ });
142
+ return authenticatedFetch;
143
+ }
144
+ async function authorizeRequest(sourceURL, requestOptions, credentials, tokenOverrides = /* @__PURE__ */ new Map(), previousCredentials = []) {
145
+ const url = new URL(sourceURL);
146
+ const headers = new Headers(requestOptions.headers);
147
+ const resolvedCredentials = [];
148
+ const previousTokens = new Map(
149
+ previousCredentials.map(({ credential, token }) => [credential, token])
150
+ );
151
+ for (const credential of credentials) {
152
+ if (!credential.origins.includes(url.origin)) continue;
153
+ const overrideToken = tokenOverrides.get(credential);
154
+ const previousToken = previousTokens.get(credential);
155
+ const ownsQueryParameter = credential.type === "query-parameter" && previousToken !== void 0;
156
+ const ownsHeader = credential.type === "header" && previousToken !== void 0;
157
+ if (credential.type === "query-parameter" && url.searchParams.has(credential.name) && !ownsQueryParameter || credential.type === "header" && headers.has(credential.name) && !ownsHeader) {
158
+ continue;
159
+ }
160
+ const token = overrideToken ?? previousToken ?? await resolveToken(credential.token, { url: sourceURL.toString(), reason: "request" });
161
+ if (!token) continue;
162
+ if (credential.type === "query-parameter") {
163
+ url.searchParams.set(credential.name, token);
164
+ } else {
165
+ headers.set(credential.name, `${credential.prefix || ""}${token}`);
166
+ }
167
+ resolvedCredentials.push({ credential, token });
168
+ }
169
+ return {
170
+ url: url.toString(),
171
+ options: { ...requestOptions, headers },
172
+ credentials: resolvedCredentials
173
+ };
174
+ }
175
+ async function refreshCredential(credential, url, response) {
176
+ const existingPromise = refreshPromises.get(credential);
177
+ if (existingPromise) return existingPromise;
178
+ const tokenProvider = credential.token;
179
+ const promise = Promise.resolve(
180
+ tokenProvider({
181
+ url,
182
+ reason: "refresh",
183
+ response: { status: response.status, headers: response.headers }
184
+ })
185
+ ).finally(() => refreshPromises.delete(credential));
186
+ refreshPromises.set(credential, promise);
187
+ return promise;
188
+ }
189
+ async function resolveToken(token, context) {
190
+ return typeof token === "function" ? token(context) : token;
191
+ }
192
+ function parseHTTPURL(url) {
193
+ try {
194
+ const parsedURL = new URL(url);
195
+ return ["http:", "https:"].includes(parsedURL.protocol) ? parsedURL : null;
196
+ } catch {
197
+ return null;
198
+ }
199
+ }
200
+ function isReplayableRequest(options) {
201
+ const method = (options.method || "GET").toUpperCase();
202
+ if (!["GET", "HEAD", "OPTIONS", "PUT", "DELETE"].includes(method)) return false;
203
+ return !(options.body && typeof ReadableStream !== "undefined" && options.body instanceof ReadableStream);
204
+ }
205
+ function createAbortError() {
206
+ return new DOMException("The operation was aborted.", "AbortError");
207
+ }
208
+
209
+ // ../loader-utils/src/lib/path-utils/file-aliases.ts
210
+ var pathPrefix = "";
211
+ var fileAliases = {};
212
+ function resolvePath(filename) {
213
+ for (const alias in fileAliases) {
214
+ if (filename.startsWith(alias)) {
215
+ const replacement = fileAliases[alias];
216
+ filename = filename.replace(alias, replacement);
217
+ }
218
+ }
219
+ if (!filename.startsWith("http://") && !filename.startsWith("https://")) {
220
+ filename = `${pathPrefix}${filename}`;
221
+ }
222
+ return filename;
223
+ }
224
+
225
+ // ../loader-utils/src/lib/sources/data-source.ts
226
+ var UNAVAILABLE_CORE_API = {
227
+ fetchFile: unavailableCoreApiMethod("fetchFile"),
228
+ parse: unavailableCoreApiMethod("parse"),
229
+ parseFile: unavailableCoreApiMethod("parseFile"),
230
+ parseSync: unavailableCoreApiMethod("parseSync"),
231
+ parseInBatches: unavailableCoreApiMethod("parseInBatches"),
232
+ load: unavailableCoreApiMethod("load"),
233
+ loadInBatches: unavailableCoreApiMethod("loadInBatches")
234
+ };
235
+ var DataSource = class _DataSource {
236
+ static defaultOptions = {
237
+ core: {
238
+ type: "auto",
239
+ attributions: [],
240
+ loadOptions: {},
241
+ loaders: [],
242
+ onError: void 0
243
+ }
244
+ };
245
+ optionsType;
246
+ options;
247
+ data;
248
+ url;
249
+ /** The actual load options, if calling a loaders.gl loader */
250
+ loadOptions;
251
+ /** A resolved fetch function extracted from loadOptions prop */
252
+ fetch;
253
+ /** Shared source-level runtime hooks, when supplied by the source factory. */
254
+ coreApi;
255
+ /** Whether a real CoreAPI instance was injected by the integration layer. */
256
+ hasCoreApi;
257
+ _needsRefresh = true;
258
+ constructor(data, options, defaultOptions, coreApi) {
259
+ var _a;
260
+ if (defaultOptions) {
261
+ this.options = mergeOptions({ ...defaultOptions, core: _DataSource.defaultOptions }, options);
262
+ } else {
263
+ this.options = { ...options };
264
+ }
265
+ this.data = data;
266
+ this.url = typeof data === "string" ? resolvePath(data) : "";
267
+ const loadOptions = normalizeDirectLoaderOptions((_a = this.options.core) == null ? void 0 : _a.loadOptions);
268
+ this.loadOptions = loadOptions;
269
+ const fetch2 = getFetchFunction(loadOptions);
270
+ this.coreApi = coreApi || UNAVAILABLE_CORE_API;
271
+ this.hasCoreApi = Boolean(coreApi);
272
+ this.fetch = fetch2;
273
+ }
274
+ setProps(options) {
275
+ this.options = Object.assign(this.options, options);
276
+ this.setNeedsRefresh();
277
+ }
278
+ /** Mark this data source as needing a refresh (redraw) */
279
+ setNeedsRefresh() {
280
+ this._needsRefresh = true;
281
+ }
282
+ /**
283
+ * Does this data source need refreshing?
284
+ * @note The specifics of the refresh mechanism depends on type of data source
285
+ */
286
+ getNeedsRefresh(clear = true) {
287
+ const needsRefresh = this._needsRefresh;
288
+ if (clear) {
289
+ this._needsRefresh = false;
290
+ }
291
+ return needsRefresh;
292
+ }
293
+ /** Reports a source-level failure through the configured callback or the shared logger. */
294
+ reportError(error, message) {
295
+ var _a;
296
+ const normalizedError = normalizeError(error, message);
297
+ const callback = (_a = this.options.core) == null ? void 0 : _a.onError;
298
+ if (callback) {
299
+ callback(normalizedError, this);
300
+ } else {
301
+ log.warn(`${this.constructor.name}: ${normalizedError.message}`)();
302
+ }
303
+ return normalizedError;
304
+ }
305
+ };
306
+ function getFetchFunction(options) {
307
+ var _a, _b;
308
+ const fetchOption = (options == null ? void 0 : options.fetch) ?? ((_a = options == null ? void 0 : options.core) == null ? void 0 : _a.fetch);
309
+ let fetchFunction;
310
+ if (typeof fetchOption === "function") {
311
+ fetchFunction = (url, fetchOptions) => fetchOption(url, fetchOptions);
312
+ } else if (fetchOption) {
313
+ fetchFunction = (url, requestOptions) => fetch(url, mergeFetchOptions(fetchOption, requestOptions));
314
+ } else {
315
+ fetchFunction = (url, requestOptions) => fetch(url, requestOptions);
316
+ }
317
+ return createAuthenticatedFetch({
318
+ fetch: fetchFunction,
319
+ credentials: ((_b = options == null ? void 0 : options.core) == null ? void 0 : _b.credentials) || []
320
+ });
321
+ }
322
+ function mergeFetchOptions(fetchOptions, requestOptions) {
323
+ const mergedOptions = { ...fetchOptions, ...requestOptions };
324
+ if (fetchOptions.headers || (requestOptions == null ? void 0 : requestOptions.headers)) {
325
+ mergedOptions.headers = mergeHeaders(fetchOptions.headers, requestOptions == null ? void 0 : requestOptions.headers);
326
+ }
327
+ return mergedOptions;
328
+ }
329
+ function mergeHeaders(defaultHeaders, requestHeaders) {
330
+ const headers = new Headers(defaultHeaders);
331
+ if (requestHeaders) {
332
+ new Headers(requestHeaders).forEach((value, key) => headers.set(key, value));
333
+ }
334
+ return headers;
335
+ }
336
+ function normalizeDirectLoaderOptions(options) {
337
+ const loadOptions = { ...options };
338
+ if (options == null ? void 0 : options.core) {
339
+ loadOptions.core = { ...options.core };
340
+ }
341
+ const topLevelBaseUri = typeof loadOptions.baseUri === "string" ? loadOptions.baseUri : void 0;
342
+ const topLevelBaseUrl = typeof loadOptions.baseUrl === "string" ? loadOptions.baseUrl : void 0;
343
+ if (topLevelBaseUri !== void 0 || topLevelBaseUrl !== void 0) {
344
+ loadOptions.core ||= {};
345
+ if (loadOptions.core.baseUrl === void 0) {
346
+ loadOptions.core.baseUrl = topLevelBaseUrl ?? topLevelBaseUri;
347
+ }
348
+ delete loadOptions.baseUri;
349
+ delete loadOptions.baseUrl;
350
+ }
351
+ return loadOptions;
352
+ }
353
+ function normalizeError(error, message) {
354
+ if (error instanceof Error) {
355
+ return error;
356
+ }
357
+ if (typeof error === "string") {
358
+ return new Error(error);
359
+ }
360
+ return new Error(message);
361
+ }
362
+ function unavailableCoreApiMethod(methodName) {
363
+ return () => {
364
+ throw new Error(
365
+ `CoreAPI.${methodName} is unavailable. Use @loaders.gl/core.createDataSource().`
366
+ );
367
+ };
368
+ }
369
+
370
+ // ../loader-utils/src/lib/scan-utils/columnar-predicate.ts
371
+ function getColumnarPredicateColumns(predicate) {
372
+ return [...new Set(getColumnarPredicatePaths(predicate).map((path) => path[0]))];
373
+ }
374
+ function getColumnarPredicatePath(property) {
375
+ return typeof property.property === "string" ? [property.property] : [...property.property];
376
+ }
377
+ function getColumnarPredicatePaths(predicate) {
378
+ const paths = /* @__PURE__ */ new Map();
379
+ visitColumnarPredicate(predicate, (child) => {
380
+ if ("property" in child.args[0]) {
381
+ const path = getColumnarPredicatePath(child.args[0]);
382
+ paths.set(path.join("\0"), path);
383
+ }
384
+ });
385
+ return [...paths.values()];
386
+ }
387
+ function validateColumnarPredicate(predicate, availableColumns) {
388
+ visitColumnarPredicate(predicate, (child) => {
389
+ if (child.op === "and" || child.op === "or") {
390
+ if (child.args.length < 2)
391
+ throw new Error(`Columnar predicate ${child.op} requires at least two child predicates`);
392
+ return;
393
+ }
394
+ if (child.op === "not") return;
395
+ const leaf = child;
396
+ const path = getColumnarPredicatePath(leaf.args[0]);
397
+ if (!path.length || path.some((component) => !component)) {
398
+ throw new Error("Columnar predicate property path must contain non-empty strings");
399
+ }
400
+ if (!availableColumns.has(path[0]))
401
+ throw new Error(`Columnar predicate column not found: ${path.join(".")}`);
402
+ if (leaf.op === "in" && leaf.args[1].length === 0) {
403
+ throw new Error("Columnar predicate in requires at least one value");
404
+ }
405
+ });
406
+ }
407
+ function isColumnarPredicateParameter(value) {
408
+ const parameterValue = value;
409
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length === 1 && Object.hasOwn(value, "parameter") && typeof parameterValue.parameter === "string" && parameterValue.parameter.length > 0;
410
+ }
411
+ function isColumnarPredicateValue(value) {
412
+ return typeof value === "boolean" || typeof value === "bigint" || typeof value === "string" || typeof value === "number" && Number.isFinite(value) || value instanceof Date && Number.isFinite(value.getTime()) || value instanceof Uint8Array;
413
+ }
414
+ function bindColumnarPredicateParameters(predicate, parameters) {
415
+ switch (predicate.op) {
416
+ case "and":
417
+ case "or":
418
+ return {
419
+ op: predicate.op,
420
+ args: predicate.args.map((child) => bindColumnarPredicateParameters(child, parameters))
421
+ };
422
+ case "not":
423
+ return {
424
+ op: "not",
425
+ args: [bindColumnarPredicateParameters(predicate.args[0], parameters)]
426
+ };
427
+ case "isNull":
428
+ return { op: "isNull", args: [copyColumnarPredicateProperty(predicate.args[0])] };
429
+ case "in":
430
+ return {
431
+ op: "in",
432
+ args: [
433
+ copyColumnarPredicateProperty(predicate.args[0]),
434
+ predicate.args[1].map((value) => bindColumnarPredicateValue(value, parameters))
435
+ ]
436
+ };
437
+ default:
438
+ return {
439
+ op: predicate.op,
440
+ args: [
441
+ copyColumnarPredicateProperty(predicate.args[0]),
442
+ bindColumnarPredicateValue(predicate.args[1], parameters)
443
+ ]
444
+ };
445
+ }
446
+ }
447
+ function visitColumnarPredicate(predicate, visitor) {
448
+ visitor(predicate);
449
+ if (predicate.op === "and" || predicate.op === "or")
450
+ predicate.args.forEach((child) => visitColumnarPredicate(child, visitor));
451
+ else if (predicate.op === "not") visitColumnarPredicate(predicate.args[0], visitor);
452
+ }
453
+ function bindColumnarPredicateValue(value, parameters) {
454
+ if (!isColumnarPredicateParameter(value)) return value;
455
+ if (!Object.hasOwn(parameters, value.parameter)) {
456
+ throw new Error(`Columnar predicate parameter ":${value.parameter}" requires a value`);
457
+ }
458
+ const parameterValue = parameters[value.parameter];
459
+ if (isColumnarPredicateParameter(parameterValue)) {
460
+ throw new Error(
461
+ `Columnar predicate parameter ":${value.parameter}" cannot reference another parameter`
462
+ );
463
+ }
464
+ if (!isColumnarPredicateValue(parameterValue)) {
465
+ throw new Error(`Columnar predicate parameter ":${value.parameter}" has an unsupported value`);
466
+ }
467
+ return copyColumnarPredicateValue(parameterValue);
468
+ }
469
+ function copyColumnarPredicateProperty(property) {
470
+ return {
471
+ ...property,
472
+ property: typeof property.property === "string" ? property.property : [...property.property]
473
+ };
474
+ }
475
+ function copyColumnarPredicateValue(value) {
476
+ if (value instanceof Uint8Array) return value.slice();
477
+ if (value instanceof Date) return new Date(value.getTime());
478
+ return value;
479
+ }
480
+
481
+ // ../loader-utils/src/lib/scan-utils/scan-query-metadata.ts
482
+ var import_crs = require("@math.gl/crs");
483
+ function createScanQueryMetadata(options) {
484
+ validateScanExecutionSupport(options.queryType, options.execution);
485
+ const schema = Object.freeze({
486
+ fields: Object.freeze(
487
+ options.schema.fields.map(
488
+ (field) => Object.freeze({ ...field, metadata: Object.freeze({ ...field.metadata }) })
489
+ )
490
+ ),
491
+ metadata: Object.freeze({ ...options.schema.metadata })
492
+ });
493
+ const columns = schema.fields.map(
494
+ (field) => {
495
+ var _a;
496
+ return Object.freeze({
497
+ name: field.name,
498
+ type: field.type,
499
+ nullable: field.nullable !== false,
500
+ role: ((_a = options.columnRoles) == null ? void 0 : _a[field.name]) || "attribute",
501
+ title: getNonEmptyMetadataValue(field.metadata, "title"),
502
+ description: getNonEmptyMetadataValue(field.metadata, "description"),
503
+ metadata: field.metadata || Object.freeze({})
504
+ });
505
+ }
506
+ );
507
+ return Object.freeze({
508
+ sourceType: options.sourceType,
509
+ queryType: options.queryType,
510
+ execution: Object.freeze({ ...options.execution }),
511
+ name: options.name,
512
+ description: options.description,
513
+ schema,
514
+ columns: Object.freeze(columns),
515
+ capabilities: Object.freeze({ ...options.capabilities }),
516
+ spatial: options.spatial ? Object.freeze({
517
+ ...options.spatial,
518
+ bounds: options.spatial.bounds ? Object.freeze({
519
+ minimum: Object.freeze([...options.spatial.bounds.minimum]),
520
+ maximum: Object.freeze([...options.spatial.bounds.maximum])
521
+ }) : void 0,
522
+ coordinateReferenceSystems: options.spatial.coordinateReferenceSystems ? Object.freeze([...options.spatial.coordinateReferenceSystems]) : void 0,
523
+ spatialReference: options.spatial.spatialReference ? (0, import_crs.createSpatialReference)(options.spatial.spatialReference) : void 0
524
+ }) : void 0,
525
+ statistics: options.statistics ? Object.freeze({ ...options.statistics }) : void 0,
526
+ levels: options.levels ? Object.freeze(
527
+ options.levels.map(
528
+ (level) => Object.freeze({
529
+ ...level,
530
+ scale: level.scale ? Object.freeze([...level.scale]) : void 0
531
+ })
532
+ )
533
+ ) : void 0
534
+ });
535
+ }
536
+ function validateScanExecutionSupport(queryType, execution) {
537
+ if (execution.status === "metadata-only") {
538
+ if (!execution.reason.trim()) {
539
+ throw new Error("Metadata-only scan support requires a concrete reason");
540
+ }
541
+ return;
542
+ }
543
+ const validMethods = {
544
+ table: ["read", "query"],
545
+ raster: ["getRaster"],
546
+ "point-cloud": ["scan"]
547
+ };
548
+ if (!validMethods[queryType].includes(execution.method)) {
549
+ throw new Error(
550
+ `Scan execution method "${execution.method}" is not valid for ${queryType} queries`
551
+ );
552
+ }
553
+ }
554
+ function getNonEmptyMetadataValue(metadata, key) {
555
+ const value = metadata == null ? void 0 : metadata[key];
556
+ return value || void 0;
557
+ }
558
+
559
+ // ../loader-utils/src/lib/scan-utils/table-query.ts
560
+ function planTableQuery(sourceColumnNames, options = {}) {
561
+ validateTableQueryOptions(sourceColumnNames, options);
562
+ const outputColumnNames = options.columns ? [...options.columns] : [...sourceColumnNames];
563
+ const predicateColumnNames = options.predicate ? getColumnarPredicateColumns(options.predicate) : [];
564
+ const requiredColumnNames = /* @__PURE__ */ new Set([...outputColumnNames, ...predicateColumnNames]);
565
+ const scanColumnNames = sourceColumnNames.filter(
566
+ (columnName) => requiredColumnNames.has(columnName)
567
+ );
568
+ const steps = [
569
+ Object.freeze({ kind: "scan", columns: Object.freeze(scanColumnNames) })
570
+ ];
571
+ if (options.predicate) {
572
+ steps.push(Object.freeze({ kind: "filter", predicate: options.predicate }));
573
+ }
574
+ steps.push(Object.freeze({ kind: "project", columns: Object.freeze(outputColumnNames) }));
575
+ if (options.limit !== void 0) {
576
+ steps.push(Object.freeze({ kind: "limit", limit: options.limit }));
577
+ }
578
+ return Object.freeze(steps);
579
+ }
580
+ function validateTableQueryOptions(sourceColumnNames, options) {
581
+ const availableColumnNames = new Set(sourceColumnNames);
582
+ const outputColumnNames = options.columns ?? sourceColumnNames;
583
+ const seenColumnNames = /* @__PURE__ */ new Set();
584
+ for (const columnName of outputColumnNames) {
585
+ if (!availableColumnNames.has(columnName)) {
586
+ throw new Error(`Table query column not found: ${columnName}`);
587
+ }
588
+ if (seenColumnNames.has(columnName)) {
589
+ throw new Error(`Table query column was selected more than once: ${columnName}`);
590
+ }
591
+ seenColumnNames.add(columnName);
592
+ }
593
+ validateTableQueryLimit(options.limit);
594
+ if (options.predicate) {
595
+ validateColumnarPredicate(options.predicate, availableColumnNames);
596
+ }
597
+ }
598
+ function validateTableQueryLimit(limit) {
599
+ if (limit !== void 0 && (!Number.isSafeInteger(limit) || limit < 0)) {
600
+ throw new Error("Table query limit must be a non-negative safe integer.");
601
+ }
602
+ }
603
+
604
+ // ../loader-utils/src/lib/scan-utils/table-scan-batch.ts
605
+ function makeTableScanBatch(table) {
606
+ return { ...table, batchType: "data", length: table.data.numRows };
607
+ }
608
+
609
+ // ../loader-utils/src/lib/scan-utils/relational-query.ts
610
+ function planRelationalQuery(sourceColumnNames, options = {}) {
611
+ var _a, _b, _c, _d, _e, _f;
612
+ const available = new Set(sourceColumnNames);
613
+ const expressionNames = /* @__PURE__ */ new Set();
614
+ for (const expression of options.expressions || []) {
615
+ if (!expression.name) throw new Error("Relational expression names must be non-empty.");
616
+ if (available.has(expression.name) || expressionNames.has(expression.name)) {
617
+ throw new Error(`Relational expression duplicates column: ${expression.name}`);
618
+ }
619
+ expressionNames.add(expression.name);
620
+ }
621
+ const aggregateNames = new Set((options.aggregates || []).map((aggregate) => aggregate.name));
622
+ const requiredColumns = /* @__PURE__ */ new Set();
623
+ const availableColumns = new Set(sourceColumnNames);
624
+ for (const expression of options.expressions || []) {
625
+ const definition = expression.expression;
626
+ if (definition.op === "column") {
627
+ validateRelationalColumnReference(definition.column, availableColumns);
628
+ if (available.has(definition.column)) requiredColumns.add(definition.column);
629
+ }
630
+ if ("left" in definition) {
631
+ validateRelationalColumnReference(definition.left, availableColumns);
632
+ validateRelationalColumnReference(definition.right, availableColumns);
633
+ if (available.has(definition.left)) requiredColumns.add(definition.left);
634
+ if (available.has(definition.right)) requiredColumns.add(definition.right);
635
+ }
636
+ availableColumns.add(expression.name);
637
+ }
638
+ for (const key of options.orderBy || []) requiredColumns.add(key.column);
639
+ for (const key of options.groupBy || []) requiredColumns.add(key);
640
+ for (const aggregate of options.aggregates || []) {
641
+ if (aggregate.column) requiredColumns.add(aggregate.column);
642
+ }
643
+ const outputColumns = (_a = options.columns) == null ? void 0 : _a.filter(
644
+ (column) => !expressionNames.has(column) && !aggregateNames.has(column)
645
+ );
646
+ const tablePlan = [
647
+ ...planTableQuery(sourceColumnNames, {
648
+ ...options,
649
+ columns: outputColumns,
650
+ predicate: options.predicate
651
+ })
652
+ ];
653
+ const scanStep = tablePlan[0];
654
+ if ((scanStep == null ? void 0 : scanStep.kind) === "scan") {
655
+ const scanColumns = new Set(scanStep.columns);
656
+ for (const column of requiredColumns) {
657
+ if (available.has(column)) scanColumns.add(column);
658
+ }
659
+ tablePlan[0] = Object.freeze({ kind: "scan", columns: Object.freeze([...scanColumns]) });
660
+ }
661
+ for (const expression of expressionNames) available.add(expression);
662
+ for (const aggregate of aggregateNames) available.add(aggregate);
663
+ for (const key of options.orderBy || []) {
664
+ if (!available.has(key.column))
665
+ throw new Error(`Relational order column not found: ${key.column}`);
666
+ }
667
+ for (const key of options.groupBy || []) {
668
+ if (!available.has(key)) throw new Error(`Relational group column not found: ${key}`);
669
+ }
670
+ for (const aggregate of options.aggregates || []) {
671
+ if (!aggregate.name) throw new Error("Relational aggregate names must be non-empty.");
672
+ if (aggregate.function !== "count" && !aggregate.column) {
673
+ throw new Error(`Relational aggregate ${aggregate.function} requires a column.`);
674
+ }
675
+ if (aggregate.column && !available.has(aggregate.column)) {
676
+ throw new Error(`Relational aggregate column not found: ${aggregate.column}`);
677
+ }
678
+ }
679
+ const relationalSteps = [];
680
+ if ((_b = options.expressions) == null ? void 0 : _b.length)
681
+ relationalSteps.push({ kind: "expression", detail: options.expressions });
682
+ if ((_c = options.orderBy) == null ? void 0 : _c.length) relationalSteps.push({ kind: "order", detail: options.orderBy });
683
+ if (((_d = options.aggregates) == null ? void 0 : _d.length) || ((_e = options.groupBy) == null ? void 0 : _e.length)) {
684
+ relationalSteps.push({
685
+ kind: "aggregate",
686
+ detail: { groupBy: options.groupBy, aggregates: options.aggregates }
687
+ });
688
+ }
689
+ if ((_f = options.union) == null ? void 0 : _f.length) relationalSteps.push({ kind: "union", detail: options.union });
690
+ if (options.join) relationalSteps.push({ kind: "join", detail: options.join });
691
+ return { tablePlan, relationalSteps: Object.freeze(relationalSteps) };
692
+ }
693
+ function validateRelationalColumnReference(columnName, availableColumns) {
694
+ if (!availableColumns.has(columnName)) {
695
+ throw new Error(`Relational expression column not found: ${columnName}`);
696
+ }
697
+ }
698
+
699
+ // ../loader-utils/src/lib/scan-utils/table-query-explain.ts
700
+ function explainTableQuery(sourceColumnNames, options, capabilities) {
701
+ const plan = planTableQuery(sourceColumnNames, options);
702
+ const outputColumns = options.columns ? [...options.columns] : [...sourceColumnNames];
703
+ const predicateColumns = options.predicate ? getColumnarPredicateColumns(options.predicate) : [];
704
+ const requiredColumns = [...plan[0].kind === "scan" ? plan[0].columns : []];
705
+ return Object.freeze({
706
+ sourceColumns: Object.freeze([...sourceColumnNames]),
707
+ outputColumns: Object.freeze(outputColumns),
708
+ requiredColumns: Object.freeze(requiredColumns),
709
+ predicateColumns: Object.freeze(predicateColumns),
710
+ plan,
711
+ capabilities: Object.freeze({ ...capabilities }),
712
+ operators: Object.freeze({
713
+ projection: createOperatorExplanation(options.columns !== void 0, capabilities.projection),
714
+ predicate: createOperatorExplanation(options.predicate !== void 0, capabilities.predicate),
715
+ limit: createOperatorExplanation(options.limit !== void 0, capabilities.limit)
716
+ })
717
+ });
718
+ }
719
+ function createOperatorExplanation(enabled, support) {
720
+ return Object.freeze({ enabled, support });
721
+ }
722
+
723
+ // dist/sql-predicate-types.js
724
+ function isSQLPredicateParameter(value) {
725
+ return isColumnarPredicateParameter(value);
726
+ }
727
+
728
+ // dist/sql-predicate-schema.js
729
+ var MAXIMUM_PREDICATE_DEPTH = 64;
730
+ var MAXIMUM_PREDICATE_NODES = 4096;
731
+ var SQL_PREDICATE_JSON_SCHEMA = {
732
+ $schema: "https://json-schema.org/draft/2020-12/schema",
733
+ $id: "https://loaders.gl/schemas/sql-predicate.schema.json",
734
+ title: "loaders.gl SQL predicate",
735
+ oneOf: [
736
+ { $ref: "#/$defs/comparison" },
737
+ { $ref: "#/$defs/in" },
738
+ { $ref: "#/$defs/isNull" },
739
+ { $ref: "#/$defs/logical" },
740
+ { $ref: "#/$defs/not" }
741
+ ],
742
+ $defs: {
743
+ property: {
744
+ type: "object",
745
+ required: ["property"],
746
+ properties: {
747
+ property: { type: "string", minLength: 1 },
748
+ quoted: { type: "boolean" }
749
+ },
750
+ additionalProperties: false
751
+ },
752
+ value: {
753
+ oneOf: [
754
+ { type: ["boolean", "number", "string"] },
755
+ {
756
+ type: "object",
757
+ required: ["parameter"],
758
+ properties: { parameter: { type: "string", minLength: 1 } },
759
+ additionalProperties: false
760
+ }
761
+ ]
762
+ },
763
+ comparison: {
764
+ type: "object",
765
+ required: ["op", "args"],
766
+ properties: {
767
+ op: { enum: ["=", "<>", "<", "<=", ">", ">="] },
768
+ args: {
769
+ type: "array",
770
+ prefixItems: [{ $ref: "#/$defs/property" }, { $ref: "#/$defs/value" }],
771
+ minItems: 2,
772
+ maxItems: 2
773
+ }
774
+ },
775
+ additionalProperties: false
776
+ },
777
+ in: {
778
+ type: "object",
779
+ required: ["op", "args"],
780
+ properties: {
781
+ op: { const: "in" },
782
+ args: {
783
+ type: "array",
784
+ prefixItems: [
785
+ { $ref: "#/$defs/property" },
786
+ { type: "array", items: { $ref: "#/$defs/value" }, minItems: 1 }
787
+ ],
788
+ minItems: 2,
789
+ maxItems: 2
790
+ }
791
+ },
792
+ additionalProperties: false
793
+ },
794
+ isNull: {
795
+ type: "object",
796
+ required: ["op", "args"],
797
+ properties: {
798
+ op: { const: "isNull" },
799
+ args: {
800
+ type: "array",
801
+ prefixItems: [{ $ref: "#/$defs/property" }],
802
+ minItems: 1,
803
+ maxItems: 1
804
+ }
805
+ },
806
+ additionalProperties: false
807
+ },
808
+ logical: {
809
+ type: "object",
810
+ required: ["op", "args"],
811
+ properties: {
812
+ op: { enum: ["and", "or"] },
813
+ args: { type: "array", items: { $ref: "#" }, minItems: 2 }
814
+ },
815
+ additionalProperties: false
816
+ },
817
+ not: {
818
+ type: "object",
819
+ required: ["op", "args"],
820
+ properties: {
821
+ op: { const: "not" },
822
+ args: { type: "array", prefixItems: [{ $ref: "#" }], minItems: 1, maxItems: 1 }
823
+ },
824
+ additionalProperties: false
825
+ }
826
+ }
827
+ };
828
+ function isSQLPredicate(value) {
829
+ try {
830
+ validateSQLPredicate(value);
831
+ return true;
832
+ } catch {
833
+ return false;
834
+ }
835
+ }
836
+ function validateSQLPredicate(value) {
837
+ const state = { nodes: 0 };
838
+ validatePredicateNode(value, "$", 0, state);
839
+ }
840
+ function validatePredicateNode(value, path, depth, state) {
841
+ if (depth > MAXIMUM_PREDICATE_DEPTH) {
842
+ throw new Error(`SQL predicate ${path} exceeds the maximum nesting depth`);
843
+ }
844
+ state.nodes++;
845
+ if (state.nodes > MAXIMUM_PREDICATE_NODES) {
846
+ throw new Error("SQL predicate exceeds the maximum node count");
847
+ }
848
+ if (!isRecord(value) || !hasExactKeys(value, ["op", "args"])) {
849
+ throw new Error(`SQL predicate ${path} must contain only op and args`);
850
+ }
851
+ if (typeof value.op !== "string" || !Array.isArray(value.args)) {
852
+ throw new Error(`SQL predicate ${path} requires string op and array args`);
853
+ }
854
+ switch (value.op) {
855
+ case "and":
856
+ case "or":
857
+ if (value.args.length < 2) {
858
+ throw new Error(`SQL predicate ${path}.${value.op} requires at least two arguments`);
859
+ }
860
+ for (let index = 0; index < value.args.length; index++) {
861
+ validatePredicateNode(value.args[index], `${path}.args[${index}]`, depth + 1, state);
862
+ }
863
+ return;
864
+ case "not":
865
+ if (value.args.length !== 1) {
866
+ throw new Error(`SQL predicate ${path}.not requires exactly one argument`);
867
+ }
868
+ validatePredicateNode(value.args[0], `${path}.args[0]`, depth + 1, state);
869
+ return;
870
+ case "isNull":
871
+ if (value.args.length !== 1) {
872
+ throw new Error(`SQL predicate ${path}.isNull requires exactly one argument`);
873
+ }
874
+ validatePredicateProperty(value.args[0], `${path}.args[0]`);
875
+ return;
876
+ case "in":
877
+ if (value.args.length !== 2 || !Array.isArray(value.args[1]) || value.args[1].length === 0) {
878
+ throw new Error(`SQL predicate ${path}.in requires a property and non-empty value list`);
879
+ }
880
+ validatePredicateProperty(value.args[0], `${path}.args[0]`);
881
+ value.args[1].forEach((item, index) => validatePredicateValue(item, `${path}.args[1][${index}]`));
882
+ return;
883
+ case "=":
884
+ case "<>":
885
+ case "<":
886
+ case "<=":
887
+ case ">":
888
+ case ">=":
889
+ if (value.args.length !== 2) {
890
+ throw new Error(`SQL predicate ${path}.${value.op} requires exactly two arguments`);
891
+ }
892
+ validatePredicateProperty(value.args[0], `${path}.args[0]`);
893
+ validatePredicateValue(value.args[1], `${path}.args[1]`);
894
+ return;
895
+ default:
896
+ throw new Error(`SQL predicate ${path} has unsupported operator ${JSON.stringify(value.op)}`);
897
+ }
898
+ }
899
+ function validatePredicateProperty(value, path) {
900
+ if (!isRecord(value) || !hasAllowedKeys(value, ["property", "quoted"]) || typeof value.property !== "string" || value.property.length === 0 || value.quoted !== void 0 && typeof value.quoted !== "boolean") {
901
+ throw new Error(`SQL predicate ${path} requires a non-empty property reference`);
902
+ }
903
+ }
904
+ function validatePredicateValue(value, path) {
905
+ if (isSQLPredicateParameter(value)) {
906
+ return;
907
+ }
908
+ if (typeof value === "boolean" || typeof value === "bigint" || typeof value === "string" || value instanceof Uint8Array) {
909
+ return;
910
+ }
911
+ if (typeof value === "number" && Number.isFinite(value)) {
912
+ return;
913
+ }
914
+ if (value instanceof Date && Number.isFinite(value.getTime())) {
915
+ return;
916
+ }
917
+ throw new Error(`SQL predicate ${path} contains an unsupported scalar value`);
918
+ }
919
+ function isRecord(value) {
920
+ return typeof value === "object" && value !== null && !Array.isArray(value);
921
+ }
922
+ function hasExactKeys(value, expectedKeys) {
923
+ const keys = Object.keys(value);
924
+ return keys.length === expectedKeys.length && expectedKeys.every((key) => keys.includes(key));
925
+ }
926
+ function hasAllowedKeys(value, allowedKeys) {
927
+ return Object.keys(value).every((key) => allowedKeys.includes(key));
928
+ }
929
+
930
+ // dist/compile-table-query.js
931
+ function compileSQLTableQuery(query, options) {
932
+ validateSQLTableQuery(query);
933
+ const context = {
934
+ dialect: options.dialect,
935
+ namedParameters: options.parameters,
936
+ parameters: []
937
+ };
938
+ return {
939
+ sql: compileTableStatement(query, context),
940
+ parameters: context.parameters
941
+ };
942
+ }
943
+ function compileTableStatement(query, context) {
944
+ var _a, _b;
945
+ const projection = compileProjection(query);
946
+ const table = [query.catalogName, query.schemaName, query.tableName].filter((identifier) => identifier !== void 0).map(quoteSQLIdentifier).join(".");
947
+ const fromClause = query.join ? compileJoinFromClause(query, table, context) : `FROM ${table}`;
948
+ const clauses = [`SELECT ${projection}`, fromClause];
949
+ if (query.predicate) {
950
+ clauses.push(`WHERE ${compileSQLPredicate(query.predicate, context)}`);
951
+ }
952
+ if ((_a = query.groupBy) == null ? void 0 : _a.length) {
953
+ clauses.push(`GROUP BY ${query.groupBy.map(quoteSQLIdentifier).join(", ")}`);
954
+ }
955
+ let sql = clauses.join("\n");
956
+ for (const child of query.union || []) {
957
+ const childQuery = {
958
+ tableName: child.source,
959
+ ...child.query || {}
960
+ };
961
+ validateSQLTableQuery(childQuery);
962
+ const childSQL = compileTableStatement(childQuery, context);
963
+ const branchSQL = hasBranchLocalModifiers(childQuery) ? `(${childSQL})` : childSQL;
964
+ sql = `${sql}
965
+ UNION ALL
966
+ ${branchSQL}`;
967
+ }
968
+ if ((_b = query.orderBy) == null ? void 0 : _b.length)
969
+ sql += `
970
+ ORDER BY ${query.orderBy.map(compileOrderKey).join(", ")}`;
971
+ if (query.limit !== void 0)
972
+ sql += `
973
+ LIMIT ${query.limit}`;
974
+ return sql;
975
+ }
976
+ function compileJoinFromClause(query, table, context) {
977
+ const join = query.join;
978
+ if (!join)
979
+ return `FROM ${table}`;
980
+ validateSQLIdentifier(join.child.source);
981
+ validateSQLIdentifier(join.left);
982
+ validateSQLIdentifier(join.right);
983
+ const childTable = quoteSQLIdentifier(join.child.source);
984
+ const rightRelation = join.child.query ? `(${compileTableStatement({ tableName: join.child.source, ...join.child.query }, context)})` : childTable;
985
+ return `FROM ${table} JOIN ${rightRelation} AS ${childTable} ON ${table}.${quoteSQLIdentifier(join.left)} = ${childTable}.${quoteSQLIdentifier(join.right)}`;
986
+ }
987
+ function compileProjection(query) {
988
+ var _a, _b;
989
+ const expressions = query.expressions || [];
990
+ const expressionByName = new Map(expressions.map((expression) => [expression.name, expression]));
991
+ const aggregates = query.aggregates || [];
992
+ const aggregateByName = new Map(aggregates.map((aggregate) => [aggregate.name, aggregate]));
993
+ const columns = query.columns === void 0 ? void 0 : [...query.columns];
994
+ const projectionColumns = columns || (((_a = query.groupBy) == null ? void 0 : _a.length) || ((_b = query.aggregates) == null ? void 0 : _b.length) ? [...query.groupBy || []] : []);
995
+ const selections = projectionColumns.map((column) => {
996
+ const expression = expressionByName.get(column);
997
+ if (expression) {
998
+ return `${compileRelationalExpression(expression.expression)} AS ${quoteSQLIdentifier(expression.name)}`;
999
+ }
1000
+ const aggregate = aggregateByName.get(column);
1001
+ return aggregate ? `${compileAggregate(aggregate)} AS ${quoteSQLIdentifier(aggregate.name)}` : compileProjectionColumn(column, query);
1002
+ });
1003
+ if (!selections.length)
1004
+ return expressions.length ? expressions.map((expression) => `${compileRelationalExpression(expression.expression)} AS ${quoteSQLIdentifier(expression.name)}`).join(", ") : aggregates.length ? aggregates.map((aggregate) => `${compileAggregate(aggregate)} AS ${quoteSQLIdentifier(aggregate.name)}`).join(", ") : "*";
1005
+ return selections.join(", ");
1006
+ }
1007
+ function compileProjectionColumn(column, query) {
1008
+ var _a;
1009
+ const childSource = (_a = query.join) == null ? void 0 : _a.child.source;
1010
+ return childSource && column.startsWith(`${childSource}.`) ? column.split(".").map(quoteSQLIdentifier).join(".") : quoteSQLIdentifier(column);
1011
+ }
1012
+ function hasBranchLocalModifiers(query) {
1013
+ var _a, _b;
1014
+ return Boolean(query.limit !== void 0 || ((_a = query.orderBy) == null ? void 0 : _a.length) || ((_b = query.union) == null ? void 0 : _b.length));
1015
+ }
1016
+ function compileRelationalExpression(expression) {
1017
+ switch (expression.op) {
1018
+ case "column":
1019
+ return quoteSQLIdentifier(expression.column);
1020
+ case "literal":
1021
+ return expression.value === null ? "NULL" : typeof expression.value === "string" ? `'${expression.value.replace(/'/g, "''")}'` : String(expression.value);
1022
+ case "add":
1023
+ return `(${quoteSQLIdentifier(expression.left)} + ${quoteSQLIdentifier(expression.right)})`;
1024
+ case "subtract":
1025
+ return `(${quoteSQLIdentifier(expression.left)} - ${quoteSQLIdentifier(expression.right)})`;
1026
+ case "multiply":
1027
+ return `(${quoteSQLIdentifier(expression.left)} * ${quoteSQLIdentifier(expression.right)})`;
1028
+ case "divide":
1029
+ return `(${quoteSQLIdentifier(expression.left)} / NULLIF(${quoteSQLIdentifier(expression.right)}, 0))`;
1030
+ }
1031
+ }
1032
+ function compileAggregate(aggregate) {
1033
+ const column = aggregate.column ? quoteSQLIdentifier(aggregate.column) : "*";
1034
+ return `${aggregate.function.toUpperCase()}(${column})`;
1035
+ }
1036
+ function compileOrderKey(orderKey) {
1037
+ var _a;
1038
+ const direction = ((_a = orderKey.direction) == null ? void 0 : _a.toUpperCase()) || "ASC";
1039
+ const nulls = orderKey.nulls ? ` NULLS ${orderKey.nulls.toUpperCase()}` : "";
1040
+ return `${quoteSQLIdentifier(orderKey.column)} ${direction}${nulls}`;
1041
+ }
1042
+ function compileSQLPredicate(predicate, context) {
1043
+ switch (predicate.op) {
1044
+ case "and":
1045
+ case "or":
1046
+ return `(${predicate.args.map((child) => compileSQLPredicate(child, context)).join(` ${predicate.op.toUpperCase()} `)})`;
1047
+ case "not":
1048
+ return `(NOT ${compileSQLPredicate(predicate.args[0], context)})`;
1049
+ case "isNull":
1050
+ return `(${quoteSQLProperty(predicate.args[0])} IS NULL)`;
1051
+ case "in":
1052
+ return `(${quoteSQLProperty(predicate.args[0])} IN (${predicate.args[1].map((value) => compileSQLPredicateValue(value, context)).join(", ")}))`;
1053
+ default:
1054
+ return `(${quoteSQLProperty(predicate.args[0])} ${predicate.op} ${compileSQLPredicateValue(predicate.args[1], context)})`;
1055
+ }
1056
+ }
1057
+ function compileSQLPredicateValue(value, context) {
1058
+ const scalar = isSQLPredicateParameter(value) ? resolveSQLPredicateParameter(value.parameter, context.namedParameters) : value;
1059
+ context.parameters.push(scalar);
1060
+ return getSQLPlaceholder(context.dialect, context.parameters.length);
1061
+ }
1062
+ function resolveSQLPredicateParameter(parameterName, parameters) {
1063
+ if (!parameters || !Object.hasOwn(parameters, parameterName)) {
1064
+ throw new Error(`SQL predicate parameter ":${parameterName}" requires a value`);
1065
+ }
1066
+ const value = parameters[parameterName];
1067
+ validateSQLPredicate({ op: "=", args: [{ property: "_parameter" }, value] });
1068
+ return value;
1069
+ }
1070
+ function getSQLPlaceholder(_dialect, _position) {
1071
+ return "?";
1072
+ }
1073
+ function quoteSQLProperty(property) {
1074
+ return property.quoted ? quoteSQLIdentifier(property.property) : property.property.split(".").map(quoteSQLIdentifier).join(".");
1075
+ }
1076
+ function quoteSQLIdentifier(identifier) {
1077
+ validateSQLIdentifier(identifier);
1078
+ return `"${identifier.replace(/"/g, '""')}"`;
1079
+ }
1080
+ function validateSQLTableQuery(query) {
1081
+ var _a;
1082
+ validateSQLIdentifier(query.tableName);
1083
+ if (query.schemaName !== void 0)
1084
+ validateSQLIdentifier(query.schemaName);
1085
+ if (query.catalogName !== void 0)
1086
+ validateSQLIdentifier(query.catalogName);
1087
+ const seenColumns = /* @__PURE__ */ new Set();
1088
+ if (((_a = query.columns) == null ? void 0 : _a.length) === 0) {
1089
+ throw new Error("SQL table-query projections must select at least one column.");
1090
+ }
1091
+ for (const column of query.columns ?? []) {
1092
+ validateSQLIdentifier(column);
1093
+ if (seenColumns.has(column)) {
1094
+ throw new Error(`Table query column was selected more than once: ${column}`);
1095
+ }
1096
+ seenColumns.add(column);
1097
+ }
1098
+ if (query.limit !== void 0 && (!Number.isSafeInteger(query.limit) || query.limit < 0)) {
1099
+ throw new Error("Table query limit must be a non-negative safe integer.");
1100
+ }
1101
+ if (query.predicate)
1102
+ validateSQLPredicate(query.predicate);
1103
+ validateRelationalQuery(query);
1104
+ }
1105
+ function validateRelationalQuery(query) {
1106
+ const expressionNames = /* @__PURE__ */ new Set();
1107
+ for (const expression of query.expressions || []) {
1108
+ validateSQLIdentifier(expression.name);
1109
+ if (expressionNames.has(expression.name))
1110
+ throw new Error(`Relational expression duplicates column: ${expression.name}`);
1111
+ expressionNames.add(expression.name);
1112
+ const definition = expression.expression;
1113
+ if (definition.op === "column")
1114
+ validateSQLIdentifier(definition.column);
1115
+ if ("left" in definition) {
1116
+ validateSQLIdentifier(definition.left);
1117
+ validateSQLIdentifier(definition.right);
1118
+ }
1119
+ }
1120
+ for (const column of query.groupBy || [])
1121
+ validateSQLIdentifier(column);
1122
+ for (const key of query.orderBy || []) {
1123
+ validateSQLIdentifier(key.column);
1124
+ if (key.direction && key.direction !== "asc" && key.direction !== "desc")
1125
+ throw new Error(`Invalid order direction: ${key.direction}`);
1126
+ if (key.nulls && key.nulls !== "first" && key.nulls !== "last")
1127
+ throw new Error(`Invalid null placement: ${key.nulls}`);
1128
+ }
1129
+ for (const aggregate of query.aggregates || []) {
1130
+ validateSQLIdentifier(aggregate.name);
1131
+ if (aggregate.function !== "count" && !aggregate.column)
1132
+ throw new Error(`Relational aggregate ${aggregate.function} requires a column.`);
1133
+ if (aggregate.column)
1134
+ validateSQLIdentifier(aggregate.column);
1135
+ }
1136
+ }
1137
+ function validateSQLIdentifier(identifier) {
1138
+ if (!identifier || identifier.includes("\0")) {
1139
+ throw new Error("SQL table-query identifiers must be non-empty and cannot contain NUL bytes.");
1140
+ }
1141
+ }
1142
+
1143
+ // dist/sql-utils.js
1144
+ var arrow5 = __toESM(require("apache-arrow"), 1);
1145
+
1146
+ // ../schema-utils/src/lib/schema/data-type.ts
1147
+ function getDataTypeFromValue(value, defaultNumberType = "float32") {
1148
+ if (value instanceof Date) {
1149
+ return "date-millisecond";
1150
+ }
1151
+ if (typeof value === "number") {
1152
+ return defaultNumberType;
1153
+ }
1154
+ if (typeof value === "boolean") {
1155
+ return "bool";
1156
+ }
1157
+ if (typeof value === "string") {
1158
+ return "utf8";
1159
+ }
1160
+ if (value === null || value === "undefined") {
1161
+ return "null";
1162
+ }
1163
+ return "null";
1164
+ }
1165
+ function getDataTypeFromArray(array) {
1166
+ let type = getDataTypeFromTypedArray(array);
1167
+ if (type !== "null") {
1168
+ return { type, nullable: false };
1169
+ }
1170
+ if (array.length > 0) {
1171
+ type = getDataTypeFromValue(array[0]);
1172
+ return { type, nullable: true };
1173
+ }
1174
+ return { type: "null", nullable: true };
1175
+ }
1176
+ function getDataTypeFromTypedArray(array) {
1177
+ switch (array.constructor) {
1178
+ case Int8Array:
1179
+ return "int8";
1180
+ case Uint8Array:
1181
+ case Uint8ClampedArray:
1182
+ return "uint8";
1183
+ case Int16Array:
1184
+ return "int16";
1185
+ case Uint16Array:
1186
+ return "uint16";
1187
+ case Int32Array:
1188
+ return "int32";
1189
+ case Uint32Array:
1190
+ return "uint32";
1191
+ case Float32Array:
1192
+ return "float32";
1193
+ case Float64Array:
1194
+ return "float64";
1195
+ default:
1196
+ return "null";
1197
+ }
1198
+ }
1199
+ function getArrayTypeFromDataType(type, nullable) {
1200
+ if (!nullable) {
1201
+ switch (type) {
1202
+ case "int8":
1203
+ return Int8Array;
1204
+ case "uint8":
1205
+ return Uint8Array;
1206
+ case "int16":
1207
+ return Int16Array;
1208
+ case "uint16":
1209
+ return Uint16Array;
1210
+ case "int32":
1211
+ return Int32Array;
1212
+ case "uint32":
1213
+ return Uint32Array;
1214
+ case "float32":
1215
+ return Float32Array;
1216
+ case "float64":
1217
+ return Float64Array;
1218
+ default:
1219
+ break;
1220
+ }
1221
+ }
1222
+ return Array;
1223
+ }
1224
+
1225
+ // ../schema-utils/src/lib/schema/convert-arrow-schema.ts
1226
+ var arrow = __toESM(require("apache-arrow"), 1);
1227
+ function convertArrowToSchema(arrowSchema) {
1228
+ return serializeArrowSchema(arrowSchema);
1229
+ }
1230
+ function convertSchemaToArrow(schema, options) {
1231
+ return deserializeArrowSchema(schema, options);
1232
+ }
1233
+ function serializeArrowSchema(arrowSchema) {
1234
+ return {
1235
+ fields: arrowSchema.fields.map((arrowField) => serializeArrowField(arrowField)),
1236
+ metadata: serializeArrowMetadata(arrowSchema.metadata)
1237
+ };
1238
+ }
1239
+ function deserializeArrowSchema(schema, options) {
1240
+ return new arrow.Schema(
1241
+ schema.fields.map((field) => deserializeArrowField(field, options)),
1242
+ deserializeArrowMetadata(schema.metadata)
1243
+ );
1244
+ }
1245
+ function serializeArrowMetadata(arrowMetadata) {
1246
+ return Object.fromEntries(arrowMetadata);
1247
+ }
1248
+ function deserializeArrowMetadata(metadata) {
1249
+ return metadata ? new Map(Object.entries(metadata)) : /* @__PURE__ */ new Map();
1250
+ }
1251
+ function serializeArrowField(field) {
1252
+ return {
1253
+ name: field.name,
1254
+ type: serializeArrowType(field.type),
1255
+ nullable: field.nullable,
1256
+ metadata: serializeArrowMetadata(field.metadata)
1257
+ };
1258
+ }
1259
+ function deserializeArrowField(field, options) {
1260
+ return new arrow.Field(
1261
+ field.name,
1262
+ deserializeArrowType(field.type, options),
1263
+ field.nullable,
1264
+ deserializeArrowMetadata(field.metadata)
1265
+ );
1266
+ }
1267
+ function serializeArrowType(arrowType) {
1268
+ if (isArrowViewType(arrowType, "BinaryView")) {
1269
+ return "binary-view";
1270
+ }
1271
+ if (isArrowViewType(arrowType, "Utf8View")) {
1272
+ return "utf8-view";
1273
+ }
1274
+ switch (arrowType.constructor) {
1275
+ case arrow.Null:
1276
+ return "null";
1277
+ case arrow.Binary:
1278
+ return "binary";
1279
+ case arrow.FixedSizeBinary:
1280
+ return {
1281
+ type: "fixed-size-binary",
1282
+ byteWidth: arrowType.byteWidth
1283
+ };
1284
+ case arrow.Bool:
1285
+ return "bool";
1286
+ case arrow.Int:
1287
+ const intType = arrowType;
1288
+ return `${intType.isSigned ? "" : "u"}int${intType.bitWidth}`;
1289
+ case arrow.Int8:
1290
+ return "int8";
1291
+ case arrow.Int16:
1292
+ return "int16";
1293
+ case arrow.Int32:
1294
+ return "int32";
1295
+ case arrow.Int64:
1296
+ return "int64";
1297
+ case arrow.Uint8:
1298
+ return "uint8";
1299
+ case arrow.Uint16:
1300
+ return "uint16";
1301
+ case arrow.Uint32:
1302
+ return "uint32";
1303
+ case arrow.Uint64:
1304
+ return "uint64";
1305
+ case arrow.Float:
1306
+ const precision = arrowType.precision;
1307
+ switch (precision) {
1308
+ case arrow.Precision.HALF:
1309
+ return "float16";
1310
+ case arrow.Precision.SINGLE:
1311
+ return "float32";
1312
+ case arrow.Precision.DOUBLE:
1313
+ return "float64";
1314
+ default:
1315
+ return "float16";
1316
+ }
1317
+ case arrow.Float16:
1318
+ return "float16";
1319
+ case arrow.Float32:
1320
+ return "float32";
1321
+ case arrow.Float64:
1322
+ return "float64";
1323
+ case arrow.Utf8:
1324
+ return "utf8";
1325
+ case arrow.Decimal:
1326
+ const decimal = arrowType;
1327
+ return {
1328
+ type: "decimal",
1329
+ bitWidth: decimal.bitWidth,
1330
+ precision: decimal.precision,
1331
+ scale: decimal.scale
1332
+ };
1333
+ case arrow.Date_:
1334
+ const dateUnit = arrowType.unit;
1335
+ return dateUnit === arrow.DateUnit.DAY ? "date-day" : "date-millisecond";
1336
+ case arrow.DateDay:
1337
+ return "date-day";
1338
+ case arrow.DateMillisecond:
1339
+ return "date-millisecond";
1340
+ case arrow.Time:
1341
+ const timeUnit = arrowType.unit;
1342
+ switch (timeUnit) {
1343
+ case arrow.TimeUnit.SECOND:
1344
+ return "time-second";
1345
+ case arrow.TimeUnit.MILLISECOND:
1346
+ return "time-millisecond";
1347
+ case arrow.TimeUnit.MICROSECOND:
1348
+ return "time-microsecond";
1349
+ case arrow.TimeUnit.NANOSECOND:
1350
+ return "time-nanosecond";
1351
+ default:
1352
+ return "time-second";
1353
+ }
1354
+ case arrow.TimeMillisecond:
1355
+ return "time-millisecond";
1356
+ case arrow.TimeSecond:
1357
+ return "time-second";
1358
+ case arrow.TimeMicrosecond:
1359
+ return "time-microsecond";
1360
+ case arrow.TimeNanosecond:
1361
+ return "time-nanosecond";
1362
+ case arrow.Timestamp:
1363
+ const timeStampUnit = arrowType.unit;
1364
+ switch (timeStampUnit) {
1365
+ case arrow.TimeUnit.SECOND:
1366
+ return "timestamp-second";
1367
+ case arrow.TimeUnit.MILLISECOND:
1368
+ return "timestamp-millisecond";
1369
+ case arrow.TimeUnit.MICROSECOND:
1370
+ return "timestamp-microsecond";
1371
+ case arrow.TimeUnit.NANOSECOND:
1372
+ return "timestamp-nanosecond";
1373
+ default:
1374
+ return "timestamp-second";
1375
+ }
1376
+ case arrow.TimestampSecond:
1377
+ return "timestamp-second";
1378
+ case arrow.TimestampMillisecond:
1379
+ return "timestamp-millisecond";
1380
+ case arrow.TimestampMicrosecond:
1381
+ return "timestamp-microsecond";
1382
+ case arrow.TimestampNanosecond:
1383
+ return "timestamp-nanosecond";
1384
+ case arrow.Interval:
1385
+ const intervalUnit = arrowType.unit;
1386
+ switch (intervalUnit) {
1387
+ case arrow.IntervalUnit.DAY_TIME:
1388
+ return "interval-daytime";
1389
+ case arrow.IntervalUnit.YEAR_MONTH:
1390
+ return "interval-yearmonth";
1391
+ default:
1392
+ return "interval-daytime";
1393
+ }
1394
+ case arrow.IntervalDayTime:
1395
+ return "interval-daytime";
1396
+ case arrow.IntervalYearMonth:
1397
+ return "interval-yearmonth";
1398
+ case arrow.Map_:
1399
+ const mapType = arrowType;
1400
+ return {
1401
+ type: "map",
1402
+ keysSorted: mapType.keysSorted,
1403
+ children: mapType.children.map((arrowField) => serializeArrowField(arrowField))
1404
+ };
1405
+ case arrow.List:
1406
+ const listType = arrowType;
1407
+ const listField = listType.valueField;
1408
+ return {
1409
+ type: "list",
1410
+ children: [serializeArrowField(listField)]
1411
+ };
1412
+ case arrow.FixedSizeList:
1413
+ const fixedSizeList = arrowType;
1414
+ return {
1415
+ type: "fixed-size-list",
1416
+ listSize: fixedSizeList.listSize,
1417
+ children: [serializeArrowField(fixedSizeList.children[0])]
1418
+ };
1419
+ case arrow.Struct:
1420
+ const structType = arrowType;
1421
+ return {
1422
+ type: "struct",
1423
+ children: structType.children.map((arrowField) => serializeArrowField(arrowField))
1424
+ };
1425
+ case arrow.Dictionary:
1426
+ const dictionaryType = arrowType;
1427
+ return {
1428
+ type: "dictionary",
1429
+ id: dictionaryType.id,
1430
+ indices: serializeArrowDictionaryKeyType(dictionaryType.indices),
1431
+ dictionary: serializeArrowType(dictionaryType.dictionary),
1432
+ isOrdered: dictionaryType.isOrdered
1433
+ };
1434
+ default:
1435
+ throw new Error(`arrow type not supported: ${arrowType.constructor.name}`);
1436
+ }
1437
+ }
1438
+ function deserializeArrowType(dataType, options) {
1439
+ if (typeof dataType === "object") {
1440
+ switch (dataType.type) {
1441
+ case "decimal":
1442
+ return new arrow.Decimal(dataType.scale, dataType.precision, dataType.bitWidth);
1443
+ case "map": {
1444
+ const children = dataType.children.map(
1445
+ (arrowField) => deserializeArrowField(arrowField, options)
1446
+ );
1447
+ return new arrow.Map_(children[0], dataType.keysSorted);
1448
+ }
1449
+ case "list": {
1450
+ const field = deserializeArrowField(dataType.children[0], options);
1451
+ return new arrow.List(field);
1452
+ }
1453
+ case "fixed-size-list": {
1454
+ const child = deserializeArrowField(dataType.children[0], options);
1455
+ return new arrow.FixedSizeList(dataType.listSize, child);
1456
+ }
1457
+ case "fixed-size-binary":
1458
+ return new arrow.FixedSizeBinary(dataType.byteWidth);
1459
+ case "struct": {
1460
+ const children = dataType.children.map(
1461
+ (arrowField) => deserializeArrowField(arrowField, options)
1462
+ );
1463
+ return new arrow.Struct(children);
1464
+ }
1465
+ case "dictionary": {
1466
+ return new arrow.Dictionary(
1467
+ deserializeArrowType(dataType.dictionary, options),
1468
+ deserializeArrowDictionaryKeyType(dataType.indices),
1469
+ dataType.id,
1470
+ dataType.isOrdered
1471
+ );
1472
+ }
1473
+ default:
1474
+ throw new Error("array type not supported");
1475
+ }
1476
+ }
1477
+ switch (dataType) {
1478
+ case "null":
1479
+ return new arrow.Null();
1480
+ case "binary":
1481
+ return makeVariableWidthArrowType("BinaryView", new arrow.Binary(), options);
1482
+ case "binary-view":
1483
+ return makeRequiredArrowViewType("BinaryView");
1484
+ case "bool":
1485
+ return new arrow.Bool();
1486
+ case "int8":
1487
+ return new arrow.Int8();
1488
+ case "int16":
1489
+ return new arrow.Int16();
1490
+ case "int32":
1491
+ return new arrow.Int32();
1492
+ case "int64":
1493
+ return new arrow.Int64();
1494
+ case "uint8":
1495
+ return new arrow.Uint8();
1496
+ case "uint16":
1497
+ return new arrow.Uint16();
1498
+ case "uint32":
1499
+ return new arrow.Uint32();
1500
+ case "uint64":
1501
+ return new arrow.Uint64();
1502
+ case "float16":
1503
+ return new arrow.Float16();
1504
+ case "float32":
1505
+ return new arrow.Float32();
1506
+ case "float64":
1507
+ return new arrow.Float64();
1508
+ case "utf8":
1509
+ return makeVariableWidthArrowType("Utf8View", new arrow.Utf8(), options);
1510
+ case "utf8-view":
1511
+ return makeRequiredArrowViewType("Utf8View");
1512
+ case "date-day":
1513
+ return new arrow.DateDay();
1514
+ case "date-millisecond":
1515
+ return new arrow.DateMillisecond();
1516
+ case "time-second":
1517
+ return new arrow.TimeSecond();
1518
+ case "time-millisecond":
1519
+ return new arrow.TimeMillisecond();
1520
+ case "time-microsecond":
1521
+ return new arrow.TimeMicrosecond();
1522
+ case "time-nanosecond":
1523
+ return new arrow.TimeNanosecond();
1524
+ case "timestamp-second":
1525
+ return new arrow.TimestampSecond();
1526
+ case "timestamp-millisecond":
1527
+ return new arrow.TimestampMillisecond();
1528
+ case "timestamp-microsecond":
1529
+ return new arrow.TimestampMicrosecond();
1530
+ case "timestamp-nanosecond":
1531
+ return new arrow.TimestampNanosecond();
1532
+ case "interval-daytime":
1533
+ return new arrow.IntervalDayTime();
1534
+ case "interval-yearmonth":
1535
+ return new arrow.IntervalYearMonth();
1536
+ default:
1537
+ throw new Error("array type not supported");
1538
+ }
1539
+ }
1540
+ function getArrowViewConstructors() {
1541
+ return arrow;
1542
+ }
1543
+ function isArrowViewType(arrowType, viewTypeName) {
1544
+ const constructor = getArrowViewConstructors()[viewTypeName];
1545
+ if (constructor && arrowType instanceof constructor) {
1546
+ return true;
1547
+ }
1548
+ const guards = arrow.DataType;
1549
+ const guard = viewTypeName === "BinaryView" ? guards.isBinaryView : guards.isUtf8View;
1550
+ return Boolean(guard == null ? void 0 : guard(arrowType));
1551
+ }
1552
+ function makeVariableWidthArrowType(viewTypeName, fallbackType, options) {
1553
+ const viewTypeMode = (options == null ? void 0 : options.viewTypes) || "never";
1554
+ if (viewTypeMode === "never") {
1555
+ return fallbackType;
1556
+ }
1557
+ const constructor = getArrowViewConstructors()[viewTypeName];
1558
+ if (constructor) {
1559
+ return new constructor();
1560
+ }
1561
+ if (viewTypeMode === "require") {
1562
+ throw new Error(
1563
+ `${viewTypeName} requires apache-arrow 21.2.0 or later; the installed runtime does not support it`
1564
+ );
1565
+ }
1566
+ return fallbackType;
1567
+ }
1568
+ function makeRequiredArrowViewType(viewTypeName) {
1569
+ const constructor = getArrowViewConstructors()[viewTypeName];
1570
+ if (!constructor) {
1571
+ throw new Error(
1572
+ `${viewTypeName} requires apache-arrow 21.2.0 or later; the installed runtime does not support it`
1573
+ );
1574
+ }
1575
+ return new constructor();
1576
+ }
1577
+ function serializeArrowDictionaryKeyType(arrowType) {
1578
+ if (arrowType instanceof arrow.Int) {
1579
+ const prefix = arrowType.isSigned ? "int" : "uint";
1580
+ const keyType = `${prefix}${arrowType.bitWidth}`;
1581
+ if (isSchemaDictionaryKeyType(keyType)) {
1582
+ return keyType;
1583
+ }
1584
+ }
1585
+ switch (arrowType.constructor) {
1586
+ case arrow.Int8:
1587
+ return "int8";
1588
+ case arrow.Int16:
1589
+ return "int16";
1590
+ case arrow.Int32:
1591
+ return "int32";
1592
+ case arrow.Uint8:
1593
+ return "uint8";
1594
+ case arrow.Uint16:
1595
+ return "uint16";
1596
+ case arrow.Uint32:
1597
+ return "uint32";
1598
+ default:
1599
+ throw new Error(`arrow dictionary index type not supported: ${arrowType.constructor.name}`);
1600
+ }
1601
+ }
1602
+ function isSchemaDictionaryKeyType(keyType) {
1603
+ return ["int8", "int16", "int32", "uint8", "uint16", "uint32"].includes(keyType);
1604
+ }
1605
+ function deserializeArrowDictionaryKeyType(keyType) {
1606
+ switch (keyType) {
1607
+ case "int8":
1608
+ return new arrow.Int8();
1609
+ case "int16":
1610
+ return new arrow.Int16();
1611
+ case "int32":
1612
+ return new arrow.Int32();
1613
+ case "uint8":
1614
+ return new arrow.Uint8();
1615
+ case "uint16":
1616
+ return new arrow.Uint16();
1617
+ case "uint32":
1618
+ return new arrow.Uint32();
1619
+ default:
1620
+ throw new Error(`schema dictionary index type not supported: ${keyType}`);
1621
+ }
1622
+ }
1623
+
1624
+ // ../schema-utils/src/lib/schema/deduce-table-schema.ts
1625
+ function deduceTableSchema(table) {
1626
+ switch (table.shape) {
1627
+ case "array-row-table":
1628
+ case "object-row-table":
1629
+ return deduceSchemaFromRows(table.data);
1630
+ case "geojson-table":
1631
+ return deduceSchemaFromGeoJSON(table.features);
1632
+ case "columnar-table":
1633
+ return deduceSchemaFromColumns(table.data);
1634
+ case "arrow-table":
1635
+ default:
1636
+ throw new Error("Deduce schema");
1637
+ }
1638
+ }
1639
+ function deduceSchemaFromColumns(columnarTable) {
1640
+ const fields = [];
1641
+ for (const [columnName, column] of Object.entries(columnarTable)) {
1642
+ const field = deduceFieldFromColumn(column, columnName);
1643
+ fields.push(field);
1644
+ }
1645
+ return { fields, metadata: {} };
1646
+ }
1647
+ function deduceSchemaFromRows(rowTable) {
1648
+ if (!rowTable.length) {
1649
+ throw new Error("deduce from empty table");
1650
+ }
1651
+ const fields = [];
1652
+ const row0 = rowTable[0];
1653
+ for (const [columnName, value] of Object.entries(row0)) {
1654
+ fields.push(deduceFieldFromValue(value, columnName));
1655
+ }
1656
+ return { fields, metadata: {} };
1657
+ }
1658
+ function deduceSchemaFromGeoJSON(features) {
1659
+ if (!features.length) {
1660
+ throw new Error("deduce from empty table");
1661
+ }
1662
+ const fields = [];
1663
+ const row0 = features[0].properties || {};
1664
+ for (const [columnName, value] of Object.entries(row0)) {
1665
+ fields.push(deduceFieldFromValue(value, columnName));
1666
+ }
1667
+ return { fields, metadata: {} };
1668
+ }
1669
+ function deduceFieldFromColumn(column, name) {
1670
+ if (ArrayBuffer.isView(column)) {
1671
+ const type = getDataTypeFromArray(column);
1672
+ return {
1673
+ name,
1674
+ type: type.type || "null",
1675
+ nullable: type.nullable
1676
+ // metadata: {}
1677
+ };
1678
+ }
1679
+ if (Array.isArray(column) && column.length > 0) {
1680
+ const value = column[0];
1681
+ const type = getDataTypeFromValue(value);
1682
+ return {
1683
+ name,
1684
+ type,
1685
+ nullable: true
1686
+ // metadata: {},
1687
+ };
1688
+ }
1689
+ throw new Error("empty table");
1690
+ }
1691
+ function deduceFieldFromValue(value, name) {
1692
+ const type = getDataTypeFromValue(value);
1693
+ return {
1694
+ name,
1695
+ type,
1696
+ nullable: true
1697
+ // metadata: {}
1698
+ };
1699
+ }
1700
+
1701
+ // ../schema-utils/src/lib/table/tables/make-table.ts
1702
+ var arrow2 = __toESM(require("apache-arrow"), 1);
1703
+ function makeTableFromData(data) {
1704
+ let table;
1705
+ switch (getTableShapeFromData(data)) {
1706
+ case "array-row-table":
1707
+ table = { shape: "array-row-table", data };
1708
+ break;
1709
+ case "object-row-table":
1710
+ table = { shape: "object-row-table", data };
1711
+ break;
1712
+ case "columnar-table":
1713
+ table = { shape: "columnar-table", data };
1714
+ break;
1715
+ case "arrow-table":
1716
+ table = { shape: "arrow-table", data };
1717
+ break;
1718
+ default:
1719
+ throw new Error("table");
1720
+ }
1721
+ const schema = deduceTableSchema(table);
1722
+ return { ...table, schema };
1723
+ }
1724
+ function getTableShapeFromData(data) {
1725
+ if (data instanceof arrow2.Table) {
1726
+ return "arrow-table";
1727
+ }
1728
+ if (Array.isArray(data)) {
1729
+ if (data.length === 0) {
1730
+ throw new Error("cannot deduce type of empty table");
1731
+ }
1732
+ const firstRow = data[0];
1733
+ if (Array.isArray(firstRow)) {
1734
+ return "array-row-table";
1735
+ }
1736
+ if (firstRow && typeof firstRow === "object") {
1737
+ return "object-row-table";
1738
+ }
1739
+ }
1740
+ if (data && typeof data === "object") {
1741
+ return "columnar-table";
1742
+ }
1743
+ throw new Error("invalid table");
1744
+ }
1745
+
1746
+ // ../schema-utils/src/lib/table/tables/table-accessors.ts
1747
+ function getTableLength(table) {
1748
+ switch (table.shape) {
1749
+ case "array-row-table":
1750
+ case "object-row-table":
1751
+ return table.data.length;
1752
+ case "geojson-table":
1753
+ return table.features.length;
1754
+ case "arrow-table":
1755
+ const arrowTable = table.data;
1756
+ return arrowTable.numRows;
1757
+ case "columnar-table":
1758
+ for (const column of Object.values(table.data)) {
1759
+ return column.length || 0;
1760
+ }
1761
+ return 0;
1762
+ default:
1763
+ throw new Error("table");
1764
+ }
1765
+ }
1766
+ function getTableNumCols(table) {
1767
+ if (table.schema) {
1768
+ return table.schema.fields.length;
1769
+ }
1770
+ if (getTableLength(table) === 0) {
1771
+ throw new Error("empty table");
1772
+ }
1773
+ switch (table.shape) {
1774
+ case "array-row-table":
1775
+ return table.data[0].length;
1776
+ case "object-row-table":
1777
+ return Object.keys(table.data[0]).length;
1778
+ case "geojson-table":
1779
+ return Object.keys(table.features[0]).length;
1780
+ case "columnar-table":
1781
+ return Object.keys(table.data).length;
1782
+ case "arrow-table":
1783
+ const arrowTable = table.data;
1784
+ return arrowTable.numCols;
1785
+ default:
1786
+ throw new Error("table");
1787
+ }
1788
+ }
1789
+ function getTableCell(table, rowIndex, columnName) {
1790
+ var _a;
1791
+ switch (table.shape) {
1792
+ case "array-row-table":
1793
+ const columnIndex = getTableColumnIndex(table, columnName);
1794
+ return table.data[rowIndex][columnIndex];
1795
+ case "object-row-table":
1796
+ return table.data[rowIndex][columnName];
1797
+ case "geojson-table":
1798
+ return table.features[rowIndex][columnName];
1799
+ case "columnar-table":
1800
+ const column = table.data[columnName];
1801
+ return column[rowIndex];
1802
+ case "arrow-table":
1803
+ const arrowTable = table.data;
1804
+ const arrowColumnIndex = arrowTable.schema.fields.findIndex(
1805
+ (field) => field.name === columnName
1806
+ );
1807
+ return (_a = arrowTable.getChildAt(arrowColumnIndex)) == null ? void 0 : _a.get(rowIndex);
1808
+ default:
1809
+ throw new Error("todo");
1810
+ }
1811
+ }
1812
+ function getTableCellAt(table, rowIndex, columnIndex) {
1813
+ var _a;
1814
+ switch (table.shape) {
1815
+ case "array-row-table":
1816
+ return table.data[rowIndex][columnIndex];
1817
+ case "object-row-table":
1818
+ const columnName1 = getTableColumnName(table, columnIndex);
1819
+ return table.data[rowIndex][columnName1];
1820
+ case "geojson-table":
1821
+ const columnName2 = getTableColumnName(table, columnIndex);
1822
+ return table.features[rowIndex][columnName2];
1823
+ case "columnar-table":
1824
+ const columnName3 = getTableColumnName(table, columnIndex);
1825
+ const column = table.data[columnName3];
1826
+ return column[rowIndex];
1827
+ case "arrow-table":
1828
+ const arrowTable = table.data;
1829
+ return (_a = arrowTable.getChildAt(columnIndex)) == null ? void 0 : _a.get(rowIndex);
1830
+ default:
1831
+ throw new Error("todo");
1832
+ }
1833
+ }
1834
+ function getTableColumnIndex(table, columnName) {
1835
+ var _a;
1836
+ const columnIndex = (_a = table.schema) == null ? void 0 : _a.fields.findIndex((field) => field.name === columnName);
1837
+ if (columnIndex === void 0) {
1838
+ throw new Error(columnName);
1839
+ }
1840
+ return columnIndex;
1841
+ }
1842
+ function getTableColumnName(table, columnIndex) {
1843
+ var _a, _b;
1844
+ const columnName = (_b = (_a = table.schema) == null ? void 0 : _a.fields[columnIndex]) == null ? void 0 : _b.name;
1845
+ if (!columnName) {
1846
+ throw new Error(`${columnIndex}`);
1847
+ }
1848
+ return columnName;
1849
+ }
1850
+ function getTableRowAsObject(table, rowIndex, target, copy) {
1851
+ switch (table.shape) {
1852
+ case "object-row-table":
1853
+ return copy ? Object.fromEntries(Object.entries(table.data[rowIndex])) : table.data[rowIndex];
1854
+ case "array-row-table":
1855
+ if (table.schema) {
1856
+ const objectRow2 = target || {};
1857
+ for (let i = 0; i < table.schema.fields.length; i++) {
1858
+ objectRow2[table.schema.fields[i].name] = table.data[rowIndex][i];
1859
+ }
1860
+ return objectRow2;
1861
+ }
1862
+ throw new Error("no schema");
1863
+ case "geojson-table":
1864
+ if (table.schema) {
1865
+ const objectRow2 = target || {};
1866
+ for (let i = 0; i < table.schema.fields.length; i++) {
1867
+ objectRow2[table.schema.fields[i].name] = table.features[rowIndex][table.schema.fields[i].name];
1868
+ }
1869
+ return objectRow2;
1870
+ }
1871
+ throw new Error("no schema");
1872
+ case "columnar-table":
1873
+ if (table.schema) {
1874
+ const objectRow2 = target || {};
1875
+ for (let i = 0; i < table.schema.fields.length; i++) {
1876
+ objectRow2[table.schema.fields[i].name] = table.data[table.schema.fields[i].name][rowIndex];
1877
+ }
1878
+ return objectRow2;
1879
+ } else {
1880
+ const objectRow2 = target || {};
1881
+ for (const [name, column] of Object.entries(table.data)) {
1882
+ objectRow2[name] = column[rowIndex];
1883
+ }
1884
+ return objectRow2;
1885
+ }
1886
+ case "arrow-table":
1887
+ const arrowTable = table.data;
1888
+ const objectRow = target || {};
1889
+ const row = arrowTable.get(rowIndex);
1890
+ const schema = arrowTable.schema;
1891
+ for (let i = 0; i < schema.fields.length; i++) {
1892
+ objectRow[schema.fields[i].name] = row == null ? void 0 : row[schema.fields[i].name];
1893
+ }
1894
+ return objectRow;
1895
+ default:
1896
+ throw new Error("shape");
1897
+ }
1898
+ }
1899
+ function getTableRowAsArray(table, rowIndex, target, copy) {
1900
+ switch (table.shape) {
1901
+ case "array-row-table":
1902
+ return copy ? Array.from(table.data[rowIndex]) : table.data[rowIndex];
1903
+ case "object-row-table":
1904
+ if (table.schema) {
1905
+ const arrayRow2 = target || [];
1906
+ for (let i = 0; i < table.schema.fields.length; i++) {
1907
+ arrayRow2[i] = table.data[rowIndex][table.schema.fields[i].name];
1908
+ }
1909
+ return arrayRow2;
1910
+ }
1911
+ return Object.values(table.data[rowIndex]);
1912
+ case "geojson-table":
1913
+ if (table.schema) {
1914
+ const arrayRow2 = target || [];
1915
+ for (let i = 0; i < table.schema.fields.length; i++) {
1916
+ arrayRow2[i] = table.features[rowIndex][table.schema.fields[i].name];
1917
+ }
1918
+ return arrayRow2;
1919
+ }
1920
+ return Object.values(table.features[rowIndex]);
1921
+ case "columnar-table":
1922
+ if (table.schema) {
1923
+ const arrayRow2 = target || [];
1924
+ for (let i = 0; i < table.schema.fields.length; i++) {
1925
+ arrayRow2[i] = table.data[table.schema.fields[i].name][rowIndex];
1926
+ }
1927
+ return arrayRow2;
1928
+ } else {
1929
+ const arrayRow2 = target || [];
1930
+ let i = 0;
1931
+ for (const column of Object.values(table.data)) {
1932
+ arrayRow2[i] = column[rowIndex];
1933
+ i++;
1934
+ }
1935
+ return arrayRow2;
1936
+ }
1937
+ case "arrow-table":
1938
+ const arrowTable = table.data;
1939
+ const arrayRow = target || [];
1940
+ const row = arrowTable.get(rowIndex);
1941
+ const schema = arrowTable.schema;
1942
+ for (let i = 0; i < schema.fields.length; i++) {
1943
+ arrayRow[i] = row == null ? void 0 : row[schema.fields[i].name];
1944
+ }
1945
+ return arrayRow;
1946
+ default:
1947
+ throw new Error("shape");
1948
+ }
1949
+ }
1950
+
1951
+ // ../schema-utils/src/lib/table/tables/table-column.ts
1952
+ function makeColumnFromField(field, length) {
1953
+ const ArrayType = getArrayTypeFromDataType(field.type, field.nullable);
1954
+ return new ArrayType(length);
1955
+ }
1956
+
1957
+ // ../schema-utils/src/lib/table/tables/convert-arrow-table.ts
1958
+ var arrow4 = __toESM(require("apache-arrow"), 1);
1959
+
1960
+ // ../schema-utils/src/lib/table/batches/make-arrow-batch-iterator.ts
1961
+ var arrow3 = __toESM(require("apache-arrow"), 1);
1962
+ function* makeArrowRecordBatchIterator(table, options) {
1963
+ const arrowSchema = convertSchemaToArrow(table.schema);
1964
+ const length = getTableLength(table);
1965
+ const numColumns = getTableNumCols(table);
1966
+ const batchSize = (options == null ? void 0 : options.batchSize) || length;
1967
+ const builders = arrowSchema == null ? void 0 : arrowSchema.fields.map(
1968
+ (arrowField) => arrow3.makeBuilder({
1969
+ type: arrowField.type,
1970
+ nullValues: [null, void 0]
1971
+ })
1972
+ );
1973
+ const structField = new arrow3.Struct(arrowSchema.fields);
1974
+ let batchLength = 0;
1975
+ for (let rowIndex = 0; rowIndex < length; rowIndex++) {
1976
+ for (let columnIndex = 0; columnIndex < numColumns; ++columnIndex) {
1977
+ const value = getTableCellAt(table, rowIndex, columnIndex);
1978
+ const builder = builders[columnIndex];
1979
+ builder.append(value);
1980
+ }
1981
+ batchLength++;
1982
+ if (batchLength >= batchSize) {
1983
+ const datas = builders.map((builder) => builder.flush());
1984
+ const structData = new arrow3.Data(structField, 0, batchLength, 0, void 0, datas);
1985
+ yield new arrow3.RecordBatch(arrowSchema, structData);
1986
+ batchLength = 0;
1987
+ }
1988
+ }
1989
+ if (batchLength > 0) {
1990
+ const datas = builders.map((builder) => builder.flush());
1991
+ const structData = new arrow3.Data(structField, 0, batchLength, 0, void 0, datas);
1992
+ yield new arrow3.RecordBatch(arrowSchema, structData);
1993
+ batchLength = 0;
1994
+ }
1995
+ builders.map((builder) => builder.finish());
1996
+ }
1997
+
1998
+ // ../schema-utils/src/lib/table/tables/convert-arrow-table.ts
1999
+ function convertTableToArrow(table, options) {
2000
+ switch (table.shape) {
2001
+ case "arrow-table":
2002
+ return table.data;
2003
+ case "columnar-table":
2004
+ // TODO - optimized implementation is possible
2005
+ // return convertColumnarTableToArrow(table, options);
2006
+ // fall through
2007
+ default:
2008
+ const arrowBatchIterator = makeArrowRecordBatchIterator(table, options);
2009
+ return new arrow4.Table(arrowBatchIterator);
2010
+ }
2011
+ }
2012
+ function convertArrowToTable(arrowTable, shape) {
2013
+ switch (shape) {
2014
+ case "arrow-table":
2015
+ return convertArrowToArrowTable(arrowTable);
2016
+ case "array-row-table":
2017
+ return convertArrowToArrayRowTable(arrowTable);
2018
+ case "object-row-table":
2019
+ return convertArrowToObjectRowTable(arrowTable);
2020
+ case "columnar-table":
2021
+ return convertArrowToColumnarTable(arrowTable);
2022
+ case "geojson-table":
2023
+ return convertArrowToGeoJSONTable(arrowTable);
2024
+ default:
2025
+ throw new Error(shape);
2026
+ }
2027
+ }
2028
+ function convertArrowToArrowTable(arrowTable) {
2029
+ return {
2030
+ shape: "arrow-table",
2031
+ schema: convertArrowToSchema(arrowTable.schema),
2032
+ data: arrowTable
2033
+ };
2034
+ }
2035
+ function convertArrowToArrayRowTable(arrowTable) {
2036
+ const columnarTable = convertArrowToColumnarTable(arrowTable);
2037
+ return convertTable(columnarTable, "array-row-table");
2038
+ }
2039
+ function convertArrowToObjectRowTable(arrowTable) {
2040
+ const columnarTable = convertArrowToColumnarTable(arrowTable);
2041
+ return convertTable(columnarTable, "object-row-table");
2042
+ }
2043
+ function convertArrowToColumnarTable(arrowTable) {
2044
+ const columns = {};
2045
+ for (const field of arrowTable.schema.fields) {
2046
+ const arrowColumn = arrowTable.getChild(field.name);
2047
+ const values = arrowColumn == null ? void 0 : arrowColumn.toArray();
2048
+ columns[field.name] = values;
2049
+ }
2050
+ const schema = convertArrowToSchema(arrowTable.schema);
2051
+ return {
2052
+ shape: "columnar-table",
2053
+ schema,
2054
+ data: columns
2055
+ };
2056
+ }
2057
+ function convertArrowToGeoJSONTable(arrowTable) {
2058
+ var _a;
2059
+ const schema = convertArrowToSchema(arrowTable.schema);
2060
+ const features = [];
2061
+ for (let row = 0; row < arrowTable.numRows; row++) {
2062
+ const properties = ((_a = arrowTable.get(row)) == null ? void 0 : _a.toJSON()) || {};
2063
+ features.push({ type: "Feature", geometry: null, properties });
2064
+ }
2065
+ return {
2066
+ shape: "geojson-table",
2067
+ type: "FeatureCollection",
2068
+ schema,
2069
+ features
2070
+ };
2071
+ }
2072
+
2073
+ // ../schema-utils/src/lib/table/tables/convert-table.ts
2074
+ function convertTable(table, shape) {
2075
+ switch (shape) {
2076
+ case "object-row-table":
2077
+ return convertToObjectRowTable(table);
2078
+ case "array-row-table":
2079
+ return convertToArrayRowTable(table);
2080
+ case "columnar-table":
2081
+ return convertToColumnarTable(table);
2082
+ case "arrow-table":
2083
+ return convertToArrowTable(table);
2084
+ default:
2085
+ throw new Error(shape);
2086
+ }
2087
+ }
2088
+ function convertToColumnarTable(table) {
2089
+ const schema = table.schema || deduceTableSchema(table);
2090
+ const fields = schema.fields;
2091
+ if (table.shape === "columnar-table") {
2092
+ return { ...table, schema };
2093
+ }
2094
+ const length = getTableLength(table);
2095
+ const columns = {};
2096
+ for (const field of fields) {
2097
+ const column = makeColumnFromField(field, length);
2098
+ columns[field.name] = column;
2099
+ for (let rowIndex = 0; rowIndex < length; rowIndex++) {
2100
+ column[rowIndex] = getTableCell(table, rowIndex, field.name);
2101
+ }
2102
+ }
2103
+ return {
2104
+ shape: "columnar-table",
2105
+ schema,
2106
+ data: columns
2107
+ };
2108
+ }
2109
+ function convertToArrayRowTable(table) {
2110
+ if (table.shape === "array-row-table") {
2111
+ return table;
2112
+ }
2113
+ const length = getTableLength(table);
2114
+ const data = new Array(length);
2115
+ for (let rowIndex = 0; rowIndex < length; rowIndex++) {
2116
+ data[rowIndex] = getTableRowAsArray(table, rowIndex);
2117
+ }
2118
+ return {
2119
+ shape: "array-row-table",
2120
+ schema: table.schema,
2121
+ data
2122
+ };
2123
+ }
2124
+ function convertToObjectRowTable(table) {
2125
+ if (table.shape === "object-row-table") {
2126
+ return table;
2127
+ }
2128
+ const length = getTableLength(table);
2129
+ const data = new Array(length);
2130
+ for (let rowIndex = 0; rowIndex < length; rowIndex++) {
2131
+ data[rowIndex] = getTableRowAsObject(table, rowIndex);
2132
+ }
2133
+ return {
2134
+ shape: "object-row-table",
2135
+ schema: table.schema,
2136
+ data
2137
+ };
2138
+ }
2139
+ function convertToArrowTable(table) {
2140
+ const schema = table.schema || deduceTableSchema(table);
2141
+ const arrowTable = convertTableToArrow({ ...table, schema });
2142
+ return {
2143
+ shape: "arrow-table",
2144
+ schema,
2145
+ data: arrowTable
2146
+ };
2147
+ }
2148
+
2149
+ // ../schema-utils/src/deprecated.ts
2150
+ var convertArrowToTable2 = ((...args) => convertArrowToTable(
2151
+ ...args
2152
+ ));
45
2153
 
46
2154
  // dist/sql-utils.js
47
- var arrow = __toESM(require("apache-arrow"), 1);
48
- var import_schema_utils = require("@loaders.gl/schema-utils");
49
2155
  function isNodeRuntime() {
50
2156
  var _a;
51
2157
  return typeof process !== "undefined" && Boolean((_a = process.versions) == null ? void 0 : _a.node);
@@ -57,19 +2163,19 @@ function quoteSqlIdentifier(identifier) {
57
2163
  return `"${identifier.replace(/"/g, '""')}"`;
58
2164
  }
59
2165
  function convertRowsToArrowTable(rows) {
60
- const table = rows.length > 0 ? (0, import_schema_utils.makeTableFromData)(rows) : { shape: "object-row-table", schema: { fields: [], metadata: {} }, data: rows };
2166
+ const table = rows.length > 0 ? makeTableFromData(rows) : { shape: "object-row-table", schema: { fields: [], metadata: {} }, data: rows };
61
2167
  const schema = deducePrimitiveAwareSchema(table);
62
2168
  if (table.data.length === 0 || schema.fields.length === 0) {
63
2169
  return {
64
2170
  shape: "arrow-table",
65
2171
  schema,
66
- data: new arrow.Table(new arrow.Schema([]))
2172
+ data: new arrow5.Table(new arrow5.Schema([]))
67
2173
  };
68
2174
  }
69
2175
  return {
70
2176
  shape: "arrow-table",
71
2177
  schema,
72
- data: arrow.tableFromJSON(table.data)
2178
+ data: arrow5.tableFromJSON(table.data)
73
2179
  };
74
2180
  }
75
2181
  function convertSQLColumnsToSchema(columns) {
@@ -121,7 +2227,7 @@ function deducePrimitiveAwareSchema(table) {
121
2227
  return field;
122
2228
  }
123
2229
  const columnValues = table.data.map((row) => row[field.name]);
124
- const inferredType = (0, import_schema_utils.getDataTypeFromArray)(columnValues);
2230
+ const inferredType = getDataTypeFromArray(columnValues);
125
2231
  return { ...field, type: inferredType.type, nullable: inferredType.nullable };
126
2232
  })
127
2233
  };
@@ -131,6 +2237,28 @@ function getQualifiedTableName(options) {
131
2237
  return identifiers.map((identifier) => quoteSqlIdentifier(identifier)).join(".");
132
2238
  }
133
2239
 
2240
+ // dist/table-query-capabilities.js
2241
+ var ARROW_TABLE_QUERY_CAPABILITIES = Object.freeze({
2242
+ projection: "residual",
2243
+ predicate: "residual",
2244
+ limit: "residual",
2245
+ streaming: false,
2246
+ cancellation: true,
2247
+ expressions: "residual",
2248
+ orderBy: "residual",
2249
+ aggregates: "residual"
2250
+ });
2251
+ var SQL_DATA_SOURCE_TABLE_QUERY_CAPABILITIES = Object.freeze({
2252
+ projection: "pushdown",
2253
+ predicate: "pushdown",
2254
+ limit: "pushdown",
2255
+ streaming: false,
2256
+ cancellation: false,
2257
+ expressions: "pushdown",
2258
+ orderBy: "pushdown",
2259
+ aggregates: "pushdown"
2260
+ });
2261
+
134
2262
  // dist/sql-source.js
135
2263
  var SQL_ADAPTER_FACTORIES = /* @__PURE__ */ new Map();
136
2264
  function registerSQLAdapter(type, factory) {
@@ -163,7 +2291,9 @@ var SQL_SOURCE_DEFAULT_OPTIONS = {
163
2291
  authenticator: void 0
164
2292
  }
165
2293
  };
166
- var SQLDataSource = class extends import_loader_utils.DataSource {
2294
+ var SQLDataSource = class extends DataSource {
2295
+ /** Optimization and execution capabilities of portable table-bound queries. */
2296
+ tableQueryCapabilities = SQL_DATA_SOURCE_TABLE_QUERY_CAPABILITIES;
167
2297
  sourceType;
168
2298
  adapterFactory;
169
2299
  adapterPromise = null;
@@ -201,17 +2331,19 @@ var SQLDataSource = class extends import_loader_utils.DataSource {
201
2331
  return await adapter.getTableSchema(options);
202
2332
  }
203
2333
  /** Executes a SQL query and returns object rows. */
204
- async queryRows(sqlText, options = {}) {
2334
+ async queryRows(query, options = {}) {
205
2335
  const adapter = await this.getAdapter();
206
- return await adapter.executeRows(sqlText, options);
2336
+ const compiledQuery = this.compileQuery(query, options);
2337
+ return await adapter.executeRows(compiledQuery.sql, compiledQuery.options);
207
2338
  }
208
2339
  /** Executes a SQL query and returns a loaders.gl Arrow table. */
209
- async queryArrow(sqlText, options = {}) {
2340
+ async queryArrow(query, options = {}) {
210
2341
  const adapter = await this.getAdapter();
2342
+ const compiledQuery = this.compileQuery(query, options);
211
2343
  if (adapter.executeArrow) {
212
- return await adapter.executeArrow(sqlText, options);
2344
+ return await adapter.executeArrow(compiledQuery.sql, compiledQuery.options);
213
2345
  }
214
- const rows = await adapter.executeRows(sqlText, options);
2346
+ const rows = await adapter.executeRows(compiledQuery.sql, compiledQuery.options);
215
2347
  return convertRowsToArrowTable(rows);
216
2348
  }
217
2349
  /** Closes any underlying adapter connection. */
@@ -230,6 +2362,21 @@ var SQLDataSource = class extends import_loader_utils.DataSource {
230
2362
  }
231
2363
  return await this.adapterPromise;
232
2364
  }
2365
+ /** Converts a portable query object to SQL while leaving raw SQL text unchanged. */
2366
+ compileQuery(query, options) {
2367
+ if (typeof query === "string") {
2368
+ return { sql: query, options };
2369
+ }
2370
+ const namedParameters = options.parameters && !Array.isArray(options.parameters) ? options.parameters : void 0;
2371
+ const compiledQuery = compileSQLTableQuery(query, {
2372
+ dialect: getSQLTableQueryDialect(this.sourceType),
2373
+ parameters: namedParameters
2374
+ });
2375
+ return {
2376
+ sql: compiledQuery.sql,
2377
+ options: { signal: options.signal, parameters: compiledQuery.parameters }
2378
+ };
2379
+ }
233
2380
  async loadAdapter() {
234
2381
  var _a, _b;
235
2382
  try {
@@ -266,17 +2413,676 @@ var SQLDataSource = class extends import_loader_utils.DataSource {
266
2413
  };
267
2414
  }
268
2415
  };
2416
+ function getSQLTableQueryDialect(sourceType) {
2417
+ if (sourceType === "duckdb-sql")
2418
+ return "duckdb";
2419
+ if (sourceType === "snowflake-sql")
2420
+ return "snowflake";
2421
+ throw new Error(`Portable table queries are not supported for SQL source type "${sourceType}".`);
2422
+ }
2423
+
2424
+ // dist/query-arrow-table.js
2425
+ var arrow6 = __toESM(require("apache-arrow"), 1);
2426
+
2427
+ // dist/table-query.js
2428
+ function planTableQuery2(sourceColumnNames, options = {}) {
2429
+ if (options.predicate) {
2430
+ validateSQLPredicate(options.predicate);
2431
+ }
2432
+ return planTableQuery(sourceColumnNames, options);
2433
+ }
2434
+ function explainTableQuery2(sourceColumnNames, options = {}) {
2435
+ if (options.predicate) {
2436
+ validateSQLPredicate(options.predicate);
2437
+ }
2438
+ return explainTableQuery(sourceColumnNames, options, SQL_DATA_SOURCE_TABLE_QUERY_CAPABILITIES);
2439
+ }
2440
+ function getSQLPredicateColumnNames(predicate) {
2441
+ return getColumnarPredicateColumns(predicate);
2442
+ }
2443
+
2444
+ // dist/query-arrow-table.js
2445
+ function explainArrowTableQuery(sourceTable, options = {}) {
2446
+ if (options.predicate) {
2447
+ validateSQLPredicate(options.predicate);
2448
+ }
2449
+ return explainTableQuery(sourceTable.data.schema.fields.map((field) => field.name), options, ARROW_TABLE_QUERY_CAPABILITIES);
2450
+ }
2451
+ function queryArrowTable(sourceTable, options = {}) {
2452
+ var _a, _b;
2453
+ throwIfAborted(options.signal);
2454
+ if (options.join) {
2455
+ validateArrowJoinQuery(sourceTable, options);
2456
+ }
2457
+ if (options.join && hasRelationalOperatorsExceptJoin(options)) {
2458
+ throw new Error("Arrow joins cannot yet be combined with other relational operators.");
2459
+ }
2460
+ if (options.join && !hasRelationalOperatorsExceptJoin(options)) {
2461
+ return queryArrowJoin(sourceTable, options);
2462
+ }
2463
+ if (hasRelationalOperators(options)) {
2464
+ return queryArrowTableRelational(sourceTable, options);
2465
+ }
2466
+ const sourceData = sourceTable.data;
2467
+ const plan = planTableQuery2(sourceData.schema.fields.map((field) => field.name), options);
2468
+ const scannedData = sourceData.select([...getScanStep(plan).columns]);
2469
+ const projectedData = scannedData.select([...getProjectStep(plan).columns]);
2470
+ const predicate = (_a = getFilterStep(plan)) == null ? void 0 : _a.predicate;
2471
+ const limit = ((_b = getLimitStep(plan)) == null ? void 0 : _b.limit) ?? Number.POSITIVE_INFINITY;
2472
+ if (!predicate) {
2473
+ return wrapArrowTable(projectedData.slice(0, limit));
2474
+ }
2475
+ const predicateColumns = getPredicateColumns(scannedData, getSQLPredicateColumnNames(predicate));
2476
+ const matchingRowIndices = [];
2477
+ for (let rowIndex = 0; rowIndex < scannedData.numRows && matchingRowIndices.length < limit; rowIndex++) {
2478
+ throwIfAborted(options.signal);
2479
+ if (evaluatePredicate(predicate, predicateColumns, rowIndex) === true) {
2480
+ matchingRowIndices.push(rowIndex);
2481
+ }
2482
+ }
2483
+ if (matchingRowIndices.length === 0) {
2484
+ return wrapArrowTable(projectedData.slice(0, 0));
2485
+ }
2486
+ const outputColumns = {};
2487
+ for (const field of projectedData.schema.fields) {
2488
+ const sourceColumn = projectedData.getChild(field.name);
2489
+ if (!sourceColumn) {
2490
+ throw new Error(`Arrow query could not read column "${field.name}".`);
2491
+ }
2492
+ const values = matchingRowIndices.map((rowIndex) => sourceColumn.get(rowIndex));
2493
+ outputColumns[field.name] = arrow6.vectorFromArray(values, sourceColumn.type);
2494
+ }
2495
+ return wrapArrowTable(new arrow6.Table(projectedData.schema, outputColumns));
2496
+ }
2497
+ function queryArrowTableRelational(sourceTable, options) {
2498
+ var _a, _b, _c, _d, _e, _f;
2499
+ const sourceData = sourceTable.data;
2500
+ const sourceColumnNames = sourceData.schema.fields.map((field) => field.name);
2501
+ const relationalPlan = planRelationalQuery(sourceColumnNames, options);
2502
+ const scanStep = relationalPlan.tablePlan.find((step) => step.kind === "scan");
2503
+ if (!scanStep || scanStep.kind !== "scan") {
2504
+ throw new Error("Arrow relational query plan is missing a scan step.");
2505
+ }
2506
+ const scannedTable = wrapArrowTable(sourceData.select([...scanStep.columns]));
2507
+ const filteredTable = queryArrowTable(scannedTable, {
2508
+ predicate: options.predicate,
2509
+ columns: scanStep.columns,
2510
+ signal: options.signal
2511
+ });
2512
+ let rows = arrowTableToRows(filteredTable.data);
2513
+ for (const child of options.union || []) {
2514
+ const childTable = (_a = options.tables) == null ? void 0 : _a[child.source];
2515
+ if (!childTable)
2516
+ throw new Error(`Arrow union source not found: ${child.source}`);
2517
+ const childResult = queryArrowTable(childTable, {
2518
+ ...child.query || {},
2519
+ columns: getUnionChildColumns(sourceColumnNames, options),
2520
+ signal: options.signal
2521
+ });
2522
+ rows = rows.concat(arrowTableToRows(childResult.data));
2523
+ }
2524
+ for (const expression of options.expressions || []) {
2525
+ for (const row of rows) {
2526
+ row[expression.name] = evaluateRelationalExpression(expression, row);
2527
+ }
2528
+ }
2529
+ if (((_b = options.groupBy) == null ? void 0 : _b.length) || ((_c = options.aggregates) == null ? void 0 : _c.length)) {
2530
+ rows = aggregateRows(rows, options.groupBy || [], options.aggregates || []);
2531
+ }
2532
+ if ((_d = options.orderBy) == null ? void 0 : _d.length) {
2533
+ const orderBy = options.orderBy;
2534
+ rows = rows.map((row, index) => ({ row, index })).sort((left, right) => compareRows(left.row, right.row, orderBy) || left.index - right.index).map((entry) => entry.row);
2535
+ }
2536
+ const outputColumns = options.columns || (((_e = options.groupBy) == null ? void 0 : _e.length) || ((_f = options.aggregates) == null ? void 0 : _f.length) ? [...options.groupBy || [], ...(options.aggregates || []).map((aggregate) => aggregate.name)] : sourceColumnNames);
2537
+ const outputRows = rows.map((row) => {
2538
+ const output = {};
2539
+ for (const columnName of outputColumns) {
2540
+ if (!(columnName in row)) {
2541
+ throw new Error(`Arrow relational query column not found: ${columnName}`);
2542
+ }
2543
+ output[columnName] = row[columnName];
2544
+ }
2545
+ return output;
2546
+ });
2547
+ const limit = options.limit === void 0 ? outputRows.length : options.limit;
2548
+ const limitedRows = outputRows.slice(0, limit);
2549
+ return limitedRows.length ? convertRowsToArrowTable(limitedRows) : createEmptyRelationalResult(sourceData, outputColumns, options);
2550
+ }
2551
+ function getUnionChildColumns(sourceColumnNames, options) {
2552
+ var _a, _b;
2553
+ const expressionNames = new Set((options.expressions || []).map((expression) => expression.name));
2554
+ const aggregateNames = new Set((options.aggregates || []).map((aggregate) => aggregate.name));
2555
+ const outputColumns = options.columns || (((_a = options.groupBy) == null ? void 0 : _a.length) || ((_b = options.aggregates) == null ? void 0 : _b.length) ? [...options.groupBy || [], ...(options.aggregates || []).map((aggregate) => aggregate.name)] : sourceColumnNames);
2556
+ const requiredColumns = new Set(outputColumns.filter((column) => !expressionNames.has(column) && !aggregateNames.has(column)));
2557
+ for (const expression of options.expressions || []) {
2558
+ const definition = expression.expression;
2559
+ if (definition.op === "column")
2560
+ requiredColumns.add(definition.column);
2561
+ if ("left" in definition) {
2562
+ requiredColumns.add(definition.left);
2563
+ requiredColumns.add(definition.right);
2564
+ }
2565
+ }
2566
+ for (const key of options.orderBy || []) {
2567
+ if (!expressionNames.has(key.column) && !aggregateNames.has(key.column)) {
2568
+ requiredColumns.add(key.column);
2569
+ }
2570
+ }
2571
+ for (const column of options.groupBy || [])
2572
+ requiredColumns.add(column);
2573
+ for (const aggregate of options.aggregates || []) {
2574
+ if (aggregate.column)
2575
+ requiredColumns.add(aggregate.column);
2576
+ }
2577
+ return sourceColumnNames.filter((column) => requiredColumns.has(column));
2578
+ }
2579
+ function hasRelationalOperators(options) {
2580
+ var _a, _b, _c, _d, _e;
2581
+ return Boolean(((_a = options.expressions) == null ? void 0 : _a.length) || ((_b = options.orderBy) == null ? void 0 : _b.length) || ((_c = options.groupBy) == null ? void 0 : _c.length) || ((_d = options.aggregates) == null ? void 0 : _d.length) || ((_e = options.union) == null ? void 0 : _e.length) || options.join);
2582
+ }
2583
+ function hasRelationalOperatorsExceptJoin(options) {
2584
+ var _a, _b, _c, _d, _e;
2585
+ return Boolean(((_a = options.expressions) == null ? void 0 : _a.length) || ((_b = options.orderBy) == null ? void 0 : _b.length) || ((_c = options.groupBy) == null ? void 0 : _c.length) || ((_d = options.aggregates) == null ? void 0 : _d.length) || ((_e = options.union) == null ? void 0 : _e.length));
2586
+ }
2587
+ function queryArrowJoin(sourceTable, options) {
2588
+ var _a;
2589
+ const join = options.join;
2590
+ if (!join)
2591
+ throw new Error("Arrow join query is missing a join definition.");
2592
+ const childTable = (_a = options.tables) == null ? void 0 : _a[join.child.source];
2593
+ if (!childTable)
2594
+ throw new Error(`Arrow join source not found: ${join.child.source}`);
2595
+ const leftResult = queryArrowTable(sourceTable, {
2596
+ predicate: options.predicate,
2597
+ columns: void 0,
2598
+ signal: options.signal
2599
+ });
2600
+ const rightResult = queryArrowTable(childTable, {
2601
+ ...join.child.query || {},
2602
+ signal: options.signal
2603
+ });
2604
+ const leftRows = arrowTableToRows(leftResult.data);
2605
+ const rightRows = arrowTableToRows(rightResult.data);
2606
+ const rightPrefix = `${join.child.source}.`;
2607
+ const defaultOutputColumns = [
2608
+ ...sourceTable.data.schema.fields.map((field) => field.name),
2609
+ ...rightResult.data.schema.fields.map((field) => `${rightPrefix}${field.name}`)
2610
+ ];
2611
+ const rows = [];
2612
+ for (const leftRow of leftRows) {
2613
+ for (const rightRow of rightRows) {
2614
+ if (leftRow[join.left] !== null && leftRow[join.left] !== void 0 && rightRow[join.right] !== null && rightRow[join.right] !== void 0 && compareSortValues(leftRow[join.left], rightRow[join.right]) === 0) {
2615
+ rows.push({
2616
+ ...leftRow,
2617
+ ...Object.fromEntries(Object.entries(rightRow).map(([key, value]) => [`${rightPrefix}${key}`, value]))
2618
+ });
2619
+ }
2620
+ }
2621
+ }
2622
+ const outputColumns = options.columns || defaultOutputColumns;
2623
+ const outputRows = rows.map((row) => Object.fromEntries(outputColumns.map((column) => [column, row[column]])));
2624
+ const limitedRows = outputRows.slice(0, options.limit);
2625
+ return limitedRows.length ? convertRowsToArrowTable(limitedRows) : createEmptyRelationalResult(sourceTable.data, outputColumns, options, new Map(rightResult.data.schema.fields.map((field) => [
2626
+ `${rightPrefix}${field.name}`,
2627
+ new arrow6.Field(`${rightPrefix}${field.name}`, field.type, field.nullable, field.metadata)
2628
+ ])));
2629
+ }
2630
+ function validateArrowJoinQuery(sourceTable, options) {
2631
+ var _a, _b, _c;
2632
+ const join = options.join;
2633
+ if (!join)
2634
+ return;
2635
+ const sourceColumnNames = sourceTable.data.schema.fields.map((field) => field.name);
2636
+ const childTable = (_a = options.tables) == null ? void 0 : _a[join.child.source];
2637
+ if (!childTable)
2638
+ throw new Error(`Arrow join source not found: ${join.child.source}`);
2639
+ const childColumnNames = childTable.data.schema.fields.map((field) => field.name);
2640
+ if (!sourceColumnNames.includes(join.left)) {
2641
+ throw new Error(`Arrow join column not found: ${join.left}`);
2642
+ }
2643
+ if (!childColumnNames.includes(join.right)) {
2644
+ throw new Error(`Arrow join column not found: ${join.right}`);
2645
+ }
2646
+ const childPrefix = `${join.child.source}.`;
2647
+ const rootColumns = (_b = options.columns) == null ? void 0 : _b.filter((column) => !column.startsWith(childPrefix));
2648
+ planTableQuery2(sourceColumnNames, {
2649
+ predicate: options.predicate,
2650
+ columns: (rootColumns == null ? void 0 : rootColumns.length) ? rootColumns : void 0,
2651
+ limit: options.limit,
2652
+ signal: options.signal
2653
+ });
2654
+ const childQuery = join.child.query || {};
2655
+ planTableQuery2(childColumnNames, childQuery);
2656
+ const childOutputColumns = childQuery.columns || childColumnNames;
2657
+ if (!childOutputColumns.includes(join.right)) {
2658
+ throw new Error(`Arrow join child projection must include: ${join.right}`);
2659
+ }
2660
+ const projectedChildColumns = ((_c = options.columns) == null ? void 0 : _c.filter((column) => column.startsWith(childPrefix))) || [];
2661
+ const seenChildColumns = /* @__PURE__ */ new Set();
2662
+ for (const projectedColumn of projectedChildColumns) {
2663
+ const childColumn = projectedColumn.slice(childPrefix.length);
2664
+ if (!childColumnNames.includes(childColumn)) {
2665
+ throw new Error(`Arrow join column not found: ${projectedColumn}`);
2666
+ }
2667
+ if (seenChildColumns.has(childColumn)) {
2668
+ throw new Error(`Arrow query column was selected more than once: ${projectedColumn}`);
2669
+ }
2670
+ seenChildColumns.add(childColumn);
2671
+ if (!childOutputColumns.includes(childColumn)) {
2672
+ throw new Error(`Arrow join child projection does not include: ${childColumn}`);
2673
+ }
2674
+ }
2675
+ }
2676
+ function arrowTableToRows(data) {
2677
+ const columns = data.schema.fields.map((field) => ({
2678
+ name: field.name,
2679
+ vector: data.getChild(field.name)
2680
+ }));
2681
+ return Array.from({ length: data.numRows }, (_, rowIndex) => {
2682
+ const row = {};
2683
+ for (const column of columns) {
2684
+ if (!column.vector)
2685
+ throw new Error(`Arrow relational query could not read ${column.name}`);
2686
+ row[column.name] = column.vector.get(rowIndex);
2687
+ }
2688
+ return row;
2689
+ });
2690
+ }
2691
+ function evaluateRelationalExpression(expression, row) {
2692
+ const definition = expression.expression;
2693
+ if (definition.op === "literal")
2694
+ return definition.value;
2695
+ if (definition.op === "column")
2696
+ return row[definition.column];
2697
+ const left = row[definition.left];
2698
+ const right = row[definition.right];
2699
+ if (left === null || left === void 0 || right === null || right === void 0)
2700
+ return null;
2701
+ if (typeof left !== "number" || typeof right !== "number") {
2702
+ throw new Error(`Arrow relational expression ${expression.name} requires numeric operands.`);
2703
+ }
2704
+ switch (definition.op) {
2705
+ case "add":
2706
+ return left + right;
2707
+ case "subtract":
2708
+ return left - right;
2709
+ case "multiply":
2710
+ return left * right;
2711
+ case "divide":
2712
+ return right === 0 ? null : left / right;
2713
+ }
2714
+ }
2715
+ function compareRows(left, right, orderBy) {
2716
+ for (const key of orderBy) {
2717
+ const leftValue = left[key.column];
2718
+ const rightValue = right[key.column];
2719
+ const nulls = key.nulls || "last";
2720
+ if (leftValue === null || leftValue === void 0 || rightValue === null || rightValue === void 0) {
2721
+ if (leftValue === rightValue)
2722
+ continue;
2723
+ const nullResult = leftValue === null || leftValue === void 0 ? -1 : 1;
2724
+ return nulls === "first" ? nullResult : -nullResult;
2725
+ }
2726
+ const result = compareSortValues(leftValue, rightValue);
2727
+ if (result)
2728
+ return (key.direction === "desc" ? -1 : 1) * result;
2729
+ }
2730
+ return 0;
2731
+ }
2732
+ function compareSortValues(left, right) {
2733
+ if (left instanceof Date && right instanceof Date)
2734
+ return compareNumbers(left.getTime(), right.getTime());
2735
+ if (typeof left === "bigint" && typeof right === "bigint")
2736
+ return left === right ? 0 : left < right ? -1 : 1;
2737
+ if (typeof left === "number" && typeof right === "number")
2738
+ return compareNumbers(left, right);
2739
+ if (typeof left === "string" && typeof right === "string")
2740
+ return left === right ? 0 : left < right ? -1 : 1;
2741
+ if (typeof left === "boolean" && typeof right === "boolean")
2742
+ return Number(left) - Number(right);
2743
+ throw new Error(`Arrow relational order cannot compare ${getValueType(left)} with ${getValueType(right)}.`);
2744
+ }
2745
+ function aggregateRows(rows, groupBy, aggregates) {
2746
+ const groups = /* @__PURE__ */ new Map();
2747
+ for (const row of rows) {
2748
+ const key = serializeGroupKey(groupBy.map((column) => row[column]));
2749
+ const group = groups.get(key) || [];
2750
+ group.push(row);
2751
+ groups.set(key, group);
2752
+ }
2753
+ if (!groupBy.length && !rows.length)
2754
+ groups.set("[]", []);
2755
+ return [...groups.values()].map((group) => {
2756
+ var _a;
2757
+ const output = {};
2758
+ for (const column of groupBy)
2759
+ output[column] = ((_a = group[0]) == null ? void 0 : _a[column]) ?? null;
2760
+ for (const aggregate of aggregates)
2761
+ output[aggregate.name] = evaluateAggregate(aggregate, group);
2762
+ return output;
2763
+ });
2764
+ }
2765
+ function serializeGroupKey(values) {
2766
+ return values.map((value) => {
2767
+ if (value === null || value === void 0)
2768
+ return "null:";
2769
+ if (value instanceof Date)
2770
+ return `date:${value.getTime()}`;
2771
+ if (value instanceof Uint8Array)
2772
+ return `bytes:${Array.from(value).join(".")}`;
2773
+ return `${typeof value}:${String(value)}`;
2774
+ }).join("");
2775
+ }
2776
+ function createEmptyRelationalResult(sourceData, outputColumns, options, additionalFields) {
2777
+ const sourceFields = new Map(sourceData.schema.fields.map((field) => [field.name, field]));
2778
+ const expressions = new Map((options.expressions || []).map((expression) => [expression.name, expression]));
2779
+ const aggregates = new Map((options.aggregates || []).map((aggregate) => [aggregate.name, aggregate]));
2780
+ const fields = outputColumns.map((columnName) => {
2781
+ const sourceField = sourceFields.get(columnName);
2782
+ if (sourceField)
2783
+ return sourceField;
2784
+ const additionalField = additionalFields == null ? void 0 : additionalFields.get(columnName);
2785
+ if (additionalField)
2786
+ return additionalField;
2787
+ const expression = expressions.get(columnName);
2788
+ if (expression)
2789
+ return new arrow6.Field(columnName, getExpressionType(expression, sourceFields), true);
2790
+ const aggregate = aggregates.get(columnName);
2791
+ if (aggregate)
2792
+ return new arrow6.Field(columnName, getAggregateType(aggregate, sourceFields), true);
2793
+ return new arrow6.Field(columnName, new arrow6.Utf8(), true);
2794
+ });
2795
+ const columns = {};
2796
+ for (const field of fields)
2797
+ columns[field.name] = arrow6.vectorFromArray([], field.type);
2798
+ return wrapArrowTable(new arrow6.Table(new arrow6.Schema(fields), columns));
2799
+ }
2800
+ function getExpressionType(expression, sourceFields) {
2801
+ var _a;
2802
+ if (expression.expression.op === "literal") {
2803
+ const value = expression.expression.value;
2804
+ if (typeof value === "boolean")
2805
+ return new arrow6.Bool();
2806
+ if (typeof value === "number")
2807
+ return new arrow6.Float64();
2808
+ return new arrow6.Utf8();
2809
+ }
2810
+ if (expression.expression.op === "column") {
2811
+ return ((_a = sourceFields.get(expression.expression.column)) == null ? void 0 : _a.type) || new arrow6.Utf8();
2812
+ }
2813
+ return new arrow6.Float64();
2814
+ }
2815
+ function getAggregateType(aggregate, sourceFields) {
2816
+ var _a;
2817
+ if (aggregate.function === "count")
2818
+ return new arrow6.Int32();
2819
+ return aggregate.column ? ((_a = sourceFields.get(aggregate.column)) == null ? void 0 : _a.type) || new arrow6.Float64() : new arrow6.Float64();
2820
+ }
2821
+ function evaluateAggregate(aggregate, rows) {
2822
+ if (aggregate.function === "count")
2823
+ return aggregate.column ? rows.filter((row) => row[aggregate.column] != null).length : rows.length;
2824
+ const values = rows.map((row) => row[aggregate.column]).filter((value) => value != null);
2825
+ if (!values.length)
2826
+ return null;
2827
+ if (!values.every((value) => typeof value === "number"))
2828
+ throw new Error(`Arrow aggregate ${aggregate.function} requires numeric values.`);
2829
+ const numericValues = values;
2830
+ switch (aggregate.function) {
2831
+ case "sum":
2832
+ return numericValues.reduce((sum, value) => sum + value, 0);
2833
+ case "avg":
2834
+ return numericValues.reduce((sum, value) => sum + value, 0) / numericValues.length;
2835
+ case "min":
2836
+ return Math.min(...numericValues);
2837
+ case "max":
2838
+ return Math.max(...numericValues);
2839
+ }
2840
+ }
2841
+ function getPredicateColumns(sourceTable, columnNames) {
2842
+ const columns = {};
2843
+ for (const columnName of columnNames) {
2844
+ const column = sourceTable.getChild(columnName);
2845
+ if (!column) {
2846
+ throw new Error(`Arrow query column not found: ${columnName}`);
2847
+ }
2848
+ columns[columnName] = column;
2849
+ }
2850
+ return columns;
2851
+ }
2852
+ function evaluatePredicate(predicate, columns, rowIndex) {
2853
+ if (isLogicalPredicate(predicate)) {
2854
+ const values = predicate.args.map((child) => evaluatePredicate(child, columns, rowIndex));
2855
+ return predicate.op === "and" ? evaluateAnd(values) : evaluateOr(values);
2856
+ }
2857
+ if (isNotPredicate(predicate)) {
2858
+ const value2 = evaluatePredicate(predicate.args[0], columns, rowIndex);
2859
+ return value2 === null ? null : !value2;
2860
+ }
2861
+ const value = getColumnValue(columns, predicate.args[0].property, rowIndex);
2862
+ if (isNullPredicate(predicate)) {
2863
+ return value === null;
2864
+ }
2865
+ if (isInPredicate(predicate)) {
2866
+ return evaluateIn(value, predicate.args[1]);
2867
+ }
2868
+ return evaluateComparison(value, predicate);
2869
+ }
2870
+ function getColumnValue(columns, columnName, rowIndex) {
2871
+ const column = columns[columnName];
2872
+ if (!column) {
2873
+ throw new Error(`Arrow query could not read predicate column "${columnName}".`);
2874
+ }
2875
+ return column.get(rowIndex);
2876
+ }
2877
+ function evaluateAnd(values) {
2878
+ if (values.includes(false)) {
2879
+ return false;
2880
+ }
2881
+ return values.includes(null) ? null : true;
2882
+ }
2883
+ function evaluateOr(values) {
2884
+ if (values.includes(true)) {
2885
+ return true;
2886
+ }
2887
+ return values.includes(null) ? null : false;
2888
+ }
2889
+ function evaluateIn(value, candidates) {
2890
+ if (value === null || value === void 0) {
2891
+ return null;
2892
+ }
2893
+ for (const candidate of candidates) {
2894
+ if (compareValues(value, candidate) === 0) {
2895
+ return true;
2896
+ }
2897
+ }
2898
+ return false;
2899
+ }
2900
+ function evaluateComparison(value, predicate) {
2901
+ if (value === null || value === void 0) {
2902
+ return null;
2903
+ }
2904
+ const comparison = compareValues(value, predicate.args[1]);
2905
+ switch (predicate.op) {
2906
+ case "=":
2907
+ return comparison === 0;
2908
+ case "<>":
2909
+ return comparison !== 0;
2910
+ case "<":
2911
+ return comparison < 0;
2912
+ case "<=":
2913
+ return comparison <= 0;
2914
+ case ">":
2915
+ return comparison > 0;
2916
+ case ">=":
2917
+ return comparison >= 0;
2918
+ }
2919
+ }
2920
+ function compareValues(left, right) {
2921
+ if (isSQLPredicateParameter(right)) {
2922
+ throw new Error(`Arrow query parameter ":${right.parameter}" must be bound before query execution.`);
2923
+ }
2924
+ if (left instanceof Date && right instanceof Date) {
2925
+ return compareNumbers(left.getTime(), right.getTime());
2926
+ }
2927
+ if (left instanceof Uint8Array && right instanceof Uint8Array) {
2928
+ return compareBinary(left, right);
2929
+ }
2930
+ if (typeof left === "bigint" && typeof right === "bigint") {
2931
+ return left === right ? 0 : left < right ? -1 : 1;
2932
+ }
2933
+ if (typeof left === "bigint" && typeof right === "number" && Number.isSafeInteger(right)) {
2934
+ return compareValues(left, BigInt(right));
2935
+ }
2936
+ if (typeof left === "number" && typeof right === "bigint" && Number.isSafeInteger(left)) {
2937
+ return compareValues(BigInt(left), right);
2938
+ }
2939
+ if (typeof left === "number" && typeof right === "number") {
2940
+ return compareNumbers(left, right);
2941
+ }
2942
+ if (typeof left === "string" && typeof right === "string") {
2943
+ return left === right ? 0 : left < right ? -1 : 1;
2944
+ }
2945
+ if (typeof left === "boolean" && typeof right === "boolean") {
2946
+ return Number(left) - Number(right);
2947
+ }
2948
+ throw new Error(`Arrow query cannot compare ${getValueType(left)} with ${getValueType(right)} values.`);
2949
+ }
2950
+ function compareNumbers(left, right) {
2951
+ if (!Number.isFinite(left) || !Number.isFinite(right)) {
2952
+ throw new Error("Arrow query cannot compare non-finite numbers.");
2953
+ }
2954
+ return left === right ? 0 : left < right ? -1 : 1;
2955
+ }
2956
+ function compareBinary(left, right) {
2957
+ const commonLength = Math.min(left.length, right.length);
2958
+ for (let index = 0; index < commonLength; index++) {
2959
+ if (left[index] !== right[index]) {
2960
+ return left[index] < right[index] ? -1 : 1;
2961
+ }
2962
+ }
2963
+ return left.length === right.length ? 0 : left.length < right.length ? -1 : 1;
2964
+ }
2965
+ function getValueType(value) {
2966
+ if (value instanceof Date) {
2967
+ return "Date";
2968
+ }
2969
+ if (value instanceof Uint8Array) {
2970
+ return "Uint8Array";
2971
+ }
2972
+ return typeof value;
2973
+ }
2974
+ function isLogicalPredicate(predicate) {
2975
+ return predicate.op === "and" || predicate.op === "or";
2976
+ }
2977
+ function isNotPredicate(predicate) {
2978
+ return predicate.op === "not";
2979
+ }
2980
+ function isNullPredicate(predicate) {
2981
+ return predicate.op === "isNull";
2982
+ }
2983
+ function isInPredicate(predicate) {
2984
+ return predicate.op === "in";
2985
+ }
2986
+ function getScanStep(plan) {
2987
+ const step = plan.find((candidate) => candidate.kind === "scan");
2988
+ if (!step) {
2989
+ throw new Error("Arrow query plan is missing a scan step.");
2990
+ }
2991
+ return step;
2992
+ }
2993
+ function getFilterStep(plan) {
2994
+ return plan.find((candidate) => candidate.kind === "filter");
2995
+ }
2996
+ function getProjectStep(plan) {
2997
+ const step = plan.find((candidate) => candidate.kind === "project");
2998
+ if (!step) {
2999
+ throw new Error("Arrow query plan is missing a project step.");
3000
+ }
3001
+ return step;
3002
+ }
3003
+ function getLimitStep(plan) {
3004
+ return plan.find((candidate) => candidate.kind === "limit");
3005
+ }
3006
+ function throwIfAborted(signal) {
3007
+ if (signal == null ? void 0 : signal.aborted) {
3008
+ const error = new Error("Arrow query was aborted.");
3009
+ error.name = "AbortError";
3010
+ throw error;
3011
+ }
3012
+ }
3013
+ function wrapArrowTable(data) {
3014
+ return {
3015
+ shape: "arrow-table",
3016
+ schema: convertArrowToSchema(data.schema),
3017
+ data
3018
+ };
3019
+ }
3020
+
3021
+ // dist/arrow-table-source.js
3022
+ var ArrowTableSource = class extends DataSource {
3023
+ /** Creates a source over an existing Arrow table without copying its vectors. */
3024
+ constructor(data, options = {}) {
3025
+ super(data, options);
3026
+ }
3027
+ /** Discovers query-visible fields and capabilities without evaluating any rows. */
3028
+ async getQueryMetadata(options = {}) {
3029
+ throwIfAborted2(options.signal);
3030
+ const schema = convertArrowToSchema(this.data.data.schema);
3031
+ return createScanQueryMetadata({
3032
+ sourceType: "arrow-table",
3033
+ queryType: "table",
3034
+ execution: { status: "supported", method: "read" },
3035
+ schema,
3036
+ capabilities: { table: ARROW_TABLE_QUERY_CAPABILITIES },
3037
+ columnRoles: getArrowColumnRoles(schema.fields.map((field) => field.name)),
3038
+ statistics: { rowCount: this.data.data.numRows }
3039
+ });
3040
+ }
3041
+ /** Executes a portable query and returns an Arrow table result. */
3042
+ query(options = {}) {
3043
+ return queryArrowTable(this.data, options);
3044
+ }
3045
+ /** Explains a portable query without evaluating table rows. */
3046
+ explain(options = {}) {
3047
+ return explainArrowTableQuery(this.data, options);
3048
+ }
3049
+ /** Executes a query as one bounded Arrow batch. */
3050
+ async *read(options = {}) {
3051
+ const result = this.query(options);
3052
+ yield makeTableScanBatch(result);
3053
+ }
3054
+ };
3055
+ function getArrowColumnRoles(columnNames) {
3056
+ const roles = {};
3057
+ for (const columnName of columnNames) {
3058
+ const normalizedName = columnName.toLowerCase();
3059
+ if (normalizedName === "x" || normalizedName === "longitude" || normalizedName === "lon") {
3060
+ roles[columnName] = normalizedName === "x" ? "x" : "longitude";
3061
+ } else if (normalizedName === "y" || normalizedName === "latitude" || normalizedName === "lat") {
3062
+ roles[columnName] = normalizedName === "y" ? "y" : "latitude";
3063
+ } else if (normalizedName === "z" || normalizedName === "elevation" || normalizedName === "altitude") {
3064
+ roles[columnName] = normalizedName === "z" ? "z" : "attribute";
3065
+ } else if (normalizedName === "time" || normalizedName.endsWith("_time") || normalizedName.endsWith("timestamp")) {
3066
+ roles[columnName] = "time";
3067
+ }
3068
+ }
3069
+ return roles;
3070
+ }
3071
+ function throwIfAborted2(signal) {
3072
+ if (signal == null ? void 0 : signal.aborted) {
3073
+ throw new Error("Request aborted");
3074
+ }
3075
+ }
269
3076
 
270
3077
  // dist/duckdb-sql-source.js
271
- var import_schema_utils2 = require("@loaders.gl/schema-utils");
272
- var VERSION = true ? "5.0.0-alpha.1" : "latest";
3078
+ var VERSION2 = true ? "5.0.0-alpha.3" : "latest";
273
3079
  var DuckDBSQLSource = {
274
3080
  dataType: null,
275
3081
  batchType: null,
276
3082
  name: "DuckDBSQLSource",
277
3083
  id: "duckdb-sql",
278
3084
  module: "sql",
279
- version: VERSION,
3085
+ version: VERSION2,
280
3086
  extensions: ["duckdb", "db"],
281
3087
  mimeTypes: [],
282
3088
  type: "duckdb-sql",
@@ -448,9 +3254,9 @@ async function createDuckDBBrowserAdapter(context) {
448
3254
  const database = new duckdb.AsyncDuckDB(logger, worker);
449
3255
  await database.instantiate(bundles.mainModule, bundles.pthreadWorker);
450
3256
  const connection = await database.connect();
451
- const executeRows = async (sqlText) => {
452
- const result = await connection.query(sqlText);
453
- return (0, import_schema_utils2.convertArrowToTable)(result, "object-row-table").data;
3257
+ const executeRows = async (sqlText, options = {}) => {
3258
+ const result = await executeDuckDBBrowserQuery(connection, sqlText, options.parameters);
3259
+ return convertArrowToTable2(result, "object-row-table").data;
454
3260
  };
455
3261
  return {
456
3262
  capabilities: {
@@ -530,15 +3336,27 @@ async function createDuckDBBrowserAdapter(context) {
530
3336
  }));
531
3337
  return convertSQLColumnsToSchema(columns);
532
3338
  },
533
- async executeRows(sqlText) {
534
- return await executeRows(sqlText);
3339
+ async executeRows(sqlText, options = {}) {
3340
+ return await executeRows(sqlText, options);
535
3341
  },
536
- async executeArrow(sqlText) {
537
- const result = await connection.query(sqlText);
538
- return (0, import_schema_utils2.convertArrowToTable)(result, "arrow-table");
3342
+ async executeArrow(sqlText, options = {}) {
3343
+ const result = await executeDuckDBBrowserQuery(connection, sqlText, options.parameters);
3344
+ return convertArrowToTable2(result, "arrow-table");
539
3345
  }
540
3346
  };
541
3347
  }
3348
+ async function executeDuckDBBrowserQuery(connection, sqlText, parameters) {
3349
+ if (!parameters) {
3350
+ return await connection.query(sqlText);
3351
+ }
3352
+ const values = Array.isArray(parameters) ? parameters : Object.values(parameters);
3353
+ const statement = await connection.prepare(sqlText);
3354
+ try {
3355
+ return await statement.query(...values);
3356
+ } finally {
3357
+ await statement.close();
3358
+ }
3359
+ }
542
3360
  function getDuckDBDatabasePath(url, options) {
543
3361
  var _a;
544
3362
  if ((_a = options.duckdb) == null ? void 0 : _a.databasePath) {
@@ -553,14 +3371,14 @@ function getDuckDBDatabasePath(url, options) {
553
3371
  }
554
3372
 
555
3373
  // dist/snowflake-sql-source.js
556
- var VERSION2 = true ? "5.0.0-alpha.1" : "latest";
3374
+ var VERSION3 = true ? "5.0.0-alpha.3" : "latest";
557
3375
  var SnowflakeSQLSource = {
558
3376
  dataType: null,
559
3377
  batchType: null,
560
3378
  name: "SnowflakeSQLSource",
561
3379
  id: "snowflake-sql",
562
3380
  module: "sql",
563
- version: VERSION2,
3381
+ version: VERSION3,
564
3382
  extensions: [],
565
3383
  mimeTypes: [],
566
3384
  type: "snowflake-sql",
@@ -729,14 +3547,15 @@ async function fetchSnowflakeJson(context, url, authorization, requestInit) {
729
3547
  return json;
730
3548
  }
731
3549
  function normalizeSnowflakeBindings(parameters) {
732
- if (!parameters || Array.isArray(parameters)) {
3550
+ if (!parameters) {
733
3551
  return void 0;
734
3552
  }
735
3553
  const bindings = {};
736
- for (const [key, value] of Object.entries(parameters)) {
3554
+ const entries = Array.isArray(parameters) ? parameters.map((value, index) => [String(index + 1), value]) : Object.entries(parameters);
3555
+ for (const [key, value] of entries) {
737
3556
  bindings[key] = {
738
- type: typeof value === "number" ? "FIXED" : "TEXT",
739
- value
3557
+ type: typeof value === "number" || typeof value === "bigint" ? "FIXED" : "TEXT",
3558
+ value: typeof value === "bigint" ? value.toString() : value
740
3559
  };
741
3560
  }
742
3561
  return bindings;
@@ -756,4 +3575,304 @@ function getSnowflakeBaseUrl(url, options) {
756
3575
  }
757
3576
  return `https://${account}.snowflakecomputing.com`;
758
3577
  }
3578
+
3579
+ // dist/parse-sql-predicate.js
3580
+ var MAXIMUM_SQL_LENGTH = 65536;
3581
+ var MAXIMUM_SQL_TOKENS = 4096;
3582
+ var MAXIMUM_EXPRESSION_DEPTH = 64;
3583
+ function parseSQLPredicate(source, options = {}) {
3584
+ const parser = new SQLPredicateParser(source, options.parameters ?? {}, options.preserveParameters === true);
3585
+ const predicate = parser.parse();
3586
+ validateSQLPredicate(predicate);
3587
+ return predicate;
3588
+ }
3589
+ var SQLPredicateParser = class {
3590
+ /** Token stream parsed by this parser instance. */
3591
+ tokens;
3592
+ /** Named scalar parameters available to the expression. */
3593
+ parameters;
3594
+ /** Whether named parameters remain references in the parsed AST. */
3595
+ preserveParameters;
3596
+ /** Current index in the token stream. */
3597
+ position = 0;
3598
+ constructor(source, parameters, preserveParameters) {
3599
+ this.tokens = tokenizeSQLPredicate(source);
3600
+ this.parameters = parameters;
3601
+ this.preserveParameters = preserveParameters;
3602
+ }
3603
+ /** Parses the complete token stream. */
3604
+ parse() {
3605
+ const predicate = this.parseOr(0);
3606
+ this.takeSymbol(";");
3607
+ const token = this.peek();
3608
+ if (token) {
3609
+ throw new Error(`SQL predicate contains unexpected token ${JSON.stringify(token.value)}`);
3610
+ }
3611
+ return predicate;
3612
+ }
3613
+ /** Parses left-associative disjunction. */
3614
+ parseOr(depth) {
3615
+ let predicate = this.parseAnd(depth + 1);
3616
+ while (this.takeKeyword("OR")) {
3617
+ predicate = combineLogicalPredicate("or", predicate, this.parseAnd(depth + 1));
3618
+ }
3619
+ return predicate;
3620
+ }
3621
+ /** Parses left-associative conjunction. */
3622
+ parseAnd(depth) {
3623
+ let predicate = this.parseNot(depth + 1);
3624
+ while (this.takeKeyword("AND")) {
3625
+ predicate = combineLogicalPredicate("and", predicate, this.parseNot(depth + 1));
3626
+ }
3627
+ return predicate;
3628
+ }
3629
+ /** Parses boolean negation and parenthesized predicates. */
3630
+ parseNot(depth) {
3631
+ this.assertDepth(depth);
3632
+ if (this.takeKeyword("NOT")) {
3633
+ return { op: "not", args: [this.parseNot(depth + 1)] };
3634
+ }
3635
+ if (this.takeSymbol("(")) {
3636
+ const predicate = this.parseOr(depth + 1);
3637
+ this.expectSymbol(")");
3638
+ return predicate;
3639
+ }
3640
+ return this.parseLeaf();
3641
+ }
3642
+ /** Parses one comparison, membership, or null predicate. */
3643
+ parseLeaf() {
3644
+ var _a, _b;
3645
+ const property = this.parseProperty();
3646
+ if (this.takeKeyword("IS")) {
3647
+ const negated = this.takeKeyword("NOT");
3648
+ this.expectKeyword("NULL");
3649
+ const predicate = { op: "isNull", args: [property] };
3650
+ return negated ? { op: "not", args: [predicate] } : predicate;
3651
+ }
3652
+ const negatedMembership = this.takeKeyword("NOT");
3653
+ if (negatedMembership || this.peekKeyword("IN")) {
3654
+ this.expectKeyword("IN");
3655
+ this.expectSymbol("(");
3656
+ if (((_a = this.peek()) == null ? void 0 : _a.kind) === "symbol" && ((_b = this.peek()) == null ? void 0 : _b.value) === ")") {
3657
+ throw new Error("SQL predicate IN requires at least one scalar value");
3658
+ }
3659
+ const values = [this.parseValue()];
3660
+ while (this.takeSymbol(",")) {
3661
+ values.push(this.parseValue());
3662
+ }
3663
+ this.expectSymbol(")");
3664
+ const predicate = { op: "in", args: [property, values] };
3665
+ return negatedMembership ? { op: "not", args: [predicate] } : predicate;
3666
+ }
3667
+ const token = this.take();
3668
+ if ((token == null ? void 0 : token.kind) !== "symbol" || !["=", "!=", "<>", "<", "<=", ">", ">="].includes(token.value)) {
3669
+ throw new Error("SQL predicate expected a comparison, IN, or IS NULL operator");
3670
+ }
3671
+ const operator = token.value === "!=" ? "<>" : token.value;
3672
+ return {
3673
+ op: operator,
3674
+ args: [property, this.parseValue()]
3675
+ };
3676
+ }
3677
+ /** Parses an identifier into a property reference. */
3678
+ parseProperty() {
3679
+ const token = this.take();
3680
+ if ((token == null ? void 0 : token.kind) !== "identifier") {
3681
+ throw new Error("SQL predicate expected a column identifier");
3682
+ }
3683
+ return token.quoted ? { property: token.value, quoted: true } : { property: token.value };
3684
+ }
3685
+ /** Parses one scalar literal or named parameter. */
3686
+ parseValue() {
3687
+ const negative = this.takeSymbol("-");
3688
+ const token = this.take();
3689
+ if (!token) {
3690
+ throw new Error("SQL predicate expected a scalar value");
3691
+ }
3692
+ if (negative && token.kind !== "number") {
3693
+ throw new Error("SQL predicate only permits unary minus on numeric literals");
3694
+ }
3695
+ if (token.kind === "number") {
3696
+ return parseNumericLiteral(negative ? `-${token.value}` : token.value);
3697
+ }
3698
+ if (negative) {
3699
+ throw new Error("SQL predicate expected a numeric literal after unary minus");
3700
+ }
3701
+ if (token.kind === "string") {
3702
+ return token.value;
3703
+ }
3704
+ if (token.kind === "parameter") {
3705
+ if (this.preserveParameters) {
3706
+ return { parameter: token.value };
3707
+ }
3708
+ if (!Object.hasOwn(this.parameters, token.value)) {
3709
+ throw new Error(`SQL predicate parameter ":${token.value}" requires a value`);
3710
+ }
3711
+ const value = this.parameters[token.value];
3712
+ validateParameterValue(value, token.value);
3713
+ return value;
3714
+ }
3715
+ if (token.kind === "identifier" && /^(TRUE|FALSE)$/i.test(token.value)) {
3716
+ return /^TRUE$/i.test(token.value);
3717
+ }
3718
+ if (token.kind === "identifier" && /^NULL$/i.test(token.value)) {
3719
+ throw new Error("SQL predicate comparisons with NULL must use IS NULL or IS NOT NULL");
3720
+ }
3721
+ throw new Error(`SQL predicate does not support scalar token ${JSON.stringify(token.value)}`);
3722
+ }
3723
+ /** Rejects excessively nested inputs before recursion can exhaust the stack. */
3724
+ assertDepth(depth) {
3725
+ if (depth > MAXIMUM_EXPRESSION_DEPTH) {
3726
+ throw new Error("SQL predicate nesting exceeds its safe limit");
3727
+ }
3728
+ }
3729
+ /** Consumes one required keyword. */
3730
+ expectKeyword(keyword) {
3731
+ if (!this.takeKeyword(keyword)) {
3732
+ throw new Error(`SQL predicate expected ${keyword}`);
3733
+ }
3734
+ }
3735
+ /** Returns whether the next token is a keyword without consuming it. */
3736
+ peekKeyword(keyword) {
3737
+ const token = this.peek();
3738
+ return (token == null ? void 0 : token.kind) === "identifier" && token.value.toUpperCase() === keyword;
3739
+ }
3740
+ /** Consumes one optional keyword. */
3741
+ takeKeyword(keyword) {
3742
+ if (!this.peekKeyword(keyword)) {
3743
+ return false;
3744
+ }
3745
+ this.position++;
3746
+ return true;
3747
+ }
3748
+ /** Consumes one required symbol. */
3749
+ expectSymbol(symbol) {
3750
+ if (!this.takeSymbol(symbol)) {
3751
+ throw new Error(`SQL predicate expected ${JSON.stringify(symbol)}`);
3752
+ }
3753
+ }
3754
+ /** Consumes one optional symbol. */
3755
+ takeSymbol(symbol) {
3756
+ const token = this.peek();
3757
+ if ((token == null ? void 0 : token.kind) !== "symbol" || token.value !== symbol) {
3758
+ return false;
3759
+ }
3760
+ this.position++;
3761
+ return true;
3762
+ }
3763
+ /** Consumes and returns the next token. */
3764
+ take() {
3765
+ const token = this.tokens[this.position];
3766
+ if (token) {
3767
+ this.position++;
3768
+ }
3769
+ return token;
3770
+ }
3771
+ /** Returns the next token without consuming it. */
3772
+ peek() {
3773
+ return this.tokens[this.position];
3774
+ }
3775
+ };
3776
+ function combineLogicalPredicate(operator, left, right) {
3777
+ return left.op === operator ? { op: operator, args: [...left.args, right] } : { op: operator, args: [left, right] };
3778
+ }
3779
+ function parseNumericLiteral(source) {
3780
+ if (/^-?\d+$/.test(source)) {
3781
+ const bigint = BigInt(source);
3782
+ if (bigint > BigInt(Number.MAX_SAFE_INTEGER) || bigint < BigInt(Number.MIN_SAFE_INTEGER)) {
3783
+ return bigint;
3784
+ }
3785
+ }
3786
+ const number = Number(source);
3787
+ if (!Number.isFinite(number)) {
3788
+ throw new Error("SQL predicate numeric literals must be finite");
3789
+ }
3790
+ return number;
3791
+ }
3792
+ function validateParameterValue(value, name) {
3793
+ const probe = { op: "=", args: [{ property: "_" }, value] };
3794
+ try {
3795
+ validateSQLPredicate(probe);
3796
+ } catch {
3797
+ throw new Error(`SQL predicate parameter ":${name}" has an unsupported value`);
3798
+ }
3799
+ }
3800
+ function tokenizeSQLPredicate(source) {
3801
+ if (typeof source !== "string" || source.trim().length === 0 || source.length > MAXIMUM_SQL_LENGTH) {
3802
+ throw new Error("SQL predicate requires a non-empty, safely bounded expression");
3803
+ }
3804
+ const tokens = [];
3805
+ let position = 0;
3806
+ while (position < source.length) {
3807
+ const character = source[position];
3808
+ if (/\s/.test(character)) {
3809
+ position++;
3810
+ continue;
3811
+ }
3812
+ if (character === "'") {
3813
+ const result = readQuotedToken(source, position, "'", "'");
3814
+ tokens.push({ kind: "string", value: result.value });
3815
+ position = result.position;
3816
+ } else if (character === '"') {
3817
+ const result = readQuotedToken(source, position, '"', '"');
3818
+ tokens.push({ kind: "identifier", value: result.value, quoted: true });
3819
+ position = result.position;
3820
+ } else if (character === ":") {
3821
+ const match = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(position + 1));
3822
+ if (!match) {
3823
+ throw new Error(`SQL predicate contains an invalid parameter at character ${position}`);
3824
+ }
3825
+ tokens.push({ kind: "parameter", value: match[0] });
3826
+ position += match[0].length + 1;
3827
+ } else {
3828
+ const numberMatch = /^(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/.exec(source.slice(position));
3829
+ const identifierMatch = /^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*/.exec(source.slice(position));
3830
+ if (numberMatch) {
3831
+ tokens.push({ kind: "number", value: numberMatch[0] });
3832
+ position += numberMatch[0].length;
3833
+ } else if (identifierMatch) {
3834
+ tokens.push({ kind: "identifier", value: identifierMatch[0] });
3835
+ position += identifierMatch[0].length;
3836
+ } else {
3837
+ const twoCharacters = source.slice(position, position + 2);
3838
+ if (["<=", ">=", "<>", "!="].includes(twoCharacters)) {
3839
+ tokens.push({ kind: "symbol", value: twoCharacters });
3840
+ position += 2;
3841
+ } else if ("(),;-=<>".includes(character)) {
3842
+ tokens.push({ kind: "symbol", value: character });
3843
+ position++;
3844
+ } else {
3845
+ throw new Error(`SQL predicate contains an unsupported token at character ${position}`);
3846
+ }
3847
+ }
3848
+ }
3849
+ if (tokens.length > MAXIMUM_SQL_TOKENS) {
3850
+ throw new Error("SQL predicate exceeds its safe token limit");
3851
+ }
3852
+ }
3853
+ return tokens;
3854
+ }
3855
+ function readQuotedToken(source, start, quote, escapedQuote) {
3856
+ let value = "";
3857
+ let position = start + 1;
3858
+ while (position < source.length) {
3859
+ if (source[position] !== quote) {
3860
+ value += source[position++];
3861
+ continue;
3862
+ }
3863
+ if (source[position + 1] === escapedQuote) {
3864
+ value += quote;
3865
+ position += 2;
3866
+ continue;
3867
+ }
3868
+ return { value, position: position + 1 };
3869
+ }
3870
+ throw new Error(`SQL predicate contains an unterminated quoted value at character ${start}`);
3871
+ }
3872
+
3873
+ // dist/bind-sql-predicate.js
3874
+ function bindSQLPredicate(predicate, parameters) {
3875
+ validateSQLPredicate(predicate);
3876
+ return bindColumnarPredicateParameters(predicate, parameters);
3877
+ }
759
3878
  //# sourceMappingURL=index.cjs.map