@peridotvault/peridotbase-sdk 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/sql.js ADDED
@@ -0,0 +1,1523 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseSql = parseSql;
4
+ exports.parseSqlStatement = parseSqlStatement;
5
+ exports.bindNameExpr = bindNameExpr;
6
+ exports.equalityTarget = equalityTarget;
7
+ exports.describeStatement = describeStatement;
8
+ const values_1 = require("./values");
9
+ function tokenize(sql) {
10
+ const tokens = [];
11
+ let i = 0;
12
+ while (i < sql.length) {
13
+ const c = sql[i];
14
+ if (/\s/.test(c)) {
15
+ i += 1;
16
+ continue;
17
+ }
18
+ if (c === "-" && sql[i + 1] === "-") {
19
+ while (i < sql.length && sql[i] !== "\n")
20
+ i += 1;
21
+ continue;
22
+ }
23
+ if (c === "'") {
24
+ let value = "";
25
+ i += 1;
26
+ while (i < sql.length) {
27
+ if (sql[i] === "'" && sql[i + 1] === "'") {
28
+ value += "'";
29
+ i += 2;
30
+ continue;
31
+ }
32
+ if (sql[i] === "'") {
33
+ i += 1;
34
+ break;
35
+ }
36
+ value += sql[i];
37
+ i += 1;
38
+ }
39
+ tokens.push({ type: "string", value });
40
+ continue;
41
+ }
42
+ if (c === '"') {
43
+ let value = "";
44
+ i += 1;
45
+ while (i < sql.length && sql[i] !== '"') {
46
+ value += sql[i];
47
+ i += 1;
48
+ }
49
+ i += 1;
50
+ tokens.push({ type: "word", value });
51
+ continue;
52
+ }
53
+ if (/[0-9]/.test(c) || (c === "." && /[0-9]/.test(sql[i + 1]))) {
54
+ let value = "";
55
+ while (i < sql.length && /[0-9.]/.test(sql[i])) {
56
+ value += sql[i];
57
+ i += 1;
58
+ }
59
+ tokens.push({ type: "number", value });
60
+ continue;
61
+ }
62
+ if (/[A-Za-z_]/.test(c)) {
63
+ let value = "";
64
+ while (i < sql.length && /[A-Za-z0-9_]/.test(sql[i])) {
65
+ value += sql[i];
66
+ i += 1;
67
+ }
68
+ tokens.push({ type: "word", value });
69
+ continue;
70
+ }
71
+ if (c === "$" && /[0-9]/.test(sql[i + 1] ?? "")) {
72
+ let value = "";
73
+ i += 1;
74
+ while (i < sql.length && /[0-9]/.test(sql[i])) {
75
+ value += sql[i];
76
+ i += 1;
77
+ }
78
+ tokens.push({ type: "param", value: `$${value}` });
79
+ continue;
80
+ }
81
+ if (c === ":" && /[A-Za-z_]/.test(sql[i + 1] ?? "")) {
82
+ let value = "";
83
+ i += 1;
84
+ while (i < sql.length && /[A-Za-z0-9_]/.test(sql[i])) {
85
+ value += sql[i];
86
+ i += 1;
87
+ }
88
+ tokens.push({ type: "param", value: `:${value}` });
89
+ continue;
90
+ }
91
+ if (c === "?") {
92
+ tokens.push({ type: "param", value: "?" });
93
+ i += 1;
94
+ continue;
95
+ }
96
+ const three = sql.slice(i, i + 3);
97
+ if (three === "-|-") {
98
+ tokens.push({ type: "op", value: three });
99
+ i += 3;
100
+ continue;
101
+ }
102
+ const two = sql.slice(i, i + 2);
103
+ if (["@>", "<@", "&&", "<<", ">>"].includes(two)) {
104
+ tokens.push({ type: "op", value: two });
105
+ i += 2;
106
+ continue;
107
+ }
108
+ if (["<>", "<=", ">=", "!="].includes(two)) {
109
+ tokens.push({ type: "op", value: two === "!=" ? "<>" : two });
110
+ i += 2;
111
+ continue;
112
+ }
113
+ if ("(),;*=<>+-/.".includes(c)) {
114
+ tokens.push({ type: "punct", value: c });
115
+ i += 1;
116
+ continue;
117
+ }
118
+ throw new Error(`SQL parse error: unexpected character '${c}'`);
119
+ }
120
+ return tokens;
121
+ }
122
+ class Parser {
123
+ constructor(tokens, params = []) {
124
+ this.tokens = tokens;
125
+ this.params = params;
126
+ this.pos = 0;
127
+ this.positional = 0;
128
+ }
129
+ paramValue(token) {
130
+ const name = token.value;
131
+ if (name === "?") {
132
+ this.positional += 1;
133
+ if (Array.isArray(this.params)) {
134
+ if (this.positional > this.params.length) {
135
+ throw new Error(`SQL parameter $${this.positional} is missing`);
136
+ }
137
+ return this.params[this.positional - 1];
138
+ }
139
+ const key = String(this.positional);
140
+ if (!(key in this.params))
141
+ throw new Error(`SQL parameter $${this.positional} is missing`);
142
+ return this.params[key];
143
+ }
144
+ if (name.startsWith("$")) {
145
+ const key = name.slice(1);
146
+ if (Array.isArray(this.params)) {
147
+ const index = Number(key);
148
+ if (!Number.isInteger(index) || index < 1 || index > this.params.length) {
149
+ throw new Error(`SQL parameter ${name} is missing`);
150
+ }
151
+ return this.params[index - 1];
152
+ }
153
+ if (!(key in this.params))
154
+ throw new Error(`SQL parameter ${name} is missing`);
155
+ return this.params[key];
156
+ }
157
+ const key = name.slice(1);
158
+ if (Array.isArray(this.params) || !(key in this.params)) {
159
+ throw new Error(`SQL parameter ${name} is missing`);
160
+ }
161
+ return this.params[key];
162
+ }
163
+ peek() {
164
+ return this.tokens[this.pos];
165
+ }
166
+ next() {
167
+ const token = this.tokens[this.pos];
168
+ if (!token)
169
+ throw new Error("SQL parse error: unexpected end of input");
170
+ this.pos += 1;
171
+ return token;
172
+ }
173
+ isKeyword(word) {
174
+ const token = this.peek();
175
+ return !!token && token.type === "word" && token.value.toUpperCase() === word;
176
+ }
177
+ eatKeyword(word) {
178
+ if (this.isKeyword(word)) {
179
+ this.pos += 1;
180
+ return true;
181
+ }
182
+ return false;
183
+ }
184
+ expectKeyword(word) {
185
+ if (!this.eatKeyword(word)) {
186
+ throw new Error(`SQL parse error: expected ${word}`);
187
+ }
188
+ }
189
+ isPunct(value) {
190
+ const token = this.peek();
191
+ return !!token && token.type === "punct" && token.value === value;
192
+ }
193
+ expectPunct(value) {
194
+ if (!this.isPunct(value)) {
195
+ throw new Error(`SQL parse error: expected '${value}'`);
196
+ }
197
+ this.pos += 1;
198
+ }
199
+ isOp(value) {
200
+ const token = this.peek();
201
+ return !!token && token.type === "op" && token.value === value;
202
+ }
203
+ identifier() {
204
+ const token = this.next();
205
+ if (token.type !== "word") {
206
+ throw new Error(`SQL parse error: expected identifier, got '${token.value}'`);
207
+ }
208
+ return token.value;
209
+ }
210
+ /** `name` or `alias.name`; dots qualify a column by table alias. */
211
+ reference() {
212
+ const name = this.identifier();
213
+ if (!this.isPunct("."))
214
+ return name;
215
+ this.next();
216
+ return `${name}.${this.identifier()}`;
217
+ }
218
+ referenceFrom(head) {
219
+ this.next();
220
+ return `${head}.${this.identifier()}`;
221
+ }
222
+ /** Optional `[AS] alias` after a table reference. */
223
+ tableAlias() {
224
+ if (this.eatKeyword("AS"))
225
+ return this.identifier();
226
+ const token = this.peek();
227
+ if (!token || token.type !== "word")
228
+ return undefined;
229
+ if (Parser.CLAUSE_WORDS.has(token.value.toUpperCase()))
230
+ return undefined;
231
+ this.next();
232
+ return token.value;
233
+ }
234
+ parseStatement() {
235
+ let statement;
236
+ if (this.isKeyword("EXPLAIN"))
237
+ statement = this.parseExplain();
238
+ else if (this.isKeyword("WITH"))
239
+ statement = this.parseWith();
240
+ else if (this.isKeyword("CREATE"))
241
+ statement = this.parseCreate();
242
+ else if (this.isKeyword("INSERT"))
243
+ statement = this.parseInsert();
244
+ else if (this.isKeyword("SELECT"))
245
+ statement = this.parseSelect();
246
+ else if (this.isKeyword("UPDATE"))
247
+ statement = this.parseUpdate();
248
+ else if (this.isKeyword("DELETE"))
249
+ statement = this.parseDelete();
250
+ else if (this.isKeyword("ALTER"))
251
+ statement = this.parseAlter();
252
+ else if (this.isKeyword("DROP"))
253
+ statement = this.parseDrop();
254
+ else
255
+ throw new Error(`SQL parse error: unsupported statement near '${this.peek()?.value ?? "EOF"}'`);
256
+ while (statement.kind === "select" &&
257
+ (this.isKeyword("UNION") || this.isKeyword("INTERSECT") || this.isKeyword("EXCEPT"))) {
258
+ const word = this.next().value.toUpperCase();
259
+ const all = word === "UNION" && this.eatKeyword("ALL");
260
+ const right = this.parseSelect();
261
+ statement = {
262
+ kind: "setOp",
263
+ op: word === "UNION"
264
+ ? all
265
+ ? "unionAll"
266
+ : "union"
267
+ : word === "INTERSECT"
268
+ ? "intersect"
269
+ : "except",
270
+ left: statement,
271
+ right,
272
+ };
273
+ }
274
+ if (this.peek()) {
275
+ throw new Error(`SQL parse error: unexpected token '${this.peek().value}' after a complete statement`);
276
+ }
277
+ return statement;
278
+ }
279
+ parseExplain() {
280
+ this.expectKeyword("EXPLAIN");
281
+ const analyze = this.eatKeyword("ANALYZE");
282
+ if (!this.isKeyword("SELECT")) {
283
+ throw new Error("SQL parse error: EXPLAIN supports only SELECT statements");
284
+ }
285
+ return { kind: "explain", statement: this.parseSelect(), analyze };
286
+ }
287
+ parseWith() {
288
+ this.expectKeyword("WITH");
289
+ if (this.eatKeyword("RECURSIVE")) {
290
+ throw new Error("SQL parse error: recursive CTEs are not supported");
291
+ }
292
+ const ctes = [];
293
+ for (;;) {
294
+ const name = this.identifier();
295
+ let columns;
296
+ if (this.isPunct("(")) {
297
+ this.next();
298
+ columns = this.identifierList();
299
+ this.expectPunct(")");
300
+ }
301
+ this.expectKeyword("AS");
302
+ this.expectPunct("(");
303
+ const query = this.subquerySelect();
304
+ this.expectPunct(")");
305
+ ctes.push({ name, columns, query });
306
+ if (this.isPunct(",")) {
307
+ this.next();
308
+ continue;
309
+ }
310
+ break;
311
+ }
312
+ if (!this.isKeyword("SELECT")) {
313
+ throw new Error("SQL parse error: WITH supports a SELECT body only");
314
+ }
315
+ let body = this.parseSelect();
316
+ while (body.kind === "select" &&
317
+ (this.isKeyword("UNION") || this.isKeyword("INTERSECT") || this.isKeyword("EXCEPT"))) {
318
+ const word = this.next().value.toUpperCase();
319
+ const all = word === "UNION" && this.eatKeyword("ALL");
320
+ const right = this.parseSelect();
321
+ body = {
322
+ kind: "setOp",
323
+ op: word === "UNION"
324
+ ? all
325
+ ? "unionAll"
326
+ : "union"
327
+ : word === "INTERSECT"
328
+ ? "intersect"
329
+ : "except",
330
+ left: body,
331
+ right,
332
+ };
333
+ }
334
+ return { kind: "with", ctes, body };
335
+ }
336
+ parseDrop() {
337
+ this.expectKeyword("DROP");
338
+ const token = this.peek();
339
+ if (!token || token.type !== "word" || token.value.toUpperCase() !== "VIEW") {
340
+ throw new Error(`SQL parse error: unsupported statement near 'DROP ${token?.value ?? "EOF"}'`);
341
+ }
342
+ this.next();
343
+ const ifExists = this.eatKeyword("IF");
344
+ if (ifExists)
345
+ this.expectKeyword("EXISTS");
346
+ return { kind: "dropView", name: this.identifier(), ifExists };
347
+ }
348
+ parseCreate() {
349
+ this.expectKeyword("CREATE");
350
+ if (this.eatKeyword("DATABASE")) {
351
+ const name = this.identifier();
352
+ return { kind: "createDatabase", name };
353
+ }
354
+ if (this.eatKeyword("VIEW")) {
355
+ const name = this.identifier();
356
+ this.expectKeyword("AS");
357
+ return { kind: "createView", name, query: this.subquerySelect() };
358
+ }
359
+ if (this.eatKeyword("OR")) {
360
+ this.expectKeyword("REPLACE");
361
+ this.expectKeyword("VIEW");
362
+ const name = this.identifier();
363
+ this.expectKeyword("AS");
364
+ return { kind: "createView", name, query: this.subquerySelect(), replace: true };
365
+ }
366
+ const unique = this.eatKeyword("UNIQUE");
367
+ if (this.eatKeyword("INDEX")) {
368
+ const name = this.identifier();
369
+ this.expectKeyword("ON");
370
+ const table = this.identifier();
371
+ this.expectPunct("(");
372
+ const columns = [];
373
+ while (!this.isPunct(")")) {
374
+ columns.push(this.identifier());
375
+ if (this.isPunct(","))
376
+ this.next();
377
+ }
378
+ this.expectPunct(")");
379
+ if (columns.length === 0)
380
+ throw new Error("SQL parse error: INDEX requires columns");
381
+ return { kind: "createIndex", name, table, column: columns[0], columns, unique };
382
+ }
383
+ if (unique) {
384
+ throw new Error("SQL parse error: UNIQUE must be followed by INDEX");
385
+ }
386
+ this.expectKeyword("TABLE");
387
+ const name = this.identifier();
388
+ this.expectPunct("(");
389
+ const columns = [];
390
+ const constraints = [];
391
+ while (!this.isPunct(")")) {
392
+ if (this.isKeyword("PRIMARY")) {
393
+ this.expectKeyword("PRIMARY");
394
+ this.expectKeyword("KEY");
395
+ this.expectPunct("(");
396
+ const columns = this.identifierList();
397
+ this.expectPunct(")");
398
+ constraints.push(columns.length === 1
399
+ ? { kind: "primaryKey", column: columns[0] }
400
+ : { kind: "compositePrimaryKey", columns });
401
+ }
402
+ else if (this.isKeyword("UNIQUE")) {
403
+ this.expectKeyword("UNIQUE");
404
+ this.expectPunct("(");
405
+ const columns = this.identifierList();
406
+ this.expectPunct(")");
407
+ constraints.push(columns.length === 1
408
+ ? { kind: "unique", column: columns[0] }
409
+ : { kind: "compositeUnique", columns });
410
+ }
411
+ else if (this.isKeyword("CHECK")) {
412
+ this.expectKeyword("CHECK");
413
+ this.expectPunct("(");
414
+ const expression = this.parseExpression();
415
+ this.expectPunct(")");
416
+ constraints.push({ kind: "check", expr: expression });
417
+ }
418
+ else if (this.isKeyword("FOREIGN")) {
419
+ throw new Error("SQL parse error: FOREIGN KEY is not supported; keep the reference in the application.");
420
+ }
421
+ else {
422
+ columns.push(this.parseColumnDef());
423
+ if (this.eatKeyword("PRIMARY")) {
424
+ this.expectKeyword("KEY");
425
+ constraints.push({ kind: "primaryKey", column: columns[columns.length - 1].name });
426
+ }
427
+ else if (this.eatKeyword("UNIQUE")) {
428
+ constraints.push({ kind: "unique", column: columns[columns.length - 1].name });
429
+ }
430
+ }
431
+ if (this.isPunct(","))
432
+ this.next();
433
+ }
434
+ this.expectPunct(")");
435
+ if (this.isPunct(";"))
436
+ this.next();
437
+ return { kind: "createTable", name, columns, constraints };
438
+ }
439
+ identifierList() {
440
+ const columns = [];
441
+ while (!this.isPunct(")")) {
442
+ columns.push(this.identifier());
443
+ if (this.isPunct(","))
444
+ this.next();
445
+ }
446
+ if (columns.length === 0)
447
+ throw new Error("SQL parse error: expected at least one column");
448
+ return columns;
449
+ }
450
+ parseColumnDef() {
451
+ const name = this.identifier();
452
+ const token = this.next();
453
+ if (token.type !== "word") {
454
+ throw new Error(`SQL parse error: expected a column type for '${name}'`);
455
+ }
456
+ const upper = token.value.toUpperCase();
457
+ let type;
458
+ let scale;
459
+ let maxLen;
460
+ switch (upper) {
461
+ case "BOOLEAN":
462
+ case "BOOL":
463
+ type = "bool";
464
+ break;
465
+ case "BIGINT":
466
+ case "INT":
467
+ case "INTEGER":
468
+ case "I64":
469
+ type = "i64";
470
+ break;
471
+ case "TEXT":
472
+ case "STRING":
473
+ type = "text";
474
+ break;
475
+ case "UUID":
476
+ type = "uuid";
477
+ break;
478
+ case "DATE":
479
+ type = "date";
480
+ break;
481
+ case "ADDRESS":
482
+ case "PUBKEY":
483
+ type = "address";
484
+ break;
485
+ case "INET":
486
+ type = "inet";
487
+ break;
488
+ case "CIDR":
489
+ type = "cidr";
490
+ break;
491
+ case "MACADDR":
492
+ type = "macaddr";
493
+ break;
494
+ case "BIT":
495
+ type = "bit";
496
+ maxLen = 1;
497
+ if (this.isPunct("(")) {
498
+ this.next();
499
+ maxLen = Number(this.next().value);
500
+ this.expectPunct(")");
501
+ }
502
+ break;
503
+ case "INT8RANGE":
504
+ case "RANGE":
505
+ type = "range";
506
+ break;
507
+ case "NUMRANGE":
508
+ type = "numrange";
509
+ scale = 0;
510
+ if (this.isPunct("(")) {
511
+ this.next();
512
+ scale = Number(this.next().value);
513
+ this.expectPunct(")");
514
+ }
515
+ break;
516
+ case "TSRANGE":
517
+ type = "tsrange";
518
+ break;
519
+ case "DATERANGE":
520
+ type = "daterange";
521
+ break;
522
+ case "VARBIT":
523
+ type = "varbit";
524
+ maxLen = 0;
525
+ if (this.isPunct("(")) {
526
+ this.next();
527
+ maxLen = Number(this.next().value);
528
+ this.expectPunct(")");
529
+ }
530
+ break;
531
+ case "TIMESTAMP":
532
+ case "TIMESTAMPTZ":
533
+ type = "timestamp";
534
+ break;
535
+ case "TIME":
536
+ case "TIMETZ":
537
+ type = "time";
538
+ break;
539
+ case "INTERVAL":
540
+ type = "interval";
541
+ break;
542
+ case "MONEY":
543
+ type = "decimal";
544
+ scale = 2;
545
+ break;
546
+ case "VARCHAR":
547
+ case "CHAR":
548
+ type = "text";
549
+ if (this.isPunct("(")) {
550
+ this.next();
551
+ maxLen = Number(this.next().value);
552
+ this.expectPunct(")");
553
+ }
554
+ break;
555
+ case "DECIMAL":
556
+ case "NUMERIC":
557
+ type = "decimal";
558
+ if (this.isPunct("(")) {
559
+ this.next();
560
+ this.next(); // precision
561
+ this.expectPunct(",");
562
+ scale = Number(this.next().value);
563
+ this.expectPunct(")");
564
+ }
565
+ else {
566
+ scale = 0;
567
+ }
568
+ break;
569
+ default:
570
+ throw new Error(`SQL parse error: unsupported column type '${token.value}'. ` +
571
+ `Use BOOL, INT/BIGINT, TEXT/VARCHAR, UUID or DECIMAL(precision, scale).`);
572
+ }
573
+ const column = { name, type, nullable: true, scale, maxLen };
574
+ if (this.eatKeyword("AUTO_INCREMENT") || this.eatKeyword("AUTOINCREMENT")) {
575
+ throw new Error("SQL parse error: AUTO_INCREMENT is not supported; supply the value in INSERT.");
576
+ }
577
+ while (true) {
578
+ if (this.eatKeyword("NOT")) {
579
+ this.expectKeyword("NULL");
580
+ column.nullable = false;
581
+ }
582
+ else if (this.eatKeyword("NULL")) {
583
+ column.nullable = true;
584
+ }
585
+ else if (this.eatKeyword("DEFAULT")) {
586
+ column.default = this.parseLiteralValue();
587
+ }
588
+ else {
589
+ break;
590
+ }
591
+ }
592
+ return column;
593
+ }
594
+ parseLiteralValue() {
595
+ // Numeric literals become bigint (integers) or number (decimals) so the
596
+ // expression compiler can infer I64/DECIMAL instead of TEXT.
597
+ let sign = 1n;
598
+ if (this.isPunct("-")) {
599
+ this.next();
600
+ sign = -1n;
601
+ }
602
+ else if (this.isPunct("+")) {
603
+ this.next();
604
+ }
605
+ const token = this.next();
606
+ if (token.type === "param")
607
+ return this.paramValue(token);
608
+ if (token.type === "string")
609
+ return token.value;
610
+ if (token.type === "number") {
611
+ if (token.value.includes("."))
612
+ return Number(token.value) * Number(sign);
613
+ return BigInt(token.value) * sign;
614
+ }
615
+ if (token.type === "word") {
616
+ const upper = token.value.toUpperCase();
617
+ if (upper === "TRUE")
618
+ return true;
619
+ if (upper === "FALSE")
620
+ return false;
621
+ if (upper === "NULL")
622
+ return null;
623
+ }
624
+ throw new Error(`SQL parse error: expected a literal, got '${token.value}'`);
625
+ }
626
+ parseInsert() {
627
+ this.expectKeyword("INSERT");
628
+ this.expectKeyword("INTO");
629
+ const table = this.identifier();
630
+ let columns = null;
631
+ if (this.isPunct("(")) {
632
+ this.next();
633
+ columns = [];
634
+ while (!this.isPunct(")")) {
635
+ columns.push(this.identifier());
636
+ if (this.isPunct(","))
637
+ this.next();
638
+ }
639
+ this.expectPunct(")");
640
+ }
641
+ this.expectKeyword("VALUES");
642
+ const rows = [];
643
+ while (true) {
644
+ this.expectPunct("(");
645
+ const row = [];
646
+ while (!this.isPunct(")")) {
647
+ row.push(this.parseLiteralValue());
648
+ if (this.isPunct(","))
649
+ this.next();
650
+ }
651
+ this.expectPunct(")");
652
+ rows.push(row);
653
+ if (this.isPunct(",")) {
654
+ this.next();
655
+ continue;
656
+ }
657
+ break;
658
+ }
659
+ let onConflict;
660
+ if (this.eatKeyword("ON")) {
661
+ this.expectKeyword("CONFLICT");
662
+ // Optional conflict target; only the primary key is supported, so the
663
+ // target is accepted for PostgreSQL compatibility and validated by the
664
+ // executor against the table's primary key.
665
+ if (this.isPunct("(")) {
666
+ this.next();
667
+ while (!this.isPunct(")")) {
668
+ this.identifier();
669
+ if (this.isPunct(","))
670
+ this.next();
671
+ }
672
+ this.expectPunct(")");
673
+ }
674
+ this.expectKeyword("DO");
675
+ if (this.eatKeyword("NOTHING")) {
676
+ onConflict = { action: "nothing" };
677
+ }
678
+ else {
679
+ this.expectKeyword("UPDATE");
680
+ this.expectKeyword("SET");
681
+ const assignments = [];
682
+ while (true) {
683
+ const column = this.identifier();
684
+ this.expectPunct("=");
685
+ assignments.push({ column, value: this.parseLiteralValue() });
686
+ if (this.isPunct(",")) {
687
+ this.next();
688
+ continue;
689
+ }
690
+ break;
691
+ }
692
+ onConflict = { action: "update", assignments };
693
+ }
694
+ }
695
+ const returning = this.parseReturning();
696
+ if (this.isPunct(";"))
697
+ this.next();
698
+ return { kind: "insert", table, columns, rows, onConflict, returning };
699
+ }
700
+ parseReturning() {
701
+ if (!this.eatKeyword("RETURNING"))
702
+ return undefined;
703
+ if (this.isPunct("*")) {
704
+ this.next();
705
+ return "*";
706
+ }
707
+ const columns = [];
708
+ while (true) {
709
+ columns.push(this.identifier());
710
+ if (this.isPunct(",")) {
711
+ this.next();
712
+ continue;
713
+ }
714
+ break;
715
+ }
716
+ return columns;
717
+ }
718
+ parseSelect() {
719
+ this.expectKeyword("SELECT");
720
+ let columns = "*";
721
+ const selectItems = [];
722
+ if (this.isPunct("*")) {
723
+ this.next();
724
+ }
725
+ else {
726
+ columns = [];
727
+ while (!this.isKeyword("FROM")) {
728
+ const token = this.peek();
729
+ const upper = token?.type === "word" ? token.value.toUpperCase() : "";
730
+ if (token?.type === "word" &&
731
+ ["COUNT", "SUM", "AVG", "MIN", "MAX"].includes(upper) &&
732
+ this.tokens[this.pos + 1]?.value === "(") {
733
+ const fn = upper.toLowerCase();
734
+ this.next();
735
+ this.expectPunct("(");
736
+ let column;
737
+ if (this.isPunct("*")) {
738
+ this.next();
739
+ }
740
+ else {
741
+ column = this.reference();
742
+ }
743
+ this.expectPunct(")");
744
+ let filter;
745
+ if (this.eatKeyword("FILTER")) {
746
+ this.expectPunct("(");
747
+ this.expectKeyword("WHERE");
748
+ filter = this.parseExpression();
749
+ this.expectPunct(")");
750
+ }
751
+ let alias;
752
+ if (this.eatKeyword("AS"))
753
+ alias = this.identifier();
754
+ selectItems.push({ kind: "aggregate", fn, column, alias, filter });
755
+ }
756
+ else {
757
+ const next = this.tokens[this.pos + 1];
758
+ const plainColumn = token?.type === "word" &&
759
+ ((next?.type === "punct" && next.value === ".") ||
760
+ !next ||
761
+ (next.type === "punct" && next.value === ",") ||
762
+ (next.type === "word" && ["AS", "FROM"].includes(next.value.toUpperCase())));
763
+ if (!plainColumn) {
764
+ const expression = this.parseExpression();
765
+ if (expression.k === "agg") {
766
+ let alias;
767
+ if (this.eatKeyword("AS"))
768
+ alias = this.identifier();
769
+ selectItems.push({
770
+ kind: "aggregate",
771
+ fn: expression.fn,
772
+ column: expression.column,
773
+ alias,
774
+ });
775
+ }
776
+ else {
777
+ let alias = `expr${selectItems.length + 1}`;
778
+ if (this.eatKeyword("AS"))
779
+ alias = this.identifier();
780
+ selectItems.push({ kind: "expr", expr: expression, alias });
781
+ }
782
+ }
783
+ else {
784
+ const name = this.reference();
785
+ let alias;
786
+ if (this.eatKeyword("AS"))
787
+ alias = this.identifier();
788
+ columns.push(name);
789
+ selectItems.push({ kind: "column", name, alias });
790
+ }
791
+ }
792
+ if (this.isPunct(","))
793
+ this.next();
794
+ }
795
+ }
796
+ this.expectKeyword("FROM");
797
+ const table = this.identifier();
798
+ const alias = this.tableAlias();
799
+ let join;
800
+ if (this.isKeyword("INNER") || this.isKeyword("LEFT") || this.isKeyword("RIGHT") || this.isKeyword("JOIN")) {
801
+ let kind = "inner";
802
+ if (this.eatKeyword("LEFT"))
803
+ kind = "left";
804
+ else if (this.eatKeyword("RIGHT"))
805
+ kind = "right";
806
+ else
807
+ this.eatKeyword("INNER");
808
+ this.expectKeyword("JOIN");
809
+ const joinTable = this.identifier();
810
+ const joinAlias = this.tableAlias();
811
+ this.expectKeyword("ON");
812
+ const left = this.reference();
813
+ this.expectPunct("=");
814
+ const right = this.reference();
815
+ join = {
816
+ kind,
817
+ table: joinTable,
818
+ alias: joinAlias,
819
+ on: {
820
+ k: "cmp",
821
+ op: "eq",
822
+ a: { k: "id", name: left, side: "new" },
823
+ b: { k: "id", name: right, side: "new" },
824
+ },
825
+ };
826
+ }
827
+ let where;
828
+ if (this.eatKeyword("WHERE")) {
829
+ where = this.parseExpression();
830
+ }
831
+ let groupBy;
832
+ if (this.eatKeyword("GROUP")) {
833
+ this.expectKeyword("BY");
834
+ groupBy = this.reference();
835
+ }
836
+ let having;
837
+ if (this.eatKeyword("HAVING")) {
838
+ having = this.parseExpression();
839
+ }
840
+ let orderBy;
841
+ if (this.eatKeyword("ORDER")) {
842
+ this.expectKeyword("BY");
843
+ orderBy = [];
844
+ while (true) {
845
+ const column = this.reference();
846
+ let direction = "asc";
847
+ if (this.eatKeyword("ASC"))
848
+ direction = "asc";
849
+ else if (this.eatKeyword("DESC"))
850
+ direction = "desc";
851
+ let nulls;
852
+ if (this.eatKeyword("NULLS")) {
853
+ if (this.eatKeyword("FIRST"))
854
+ nulls = "first";
855
+ else {
856
+ this.expectKeyword("LAST");
857
+ nulls = "last";
858
+ }
859
+ }
860
+ orderBy.push({ column, direction, nulls });
861
+ if (this.isPunct(",")) {
862
+ this.next();
863
+ continue;
864
+ }
865
+ break;
866
+ }
867
+ }
868
+ let limit;
869
+ if (this.eatKeyword("LIMIT")) {
870
+ limit = Number(this.next().value);
871
+ if (!Number.isInteger(limit) || limit < 0) {
872
+ throw new Error("SQL parse error: LIMIT must be a non-negative integer");
873
+ }
874
+ }
875
+ let offset;
876
+ if (this.eatKeyword("OFFSET")) {
877
+ offset = Number(this.next().value);
878
+ if (!Number.isInteger(offset) || offset < 0) {
879
+ throw new Error("SQL parse error: OFFSET must be a non-negative integer");
880
+ }
881
+ }
882
+ if (this.isPunct(";"))
883
+ this.next();
884
+ return {
885
+ kind: "select",
886
+ table,
887
+ alias,
888
+ columns,
889
+ selectItems: selectItems.length > 0 ? selectItems : undefined,
890
+ join,
891
+ groupBy,
892
+ having,
893
+ where,
894
+ orderBy,
895
+ limit,
896
+ offset,
897
+ };
898
+ }
899
+ parseUpdate() {
900
+ this.expectKeyword("UPDATE");
901
+ const table = this.identifier();
902
+ this.expectKeyword("SET");
903
+ const assignments = [];
904
+ while (true) {
905
+ const column = this.identifier();
906
+ this.expectPunct("=");
907
+ assignments.push({ column, value: this.parseLiteralValue() });
908
+ if (this.isPunct(",")) {
909
+ this.next();
910
+ continue;
911
+ }
912
+ break;
913
+ }
914
+ this.expectKeyword("WHERE");
915
+ const where = this.parseExpression();
916
+ const returning = this.parseReturning();
917
+ if (this.isPunct(";"))
918
+ this.next();
919
+ return { kind: "update", table, assignments, where, returning };
920
+ }
921
+ parseDelete() {
922
+ this.expectKeyword("DELETE");
923
+ this.expectKeyword("FROM");
924
+ const table = this.identifier();
925
+ this.expectKeyword("WHERE");
926
+ const where = this.parseExpression();
927
+ const returning = this.parseReturning();
928
+ if (this.isPunct(";"))
929
+ this.next();
930
+ return { kind: "delete", table, where, returning };
931
+ }
932
+ parseAlter() {
933
+ this.expectKeyword("ALTER");
934
+ this.expectKeyword("TABLE");
935
+ const table = this.identifier();
936
+ this.expectKeyword("ADD");
937
+ this.eatKeyword("COLUMN");
938
+ const addColumns = [];
939
+ while (true) {
940
+ addColumns.push(this.parseColumnDef());
941
+ if (this.isPunct(",")) {
942
+ this.next();
943
+ continue;
944
+ }
945
+ break;
946
+ }
947
+ if (this.isPunct(";"))
948
+ this.next();
949
+ return { kind: "alterTable", table, addColumns };
950
+ }
951
+ // Expression grammar: OR < AND < NOT < comparison < additive < primary.
952
+ parseExpression() {
953
+ return this.parseOr();
954
+ }
955
+ parseOr() {
956
+ let left = this.parseAnd();
957
+ while (this.eatKeyword("OR")) {
958
+ left = { k: "or", a: left, b: this.parseAnd() };
959
+ }
960
+ return left;
961
+ }
962
+ parseAnd() {
963
+ let left = this.parseNot();
964
+ while (this.eatKeyword("AND")) {
965
+ left = { k: "and", a: left, b: this.parseNot() };
966
+ }
967
+ return left;
968
+ }
969
+ parseNot() {
970
+ if (this.eatKeyword("NOT")) {
971
+ return { k: "not", a: this.parseNot() };
972
+ }
973
+ return this.parseComparison();
974
+ }
975
+ parseComparison() {
976
+ const left = this.parseAdditive();
977
+ if (this.isKeyword("IS")) {
978
+ this.next();
979
+ const not = this.eatKeyword("NOT");
980
+ this.expectKeyword("NULL");
981
+ return not ? { k: "isnotnull", a: left } : { k: "isnull", a: left };
982
+ }
983
+ const negated = this.eatKeyword("NOT");
984
+ if (this.isKeyword("BETWEEN")) {
985
+ this.next();
986
+ const low = this.parseAdditive();
987
+ this.expectKeyword("AND");
988
+ const high = this.parseAdditive();
989
+ return { k: "between", a: left, low, high, negated };
990
+ }
991
+ if (this.isKeyword("IN")) {
992
+ this.next();
993
+ this.expectPunct("(");
994
+ if (this.isKeyword("SELECT")) {
995
+ const query = this.subquerySelect();
996
+ this.expectPunct(")");
997
+ return {
998
+ k: "subquery",
999
+ query,
1000
+ mode: negated ? "notin" : "in",
1001
+ a: left,
1002
+ };
1003
+ }
1004
+ const values = [];
1005
+ while (!this.isPunct(")")) {
1006
+ values.push(this.parseAdditive());
1007
+ if (this.isPunct(","))
1008
+ this.next();
1009
+ }
1010
+ this.expectPunct(")");
1011
+ if (values.length === 0)
1012
+ throw new Error("SQL parse error: IN requires at least one value");
1013
+ return { k: "in", a: left, values, negated };
1014
+ }
1015
+ if (negated) {
1016
+ throw new Error("SQL parse error: NOT is only supported before NULL, BETWEEN and IN");
1017
+ }
1018
+ const token = this.peek();
1019
+ const rangeOps = {
1020
+ "@>": "contains",
1021
+ "<@": "contained",
1022
+ "&&": "overlaps",
1023
+ "<<": "leftOf",
1024
+ ">>": "rightOf",
1025
+ "-|-": "adjacent",
1026
+ };
1027
+ if (token && token.type === "op" && rangeOps[token.value]) {
1028
+ this.next();
1029
+ return { k: "rangep", op: rangeOps[token.value], a: left, b: this.parseAdditive() };
1030
+ }
1031
+ const comparisonOps = { "=": "eq", "<>": "ne", "!=": "ne", "<": "lt", "<=": "le", ">": "gt", ">=": "ge" };
1032
+ if (token && comparisonOps[token.value] && (token.type === "op" || token.type === "punct")) {
1033
+ this.next();
1034
+ const op = comparisonOps[token.value];
1035
+ const right = this.parseAdditive();
1036
+ return { k: "cmp", op: op, a: left, b: right };
1037
+ }
1038
+ return left;
1039
+ }
1040
+ parseAdditive() {
1041
+ let left = this.parsePrimary();
1042
+ while (this.isPunct("+") || this.isPunct("-") || this.isPunct("*") || this.isPunct("/")) {
1043
+ const op = this.next().value;
1044
+ const right = this.parsePrimary();
1045
+ const mapped = { "+": "add", "-": "sub", "*": "mul", "/": "div" }[op];
1046
+ left = { k: "arith", op: mapped, a: left, b: right };
1047
+ }
1048
+ return left;
1049
+ }
1050
+ subquerySelect() {
1051
+ const statement = this.parseSelect();
1052
+ if (statement.kind !== "select") {
1053
+ throw new Error("SQL parse error: expected a SELECT subquery");
1054
+ }
1055
+ return statement;
1056
+ }
1057
+ parseCastType() {
1058
+ const token = this.next();
1059
+ if (token.type !== "word") {
1060
+ throw new Error(`SQL parse error: expected a CAST target type`);
1061
+ }
1062
+ const upper = token.value.toUpperCase();
1063
+ const readLength = () => {
1064
+ this.expectPunct("(");
1065
+ const value = Number(this.next().value);
1066
+ this.expectPunct(")");
1067
+ return value;
1068
+ };
1069
+ switch (upper) {
1070
+ case "BOOLEAN":
1071
+ case "BOOL":
1072
+ return { type: "bool" };
1073
+ case "BIGINT":
1074
+ case "INT":
1075
+ case "INTEGER":
1076
+ case "I64":
1077
+ return { type: "i64" };
1078
+ case "TEXT":
1079
+ case "STRING":
1080
+ case "VARCHAR":
1081
+ case "CHAR":
1082
+ return { type: "text", maxLen: this.isPunct("(") ? readLength() : undefined };
1083
+ case "UUID":
1084
+ return { type: "uuid" };
1085
+ case "DATE":
1086
+ return { type: "date" };
1087
+ case "TIMESTAMP":
1088
+ case "TIMESTAMPTZ":
1089
+ return { type: "timestamp" };
1090
+ case "TIME":
1091
+ case "TIMETZ":
1092
+ return { type: "time" };
1093
+ case "INT8RANGE":
1094
+ case "RANGE":
1095
+ return { type: "range" };
1096
+ case "NUMRANGE":
1097
+ return { type: "numrange" };
1098
+ case "TSRANGE":
1099
+ return { type: "tsrange" };
1100
+ case "DATERANGE":
1101
+ return { type: "daterange" };
1102
+ case "INTERVAL":
1103
+ return { type: "interval" };
1104
+ case "ADDRESS":
1105
+ case "PUBKEY":
1106
+ return { type: "address" };
1107
+ case "INET":
1108
+ return { type: "inet" };
1109
+ case "CIDR":
1110
+ return { type: "cidr" };
1111
+ case "MACADDR":
1112
+ return { type: "macaddr" };
1113
+ case "BIT":
1114
+ return { type: "bit", maxLen: this.isPunct("(") ? readLength() : 1 };
1115
+ case "VARBIT":
1116
+ return { type: "varbit", maxLen: this.isPunct("(") ? readLength() : 0 };
1117
+ case "INT8RANGE":
1118
+ case "RANGE":
1119
+ return { type: "range" };
1120
+ case "MONEY":
1121
+ return { type: "decimal", scale: 2 };
1122
+ case "DECIMAL":
1123
+ case "NUMERIC": {
1124
+ if (!this.isPunct("("))
1125
+ return { type: "decimal", scale: 0 };
1126
+ this.expectPunct("(");
1127
+ this.next();
1128
+ this.expectPunct(",");
1129
+ const scale = Number(this.next().value);
1130
+ this.expectPunct(")");
1131
+ return { type: "decimal", scale };
1132
+ }
1133
+ default:
1134
+ throw new Error(`SQL parse error: unsupported CAST target type '${token.value}'`);
1135
+ }
1136
+ }
1137
+ parsePrimary() {
1138
+ if (this.isPunct("(")) {
1139
+ if (this.tokens[this.pos + 1]?.type === "word" && this.tokens[this.pos + 1].value.toUpperCase() === "SELECT") {
1140
+ this.next();
1141
+ const query = this.subquerySelect();
1142
+ this.expectPunct(")");
1143
+ return { k: "subquery", query, mode: "scalar" };
1144
+ }
1145
+ this.next();
1146
+ const expression = this.parseExpression();
1147
+ this.expectPunct(")");
1148
+ return expression;
1149
+ }
1150
+ const token = this.next();
1151
+ if (token.type === "param")
1152
+ return { k: "lit", value: this.paramValue(token) };
1153
+ if (token.type === "string")
1154
+ return { k: "lit", value: token.value };
1155
+ if (token.type === "number") {
1156
+ const value = token.value.includes(".") ? Number(token.value) : BigInt(token.value);
1157
+ return { k: "lit", value };
1158
+ }
1159
+ if (token.type === "punct" && (token.value === "-" || token.value === "+")) {
1160
+ const value = this.parsePrimary();
1161
+ if (value.k !== "lit")
1162
+ throw new Error("SQL parse error: unary sign requires a numeric literal");
1163
+ const numeric = typeof value.value === "bigint" ? -value.value : -Number(value.value);
1164
+ return { k: "lit", value: numeric };
1165
+ }
1166
+ if (token.type === "word") {
1167
+ const upper = token.value.toUpperCase();
1168
+ if (upper === "TRUE")
1169
+ return { k: "lit", value: true };
1170
+ if (upper === "FALSE")
1171
+ return { k: "lit", value: false };
1172
+ if (upper === "NULL")
1173
+ return { k: "lit", value: null };
1174
+ if (upper === "SIGNER" || upper === "CURRENT_USER" || upper === "SESSION_USER") {
1175
+ return { k: "signer" };
1176
+ }
1177
+ if (upper === "EXISTS" && this.isPunct("(")) {
1178
+ this.next();
1179
+ const query = this.subquerySelect();
1180
+ this.expectPunct(")");
1181
+ return { k: "subquery", query, mode: "exists" };
1182
+ }
1183
+ if (upper === "INTERVAL") {
1184
+ const literal = this.next();
1185
+ if (literal.type !== "string") {
1186
+ throw new Error("SQL parse error: INTERVAL requires a quoted literal");
1187
+ }
1188
+ return { k: "lit", value: (0, values_1.parseInterval)(literal.value) };
1189
+ }
1190
+ if (upper === "CASE")
1191
+ return this.parseCase();
1192
+ if (upper === "CAST" && this.isPunct("(")) {
1193
+ this.next();
1194
+ const value = this.parseExpression();
1195
+ this.expectKeyword("AS");
1196
+ const target = this.parseCastType();
1197
+ this.expectPunct(")");
1198
+ return { k: "cast", a: value, ...target };
1199
+ }
1200
+ if (upper === "COALESCE" && this.isPunct("(")) {
1201
+ this.next();
1202
+ const args = [];
1203
+ while (!this.isPunct(")")) {
1204
+ args.push(this.parseExpression());
1205
+ if (this.isPunct(","))
1206
+ this.next();
1207
+ }
1208
+ this.expectPunct(")");
1209
+ if (args.length === 0)
1210
+ throw new Error("SQL parse error: COALESCE requires arguments");
1211
+ return { k: "coalesce", args };
1212
+ }
1213
+ if (upper === "NULLIF" && this.isPunct("(")) {
1214
+ this.next();
1215
+ const a = this.parseExpression();
1216
+ this.expectPunct(",");
1217
+ const b = this.parseExpression();
1218
+ this.expectPunct(")");
1219
+ return { k: "nullif", a, b };
1220
+ }
1221
+ const scalarFns = {
1222
+ LOWER: "lower",
1223
+ UPPER: "upper",
1224
+ LENGTH: "length",
1225
+ CHAR_LENGTH: "length",
1226
+ ROUND: "round",
1227
+ ABS: "abs",
1228
+ TRIM: "trim",
1229
+ LTRIM: "ltrim",
1230
+ RTRIM: "rtrim",
1231
+ };
1232
+ if (scalarFns[upper] && this.isPunct("(")) {
1233
+ this.next();
1234
+ const args = [];
1235
+ while (!this.isPunct(")")) {
1236
+ args.push(this.parseExpression());
1237
+ if (this.isPunct(","))
1238
+ this.next();
1239
+ }
1240
+ this.expectPunct(")");
1241
+ return { k: "func", fn: scalarFns[upper], args };
1242
+ }
1243
+ if (["COUNT", "SUM", "AVG", "MIN", "MAX"].includes(upper) &&
1244
+ this.isPunct("(")) {
1245
+ const fn = upper.toLowerCase();
1246
+ this.next();
1247
+ let column;
1248
+ if (this.isPunct("*"))
1249
+ this.next();
1250
+ else
1251
+ column = this.reference();
1252
+ this.expectPunct(")");
1253
+ return { k: "agg", fn, column };
1254
+ }
1255
+ return { k: "id", name: this.isPunct(".") ? this.referenceFrom(token.value) : token.value, side: "new" };
1256
+ }
1257
+ throw new Error(`SQL parse error: unexpected token '${token.value}'`);
1258
+ }
1259
+ parseCase() {
1260
+ let operand;
1261
+ if (!this.isKeyword("WHEN"))
1262
+ operand = this.parseExpression();
1263
+ const whens = [];
1264
+ while (this.eatKeyword("WHEN")) {
1265
+ const when = this.parseExpression();
1266
+ this.expectKeyword("THEN");
1267
+ const then = this.parseExpression();
1268
+ whens.push({ when, then });
1269
+ }
1270
+ if (whens.length === 0)
1271
+ throw new Error("SQL parse error: CASE requires at least one WHEN");
1272
+ const otherwise = this.eatKeyword("ELSE") ? this.parseExpression() : undefined;
1273
+ this.expectKeyword("END");
1274
+ return { k: "case", operand, whens, otherwise };
1275
+ }
1276
+ }
1277
+ Parser.CLAUSE_WORDS = new Set([
1278
+ "WHERE",
1279
+ "INNER",
1280
+ "LEFT",
1281
+ "RIGHT",
1282
+ "JOIN",
1283
+ "GROUP",
1284
+ "HAVING",
1285
+ "ORDER",
1286
+ "LIMIT",
1287
+ "OFFSET",
1288
+ "UNION",
1289
+ "INTERSECT",
1290
+ "EXCEPT",
1291
+ "ON",
1292
+ ]);
1293
+ /** Splits on top-level semicolons, ignoring those inside literals/comments. */
1294
+ function splitStatements(sql) {
1295
+ const chunks = [];
1296
+ let start = 0;
1297
+ let i = 0;
1298
+ while (i < sql.length) {
1299
+ const c = sql[i];
1300
+ if (c === "-" && sql[i + 1] === "-") {
1301
+ while (i < sql.length && sql[i] !== "\n")
1302
+ i += 1;
1303
+ continue;
1304
+ }
1305
+ if (c === "'" || c === '"') {
1306
+ const quote = c;
1307
+ i += 1;
1308
+ while (i < sql.length) {
1309
+ if (sql[i] === quote && sql[i + 1] === quote) {
1310
+ i += 2;
1311
+ continue;
1312
+ }
1313
+ if (sql[i] === quote) {
1314
+ i += 1;
1315
+ break;
1316
+ }
1317
+ i += 1;
1318
+ }
1319
+ continue;
1320
+ }
1321
+ if (c === ";") {
1322
+ chunks.push(sql.slice(start, i));
1323
+ start = i + 1;
1324
+ }
1325
+ i += 1;
1326
+ }
1327
+ chunks.push(sql.slice(start));
1328
+ return chunks;
1329
+ }
1330
+ /** Splits a SQL script into statements and parses each one. */
1331
+ function parseSql(sql, params = []) {
1332
+ const statements = [];
1333
+ if (!sql.trim())
1334
+ return statements;
1335
+ for (const chunk of splitStatements(sql)) {
1336
+ if (!chunk.trim())
1337
+ continue;
1338
+ statements.push(new Parser(tokenize(chunk), params).parseStatement());
1339
+ }
1340
+ return statements;
1341
+ }
1342
+ /** Parses a single SQL statement. */
1343
+ function parseSqlStatement(sql, params = []) {
1344
+ const statements = parseSql(sql, params);
1345
+ if (statements.length !== 1) {
1346
+ throw new Error(`SQL parse error: expected exactly one statement`);
1347
+ }
1348
+ return statements[0];
1349
+ }
1350
+ /** Infers a range subtype from a literal such as `[1,10)`, `[1.50,2.00)` or `["2020-01-01","2020-02-01")`. */
1351
+ function inferRangeLiteral(text) {
1352
+ const inner = text.trim().slice(1, -1);
1353
+ const parts = inner.split(",");
1354
+ const quoted = parts.every((part) => part.trim().startsWith('"'));
1355
+ if (quoted) {
1356
+ return {
1357
+ type: parts.some((part) => part.includes(":")) ? "tsrange" : "daterange",
1358
+ };
1359
+ }
1360
+ const decimals = Math.max(...parts.map((part) => {
1361
+ const dot = part.indexOf(".");
1362
+ return dot < 0 ? 0 : part.trim().replace(/^-/, "").split(".")[1]?.length ?? 0;
1363
+ }));
1364
+ return decimals > 0 ? { type: "numrange", scale: decimals } : { type: "range" };
1365
+ }
1366
+ /** Binds a name-based expression onto a table's column list. */
1367
+ /** Best-effort static type of a name expression, used to pick calendar opcodes. */
1368
+ function nameExprType(node, columns) {
1369
+ if (node.k === "id") {
1370
+ return columns.find((column) => column.name === node.name)?.type;
1371
+ }
1372
+ if (node.k === "lit") {
1373
+ const value = node.value;
1374
+ if (value === null || value === undefined)
1375
+ return undefined;
1376
+ if (typeof value === "boolean")
1377
+ return "bool";
1378
+ if (typeof value === "bigint" || typeof value === "number")
1379
+ return "i64";
1380
+ if (typeof value === "string")
1381
+ return "text";
1382
+ if (typeof value === "object" && value !== null && "interval" in value)
1383
+ return "interval";
1384
+ }
1385
+ return undefined;
1386
+ }
1387
+ function calendarKind(op, left, right) {
1388
+ if (op === "mul" || op === "div")
1389
+ return undefined;
1390
+ if (left === "date" && right === "interval")
1391
+ return "date";
1392
+ if (left === "timestamp" && right === "interval")
1393
+ return "timestamp";
1394
+ if (left === "interval" && right === "interval")
1395
+ return "interval";
1396
+ if (op === "sub" && left === "date" && right === "date")
1397
+ return "date";
1398
+ if (op === "sub" && left === "timestamp" && right === "timestamp")
1399
+ return "timestamp";
1400
+ return undefined;
1401
+ }
1402
+ function bindNameExpr(node, columns) {
1403
+ switch (node.k) {
1404
+ case "lit":
1405
+ return { k: "lit", value: node.value };
1406
+ case "id": {
1407
+ const index = columns.findIndex((c) => c.name === node.name);
1408
+ if (index < 0)
1409
+ throw new Error(`unknown column: ${node.name}`);
1410
+ return { k: "col", index, side: node.side };
1411
+ }
1412
+ case "signer":
1413
+ return { k: "signer" };
1414
+ case "agg":
1415
+ throw new Error("aggregate functions are only valid in SELECT and HAVING");
1416
+ case "cmp":
1417
+ return { k: "cmp", op: node.op, a: bindNameExpr(node.a, columns), b: bindNameExpr(node.b, columns) };
1418
+ case "rangep": {
1419
+ // Range literals arrive as text ("[1,10)"); coerce them against the
1420
+ // other operand's declared range type before compiling.
1421
+ const bindOperand = (operand, other) => {
1422
+ const literal = operand.k === "lit" ? operand.value : undefined;
1423
+ const rangeLiteral = typeof literal === "string" ||
1424
+ (typeof literal === "object" && literal !== null && "range" in literal);
1425
+ if (operand.k === "lit" && rangeLiteral) {
1426
+ const column = other.k === "id"
1427
+ ? columns.find((c) => c.name === other.name)
1428
+ : undefined;
1429
+ const target = column && column.type.endsWith("range")
1430
+ ? { type: column.type, scale: column.scale }
1431
+ : typeof literal === "string"
1432
+ ? inferRangeLiteral(literal)
1433
+ : null;
1434
+ if (target) {
1435
+ const value = (0, values_1.coerceValue)(operand.value, target);
1436
+ return { k: "lit", value };
1437
+ }
1438
+ }
1439
+ return bindNameExpr(operand, columns);
1440
+ };
1441
+ return {
1442
+ k: "rangep",
1443
+ op: node.op,
1444
+ a: bindOperand(node.a, node.b),
1445
+ b: bindOperand(node.b, node.a),
1446
+ };
1447
+ }
1448
+ case "and":
1449
+ case "or":
1450
+ return { k: node.k, a: bindNameExpr(node.a, columns), b: bindNameExpr(node.b, columns) };
1451
+ case "not":
1452
+ return { k: "not", a: bindNameExpr(node.a, columns) };
1453
+ case "isnull":
1454
+ case "isnotnull":
1455
+ return { k: node.k, a: bindNameExpr(node.a, columns) };
1456
+ case "between":
1457
+ return {
1458
+ k: "between",
1459
+ a: bindNameExpr(node.a, columns),
1460
+ low: bindNameExpr(node.low, columns),
1461
+ high: bindNameExpr(node.high, columns),
1462
+ negated: node.negated,
1463
+ };
1464
+ case "in":
1465
+ return {
1466
+ k: "in",
1467
+ a: bindNameExpr(node.a, columns),
1468
+ values: node.values.map((value) => bindNameExpr(value, columns)),
1469
+ negated: node.negated,
1470
+ };
1471
+ case "arith": {
1472
+ const left = bindNameExpr(node.a, columns);
1473
+ const right = bindNameExpr(node.b, columns);
1474
+ const calendar = calendarKind(node.op, nameExprType(node.a, columns), nameExprType(node.b, columns));
1475
+ return { k: "arith", op: node.op, a: left, b: right, ...(calendar ? { calendar } : {}) };
1476
+ }
1477
+ case "case":
1478
+ return {
1479
+ k: "case",
1480
+ operand: node.operand ? bindNameExpr(node.operand, columns) : undefined,
1481
+ whens: node.whens.map((entry) => ({
1482
+ when: bindNameExpr(entry.when, columns),
1483
+ then: bindNameExpr(entry.then, columns),
1484
+ })),
1485
+ otherwise: node.otherwise ? bindNameExpr(node.otherwise, columns) : undefined,
1486
+ };
1487
+ case "coalesce":
1488
+ return { k: "coalesce", args: node.args.map((arg) => bindNameExpr(arg, columns)) };
1489
+ case "nullif":
1490
+ return { k: "nullif", a: bindNameExpr(node.a, columns), b: bindNameExpr(node.b, columns) };
1491
+ case "cast":
1492
+ return {
1493
+ k: "cast",
1494
+ a: bindNameExpr(node.a, columns),
1495
+ type: node.type,
1496
+ scale: node.scale,
1497
+ maxLen: node.maxLen,
1498
+ };
1499
+ case "func":
1500
+ return { k: "func", fn: node.fn, args: node.args.map((arg) => bindNameExpr(arg, columns)) };
1501
+ case "subquery":
1502
+ throw new Error("subqueries must be resolved before binding; use the SQL executor or resolveSubqueries()");
1503
+ }
1504
+ }
1505
+ /** True when a WHERE clause constrains exactly one column with equality. */
1506
+ function equalityTarget(node, tableName) {
1507
+ if (node.k === "cmp" && node.op === "eq") {
1508
+ if (node.a.k === "id" && node.b.k === "lit") {
1509
+ return { column: node.a.name, value: node.b.value };
1510
+ }
1511
+ if (node.b.k === "id" && node.a.k === "lit") {
1512
+ return { column: node.b.name, value: node.a.value };
1513
+ }
1514
+ }
1515
+ if (node.k === "and") {
1516
+ return equalityTarget(node.a, tableName) ?? equalityTarget(node.b, tableName);
1517
+ }
1518
+ return null;
1519
+ }
1520
+ /** Unused placeholder to keep the signature easy to evolve. */
1521
+ function describeStatement(statement) {
1522
+ return statement.kind;
1523
+ }