-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathtable.go
More file actions
1574 lines (1376 loc) · 55.1 KB
/
table.go
File metadata and controls
1574 lines (1376 loc) · 55.1 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
package diff
import (
"fmt"
"sort"
"strings"
"github.com/pgplex/pgschema/ir"
)
// stripSchemaPrefix removes the schema prefix from a type name if it matches the target schema.
// It handles both simple type names (e.g., "schema.typename") and type casts within expressions
// (e.g., "'value'::schema.typename" -> "'value'::typename").
func stripSchemaPrefix(typeName, targetSchema string) string {
if typeName == "" || targetSchema == "" {
return typeName
}
// Check if the type has the target schema prefix at the beginning
prefix := targetSchema + "."
if after, found := strings.CutPrefix(typeName, prefix); found {
return after
}
// Also handle type casts within expressions: ::schema.typename -> ::typename
// This is needed for function parameter default values like 'value'::schema.enum_type
castPrefix := "::" + targetSchema + "."
if strings.Contains(typeName, castPrefix) {
return strings.ReplaceAll(typeName, castPrefix, "::")
}
return typeName
}
// stripTempSchemaPrefix removes temporary embedded postgres schema prefixes (pgschema_tmp_*).
// These are used internally during plan generation and should not appear in output DDL.
func stripTempSchemaPrefix(value string) string {
if value == "" {
return value
}
// Pattern: ::pgschema_tmp_YYYYMMDD_HHMMSS_XXXXXXXX.typename -> ::typename
// We look for ::pgschema_tmp_ followed by anything until the next dot
idx := strings.Index(value, "::pgschema_tmp_")
if idx == -1 {
return value
}
// Find the dot after pgschema_tmp_*
dotIdx := strings.Index(value[idx+15:], ".")
if dotIdx == -1 {
return value
}
// Replace ::pgschema_tmp_XXX.typename with ::typename
prefix := value[idx : idx+15+dotIdx+1] // includes the trailing dot
return strings.ReplaceAll(value, prefix, "::")
}
// sortConstraintColumnsByPosition sorts constraint columns by their position
func sortConstraintColumnsByPosition(columns []*ir.ConstraintColumn) []*ir.ConstraintColumn {
sorted := make([]*ir.ConstraintColumn, len(columns))
copy(sorted, columns)
sort.Slice(sorted, func(i, j int) bool {
return sorted[i].Position < sorted[j].Position
})
return sorted
}
// diffTriggers compares triggers between two tables and populates the diff
func diffTriggers(oldTable, newTable *ir.Table, diff *tableDiff) {
oldTriggers := make(map[string]*ir.Trigger)
newTriggers := make(map[string]*ir.Trigger)
if oldTable.Triggers != nil {
for name, trigger := range oldTable.Triggers {
oldTriggers[name] = trigger
}
}
if newTable.Triggers != nil {
for name, trigger := range newTable.Triggers {
newTriggers[name] = trigger
}
}
// Find added triggers
for name, trigger := range newTriggers {
if _, exists := oldTriggers[name]; !exists {
diff.AddedTriggers = append(diff.AddedTriggers, trigger)
}
}
// Find dropped triggers
for name, trigger := range oldTriggers {
if _, exists := newTriggers[name]; !exists {
diff.DroppedTriggers = append(diff.DroppedTriggers, trigger)
}
}
// Find modified triggers
for name, newTrigger := range newTriggers {
if oldTrigger, exists := oldTriggers[name]; exists {
if !triggersEqual(oldTrigger, newTrigger) {
diff.ModifiedTriggers = append(diff.ModifiedTriggers, &triggerDiff{
Old: oldTrigger,
New: newTrigger,
})
}
}
}
}
// diffTables compares two tables and returns the differences
// targetSchema is used to normalize type names before comparison
func diffTables(oldTable, newTable *ir.Table, targetSchema string) *tableDiff {
diff := &tableDiff{
Table: newTable,
AddedColumns: []*ir.Column{},
DroppedColumns: []*ir.Column{},
ModifiedColumns: []*ColumnDiff{},
AddedConstraints: []*ir.Constraint{},
DroppedConstraints: []*ir.Constraint{},
ModifiedConstraints: []*ConstraintDiff{},
AddedIndexes: []*ir.Index{},
DroppedIndexes: []*ir.Index{},
ModifiedIndexes: []*IndexDiff{},
AddedTriggers: []*ir.Trigger{},
DroppedTriggers: []*ir.Trigger{},
ModifiedTriggers: []*triggerDiff{},
AddedPolicies: []*ir.RLSPolicy{},
DroppedPolicies: []*ir.RLSPolicy{},
ModifiedPolicies: []*policyDiff{},
RLSChanges: []*rlsChange{},
}
// Build maps for efficient lookup
oldColumns := make(map[string]*ir.Column)
newColumns := make(map[string]*ir.Column)
for _, column := range oldTable.Columns {
oldColumns[column.Name] = column
}
for _, column := range newTable.Columns {
newColumns[column.Name] = column
}
// Find added columns
for name, column := range newColumns {
if _, exists := oldColumns[name]; !exists {
diff.AddedColumns = append(diff.AddedColumns, column)
}
}
// Find dropped columns
for name, column := range oldColumns {
if _, exists := newColumns[name]; !exists {
diff.DroppedColumns = append(diff.DroppedColumns, column)
}
}
// Find modified columns
for name, newColumn := range newColumns {
if oldColumn, exists := oldColumns[name]; exists {
if !columnsEqual(oldColumn, newColumn, targetSchema) {
diff.ModifiedColumns = append(diff.ModifiedColumns, &ColumnDiff{
Old: oldColumn,
New: newColumn,
})
}
}
}
// Compare constraints
oldConstraints := make(map[string]*ir.Constraint)
newConstraints := make(map[string]*ir.Constraint)
if oldTable.Constraints != nil {
for name, constraint := range oldTable.Constraints {
oldConstraints[name] = constraint
}
}
if newTable.Constraints != nil {
for name, constraint := range newTable.Constraints {
newConstraints[name] = constraint
}
}
// Find added constraints
for name, constraint := range newConstraints {
if _, exists := oldConstraints[name]; !exists {
diff.AddedConstraints = append(diff.AddedConstraints, constraint)
}
}
// Find dropped constraints
for name, constraint := range oldConstraints {
if _, exists := newConstraints[name]; !exists {
diff.DroppedConstraints = append(diff.DroppedConstraints, constraint)
}
}
// Find modified constraints
for name, newConstraint := range newConstraints {
if oldConstraint, exists := oldConstraints[name]; exists {
if !constraintsEqual(oldConstraint, newConstraint) {
diff.ModifiedConstraints = append(diff.ModifiedConstraints, &ConstraintDiff{
Old: oldConstraint,
New: newConstraint,
})
}
}
}
// Compare indexes
oldIndexes := make(map[string]*ir.Index)
newIndexes := make(map[string]*ir.Index)
for _, index := range oldTable.Indexes {
oldIndexes[index.Name] = index
}
for _, index := range newTable.Indexes {
newIndexes[index.Name] = index
}
// Find added indexes
for name, index := range newIndexes {
if _, exists := oldIndexes[name]; !exists {
diff.AddedIndexes = append(diff.AddedIndexes, index)
}
}
// Find dropped indexes
for name, index := range oldIndexes {
if _, exists := newIndexes[name]; !exists {
diff.DroppedIndexes = append(diff.DroppedIndexes, index)
}
}
// Find modified indexes (comment changes and structural changes)
for name, newIndex := range newIndexes {
if oldIndex, exists := oldIndexes[name]; exists {
structurallyEqual := indexesStructurallyEqual(oldIndex, newIndex)
commentChanged := oldIndex.Comment != newIndex.Comment
// If only comments changed, treat as modification
if structurallyEqual && commentChanged {
diff.ModifiedIndexes = append(diff.ModifiedIndexes, &IndexDiff{
Old: oldIndex,
New: newIndex,
})
} else if !structurallyEqual {
// If structure changed, treat as drop + add for proper online handling
diff.DroppedIndexes = append(diff.DroppedIndexes, oldIndex)
diff.AddedIndexes = append(diff.AddedIndexes, newIndex)
}
}
}
// Compare triggers
diffTriggers(oldTable, newTable, diff)
// Compare policies
oldPolicies := make(map[string]*ir.RLSPolicy)
newPolicies := make(map[string]*ir.RLSPolicy)
if oldTable.Policies != nil {
for name, policy := range oldTable.Policies {
oldPolicies[name] = policy
}
}
if newTable.Policies != nil {
for name, policy := range newTable.Policies {
newPolicies[name] = policy
}
}
// Find added policies
for name, policy := range newPolicies {
if _, exists := oldPolicies[name]; !exists {
diff.AddedPolicies = append(diff.AddedPolicies, policy)
}
}
// Find dropped policies
for name, policy := range oldPolicies {
if _, exists := newPolicies[name]; !exists {
diff.DroppedPolicies = append(diff.DroppedPolicies, policy)
}
}
// Find modified policies
for name, newPolicy := range newPolicies {
if oldPolicy, exists := oldPolicies[name]; exists {
if !policiesEqual(oldPolicy, newPolicy) {
diff.ModifiedPolicies = append(diff.ModifiedPolicies, &policyDiff{
Old: oldPolicy,
New: newPolicy,
})
}
}
}
// Check for RLS enable/disable and force changes
if oldTable.RLSEnabled != newTable.RLSEnabled || oldTable.RLSForced != newTable.RLSForced {
change := &rlsChange{
Table: newTable,
}
if oldTable.RLSEnabled != newTable.RLSEnabled {
change.Enabled = &newTable.RLSEnabled
}
// Only track FORCE changes if RLS is not being disabled
// (disabling RLS implicitly clears FORCE, making NO FORCE redundant)
if oldTable.RLSForced != newTable.RLSForced && newTable.RLSEnabled {
change.Forced = &newTable.RLSForced
}
diff.RLSChanges = append(diff.RLSChanges, change)
}
// Check for table comment changes
if oldTable.Comment != newTable.Comment {
diff.CommentChanged = true
diff.OldComment = oldTable.Comment
diff.NewComment = newTable.Comment
}
// Return nil if no changes
if len(diff.AddedColumns) == 0 && len(diff.DroppedColumns) == 0 &&
len(diff.ModifiedColumns) == 0 && len(diff.AddedConstraints) == 0 &&
len(diff.DroppedConstraints) == 0 && len(diff.ModifiedConstraints) == 0 &&
len(diff.AddedIndexes) == 0 && len(diff.DroppedIndexes) == 0 &&
len(diff.ModifiedIndexes) == 0 && len(diff.AddedTriggers) == 0 &&
len(diff.DroppedTriggers) == 0 && len(diff.ModifiedTriggers) == 0 &&
len(diff.AddedPolicies) == 0 && len(diff.DroppedPolicies) == 0 &&
len(diff.ModifiedPolicies) == 0 && len(diff.RLSChanges) == 0 &&
!diff.CommentChanged {
return nil
}
return diff
}
// diffExternalTable compares two external tables and returns only trigger differences
// External tables are not managed by pgschema, so we only track triggers on them
func diffExternalTable(oldTable, newTable *ir.Table) *tableDiff {
diff := &tableDiff{
Table: newTable,
AddedColumns: []*ir.Column{},
DroppedColumns: []*ir.Column{},
ModifiedColumns: []*ColumnDiff{},
AddedConstraints: []*ir.Constraint{},
DroppedConstraints: []*ir.Constraint{},
ModifiedConstraints: []*ConstraintDiff{},
AddedIndexes: []*ir.Index{},
DroppedIndexes: []*ir.Index{},
ModifiedIndexes: []*IndexDiff{},
AddedTriggers: []*ir.Trigger{},
DroppedTriggers: []*ir.Trigger{},
ModifiedTriggers: []*triggerDiff{},
AddedPolicies: []*ir.RLSPolicy{},
DroppedPolicies: []*ir.RLSPolicy{},
ModifiedPolicies: []*policyDiff{},
RLSChanges: []*rlsChange{},
}
// For external tables, only compare triggers (not table structure)
diffTriggers(oldTable, newTable, diff)
// Return nil if no trigger changes
if len(diff.AddedTriggers) == 0 && len(diff.DroppedTriggers) == 0 && len(diff.ModifiedTriggers) == 0 {
return nil
}
return diff
}
type deferredConstraint struct {
table *ir.Table
constraint *ir.Constraint
}
// generateCreateTablesSQL generates CREATE TABLE statements with co-located indexes, policies, and RLS.
// Policies that reference other new tables in the same migration or newly added functions
// (via USING/WITH CHECK expressions) are deferred for creation after all tables and functions
// exist (#373). All other policies are emitted inline.
// It returns deferred policies and foreign key constraints that should be applied after dependent objects exist.
// Tables are assumed to be pre-sorted in topological order for dependency-aware creation.
func generateCreateTablesSQL(
tables []*ir.Table,
targetSchema string,
collector *diffCollector,
existingTables map[string]bool,
shouldDeferPolicy func(*ir.RLSPolicy) bool,
) ([]*ir.RLSPolicy, []*deferredConstraint) {
var deferredPolicies []*ir.RLSPolicy
var deferredConstraints []*deferredConstraint
createdTables := make(map[string]bool, len(tables))
// Process tables in the provided order (already topologically sorted)
for _, table := range tables {
// Create the table, deferring FK constraints that reference not-yet-created tables
sql, tableDeferred := generateTableSQL(table, targetSchema, createdTables, existingTables)
deferredConstraints = append(deferredConstraints, tableDeferred...)
// Create context for this statement
context := &diffContext{
Type: DiffTypeTable,
Operation: DiffOperationCreate,
Path: fmt.Sprintf("%s.%s", table.Schema, table.Name),
Source: table,
CanRunInTransaction: true, // CREATE TABLE can run in a transaction
}
collector.collect(context, sql)
// Add table comment
if table.Comment != "" {
tableName := qualifyEntityName(table.Schema, table.Name, targetSchema)
sql := fmt.Sprintf("COMMENT ON TABLE %s IS %s;", tableName, quoteString(table.Comment))
// Create context for this statement
context := &diffContext{
Type: DiffTypeTableComment,
Operation: DiffOperationCreate,
Path: fmt.Sprintf("%s.%s", table.Schema, table.Name),
Source: table,
CanRunInTransaction: true,
}
collector.collect(context, sql)
}
// Add column comments
for _, column := range table.Columns {
if column.Comment != "" {
tableName := qualifyEntityName(table.Schema, table.Name, targetSchema)
sql := fmt.Sprintf("COMMENT ON COLUMN %s.%s IS %s;", tableName, ir.QuoteIdentifier(column.Name), quoteString(column.Comment))
// Create context for this statement
context := &diffContext{
Type: DiffTypeTableColumnComment,
Operation: DiffOperationCreate,
Path: fmt.Sprintf("%s.%s.%s", table.Schema, table.Name, column.Name),
Source: table,
CanRunInTransaction: true,
}
collector.collect(context, sql)
}
}
// Convert map to slice for indexes
indexes := make([]*ir.Index, 0, len(table.Indexes))
for _, index := range table.Indexes {
indexes = append(indexes, index)
}
generateCreateIndexesSQL(indexes, targetSchema, collector)
// Handle RLS enable/force changes (before creating policies) - only for diff scenarios
if table.RLSEnabled || table.RLSForced {
change := &rlsChange{Table: table}
if table.RLSEnabled {
enabled := true
change.Enabled = &enabled
}
if table.RLSForced {
forced := true
change.Forced = &forced
}
rlsChanges := []*rlsChange{change}
generateRLSChangesSQL(rlsChanges, targetSchema, collector)
}
// Collect policies: defer those that reference other new tables or new functions (#373),
// emit the rest inline with their parent table.
if len(table.Policies) > 0 {
var inlinePolicies []*ir.RLSPolicy
policyNames := sortedKeys(table.Policies)
for _, name := range policyNames {
policy := table.Policies[name]
if shouldDeferPolicy != nil && shouldDeferPolicy(policy) {
deferredPolicies = append(deferredPolicies, policy)
} else {
inlinePolicies = append(inlinePolicies, policy)
}
}
if len(inlinePolicies) > 0 {
generateCreatePoliciesSQL(inlinePolicies, targetSchema, collector)
}
}
createdTables[fmt.Sprintf("%s.%s", table.Schema, table.Name)] = true
}
return deferredPolicies, deferredConstraints
}
func generateDeferredConstraintsSQL(deferred []*deferredConstraint, targetSchema string, collector *diffCollector) {
for _, item := range deferred {
constraint := item.constraint
if constraint == nil || item.table == nil || constraint.Name == "" {
continue
}
columns := sortConstraintColumnsByPosition(constraint.Columns)
var columnNames []string
for _, col := range columns {
columnNames = append(columnNames, ir.QuoteIdentifier(col.Name))
}
if constraint.IsTemporal && len(columnNames) > 0 {
columnNames[len(columnNames)-1] = "PERIOD " + columnNames[len(columnNames)-1]
}
tableName := getTableNameWithSchema(item.table.Schema, item.table.Name, targetSchema)
sql := fmt.Sprintf("ALTER TABLE %s\nADD CONSTRAINT %s FOREIGN KEY (%s) %s;",
tableName,
ir.QuoteIdentifier(constraint.Name),
strings.Join(columnNames, ", "),
generateForeignKeyClause(constraint, targetSchema, false),
)
context := &diffContext{
Type: DiffTypeTableConstraint,
Operation: DiffOperationCreate,
Path: fmt.Sprintf("%s.%s.%s", item.table.Schema, item.table.Name, constraint.Name),
Source: constraint,
CanRunInTransaction: true,
}
collector.collect(context, sql)
}
}
// generateModifyTablesSQL generates ALTER TABLE statements
func generateModifyTablesSQL(diffs []*tableDiff, droppedTables []*ir.Table, targetSchema string, collector *diffCollector) {
// Build a set of tables being dropped (CASCADE will remove their dependent FK constraints)
droppedTableSet := make(map[string]bool, len(droppedTables))
for _, t := range droppedTables {
droppedTableSet[t.Schema+"."+t.Name] = true
}
// Diffs are already sorted by the Diff operation
for _, diff := range diffs {
// Build a set of columns being dropped (DROP COLUMN will remove dependent constraints)
droppedColumnSet := make(map[string]bool, len(diff.DroppedColumns))
for _, column := range diff.DroppedColumns {
droppedColumnSet[column.Name] = true
}
// Pass collector to generateAlterTableStatements to collect with proper context
diff.generateAlterTableStatements(targetSchema, collector, droppedTableSet, droppedColumnSet)
}
}
// generateDropTablesSQL generates DROP TABLE statements
// Tables are assumed to be pre-sorted in reverse topological order for dependency-aware dropping
func generateDropTablesSQL(tables []*ir.Table, targetSchema string, collector *diffCollector) {
// Process tables in the provided order (already reverse topologically sorted)
for _, table := range tables {
tableName := qualifyEntityName(table.Schema, table.Name, targetSchema)
sql := fmt.Sprintf("DROP TABLE IF EXISTS %s CASCADE;", tableName)
// Create context for this statement
context := &diffContext{
Type: DiffTypeTable,
Operation: DiffOperationDrop,
Path: fmt.Sprintf("%s.%s", table.Schema, table.Name),
Source: table,
CanRunInTransaction: true,
}
collector.collect(context, sql)
}
}
// generateTableSQL generates CREATE TABLE statement and returns any deferred FK constraints
func generateTableSQL(table *ir.Table, targetSchema string, createdTables map[string]bool, existingTables map[string]bool) (string, []*deferredConstraint) {
// Only include table name without schema if it's in the target schema
tableName := ir.QualifyEntityNameWithQuotes(table.Schema, table.Name, targetSchema)
var parts []string
parts = append(parts, fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (", tableName))
// Add columns
var columnParts []string
for _, column := range table.Columns {
// Build column definition with SERIAL detection
var builder strings.Builder
writeColumnDefinitionToBuilder(&builder, table, column, targetSchema)
columnParts = append(columnParts, fmt.Sprintf(" %s", builder.String()))
}
// Add LIKE clauses
for _, likeClause := range table.LikeClauses {
likeTableName := ir.QualifyEntityNameWithQuotes(likeClause.SourceSchema, likeClause.SourceTable, targetSchema)
likeSQL := fmt.Sprintf("LIKE %s", likeTableName)
if likeClause.Options != "" {
likeSQL += " " + likeClause.Options
}
columnParts = append(columnParts, fmt.Sprintf(" %s", likeSQL))
}
// Add constraints inline in the correct order (PRIMARY KEY, UNIQUE, FOREIGN KEY)
inlineConstraints := getInlineConstraintsForTable(table)
var deferred []*deferredConstraint
currentKey := fmt.Sprintf("%s.%s", table.Schema, table.Name)
for _, constraint := range inlineConstraints {
if shouldDeferConstraint(table, constraint, currentKey, createdTables, existingTables) {
deferred = append(deferred, &deferredConstraint{
table: table,
constraint: constraint,
})
continue
}
constraintDef := generateConstraintSQL(constraint, targetSchema)
if constraintDef != "" {
columnParts = append(columnParts, fmt.Sprintf(" %s", constraintDef))
}
}
parts = append(parts, strings.Join(columnParts, ",\n"))
// Add partition clause for partitioned tables
if table.IsPartitioned && table.PartitionStrategy != "" && table.PartitionKey != "" {
parts = append(parts, fmt.Sprintf(") PARTITION BY %s (%s);", table.PartitionStrategy, table.PartitionKey))
} else {
parts = append(parts, ");")
}
return strings.Join(parts, "\n"), deferred
}
func shouldDeferConstraint(table *ir.Table, constraint *ir.Constraint, currentKey string, createdTables map[string]bool, existingTables map[string]bool) bool {
if constraint == nil || constraint.Type != ir.ConstraintTypeForeignKey {
return false
}
refSchema := constraint.ReferencedSchema
if refSchema == "" {
refSchema = table.Schema
}
if constraint.ReferencedTable == "" {
return false
}
refKey := fmt.Sprintf("%s.%s", refSchema, constraint.ReferencedTable)
if refKey == currentKey {
return false
}
// Check if the referenced table exists (either being created or already exists)
if existingTables != nil && existingTables[refKey] {
return false // Table exists, no need to defer
}
if createdTables != nil && createdTables[refKey] {
return false // Table already created in this operation
}
// Referenced table doesn't exist yet, defer the constraint
return true
}
// constraintDroppedWithColumns reports whether dropping any column in droppedColumnSet
// will implicitly remove the constraint. PostgreSQL drops dependent constraints as part
// of ALTER TABLE ... DROP COLUMN, so emitting an explicit DROP CONSTRAINT would be redundant.
func constraintDroppedWithColumns(constraint *ir.Constraint, droppedColumnSet map[string]bool) bool {
if constraint == nil || len(droppedColumnSet) == 0 {
return false
}
for _, column := range constraint.Columns {
if droppedColumnSet[column.Name] {
return true
}
}
return false
}
// generateAlterTableStatements generates SQL statements for table modifications
// Note: DroppedTriggers are skipped here because they are already processed in the DROP phase
// (see generateDropTriggersFromModifiedTables in trigger.go)
// droppedTableSet contains "schema.table" keys for tables being dropped with CASCADE;
// FK constraints referencing these tables are skipped since CASCADE already removes them.
// droppedColumnSet contains column names being dropped from this table; constraints that
// depend on those columns are skipped because DROP COLUMN already removes them. (#384)
func (td *tableDiff) generateAlterTableStatements(targetSchema string, collector *diffCollector, droppedTableSet map[string]bool, droppedColumnSet map[string]bool) {
// Drop constraints first (before dropping columns) - already sorted by the Diff operation
for _, constraint := range td.DroppedConstraints {
// Skip constraints already removed by a dropped column. (#384)
if constraintDroppedWithColumns(constraint, droppedColumnSet) {
continue
}
// Skip FK constraints whose referenced table is being dropped with CASCADE,
// since the CASCADE will already remove the constraint. (#382)
if constraint.Type == ir.ConstraintTypeForeignKey && constraint.ReferencedTable != "" {
refSchema := constraint.ReferencedSchema
if refSchema == "" {
refSchema = td.Table.Schema
}
refKey := refSchema + "." + constraint.ReferencedTable
if droppedTableSet[refKey] {
continue
}
}
tableName := getTableNameWithSchema(td.Table.Schema, td.Table.Name, targetSchema)
sql := fmt.Sprintf("ALTER TABLE %s DROP CONSTRAINT %s;", tableName, ir.QuoteIdentifier(constraint.Name))
context := &diffContext{
Type: DiffTypeTableConstraint,
Operation: DiffOperationDrop,
Path: fmt.Sprintf("%s.%s.%s", td.Table.Schema, td.Table.Name, constraint.Name),
Source: constraint,
CanRunInTransaction: true,
}
collector.collect(context, sql)
}
// Drop columns - already sorted by the Diff operation
for _, column := range td.DroppedColumns {
tableName := getTableNameWithSchema(td.Table.Schema, td.Table.Name, targetSchema)
sql := fmt.Sprintf("ALTER TABLE %s DROP COLUMN %s;", tableName, ir.QuoteIdentifier(column.Name))
context := &diffContext{
Type: DiffTypeTableColumn,
Operation: DiffOperationDrop,
Path: fmt.Sprintf("%s.%s.%s", td.Table.Schema, td.Table.Name, column.Name),
Source: column,
CanRunInTransaction: true,
}
collector.collect(context, sql)
}
// Track constraints that are added inline with columns to avoid duplicate generation
inlineConstraints := make(map[string]bool)
// Add new columns - already sorted by the Diff operation
for _, column := range td.AddedColumns {
// Check if column is part of any primary key constraint for NOT NULL handling
isPartOfAnyPK := false
for _, constraint := range td.AddedConstraints {
if constraint.Type == ir.ConstraintTypePrimaryKey {
for _, col := range constraint.Columns {
if col.Name == column.Name {
isPartOfAnyPK = true
break
}
}
if isPartOfAnyPK {
break
}
}
}
// Build column type and strip schema prefix if it matches target schema
columnType := formatColumnDataType(column)
columnType = stripSchemaPrefix(columnType, targetSchema)
tableName := getTableNameWithSchema(td.Table.Schema, td.Table.Name, targetSchema)
// Build and append all column clauses
clauses := buildColumnClauses(column, isPartOfAnyPK, td.Table.Schema, targetSchema)
// Check for single-column constraints that can be added inline
var inlineConstraint string
for _, constraint := range td.AddedConstraints {
// Only add inline for single-column constraints
if len(constraint.Columns) == 1 && constraint.Columns[0].Name == column.Name {
switch constraint.Type {
case ir.ConstraintTypePrimaryKey:
inlineConstraint = fmt.Sprintf(" CONSTRAINT %s PRIMARY KEY", ir.QuoteIdentifier(constraint.Name))
case ir.ConstraintTypeUnique:
inlineConstraint = fmt.Sprintf(" CONSTRAINT %s UNIQUE", ir.QuoteIdentifier(constraint.Name))
case ir.ConstraintTypeForeignKey:
// For FK, use the generateForeignKeyClause with inline=true
fkClause := generateForeignKeyClause(constraint, targetSchema, true)
inlineConstraint = fmt.Sprintf(" CONSTRAINT %s%s", ir.QuoteIdentifier(constraint.Name), fkClause)
case ir.ConstraintTypeCheck:
// For CHECK, format the clause inline
checkExpr := constraint.CheckClause
// Strip "CHECK" prefix if present
if len(checkExpr) >= 5 && strings.EqualFold(checkExpr[:5], "check") {
checkExpr = strings.TrimSpace(checkExpr[5:])
}
checkExpr = strings.TrimSpace(checkExpr)
// Ensure parentheses
if !strings.HasPrefix(checkExpr, "(") {
checkExpr = "(" + checkExpr + ")"
}
inlineConstraint = fmt.Sprintf(" CONSTRAINT %s CHECK %s", ir.QuoteIdentifier(constraint.Name), checkExpr)
}
if inlineConstraint != "" {
inlineConstraints[constraint.Name] = true
break
}
}
}
// Build base ALTER TABLE ADD COLUMN statement
// Use newline format if there's an inline constraint for better readability
var stmt string
if inlineConstraint != "" {
stmt = fmt.Sprintf("ALTER TABLE %s\nADD COLUMN %s %s%s%s",
tableName, ir.QuoteIdentifier(column.Name), columnType, clauses, inlineConstraint)
} else {
stmt = fmt.Sprintf("ALTER TABLE %s ADD COLUMN %s %s%s",
tableName, ir.QuoteIdentifier(column.Name), columnType, clauses)
}
context := &diffContext{
Type: DiffTypeTableColumn,
Operation: DiffOperationCreate,
Path: fmt.Sprintf("%s.%s.%s", td.Table.Schema, td.Table.Name, column.Name),
Source: column,
CanRunInTransaction: true,
}
collector.collect(context, stmt+";")
}
// Add comments for new columns
for _, column := range td.AddedColumns {
if column.Comment != "" {
tableName := getTableNameWithSchema(td.Table.Schema, td.Table.Name, targetSchema)
sql := fmt.Sprintf("COMMENT ON COLUMN %s.%s IS %s;", tableName, ir.QuoteIdentifier(column.Name), quoteString(column.Comment))
context := &diffContext{
Type: DiffTypeTableColumnComment,
Operation: DiffOperationCreate,
Path: fmt.Sprintf("%s.%s.%s", td.Table.Schema, td.Table.Name, column.Name),
Source: column,
CanRunInTransaction: true,
}
collector.collect(context, sql)
}
}
// Modify existing columns - already sorted by the Diff operation
for _, ColumnDiff := range td.ModifiedColumns {
// Generate column modification statements and collect as a single step
columnStatements := ColumnDiff.generateColumnSQL(td.Table.Schema, td.Table.Name, targetSchema)
// Emit separate diffs for each column operation
for _, stmt := range columnStatements {
context := &diffContext{
Type: DiffTypeTableColumn,
Operation: DiffOperationAlter,
Path: fmt.Sprintf("%s.%s.%s", td.Table.Schema, td.Table.Name, ColumnDiff.New.Name),
Source: ColumnDiff,
CanRunInTransaction: true,
}
collector.collect(context, stmt)
}
}
// Add new constraints - already sorted by the Diff operation
for _, constraint := range td.AddedConstraints {
// Skip constraints that were already added inline with columns
if inlineConstraints[constraint.Name] {
continue
}
switch constraint.Type {
case ir.ConstraintTypeUnique:
// Sort columns by position
columns := sortConstraintColumnsByPosition(constraint.Columns)
var columnNames []string
for _, col := range columns {
columnNames = append(columnNames, ir.QuoteIdentifier(col.Name))
}
if constraint.IsTemporal && len(columnNames) > 0 {
columnNames[len(columnNames)-1] = columnNames[len(columnNames)-1] + " WITHOUT OVERLAPS"
}
tableName := getTableNameWithSchema(td.Table.Schema, td.Table.Name, targetSchema)
sql := fmt.Sprintf("ALTER TABLE %s\nADD CONSTRAINT %s UNIQUE (%s);",
tableName, ir.QuoteIdentifier(constraint.Name), strings.Join(columnNames, ", "))
context := &diffContext{
Type: DiffTypeTableConstraint,
Operation: DiffOperationCreate,
Path: fmt.Sprintf("%s.%s.%s", td.Table.Schema, td.Table.Name, constraint.Name),
Source: constraint,
CanRunInTransaction: true,
}
collector.collect(context, sql)
case ir.ConstraintTypeCheck:
// Ensure CHECK clause has outer parentheses around the full expression
tableName := getTableNameWithSchema(td.Table.Schema, td.Table.Name, targetSchema)
clause := ensureCheckClauseParens(constraint.CheckClause)
suffix := ""
if constraint.NoInherit {
suffix += " NO INHERIT"
}
canonicalSQL := fmt.Sprintf("ALTER TABLE %s\nADD CONSTRAINT %s %s%s;",
tableName, ir.QuoteIdentifier(constraint.Name), clause, suffix)
context := &diffContext{
Type: DiffTypeTableConstraint,
Operation: DiffOperationCreate,
Path: fmt.Sprintf("%s.%s.%s", td.Table.Schema, td.Table.Name, constraint.Name),
Source: constraint,
CanRunInTransaction: true,
}
collector.collect(context, canonicalSQL)
case ir.ConstraintTypeForeignKey:
// Sort columns by position
columns := sortConstraintColumnsByPosition(constraint.Columns)
var columnNames []string
for _, col := range columns {
columnNames = append(columnNames, ir.QuoteIdentifier(col.Name))
}
if constraint.IsTemporal && len(columnNames) > 0 {
columnNames[len(columnNames)-1] = "PERIOD " + columnNames[len(columnNames)-1]
}
tableName := getTableNameWithSchema(td.Table.Schema, td.Table.Name, targetSchema)
canonicalSQL := fmt.Sprintf("ALTER TABLE %s\nADD CONSTRAINT %s FOREIGN KEY (%s) %s;",
tableName, ir.QuoteIdentifier(constraint.Name),
strings.Join(columnNames, ", "),
generateForeignKeyClause(constraint, targetSchema, false))
context := &diffContext{
Type: DiffTypeTableConstraint,
Operation: DiffOperationCreate,
Path: fmt.Sprintf("%s.%s.%s", td.Table.Schema, td.Table.Name, constraint.Name),
Source: constraint,
CanRunInTransaction: true,
}
collector.collect(context, canonicalSQL)
case ir.ConstraintTypePrimaryKey:
// Sort columns by position
columns := sortConstraintColumnsByPosition(constraint.Columns)
var columnNames []string
for _, col := range columns {
columnNames = append(columnNames, ir.QuoteIdentifier(col.Name))
}
if constraint.IsTemporal && len(columnNames) > 0 {
columnNames[len(columnNames)-1] = columnNames[len(columnNames)-1] + " WITHOUT OVERLAPS"
}
tableName := getTableNameWithSchema(td.Table.Schema, td.Table.Name, targetSchema)
sql := fmt.Sprintf("ALTER TABLE %s\nADD CONSTRAINT %s PRIMARY KEY (%s);",
tableName, ir.QuoteIdentifier(constraint.Name), strings.Join(columnNames, ", "))
context := &diffContext{
Type: DiffTypeTableConstraint,
Operation: DiffOperationCreate,
Path: fmt.Sprintf("%s.%s.%s", td.Table.Schema, td.Table.Name, constraint.Name),
Source: constraint,
CanRunInTransaction: true,
}
collector.collect(context, sql)
case ir.ConstraintTypeExclusion:
tableName := getTableNameWithSchema(td.Table.Schema, td.Table.Name, targetSchema)
sql := fmt.Sprintf("ALTER TABLE %s\nADD CONSTRAINT %s %s;",
tableName, ir.QuoteIdentifier(constraint.Name), constraint.ExclusionDefinition)
context := &diffContext{
Type: DiffTypeTableConstraint,
Operation: DiffOperationCreate,
Path: fmt.Sprintf("%s.%s.%s", td.Table.Schema, td.Table.Name, constraint.Name),
Source: constraint,
CanRunInTransaction: true,
}
collector.collect(context, sql)
}
}
// Handle modified constraints - drop and recreate them as separate operations
for _, ConstraintDiff := range td.ModifiedConstraints {
tableName := getTableNameWithSchema(td.Table.Schema, td.Table.Name, targetSchema)
constraint := ConstraintDiff.New
// Step 1: Drop the old constraint unless a dropped column already removes it. (#384)
if !constraintDroppedWithColumns(ConstraintDiff.Old, droppedColumnSet) {
dropSQL := fmt.Sprintf("ALTER TABLE %s DROP CONSTRAINT %s;", tableName, ir.QuoteIdentifier(ConstraintDiff.Old.Name))
dropContext := &diffContext{
Type: DiffTypeTableConstraint,
Operation: DiffOperationDrop,
Path: fmt.Sprintf("%s.%s.%s", td.Table.Schema, td.Table.Name, ConstraintDiff.Old.Name),
Source: ConstraintDiff.Old,
CanRunInTransaction: true,
}
collector.collect(dropContext, dropSQL)
}
// Step 2: Add new constraint
var addSQL string
switch constraint.Type {
case ir.ConstraintTypeUnique:
// Sort columns by position
columns := sortConstraintColumnsByPosition(constraint.Columns)
var columnNames []string