@loaders.gl/core 5.0.0-beta.5 → 5.0.0-beta.7

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 (181) hide show
  1. package/dist/cluster-source.cjs +45 -1
  2. package/dist/cluster-source.cjs.map +1 -1
  3. package/dist/dist.min.js +2 -2
  4. package/dist/federated-table-scan-source.cjs +279 -201
  5. package/dist/federated-table-scan-source.cjs.map +3 -3
  6. package/dist/index.cjs +1 -1
  7. package/dist/lib/init.js +1 -1
  8. package/dist/loader-utils/index.cjs +233 -12
  9. package/dist/loader-utils/index.cjs.map +2 -2
  10. package/dist/loader-utils/index.d.ts +8 -4
  11. package/dist/loader-utils/index.d.ts.map +1 -1
  12. package/dist/loader-utils/index.js +3 -1
  13. package/dist/loader-utils/index.js.map +1 -1
  14. package/dist/loader-utils/json-loader.js +1 -1
  15. package/dist/loader-utils/lib/files/http-file-transport.d.ts +4 -0
  16. package/dist/loader-utils/lib/files/http-file-transport.d.ts.map +1 -1
  17. package/dist/loader-utils/lib/files/http-file-transport.js +45 -1
  18. package/dist/loader-utils/lib/files/http-file-transport.js.map +1 -1
  19. package/dist/loader-utils/lib/files/http-file-types.d.ts +2 -0
  20. package/dist/loader-utils/lib/files/http-file-types.d.ts.map +1 -1
  21. package/dist/loader-utils/lib/files/read-range-response.d.ts +3 -0
  22. package/dist/loader-utils/lib/files/read-range-response.d.ts.map +1 -0
  23. package/dist/loader-utils/lib/files/read-range-response.js +62 -0
  24. package/dist/loader-utils/lib/files/read-range-response.js.map +1 -0
  25. package/dist/loader-utils/lib/log-utils/log.js +1 -1
  26. package/dist/loader-utils/lib/scan-utils/logical-table-query.d.ts +38 -0
  27. package/dist/loader-utils/lib/scan-utils/logical-table-query.d.ts.map +1 -0
  28. package/dist/loader-utils/lib/scan-utils/logical-table-query.js +96 -0
  29. package/dist/loader-utils/lib/scan-utils/logical-table-query.js.map +1 -0
  30. package/dist/loader-utils/lib/scan-utils/{experimental-scan-options.d.ts → query-options.d.ts} +5 -8
  31. package/dist/loader-utils/lib/scan-utils/query-options.d.ts.map +1 -0
  32. package/dist/loader-utils/lib/scan-utils/{experimental-scan-options.js → query-options.js} +1 -1
  33. package/dist/loader-utils/lib/scan-utils/query-options.js.map +1 -0
  34. package/dist/loader-utils/lib/scan-utils/scan-query-metadata.d.ts +12 -17
  35. package/dist/loader-utils/lib/scan-utils/scan-query-metadata.d.ts.map +1 -1
  36. package/dist/loader-utils/lib/scan-utils/scan-query-metadata.js +5 -5
  37. package/dist/loader-utils/lib/scan-utils/scan-query-metadata.js.map +1 -1
  38. package/dist/loader-utils/lib/scan-utils/table-query.d.ts +33 -3
  39. package/dist/loader-utils/lib/scan-utils/table-query.d.ts.map +1 -1
  40. package/dist/loader-utils/lib/scan-utils/table-query.js.map +1 -1
  41. package/dist/loader-utils/lib/scan-utils/table-scan-batch.d.ts +2 -2
  42. package/dist/loader-utils/lib/scan-utils/table-scan-batch.d.ts.map +1 -1
  43. package/dist/loader-utils/lib/scan-utils/table-scan-batch.js +11 -3
  44. package/dist/loader-utils/lib/scan-utils/table-scan-batch.js.map +1 -1
  45. package/dist/loader-utils/lib/sources/data-source.d.ts +4 -0
  46. package/dist/loader-utils/lib/sources/data-source.d.ts.map +1 -1
  47. package/dist/loader-utils/lib/sources/data-source.js +50 -1
  48. package/dist/loader-utils/lib/sources/data-source.js.map +1 -1
  49. package/dist/loader-utils/lib/sources/table-source-collection.d.ts +30 -0
  50. package/dist/loader-utils/lib/sources/table-source-collection.d.ts.map +1 -0
  51. package/dist/loader-utils/lib/sources/table-source-collection.js +5 -0
  52. package/dist/loader-utils/lib/sources/table-source-collection.js.map +1 -0
  53. package/dist/loader-utils/loader-types.d.ts +5 -5
  54. package/dist/loader-utils/loader-types.d.ts.map +1 -1
  55. package/dist/null-loader.js +1 -1
  56. package/dist/null-worker-node.js +1 -1
  57. package/dist/null-worker.js +1 -1
  58. package/dist/scan/arrow-execution/expressions.cjs +110 -0
  59. package/dist/scan/arrow-execution/expressions.cjs.map +7 -0
  60. package/dist/scan/arrow-execution/expressions.d.ts +9 -0
  61. package/dist/scan/arrow-execution/expressions.d.ts.map +1 -0
  62. package/dist/scan/arrow-execution/expressions.js +60 -0
  63. package/dist/scan/arrow-execution/expressions.js.map +1 -0
  64. package/dist/scan/arrow-execution/filter-arrow-table.cjs +266 -0
  65. package/dist/scan/arrow-execution/filter-arrow-table.cjs.map +7 -0
  66. package/dist/scan/arrow-execution/filter-arrow-table.d.ts +18 -0
  67. package/dist/scan/arrow-execution/filter-arrow-table.d.ts.map +1 -0
  68. package/dist/scan/arrow-execution/filter-arrow-table.js +230 -0
  69. package/dist/scan/arrow-execution/filter-arrow-table.js.map +1 -0
  70. package/dist/scan/arrow-execution/project-arrow-table.cjs +70 -0
  71. package/dist/scan/arrow-execution/project-arrow-table.cjs.map +7 -0
  72. package/dist/scan/arrow-execution/project-arrow-table.d.ts +8 -0
  73. package/dist/scan/arrow-execution/project-arrow-table.d.ts.map +1 -0
  74. package/dist/scan/arrow-execution/project-arrow-table.js +39 -0
  75. package/dist/scan/arrow-execution/project-arrow-table.js.map +1 -0
  76. package/dist/scan/arrow-execution.cjs +34 -0
  77. package/dist/scan/arrow-execution.cjs.map +7 -0
  78. package/dist/scan/arrow-execution.d.ts +4 -0
  79. package/dist/scan/arrow-execution.d.ts.map +1 -0
  80. package/dist/scan/arrow-execution.js +6 -0
  81. package/dist/scan/arrow-execution.js.map +1 -0
  82. package/dist/scan/arrow-query.cjs.map +1 -1
  83. package/dist/scan/arrow-query.d.ts +1 -1
  84. package/dist/scan/arrow-query.d.ts.map +1 -1
  85. package/dist/scan/catalog-query-source.cjs +122 -0
  86. package/dist/scan/catalog-query-source.cjs.map +7 -0
  87. package/dist/scan/catalog-query-source.d.ts +6 -0
  88. package/dist/scan/catalog-query-source.d.ts.map +1 -0
  89. package/dist/scan/catalog-query-source.js +115 -0
  90. package/dist/scan/catalog-query-source.js.map +1 -0
  91. package/dist/scan/federated-table-scan-source.cjs +4 -4
  92. package/dist/scan/federated-table-scan-source.cjs.map +2 -2
  93. package/dist/scan/federated-table-scan-source.d.ts +1 -1
  94. package/dist/scan/federated-table-scan-source.d.ts.map +1 -1
  95. package/dist/scan/federated-table-scan-source.js +4 -4
  96. package/dist/scan/federated-table-scan-source.js.map +1 -1
  97. package/dist/scan/index.cjs +188 -4
  98. package/dist/scan/index.cjs.map +4 -4
  99. package/dist/scan/index.d.ts +9 -2
  100. package/dist/scan/index.d.ts.map +1 -1
  101. package/dist/scan/index.js +4 -0
  102. package/dist/scan/index.js.map +1 -1
  103. package/dist/scan/parse-sql-predicate.cjs +3 -294
  104. package/dist/scan/parse-sql-predicate.cjs.map +3 -3
  105. package/dist/scan/parse-sql-predicate.d.ts +6 -9
  106. package/dist/scan/parse-sql-predicate.d.ts.map +1 -1
  107. package/dist/scan/parse-sql-predicate.js +5 -314
  108. package/dist/scan/parse-sql-predicate.js.map +1 -1
  109. package/dist/scan/query-arrow-table-in-batches.cjs +65 -0
  110. package/dist/scan/query-arrow-table-in-batches.cjs.map +7 -0
  111. package/dist/scan/query-arrow-table-in-batches.d.ts +8 -0
  112. package/dist/scan/query-arrow-table-in-batches.d.ts.map +1 -0
  113. package/dist/scan/query-arrow-table-in-batches.js +44 -0
  114. package/dist/scan/query-arrow-table-in-batches.js.map +1 -0
  115. package/dist/scan/query-arrow-table.cjs +52 -179
  116. package/dist/scan/query-arrow-table.cjs.map +3 -3
  117. package/dist/scan/query-arrow-table.d.ts +4 -37
  118. package/dist/scan/query-arrow-table.d.ts.map +1 -1
  119. package/dist/scan/query-arrow-table.js +37 -188
  120. package/dist/scan/query-arrow-table.js.map +1 -1
  121. package/dist/scan/query.cjs +344 -0
  122. package/dist/scan/query.cjs.map +7 -0
  123. package/dist/scan/query.d.ts +42 -0
  124. package/dist/scan/query.d.ts.map +1 -0
  125. package/dist/scan/query.js +367 -0
  126. package/dist/scan/query.js.map +1 -0
  127. package/dist/scan/resolve-query-source.cjs +59 -0
  128. package/dist/scan/resolve-query-source.cjs.map +7 -0
  129. package/dist/scan/resolve-query-source.d.ts +6 -0
  130. package/dist/scan/resolve-query-source.d.ts.map +1 -0
  131. package/dist/scan/resolve-query-source.js +37 -0
  132. package/dist/scan/resolve-query-source.js.map +1 -0
  133. package/dist/scan/sql-catalog.cjs +110 -0
  134. package/dist/scan/sql-catalog.cjs.map +7 -0
  135. package/dist/scan/sql-catalog.d.ts +47 -0
  136. package/dist/scan/sql-catalog.d.ts.map +1 -0
  137. package/dist/scan/sql-catalog.js +97 -0
  138. package/dist/scan/sql-catalog.js.map +1 -0
  139. package/dist/scan/table-query.cjs.map +2 -2
  140. package/dist/scan/table-query.d.ts +4 -1
  141. package/dist/scan/table-query.d.ts.map +1 -1
  142. package/dist/scan/table-query.js.map +1 -1
  143. package/dist/vector-table-scan-source.cjs +288 -193
  144. package/dist/vector-table-scan-source.cjs.map +3 -3
  145. package/dist/worker-utils/index.cjs +2 -1
  146. package/dist/worker-utils/index.cjs.map +1 -1
  147. package/dist/worker-utils/lib/env-utils/version.js +1 -1
  148. package/dist/worker-utils/lib/library-utils/library-utils.js +1 -1
  149. package/dist/worker-utils/lib/library-utils/library-utils.js.map +1 -1
  150. package/package.json +17 -7
  151. package/src/loader-utils/index.ts +30 -6
  152. package/src/loader-utils/lib/files/http-file-transport.ts +65 -1
  153. package/src/loader-utils/lib/files/http-file-types.ts +2 -0
  154. package/src/loader-utils/lib/files/read-range-response.ts +66 -0
  155. package/src/loader-utils/lib/scan-utils/logical-table-query.ts +164 -0
  156. package/src/loader-utils/lib/scan-utils/query-options.ts +44 -0
  157. package/src/loader-utils/lib/scan-utils/scan-query-metadata.ts +17 -26
  158. package/src/loader-utils/lib/scan-utils/table-query.ts +49 -8
  159. package/src/loader-utils/lib/scan-utils/table-scan-batch.ts +25 -9
  160. package/src/loader-utils/lib/sources/data-source.ts +54 -1
  161. package/src/loader-utils/lib/sources/table-source-collection.ts +38 -0
  162. package/src/loader-utils/loader-types.ts +5 -5
  163. package/src/scan/arrow-execution/expressions.ts +86 -0
  164. package/src/scan/arrow-execution/filter-arrow-table.ts +309 -0
  165. package/src/scan/arrow-execution/project-arrow-table.ts +53 -0
  166. package/src/scan/arrow-execution.ts +7 -0
  167. package/src/scan/arrow-query.ts +3 -0
  168. package/src/scan/catalog-query-source.ts +132 -0
  169. package/src/scan/federated-table-scan-source.ts +19 -19
  170. package/src/scan/index.ts +28 -4
  171. package/src/scan/parse-sql-predicate.ts +14 -367
  172. package/src/scan/query-arrow-table-in-batches.ts +58 -0
  173. package/src/scan/query-arrow-table.ts +60 -237
  174. package/src/scan/query.ts +480 -0
  175. package/src/scan/resolve-query-source.ts +47 -0
  176. package/src/scan/sql-catalog.ts +167 -0
  177. package/src/scan/table-query.ts +6 -1
  178. package/src/worker-utils/lib/library-utils/library-utils.ts +1 -1
  179. package/dist/loader-utils/lib/scan-utils/experimental-scan-options.d.ts.map +0 -1
  180. package/dist/loader-utils/lib/scan-utils/experimental-scan-options.js.map +0 -1
  181. package/src/loader-utils/lib/scan-utils/experimental-scan-options.ts +0 -46
@@ -0,0 +1,480 @@
1
+ // loaders.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import * as arrow from 'apache-arrow';
6
+ import type {SQLQuery} from '@math.gl/core/sql';
7
+ import type {ArrowTable, ArrowTableBatch, TableBatch, Schema} from '@loaders.gl/core/schema';
8
+ import {
9
+ normalizeTableQuery,
10
+ getColumnarPredicateColumns,
11
+ executeTableScanBatches,
12
+ planTableQuery,
13
+ emitQueryComplete,
14
+ type TableQuery,
15
+ type TableQueryExecutionOptions,
16
+ type TableQueryExecutionSummary,
17
+ type TableScanSource,
18
+ type TableScanReadOptions,
19
+ type LoaderOptions,
20
+ type DataSourceOptions,
21
+ type SourceLoader,
22
+ resolveLoaderAuthenticationOptions,
23
+ isSourceLoader
24
+ } from '@loaders.gl/core/loader-utils';
25
+ import {
26
+ convertArrowToSchema,
27
+ convertSchemaToArrow,
28
+ convertTableToArrow
29
+ } from '@loaders.gl/core/schema-utils';
30
+ import {projectArrowTable, filterArrowTable} from './arrow-execution';
31
+ import {filterArrowRows} from './arrow-execution/filter-arrow-table';
32
+ import {createCatalogQuerySource} from './catalog-query-source';
33
+ import type {SQLCatalogQuery} from './sql-catalog';
34
+ import {resolveQuerySource} from './resolve-query-source';
35
+ import type {DataSource} from '@loaders.gl/core/loader-utils';
36
+
37
+ /** Logical table or metadata request. */
38
+ export type Query = TableQuery | SQLQuery;
39
+
40
+ /** Injected SQL parser; core validates and executes the returned logical query. */
41
+ export type SQLQueryParser = (sql: string) => Query | Promise<Query>;
42
+
43
+ /** Input and execution controls for one public asynchronous table query. */
44
+ export type QueryOptions = TableQueryExecutionOptions &
45
+ LoaderOptions &
46
+ Readonly<{
47
+ /** Source construction options, including an explicit core.name. */
48
+ core?: DataSourceOptions['core'];
49
+ /** Named caller-owned data sources used by FROM and metadata commands. */
50
+ sources?: readonly DataSource<unknown, DataSourceOptions>[];
51
+ /** Parser or lazy parser promise, required only for SQL string input. */
52
+ sqlParser?: SQLQueryParser | Promise<SQLQueryParser>;
53
+ }> &
54
+ Readonly<
55
+ | {
56
+ /** Already loaded Arrow table or caller-owned table scan source. */
57
+ source: ArrowTable | TableScanSource;
58
+ /** URL loader selection is only used with URL sources. */
59
+ loaders?: never;
60
+ }
61
+ | {
62
+ /** FROM chooses a source from the named registry when no default source is supplied. */
63
+ source?: undefined;
64
+ /** Named sources available for FROM resolution. */
65
+ sources: readonly DataSource<unknown, DataSourceOptions>[];
66
+ /** URL loader selection requires a URL source. */
67
+ loaders?: never;
68
+ }
69
+ | {
70
+ /** URL opened lazily with the explicitly supplied source loaders. */
71
+ source: string;
72
+ /** URL-capable source loaders; registered loaders are never selected implicitly. */
73
+ loaders: SourceLoader | SourceLoader[];
74
+ }
75
+ >;
76
+
77
+ /** Collects the same ordered Arrow batch pipeline exposed by queryInBatches. */
78
+ export async function query(
79
+ tableQuery: Query | string,
80
+ options: QueryOptions
81
+ ): Promise<ArrowTable> {
82
+ let schema: arrow.Schema | undefined;
83
+ const batches: arrow.RecordBatch[] = [];
84
+ for await (const batch of queryInBatches(tableQuery, options)) {
85
+ schema = batch.data.schema;
86
+ batches.push(...batch.data.batches);
87
+ }
88
+ const data = new arrow.Table(schema!, batches);
89
+ return {shape: 'arrow-table', schema: convertArrowToSchema(data.schema), data};
90
+ }
91
+
92
+ /** Executes one logical query with bounded batch buffering and cooperative cancellation. */
93
+ export async function* queryInBatches(
94
+ tableQuery: Query | string,
95
+ options: QueryOptions
96
+ ): AsyncIterable<ArrowTableBatch> {
97
+ const startedAt = Date.now();
98
+ let status: TableQueryExecutionSummary['status'] = 'early-terminated';
99
+ let rowsRead = 0;
100
+ let rowsReturned = 0;
101
+ let batchesRead = 0;
102
+ let sourcesRead = 0;
103
+ let error: unknown;
104
+ let ownedSource: {close?: () => void | Promise<void>} | undefined;
105
+ let earlyTerminationReason: TableQueryExecutionSummary['earlyTerminationReason'];
106
+ try {
107
+ options.signal?.throwIfAborted();
108
+ let parsedQuery: Query;
109
+ if (typeof tableQuery === 'string') {
110
+ const parser = await options.sqlParser;
111
+ options.signal?.throwIfAborted();
112
+ if (typeof parser !== 'function')
113
+ throw new Error('SQL queries require a sqlParser function or promise.');
114
+ parsedQuery = await parser(tableQuery);
115
+ options.signal?.throwIfAborted();
116
+ } else parsedQuery = tableQuery;
117
+ if (!parsedQuery || typeof parsedQuery !== 'object' || Array.isArray(parsedQuery))
118
+ throw new Error('Table query must be an object.');
119
+ const castPredicate =
120
+ 'command' in parsedQuery ? false : validatePredicateOperands(parsedQuery.where);
121
+ let logicalQuery: TableQuery | Exclude<SQLQuery, SQLCatalogQuery>;
122
+ let source: unknown;
123
+ if ('command' in parsedQuery) {
124
+ logicalQuery = {};
125
+ source = createCatalogQuerySource(parsedQuery, options.sources);
126
+ } else {
127
+ logicalQuery = parsedQuery;
128
+ source =
129
+ logicalQuery.from === undefined
130
+ ? options.source
131
+ : await resolveQuerySource(logicalQuery.from, options.sources, options.signal);
132
+ }
133
+ if (logicalQuery.from === undefined && typeof source === 'string') {
134
+ const opened = await openQuerySource(options);
135
+ if (
136
+ opened &&
137
+ typeof opened === 'object' &&
138
+ 'close' in opened &&
139
+ typeof opened.close === 'function'
140
+ )
141
+ ownedSource = opened as {close: () => void | Promise<void>};
142
+ source = opened;
143
+ }
144
+ options.signal?.throwIfAborted();
145
+ if (!source || typeof source !== 'object')
146
+ throw new Error('Query source must be an Arrow table or table scan source.');
147
+ const inMemory = 'shape' in source && source.shape === 'arrow-table';
148
+ if (
149
+ !inMemory &&
150
+ (!('read' in source) ||
151
+ typeof source.read !== 'function' ||
152
+ !('getQueryMetadata' in source) ||
153
+ typeof source.getQueryMetadata !== 'function')
154
+ ) {
155
+ throw new Error('Query source must be an Arrow table or table scan source.');
156
+ }
157
+ const metadata = inMemory
158
+ ? undefined
159
+ : await (source as TableScanSource).getQueryMetadata({signal: options.signal});
160
+ options.signal?.throwIfAborted();
161
+ if (
162
+ metadata &&
163
+ (metadata.queryType !== 'table' ||
164
+ metadata.execution.status !== 'supported' ||
165
+ metadata.execution.method !== 'read')
166
+ ) {
167
+ throw new Error('Query source must support table reads.');
168
+ }
169
+ const sourceSchema = inMemory
170
+ ? (source as ArrowTable).data.schema
171
+ : convertSchemaToArrow(metadata!.schema);
172
+ const names = sourceSchema.fields.map(field => field.name);
173
+ const {select, where, ...controls} = logicalQuery;
174
+ const computedProjection =
175
+ Array.isArray(select) &&
176
+ select.some(
177
+ selection =>
178
+ selection &&
179
+ typeof selection === 'object' &&
180
+ ('expression' in selection || 'array' in selection)
181
+ );
182
+ const expressionFilter =
183
+ where && typeof where === 'object' && 'expression' in where ? where : undefined;
184
+ const portablePredicate = expressionFilter ? undefined : (where as TableQuery['where']);
185
+ const normalized = normalizeTableQuery(names, {
186
+ ...controls,
187
+ select: computedProjection ? undefined : (select as TableQuery['select']),
188
+ where: castPredicate ? undefined : portablePredicate
189
+ });
190
+ const expressionTools =
191
+ computedProjection || expressionFilter || castPredicate
192
+ ? await import('./arrow-execution/expressions')
193
+ : undefined;
194
+ const outputColumns = computedProjection
195
+ ? expressionTools!.getProjectionColumns(select!)
196
+ : normalized.select.map(selection => selection.column);
197
+ const expressionColumns = expressionFilter
198
+ ? expressionTools!.getExpressionColumns(expressionFilter.expression)
199
+ : castPredicate && portablePredicate
200
+ ? getColumnarPredicateColumns(portablePredicate)
201
+ : [];
202
+ const required = [...new Set([...outputColumns, ...expressionColumns])];
203
+ const plan = planTableQuery(names, {
204
+ // A literal-only projection still needs a physical column to retain row counts.
205
+ columns: required.length ? required : names.slice(0, 1),
206
+ predicate: normalized.where
207
+ });
208
+ const requiredColumns = plan[0].kind === 'scan' ? plan[0].columns : names;
209
+ const capabilities = metadata?.capabilities.table;
210
+ // read() must perform exact filtering when it advertises pushdown+residual, not only pruning.
211
+ const delegatePredicate = Boolean(
212
+ normalized.where &&
213
+ capabilities &&
214
+ ['pushdown', 'pushdown+residual'].includes(capabilities.predicate)
215
+ );
216
+ const residual = delegatePredicate ? undefined : normalized.where;
217
+ const readOptions: TableScanReadOptions = {
218
+ signal: options.signal,
219
+ ...(capabilities && capabilities.projection !== 'unsupported'
220
+ ? {columns: requiredColumns}
221
+ : {}),
222
+ ...(delegatePredicate ? {predicate: normalized.where} : {}),
223
+ ...(!residual &&
224
+ !expressionFilter &&
225
+ !castPredicate &&
226
+ capabilities &&
227
+ ['pushdown', 'pushdown+residual'].includes(capabilities.limit)
228
+ ? {limit: normalized.limit}
229
+ : {})
230
+ };
231
+ const inputSchema = readOptions.columns
232
+ ? sourceSchema.select([...readOptions.columns])
233
+ : sourceSchema;
234
+ const readSchema = convertArrowToSchema(inputSchema);
235
+ const comparisonInputSchema = expressionTools ? convertSchemaToArrow(readSchema) : undefined;
236
+ const compiledFilter = expressionFilter
237
+ ? expressionTools!.compileArrowExpression(expressionFilter.expression, {inputSchema})
238
+ : castPredicate && portablePredicate
239
+ ? expressionTools!.compileArrowPredicate(portablePredicate, {inputSchema})
240
+ : undefined;
241
+ if (compiledFilter && !arrow.DataType.isBool(compiledFilter.outputField.type))
242
+ throw new Error('SQL WHERE expression must return Boolean.');
243
+ const project = computedProjection
244
+ ? expressionTools!.compileArrowProjection(inputSchema, select!, options.signal)
245
+ : (data: arrow.Table) => projectArrowTable(data, normalized.select);
246
+ const empty = project(new arrow.Table(inputSchema));
247
+ const comparisonSchema = convertSchemaToArrow(convertArrowToSchema(empty.schema));
248
+ let emitted = false;
249
+ /** Adapts physical batches without pulling ahead of the query consumer. */
250
+ async function* inputs(): AsyncIterable<ArrowTableBatch> {
251
+ sourcesRead = 1;
252
+ const batches: AsyncIterable<unknown> = inMemory
253
+ ? memoryBatches((source as ArrowTable).data)
254
+ : (source as TableScanSource).read(readOptions);
255
+ for await (const value of batches) {
256
+ options.signal?.throwIfAborted();
257
+ let batch = normalizeBatch(value, readSchema);
258
+ if (
259
+ comparisonInputSchema &&
260
+ !arrow.util.compareSchemas(comparisonInputSchema, convertSchemaToArrow(batch.schema!))
261
+ ) {
262
+ // A source may return a wider or differently ordered projection than requested.
263
+ const data = batch.data.select(inputSchema.names);
264
+ batch = {...batch, ...wrapBatch(data)};
265
+ if (
266
+ !arrow.util.compareSchemas(comparisonInputSchema, convertSchemaToArrow(batch.schema!))
267
+ )
268
+ throw new Error('Query input schema does not match source metadata.');
269
+ }
270
+ batchesRead++;
271
+ rowsRead += batch.length;
272
+ yield batch;
273
+ }
274
+ }
275
+ for await (const value of executeTableScanBatches(
276
+ () => inputs(),
277
+ {
278
+ predicate: residual,
279
+ limit: normalized.limit,
280
+ signal: options.signal
281
+ },
282
+ {
283
+ filter: (batch, predicate, signal) => {
284
+ const input = batch as ArrowTableBatch;
285
+ const data = compiledFilter
286
+ ? filterArrowRows(
287
+ input.data,
288
+ batch => {
289
+ const matches = compiledFilter.evaluate(batch, {signal});
290
+ return index => matches.get(index) === true;
291
+ },
292
+ {signal}
293
+ )
294
+ : predicate
295
+ ? filterArrowTable(input.data, predicate, {signal})
296
+ : input.data;
297
+ return {...input, ...wrapBatch(data)};
298
+ },
299
+ project: batch => {
300
+ const input = batch as ArrowTableBatch;
301
+ return computedProjection ? input : {...input, ...wrapBatch(project(input.data))};
302
+ }
303
+ }
304
+ )) {
305
+ const input = value as ArrowTableBatch;
306
+ const batch = computedProjection ? {...input, ...wrapBatch(project(input.data))} : input;
307
+ if (!arrow.util.compareSchemas(comparisonSchema, convertSchemaToArrow(batch.schema!)))
308
+ throw new Error('Query output schema does not match source metadata.');
309
+ emitted = true;
310
+ rowsReturned += batch.length;
311
+ yield batch;
312
+ }
313
+ // An empty schema-bearing batch makes collected and streaming empty results identical.
314
+ if (!emitted) yield wrapBatch(empty);
315
+ if (normalized.limit !== undefined && rowsReturned >= normalized.limit)
316
+ earlyTerminationReason = 'limit';
317
+ status = earlyTerminationReason ? 'early-terminated' : 'completed';
318
+ } catch (failure) {
319
+ error = failure;
320
+ status = options.signal?.aborted ? 'cancelled' : 'failed';
321
+ throw failure;
322
+ } finally {
323
+ if (status === 'early-terminated' && !earlyTerminationReason)
324
+ earlyTerminationReason = 'consumer-return';
325
+ try {
326
+ await ownedSource?.close?.();
327
+ } catch (failure) {
328
+ if (error === undefined) {
329
+ error = failure;
330
+ status = options.signal?.aborted ? 'cancelled' : 'failed';
331
+ earlyTerminationReason = undefined;
332
+ throw failure;
333
+ }
334
+ } finally {
335
+ emitQueryComplete(
336
+ options.onQueryComplete,
337
+ Object.freeze({
338
+ status,
339
+ sourcesPlanned: 1,
340
+ sourcesRead,
341
+ batchesRead,
342
+ rowsRead,
343
+ rowsReturned,
344
+ durationMilliseconds: Date.now() - startedAt,
345
+ ...(earlyTerminationReason ? {earlyTerminationReason} : {}),
346
+ ...(error === undefined ? {} : {error})
347
+ })
348
+ );
349
+ }
350
+ }
351
+ }
352
+
353
+ /** Emits original Arrow RecordBatches without copying their buffers. */
354
+ async function* memoryBatches(data: arrow.Table): AsyncIterable<ArrowTableBatch> {
355
+ for (const batch of data.batches) yield wrapBatch(new arrow.Table(data.schema, [batch]));
356
+ }
357
+
358
+ /** Converts supported native table batches to Arrow while preserving their declared schema. */
359
+ function normalizeBatch(value: unknown, fallbackSchema: Schema): ArrowTableBatch {
360
+ if (!value || typeof value !== 'object' || !('shape' in value))
361
+ throw new Error('Query source returned an unsupported batch.');
362
+ const input = value as TableBatch;
363
+ const batch = {...input, schema: input.schema ?? fallbackSchema} as TableBatch;
364
+ if (
365
+ !['arrow-table', 'object-row-table', 'array-row-table', 'columnar-table'].includes(batch.shape)
366
+ )
367
+ throw new Error(`Unsupported query batch shape: ${batch.shape}`);
368
+ const data =
369
+ batch.length === 0 && batch.schema
370
+ ? new arrow.Table(convertSchemaToArrow(batch.schema))
371
+ : convertTableToArrow(batch);
372
+ return {...batch, ...wrapBatch(data)} as ArrowTableBatch;
373
+ }
374
+
375
+ /** Wraps Arrow data in the standard batch envelope. */
376
+ function wrapBatch(data: arrow.Table): ArrowTableBatch {
377
+ return {
378
+ shape: 'arrow-table',
379
+ data,
380
+ schema: convertArrowToSchema(data.schema),
381
+ batchType: 'data',
382
+ length: data.numRows
383
+ } as ArrowTableBatch;
384
+ }
385
+
386
+ /** Opens only explicit URL source loaders; the public query owns the returned source. */
387
+ async function openQuerySource(options: QueryOptions): Promise<unknown> {
388
+ const candidates = Array.isArray(options.loaders) ? options.loaders : [options.loaders];
389
+ if (!candidates.length || candidates.some(loader => !isSourceLoader(loader) || !loader.fromUrl))
390
+ throw new Error('Query source must specify explicit URL-capable source loaders for a URL.');
391
+ const {source, sources, loaders, sqlParser, onQueryComplete, ...sourceOptions} = options;
392
+ const url = source as string;
393
+ const selected =
394
+ candidates.length === 1 ? candidates[0]! : candidates.find(loader => loader!.testURL(url));
395
+ if (!selected) throw new Error('No explicit source loader matches the query URL.');
396
+ const implementation = selected.preload ? await selected.preload(url, sourceOptions) : selected;
397
+ options.signal?.throwIfAborted();
398
+ if (!isSourceLoader(implementation) || !implementation.fromUrl)
399
+ throw new Error('Query source preload did not return a URL-capable source loader.');
400
+ const authenticatedOptions = await resolveLoaderAuthenticationOptions(
401
+ selected.getAuthentications ? selected : implementation,
402
+ url,
403
+ {...sourceOptions, core: {...sourceOptions.core, ignoreRegisteredLoaders: true}}
404
+ );
405
+ options.signal?.throwIfAborted();
406
+ return implementation.createDataSource(url, authenticatedOptions as DataSourceOptions);
407
+ }
408
+
409
+ export {parseSQLQuery, parseSQLSelect, type SQLSelectParserOptions} from '@math.gl/core/sql';
410
+
411
+ export {createSQLCatalog} from './sql-catalog';
412
+ export type {SQLCatalog, SQLCatalogQuery, SQLCatalogSource, SQLCatalogTable} from './sql-catalog';
413
+
414
+ /** Checks predicate tree bounds and detects casts that require Arrow execution. */
415
+ function validatePredicateOperands(where: unknown): boolean {
416
+ if (where && typeof where === 'object' && 'expression' in where) {
417
+ if (Object.keys(where).some(key => key !== 'expression'))
418
+ throw new Error('Unsupported computed WHERE field.');
419
+ return false;
420
+ }
421
+ let castPredicate = false;
422
+ const pending: {value: unknown; exit?: boolean}[] = where ? [{value: where}] : [];
423
+ const visited = new WeakSet<object>();
424
+ let nodes = 0;
425
+ while (pending.length) {
426
+ const frame = pending.pop()!;
427
+ const candidate = frame.value;
428
+ if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) continue;
429
+ if (frame.exit) {
430
+ visited.delete(candidate);
431
+ continue;
432
+ }
433
+ if (visited.has(candidate) || ++nodes > 4096)
434
+ throw new Error('Query predicate must be an acyclic tree of at most 4096 nodes.');
435
+ visited.add(candidate);
436
+ if (isUnsupportedQueryExpression(candidate))
437
+ throw new Error('CAST and computed WHERE operands are not supported by this query executor.');
438
+ const predicate = candidate as {op?: unknown; args?: unknown};
439
+ if (!Array.isArray(predicate.args)) continue;
440
+ if (predicate.op === 'and' || predicate.op === 'or' || predicate.op === 'not') {
441
+ if (predicate.args.length > 4096 - nodes)
442
+ throw new Error('Query predicate exceeds 4096 nodes.');
443
+ pending.push({value: candidate, exit: true});
444
+ pending.push(...predicate.args.map(value => ({value})));
445
+ continue;
446
+ }
447
+ visited.delete(candidate);
448
+ for (const [index, operand] of predicate.args.entries()) {
449
+ if (
450
+ index === 0 &&
451
+ operand &&
452
+ typeof operand === 'object' &&
453
+ typeof operand.property === 'string' &&
454
+ 'casts' in operand
455
+ ) {
456
+ castPredicate = true;
457
+ continue;
458
+ }
459
+ if (
460
+ isUnsupportedQueryExpression(operand) ||
461
+ (Array.isArray(operand) && operand.some(isUnsupportedQueryExpression))
462
+ )
463
+ throw new Error(
464
+ 'CAST and computed WHERE operands are not supported by this query executor.'
465
+ );
466
+ }
467
+ }
468
+ return castPredicate;
469
+ }
470
+
471
+ /** Identifies newer portable operands and raw expression ASTs without interpreting scalar values. */
472
+ function isUnsupportedQueryExpression(value: unknown): boolean {
473
+ if (!value || typeof value !== 'object') return false;
474
+ if ('casts' in value || 'expression' in value) return true;
475
+ return (
476
+ 'type' in value &&
477
+ typeof value.type === 'string' &&
478
+ /Expression$|^(Identifier|Literal|Compound)$/.test(value.type)
479
+ );
480
+ }
@@ -0,0 +1,47 @@
1
+ // loaders.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import {validateTableReference} from '@loaders.gl/core/loader-utils';
6
+ import type {
7
+ DataSource,
8
+ DataSourceOptions,
9
+ TableReference,
10
+ TableSourceCollection
11
+ } from '@loaders.gl/core/loader-utils';
12
+
13
+ /** Resolves one literal source/table reference without inspecting unrelated source data. */
14
+ export async function resolveQuerySource(
15
+ reference: TableReference,
16
+ sources: readonly DataSource<unknown, DataSourceOptions>[] | undefined,
17
+ signal?: AbortSignal
18
+ ): Promise<unknown> {
19
+ validateTableReference(reference);
20
+ const registry = createSourceRegistry(sources);
21
+ const name = typeof reference === 'string' ? reference : reference.source;
22
+ const source = registry.get(name);
23
+ if (!source) throw new Error(`Unknown data source: ${name}`);
24
+ signal?.throwIfAborted();
25
+ if (typeof reference === 'string') return source;
26
+ const collection = source as unknown as Partial<TableSourceCollection>;
27
+ if (typeof collection.getTable !== 'function')
28
+ throw new Error(`Data source ${name} does not expose named tables.`);
29
+ const table = await collection.getTable(reference.table, {signal});
30
+ signal?.throwIfAborted();
31
+ return table;
32
+ }
33
+
34
+ /** Snapshots source identities consistently for FROM and metadata queries. */
35
+ export function createSourceRegistry(
36
+ sources: readonly DataSource<unknown, DataSourceOptions>[] | undefined
37
+ ): ReadonlyMap<string, DataSource<unknown, DataSourceOptions>> {
38
+ if (!Array.isArray(sources)) throw new Error('Query requires a sources array.');
39
+ const registry = new Map<string, DataSource<unknown, DataSourceOptions>>();
40
+ for (const source of sources) {
41
+ if (!source || typeof source.name !== 'string' || !source.name.trim())
42
+ throw new Error('Registered data sources require non-empty names.');
43
+ if (registry.has(source.name)) throw new Error(`Duplicate data source name: ${source.name}`);
44
+ registry.set(source.name, source);
45
+ }
46
+ return registry;
47
+ }
@@ -0,0 +1,167 @@
1
+ // loaders.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import type {Schema} from '@loaders.gl/core/schema';
6
+ import type {
7
+ DataSource,
8
+ DataSourceOptions,
9
+ TableReference,
10
+ TableDiscoverySource,
11
+ TableMetadata,
12
+ TableScanSource,
13
+ TableSourceCollection
14
+ } from '@loaders.gl/core/loader-utils';
15
+ import {validateTableReference} from '@loaders.gl/core/loader-utils';
16
+ import {createSourceRegistry} from './resolve-query-source';
17
+
18
+ /** Portable logical metadata commands, independent of SQL parsing and execution controls. */
19
+ export type SQLCatalogQuery = Readonly<
20
+ | {
21
+ /** Lists locally registered source names. */
22
+ command: 'showSources';
23
+ }
24
+ | {
25
+ /** Lists discoverable tables in registration order. */
26
+ command: 'showTables';
27
+ /** Optional exact source name; omission discovers every registered source. */
28
+ from?: string;
29
+ }
30
+ | {
31
+ /** Describes the fields of one table. */
32
+ command: 'describe';
33
+ /** Literal source name, or separate source and loaded table names. */
34
+ from: TableReference;
35
+ }
36
+ >;
37
+
38
+ /** One locally registered source, available without metadata I/O. */
39
+ export type SQLCatalogSource = Readonly<{
40
+ /** Stable DataSource.name. */
41
+ name: string;
42
+ }>;
43
+
44
+ /** One discovered table with its actual logical FROM reference. */
45
+ export type SQLCatalogTable = TableMetadata &
46
+ Readonly<{
47
+ /** Parent DataSource.name. */
48
+ sourceName: string;
49
+ /** Literal or qualified reference used by the query API. */
50
+ reference: TableReference;
51
+ /** Whether the provider advertises table query support. */
52
+ queryable: boolean;
53
+ }>;
54
+
55
+ /** Lazy schema model shared by SQL commands and schema explorer applications. */
56
+ export interface SQLCatalog {
57
+ /** Lists registered source names without contacting them. */
58
+ getSources(): readonly SQLCatalogSource[];
59
+ /** Discovers tables only in the requested source, or all sources in registration order. */
60
+ getTables(
61
+ sourceName?: string,
62
+ options?: {signal?: AbortSignal}
63
+ ): Promise<readonly SQLCatalogTable[]>;
64
+ /** Discovers one table's portable schema without calling read() or getTable(). */
65
+ getSchema(reference: TableReference, options?: {signal?: AbortSignal}): Promise<Schema>;
66
+ }
67
+
68
+ /** Creates a lazy metadata catalog over caller-owned sources; it does not open or close them. */
69
+ export function createSQLCatalog(
70
+ sources: readonly DataSource<unknown, DataSourceOptions>[]
71
+ ): SQLCatalog {
72
+ const registry = createSourceRegistry(sources);
73
+ const names = Object.freeze([...registry.keys()].map(name => Object.freeze({name})));
74
+ /** Looks up exact names without falling back to a default source. */
75
+ function getSource(name: string) {
76
+ const source = registry.get(name);
77
+ if (!source) throw new Error(`Unknown data source: ${name}`);
78
+ return source;
79
+ }
80
+ /** Adapts one source's metadata discovery without reading table rows. */
81
+ async function getTables(
82
+ sourceName?: string,
83
+ options: {signal?: AbortSignal} = {}
84
+ ): Promise<readonly SQLCatalogTable[]> {
85
+ options.signal?.throwIfAborted();
86
+ const selected = sourceName === undefined ? [...registry.values()] : [getSource(sourceName)];
87
+ const result: SQLCatalogTable[] = [];
88
+ for (const source of selected) {
89
+ options.signal?.throwIfAborted();
90
+ const discovery = source as unknown as Partial<
91
+ TableDiscoverySource & TableSourceCollection & TableScanSource
92
+ >;
93
+ if (typeof discovery.getTablesMetadata === 'function') {
94
+ const tables = await discovery.getTablesMetadata(options);
95
+ options.signal?.throwIfAborted();
96
+ const tableNames = new Set<string>();
97
+ if (!Array.isArray(tables)) throw new Error('Table discovery must return an array.');
98
+ for (const table of tables) {
99
+ if (
100
+ !table ||
101
+ typeof table.name !== 'string' ||
102
+ !table.name.trim() ||
103
+ tableNames.has(table.name)
104
+ )
105
+ throw new Error('Table metadata requires unique non-empty names.');
106
+ if (table.queryable !== undefined && typeof table.queryable !== 'boolean')
107
+ throw new Error('Table metadata queryable must be a boolean.');
108
+ tableNames.add(table.name);
109
+ result.push({
110
+ ...table,
111
+ sourceName: source.name,
112
+ reference: {source: source.name, table: table.name},
113
+ queryable: table.queryable ?? typeof discovery.getTable === 'function'
114
+ });
115
+ }
116
+ } else if (typeof discovery.getQueryMetadata === 'function') {
117
+ const metadata = await discovery.getQueryMetadata(options);
118
+ options.signal?.throwIfAborted();
119
+ if (metadata.queryType === 'table')
120
+ result.push({
121
+ name: source.name,
122
+ sourceName: source.name,
123
+ reference: source.name,
124
+ schema: metadata.schema,
125
+ queryable:
126
+ typeof discovery.read === 'function' &&
127
+ metadata.execution.status === 'supported' &&
128
+ metadata.execution.method === 'read'
129
+ });
130
+ }
131
+ }
132
+ return result;
133
+ }
134
+ /** Resolves schemas through metadata APIs, never by opening a child table. */
135
+ async function getSchema(
136
+ reference: TableReference,
137
+ options: {signal?: AbortSignal} = {}
138
+ ): Promise<Schema> {
139
+ validateTableReference(reference);
140
+ if (reference === undefined) throw new Error('A table reference is required.');
141
+ options.signal?.throwIfAborted();
142
+ const sourceName = typeof reference === 'string' ? reference : reference.source;
143
+ const source = getSource(sourceName);
144
+ const discovery = source as unknown as Partial<TableDiscoverySource & TableScanSource>;
145
+ let schema: Schema | undefined;
146
+ if (typeof reference === 'string') {
147
+ if (typeof discovery.getTablesMetadata === 'function')
148
+ throw new Error(
149
+ `DESCRIBE requires a qualified table reference for collection ${sourceName}.`
150
+ );
151
+ if (typeof discovery.getQueryMetadata === 'function') {
152
+ const metadata = await discovery.getQueryMetadata(options);
153
+ if (metadata.queryType === 'table') schema = metadata.schema;
154
+ }
155
+ } else if (typeof discovery.getTableMetadata === 'function') {
156
+ schema = (await discovery.getTableMetadata(reference.table, options)).schema;
157
+ } else {
158
+ schema = (await getTables(sourceName, options)).find(
159
+ table => typeof table.reference === 'object' && table.name === reference.table
160
+ )?.schema;
161
+ }
162
+ options.signal?.throwIfAborted();
163
+ if (!schema) throw new Error(`No discoverable table schema: ${sourceName}`);
164
+ return schema;
165
+ }
166
+ return Object.freeze({getSources: () => names, getTables, getSchema});
167
+ }