Repository navigation
Expand file tree
/
Copy pathparser_ir_ddl_test.go
More file actions
1648 lines (1530 loc) · 53.4 KB
/
Copy pathparser_ir_ddl_test.go
File metadata and controls
1648 lines (1530 loc) · 53.4 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
// parser_ir_ddl_test.go exercises DDL statement parsing at the IR level.
package postgresparser
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestIR_DDL_DropTable(t *testing.T) {
tests := []struct {
name string
sql string
wantActions int
wantType DDLActionType
wantObject string
wantSchema string
wantFlags []string
wantTables int
}{
{
name: "simple",
sql: "DROP TABLE users",
wantActions: 1,
wantType: DDLDropTable,
wantObject: "users",
wantTables: 1,
},
{
name: "IF EXISTS",
sql: "DROP TABLE IF EXISTS users",
wantActions: 1,
wantType: DDLDropTable,
wantObject: "users",
wantFlags: []string{"IF_EXISTS"},
wantTables: 1,
},
{
name: "CASCADE",
sql: "DROP TABLE users CASCADE",
wantActions: 1,
wantType: DDLDropTable,
wantObject: "users",
wantFlags: []string{"CASCADE"},
wantTables: 1,
},
{
name: "schema-qualified",
sql: "DROP TABLE myschema.users",
wantActions: 1,
wantType: DDLDropTable,
wantObject: "users",
wantSchema: "myschema",
wantTables: 1,
},
{
name: "multiple tables",
sql: "DROP TABLE users, orders, products",
wantActions: 3,
wantType: DDLDropTable,
wantTables: 3,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
ir := parseAssertNoError(t, tc.sql)
assert.Equal(t, QueryCommandDDL, ir.Command, "expected DDL command")
require.Len(t, ir.DDLActions, tc.wantActions, "action count mismatch")
act := ir.DDLActions[0]
assert.Equal(t, tc.wantType, act.Type, "action type mismatch")
if tc.wantObject != "" {
assert.Equal(t, tc.wantObject, act.ObjectName, "object name mismatch")
}
if tc.wantSchema != "" {
assert.Equal(t, tc.wantSchema, act.Schema, "schema mismatch")
}
assert.Subset(t, act.Flags, tc.wantFlags, "flags mismatch")
assert.Len(t, ir.Tables, tc.wantTables, "tables count mismatch")
})
}
}
func TestIR_DDL_DropIndex(t *testing.T) {
tests := []struct {
name string
sql string
wantActions int
wantObject string
wantSchema string
wantFlags []string
}{
{
name: "simple",
sql: "DROP INDEX idx_users_email",
wantActions: 1,
wantObject: "idx_users_email",
},
{
name: "CONCURRENTLY",
sql: "DROP INDEX CONCURRENTLY idx_users_email",
wantActions: 1,
wantObject: "idx_users_email",
wantFlags: []string{"CONCURRENTLY"},
},
{
name: "IF EXISTS",
sql: "DROP INDEX IF EXISTS idx_users_email",
wantActions: 1,
wantObject: "idx_users_email",
wantFlags: []string{"IF_EXISTS"},
},
{
name: "schema-qualified",
sql: "DROP INDEX public.idx_users_email",
wantActions: 1,
wantObject: "idx_users_email",
wantSchema: "public",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
ir := parseAssertNoError(t, tc.sql)
assert.Equal(t, QueryCommandDDL, ir.Command, "expected DDL command")
require.Len(t, ir.DDLActions, tc.wantActions, "action count mismatch")
act := ir.DDLActions[0]
assert.Equal(t, DDLDropIndex, act.Type, "expected DROP_INDEX")
assert.Equal(t, tc.wantObject, act.ObjectName, "object name mismatch")
if tc.wantSchema != "" {
assert.Equal(t, tc.wantSchema, act.Schema, "schema mismatch")
}
assert.Subset(t, act.Flags, tc.wantFlags, "flags mismatch")
})
}
}
func TestIR_DDL_CreateIndex(t *testing.T) {
tests := []struct {
name string
sql string
wantObject string
wantSchema string
wantCols int
wantFlags []string
wantIdx string
wantTables int
}{
{
name: "simple",
sql: "CREATE INDEX idx_email ON users (email)",
wantObject: "idx_email",
wantCols: 1,
wantTables: 1,
},
{
name: "CONCURRENTLY",
sql: "CREATE INDEX CONCURRENTLY idx_email ON users (email)",
wantObject: "idx_email",
wantCols: 1,
wantFlags: []string{"CONCURRENTLY"},
wantTables: 1,
},
{
name: "UNIQUE",
sql: "CREATE UNIQUE INDEX idx_email ON users (email)",
wantObject: "idx_email",
wantCols: 1,
wantFlags: []string{"UNIQUE"},
wantTables: 1,
},
{
name: "USING gin",
sql: "CREATE INDEX idx_tags ON posts USING gin (tags)",
wantObject: "idx_tags",
wantCols: 1,
wantIdx: "gin",
wantTables: 1,
},
{
name: "USING btree",
sql: "CREATE INDEX idx_name ON users USING btree (name)",
wantObject: "idx_name",
wantCols: 1,
wantIdx: "btree",
wantTables: 1,
},
{
name: "multi-column",
sql: "CREATE INDEX idx_compound ON users (last_name, first_name)",
wantObject: "idx_compound",
wantCols: 2,
wantTables: 1,
},
{
name: "IF NOT EXISTS",
sql: "CREATE INDEX IF NOT EXISTS idx_email ON users (email)",
wantObject: "idx_email",
wantCols: 1,
wantFlags: []string{"IF_NOT_EXISTS"},
wantTables: 1,
},
{
name: "schema-qualified table",
sql: "CREATE INDEX idx_email ON public.users (email)",
wantObject: "idx_email",
wantSchema: "public",
wantCols: 1,
wantTables: 1,
},
{
name: "schema-qualified index and table",
sql: "CREATE UNIQUE INDEX public.idx_users_email ON public.users (email)",
wantObject: "idx_users_email",
wantSchema: "public",
wantCols: 1,
wantFlags: []string{"UNIQUE"},
wantTables: 1,
},
{
name: "schema-qualified index on unqualified table",
sql: "CREATE INDEX analytics.idx_users_email ON users (email)",
wantObject: "idx_users_email",
wantSchema: "analytics",
wantCols: 1,
wantTables: 1,
},
{
name: "IF NOT EXISTS with schema-qualified index and table",
sql: "CREATE INDEX IF NOT EXISTS public.idx_users_email ON public.users (email)",
wantObject: "idx_users_email",
wantSchema: "public",
wantCols: 1,
wantFlags: []string{"IF_NOT_EXISTS"},
wantTables: 1,
},
{
name: "quoted schema-qualified index and table",
sql: `CREATE UNIQUE INDEX "analytics"."IdxUsersEmail" ON "public"."users" ("email")`,
wantObject: `"IdxUsersEmail"`,
wantSchema: `"analytics"`,
wantCols: 1,
wantFlags: []string{"UNIQUE"},
wantTables: 1,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
ir := parseAssertNoError(t, tc.sql)
assert.Equal(t, QueryCommandDDL, ir.Command, "expected DDL command")
require.Len(t, ir.DDLActions, 1, "action count mismatch")
act := ir.DDLActions[0]
assert.Equal(t, DDLCreateIndex, act.Type, "expected CREATE_INDEX")
assert.Equal(t, tc.wantObject, act.ObjectName, "object name mismatch")
if tc.wantSchema != "" {
assert.Equal(t, tc.wantSchema, act.Schema, "schema mismatch")
}
assert.Len(t, act.Columns, tc.wantCols, "column count mismatch")
assert.Subset(t, act.Flags, tc.wantFlags, "flags mismatch")
if tc.wantIdx != "" {
assert.Equal(t, tc.wantIdx, act.IndexType, "index type mismatch")
}
assert.Len(t, ir.Tables, tc.wantTables, "tables count mismatch")
})
}
}
func TestIR_DDL_CreateIndex_QualifiedIndexNameNormalization(t *testing.T) {
ir := parseAssertNoError(t, "CREATE INDEX analytics.idx_users_email ON public.users (email)")
assert.Equal(t, QueryCommandDDL, ir.Command, "expected DDL command")
require.Len(t, ir.DDLActions, 1, "action count mismatch")
act := ir.DDLActions[0]
assert.Equal(t, DDLCreateIndex, act.Type, "expected CREATE_INDEX")
assert.Equal(t, "idx_users_email", act.ObjectName, "object name mismatch")
assert.Equal(t, "analytics", act.Schema, "index schema should come from index name")
require.Len(t, ir.Tables, 1, "tables count mismatch")
assert.Equal(t, "public", ir.Tables[0].Schema, "table schema mismatch")
assert.Equal(t, "users", ir.Tables[0].Name, "table name mismatch")
}
func TestIR_DDL_CreateIndex_OnlyRelationRawPreserved(t *testing.T) {
ir := parseAssertNoError(t, "CREATE INDEX idx_users_email ON ONLY public.users (email)")
assert.Equal(t, QueryCommandDDL, ir.Command, "expected DDL command")
require.Len(t, ir.DDLActions, 1, "action count mismatch")
act := ir.DDLActions[0]
assert.Equal(t, DDLCreateIndex, act.Type, "expected CREATE_INDEX")
assert.Equal(t, "idx_users_email", act.ObjectName, "object name mismatch")
assert.Equal(t, "public", act.Schema, "index schema should inherit parsed table schema")
require.Len(t, ir.Tables, 1, "tables count mismatch")
assert.Equal(t, "public", ir.Tables[0].Schema, "table schema mismatch")
assert.Equal(t, "users", ir.Tables[0].Name, "table name mismatch")
assert.Equal(t, "ONLY public.users", ir.Tables[0].Raw, "table raw mismatch")
}
// TestIR_DDL_CreateIndex_IncludeAndPredicate verifies that INCLUDE columns and
// the partial-index WHERE predicate are captured on the CREATE_INDEX action.
func TestIR_DDL_CreateIndex_IncludeAndPredicate(t *testing.T) {
tests := []struct {
name string
sql string
wantInclude []string
wantPredicate string
}{
{
name: "include columns and partial predicate",
sql: `CREATE INDEX idx_users_active_email
ON users (email)
INCLUDE (last_login_at)
WHERE active = true`,
wantInclude: []string{"last_login_at"},
wantPredicate: "active = true",
},
{
name: "multiple include columns, no predicate",
sql: `CREATE INDEX idx_users_email ON users (email) INCLUDE (name, last_login_at)`,
wantInclude: []string{"name", "last_login_at"},
wantPredicate: "",
},
{
name: "partial predicate only",
sql: `CREATE INDEX idx_users_partial ON users (email) WHERE created_at > '2024-01-01'`,
wantInclude: nil,
wantPredicate: "created_at > '2024-01-01'",
},
{
name: "plain index leaves both fields empty",
sql: `CREATE INDEX idx_users_email ON users (email)`,
wantInclude: nil,
wantPredicate: "",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
ir := parseAssertNoError(t, tc.sql)
require.Len(t, ir.DDLActions, 1, "action count mismatch")
act := ir.DDLActions[0]
assert.Equal(t, DDLCreateIndex, act.Type, "expected CREATE_INDEX")
assert.Equal(t, tc.wantInclude, act.IncludeColumns, "IncludeColumns mismatch")
assert.Equal(t, tc.wantPredicate, act.Predicate, "Predicate mismatch")
})
}
}
func TestIR_DDL_CreateTable(t *testing.T) {
sql := `CREATE TABLE public.users (
id integer NOT NULL,
email text NOT NULL,
name text,
created_at timestamp without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL
);`
ir := parseAssertNoError(t, sql)
assert.Equal(t, QueryCommandDDL, ir.Command, "expected DDL command")
require.Len(t, ir.DDLActions, 1, "action count mismatch")
act := ir.DDLActions[0]
assert.Equal(t, DDLCreateTable, act.Type, "expected CREATE_TABLE")
assert.Equal(t, "users", act.ObjectName, "object name mismatch")
assert.Equal(t, "public", act.Schema, "schema mismatch")
assert.Equal(t, []string{"id", "email", "name", "created_at"}, act.Columns, "column names mismatch")
assert.Equal(t, []DDLColumn{
{Name: "id", Type: "integer", Nullable: false},
{Name: "email", Type: "text", Nullable: false},
{Name: "name", Type: "text", Nullable: true},
{Name: "created_at", Type: "timestamp without time zone", Nullable: false, Default: "CURRENT_TIMESTAMP"},
}, act.ColumnDetails, "column details mismatch")
require.Len(t, ir.Tables, 1, "tables count mismatch")
assert.Equal(t, "public", ir.Tables[0].Schema, "table schema mismatch")
assert.Equal(t, "users", ir.Tables[0].Name, "table name mismatch")
}
func TestIR_DDL_CreateTableIfNotExists(t *testing.T) {
ir := parseAssertNoError(t, "CREATE TABLE IF NOT EXISTS users (id integer)")
assert.Equal(t, QueryCommandDDL, ir.Command, "expected DDL command")
require.Len(t, ir.DDLActions, 1, "action count mismatch")
act := ir.DDLActions[0]
assert.Equal(t, DDLCreateTable, act.Type, "expected CREATE_TABLE")
assert.Equal(t, "users", act.ObjectName, "object name mismatch")
assert.Subset(t, act.Flags, []string{"IF_NOT_EXISTS"}, "flags mismatch")
require.Len(t, act.ColumnDetails, 1, "column details mismatch")
assert.Equal(t, DDLColumn{Name: "id", Type: "integer", Nullable: true}, act.ColumnDetails[0], "column mismatch")
}
func TestIR_DDL_CreateTable_TablePrimaryKeySetsNullableFalse(t *testing.T) {
sql := `CREATE TABLE public.accounts (
id integer,
tenant_id integer,
payload text,
CONSTRAINT accounts_pk PRIMARY KEY (id, tenant_id)
);`
ir := parseAssertNoError(t, sql)
assert.Equal(t, QueryCommandDDL, ir.Command, "expected DDL command")
require.Len(t, ir.DDLActions, 1, "action count mismatch")
act := ir.DDLActions[0]
assert.Equal(t, DDLCreateTable, act.Type, "expected CREATE_TABLE")
assert.Equal(t, "accounts", act.ObjectName, "object name mismatch")
assert.Equal(t, "public", act.Schema, "schema mismatch")
assert.Equal(t, []string{"id", "tenant_id", "payload"}, act.Columns, "column names mismatch")
assert.Equal(t, []DDLColumn{
{Name: "id", Type: "integer", Nullable: false},
{Name: "tenant_id", Type: "integer", Nullable: false},
{Name: "payload", Type: "text", Nullable: true},
}, act.ColumnDetails, "column details mismatch")
require.NotNil(t, act.Constraints.PrimaryKey, "expected primary key metadata")
assert.Equal(t, &DDLPrimaryKey{
ConstraintName: "accounts_pk",
Columns: []string{"id", "tenant_id"},
}, act.Constraints.PrimaryKey, "primary key metadata mismatch")
assert.Empty(t, act.Constraints.ForeignKeys, "foreign keys mismatch")
require.Len(t, ir.Tables, 1, "tables count mismatch")
assert.Equal(t, "public", ir.Tables[0].Schema, "table schema mismatch")
assert.Equal(t, "accounts", ir.Tables[0].Name, "table name mismatch")
}
func TestIR_DDL_CreateTable_TablePrimaryKeySetsNullableFalse_NoSchema(t *testing.T) {
sql := `CREATE TABLE accounts (
id integer,
tenant_id integer,
payload text,
PRIMARY KEY (id, tenant_id)
);`
ir := parseAssertNoError(t, sql)
assert.Equal(t, QueryCommandDDL, ir.Command, "expected DDL command")
require.Len(t, ir.DDLActions, 1, "action count mismatch")
act := ir.DDLActions[0]
assert.Equal(t, DDLCreateTable, act.Type, "expected CREATE_TABLE")
assert.Equal(t, "accounts", act.ObjectName, "object name mismatch")
assert.Empty(t, act.Schema, "schema mismatch")
assert.Equal(t, []string{"id", "tenant_id", "payload"}, act.Columns, "column names mismatch")
assert.Equal(t, []DDLColumn{
{Name: "id", Type: "integer", Nullable: false},
{Name: "tenant_id", Type: "integer", Nullable: false},
{Name: "payload", Type: "text", Nullable: true},
}, act.ColumnDetails, "column details mismatch")
require.NotNil(t, act.Constraints.PrimaryKey, "expected primary key metadata")
assert.Equal(t, &DDLPrimaryKey{
Columns: []string{"id", "tenant_id"},
}, act.Constraints.PrimaryKey, "primary key metadata mismatch")
assert.Empty(t, act.Constraints.ForeignKeys, "foreign keys mismatch")
require.Len(t, ir.Tables, 1, "tables count mismatch")
assert.Empty(t, ir.Tables[0].Schema, "table schema mismatch")
assert.Equal(t, "accounts", ir.Tables[0].Name, "table name mismatch")
}
func TestIR_DDL_CreateTable_Relationships_TableConstraints(t *testing.T) {
sql := `CREATE TABLE public.users (
id integer,
org_id integer,
region text NOT NULL,
branch_id integer NOT NULL,
CONSTRAINT users_pk PRIMARY KEY (id),
CONSTRAINT users_org_fk FOREIGN KEY (org_id) REFERENCES public.organizations(id),
CONSTRAINT users_branch_fk FOREIGN KEY (region, branch_id) REFERENCES public.branches(region, branch_id)
);`
ir := parseAssertNoError(t, sql)
assert.Equal(t, QueryCommandDDL, ir.Command, "expected DDL command")
require.Len(t, ir.DDLActions, 1, "action count mismatch")
act := ir.DDLActions[0]
assert.Equal(t, DDLCreateTable, act.Type, "expected CREATE_TABLE")
require.NotNil(t, act.Constraints.PrimaryKey, "expected primary key metadata")
assert.Equal(t, &DDLPrimaryKey{
ConstraintName: "users_pk",
Columns: []string{"id"},
}, act.Constraints.PrimaryKey, "primary key metadata mismatch")
assert.Equal(t, []DDLForeignKey{
{
ConstraintName: "users_org_fk",
Columns: []string{"org_id"},
ReferencesSchema: "public",
ReferencesTable: "organizations",
ReferencesColumns: []string{"id"},
},
{
ConstraintName: "users_branch_fk",
Columns: []string{"region", "branch_id"},
ReferencesSchema: "public",
ReferencesTable: "branches",
ReferencesColumns: []string{"region", "branch_id"},
},
}, act.Constraints.ForeignKeys, "foreign keys mismatch")
require.Len(t, act.ColumnDetails, 4, "column details mismatch")
assert.Equal(t, DDLColumn{Name: "id", Type: "integer", Nullable: false}, act.ColumnDetails[0], "id column mismatch")
}
func TestIR_DDL_CreateTable_Relationships_InlineConstraints(t *testing.T) {
sql := `CREATE TABLE public.memberships (
id integer PRIMARY KEY,
org_id integer CONSTRAINT memberships_org_fk REFERENCES public.organizations(id),
branch_id integer REFERENCES branches(id)
);`
ir := parseAssertNoError(t, sql)
assert.Equal(t, QueryCommandDDL, ir.Command, "expected DDL command")
require.Len(t, ir.DDLActions, 1, "action count mismatch")
act := ir.DDLActions[0]
assert.Equal(t, DDLCreateTable, act.Type, "expected CREATE_TABLE")
require.NotNil(t, act.Constraints.PrimaryKey, "expected primary key metadata")
assert.Equal(t, &DDLPrimaryKey{
Columns: []string{"id"},
}, act.Constraints.PrimaryKey, "primary key metadata mismatch")
assert.Equal(t, []DDLForeignKey{
{
ConstraintName: "memberships_org_fk",
Columns: []string{"org_id"},
ReferencesSchema: "public",
ReferencesTable: "organizations",
ReferencesColumns: []string{"id"},
},
{
Columns: []string{"branch_id"},
ReferencesTable: "branches",
ReferencesColumns: []string{"id"},
},
}, act.Constraints.ForeignKeys, "foreign keys mismatch")
require.Len(t, act.ColumnDetails, 3, "column details mismatch")
assert.Equal(t, DDLColumn{Name: "id", Type: "integer", Nullable: false}, act.ColumnDetails[0], "id column mismatch")
}
func TestIR_DDL_CreateTable_Relationships_ReferentialActions(t *testing.T) {
sql := `CREATE TABLE public.orders (
id integer PRIMARY KEY,
user_id integer REFERENCES public.users(id) ON DELETE CASCADE ON UPDATE SET NULL,
product_id integer,
CONSTRAINT orders_product_fk FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE SET DEFAULT ON UPDATE RESTRICT
);`
ir := parseAssertNoError(t, sql)
assert.Equal(t, QueryCommandDDL, ir.Command, "expected DDL command")
require.Len(t, ir.DDLActions, 1, "action count mismatch")
act := ir.DDLActions[0]
require.NotNil(t, act.Constraints.PrimaryKey, "expected primary key metadata")
assert.Equal(t, &DDLPrimaryKey{Columns: []string{"id"}}, act.Constraints.PrimaryKey, "primary key mismatch")
require.Len(t, act.Constraints.ForeignKeys, 2, "foreign key count mismatch")
assert.Equal(t, DDLForeignKey{
Columns: []string{"user_id"},
ReferencesSchema: "public",
ReferencesTable: "users",
ReferencesColumns: []string{"id"},
OnDelete: FKCascade,
OnUpdate: FKSetNull,
}, act.Constraints.ForeignKeys[0], "inline FK mismatch")
assert.Equal(t, DDLForeignKey{
ConstraintName: "orders_product_fk",
Columns: []string{"product_id"},
ReferencesTable: "products",
ReferencesColumns: []string{"id"},
OnDelete: FKSetDefault,
OnUpdate: FKRestrict,
}, act.Constraints.ForeignKeys[1], "table-level FK mismatch")
}
func TestIR_DDL_CreateTable_Relationships_NoAction(t *testing.T) {
sql := `CREATE TABLE t (
id integer PRIMARY KEY,
ref_id integer REFERENCES other(id) ON DELETE NO ACTION
);`
ir := parseAssertNoError(t, sql)
require.Len(t, ir.DDLActions, 1)
require.Len(t, ir.DDLActions[0].Constraints.ForeignKeys, 1)
assert.Equal(t, FKNoAction, ir.DDLActions[0].Constraints.ForeignKeys[0].OnDelete)
assert.Empty(t, ir.DDLActions[0].Constraints.ForeignKeys[0].OnUpdate)
}
func TestIR_DDL_CreateTable_UniqueConstraints(t *testing.T) {
sql := `CREATE TABLE public.users (
id integer PRIMARY KEY,
email text UNIQUE,
code text,
region text,
CONSTRAINT users_code_region_uniq UNIQUE (code, region)
);`
ir := parseAssertNoError(t, sql)
assert.Equal(t, QueryCommandDDL, ir.Command)
require.Len(t, ir.DDLActions, 1)
act := ir.DDLActions[0]
assert.Equal(t, []DDLUniqueConstraint{
{Columns: []string{"email"}},
{ConstraintName: "users_code_region_uniq", Columns: []string{"code", "region"}},
}, act.Constraints.UniqueKeys, "unique keys mismatch")
assert.NotNil(t, act.Constraints.PrimaryKey, "expected primary key")
}
func TestIR_DDL_AlterTableAddConstraintUnique(t *testing.T) {
sql := `ALTER TABLE public.users ADD CONSTRAINT users_email_uniq UNIQUE (email);`
ir := parseAssertNoError(t, sql)
assert.Equal(t, QueryCommandDDL, ir.Command)
require.Len(t, ir.DDLActions, 1)
act := ir.DDLActions[0]
assert.Equal(t, DDLAlterTable, act.Type)
assert.Contains(t, act.Flags, "ADD_CONSTRAINT")
assert.Equal(t, []DDLUniqueConstraint{
{ConstraintName: "users_email_uniq", Columns: []string{"email"}},
}, act.Constraints.UniqueKeys, "unique keys mismatch")
assert.Nil(t, act.Constraints.PrimaryKey)
assert.Empty(t, act.Constraints.ForeignKeys)
}
func TestIR_DDL_CreateTableTypeCoverage(t *testing.T) {
sql := `CREATE TABLE public.type_matrix (
c_smallint smallint,
c_integer integer,
c_bigint bigint,
c_numeric numeric(10,2),
c_real real,
c_double double precision,
c_money money,
c_bool boolean,
c_char char(3),
c_varchar varchar(50),
c_text text,
c_bytea bytea,
c_date date,
c_time time without time zone,
c_timetz time with time zone,
c_timestamp timestamp without time zone,
c_timestamptz timestamp with time zone,
c_interval interval year to month,
c_uuid uuid,
c_json json,
c_jsonb jsonb,
c_xml xml,
c_inet inet,
c_cidr cidr,
c_macaddr macaddr,
c_macaddr8 macaddr8,
c_point point,
c_line line,
c_lseg lseg,
c_box box,
c_path path,
c_polygon polygon,
c_circle circle,
c_int4range int4range,
c_numrange numrange,
c_tstzrange tstzrange,
c_int_array integer[],
c_text_array text[]
);`
ir := parseAssertNoError(t, sql)
assert.Equal(t, QueryCommandDDL, ir.Command, "expected DDL command")
require.Len(t, ir.DDLActions, 1, "action count mismatch")
act := ir.DDLActions[0]
assert.Equal(t, DDLCreateTable, act.Type, "expected CREATE_TABLE")
assert.Equal(t, "public", act.Schema, "schema mismatch")
assert.Equal(t, "type_matrix", act.ObjectName, "object name mismatch")
wantTypes := map[string]string{
"c_smallint": "smallint",
"c_integer": "integer",
"c_bigint": "bigint",
"c_numeric": "numeric(10,2)",
"c_real": "real",
"c_double": "double precision",
"c_money": "money",
"c_bool": "boolean",
"c_char": "char(3)",
"c_varchar": "varchar(50)",
"c_text": "text",
"c_bytea": "bytea",
"c_date": "date",
"c_time": "time without time zone",
"c_timetz": "time with time zone",
"c_timestamp": "timestamp without time zone",
"c_timestamptz": "timestamp with time zone",
"c_interval": "interval year to month",
"c_uuid": "uuid",
"c_json": "json",
"c_jsonb": "jsonb",
"c_xml": "xml",
"c_inet": "inet",
"c_cidr": "cidr",
"c_macaddr": "macaddr",
"c_macaddr8": "macaddr8",
"c_point": "point",
"c_line": "line",
"c_lseg": "lseg",
"c_box": "box",
"c_path": "path",
"c_polygon": "polygon",
"c_circle": "circle",
"c_int4range": "int4range",
"c_numrange": "numrange",
"c_tstzrange": "tstzrange",
"c_int_array": "integer[]",
"c_text_array": "text[]",
}
require.Len(t, act.ColumnDetails, len(wantTypes), "column count mismatch")
got := make(map[string]DDLColumn, len(act.ColumnDetails))
for _, col := range act.ColumnDetails {
got[col.Name] = col
}
for colName, wantType := range wantTypes {
col, ok := got[colName]
require.Truef(t, ok, "missing column %q", colName)
assert.Equal(t, wantType, col.Type, "type mismatch for %s", colName)
assert.True(t, col.Nullable, "expected nullable=true by default for %s", colName)
assert.Empty(t, col.Default, "expected no default for %s", colName)
}
}
func TestIR_DDL_CommentOn_Table(t *testing.T) {
tests := []struct {
name string
sql string
wantObjectType string
wantSchema string
wantObjectName string
wantTarget string
wantColumns []string
wantComment string
wantTables int
wantFirstTable *TableRef
}{
{
name: "issue34 table comment",
sql: `COMMENT ON TABLE public.users IS 'Stores user account information';`,
wantObjectType: "TABLE",
wantSchema: "public",
wantObjectName: "users",
wantTarget: "public.users",
wantComment: "Stores user account information",
wantTables: 1,
wantFirstTable: &TableRef{Schema: "public", Name: "users", Type: TableTypeBase, Raw: "public.users"},
},
{
name: "issue34 column comment",
sql: `COMMENT ON COLUMN public.users.email IS 'User email address, must be unique';`,
wantObjectType: "COLUMN",
wantSchema: "public",
wantObjectName: "users",
wantTarget: "public.users.email",
wantColumns: []string{"email"},
wantComment: "User email address, must be unique",
wantTables: 1,
wantFirstTable: &TableRef{Schema: "public", Name: "users", Type: TableTypeBase, Raw: "public.users"},
},
{
name: "issue34 index comment",
sql: `COMMENT ON INDEX public.idx_bookings_dates IS 'Composite index for efficient date range queries on bookings';`,
wantObjectType: "INDEX",
wantSchema: "public",
wantObjectName: "idx_bookings_dates",
wantTarget: "public.idx_bookings_dates",
wantComment: "Composite index for efficient date range queries on bookings",
wantTables: 0,
},
{
name: "unqualified column target",
sql: `COMMENT ON COLUMN users.email IS 'x';`,
wantObjectType: "COLUMN",
wantObjectName: "users",
wantTarget: "users.email",
wantColumns: []string{"email"},
wantComment: "x",
wantTables: 1,
wantFirstTable: &TableRef{Name: "users", Type: TableTypeBase, Raw: "users"},
},
{
name: "quoted dotted identifiers in column target",
sql: `COMMENT ON COLUMN public."my.table"."my.col" IS 'x';`,
wantObjectType: "COLUMN",
wantSchema: "public",
wantObjectName: `"my.table"`,
wantTarget: `public."my.table"."my.col"`,
wantColumns: []string{`"my.col"`},
wantComment: "x",
wantTables: 1,
wantFirstTable: &TableRef{Schema: "public", Name: `"my.table"`, Type: TableTypeBase, Raw: `public."my.table"`},
},
{
name: "unquoted dotted identifiers are treated as qualifiers",
sql: `COMMENT ON COLUMN public.my.table.my.col IS 'x';`,
wantObjectType: "COLUMN",
wantSchema: "public.my.table",
wantObjectName: "my",
wantTarget: "public.my.table.my.col",
wantColumns: []string{"col"},
wantComment: "x",
wantTables: 1,
wantFirstTable: &TableRef{Schema: "public.my.table", Name: "my", Type: TableTypeBase, Raw: "public.my.table.my"},
},
{
name: "null comment literal",
sql: `COMMENT ON TABLE public.users IS NULL;`,
wantObjectType: "TABLE",
wantSchema: "public",
wantObjectName: "users",
wantTarget: "public.users",
wantComment: "",
wantTables: 1,
wantFirstTable: &TableRef{Schema: "public", Name: "users", Type: TableTypeBase, Raw: "public.users"},
},
{
name: "escaped string literal",
sql: `COMMENT ON TABLE public.users IS E'line1\nline2';`,
wantObjectType: "TABLE",
wantSchema: "public",
wantObjectName: "users",
wantTarget: "public.users",
wantComment: "line1\nline2",
wantTables: 1,
wantFirstTable: &TableRef{Schema: "public", Name: "users", Type: TableTypeBase, Raw: "public.users"},
},
{
name: "dollar quoted string literal",
sql: `COMMENT ON TABLE public.users IS $tag$Stores "quoted" data$tag$;`,
wantObjectType: "TABLE",
wantSchema: "public",
wantObjectName: "users",
wantTarget: "public.users",
wantComment: `Stores "quoted" data`,
wantTables: 1,
wantFirstTable: &TableRef{Schema: "public", Name: "users", Type: TableTypeBase, Raw: "public.users"},
},
{
name: "foreign table comment",
sql: `COMMENT ON FOREIGN TABLE public.remote_users IS 'Foreign mirror';`,
wantObjectType: "FOREIGN TABLE",
wantSchema: "public",
wantObjectName: "remote_users",
wantTarget: "public.remote_users",
wantComment: "Foreign mirror",
wantTables: 1,
wantFirstTable: &TableRef{Schema: "public", Name: "remote_users", Type: TableTypeBase, Raw: "public.remote_users"},
},
{
name: "type comment",
sql: `COMMENT ON TYPE public.email_address IS 'Type used for email addresses';`,
wantObjectType: "TYPE",
wantSchema: "public",
wantObjectName: "email_address",
wantTarget: "public.email_address",
wantComment: "Type used for email addresses",
wantTables: 0,
},
{
name: "schema comment",
sql: `COMMENT ON SCHEMA public IS 'Application schema';`,
wantObjectType: "SCHEMA",
wantObjectName: "public",
wantTarget: "public",
wantComment: "Application schema",
wantTables: 0,
},
{
name: "unknown object type (FUNCTION)",
sql: `COMMENT ON FUNCTION public.my_func(integer) IS 'Does something';`,
wantObjectType: "UNKNOWN",
wantComment: "Does something",
wantTables: 0,
},
{
name: "doubled single-quote escaping",
sql: `COMMENT ON TABLE users IS 'it''s a test';`,
wantObjectType: "TABLE",
wantObjectName: "users",
wantTarget: "users",
wantComment: "it's a test",
wantTables: 1,
wantFirstTable: &TableRef{Name: "users", Type: TableTypeBase, Raw: "users"},
},
{
name: "empty string comment",
sql: `COMMENT ON TABLE users IS '';`,
wantObjectType: "TABLE",
wantObjectName: "users",
wantTarget: "users",
wantComment: "",
wantTables: 1,
wantFirstTable: &TableRef{Name: "users", Type: TableTypeBase, Raw: "users"},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
ir := parseAssertNoError(t, tc.sql)
assert.Equal(t, QueryCommandDDL, ir.Command, "expected DDL command")
require.Len(t, ir.DDLActions, 1, "action count mismatch")
act := ir.DDLActions[0]
assert.Equal(t, DDLComment, act.Type, "expected COMMENT action")
assert.Equal(t, tc.wantObjectType, act.ObjectType, "object type mismatch")
assert.Equal(t, tc.wantSchema, act.Schema, "schema mismatch")
assert.Equal(t, tc.wantObjectName, act.ObjectName, "object name mismatch")
assert.Equal(t, tc.wantTarget, act.Target, "target mismatch")
assert.Equal(t, tc.wantColumns, act.Columns, "column list mismatch")
assert.Equal(t, tc.wantComment, act.Comment, "comment mismatch")
require.Len(t, ir.Tables, tc.wantTables, "tables count mismatch")
if tc.wantFirstTable != nil {
assert.Equal(t, *tc.wantFirstTable, ir.Tables[0], "first table ref mismatch")
}
})
}
}
func TestIR_DDL_CreateTableFieldComments_Table(t *testing.T) {
tests := []struct {
name string
sql string
opts ParseOptions
wantCommentsByCol map[string][]string
wantColumnSequence []string
}{
{
name: "issue25 example",
sql: `CREATE TABLE public.users (
-- [Attribute("Just an example")]
-- required, min 5, max 55
name text,
-- single-column FK, inline
org_id integer REFERENCES public.organizations(id)
);`,
opts: ParseOptions{IncludeCreateTableFieldComments: true},
wantCommentsByCol: map[string][]string{
"name": {`[Attribute("Just an example")]`, "required, min 5, max 55"},
"org_id": {"single-column FK, inline"},
},
wantColumnSequence: []string{"name", "org_id"},
},
{
name: "disabled by default",
sql: `CREATE TABLE public.users (
-- should not be extracted by default
name text
);`,
wantCommentsByCol: map[string][]string{
"name": {},
},
wantColumnSequence: []string{"name"},
},
{
name: "skips constraint comments",
sql: `CREATE TABLE public.users (
-- user id
id integer,
-- should not attach to any column
CONSTRAINT users_pk PRIMARY KEY (id),
-- user email
email text
);`,
opts: ParseOptions{IncludeCreateTableFieldComments: true},
wantCommentsByCol: map[string][]string{
"id": {"user id"},
"email": {"user email"},
},
wantColumnSequence: []string{"id", "email"},
},
{
name: "quoted and unquoted identifiers",
sql: `CREATE TABLE public.users (
-- case-sensitive display email
"Email" text,
-- lowercase fallback
email text
);`,
opts: ParseOptions{IncludeCreateTableFieldComments: true},
wantCommentsByCol: map[string][]string{
`"Email"`: {"case-sensitive display email"},
"email": {"lowercase fallback"},
},
wantColumnSequence: []string{`"Email"`, "email"},