drizzle-migrations 0.1.16

Migration infrastructure for drizzle-rs
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
//! PostgreSQL Column Alteration Tests
//!
//! These tests verify that column alterations generate proper SQL statements.
//! Unlike SQLite, PostgreSQL supports ALTER COLUMN for most changes:
//! - SET NOT NULL / DROP NOT NULL
//! - SET DATA TYPE
//! - SET DEFAULT / DROP DEFAULT
//! - DROP EXPRESSION
//!
//! Only adding generated expressions requires column recreation (drop + add).

use drizzle_migrations::postgres::{
    PostgresDDL,
    collection::diff_ddl,
    ddl::{
        Column, ForeignKey, Generated, GeneratedType, Identity, Index, IndexColumn, PrimaryKey,
        Table, UniqueConstraint,
    },
    statements::Generator as PostgresGenerator,
};
use std::borrow::Cow;

// =============================================================================
// Helper Functions
// =============================================================================

/// Generate SQL statements from the diff between two DDL states
fn diff_to_sql(from: &PostgresDDL, to: &PostgresDDL) -> Vec<String> {
    let diffs = diff_ddl(from, to);
    let generator = PostgresGenerator::new().with_breakpoints(false);
    generator.generate(&diffs)
}

/// Normalize a CREATE TABLE statement by sorting the column definition lines.
fn normalize_create_table(sql: &str) -> String {
    let Some(paren_start) = sql.find("(\n\t") else {
        return sql.to_string();
    };
    let header = &sql[..paren_start + 1];
    let body = &sql[paren_start + 3..sql.len() - 3];
    let mut lines: Vec<&str> = body.split(",\n\t").collect();
    lines.sort();
    format!("{}\n\t{}\n);", header, lines.join(",\n\t"))
}

/// Helper to create a basic column
fn column(table: &str, name: &str, sql_type: &str) -> Column {
    Column {
        schema: Cow::Borrowed("public"),
        table: Cow::Owned(table.to_string()),
        name: Cow::Owned(name.to_string()),
        sql_type: Cow::Owned(sql_type.to_string()),
        type_schema: None,
        not_null: false,
        default: None,
        generated: None,
        identity: None,
        dimensions: None,
        comment: None,
        collate: None,
        ordinal_position: None,
    }
}

/// Helper to create a NOT NULL column
fn column_not_null(table: &str, name: &str, sql_type: &str) -> Column {
    Column {
        not_null: true,
        ..column(table, name, sql_type)
    }
}

/// Helper to create a column with default
fn column_default(table: &str, name: &str, sql_type: &str, default: &str) -> Column {
    Column {
        default: Some(Cow::Owned(default.to_string())),
        ..column(table, name, sql_type)
    }
}

/// Helper to create a table
fn table(name: &str) -> Table {
    Table {
        schema: Cow::Borrowed("public"),
        name: Cow::Owned(name.to_string()),
        is_unlogged: None,
        is_temporary: None,
        inherits: None,
        tablespace: None,
        is_rls_enabled: None,
        comment: None,
    }
}

/// Helper to create a primary key
fn primary_key(table_name: &str, columns: Vec<&str>) -> PrimaryKey {
    let pk_name = format!("{}_pkey", table_name);
    PrimaryKey::from_strings(
        "public".to_string(),
        table_name.to_string(),
        pk_name,
        columns.into_iter().map(|s| s.to_string()).collect(),
    )
}

/// Helper to create a foreign key
fn foreign_key(
    table_name: &str,
    name: &str,
    columns: Vec<&str>,
    ref_table: &str,
    ref_columns: Vec<&str>,
) -> ForeignKey {
    ForeignKey::from_strings(
        "public".to_string(),
        table_name.to_string(),
        name.to_string(),
        columns.into_iter().map(|s| s.to_string()).collect(),
        "public".to_string(),
        ref_table.to_string(),
        ref_columns.into_iter().map(|s| s.to_string()).collect(),
    )
}

/// Helper to create an index
fn index(table_name: &str, name: &str, columns: Vec<&str>) -> Index {
    Index {
        schema: Cow::Borrowed("public"),
        table: Cow::Owned(table_name.to_string()),
        name: Cow::Owned(name.to_string()),
        name_explicit: false,
        columns: columns
            .into_iter()
            .map(|c| IndexColumn {
                value: Cow::Owned(c.to_string()),
                is_expression: false,
                asc: true,
                nulls_first: false,
                opclass: None,
            })
            .collect(),
        method: None,
        is_unique: false,
        concurrently: false,
        where_clause: None,
        with: None,
    }
}

/// Helper to create a unique constraint
fn unique_constraint(table_name: &str, name: &str, columns: Vec<&str>) -> UniqueConstraint {
    UniqueConstraint::from_strings(
        "public".to_string(),
        table_name.to_string(),
        name.to_string(),
        columns.into_iter().map(|s| s.to_string()).collect(),
    )
}

// =============================================================================
// ADD COLUMN Tests
// =============================================================================

/// Test: Add single column NOT NULL (uses ALTER TABLE ADD COLUMN)
#[test]
fn test_add_column_not_null() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer"));
    from.pks.push(primary_key("users", vec!["id"]));

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    to.columns.push(column_not_null("users", "id", "integer"));
    to.columns.push(column_not_null("users", "name", "text"));
    to.pks.push(primary_key("users", vec!["id"]));

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 1, "Expected 1 SQL statement, got: {:?}", sql);
    assert_eq!(
        sql[0],
        "ALTER TABLE \"users\" ADD COLUMN \"name\" text NOT NULL;"
    );
}

/// Test: Add multiple columns
#[test]
fn test_add_multiple_columns() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer"));
    from.pks.push(primary_key("users", vec!["id"]));

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    to.columns.push(column_not_null("users", "id", "integer"));
    to.columns.push(column("users", "name", "text"));
    to.columns.push(column("users", "email", "text"));
    to.pks.push(primary_key("users", vec!["id"]));

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 2, "Expected 2 SQL statements, got: {:?}", sql);
    let mut sorted = sql.clone();
    sorted.sort();
    assert_eq!(
        sorted,
        vec![
            "ALTER TABLE \"users\" ADD COLUMN \"email\" text;",
            "ALTER TABLE \"users\" ADD COLUMN \"name\" text;",
        ],
        "Unexpected ADD COLUMN statements: {:?}",
        sql
    );
}

/// Test: Add column with default
#[test]
fn test_add_column_with_default() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer"));
    from.pks.push(primary_key("users", vec!["id"]));

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    to.columns.push(column_not_null("users", "id", "integer"));
    to.columns
        .push(column_default("users", "status", "text", "'active'"));
    to.pks.push(primary_key("users", vec!["id"]));

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 1, "Expected 1 SQL statement, got: {:?}", sql);
    assert_eq!(
        sql[0],
        "ALTER TABLE \"users\" ADD COLUMN \"status\" text DEFAULT 'active';"
    );
}

// =============================================================================
// DROP COLUMN Tests
// =============================================================================

/// Test: Drop column (uses ALTER TABLE DROP COLUMN)
#[test]
fn test_drop_column() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer"));
    from.columns.push(column("users", "name", "text"));
    from.pks.push(primary_key("users", vec!["id"]));

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    to.columns.push(column_not_null("users", "id", "integer"));
    to.pks.push(primary_key("users", vec!["id"]));

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 1, "Expected 1 SQL statement, got: {:?}", sql);
    assert_eq!(sql[0], "ALTER TABLE \"users\" DROP COLUMN \"name\";");
}

// =============================================================================
// ALTER COLUMN Tests - PostgreSQL uses ALTER TABLE ALTER COLUMN
// =============================================================================

/// Test: Alter column add NOT NULL (uses SET NOT NULL)
#[test]
fn test_alter_column_add_not_null() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer"));
    from.columns.push(column("users", "email", "text")); // nullable
    from.pks.push(primary_key("users", vec!["id"]));

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    to.columns.push(column_not_null("users", "id", "integer"));
    to.columns.push(column_not_null("users", "email", "text")); // NOT NULL
    to.pks.push(primary_key("users", vec!["id"]));

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 1, "Expected 1 SQL statement, got: {:?}", sql);
    assert_eq!(
        sql[0],
        "ALTER TABLE \"users\" ALTER COLUMN \"email\" SET NOT NULL;"
    );
}

/// Test: Alter column drop NOT NULL (uses DROP NOT NULL)
#[test]
fn test_alter_column_drop_not_null() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer"));
    from.columns.push(column_not_null("users", "email", "text")); // NOT NULL
    from.pks.push(primary_key("users", vec!["id"]));

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    to.columns.push(column_not_null("users", "id", "integer"));
    to.columns.push(column("users", "email", "text")); // nullable
    to.pks.push(primary_key("users", vec!["id"]));

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 1, "Expected 1 SQL statement, got: {:?}", sql);
    assert_eq!(
        sql[0],
        "ALTER TABLE \"users\" ALTER COLUMN \"email\" DROP NOT NULL;"
    );
}

/// Test: Alter column add default (uses SET DEFAULT)
#[test]
fn test_alter_column_add_default() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer"));
    from.columns.push(column("users", "status", "text")); // no default
    from.pks.push(primary_key("users", vec!["id"]));

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    to.columns.push(column_not_null("users", "id", "integer"));
    to.columns
        .push(column_default("users", "status", "text", "'active'")); // with default
    to.pks.push(primary_key("users", vec!["id"]));

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 1, "Expected 1 SQL statement, got: {:?}", sql);
    assert_eq!(
        sql[0],
        "ALTER TABLE \"users\" ALTER COLUMN \"status\" SET DEFAULT 'active';"
    );
}

/// Test: Alter column drop default (uses DROP DEFAULT)
#[test]
fn test_alter_column_drop_default() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer"));
    from.columns
        .push(column_default("users", "status", "text", "'active'")); // with default
    from.pks.push(primary_key("users", vec!["id"]));

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    to.columns.push(column_not_null("users", "id", "integer"));
    to.columns.push(column("users", "status", "text")); // no default
    to.pks.push(primary_key("users", vec!["id"]));

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 1, "Expected 1 SQL statement, got: {:?}", sql);
    assert_eq!(
        sql[0],
        "ALTER TABLE \"users\" ALTER COLUMN \"status\" DROP DEFAULT;"
    );
}

/// Test: Alter column type change (uses SET DATA TYPE)
#[test]
fn test_alter_column_type_change() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer"));
    from.columns.push(column("users", "age", "text")); // text
    from.pks.push(primary_key("users", vec!["id"]));

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    to.columns.push(column_not_null("users", "id", "integer"));
    to.columns.push(column("users", "age", "integer")); // integer
    to.pks.push(primary_key("users", vec!["id"]));

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 1, "Expected 1 SQL statement, got: {:?}", sql);
    assert_eq!(
        sql[0],
        "ALTER TABLE \"users\" ALTER COLUMN \"age\" SET DATA TYPE integer USING \"age\"::integer;"
    );
}

#[test]
fn test_alter_column_array_dimension_change() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column("users", "scores", "integer"));

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    let mut scores = column("users", "scores", "integer");
    scores.dimensions = Some(1);
    to.columns.push(scores);

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 1, "Expected 1 SQL statement, got: {:?}", sql);
    assert_eq!(
        sql[0],
        "ALTER TABLE \"users\" ALTER COLUMN \"scores\" SET DATA TYPE integer[] USING \"scores\"::integer[];"
    );
}

#[test]
fn test_column_comment_change_and_removal() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    let mut from_email = column("users", "email", "text");
    from_email.comment = Some(Cow::Borrowed("Old comment"));
    from.columns.push(from_email);

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    let mut to_email = column("users", "email", "text");
    to_email.comment = Some(Cow::Borrowed("It's new"));
    to.columns.push(to_email);

    let sql = diff_to_sql(&from, &to);
    assert_eq!(
        sql,
        vec!["COMMENT ON COLUMN \"users\".\"email\" IS 'It''s new';"]
    );

    let mut removed = PostgresDDL::new();
    removed.tables.push(table("users"));
    removed.columns.push(column("users", "email", "text"));
    let sql = diff_to_sql(&to, &removed);
    assert_eq!(sql, vec!["COMMENT ON COLUMN \"users\".\"email\" IS NULL;"]);
}

/// Test: Alter column multiple properties at once
#[test]
fn test_alter_column_multiple_changes() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer"));
    from.columns.push(column("users", "status", "text")); // nullable, no default
    from.pks.push(primary_key("users", vec!["id"]));

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    to.columns.push(column_not_null("users", "id", "integer"));
    // NOT NULL + default
    let mut status_col = column_default("users", "status", "text", "'pending'");
    status_col.not_null = true;
    to.columns.push(status_col);
    to.pks.push(primary_key("users", vec!["id"]));

    let sql = diff_to_sql(&from, &to);

    // Multiple changes come back as one statement per command so drivers
    // can execute each through a prepared statement.
    assert_eq!(sql.len(), 2, "Expected 2 SQL statements, got: {:?}", sql);
    assert_eq!(
        sql[0],
        "ALTER TABLE \"users\" ALTER COLUMN \"status\" SET NOT NULL;"
    );
    assert_eq!(
        sql[1],
        "ALTER TABLE \"users\" ALTER COLUMN \"status\" SET DEFAULT 'pending';"
    );
}

// =============================================================================
// Generated Column Tests - Adding generated expressions requires column recreation
// =============================================================================

/// Test: Add generated stored column to new table (inline in CREATE TABLE)
#[test]
fn test_create_table_with_generated_column() {
    let from = PostgresDDL::new();

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    to.columns.push(column_not_null("users", "id", "integer"));
    to.columns.push(column("users", "first_name", "text"));
    to.columns.push(column("users", "last_name", "text"));

    // Generated column
    let mut full_name = column("users", "full_name", "text");
    full_name.generated = Some(Generated {
        expression: Cow::Borrowed("first_name || ' ' || last_name"),
        gen_type: GeneratedType::Stored,
    });
    to.columns.push(full_name);
    to.pks.push(primary_key("users", vec!["id"]));

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 1, "Expected 1 SQL statement, got: {:?}", sql);
    // Column order may vary, so normalize
    let expected = "CREATE TABLE \"users\" (\n\
        \t\"id\" integer NOT NULL,\n\
        \t\"first_name\" text,\n\
        \t\"last_name\" text,\n\
        \t\"full_name\" text GENERATED ALWAYS AS (first_name || ' ' || last_name) STORED,\n\
        \tPRIMARY KEY(\"id\")\n\
        );";
    assert_eq!(
        normalize_create_table(&sql[0]),
        normalize_create_table(expected),
        "Unexpected CREATE TABLE with generated column SQL: {}",
        sql[0]
    );
}

#[test]
fn test_create_table_with_virtual_generated_column() {
    let from = PostgresDDL::new();

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    to.columns.push(column_not_null("users", "id", "integer"));
    to.columns.push(column("users", "name", "text"));

    let mut name_len = column("users", "name_len", "integer");
    name_len.generated = Some(Generated {
        expression: Cow::Borrowed("length(name)"),
        gen_type: GeneratedType::Virtual,
    });
    to.columns.push(name_len);
    to.pks.push(primary_key("users", vec!["id"]));

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 1, "Expected 1 SQL statement, got: {:?}", sql);
    let expected = "CREATE TABLE \"users\" (\n\
        \t\"id\" integer NOT NULL,\n\
        \t\"name\" text,\n\
        \t\"name_len\" integer GENERATED ALWAYS AS (length(name)) VIRTUAL,\n\
        \tPRIMARY KEY(\"id\")\n\
        );";
    assert_eq!(
        normalize_create_table(&sql[0]),
        normalize_create_table(expected),
        "Unexpected CREATE TABLE with virtual generated column SQL: {}",
        sql[0]
    );
}

/// Test: Adding generated expression to existing column requires DROP+ADD
#[test]
fn test_alter_column_add_generated_expression() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer"));
    from.columns.push(column("users", "first_name", "text"));
    from.columns.push(column("users", "last_name", "text"));
    from.columns.push(column("users", "full_name", "text")); // Regular column
    from.pks.push(primary_key("users", vec!["id"]));

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    to.columns.push(column_not_null("users", "id", "integer"));
    to.columns.push(column("users", "first_name", "text"));
    to.columns.push(column("users", "last_name", "text"));

    // full_name is now a generated column
    let mut full_name = column("users", "full_name", "text");
    full_name.generated = Some(Generated {
        expression: Cow::Borrowed("first_name || ' ' || last_name"),
        gen_type: GeneratedType::Stored,
    });
    to.columns.push(full_name);
    to.pks.push(primary_key("users", vec!["id"]));

    let sql = diff_to_sql(&from, &to);

    // DROP + ADD come back as separate single-command statements.
    assert_eq!(sql.len(), 2, "Expected 2 SQL statements, got: {:?}", sql);
    assert_eq!(sql[0], "ALTER TABLE \"users\" DROP COLUMN \"full_name\";");
    assert_eq!(
        sql[1],
        "ALTER TABLE \"users\" ADD COLUMN \"full_name\" text GENERATED ALWAYS AS (first_name || ' ' || last_name) STORED;"
    );
}

/// Test: Drop generated expression (uses DROP EXPRESSION)
#[test]
fn test_alter_column_drop_generated_expression() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer"));
    from.columns.push(column("users", "first_name", "text"));
    from.columns.push(column("users", "last_name", "text"));

    // Generated column
    let mut full_name = column("users", "full_name", "text");
    full_name.generated = Some(Generated {
        expression: Cow::Borrowed("first_name || ' ' || last_name"),
        gen_type: GeneratedType::Stored,
    });
    from.columns.push(full_name);
    from.pks.push(primary_key("users", vec!["id"]));

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    to.columns.push(column_not_null("users", "id", "integer"));
    to.columns.push(column("users", "first_name", "text"));
    to.columns.push(column("users", "last_name", "text"));
    to.columns.push(column("users", "full_name", "text")); // Now regular column
    to.pks.push(primary_key("users", vec!["id"]));

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 1, "Expected 1 SQL statement, got: {:?}", sql);
    assert_eq!(
        sql[0],
        "ALTER TABLE \"users\" ALTER COLUMN \"full_name\" DROP EXPRESSION;"
    );
}

// =============================================================================
// Identity Column Tests
// =============================================================================

/// Test: Add identity to column
#[test]
fn test_alter_column_add_identity() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer")); // no identity
    from.pks.push(primary_key("users", vec!["id"]));

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));

    let mut id_col = column_not_null("users", "id", "integer");
    id_col.identity = Some(Identity::always("users_id_seq").schema("public"));
    to.columns.push(id_col);
    to.pks.push(primary_key("users", vec!["id"]));

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 1, "Expected 1 SQL statement, got: {:?}", sql);
    assert_eq!(
        sql[0],
        "ALTER TABLE \"users\" ALTER COLUMN \"id\" ADD GENERATED ALWAYS AS IDENTITY;"
    );
}

/// Test: Drop identity from column
#[test]
fn test_alter_column_drop_identity() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));

    let mut id_col = column_not_null("users", "id", "integer");
    id_col.identity = Some(Identity::always("users_id_seq").schema("public"));
    from.columns.push(id_col);
    from.pks.push(primary_key("users", vec!["id"]));

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    to.columns.push(column_not_null("users", "id", "integer")); // no identity
    to.pks.push(primary_key("users", vec!["id"]));

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 1, "Expected 1 SQL statement, got: {:?}", sql);
    assert_eq!(
        sql[0],
        "ALTER TABLE \"users\" ALTER COLUMN \"id\" DROP IDENTITY;"
    );
}

// =============================================================================
// Constraint Tests - PostgreSQL uses ALTER TABLE ADD/DROP CONSTRAINT
// =============================================================================

/// Test: Add foreign key to existing table
#[test]
fn test_add_foreign_key() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer"));
    from.pks.push(primary_key("users", vec!["id"]));

    from.tables.push(table("posts"));
    from.columns.push(column_not_null("posts", "id", "integer"));
    from.columns.push(column("posts", "author_id", "integer"));
    from.pks.push(primary_key("posts", vec!["id"]));

    let mut to = from.clone();
    to.fks.push(foreign_key(
        "posts",
        "posts_author_fk",
        vec!["author_id"],
        "users",
        vec!["id"],
    ));

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 1, "Expected 1 SQL statement, got: {:?}", sql);
    assert_eq!(
        sql[0],
        "ALTER TABLE \"posts\" ADD CONSTRAINT \"posts_author_fk\" FOREIGN KEY (\"author_id\") REFERENCES \"users\"(\"id\");"
    );
}

/// Test: Drop foreign key
#[test]
fn test_drop_foreign_key() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer"));
    from.pks.push(primary_key("users", vec!["id"]));

    from.tables.push(table("posts"));
    from.columns.push(column_not_null("posts", "id", "integer"));
    from.columns.push(column("posts", "author_id", "integer"));
    from.pks.push(primary_key("posts", vec!["id"]));
    from.fks.push(foreign_key(
        "posts",
        "posts_author_fk",
        vec!["author_id"],
        "users",
        vec!["id"],
    ));

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    to.columns.push(column_not_null("users", "id", "integer"));
    to.pks.push(primary_key("users", vec!["id"]));

    to.tables.push(table("posts"));
    to.columns.push(column_not_null("posts", "id", "integer"));
    to.columns.push(column("posts", "author_id", "integer"));
    to.pks.push(primary_key("posts", vec!["id"]));
    // No FK in "to"

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 1, "Expected 1 SQL statement, got: {:?}", sql);
    assert_eq!(
        sql[0],
        "ALTER TABLE \"posts\" DROP CONSTRAINT \"posts_author_fk\";"
    );
}

/// Test: Change foreign key deferrability (drop + recreate)
#[test]
fn test_foreign_key_deferrability_change_recreates_constraint() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer"));
    from.pks.push(primary_key("users", vec!["id"]));

    from.tables.push(table("posts"));
    from.columns.push(column_not_null("posts", "id", "integer"));
    from.columns.push(column("posts", "author_id", "integer"));
    from.pks.push(primary_key("posts", vec!["id"]));
    from.fks.push(foreign_key(
        "posts",
        "posts_author_fk",
        vec!["author_id"],
        "users",
        vec!["id"],
    ));

    let mut to = from.clone();
    to.fks.list_mut()[0].deferrable = true;
    to.fks.list_mut()[0].initially_deferred = true;

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 2, "Expected 2 SQL statements, got: {:?}", sql);
    assert_eq!(
        sql[0],
        "ALTER TABLE \"posts\" DROP CONSTRAINT \"posts_author_fk\";"
    );
    assert_eq!(
        sql[1],
        "ALTER TABLE \"posts\" ADD CONSTRAINT \"posts_author_fk\" FOREIGN KEY (\"author_id\") REFERENCES \"users\"(\"id\") DEFERRABLE INITIALLY DEFERRED;"
    );
}

/// Test: Add primary key to existing table
#[test]
fn test_add_primary_key() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer"));
    from.columns.push(column("users", "name", "text"));
    // No PK

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    to.columns.push(column_not_null("users", "id", "integer"));
    to.columns.push(column("users", "name", "text"));
    to.pks.push(primary_key("users", vec!["id"])); // Add PK

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 1, "Expected 1 SQL statement, got: {:?}", sql);
    assert_eq!(
        sql[0],
        "ALTER TABLE \"users\" ADD CONSTRAINT \"users_pkey\" PRIMARY KEY(\"id\");"
    );
}

/// Test: Drop primary key
#[test]
fn test_drop_primary_key() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer"));
    from.columns.push(column("users", "name", "text"));
    from.pks.push(primary_key("users", vec!["id"]));

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    to.columns.push(column_not_null("users", "id", "integer"));
    to.columns.push(column("users", "name", "text"));
    // No PK

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 1, "Expected 1 SQL statement, got: {:?}", sql);
    assert_eq!(
        sql[0],
        "ALTER TABLE \"users\" DROP CONSTRAINT \"users_pkey\";"
    );
}

/// Test: Add unique constraint
#[test]
fn test_add_unique_constraint() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer"));
    from.columns.push(column("users", "email", "text"));
    from.pks.push(primary_key("users", vec!["id"]));

    let mut to = from.clone();
    to.uniques.push(unique_constraint(
        "users",
        "users_email_unique",
        vec!["email"],
    ));

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 1, "Expected 1 SQL statement, got: {:?}", sql);
    assert_eq!(
        sql[0],
        "ALTER TABLE \"users\" ADD CONSTRAINT \"users_email_unique\" UNIQUE (\"email\");"
    );
}

/// Test: Drop unique constraint
#[test]
fn test_drop_unique_constraint() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer"));
    from.columns.push(column("users", "email", "text"));
    from.pks.push(primary_key("users", vec!["id"]));
    from.uniques.push(unique_constraint(
        "users",
        "users_email_unique",
        vec!["email"],
    ));

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    to.columns.push(column_not_null("users", "id", "integer"));
    to.columns.push(column("users", "email", "text"));
    to.pks.push(primary_key("users", vec!["id"]));
    // No unique constraint

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 1, "Expected 1 SQL statement, got: {:?}", sql);
    assert_eq!(
        sql[0],
        "ALTER TABLE \"users\" DROP CONSTRAINT \"users_email_unique\";"
    );
}

/// Test: Change unique constraint deferrability (drop + recreate)
#[test]
fn test_unique_constraint_deferrability_change_recreates_constraint() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer"));
    from.columns.push(column("users", "email", "text"));
    from.pks.push(primary_key("users", vec!["id"]));
    from.uniques.push(unique_constraint(
        "users",
        "users_email_unique",
        vec!["email"],
    ));

    let mut to = from.clone();
    to.uniques.list_mut()[0].deferrable = true;
    to.uniques.list_mut()[0].initially_deferred = true;

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 2, "Expected 2 SQL statements, got: {:?}", sql);
    assert_eq!(
        sql[0],
        "ALTER TABLE \"users\" DROP CONSTRAINT \"users_email_unique\";"
    );
    assert_eq!(
        sql[1],
        "ALTER TABLE \"users\" ADD CONSTRAINT \"users_email_unique\" UNIQUE (\"email\") DEFERRABLE INITIALLY DEFERRED;"
    );
}

// =============================================================================
// Index Tests
// =============================================================================

/// Test: Add index to existing table
#[test]
fn test_add_index() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer"));
    from.columns.push(column("users", "email", "text"));
    from.pks.push(primary_key("users", vec!["id"]));

    let mut to = from.clone();
    to.indexes
        .push(index("users", "users_email_idx", vec!["email"]));

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 1, "Expected 1 SQL statement, got: {:?}", sql);
    assert_eq!(
        sql[0],
        "CREATE INDEX \"users_email_idx\" ON \"users\"(\"email\");"
    );
}

/// Test: Drop index
#[test]
fn test_drop_index() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer"));
    from.columns.push(column("users", "email", "text"));
    from.pks.push(primary_key("users", vec!["id"]));
    from.indexes
        .push(index("users", "users_email_idx", vec!["email"]));

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    to.columns.push(column_not_null("users", "id", "integer"));
    to.columns.push(column("users", "email", "text"));
    to.pks.push(primary_key("users", vec!["id"]));
    // No index

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 1, "Expected 1 SQL statement, got: {:?}", sql);
    assert_eq!(sql[0], "DROP INDEX \"users_email_idx\";");
}

// =============================================================================
// Edge Cases and No-Op Tests
// =============================================================================

/// Test: No changes produces no SQL
#[test]
fn test_no_changes_no_sql() {
    let mut schema = PostgresDDL::new();
    schema.tables.push(table("users"));
    schema
        .columns
        .push(column_not_null("users", "id", "integer"));
    schema
        .columns
        .push(column_not_null("users", "name", "text"));
    schema.pks.push(primary_key("users", vec!["id"]));

    let sql = diff_to_sql(&schema, &schema.clone());

    assert!(
        sql.is_empty(),
        "Expected no SQL for identical schemas, got: {:?}",
        sql
    );
}

/// Test: Multiple tables with different changes
#[test]
fn test_multiple_tables_different_changes() {
    let mut from = PostgresDDL::new();
    // users table
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer"));
    from.columns.push(column("users", "email", "text")); // nullable
    from.pks.push(primary_key("users", vec!["id"]));
    // posts table
    from.tables.push(table("posts"));
    from.columns.push(column_not_null("posts", "id", "integer"));
    from.columns.push(column_not_null("posts", "title", "text"));
    from.pks.push(primary_key("posts", vec!["id"]));

    let mut to = PostgresDDL::new();
    // users: make email NOT NULL
    to.tables.push(table("users"));
    to.columns.push(column_not_null("users", "id", "integer"));
    to.columns.push(column_not_null("users", "email", "text")); // NOT NULL now
    to.pks.push(primary_key("users", vec!["id"]));
    // posts: add a column
    to.tables.push(table("posts"));
    to.columns.push(column_not_null("posts", "id", "integer"));
    to.columns.push(column_not_null("posts", "title", "text"));
    to.columns.push(column("posts", "content", "text")); // new column
    to.pks.push(primary_key("posts", vec!["id"]));

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 2, "Expected 2 SQL statements, got: {:?}", sql);
    let mut sorted = sql.clone();
    sorted.sort();
    assert_eq!(
        sorted,
        vec![
            "ALTER TABLE \"posts\" ADD COLUMN \"content\" text;",
            "ALTER TABLE \"users\" ALTER COLUMN \"email\" SET NOT NULL;",
        ],
        "Unexpected multi-table alteration statements: {:?}",
        sql
    );
}

/// Test: Custom schema table alterations
#[test]
fn test_custom_schema_alterations() {
    let mut from = PostgresDDL::new();
    from.tables.push(Table {
        schema: Cow::Borrowed("myschema"),
        name: Cow::Borrowed("users"),
        is_unlogged: None,
        is_temporary: None,
        inherits: None,
        tablespace: None,
        is_rls_enabled: None,
        comment: None,
    });
    from.columns.push(Column {
        schema: Cow::Borrowed("myschema"),
        table: Cow::Borrowed("users"),
        name: Cow::Borrowed("id"),
        sql_type: Cow::Borrowed("integer"),
        type_schema: None,
        not_null: true,
        default: None,
        generated: None,
        identity: None,
        dimensions: None,
        comment: None,
        collate: None,
        ordinal_position: None,
    });

    let mut to = from.clone();
    to.columns.push(Column {
        schema: Cow::Borrowed("myschema"),
        table: Cow::Borrowed("users"),
        name: Cow::Borrowed("name"),
        sql_type: Cow::Borrowed("text"),
        type_schema: None,
        not_null: false,
        default: None,
        generated: None,
        identity: None,
        dimensions: None,
        comment: None,
        collate: None,
        ordinal_position: None,
    });

    let sql = diff_to_sql(&from, &to);

    assert_eq!(sql.len(), 1, "Expected 1 SQL statement, got: {:?}", sql);
    assert_eq!(
        sql[0],
        "ALTER TABLE \"myschema\".\"users\" ADD COLUMN \"name\" text;"
    );
}

// =============================================================================
// Identity modification (SET GENERATED / SET <option> / DROP IDENTITY)
// =============================================================================

/// Changing the identity kind on an existing identity column must emit
/// `SET GENERATED ...`, never the invalid `ADD GENERATED ...`.
#[test]
fn test_alter_identity_kind_uses_set_generated() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    let mut old_col = column_not_null("users", "id", "integer");
    old_col.identity = Some(Identity::always("users_id_seq").schema("public"));
    from.columns.push(old_col);

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    let mut new_col = column_not_null("users", "id", "integer");
    new_col.identity = Some(Identity::by_default("users_id_seq").schema("public"));
    to.columns.push(new_col);

    let sql = diff_to_sql(&from, &to);
    assert_eq!(
        sql,
        vec!["ALTER TABLE \"users\" ALTER COLUMN \"id\" SET GENERATED BY DEFAULT;".to_string()]
    );
}

/// Changing sequence options on an existing identity column emits the
/// corresponding `SET <option>` clauses.
#[test]
fn test_alter_identity_options_uses_set_clauses() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    let mut old_col = column_not_null("users", "id", "integer");
    old_col.identity = Some(Identity::always("users_id_seq").schema("public"));
    from.columns.push(old_col);

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    let mut new_col = column_not_null("users", "id", "integer");
    let mut identity = Identity::always("users_id_seq").schema("public");
    identity.increment = Some(Cow::Borrowed("10"));
    identity.max_value = Some(Cow::Borrowed("5000"));
    identity.cycle = Some(true);
    new_col.identity = Some(identity);
    to.columns.push(new_col);

    let sql = diff_to_sql(&from, &to);
    assert_eq!(
        sql,
        vec![
            "ALTER TABLE \"users\" ALTER COLUMN \"id\" SET INCREMENT BY 10 SET MAXVALUE 5000 SET CYCLE;"
                .to_string()
        ]
    );
}

/// Adding an identity to a plain column still uses `ADD GENERATED`.
#[test]
fn test_alter_identity_add_still_uses_add_generated() {
    let mut from = PostgresDDL::new();
    from.tables.push(table("users"));
    from.columns.push(column_not_null("users", "id", "integer"));

    let mut to = PostgresDDL::new();
    to.tables.push(table("users"));
    let mut new_col = column_not_null("users", "id", "integer");
    let mut identity = Identity::always("users_id_seq").schema("public");
    identity.start_with = Some(Cow::Borrowed("100"));
    new_col.identity = Some(identity);
    to.columns.push(new_col);

    let sql = diff_to_sql(&from, &to);
    assert_eq!(
        sql,
        vec![
            "ALTER TABLE \"users\" ALTER COLUMN \"id\" ADD GENERATED ALWAYS AS IDENTITY (START WITH 100);"
                .to_string()
        ]
    );
}