Repository navigation
Expand file tree
/
Copy pathsql-lite.test.ts
More file actions
2677 lines (2426 loc) · 111 KB
/
Copy pathsql-lite.test.ts
File metadata and controls
2677 lines (2426 loc) · 111 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { createInputStream, ParseError, stripSpans } from "@parser-kit/core";
import { describe, expect, it } from "vitest";
import { type Stmt, sqlLexer, sqlLite } from "./index";
// --- helpers ---
const parse = (text: string) => stripSpans(sqlLite.parse(text)) as Record<string, any>[];
const firstStmt = (text: string) => parse(text)[0]!;
// Expressions are reached through a CHECK constraint, whose parenthesised body
// is a full scalar expression.
const exprOf = (src: string) => {
const [stmt] = parse(`CREATE TABLE t (c int CHECK (${src}));`);
return (stmt as any).items[0].constraints[0].expr;
};
const lex = (text: string) => {
const stream = sqlLexer.tokenize(createInputStream(text));
const out: { type: string; value: string }[] = [];
let tok = stream.next();
while (tok !== null) {
out.push({ type: tok.type, value: tok.value });
tok = stream.next();
}
return out;
};
const name = (...parts: string[]) => ({ kind: "name", parts });
const num = (value: number) => ({ kind: "number", value });
const str = (value: string) => ({ kind: "string", value });
const bin = (op: string, left: unknown, right: unknown) => ({ kind: "binary", op, left, right });
const star = (table: string[] | null = null) => ({ kind: "star", table });
const col = (expr: unknown, alias: string | null = null) => ({ expr, alias });
// A fully-defaulted SELECT node; spread overrides in for the fields under test.
const sel = (over: Record<string, unknown>) => ({
kind: "select",
with_: null,
recursive: false,
distinct: false,
columns: [],
from: null,
where: null,
groupBy: null,
having: null,
window: null,
orderBy: null,
limit: null,
offset: null,
locking: null,
...over,
});
const tableFrom = (name: string[], alias: string | null = null) => ({ kind: "table", name, alias });
// --- lexer ---
describe("SQL-lite lexer", () => {
it("folds unquoted identifiers and preserves quoted ones", () => {
expect(lex('Select FROM "Users"')).toEqual([
{ type: "ident", value: "select" },
{ type: "ident", value: "from" },
{ type: "qident", value: "Users" },
]);
});
it("decodes standard, E- and dollar-quoted strings", () => {
expect(lex("'it''s'")).toEqual([{ type: "string", value: "it's" }]);
expect(lex("E'a\\nb'")).toEqual([{ type: "string", value: "a\nb" }]);
expect(lex("$t$raw $x$ text$t$")).toEqual([{ type: "string", value: "raw $x$ text" }]);
});
it("falls the E prefix through to an identifier when no quote follows", () => {
expect(lex("end explain")).toEqual([
{ type: "ident", value: "end" },
{ type: "ident", value: "explain" },
]);
});
it("reads line comments and nested block comments as one token each", () => {
expect(lex("-- a comment\nx")).toEqual([
{ type: "comment", value: " a comment" },
{ type: "ident", value: "x" },
]);
const nested = lex("/* a /* b */ c */ x");
expect(nested).toHaveLength(2);
expect(nested[0]!.type).toBe("comment");
expect(nested[1]).toEqual({ type: "ident", value: "x" });
});
it("reads PG numbers: exponent, leading dot, hex, separators", () => {
expect(lex("1e5 .5 0xff 1_000")).toEqual([
{ type: "number", value: "1e5" },
{ type: "number", value: ".5" },
{ type: "number", value: "0xff" },
{ type: "number", value: "1000" },
]);
});
it("partitions operators from punctuation (:: casts next to || and @>)", () => {
expect(lex("x::int || tags @> other")).toEqual([
{ type: "ident", value: "x" },
{ type: "punc", value: "::" },
{ type: "ident", value: "int" },
{ type: "op", value: "||" },
{ type: "ident", value: "tags" },
{ type: "op", value: "@>" },
{ type: "ident", value: "other" },
]);
});
});
// --- statements ---
describe("SQL-lite statements", () => {
it("parses CREATE TABLE with column and table constraints", () => {
const stmt = firstStmt(
"CREATE TABLE users (\n" +
" id int PRIMARY KEY,\n" +
" email text NOT NULL,\n" +
" age int DEFAULT 0 CHECK (age >= 0),\n" +
" team_id int REFERENCES teams (id) ON DELETE CASCADE,\n" +
" UNIQUE (email)\n" +
");",
);
expect(stmt.kind).toBe("createTable");
expect(stmt.ifNotExists).toBe(false);
expect(stmt.name).toEqual(["users"]);
const items = stmt.items as any[];
expect(items.map((i) => i.kind)).toEqual(["column", "column", "column", "column", "unique"]);
expect(items[0]).toMatchObject({ name: "id", dataType: { name: "int", args: [], array: false } });
expect(items[0].constraints).toEqual([{ kind: "primaryKey" }]);
expect(items[1].constraints).toEqual([{ kind: "notNull" }]);
expect(items[2].constraints).toEqual([
{ kind: "default", expr: num(0) },
{ kind: "check", expr: bin(">=", name("age"), num(0)) },
]);
expect(items[3].constraints).toEqual([
{ kind: "references", table: ["teams"], columns: ["id"], onDelete: "cascade" },
]);
expect(items[4]).toEqual({ kind: "unique", name: null, columns: ["email"] });
});
it("parses parameterized and array types", () => {
const stmt = firstStmt("CREATE TABLE t (a varchar(10), b numeric(10, 2), c int[], d text[][]);");
const types = (stmt.items as any[]).map((i) => i.dataType);
expect(types).toEqual([
{ name: "varchar", args: [10], array: false },
{ name: "numeric", args: [10, 2], array: false },
{ name: "int", args: [], array: true },
{ name: "text", args: [], array: true },
]);
});
it("accepts IF NOT EXISTS and named table constraints", () => {
const stmt = firstStmt("CREATE TABLE IF NOT EXISTS app.users (id int, CONSTRAINT pk PRIMARY KEY (id));");
expect(stmt.ifNotExists).toBe(true);
expect(stmt.name).toEqual(["app", "users"]);
expect((stmt.items as any[])[1]).toEqual({ kind: "primaryKey", name: "pk", columns: ["id"] });
});
it("proves the keyword tier: unreserved words as names, reserved only quoted", () => {
const stmt = firstStmt('CREATE TABLE data ("select" text, type text, role varchar(10), comment text);');
expect(stmt.name).toEqual(["data"]);
expect((stmt.items as any[]).map((i) => i.name)).toEqual(["select", "type", "role", "comment"]);
});
it("rejects a bare reserved word as a name", () => {
expect(() => sqlLite.parse("CREATE TABLE t (select int);")).toThrow(/Expected a name but found "select"/);
});
it("parses CREATE [UNIQUE] INDEX with expressions and a partial WHERE", () => {
const plain = firstStmt("CREATE INDEX idx_email ON users (email);");
expect(plain).toMatchObject({ kind: "createIndex", unique: false, name: "idx_email", table: ["users"] });
expect((plain as any).columns).toEqual([name("email")]);
const partial = firstStmt("CREATE UNIQUE INDEX ON users (lower(email)) WHERE active;");
expect(partial).toMatchObject({ kind: "createIndex", unique: true, name: null });
expect((partial as any).columns).toEqual([{ kind: "call", name: "lower", args: [name("email")] }]);
expect((partial as any).where).toEqual(name("active"));
// The Phase 6 extras default off / absent on a plain index.
expect(plain).toMatchObject({ concurrently: false, ifNotExists: false, include: null });
});
it("parses CREATE INDEX CONCURRENTLY IF NOT EXISTS with INCLUDE", () => {
const idx = firstStmt("CREATE INDEX CONCURRENTLY IF NOT EXISTS idx ON users (email) INCLUDE (name, id);");
expect(idx).toMatchObject({
kind: "createIndex",
concurrently: true,
ifNotExists: true,
name: "idx",
table: ["users"],
include: ["name", "id"],
});
expect((idx as any).columns).toEqual([name("email")]);
});
it("parses CREATE TYPE ... AS ENUM", () => {
expect(firstStmt("CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');")).toEqual({
kind: "createType",
form: "enum",
name: ["mood"],
values: ["sad", "ok", "happy"],
});
});
it("parses DROP TABLE IF EXISTS with several names", () => {
expect(firstStmt("DROP TABLE IF EXISTS a, public.b;")).toEqual({
kind: "drop",
objectType: "table",
concurrently: false,
ifExists: true,
names: [["a"], ["public", "b"]],
behavior: null,
});
});
it("parses COMMENT ON ... IS with a dollar-quoted body", () => {
expect(firstStmt("COMMENT ON COLUMN users.email IS $q$primary contact$q$;")).toEqual({
kind: "comment",
objectType: "column",
name: ["users", "email"],
comment: "primary contact",
});
expect((firstStmt("COMMENT ON TABLE users IS NULL;") as any).comment).toBeNull();
});
});
// --- ALTER TABLE (peekAhead / phrase dispatch) ---
describe("SQL-lite ALTER TABLE", () => {
const action = (text: string) => (firstStmt(text) as any).action;
it("adds a column, with or without the COLUMN keyword", () => {
expect(action("ALTER TABLE t ADD COLUMN age int;")).toMatchObject({
kind: "addColumn",
column: { name: "age", dataType: { name: "int" } },
});
expect(action("ALTER TABLE t ADD email text NOT NULL;")).toMatchObject({
kind: "addColumn",
column: { name: "email", constraints: [{ kind: "notNull" }] },
});
});
it("drops a column", () => {
expect(action("ALTER TABLE t DROP COLUMN age;")).toEqual({ kind: "dropColumn", name: "age" });
expect(action("ALTER TABLE t DROP legacy;")).toEqual({ kind: "dropColumn", name: "legacy" });
});
it("adds named and bare constraints", () => {
expect(action("ALTER TABLE t ADD CONSTRAINT pk PRIMARY KEY (id);")).toEqual({
kind: "addConstraint",
name: "pk",
constraint: { kind: "primaryKey", name: null, columns: ["id"] },
});
expect(action("ALTER TABLE t ADD UNIQUE (email);")).toEqual({
kind: "addConstraint",
name: null,
constraint: { kind: "unique", name: null, columns: ["email"] },
});
});
it("alters a column default (phrase dispatch: SET vs DROP DEFAULT)", () => {
expect(action("ALTER TABLE t ALTER COLUMN status SET DEFAULT 'active';")).toEqual({
kind: "setDefault",
column: "status",
expr: str("active"),
});
expect(action("ALTER TABLE t ALTER COLUMN status DROP DEFAULT;")).toEqual({
kind: "dropDefault",
column: "status",
});
});
});
// --- Phase 6: richer ALTER TABLE actions ---
describe("SQL-lite ALTER TABLE (Phase 6 actions)", () => {
const action = (text: string) => (firstStmt(text) as any).action;
it("sets and drops NOT NULL", () => {
expect(action("ALTER TABLE t ALTER COLUMN email SET NOT NULL;")).toEqual({ kind: "setNotNull", column: "email" });
expect(action("ALTER TABLE t ALTER email DROP NOT NULL;")).toEqual({ kind: "dropNotNull", column: "email" });
});
it("changes a column type via SET DATA TYPE and the TYPE shorthand", () => {
expect(action("ALTER TABLE t ALTER COLUMN n SET DATA TYPE bigint;")).toMatchObject({
kind: "setDataType",
column: "n",
dataType: { name: "bigint" },
});
expect(action("ALTER TABLE t ALTER n TYPE numeric(10, 2);")).toMatchObject({
kind: "setDataType",
column: "n",
dataType: { name: "numeric", args: [10, 2] },
});
});
it("renames a column, a constraint, and the table", () => {
expect(action("ALTER TABLE t RENAME COLUMN old TO new;")).toEqual({ kind: "renameColumn", from: "old", to: "new" });
expect(action("ALTER TABLE t RENAME legacy TO current;")).toEqual({
kind: "renameColumn",
from: "legacy",
to: "current",
});
expect(action("ALTER TABLE t RENAME CONSTRAINT pk_old TO pk_new;")).toEqual({
kind: "renameConstraint",
from: "pk_old",
to: "pk_new",
});
expect(action("ALTER TABLE t RENAME TO t2;")).toEqual({ kind: "renameTable", to: "t2" });
});
it("changes owner and replica identity", () => {
expect(action("ALTER TABLE t OWNER TO admin;")).toEqual({ kind: "ownerTo", owner: "admin" });
expect(action("ALTER TABLE t REPLICA IDENTITY FULL;")).toEqual({
kind: "replicaIdentity",
mode: "full",
index: null,
});
expect(action("ALTER TABLE t REPLICA IDENTITY USING INDEX t_pkey;")).toEqual({
kind: "replicaIdentity",
mode: "usingIndex",
index: "t_pkey",
});
expect(action("ALTER TABLE t REPLICA IDENTITY DEFAULT;")).toMatchObject({
kind: "replicaIdentity",
mode: "default",
});
});
it("rejects an unknown ALTER TABLE action", () => {
expect(() => sqlLite.parse("ALTER TABLE t frobnicate;")).toThrow(
/Expected "add", "drop", "alter", "rename", "owner" or "replica"/,
);
});
});
// --- Phase 6: DROP family & TRUNCATE ---
describe("SQL-lite DROP family & TRUNCATE", () => {
it("drops non-table objects with CASCADE / RESTRICT", () => {
expect(firstStmt("DROP VIEW v;")).toEqual({
kind: "drop",
objectType: "view",
concurrently: false,
ifExists: false,
names: [["v"]],
behavior: null,
});
expect(firstStmt("DROP SEQUENCE IF EXISTS s CASCADE;")).toEqual({
kind: "drop",
objectType: "sequence",
concurrently: false,
ifExists: true,
names: [["s"]],
behavior: "cascade",
});
expect(firstStmt("DROP TYPE mood RESTRICT;")).toMatchObject({ objectType: "type", behavior: "restrict" });
expect(firstStmt("DROP SCHEMA a, b;")).toMatchObject({ objectType: "schema", names: [["a"], ["b"]] });
});
it("drops an index CONCURRENTLY", () => {
expect(firstStmt("DROP INDEX CONCURRENTLY IF EXISTS idx;")).toEqual({
kind: "drop",
objectType: "index",
concurrently: true,
ifExists: true,
names: [["idx"]],
behavior: null,
});
});
it("truncates one or more tables with identity and behavior", () => {
expect(firstStmt("TRUNCATE t;")).toEqual({
kind: "truncate",
names: [["t"]],
identity: null,
behavior: null,
});
expect(firstStmt("TRUNCATE TABLE a, b RESTART IDENTITY CASCADE;")).toEqual({
kind: "truncate",
names: [["a"], ["b"]],
identity: "restart",
behavior: "cascade",
});
expect(firstStmt("TRUNCATE public.t CONTINUE IDENTITY;")).toMatchObject({
names: [["public", "t"]],
identity: "continue",
});
});
});
// --- Phase 7: more CREATE objects ---
describe("SQL-lite CREATE VIEW / MATERIALIZED VIEW", () => {
it("parses a plain view whose body reuses the query rule", () => {
expect(firstStmt("CREATE VIEW active AS SELECT id FROM users WHERE active;")).toEqual({
kind: "createView",
materialized: false,
orReplace: false,
ifNotExists: false,
name: ["active"],
columns: null,
query: sel({ columns: [col(name("id"))], from: [tableFrom(["users"])], where: name("active") }),
withData: null,
});
});
it("parses OR REPLACE with an output column list", () => {
expect(firstStmt("CREATE OR REPLACE VIEW v (a, b) AS SELECT 1, 2;")).toMatchObject({
kind: "createView",
materialized: false,
orReplace: true,
name: ["v"],
columns: ["a", "b"],
withData: null,
});
});
it("parses MATERIALIZED VIEW with IF NOT EXISTS and WITH [NO] DATA", () => {
expect(firstStmt("CREATE MATERIALIZED VIEW IF NOT EXISTS mv AS SELECT * FROM t WITH NO DATA;")).toMatchObject({
kind: "createView",
materialized: true,
ifNotExists: true,
name: ["mv"],
withData: false,
});
expect(firstStmt("CREATE MATERIALIZED VIEW mv AS SELECT 1 WITH DATA;")).toMatchObject({
materialized: true,
withData: true,
});
});
it("rejects OR REPLACE before a non-replaceable object", () => {
expect(() => sqlLite.parse("CREATE OR REPLACE TABLE t (id int);")).toThrow(
/Expected "view", "materialized", "function", "aggregate" or "trigger"/,
);
});
});
describe("SQL-lite CREATE TABLE AS", () => {
it("parses CREATE TABLE AS SELECT", () => {
expect(firstStmt("CREATE TABLE snap AS SELECT id, name FROM users;")).toEqual({
kind: "createTableAs",
ifNotExists: false,
name: ["snap"],
columns: null,
query: sel({ columns: [col(name("id")), col(name("name"))], from: [tableFrom(["users"])] }),
withData: null,
});
});
it("parses a column list, IF NOT EXISTS and WITH NO DATA", () => {
expect(firstStmt("CREATE TABLE IF NOT EXISTS t (a, b) AS SELECT 1, 2 WITH NO DATA;")).toMatchObject({
kind: "createTableAs",
ifNotExists: true,
name: ["t"],
columns: ["a", "b"],
withData: false,
});
});
it("still parses an ordinary CREATE TABLE (the CTAS column list backtracks)", () => {
expect(firstStmt("CREATE TABLE t (id int, name text);")).toMatchObject({
kind: "createTable",
name: ["t"],
});
});
});
describe("SQL-lite CREATE TYPE composite / range", () => {
it("parses a composite type", () => {
expect(firstStmt("CREATE TYPE point AS (x float8, y float8);")).toEqual({
kind: "createType",
form: "composite",
name: ["point"],
attributes: [
{ name: "x", type: { name: "float8", args: [], array: false } },
{ name: "y", type: { name: "float8", args: [], array: false } },
],
});
});
it("parses a range type option list", () => {
expect(firstStmt("CREATE TYPE floatrange AS RANGE (SUBTYPE = float8, SUBTYPE_OPCLASS = float8_ops);")).toEqual({
kind: "createType",
form: "range",
name: ["floatrange"],
options: [
{ name: "subtype", value: "float8" },
{ name: "subtype_opclass", value: "float8_ops" },
],
});
});
});
describe("SQL-lite CREATE SEQUENCE", () => {
it("parses a sequence with a full option list", () => {
const stmt = firstStmt(
"CREATE SEQUENCE IF NOT EXISTS s AS bigint INCREMENT BY 2 MINVALUE 1 NO MAXVALUE START WITH 10 CACHE 5 CYCLE OWNED BY t.id;",
);
expect(stmt).toMatchObject({ kind: "createSequence", ifNotExists: true, name: ["s"] });
expect((stmt as any).options).toEqual([
{ kind: "as", type: { name: "bigint", args: [], array: false } },
{ kind: "increment", value: num(2) },
{ kind: "minValue", value: num(1) },
{ kind: "maxValue", value: null },
{ kind: "start", value: num(10) },
{ kind: "cache", value: num(5) },
{ kind: "cycle", value: true },
{ kind: "ownedBy", owner: ["t", "id"] },
]);
});
it("parses NO CYCLE, OWNED BY NONE and a signed MINVALUE", () => {
const stmt = firstStmt("CREATE SEQUENCE s MINVALUE -100 NO CYCLE OWNED BY NONE;");
expect((stmt as any).options).toEqual([
{ kind: "minValue", value: { kind: "unary", op: "-", operand: num(100) } },
{ kind: "cycle", value: false },
{ kind: "ownedBy", owner: null },
]);
});
});
describe("SQL-lite CREATE DOMAIN", () => {
it("parses a domain with DEFAULT and a named CHECK", () => {
const stmt = firstStmt(
"CREATE DOMAIN us_postal AS text NOT NULL DEFAULT '00000' CONSTRAINT fmt CHECK (VALUE ~ '^[0-9]{5}$');",
);
expect(stmt).toMatchObject({ kind: "createDomain", name: ["us_postal"], dataType: { name: "text" } });
expect((stmt as any).constraints).toEqual([
{ kind: "notNull", name: null },
{ kind: "default", expr: str("00000") },
{ kind: "check", name: "fmt", expr: bin("~", name("value"), str("^[0-9]{5}$")) },
]);
});
it("parses a domain without the optional AS", () => {
expect(firstStmt("CREATE DOMAIN positive int CHECK (VALUE > 0);")).toMatchObject({
kind: "createDomain",
name: ["positive"],
dataType: { name: "int" },
});
});
});
// --- Phase 8: functions / aggregates / triggers ---
// A ColType literal (the shape typeRef yields once spans are stripped).
const ct = (name: string, over: Record<string, unknown> = {}) => ({ name, args: [], array: false, ...over });
describe("SQL-lite CREATE FUNCTION", () => {
it("parses OR REPLACE, arg defaults, RETURNS and an opaque dollar body", () => {
const stmt = firstStmt(
"CREATE OR REPLACE FUNCTION add(a integer, b integer DEFAULT 0) RETURNS integer LANGUAGE sql IMMUTABLE STRICT AS $$SELECT a + b$$;",
);
expect(stmt).toEqual({
kind: "createFunction",
orReplace: true,
name: ["add"],
args: [
{ mode: null, name: "a", type: ct("integer"), defaultValue: null },
{ mode: null, name: "b", type: ct("integer"), defaultValue: num(0) },
],
returns: { kind: "type", setof: false, type: ct("integer") },
options: [
{ kind: "language", name: "sql" },
{ kind: "volatility", value: "immutable" },
{ kind: "strictness", value: "strict" },
// The body is one opaque string token — `a + b` is NOT parsed.
{ kind: "as", parts: ["SELECT a + b"] },
],
});
});
it("parses argument modes and an array type", () => {
const stmt = firstStmt(
"CREATE FUNCTION f(IN x integer, OUT y text, VARIADIC vals integer[]) RETURNS void LANGUAGE plpgsql AS $body$BEGIN END$body$;",
);
expect((stmt as any).args).toEqual([
{ mode: "in", name: "x", type: ct("integer"), defaultValue: null },
{ mode: "out", name: "y", type: ct("text"), defaultValue: null },
{ mode: "variadic", name: "vals", type: ct("integer", { array: true }), defaultValue: null },
]);
expect((stmt as any).options).toEqual([
{ kind: "language", name: "plpgsql" },
{ kind: "as", parts: ["BEGIN END"] },
]);
});
it("parses RETURNS TABLE and an unnamed-argument type", () => {
const stmt = firstStmt(
"CREATE FUNCTION top_users(numeric(10, 2)) RETURNS TABLE(id integer, label text) LANGUAGE sql AS $$SELECT 1$$;",
);
expect((stmt as any).args).toEqual([
{ mode: null, name: null, type: ct("numeric", { args: [10, 2] }), defaultValue: null },
]);
expect((stmt as any).returns).toEqual({
kind: "table",
columns: [
{ name: "id", type: ct("integer") },
{ name: "label", type: ct("text") },
],
});
});
it("parses SECURITY / SET / COST / PARALLEL characteristics", () => {
const stmt = firstStmt(
"CREATE FUNCTION g() RETURNS int LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public COST 100 PARALLEL SAFE AS $$SELECT 1$$;",
);
expect((stmt as any).options).toEqual([
{ kind: "language", name: "sql" },
{ kind: "security", external: false, definer: true },
{ kind: "set", parameter: "search_path", value: { kind: "list", values: [name("pg_catalog"), name("public")] } },
{ kind: "cost", value: num(100) },
{ kind: "parallel", value: "safe" },
{ kind: "as", parts: ["SELECT 1"] },
]);
});
it("parses a C-language two-part AS body and RETURNS NULL ON NULL INPUT", () => {
const stmt = firstStmt(
"CREATE FUNCTION c_fn() RETURNS int LANGUAGE c RETURNS NULL ON NULL INPUT AS 'obj_file', 'link_sym';",
);
expect((stmt as any).options).toEqual([
{ kind: "language", name: "c" },
{ kind: "strictness", value: "returnsNullOnNullInput" },
{ kind: "as", parts: ["obj_file", "link_sym"] },
]);
});
});
describe("SQL-lite CREATE AGGREGATE", () => {
it("parses the modern signature + definition-list form", () => {
const stmt = firstStmt("CREATE AGGREGATE sum_agg(numeric) (SFUNC = numeric_add, STYPE = numeric, INITCOND = '0');");
expect(stmt).toEqual({
kind: "createAggregate",
orReplace: false,
name: ["sum_agg"],
star: false,
args: [{ mode: null, name: null, type: ct("numeric"), defaultValue: null }],
options: [
{ name: "sfunc", value: { kind: "type", type: ct("numeric_add") } },
{ name: "stype", value: { kind: "type", type: ct("numeric") } },
{ name: "initcond", value: { kind: "literal", expr: str("0") } },
],
});
});
it("parses the legacy single-paren form", () => {
const stmt = firstStmt("CREATE AGGREGATE avg_legacy (BASETYPE = numeric, SFUNC = avg_acc, STYPE = internal);");
expect(stmt).toMatchObject({ kind: "createAggregate", star: false, args: [] });
expect((stmt as any).options).toEqual([
{ name: "basetype", value: { kind: "type", type: ct("numeric") } },
{ name: "sfunc", value: { kind: "type", type: ct("avg_acc") } },
{ name: "stype", value: { kind: "type", type: ct("internal") } },
]);
});
it("parses a (*) signature", () => {
const stmt = firstStmt("CREATE AGGREGATE my_count(*) (SFUNC = int8inc, STYPE = int8);");
expect(stmt).toMatchObject({ kind: "createAggregate", name: ["my_count"], star: true, args: [] });
});
});
describe("SQL-lite CREATE TRIGGER", () => {
it("parses timing, OR-joined events, UPDATE OF cols, WHEN and EXECUTE FUNCTION", () => {
const stmt = firstStmt(
"CREATE TRIGGER audit AFTER INSERT OR UPDATE OF a, b ON accounts FOR EACH ROW WHEN (new.active) EXECUTE FUNCTION log_change(1, 'x');",
);
expect(stmt).toEqual({
kind: "createTrigger",
orReplace: false,
name: "audit",
timing: "after",
events: [
{ event: "insert", columns: null },
{ event: "update", columns: ["a", "b"] },
],
table: ["accounts"],
forEach: "row",
when: name("new", "active"),
execute: { routine: "function", name: ["log_change"], args: [num(1), str("x")] },
});
});
it("parses OR REPLACE, INSTEAD OF and EXECUTE PROCEDURE with no args", () => {
const stmt = firstStmt(
"CREATE OR REPLACE TRIGGER v_ins INSTEAD OF DELETE ON myview FOR EACH ROW EXECUTE PROCEDURE do_delete();",
);
expect(stmt).toEqual({
kind: "createTrigger",
orReplace: true,
name: "v_ins",
timing: "insteadOf",
events: [{ event: "delete", columns: null }],
table: ["myview"],
forEach: "row",
when: null,
execute: { routine: "procedure", name: ["do_delete"], args: [] },
});
});
it("rejects a trigger without a timing keyword", () => {
expect(() => sqlLite.parse("CREATE TRIGGER t INSERT ON x EXECUTE FUNCTION f();")).toThrow(
/Expected "before", "after" or "instead"/,
);
});
});
// --- expressions ---
describe("SQL-lite expressions", () => {
it("applies arithmetic precedence and concatenation", () => {
expect(exprOf("1 + 2 * 3")).toEqual(bin("+", num(1), bin("*", num(2), num(3))));
expect(exprOf("(1 + 2) * 3")).toEqual(bin("*", bin("+", num(1), num(2)), num(3)));
expect(exprOf("a || b || c")).toEqual(bin("||", bin("||", name("a"), name("b")), name("c")));
});
it("parses the containment operator and casts", () => {
expect(exprOf("tags @> other")).toEqual(bin("@>", name("tags"), name("other")));
expect(exprOf("x::int")).toEqual({ kind: "cast", expr: name("x"), type: { name: "int", args: [], array: false } });
expect(exprOf("'123'::int::text")).toMatchObject({ kind: "cast", type: { name: "text" }, expr: { kind: "cast" } });
});
it("binds unary minus and NOT", () => {
expect(exprOf("-a * b")).toEqual(bin("*", { kind: "unary", op: "-", operand: name("a") }, name("b")));
expect(exprOf("NOT a")).toEqual({ kind: "unary", op: "not", operand: name("a") });
});
it("orders keyword logical operators below comparisons", () => {
expect(exprOf("a = 1 AND b = 2 OR c = 3")).toEqual(
bin("or", bin("and", bin("=", name("a"), num(1)), bin("=", name("b"), num(2))), bin("=", name("c"), num(3))),
);
});
it("rejects chained non-associative comparisons", () => {
expect(() => sqlLite.parse("CREATE TABLE t (c int CHECK (a < b < c));")).toThrow(/non-associative/);
// The parenthesised form re-enters at bp 0 and parses.
expect(exprOf("(a < b) = c")).toEqual(bin("=", bin("<", name("a"), name("b")), name("c")));
});
it("parses IS [NOT] NULL, [NOT] LIKE/ILIKE, BETWEEN and IN", () => {
expect(exprOf("a IS NULL")).toEqual({ kind: "is", expr: name("a"), negated: false });
expect(exprOf("a IS NOT NULL")).toEqual({ kind: "is", expr: name("a"), negated: true });
expect(exprOf("name LIKE 'a%'")).toEqual({
kind: "like",
expr: name("name"),
pattern: str("a%"),
negated: false,
ci: false,
});
expect(exprOf("name NOT ILIKE 'a%'")).toEqual({
kind: "like",
expr: name("name"),
pattern: str("a%"),
negated: true,
ci: true,
});
expect(exprOf("age BETWEEN 1 AND 10")).toEqual({
kind: "between",
expr: name("age"),
lo: num(1),
hi: num(10),
negated: false,
});
expect(exprOf("age NOT BETWEEN 1 AND 10")).toMatchObject({ kind: "between", negated: true });
expect(exprOf("id IN (1, 2, 3)")).toEqual({
kind: "in",
expr: name("id"),
list: [num(1), num(2), num(3)],
negated: false,
});
expect(exprOf("id NOT IN (1, 2)")).toMatchObject({ kind: "in", negated: true });
});
it("parses qualified names and function calls", () => {
expect(exprOf("schema.tbl.col")).toEqual(name("schema", "tbl", "col"));
expect(exprOf("coalesce(a, 0)")).toEqual({ kind: "call", name: "coalesce", args: [name("a"), num(0)] });
expect(exprOf("now()")).toEqual({ kind: "call", name: "now", args: [] });
});
});
// --- expression operators (Phase 1) ---
describe("SQL-lite expression operators", () => {
it("lexes JSON / regex / full-text operators as single op tokens", () => {
const toks = lex("~* !~* #- ->> #>> ?| ?& <@ @@ -> #>");
expect(toks.every((t) => t.type === "op")).toBe(true);
expect(toks.map((t) => t.value)).toEqual(["~*", "!~*", "#-", "->>", "#>>", "?|", "?&", "<@", "@@", "->", "#>"]);
});
it("parses JSON / regex / full-text operators at the bp-12 tier", () => {
expect(exprOf("data -> 'k'")).toEqual(bin("->", name("data"), str("k")));
// Chained JSON accessors nest left-associatively.
expect(exprOf("a -> 'k' ->> 'j'")).toEqual(bin("->>", bin("->", name("a"), str("k")), str("j")));
expect(exprOf("meta #- '{x}'")).toEqual(bin("#-", name("meta"), str("{x}")));
expect(exprOf("col ~ 'a.*'")).toEqual(bin("~", name("col"), str("a.*")));
expect(exprOf("col !~* 'a'")).toEqual(bin("!~*", name("col"), str("a")));
expect(exprOf("doc @@ 'query'")).toEqual(bin("@@", name("doc"), str("query")));
expect(exprOf("tags ?& other")).toEqual(bin("?&", name("tags"), name("other")));
// bp-12 binds tighter than a comparison (bp 9): (a -> 'k') = 'v'.
expect(exprOf("a -> 'k' = 'v'")).toEqual(bin("=", bin("->", name("a"), str("k")), str("v")));
});
it("parses IS [NOT] DISTINCT FROM and IS [NOT] TRUE/FALSE/UNKNOWN", () => {
expect(exprOf("a IS DISTINCT FROM b")).toEqual({
kind: "isDistinct",
expr: name("a"),
from: name("b"),
negated: false,
});
expect(exprOf("a IS NOT DISTINCT FROM b")).toMatchObject({ kind: "isDistinct", negated: true });
expect(exprOf("a IS TRUE")).toEqual({ kind: "isTest", expr: name("a"), test: "true", negated: false });
expect(exprOf("a IS NOT FALSE")).toEqual({ kind: "isTest", expr: name("a"), test: "false", negated: true });
expect(exprOf("a IS UNKNOWN")).toEqual({ kind: "isTest", expr: name("a"), test: "unknown", negated: false });
// The plain IS [NOT] NULL node is untouched.
expect(exprOf("a IS NULL")).toEqual({ kind: "is", expr: name("a"), negated: false });
// IS binds tighter than AND: (a IS DISTINCT FROM b) AND c.
expect(exprOf("a IS DISTINCT FROM b AND c")).toEqual(
bin("and", { kind: "isDistinct", expr: name("a"), from: name("b"), negated: false }, name("c")),
);
});
it("parses LIKE ... ESCAPE and [NOT] SIMILAR TO", () => {
expect(exprOf("name LIKE 'a%' ESCAPE '!'")).toEqual({
kind: "like",
expr: name("name"),
pattern: str("a%"),
negated: false,
ci: false,
escape: str("!"),
});
// No ESCAPE → the key is absent (existing LIKE shape is preserved).
expect(exprOf("name LIKE 'a%'")).toEqual({
kind: "like",
expr: name("name"),
pattern: str("a%"),
negated: false,
ci: false,
});
expect(exprOf("name SIMILAR TO 'a%'")).toEqual({
kind: "similarTo",
expr: name("name"),
pattern: str("a%"),
negated: false,
});
expect(exprOf("name NOT SIMILAR TO 'a%' ESCAPE '/'")).toEqual({
kind: "similarTo",
expr: name("name"),
pattern: str("a%"),
negated: true,
escape: str("/"),
});
});
it("parses <cmp> ANY / ALL / SOME over an array or subquery", () => {
expect(exprOf("x = ANY (arr)")).toEqual({
kind: "anyAll",
op: "=",
quantifier: "any",
left: name("x"),
right: name("arr"),
});
expect(exprOf("x < ALL (arr)")).toMatchObject({ kind: "anyAll", op: "<", quantifier: "all" });
expect(exprOf("x = SOME (arr)")).toMatchObject({ kind: "anyAll", quantifier: "some" });
// A subquery RHS produces the scalar-subquery node.
const w = (firstStmt("SELECT 1 FROM t WHERE x = ANY (SELECT id FROM u);") as any).where;
expect(w).toEqual({
kind: "anyAll",
op: "=",
quantifier: "any",
left: name("x"),
right: { kind: "subquery", query: sel({ columns: [col(name("id"))], from: [tableFrom(["u"])] }) },
});
});
it("reports the NOT dispatcher's extended keyword set", () => {
expect(() => sqlLite.parse("CREATE TABLE t (c int CHECK (a NOT frobnicate b));")).toThrow(
/Expected "like", "ilike", "similar", "between" or "in"/,
);
});
});
// --- arithmetic, bitwise and jsonpath operators ---
describe("SQL-lite arithmetic, bitwise and jsonpath operators", () => {
const un = (op: string, operand: unknown) => ({ kind: "unary", op, operand });
const cast = (expr: unknown, type: string) => ({ kind: "cast", expr, type: ct(type) });
it("lexes the arithmetic, bitwise and jsonpath operators as single op tokens", () => {
const toks = lex("% ^ & | # << >> @?");
expect(toks.every((t) => t.type === "op")).toBe(true);
expect(toks.map((t) => t.value)).toEqual(["%", "^", "&", "|", "#", "<<", ">>", "@?"]);
});
it("parses modulo at the multiplicative tier", () => {
expect(exprOf("a % b")).toEqual(bin("%", name("a"), name("b")));
// bp 14, same tier as `*` and `/`: left-associative and above `+`.
expect(exprOf("a % b * c")).toEqual(bin("*", bin("%", name("a"), name("b")), name("c")));
expect(exprOf("a + b % c")).toEqual(bin("+", name("a"), bin("%", name("b"), name("c"))));
});
it("parses unary plus alongside unary minus", () => {
expect(exprOf("+a")).toEqual(un("+", name("a")));
// The operator is kept verbatim rather than folded away.
expect(exprOf("+1")).toEqual(un("+", num(1)));
// bp 16, above `*`: `(+a) * b`, not `+(a * b)`. (It is *not* above every
// arithmetic tier — `^` at bp 17 is tighter still; see the next test.)
expect(exprOf("+a * b")).toEqual(bin("*", un("+", name("a")), name("b")));
// A sign on the right-hand side of a binary operator still reaches the prefix.
expect(exprOf("a * +b")).toEqual(bin("*", name("a"), un("+", name("b"))));
// Unchanged: unary minus keeps its own shape and precedence.
expect(exprOf("-a * b")).toEqual(bin("*", un("-", name("a")), name("b")));
});
it("parses exponentiation tighter than the unary sign, left-associatively", () => {
expect(exprOf("a ^ b")).toEqual(bin("^", name("a"), name("b")));
expect(exprOf("a ^ b ^ c")).toEqual(bin("^", bin("^", name("a"), name("b")), name("c")));
// bp 17 is above the unary sign (16), so the sign wraps the whole power.
expect(exprOf("-2 ^ 2")).toEqual(un("-", bin("^", num(2), num(2))));
expect(exprOf("+2 ^ 2")).toEqual(un("+", bin("^", num(2), num(2))));
// ... and below the bp-18 postfixes. The right operand is what discriminates:
// a cast there binds to that operand, not to the power. (`a::int ^ 2` is the
// same tree at any bp, since the postfix loop runs before the infix scan.)
expect(exprOf("a ^ b::int")).toEqual(bin("^", name("a"), cast(name("b"), "int")));
expect(exprOf("a::int ^ 2")).toEqual(bin("^", cast(name("a"), "int"), num(2)));
// ... and above `*`, so the power is the multiplicand.
expect(exprOf("2 ^ 3 * 4")).toEqual(bin("*", bin("^", num(2), num(3)), num(4)));
});
it("nests a signed right operand of ^ under the sign, not the power", () => {
// The tail of putting `^` above the unary sign: a prefix parses its operand
// at its own bp (16), which is below `^`'s 17, so the sign on the right
// swallows the rest of the chain instead of the chain nesting left.
expect(exprOf("2 ^ -3 ^ 4")).toEqual(bin("^", num(2), un("-", bin("^", num(3), num(4)))));
// Without a sign the same chain is plain left-associative.
expect(exprOf("2 ^ 3 ^ 4")).toEqual(bin("^", bin("^", num(2), num(3)), num(4)));
});
it("parses the bitwise and shift operators at the bp-12 tier", () => {
expect(exprOf("a & b")).toEqual(bin("&", name("a"), name("b")));
expect(exprOf("a | b")).toEqual(bin("|", name("a"), name("b")));
expect(exprOf("a # b")).toEqual(bin("#", name("a"), name("b")));
expect(exprOf("a << 2")).toEqual(bin("<<", name("a"), num(2)));
expect(exprOf("a >> 2")).toEqual(bin(">>", name("a"), num(2)));
// Left-associative within the tier.
expect(exprOf("a | b | c")).toEqual(bin("|", bin("|", name("a"), name("b")), name("c")));
// bp 12 is below `+` (13) and above the bp-9 comparisons.
expect(exprOf("a | b + c")).toEqual(bin("|", name("a"), bin("+", name("b"), name("c"))));
expect(exprOf("a & b = c")).toEqual(bin("=", bin("&", name("a"), name("b")), name("c")));
});
it("parses the jsonpath existence operator", () => {
expect(exprOf("data @? '$.x'")).toEqual(bin("@?", name("data"), str("$.x")));
// Same tier as `@@`, so a comparison still takes the whole match as its LHS.
expect(exprOf("data @? '$.x' = b")).toEqual(bin("=", bin("@?", name("data"), str("$.x")), name("b")));
});
it("keeps the longer operators that share a lead character intact", () => {
// `#` is bitwise XOR, but `#-` / `#>` / `#>>` are their own tokens: maximal
// munch in the lexer, so adding `#` cannot split them.
expect(exprOf("meta #- '{x}'")).toEqual(bin("#-", name("meta"), str("{x}")));
expect(exprOf("meta #> '{x}'")).toEqual(bin("#>", name("meta"), str("{x}")));
expect(exprOf("meta #>> '{x}'")).toEqual(bin("#>>", name("meta"), str("{x}")));
// `|` is bitwise OR, `||` is still concatenation, `?|` still key-existence.
expect(exprOf("a || b")).toEqual(bin("||", name("a"), name("b")));
expect(exprOf("tags ?| other")).toEqual(bin("?|", name("tags"), name("other")));
// `@?` is jsonpath existence, `@>` containment and `@@` full-text match.
expect(exprOf("a @> b")).toEqual(bin("@>", name("a"), name("b")));
expect(exprOf("doc @@ 'q'")).toEqual(bin("@@", name("doc"), str("q")));
});
it("leaves the lexer's trailing-sign rule to decide where an unspaced sign goes", () => {
// The operator reader trims a trailing `+`/`-` from a run unless the run
// holds a "strong" character, so `<<` and `>>` let the sign go while
// `% & | ^` absorb it into one unknown operator — PG's own rule, now
// reachable from both sides because the sign is a prefix here.
expect(exprOf("a << -1")).toEqual(bin("<<", name("a"), un("-", num(1))));
expect(exprOf("a >> -1")).toEqual(bin(">>", name("a"), un("-", num(1))));
// Spaced, the sign is its own token and the power parses.
expect(exprOf("2 ^ -2")).toEqual(bin("^", num(2), un("-", num(2))));
// Unspaced, `^-` lexes as one operator that no group claims.
expect(() => sqlLite.parse("SELECT 2^-2 FROM t;")).toThrow(/but found "\^-"/);
// `++` is trimmed to a single `+`, so a doubled sign reaches the prefix.
expect(exprOf("a ++ b")).toEqual(bin("+", name("a"), un("+", name("b"))));
});
it("shares the new operators with the b-expression", () => {
// POSITION's first operand is parsed by the b-expression, which reuses
// `arithInfix` verbatim — so a widened group (`%` joining `*` and `/`) and
// a brand-new one (`^`) both reach it without a second table.
const posOf = (src: string) => (firstStmt(`SELECT position(${src}) FROM t;`) as any).columns[0].expr;
expect(posOf("a % 2 IN s")).toEqual({
kind: "position",
substring: bin("%", name("a"), num(2)),
string: name("s"),
});
expect(posOf("a ^ 2 IN s")).toEqual({
kind: "position",