@loaders.gl/core 5.0.0-beta.6 → 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 (58) hide show
  1. package/dist/dist.min.js +2 -2
  2. package/dist/federated-table-scan-source.cjs +10 -3
  3. package/dist/federated-table-scan-source.cjs.map +1 -1
  4. package/dist/index.cjs +1 -1
  5. package/dist/lib/init.js +1 -1
  6. package/dist/loader-utils/index.cjs +2 -2
  7. package/dist/loader-utils/json-loader.js +1 -1
  8. package/dist/loader-utils/lib/log-utils/log.js +1 -1
  9. package/dist/null-loader.js +1 -1
  10. package/dist/null-worker-node.js +1 -1
  11. package/dist/null-worker.js +1 -1
  12. package/dist/scan/arrow-execution/expressions.cjs +110 -0
  13. package/dist/scan/arrow-execution/expressions.cjs.map +7 -0
  14. package/dist/scan/arrow-execution/expressions.d.ts +9 -0
  15. package/dist/scan/arrow-execution/expressions.d.ts.map +1 -0
  16. package/dist/scan/arrow-execution/expressions.js +60 -0
  17. package/dist/scan/arrow-execution/expressions.js.map +1 -0
  18. package/dist/scan/arrow-execution/filter-arrow-table.cjs +15 -3
  19. package/dist/scan/arrow-execution/filter-arrow-table.cjs.map +2 -2
  20. package/dist/scan/arrow-execution/filter-arrow-table.d.ts +2 -0
  21. package/dist/scan/arrow-execution/filter-arrow-table.d.ts.map +1 -1
  22. package/dist/scan/arrow-execution/filter-arrow-table.js +10 -2
  23. package/dist/scan/arrow-execution/filter-arrow-table.js.map +1 -1
  24. package/dist/scan/parse-sql-predicate.cjs +3 -294
  25. package/dist/scan/parse-sql-predicate.cjs.map +3 -3
  26. package/dist/scan/parse-sql-predicate.d.ts +1 -7
  27. package/dist/scan/parse-sql-predicate.d.ts.map +1 -1
  28. package/dist/scan/parse-sql-predicate.js +5 -307
  29. package/dist/scan/parse-sql-predicate.js.map +1 -1
  30. package/dist/scan/query.cjs +103 -16
  31. package/dist/scan/query.cjs.map +3 -3
  32. package/dist/scan/query.d.ts +3 -5
  33. package/dist/scan/query.d.ts.map +1 -1
  34. package/dist/scan/query.js +133 -12
  35. package/dist/scan/query.js.map +1 -1
  36. package/dist/vector-table-scan-source.cjs +10 -3
  37. package/dist/vector-table-scan-source.cjs.map +1 -1
  38. package/dist/worker-utils/index.cjs +1 -1
  39. package/dist/worker-utils/lib/env-utils/version.js +1 -1
  40. package/package.json +7 -7
  41. package/src/scan/arrow-execution/expressions.ts +86 -0
  42. package/src/scan/arrow-execution/filter-arrow-table.ts +19 -3
  43. package/src/scan/parse-sql-predicate.ts +8 -367
  44. package/src/scan/query.ts +157 -16
  45. package/dist/scan/parse-sql-query.cjs +0 -70
  46. package/dist/scan/parse-sql-query.cjs.map +0 -7
  47. package/dist/scan/parse-sql-query.d.ts +0 -5
  48. package/dist/scan/parse-sql-query.d.ts.map +0 -1
  49. package/dist/scan/parse-sql-query.js +0 -49
  50. package/dist/scan/parse-sql-query.js.map +0 -1
  51. package/dist/scan/parse-sql-select.cjs +0 -215
  52. package/dist/scan/parse-sql-select.cjs.map +0 -7
  53. package/dist/scan/parse-sql-select.d.ts +0 -38
  54. package/dist/scan/parse-sql-select.d.ts.map +0 -1
  55. package/dist/scan/parse-sql-select.js +0 -208
  56. package/dist/scan/parse-sql-select.js.map +0 -1
  57. package/src/scan/parse-sql-query.ts +0 -53
  58. package/src/scan/parse-sql-select.ts +0 -220
@@ -2,34 +2,15 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  // Copyright (c) vis.gl contributors
4
4
 
5
+ import {parseSQLPredicate as parseMathSQLPredicate} from '@math.gl/core/sql';
6
+ import {validateSQLPredicate} from './sql-predicate-schema';
5
7
  import type {
6
8
  BoundSQLPredicate,
7
- SQLLogicalPredicate,
8
9
  SQLPredicate,
9
- SQLPredicateParameterValues,
10
- SQLPredicateParserOptions,
11
- SQLPredicateProperty,
12
- SQLPredicateValue
10
+ SQLPredicateParserOptions
13
11
  } from './sql-predicate-types';
14
- import {validateSQLPredicate} from './sql-predicate-schema';
15
-
16
- const MAXIMUM_SQL_LENGTH = 65_536;
17
- const MAXIMUM_SQL_TOKENS = 4096;
18
- const MAXIMUM_EXPRESSION_DEPTH = 64;
19
12
 
20
- type SQLPredicateToken = Readonly<{
21
- kind: 'identifier' | 'number' | 'parameter' | 'string' | 'symbol';
22
- value: string;
23
- quoted?: boolean;
24
- }>;
25
-
26
- /**
27
- * Parses a small SQL `WHERE` expression into a portable CQL2-shaped predicate AST.
28
- *
29
- * Supported syntax is limited to comparisons, `IN`, `IS [NOT] NULL`, `AND`, `OR`, `NOT`, named
30
- * parameters, scalar literals, and parentheses. The input is the expression after `WHERE`, not a
31
- * complete `SELECT` statement.
32
- */
13
+ /** Parses predicates for scan backends, which accept the portable column-only vocabulary. */
33
14
  export function parseSQLPredicate(
34
15
  source: string,
35
16
  options?: SQLPredicateParserOptions & {preserveParameters?: false}
@@ -37,351 +18,11 @@ export function parseSQLPredicate(
37
18
  export function parseSQLPredicate(source: string, options: SQLPredicateParserOptions): SQLPredicate;
38
19
  export function parseSQLPredicate(
39
20
  source: string,
40
- options: SQLPredicateParserOptions = {}
21
+ options?: SQLPredicateParserOptions
41
22
  ): SQLPredicate {
42
- const parser = new SQLPredicateParser(
43
- source,
44
- options.parameters ?? {},
45
- options.preserveParameters === true
46
- );
47
- const predicate = parser.parse();
23
+ const predicate = options
24
+ ? parseMathSQLPredicate(source, options)
25
+ : parseMathSQLPredicate(source);
48
26
  validateSQLPredicate(predicate);
49
27
  return predicate;
50
28
  }
51
-
52
- /** Dependency-free recursive-descent parser for one SQL predicate expression. */
53
- class SQLPredicateParser {
54
- /** Token stream parsed by this parser instance. */
55
- private readonly tokens: readonly SQLPredicateToken[];
56
- /** Named scalar parameters available to the expression. */
57
- private readonly parameters: SQLPredicateParameterValues;
58
- /** Whether named parameters remain references in the parsed AST. */
59
- private readonly preserveParameters: boolean;
60
- /** Current index in the token stream. */
61
- private position = 0;
62
-
63
- constructor(
64
- source: string,
65
- parameters: SQLPredicateParameterValues,
66
- preserveParameters: boolean
67
- ) {
68
- this.tokens = tokenizeSQLPredicate(source);
69
- this.parameters = parameters;
70
- this.preserveParameters = preserveParameters;
71
- }
72
-
73
- /** Parses the complete token stream. */
74
- parse(): SQLPredicate {
75
- const predicate = this.parseOr(0);
76
- this.takeSymbol(';');
77
- const token = this.peek();
78
- if (token) {
79
- throw new Error(`SQL predicate contains unexpected token ${JSON.stringify(token.value)}`);
80
- }
81
- return predicate;
82
- }
83
-
84
- /** Parses left-associative disjunction. */
85
- private parseOr(depth: number): SQLPredicate {
86
- let predicate = this.parseAnd(depth + 1);
87
- while (this.takeKeyword('OR')) {
88
- predicate = combineLogicalPredicate('or', predicate, this.parseAnd(depth + 1));
89
- }
90
- return predicate;
91
- }
92
-
93
- /** Parses left-associative conjunction. */
94
- private parseAnd(depth: number): SQLPredicate {
95
- let predicate = this.parseNot(depth + 1);
96
- while (this.takeKeyword('AND')) {
97
- predicate = combineLogicalPredicate('and', predicate, this.parseNot(depth + 1));
98
- }
99
- return predicate;
100
- }
101
-
102
- /** Parses boolean negation and parenthesized predicates. */
103
- private parseNot(depth: number): SQLPredicate {
104
- this.assertDepth(depth);
105
- if (this.takeKeyword('NOT')) {
106
- return {op: 'not', args: [this.parseNot(depth + 1)]};
107
- }
108
- if (this.takeSymbol('(')) {
109
- const predicate = this.parseOr(depth + 1);
110
- this.expectSymbol(')');
111
- return predicate;
112
- }
113
- return this.parseLeaf();
114
- }
115
-
116
- /** Parses one comparison, membership, or null predicate. */
117
- private parseLeaf(): SQLPredicate {
118
- const property = this.parseProperty();
119
- if (this.takeKeyword('IS')) {
120
- const negated = this.takeKeyword('NOT');
121
- this.expectKeyword('NULL');
122
- const predicate: SQLPredicate = {op: 'isNull', args: [property]};
123
- return negated ? {op: 'not', args: [predicate]} : predicate;
124
- }
125
-
126
- const negatedMembership = this.takeKeyword('NOT');
127
- if (negatedMembership || this.peekKeyword('IN')) {
128
- this.expectKeyword('IN');
129
- this.expectSymbol('(');
130
- if (this.peek()?.kind === 'symbol' && this.peek()?.value === ')') {
131
- throw new Error('SQL predicate IN requires at least one scalar value');
132
- }
133
- const values: SQLPredicateValue[] = [this.parseValue()];
134
- while (this.takeSymbol(',')) {
135
- values.push(this.parseValue());
136
- }
137
- this.expectSymbol(')');
138
- const predicate: SQLPredicate = {op: 'in', args: [property, values]};
139
- return negatedMembership ? {op: 'not', args: [predicate]} : predicate;
140
- }
141
-
142
- const token = this.take();
143
- if (
144
- token?.kind !== 'symbol' ||
145
- !['=', '!=', '<>', '<', '<=', '>', '>='].includes(token.value)
146
- ) {
147
- throw new Error('SQL predicate expected a comparison, IN, or IS NULL operator');
148
- }
149
- const operator = token.value === '!=' ? '<>' : token.value;
150
- return {
151
- op: operator as '=' | '<>' | '<' | '<=' | '>' | '>=',
152
- args: [property, this.parseValue()]
153
- };
154
- }
155
-
156
- /** Parses an identifier into a property reference. */
157
- private parseProperty(): SQLPredicateProperty {
158
- const token = this.take();
159
- if (token?.kind !== 'identifier') {
160
- throw new Error('SQL predicate expected a column identifier');
161
- }
162
- return token.quoted ? {property: token.value, quoted: true} : {property: token.value};
163
- }
164
-
165
- /** Parses one scalar literal or named parameter. */
166
- private parseValue(): SQLPredicateValue {
167
- const negative = this.takeSymbol('-');
168
- const token = this.take();
169
- if (!token) {
170
- throw new Error('SQL predicate expected a scalar value');
171
- }
172
- if (negative && token.kind !== 'number') {
173
- throw new Error('SQL predicate only permits unary minus on numeric literals');
174
- }
175
- if (token.kind === 'number') {
176
- return parseNumericLiteral(negative ? `-${token.value}` : token.value);
177
- }
178
- if (negative) {
179
- throw new Error('SQL predicate expected a numeric literal after unary minus');
180
- }
181
- if (token.kind === 'string') {
182
- return token.value;
183
- }
184
- if (token.kind === 'parameter') {
185
- if (this.preserveParameters) {
186
- return {parameter: token.value};
187
- }
188
- if (!Object.hasOwn(this.parameters, token.value)) {
189
- throw new Error(`SQL predicate parameter ":${token.value}" requires a value`);
190
- }
191
- const value = this.parameters[token.value];
192
- validateParameterValue(value, token.value);
193
- return value;
194
- }
195
- if (token.kind === 'identifier' && !token.quoted && /^(TRUE|FALSE)$/i.test(token.value)) {
196
- return /^TRUE$/i.test(token.value);
197
- }
198
- if (token.kind === 'identifier' && !token.quoted && /^NULL$/i.test(token.value)) {
199
- throw new Error('SQL predicate comparisons with NULL must use IS NULL or IS NOT NULL');
200
- }
201
- throw new Error(`SQL predicate does not support scalar token ${JSON.stringify(token.value)}`);
202
- }
203
-
204
- /** Rejects excessively nested inputs before recursion can exhaust the stack. */
205
- private assertDepth(depth: number): void {
206
- if (depth > MAXIMUM_EXPRESSION_DEPTH) {
207
- throw new Error('SQL predicate nesting exceeds its safe limit');
208
- }
209
- }
210
-
211
- /** Consumes one required keyword. */
212
- private expectKeyword(keyword: string): void {
213
- if (!this.takeKeyword(keyword)) {
214
- throw new Error(`SQL predicate expected ${keyword}`);
215
- }
216
- }
217
-
218
- /** Returns whether the next token is a keyword without consuming it. */
219
- private peekKeyword(keyword: string): boolean {
220
- const token = this.peek();
221
- return token?.kind === 'identifier' && !token.quoted && token.value.toUpperCase() === keyword;
222
- }
223
-
224
- /** Consumes one optional keyword. */
225
- private takeKeyword(keyword: string): boolean {
226
- if (!this.peekKeyword(keyword)) {
227
- return false;
228
- }
229
- this.position++;
230
- return true;
231
- }
232
-
233
- /** Consumes one required symbol. */
234
- private expectSymbol(symbol: string): void {
235
- if (!this.takeSymbol(symbol)) {
236
- throw new Error(`SQL predicate expected ${JSON.stringify(symbol)}`);
237
- }
238
- }
239
-
240
- /** Consumes one optional symbol. */
241
- private takeSymbol(symbol: string): boolean {
242
- const token = this.peek();
243
- if (token?.kind !== 'symbol' || token.value !== symbol) {
244
- return false;
245
- }
246
- this.position++;
247
- return true;
248
- }
249
-
250
- /** Consumes and returns the next token. */
251
- private take(): SQLPredicateToken | undefined {
252
- const token = this.tokens[this.position];
253
- if (token) {
254
- this.position++;
255
- }
256
- return token;
257
- }
258
-
259
- /** Returns the next token without consuming it. */
260
- private peek(): SQLPredicateToken | undefined {
261
- return this.tokens[this.position];
262
- }
263
- }
264
-
265
- /** Flattens adjacent equal logical operators into one CQL2-shaped node. */
266
- function combineLogicalPredicate(
267
- operator: 'and' | 'or',
268
- left: SQLPredicate,
269
- right: SQLPredicate
270
- ): SQLLogicalPredicate {
271
- return left.op === operator
272
- ? {op: operator, args: [...(left as SQLLogicalPredicate).args, right]}
273
- : {op: operator, args: [left, right]};
274
- }
275
-
276
- /** Converts a bounded SQL numeric token to a number or exact bigint. */
277
- function parseNumericLiteral(source: string): number | bigint {
278
- if (/^-?\d+$/.test(source)) {
279
- const bigint = BigInt(source);
280
- if (bigint > BigInt(Number.MAX_SAFE_INTEGER) || bigint < BigInt(Number.MIN_SAFE_INTEGER)) {
281
- return bigint;
282
- }
283
- }
284
- const number = Number(source);
285
- if (!Number.isFinite(number)) {
286
- throw new Error('SQL predicate numeric literals must be finite');
287
- }
288
- return number;
289
- }
290
-
291
- /** Validates one named parameter at its parser boundary. */
292
- function validateParameterValue(value: unknown, name: string): asserts value is SQLPredicateValue {
293
- const probe = {op: '=', args: [{property: '_'}, value]} as unknown;
294
- try {
295
- validateSQLPredicate(probe);
296
- } catch {
297
- throw new Error(`SQL predicate parameter ":${name}" has an unsupported value`);
298
- }
299
- }
300
-
301
- /** Tokenizes a safely bounded SQL predicate expression. */
302
- function tokenizeSQLPredicate(source: string): SQLPredicateToken[] {
303
- if (
304
- typeof source !== 'string' ||
305
- source.trim().length === 0 ||
306
- source.length > MAXIMUM_SQL_LENGTH
307
- ) {
308
- throw new Error('SQL predicate requires a non-empty, safely bounded expression');
309
- }
310
-
311
- const tokens: SQLPredicateToken[] = [];
312
- let position = 0;
313
- while (position < source.length) {
314
- const character = source[position];
315
- if (/\s/.test(character)) {
316
- position++;
317
- continue;
318
- }
319
- if (character === "'") {
320
- const result = readQuotedToken(source, position, "'", "'");
321
- tokens.push({kind: 'string', value: result.value});
322
- position = result.position;
323
- } else if (character === '"') {
324
- const result = readQuotedToken(source, position, '"', '"');
325
- tokens.push({kind: 'identifier', value: result.value, quoted: true});
326
- position = result.position;
327
- } else if (character === ':') {
328
- const match = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(position + 1));
329
- if (!match) {
330
- throw new Error(`SQL predicate contains an invalid parameter at character ${position}`);
331
- }
332
- tokens.push({kind: 'parameter', value: match[0]});
333
- position += match[0].length + 1;
334
- } else {
335
- const numberMatch = /^(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/.exec(source.slice(position));
336
- const identifierMatch = /^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*/.exec(
337
- source.slice(position)
338
- );
339
- if (numberMatch) {
340
- tokens.push({kind: 'number', value: numberMatch[0]});
341
- position += numberMatch[0].length;
342
- } else if (identifierMatch) {
343
- tokens.push({kind: 'identifier', value: identifierMatch[0]});
344
- position += identifierMatch[0].length;
345
- } else {
346
- const twoCharacters = source.slice(position, position + 2);
347
- if (['<=', '>=', '<>', '!='].includes(twoCharacters)) {
348
- tokens.push({kind: 'symbol', value: twoCharacters});
349
- position += 2;
350
- } else if ('(),;-=<>'.includes(character)) {
351
- tokens.push({kind: 'symbol', value: character});
352
- position++;
353
- } else {
354
- throw new Error(`SQL predicate contains an unsupported token at character ${position}`);
355
- }
356
- }
357
- }
358
- if (tokens.length > MAXIMUM_SQL_TOKENS) {
359
- throw new Error('SQL predicate exceeds its safe token limit');
360
- }
361
- }
362
- return tokens;
363
- }
364
-
365
- /** Reads one SQL string or quoted identifier with doubled-quote escaping. */
366
- function readQuotedToken(
367
- source: string,
368
- start: number,
369
- quote: string,
370
- escapedQuote: string
371
- ): {value: string; position: number} {
372
- let value = '';
373
- let position = start + 1;
374
- while (position < source.length) {
375
- if (source[position] !== quote) {
376
- value += source[position++];
377
- continue;
378
- }
379
- if (source[position + 1] === escapedQuote) {
380
- value += quote;
381
- position += 2;
382
- continue;
383
- }
384
- return {value, position: position + 1};
385
- }
386
- throw new Error(`SQL predicate contains an unterminated quoted value at character ${start}`);
387
- }
package/src/scan/query.ts CHANGED
@@ -3,9 +3,11 @@
3
3
  // Copyright (c) vis.gl contributors
4
4
 
5
5
  import * as arrow from 'apache-arrow';
6
+ import type {SQLQuery} from '@math.gl/core/sql';
6
7
  import type {ArrowTable, ArrowTableBatch, TableBatch, Schema} from '@loaders.gl/core/schema';
7
8
  import {
8
9
  normalizeTableQuery,
10
+ getColumnarPredicateColumns,
9
11
  executeTableScanBatches,
10
12
  planTableQuery,
11
13
  emitQueryComplete,
@@ -26,13 +28,14 @@ import {
26
28
  convertTableToArrow
27
29
  } from '@loaders.gl/core/schema-utils';
28
30
  import {projectArrowTable, filterArrowTable} from './arrow-execution';
31
+ import {filterArrowRows} from './arrow-execution/filter-arrow-table';
29
32
  import {createCatalogQuerySource} from './catalog-query-source';
30
33
  import type {SQLCatalogQuery} from './sql-catalog';
31
34
  import {resolveQuerySource} from './resolve-query-source';
32
35
  import type {DataSource} from '@loaders.gl/core/loader-utils';
33
36
 
34
37
  /** Logical table or metadata request. */
35
- export type Query = TableQuery | SQLCatalogQuery;
38
+ export type Query = TableQuery | SQLQuery;
36
39
 
37
40
  /** Injected SQL parser; core validates and executes the returned logical query. */
38
41
  export type SQLQueryParser = (sql: string) => Query | Promise<Query>;
@@ -113,7 +116,9 @@ export async function* queryInBatches(
113
116
  } else parsedQuery = tableQuery;
114
117
  if (!parsedQuery || typeof parsedQuery !== 'object' || Array.isArray(parsedQuery))
115
118
  throw new Error('Table query must be an object.');
116
- let logicalQuery: TableQuery;
119
+ const castPredicate =
120
+ 'command' in parsedQuery ? false : validatePredicateOperands(parsedQuery.where);
121
+ let logicalQuery: TableQuery | Exclude<SQLQuery, SQLCatalogQuery>;
117
122
  let source: unknown;
118
123
  if ('command' in parsedQuery) {
119
124
  logicalQuery = {};
@@ -165,9 +170,41 @@ export async function* queryInBatches(
165
170
  ? (source as ArrowTable).data.schema
166
171
  : convertSchemaToArrow(metadata!.schema);
167
172
  const names = sourceSchema.fields.map(field => field.name);
168
- const normalized = normalizeTableQuery(names, logicalQuery);
169
- const outputColumns = [...new Set(normalized.select.map(selection => selection.column))];
170
- const plan = planTableQuery(names, {columns: outputColumns, predicate: normalized.where});
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
+ });
171
208
  const requiredColumns = plan[0].kind === 'scan' ? plan[0].columns : names;
172
209
  const capabilities = metadata?.capabilities.table;
173
210
  // read() must perform exact filtering when it advertises pushdown+residual, not only pruning.
@@ -184,15 +221,29 @@ export async function* queryInBatches(
184
221
  : {}),
185
222
  ...(delegatePredicate ? {predicate: normalized.where} : {}),
186
223
  ...(!residual &&
224
+ !expressionFilter &&
225
+ !castPredicate &&
187
226
  capabilities &&
188
227
  ['pushdown', 'pushdown+residual'].includes(capabilities.limit)
189
228
  ? {limit: normalized.limit}
190
229
  : {})
191
230
  };
192
- const readSchema = convertArrowToSchema(
193
- readOptions.columns ? sourceSchema.select([...readOptions.columns]) : sourceSchema
194
- );
195
- const empty = projectArrowTable(new arrow.Table(sourceSchema), normalized.select);
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));
196
247
  const comparisonSchema = convertSchemaToArrow(convertArrowToSchema(empty.schema));
197
248
  let emitted = false;
198
249
  /** Adapts physical batches without pulling ahead of the query consumer. */
@@ -203,7 +254,19 @@ export async function* queryInBatches(
203
254
  : (source as TableScanSource).read(readOptions);
204
255
  for await (const value of batches) {
205
256
  options.signal?.throwIfAborted();
206
- const batch = normalizeBatch(value, readSchema);
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
+ }
207
270
  batchesRead++;
208
271
  rowsRead += batch.length;
209
272
  yield batch;
@@ -219,16 +282,28 @@ export async function* queryInBatches(
219
282
  {
220
283
  filter: (batch, predicate, signal) => {
221
284
  const input = batch as ArrowTableBatch;
222
- const data = predicate ? filterArrowTable(input.data, predicate, {signal}) : input.data;
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;
223
297
  return {...input, ...wrapBatch(data)};
224
298
  },
225
299
  project: batch => {
226
300
  const input = batch as ArrowTableBatch;
227
- return {...input, ...wrapBatch(projectArrowTable(input.data, normalized.select))};
301
+ return computedProjection ? input : {...input, ...wrapBatch(project(input.data))};
228
302
  }
229
303
  }
230
304
  )) {
231
- const batch = value as ArrowTableBatch;
305
+ const input = value as ArrowTableBatch;
306
+ const batch = computedProjection ? {...input, ...wrapBatch(project(input.data))} : input;
232
307
  if (!arrow.util.compareSchemas(comparisonSchema, convertSchemaToArrow(batch.schema!)))
233
308
  throw new Error('Query output schema does not match source metadata.');
234
309
  emitted = true;
@@ -331,9 +406,75 @@ async function openQuerySource(options: QueryOptions): Promise<unknown> {
331
406
  return implementation.createDataSource(url, authenticatedOptions as DataSourceOptions);
332
407
  }
333
408
 
334
- export {parseSQLQuery} from './parse-sql-query';
335
- export {parseSQLSelect} from './parse-sql-select';
336
- export type {SQLSelectParserOptions} from './parse-sql-select';
409
+ export {parseSQLQuery, parseSQLSelect, type SQLSelectParserOptions} from '@math.gl/core/sql';
337
410
 
338
411
  export {createSQLCatalog} from './sql-catalog';
339
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
+ }