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

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 (41) hide show
  1. package/LICENSE +14 -3
  2. package/README.md +49 -0
  3. package/dist/duckdb-sql-source.js +1 -1
  4. package/dist/index.cjs +1699 -19
  5. package/dist/index.cjs.map +3 -4
  6. package/dist/index.d.ts +3 -0
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +2 -0
  9. package/dist/index.js.map +1 -1
  10. package/dist/parse-sql-predicate.d.ts +10 -0
  11. package/dist/parse-sql-predicate.d.ts.map +1 -0
  12. package/dist/parse-sql-predicate.js +316 -0
  13. package/dist/parse-sql-predicate.js.map +1 -0
  14. package/dist/snowflake-sql-source.js +1 -1
  15. package/dist/sql-predicate-schema.d.ts +141 -0
  16. package/dist/sql-predicate-schema.d.ts.map +1 -0
  17. package/dist/sql-predicate-schema.js +205 -0
  18. package/dist/sql-predicate-schema.js.map +1 -0
  19. package/dist/sql-predicate-types.d.ts +55 -0
  20. package/dist/sql-predicate-types.d.ts.map +1 -0
  21. package/dist/sql-predicate-types.js +5 -0
  22. package/dist/sql-predicate-types.js.map +1 -0
  23. package/dist/sql-predicate-zod.cjs +53 -0
  24. package/dist/sql-predicate-zod.cjs.map +6 -0
  25. package/dist/sql-predicate-zod.d.ts +11 -0
  26. package/dist/sql-predicate-zod.d.ts.map +1 -0
  27. package/dist/sql-predicate-zod.js +42 -0
  28. package/dist/sql-predicate-zod.js.map +1 -0
  29. package/dist/sql-predicate.cjs +500 -0
  30. package/dist/sql-predicate.cjs.map +6 -0
  31. package/dist/sql-predicate.d.ts +4 -0
  32. package/dist/sql-predicate.d.ts.map +1 -0
  33. package/dist/sql-predicate.js +6 -0
  34. package/dist/sql-predicate.js.map +1 -0
  35. package/package.json +35 -8
  36. package/src/index.ts +18 -0
  37. package/src/parse-sql-predicate.ts +365 -0
  38. package/src/sql-predicate-schema.ts +226 -0
  39. package/src/sql-predicate-types.ts +71 -0
  40. package/src/sql-predicate-zod.ts +49 -0
  41. package/src/sql-predicate.ts +22 -0
@@ -0,0 +1,365 @@
1
+ // loaders.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import type {
6
+ SQLLogicalPredicate,
7
+ SQLPredicate,
8
+ SQLPredicateParserOptions,
9
+ SQLPredicateProperty,
10
+ SQLPredicateValue
11
+ } from './sql-predicate-types';
12
+ import {validateSQLPredicate} from './sql-predicate-schema';
13
+
14
+ const MAXIMUM_SQL_LENGTH = 65_536;
15
+ const MAXIMUM_SQL_TOKENS = 4096;
16
+ const MAXIMUM_EXPRESSION_DEPTH = 64;
17
+
18
+ type SQLPredicateToken = Readonly<{
19
+ kind: 'identifier' | 'number' | 'parameter' | 'string' | 'symbol';
20
+ value: string;
21
+ }>;
22
+
23
+ /**
24
+ * Parses a small SQL `WHERE` expression into a portable CQL2-shaped predicate AST.
25
+ *
26
+ * Supported syntax is limited to comparisons, `IN`, `IS [NOT] NULL`, `AND`, `OR`, `NOT`, named
27
+ * parameters, scalar literals, and parentheses. The input is the expression after `WHERE`, not a
28
+ * complete `SELECT` statement.
29
+ */
30
+ export function parseSQLPredicate(
31
+ source: string,
32
+ options: SQLPredicateParserOptions = {}
33
+ ): SQLPredicate {
34
+ const parser = new SQLPredicateParser(source, options.parameters ?? {});
35
+ const predicate = parser.parse();
36
+ validateSQLPredicate(predicate);
37
+ return predicate;
38
+ }
39
+
40
+ /** Dependency-free recursive-descent parser for one SQL predicate expression. */
41
+ class SQLPredicateParser {
42
+ /** Token stream parsed by this parser instance. */
43
+ private readonly tokens: readonly SQLPredicateToken[];
44
+ /** Named scalar parameters available to the expression. */
45
+ private readonly parameters: Readonly<Record<string, SQLPredicateValue>>;
46
+ /** Current index in the token stream. */
47
+ private position = 0;
48
+
49
+ constructor(source: string, parameters: Readonly<Record<string, SQLPredicateValue>>) {
50
+ this.tokens = tokenizeSQLPredicate(source);
51
+ this.parameters = parameters;
52
+ }
53
+
54
+ /** Parses the complete token stream. */
55
+ parse(): SQLPredicate {
56
+ const predicate = this.parseOr(0);
57
+ this.takeSymbol(';');
58
+ const token = this.peek();
59
+ if (token) {
60
+ throw new Error(`SQL predicate contains unexpected token ${JSON.stringify(token.value)}`);
61
+ }
62
+ return predicate;
63
+ }
64
+
65
+ /** Parses left-associative disjunction. */
66
+ private parseOr(depth: number): SQLPredicate {
67
+ let predicate = this.parseAnd(depth + 1);
68
+ while (this.takeKeyword('OR')) {
69
+ predicate = combineLogicalPredicate('or', predicate, this.parseAnd(depth + 1));
70
+ }
71
+ return predicate;
72
+ }
73
+
74
+ /** Parses left-associative conjunction. */
75
+ private parseAnd(depth: number): SQLPredicate {
76
+ let predicate = this.parseNot(depth + 1);
77
+ while (this.takeKeyword('AND')) {
78
+ predicate = combineLogicalPredicate('and', predicate, this.parseNot(depth + 1));
79
+ }
80
+ return predicate;
81
+ }
82
+
83
+ /** Parses boolean negation and parenthesized predicates. */
84
+ private parseNot(depth: number): SQLPredicate {
85
+ this.assertDepth(depth);
86
+ if (this.takeKeyword('NOT')) {
87
+ return {op: 'not', args: [this.parseNot(depth + 1)]};
88
+ }
89
+ if (this.takeSymbol('(')) {
90
+ const predicate = this.parseOr(depth + 1);
91
+ this.expectSymbol(')');
92
+ return predicate;
93
+ }
94
+ return this.parseLeaf();
95
+ }
96
+
97
+ /** Parses one comparison, membership, or null predicate. */
98
+ private parseLeaf(): SQLPredicate {
99
+ const property = this.parseProperty();
100
+ if (this.takeKeyword('IS')) {
101
+ const negated = this.takeKeyword('NOT');
102
+ this.expectKeyword('NULL');
103
+ const predicate: SQLPredicate = {op: 'isNull', args: [property]};
104
+ return negated ? {op: 'not', args: [predicate]} : predicate;
105
+ }
106
+
107
+ const negatedMembership = this.takeKeyword('NOT');
108
+ if (negatedMembership || this.peekKeyword('IN')) {
109
+ this.expectKeyword('IN');
110
+ this.expectSymbol('(');
111
+ if (this.peek()?.kind === 'symbol' && this.peek()?.value === ')') {
112
+ throw new Error('SQL predicate IN requires at least one scalar value');
113
+ }
114
+ const values: SQLPredicateValue[] = [this.parseValue()];
115
+ while (this.takeSymbol(',')) {
116
+ values.push(this.parseValue());
117
+ }
118
+ this.expectSymbol(')');
119
+ const predicate: SQLPredicate = {op: 'in', args: [property, values]};
120
+ return negatedMembership ? {op: 'not', args: [predicate]} : predicate;
121
+ }
122
+
123
+ const token = this.take();
124
+ if (
125
+ token?.kind !== 'symbol' ||
126
+ !['=', '!=', '<>', '<', '<=', '>', '>='].includes(token.value)
127
+ ) {
128
+ throw new Error('SQL predicate expected a comparison, IN, or IS NULL operator');
129
+ }
130
+ const operator = token.value === '!=' ? '<>' : token.value;
131
+ return {
132
+ op: operator as '=' | '<>' | '<' | '<=' | '>' | '>=',
133
+ args: [property, this.parseValue()]
134
+ };
135
+ }
136
+
137
+ /** Parses an identifier into a property reference. */
138
+ private parseProperty(): SQLPredicateProperty {
139
+ const token = this.take();
140
+ if (token?.kind !== 'identifier') {
141
+ throw new Error('SQL predicate expected a column identifier');
142
+ }
143
+ return {property: token.value};
144
+ }
145
+
146
+ /** Parses one scalar literal or named parameter. */
147
+ private parseValue(): SQLPredicateValue {
148
+ const negative = this.takeSymbol('-');
149
+ const token = this.take();
150
+ if (!token) {
151
+ throw new Error('SQL predicate expected a scalar value');
152
+ }
153
+ if (negative && token.kind !== 'number') {
154
+ throw new Error('SQL predicate only permits unary minus on numeric literals');
155
+ }
156
+ if (token.kind === 'number') {
157
+ return parseNumericLiteral(negative ? `-${token.value}` : token.value);
158
+ }
159
+ if (negative) {
160
+ throw new Error('SQL predicate expected a numeric literal after unary minus');
161
+ }
162
+ if (token.kind === 'string') {
163
+ return token.value;
164
+ }
165
+ if (token.kind === 'parameter') {
166
+ if (!Object.hasOwn(this.parameters, token.value)) {
167
+ throw new Error(`SQL predicate parameter ":${token.value}" requires a value`);
168
+ }
169
+ const value = this.parameters[token.value];
170
+ validateParameterValue(value, token.value);
171
+ return value;
172
+ }
173
+ if (token.kind === 'identifier' && /^(TRUE|FALSE)$/i.test(token.value)) {
174
+ return /^TRUE$/i.test(token.value);
175
+ }
176
+ if (token.kind === 'identifier' && /^NULL$/i.test(token.value)) {
177
+ throw new Error('SQL predicate comparisons with NULL must use IS NULL or IS NOT NULL');
178
+ }
179
+ throw new Error(`SQL predicate does not support scalar token ${JSON.stringify(token.value)}`);
180
+ }
181
+
182
+ /** Rejects excessively nested inputs before recursion can exhaust the stack. */
183
+ private assertDepth(depth: number): void {
184
+ if (depth > MAXIMUM_EXPRESSION_DEPTH) {
185
+ throw new Error('SQL predicate nesting exceeds its safe limit');
186
+ }
187
+ }
188
+
189
+ /** Consumes one required keyword. */
190
+ private expectKeyword(keyword: string): void {
191
+ if (!this.takeKeyword(keyword)) {
192
+ throw new Error(`SQL predicate expected ${keyword}`);
193
+ }
194
+ }
195
+
196
+ /** Returns whether the next token is a keyword without consuming it. */
197
+ private peekKeyword(keyword: string): boolean {
198
+ const token = this.peek();
199
+ return token?.kind === 'identifier' && token.value.toUpperCase() === keyword;
200
+ }
201
+
202
+ /** Consumes one optional keyword. */
203
+ private takeKeyword(keyword: string): boolean {
204
+ if (!this.peekKeyword(keyword)) {
205
+ return false;
206
+ }
207
+ this.position++;
208
+ return true;
209
+ }
210
+
211
+ /** Consumes one required symbol. */
212
+ private expectSymbol(symbol: string): void {
213
+ if (!this.takeSymbol(symbol)) {
214
+ throw new Error(`SQL predicate expected ${JSON.stringify(symbol)}`);
215
+ }
216
+ }
217
+
218
+ /** Consumes one optional symbol. */
219
+ private takeSymbol(symbol: string): boolean {
220
+ const token = this.peek();
221
+ if (token?.kind !== 'symbol' || token.value !== symbol) {
222
+ return false;
223
+ }
224
+ this.position++;
225
+ return true;
226
+ }
227
+
228
+ /** Consumes and returns the next token. */
229
+ private take(): SQLPredicateToken | undefined {
230
+ const token = this.tokens[this.position];
231
+ if (token) {
232
+ this.position++;
233
+ }
234
+ return token;
235
+ }
236
+
237
+ /** Returns the next token without consuming it. */
238
+ private peek(): SQLPredicateToken | undefined {
239
+ return this.tokens[this.position];
240
+ }
241
+ }
242
+
243
+ /** Flattens adjacent equal logical operators into one CQL2-shaped node. */
244
+ function combineLogicalPredicate(
245
+ operator: 'and' | 'or',
246
+ left: SQLPredicate,
247
+ right: SQLPredicate
248
+ ): SQLLogicalPredicate {
249
+ return left.op === operator
250
+ ? {op: operator, args: [...(left as SQLLogicalPredicate).args, right]}
251
+ : {op: operator, args: [left, right]};
252
+ }
253
+
254
+ /** Converts a bounded SQL numeric token to a number or exact bigint. */
255
+ function parseNumericLiteral(source: string): number | bigint {
256
+ if (/^-?\d+$/.test(source)) {
257
+ const bigint = BigInt(source);
258
+ if (bigint > BigInt(Number.MAX_SAFE_INTEGER) || bigint < BigInt(Number.MIN_SAFE_INTEGER)) {
259
+ return bigint;
260
+ }
261
+ }
262
+ const number = Number(source);
263
+ if (!Number.isFinite(number)) {
264
+ throw new Error('SQL predicate numeric literals must be finite');
265
+ }
266
+ return number;
267
+ }
268
+
269
+ /** Validates one named parameter at its parser boundary. */
270
+ function validateParameterValue(value: unknown, name: string): asserts value is SQLPredicateValue {
271
+ const probe = {op: '=', args: [{property: '_'}, value]} as unknown;
272
+ try {
273
+ validateSQLPredicate(probe);
274
+ } catch {
275
+ throw new Error(`SQL predicate parameter ":${name}" has an unsupported value`);
276
+ }
277
+ }
278
+
279
+ /** Tokenizes a safely bounded SQL predicate expression. */
280
+ function tokenizeSQLPredicate(source: string): SQLPredicateToken[] {
281
+ if (
282
+ typeof source !== 'string' ||
283
+ source.trim().length === 0 ||
284
+ source.length > MAXIMUM_SQL_LENGTH
285
+ ) {
286
+ throw new Error('SQL predicate requires a non-empty, safely bounded expression');
287
+ }
288
+
289
+ const tokens: SQLPredicateToken[] = [];
290
+ let position = 0;
291
+ while (position < source.length) {
292
+ const character = source[position];
293
+ if (/\s/.test(character)) {
294
+ position++;
295
+ continue;
296
+ }
297
+ if (character === "'") {
298
+ const result = readQuotedToken(source, position, "'", "'");
299
+ tokens.push({kind: 'string', value: result.value});
300
+ position = result.position;
301
+ } else if (character === '"') {
302
+ const result = readQuotedToken(source, position, '"', '"');
303
+ tokens.push({kind: 'identifier', value: result.value});
304
+ position = result.position;
305
+ } else if (character === ':') {
306
+ const match = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(position + 1));
307
+ if (!match) {
308
+ throw new Error(`SQL predicate contains an invalid parameter at character ${position}`);
309
+ }
310
+ tokens.push({kind: 'parameter', value: match[0]});
311
+ position += match[0].length + 1;
312
+ } else {
313
+ const numberMatch = /^(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/.exec(source.slice(position));
314
+ const identifierMatch = /^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*/.exec(
315
+ source.slice(position)
316
+ );
317
+ if (numberMatch) {
318
+ tokens.push({kind: 'number', value: numberMatch[0]});
319
+ position += numberMatch[0].length;
320
+ } else if (identifierMatch) {
321
+ tokens.push({kind: 'identifier', value: identifierMatch[0]});
322
+ position += identifierMatch[0].length;
323
+ } else {
324
+ const twoCharacters = source.slice(position, position + 2);
325
+ if (['<=', '>=', '<>', '!='].includes(twoCharacters)) {
326
+ tokens.push({kind: 'symbol', value: twoCharacters});
327
+ position += 2;
328
+ } else if ('(),;-=<>'.includes(character)) {
329
+ tokens.push({kind: 'symbol', value: character});
330
+ position++;
331
+ } else {
332
+ throw new Error(`SQL predicate contains an unsupported token at character ${position}`);
333
+ }
334
+ }
335
+ }
336
+ if (tokens.length > MAXIMUM_SQL_TOKENS) {
337
+ throw new Error('SQL predicate exceeds its safe token limit');
338
+ }
339
+ }
340
+ return tokens;
341
+ }
342
+
343
+ /** Reads one SQL string or quoted identifier with doubled-quote escaping. */
344
+ function readQuotedToken(
345
+ source: string,
346
+ start: number,
347
+ quote: string,
348
+ escapedQuote: string
349
+ ): {value: string; position: number} {
350
+ let value = '';
351
+ let position = start + 1;
352
+ while (position < source.length) {
353
+ if (source[position] !== quote) {
354
+ value += source[position++];
355
+ continue;
356
+ }
357
+ if (source[position + 1] === escapedQuote) {
358
+ value += quote;
359
+ position += 2;
360
+ continue;
361
+ }
362
+ return {value, position: position + 1};
363
+ }
364
+ throw new Error(`SQL predicate contains an unterminated quoted value at character ${start}`);
365
+ }
@@ -0,0 +1,226 @@
1
+ // loaders.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import type {SQLPredicate, SQLPredicateValue} from './sql-predicate-types';
6
+
7
+ const MAXIMUM_PREDICATE_DEPTH = 64;
8
+ const MAXIMUM_PREDICATE_NODES = 4096;
9
+
10
+ /**
11
+ * JSON Schema for the JSON-serializable portion of the loaders.gl SQL predicate AST.
12
+ *
13
+ * In-process predicates additionally accept `bigint`, `Date`, and `Uint8Array` values, which JSON
14
+ * Schema cannot represent directly.
15
+ */
16
+ export const SQL_PREDICATE_JSON_SCHEMA = {
17
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
18
+ $id: 'https://loaders.gl/schemas/sql-predicate.schema.json',
19
+ title: 'loaders.gl SQL predicate',
20
+ oneOf: [
21
+ {$ref: '#/$defs/comparison'},
22
+ {$ref: '#/$defs/in'},
23
+ {$ref: '#/$defs/isNull'},
24
+ {$ref: '#/$defs/logical'},
25
+ {$ref: '#/$defs/not'}
26
+ ],
27
+ $defs: {
28
+ property: {
29
+ type: 'object',
30
+ required: ['property'],
31
+ properties: {property: {type: 'string', minLength: 1}},
32
+ additionalProperties: false
33
+ },
34
+ value: {type: ['boolean', 'number', 'string']},
35
+ comparison: {
36
+ type: 'object',
37
+ required: ['op', 'args'],
38
+ properties: {
39
+ op: {enum: ['=', '<>', '<', '<=', '>', '>=']},
40
+ args: {
41
+ type: 'array',
42
+ prefixItems: [{$ref: '#/$defs/property'}, {$ref: '#/$defs/value'}],
43
+ minItems: 2,
44
+ maxItems: 2
45
+ }
46
+ },
47
+ additionalProperties: false
48
+ },
49
+ in: {
50
+ type: 'object',
51
+ required: ['op', 'args'],
52
+ properties: {
53
+ op: {const: 'in'},
54
+ args: {
55
+ type: 'array',
56
+ prefixItems: [
57
+ {$ref: '#/$defs/property'},
58
+ {type: 'array', items: {$ref: '#/$defs/value'}, minItems: 1}
59
+ ],
60
+ minItems: 2,
61
+ maxItems: 2
62
+ }
63
+ },
64
+ additionalProperties: false
65
+ },
66
+ isNull: {
67
+ type: 'object',
68
+ required: ['op', 'args'],
69
+ properties: {
70
+ op: {const: 'isNull'},
71
+ args: {
72
+ type: 'array',
73
+ prefixItems: [{$ref: '#/$defs/property'}],
74
+ minItems: 1,
75
+ maxItems: 1
76
+ }
77
+ },
78
+ additionalProperties: false
79
+ },
80
+ logical: {
81
+ type: 'object',
82
+ required: ['op', 'args'],
83
+ properties: {
84
+ op: {enum: ['and', 'or']},
85
+ args: {type: 'array', items: {$ref: '#'}, minItems: 2}
86
+ },
87
+ additionalProperties: false
88
+ },
89
+ not: {
90
+ type: 'object',
91
+ required: ['op', 'args'],
92
+ properties: {
93
+ op: {const: 'not'},
94
+ args: {type: 'array', prefixItems: [{$ref: '#'}], minItems: 1, maxItems: 1}
95
+ },
96
+ additionalProperties: false
97
+ }
98
+ }
99
+ } as const;
100
+
101
+ /** Returns whether an unknown value is a valid portable SQL predicate. */
102
+ export function isSQLPredicate(value: unknown): value is SQLPredicate {
103
+ try {
104
+ validateSQLPredicate(value);
105
+ return true;
106
+ } catch {
107
+ return false;
108
+ }
109
+ }
110
+
111
+ /** Validates an unknown portable SQL predicate or throws a path-specific error. */
112
+ export function validateSQLPredicate(value: unknown): asserts value is SQLPredicate {
113
+ const state = {nodes: 0};
114
+ validatePredicateNode(value, '$', 0, state);
115
+ }
116
+
117
+ /** Validates one recursive predicate node. */
118
+ function validatePredicateNode(
119
+ value: unknown,
120
+ path: string,
121
+ depth: number,
122
+ state: {nodes: number}
123
+ ): asserts value is SQLPredicate {
124
+ if (depth > MAXIMUM_PREDICATE_DEPTH) {
125
+ throw new Error(`SQL predicate ${path} exceeds the maximum nesting depth`);
126
+ }
127
+ state.nodes++;
128
+ if (state.nodes > MAXIMUM_PREDICATE_NODES) {
129
+ throw new Error('SQL predicate exceeds the maximum node count');
130
+ }
131
+ if (!isRecord(value) || !hasExactKeys(value, ['op', 'args'])) {
132
+ throw new Error(`SQL predicate ${path} must contain only op and args`);
133
+ }
134
+ if (typeof value.op !== 'string' || !Array.isArray(value.args)) {
135
+ throw new Error(`SQL predicate ${path} requires string op and array args`);
136
+ }
137
+
138
+ switch (value.op) {
139
+ case 'and':
140
+ case 'or':
141
+ if (value.args.length < 2) {
142
+ throw new Error(`SQL predicate ${path}.${value.op} requires at least two arguments`);
143
+ }
144
+ for (let index = 0; index < value.args.length; index++) {
145
+ validatePredicateNode(value.args[index], `${path}.args[${index}]`, depth + 1, state);
146
+ }
147
+ return;
148
+ case 'not':
149
+ if (value.args.length !== 1) {
150
+ throw new Error(`SQL predicate ${path}.not requires exactly one argument`);
151
+ }
152
+ validatePredicateNode(value.args[0], `${path}.args[0]`, depth + 1, state);
153
+ return;
154
+ case 'isNull':
155
+ if (value.args.length !== 1) {
156
+ throw new Error(`SQL predicate ${path}.isNull requires exactly one argument`);
157
+ }
158
+ validatePredicateProperty(value.args[0], `${path}.args[0]`);
159
+ return;
160
+ case 'in':
161
+ if (value.args.length !== 2 || !Array.isArray(value.args[1]) || value.args[1].length === 0) {
162
+ throw new Error(`SQL predicate ${path}.in requires a property and non-empty value list`);
163
+ }
164
+ validatePredicateProperty(value.args[0], `${path}.args[0]`);
165
+ value.args[1].forEach((item, index) =>
166
+ validatePredicateValue(item, `${path}.args[1][${index}]`)
167
+ );
168
+ return;
169
+ case '=':
170
+ case '<>':
171
+ case '<':
172
+ case '<=':
173
+ case '>':
174
+ case '>=':
175
+ if (value.args.length !== 2) {
176
+ throw new Error(`SQL predicate ${path}.${value.op} requires exactly two arguments`);
177
+ }
178
+ validatePredicateProperty(value.args[0], `${path}.args[0]`);
179
+ validatePredicateValue(value.args[1], `${path}.args[1]`);
180
+ return;
181
+ default:
182
+ throw new Error(`SQL predicate ${path} has unsupported operator ${JSON.stringify(value.op)}`);
183
+ }
184
+ }
185
+
186
+ /** Validates one property reference. */
187
+ function validatePredicateProperty(value: unknown, path: string): void {
188
+ if (
189
+ !isRecord(value) ||
190
+ !hasExactKeys(value, ['property']) ||
191
+ typeof value.property !== 'string' ||
192
+ value.property.length === 0
193
+ ) {
194
+ throw new Error(`SQL predicate ${path} requires a non-empty property reference`);
195
+ }
196
+ }
197
+
198
+ /** Validates one structured-cloneable predicate scalar. */
199
+ function validatePredicateValue(value: unknown, path: string): asserts value is SQLPredicateValue {
200
+ if (
201
+ typeof value === 'boolean' ||
202
+ typeof value === 'bigint' ||
203
+ typeof value === 'string' ||
204
+ value instanceof Uint8Array
205
+ ) {
206
+ return;
207
+ }
208
+ if (typeof value === 'number' && Number.isFinite(value)) {
209
+ return;
210
+ }
211
+ if (value instanceof Date && Number.isFinite(value.getTime())) {
212
+ return;
213
+ }
214
+ throw new Error(`SQL predicate ${path} contains an unsupported scalar value`);
215
+ }
216
+
217
+ /** Returns whether an unknown value is a non-null object. */
218
+ function isRecord(value: unknown): value is Record<string, unknown> {
219
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
220
+ }
221
+
222
+ /** Returns whether an object contains exactly the expected enumerable keys. */
223
+ function hasExactKeys(value: Record<string, unknown>, expectedKeys: readonly string[]): boolean {
224
+ const keys = Object.keys(value);
225
+ return keys.length === expectedKeys.length && expectedKeys.every(key => keys.includes(key));
226
+ }
@@ -0,0 +1,71 @@
1
+ // loaders.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ /** Scalar values supported by portable SQL predicate expressions. */
6
+ export type SQLPredicateValue = boolean | number | bigint | string | Date | Uint8Array;
7
+
8
+ /** Reference to one column in a portable SQL predicate expression. */
9
+ export type SQLPredicateProperty = Readonly<{
10
+ /** Column or qualified column name. */
11
+ property: string;
12
+ }>;
13
+
14
+ /** Binary comparison between a column and a scalar value. */
15
+ export type SQLComparisonPredicate = Readonly<{
16
+ /** CQL2-shaped comparison operator. */
17
+ op: '=' | '<>' | '<' | '<=' | '>' | '>=';
18
+ /** Column reference followed by the scalar value to compare. */
19
+ args: readonly [SQLPredicateProperty, SQLPredicateValue];
20
+ }>;
21
+
22
+ /** Membership test between a column and scalar values. */
23
+ export type SQLInPredicate = Readonly<{
24
+ /** CQL2-shaped membership operator. */
25
+ op: 'in';
26
+ /** Column reference followed by a non-empty list of candidate values. */
27
+ args: readonly [SQLPredicateProperty, readonly SQLPredicateValue[]];
28
+ }>;
29
+
30
+ /** Null test for one column. */
31
+ export type SQLNullPredicate = Readonly<{
32
+ /** CQL2-shaped null-test operator. */
33
+ op: 'isNull';
34
+ /** Column reference to test. */
35
+ args: readonly [SQLPredicateProperty];
36
+ }>;
37
+
38
+ /** Conjunction or disjunction of two or more predicates. */
39
+ export type SQLLogicalPredicate = Readonly<{
40
+ /** CQL2-shaped logical operator. */
41
+ op: 'and' | 'or';
42
+ /** Two or more child predicates. */
43
+ args: readonly SQLPredicate[];
44
+ }>;
45
+
46
+ /** Negation of one predicate. */
47
+ export type SQLNotPredicate = Readonly<{
48
+ /** CQL2-shaped negation operator. */
49
+ op: 'not';
50
+ /** Single child predicate. */
51
+ args: readonly [SQLPredicate];
52
+ }>;
53
+
54
+ /**
55
+ * Portable predicate AST emitted by the loaders.gl SQL expression parser.
56
+ *
57
+ * The expression shape is directionally aligned with CQL2 JSON, but this deliberately small
58
+ * subset does not claim CQL2 conformance.
59
+ */
60
+ export type SQLPredicate =
61
+ | SQLComparisonPredicate
62
+ | SQLInPredicate
63
+ | SQLNullPredicate
64
+ | SQLLogicalPredicate
65
+ | SQLNotPredicate;
66
+
67
+ /** Options for parsing one SQL predicate expression. */
68
+ export type SQLPredicateParserOptions = Readonly<{
69
+ /** Named values referenced using SQL parameters such as `:minimumFare`. */
70
+ parameters?: Readonly<Record<string, SQLPredicateValue>>;
71
+ }>;