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
//! SQLite Column Alteration Tests
//!
//! These tests mirror the patterns from drizzle-orm's drizzle-kit/tests/sqlite/sqlite-columns.test.ts
//! They verify that column alterations generate proper table recreation SQL since SQLite
//! doesn't support ALTER COLUMN.
//!
//! SQLite has limited ALTER TABLE support:
//! - ADD COLUMN (with restrictions)
//! - DROP COLUMN (SQLite 3.35.0+)
//! - RENAME COLUMN
//!
//! For changes to column properties (type, notNull, default, autoincrement), we must
//! recreate the entire table using the "12-step" migration pattern:
//! 1. PRAGMA foreign_keys=OFF
//! 2. CREATE TABLE __new_tablename (with new schema)
//! 3. INSERT INTO __new_tablename SELECT ... FROM tablename
//! 4. DROP TABLE tablename
//! 5. ALTER TABLE __new_tablename RENAME TO tablename
//! 6. PRAGMA foreign_keys=ON

use std::borrow::Cow;

use drizzle_migrations::sqlite::{
    SQLiteDDL, compute_migration,
    ddl::{ColumnDef, ForeignKeyDef, IndexColumnDef, IndexDef, PrimaryKeyDef, TableDef},
    statements::JsonStatement,
};

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

/// Compute migration SQL statements from two DDL states
fn diff_sql(from: &SQLiteDDL, to: &SQLiteDDL) -> Vec<String> {
    let migration = compute_migration(from, to);
    migration.sql_statements
}

/// Check if migration has RecreateTable statement
fn has_recreate_table_statement(from: &SQLiteDDL, to: &SQLiteDDL) -> bool {
    let migration = compute_migration(from, to);
    migration
        .statements
        .iter()
        .any(|s| matches!(s, JsonStatement::RecreateTable(_)))
}

// =============================================================================
// ADD COLUMN Tests (matches drizzle-orm "add columns #1-6")
// =============================================================================

/// Test #1: Add single column NOT NULL
#[test]
fn test_add_column_not_null() {
    let mut from = SQLiteDDL::default();
    from.tables.push(TableDef::new("users").into_table());
    from.columns.push(
        ColumnDef::new("users", "id", "integer")
            .primary_key()
            .autoincrement()
            .into_column(),
    );

    let mut to = SQLiteDDL::default();
    to.tables.push(TableDef::new("users").into_table());
    to.columns.push(
        ColumnDef::new("users", "id", "integer")
            .primary_key()
            .autoincrement()
            .into_column(),
    );
    to.columns.push(
        ColumnDef::new("users", "name", "text")
            .not_null()
            .into_column(),
    );

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

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

/// Test #2: Add multiple columns
#[test]
fn test_add_multiple_columns() {
    let mut from = SQLiteDDL::default();
    from.tables.push(TableDef::new("users").into_table());
    from.columns.push(
        ColumnDef::new("users", "id", "integer")
            .primary_key()
            .autoincrement()
            .into_column(),
    );

    let mut to = SQLiteDDL::default();
    to.tables.push(TableDef::new("users").into_table());
    to.columns.push(
        ColumnDef::new("users", "id", "integer")
            .primary_key()
            .autoincrement()
            .into_column(),
    );
    to.columns
        .push(ColumnDef::new("users", "name", "text").into_column());
    to.columns
        .push(ColumnDef::new("users", "email", "text").into_column());

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

    assert_eq!(sql.len(), 2, "Expected 2 SQL statements, got: {:?}", sql);

    // Order may vary
    let has_name = sql
        .iter()
        .any(|s| *s == "ALTER TABLE `users` ADD `name` TEXT;");
    let has_email = sql
        .iter()
        .any(|s| *s == "ALTER TABLE `users` ADD `email` TEXT;");

    assert!(
        has_name,
        "Should have ALTER TABLE ADD `name`, got: {:?}",
        sql
    );
    assert!(
        has_email,
        "Should have ALTER TABLE ADD `email`, got: {:?}",
        sql
    );
}

/// Test #3: Add columns with various modifiers
#[test]
fn test_add_columns_with_modifiers() {
    let mut from = SQLiteDDL::default();
    from.tables.push(TableDef::new("users").into_table());
    from.columns.push(
        ColumnDef::new("users", "id", "integer")
            .primary_key()
            .autoincrement()
            .into_column(),
    );

    let mut to = SQLiteDDL::default();
    to.tables.push(TableDef::new("users").into_table());
    to.columns.push(
        ColumnDef::new("users", "id", "integer")
            .primary_key()
            .autoincrement()
            .into_column(),
    );
    to.columns.push(
        ColumnDef::new("users", "name1", "text")
            .default_value("'name'")
            .into_column(),
    );
    to.columns.push(
        ColumnDef::new("users", "name2", "text")
            .not_null()
            .into_column(),
    );
    to.columns.push(
        ColumnDef::new("users", "name3", "text")
            .default_value("'name'")
            .not_null()
            .into_column(),
    );

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

    assert_eq!(sql.len(), 3, "Expected 3 SQL statements, got: {:?}", sql);

    let has_name1 = sql
        .iter()
        .any(|s| *s == "ALTER TABLE `users` ADD `name1` TEXT DEFAULT 'name';");
    let has_name2 = sql
        .iter()
        .any(|s| *s == "ALTER TABLE `users` ADD `name2` TEXT NOT NULL;");
    let has_name3 = sql
        .iter()
        .any(|s| *s == "ALTER TABLE `users` ADD `name3` TEXT DEFAULT 'name' NOT NULL;");

    assert!(has_name1, "Should have name1 with DEFAULT, got: {:?}", sql);
    assert!(has_name2, "Should have name2 with NOT NULL, got: {:?}", sql);
    assert!(
        has_name3,
        "Should have name3 with DEFAULT and NOT NULL, got: {:?}",
        sql
    );
}

/// Test #6: Add column to table that already has unique column
#[test]
fn test_add_column_to_table_with_unique() {
    let mut from = SQLiteDDL::default();
    from.tables.push(TableDef::new("users").into_table());
    from.columns.push(
        ColumnDef::new("users", "id", "integer")
            .primary_key()
            .autoincrement()
            .into_column(),
    );
    from.columns
        .push(ColumnDef::new("users", "name", "text").into_column());
    from.columns.push(
        ColumnDef::new("users", "email", "text")
            .unique()
            .not_null()
            .into_column(),
    );

    let mut to = SQLiteDDL::default();
    to.tables.push(TableDef::new("users").into_table());
    to.columns.push(
        ColumnDef::new("users", "id", "integer")
            .primary_key()
            .autoincrement()
            .into_column(),
    );
    to.columns
        .push(ColumnDef::new("users", "name", "text").into_column());
    to.columns.push(
        ColumnDef::new("users", "email", "text")
            .unique()
            .not_null()
            .into_column(),
    );
    to.columns.push(
        ColumnDef::new("users", "password", "text")
            .not_null()
            .into_column(),
    );

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

    assert_eq!(sql.len(), 1, "Expected 1 SQL statement, got: {:?}", sql);
    assert_eq!(
        sql[0], "ALTER TABLE `users` ADD `password` TEXT NOT NULL;",
        "Unexpected ALTER TABLE ADD SQL"
    );
}

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

/// Test: Drop column
#[test]
fn test_drop_column() {
    let mut from = SQLiteDDL::default();
    from.tables.push(TableDef::new("users").into_table());
    from.columns.push(
        ColumnDef::new("users", "id", "integer")
            .primary_key()
            .autoincrement()
            .into_column(),
    );
    from.columns
        .push(ColumnDef::new("users", "name", "text").into_column());

    let mut to = SQLiteDDL::default();
    to.tables.push(TableDef::new("users").into_table());
    to.columns.push(
        ColumnDef::new("users", "id", "integer")
            .primary_key()
            .autoincrement()
            .into_column(),
    );

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

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

// =============================================================================
// ALTER COLUMN Tests - These require table recreation
// =============================================================================

/// Test: Alter column drop NOT NULL (make nullable)
#[test]
fn test_alter_column_drop_not_null() {
    let mut from = SQLiteDDL::default();
    from.tables.push(TableDef::new("table").into_table());
    from.columns.push(
        ColumnDef::new("table", "name", "text")
            .not_null()
            .into_column(),
    );

    let mut to = SQLiteDDL::default();
    to.tables.push(TableDef::new("table").into_table());
    to.columns
        .push(ColumnDef::new("table", "name", "text").into_column()); // nullable

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

    assert!(
        has_recreate_table_statement(&from, &to),
        "Expected RecreateTable statement"
    );

    // Verify the complete recreation sequence
    assert_eq!(
        sql.len(),
        6,
        "Expected 6 SQL statements for table recreation, got: {:?}",
        sql
    );
    assert_eq!(sql[0], "PRAGMA foreign_keys=OFF;");
    assert_eq!(sql[1], "CREATE TABLE `__new_table` (\n\t`name` TEXT\n);");
    assert_eq!(
        sql[2],
        "INSERT INTO `__new_table`(`name`) SELECT `name` FROM `table`;"
    );
    assert_eq!(sql[3], "DROP TABLE `table`;");
    assert_eq!(sql[4], "ALTER TABLE `__new_table` RENAME TO `table`;");
    assert_eq!(sql[5], "PRAGMA foreign_keys=ON;");
}

/// Test: Alter column add NOT NULL (make non-nullable)
#[test]
fn test_alter_column_add_not_null() {
    let mut from = SQLiteDDL::default();
    from.tables.push(TableDef::new("table").into_table());
    from.columns
        .push(ColumnDef::new("table", "name", "text").into_column()); // nullable

    let mut to = SQLiteDDL::default();
    to.tables.push(TableDef::new("table").into_table());
    to.columns.push(
        ColumnDef::new("table", "name", "text")
            .not_null()
            .into_column(),
    );

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

    assert_eq!(sql.len(), 6, "Expected 6 SQL statements, got: {:?}", sql);
    assert_eq!(sql[0], "PRAGMA foreign_keys=OFF;");
    assert_eq!(
        sql[1],
        "CREATE TABLE `__new_table` (\n\t`name` TEXT NOT NULL\n);"
    );
    assert_eq!(
        sql[2],
        "INSERT INTO `__new_table`(`name`) SELECT `name` FROM `table`;"
    );
    assert_eq!(sql[3], "DROP TABLE `table`;");
    assert_eq!(sql[4], "ALTER TABLE `__new_table` RENAME TO `table`;");
    assert_eq!(sql[5], "PRAGMA foreign_keys=ON;");
}

/// Test: Alter column add default
#[test]
fn test_alter_column_add_default() {
    let mut from = SQLiteDDL::default();
    from.tables.push(TableDef::new("table").into_table());
    from.columns
        .push(ColumnDef::new("table", "name", "text").into_column());

    let mut to = SQLiteDDL::default();
    to.tables.push(TableDef::new("table").into_table());
    to.columns.push(
        ColumnDef::new("table", "name", "text")
            .default_value("'dan'")
            .into_column(),
    );

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

    assert_eq!(sql.len(), 6, "Expected 6 SQL statements, got: {:?}", sql);
    assert_eq!(sql[0], "PRAGMA foreign_keys=OFF;");
    assert_eq!(
        sql[1],
        "CREATE TABLE `__new_table` (\n\t`name` TEXT DEFAULT 'dan'\n);"
    );
    assert_eq!(
        sql[2],
        "INSERT INTO `__new_table`(`name`) SELECT `name` FROM `table`;"
    );
    assert_eq!(sql[3], "DROP TABLE `table`;");
    assert_eq!(sql[4], "ALTER TABLE `__new_table` RENAME TO `table`;");
    assert_eq!(sql[5], "PRAGMA foreign_keys=ON;");
}

/// Test: Alter column drop default
#[test]
fn test_alter_column_drop_default() {
    let mut from = SQLiteDDL::default();
    from.tables.push(TableDef::new("table").into_table());
    from.columns.push(
        ColumnDef::new("table", "name", "text")
            .default_value("'dan'")
            .into_column(),
    );

    let mut to = SQLiteDDL::default();
    to.tables.push(TableDef::new("table").into_table());
    to.columns
        .push(ColumnDef::new("table", "name", "text").into_column());

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

    assert_eq!(sql.len(), 6, "Expected 6 SQL statements, got: {:?}", sql);
    assert_eq!(sql[0], "PRAGMA foreign_keys=OFF;");
    assert_eq!(sql[1], "CREATE TABLE `__new_table` (\n\t`name` TEXT\n);");
    assert_eq!(
        sql[2],
        "INSERT INTO `__new_table`(`name`) SELECT `name` FROM `table`;"
    );
    assert_eq!(sql[3], "DROP TABLE `table`;");
    assert_eq!(sql[4], "ALTER TABLE `__new_table` RENAME TO `table`;");
    assert_eq!(sql[5], "PRAGMA foreign_keys=ON;");
}

/// Test: Alter column add default and NOT NULL together
#[test]
fn test_alter_column_add_default_not_null() {
    let mut from = SQLiteDDL::default();
    from.tables.push(TableDef::new("table").into_table());
    from.columns
        .push(ColumnDef::new("table", "name", "text").into_column());

    let mut to = SQLiteDDL::default();
    to.tables.push(TableDef::new("table").into_table());
    to.columns.push(
        ColumnDef::new("table", "name", "text")
            .not_null()
            .default_value("'dan'")
            .into_column(),
    );

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

    assert_eq!(sql.len(), 6, "Expected 6 SQL statements, got: {:?}", sql);
    assert_eq!(sql[0], "PRAGMA foreign_keys=OFF;");
    assert_eq!(
        sql[1],
        "CREATE TABLE `__new_table` (\n\t`name` TEXT DEFAULT 'dan' NOT NULL\n);"
    );
    assert_eq!(
        sql[2],
        "INSERT INTO `__new_table`(`name`) SELECT `name` FROM `table`;"
    );
    assert_eq!(sql[3], "DROP TABLE `table`;");
    assert_eq!(sql[4], "ALTER TABLE `__new_table` RENAME TO `table`;");
    assert_eq!(sql[5], "PRAGMA foreign_keys=ON;");
}

/// Test: Alter column drop both default and NOT NULL
#[test]
fn test_alter_column_drop_default_not_null() {
    let mut from = SQLiteDDL::default();
    from.tables.push(TableDef::new("table").into_table());
    from.columns.push(
        ColumnDef::new("table", "name", "text")
            .not_null()
            .default_value("'dan'")
            .into_column(),
    );

    let mut to = SQLiteDDL::default();
    to.tables.push(TableDef::new("table").into_table());
    to.columns
        .push(ColumnDef::new("table", "name", "text").into_column());

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

    assert_eq!(sql.len(), 6, "Expected 6 SQL statements, got: {:?}", sql);
    assert_eq!(sql[0], "PRAGMA foreign_keys=OFF;");
    assert_eq!(sql[1], "CREATE TABLE `__new_table` (\n\t`name` TEXT\n);");
    assert_eq!(
        sql[2],
        "INSERT INTO `__new_table`(`name`) SELECT `name` FROM `table`;"
    );
    assert_eq!(sql[3], "DROP TABLE `table`;");
    assert_eq!(sql[4], "ALTER TABLE `__new_table` RENAME TO `table`;");
    assert_eq!(sql[5], "PRAGMA foreign_keys=ON;");
}

/// Test: Alter column type change
#[test]
fn test_alter_column_type_change() {
    let mut from = SQLiteDDL::default();
    from.tables.push(TableDef::new("users").into_table());
    from.columns
        .push(ColumnDef::new("users", "age", "text").into_column());

    let mut to = SQLiteDDL::default();
    to.tables.push(TableDef::new("users").into_table());
    to.columns
        .push(ColumnDef::new("users", "age", "integer").into_column());

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

    assert_eq!(sql.len(), 6, "Expected 6 SQL statements, got: {:?}", sql);
    assert_eq!(sql[0], "PRAGMA foreign_keys=OFF;");
    assert_eq!(sql[1], "CREATE TABLE `__new_users` (\n\t`age` INTEGER\n);");
    assert_eq!(
        sql[2],
        "INSERT INTO `__new_users`(`age`) SELECT `age` FROM `users`;"
    );
    assert_eq!(sql[3], "DROP TABLE `users`;");
    assert_eq!(sql[4], "ALTER TABLE `__new_users` RENAME TO `users`;");
    assert_eq!(sql[5], "PRAGMA foreign_keys=ON;");
}

/// Test: Drop autoincrement requires table recreation
#[test]
fn test_drop_autoincrement() {
    let mut from = SQLiteDDL::default();
    from.tables.push(TableDef::new("companies").into_table());
    from.columns.push(
        ColumnDef::new("companies", "id", "integer")
            .primary_key()
            .autoincrement()
            .into_column(),
    );
    from.columns
        .push(ColumnDef::new("companies", "name", "text").into_column());

    let mut to = SQLiteDDL::default();
    to.tables.push(TableDef::new("companies").into_table());
    to.columns.push(
        ColumnDef::new("companies", "id", "integer")
            .primary_key()
            .into_column(),
    );

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

    assert_eq!(sql.len(), 6, "Expected 6 SQL statements, got: {:?}", sql);
    assert_eq!(sql[0], "PRAGMA foreign_keys=OFF;");
    assert_eq!(
        sql[1],
        "CREATE TABLE `__new_companies` (\n\t`id` INTEGER PRIMARY KEY\n);"
    );
    assert_eq!(
        sql[2],
        "INSERT INTO `__new_companies`(`id`) SELECT `id` FROM `companies`;"
    );
    assert_eq!(sql[3], "DROP TABLE `companies`;");
    assert_eq!(
        sql[4],
        "ALTER TABLE `__new_companies` RENAME TO `companies`;"
    );
    assert_eq!(sql[5], "PRAGMA foreign_keys=ON;");
}

// =============================================================================
// FOREIGN KEY Tests - These require table recreation
// =============================================================================

/// Test: Add foreign key (requires table recreation)
#[test]
fn test_add_foreign_key() {
    let mut from = SQLiteDDL::default();
    from.tables.push(TableDef::new("users").into_table());
    from.columns.push(
        ColumnDef::new("users", "id", "integer")
            .primary_key()
            .autoincrement()
            .into_column(),
    );
    from.columns
        .push(ColumnDef::new("users", "report_to", "integer").into_column());

    let users = TableDef::new("users").into_table();
    let mut to = SQLiteDDL::default();
    to.tables.push(users);
    to.columns.push(
        ColumnDef::new("users", "id", "integer")
            .primary_key()
            .autoincrement()
            .into_column(),
    );
    to.columns
        .push(ColumnDef::new("users", "report_to", "integer").into_column());

    // Add self-referencing foreign key
    const FK_COLS: &[Cow<'static, str>] = &[Cow::Borrowed("report_to")];
    const FK_REFS: &[Cow<'static, str>] = &[Cow::Borrowed("id")];
    to.fks.push(
        ForeignKeyDef::new("users", "fk_users_report_to_users_id_fk")
            .columns(FK_COLS)
            .references("users", FK_REFS)
            .into_foreign_key(),
    );

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

    assert_eq!(sql.len(), 6, "Expected 6 SQL statements, got: {:?}", sql);
    assert_eq!(sql[0], "PRAGMA foreign_keys=OFF;");
    assert_eq!(
        sql[1],
        "CREATE TABLE `__new_users` (\n\t`id` INTEGER PRIMARY KEY AUTOINCREMENT,\n\t`report_to` INTEGER,\n\tCONSTRAINT `fk_users_report_to_users_id_fk` FOREIGN KEY (`report_to`) REFERENCES `users`(`id`)\n);"
    );
    assert_eq!(
        sql[2],
        "INSERT INTO `__new_users`(`id`, `report_to`) SELECT `id`, `report_to` FROM `users`;"
    );
    assert_eq!(sql[3], "DROP TABLE `users`;");
    assert_eq!(sql[4], "ALTER TABLE `__new_users` RENAME TO `users`;");
    assert_eq!(sql[5], "PRAGMA foreign_keys=ON;");
}

// =============================================================================
// PRIMARY KEY Tests - These require table recreation
// =============================================================================

/// Test: Add composite primary key (requires table recreation)
#[test]
fn test_add_composite_pk() {
    let mut from = SQLiteDDL::default();
    from.tables.push(TableDef::new("table").into_table());
    from.columns
        .push(ColumnDef::new("table", "id1", "integer").into_column());
    from.columns
        .push(ColumnDef::new("table", "id2", "integer").into_column());

    let mut to = SQLiteDDL::default();
    to.tables.push(TableDef::new("table").into_table());
    to.columns
        .push(ColumnDef::new("table", "id1", "integer").into_column());
    to.columns
        .push(ColumnDef::new("table", "id2", "integer").into_column());

    // Add composite primary key
    const PK_COLS: &[Cow<'static, str>] = &[Cow::Borrowed("id1"), Cow::Borrowed("id2")];
    to.pks.push(
        PrimaryKeyDef::new("table", "table_pk")
            .columns(PK_COLS)
            .into_primary_key(),
    );

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

    assert_eq!(sql.len(), 6, "Expected 6 SQL statements, got: {:?}", sql);
    assert_eq!(sql[0], "PRAGMA foreign_keys=OFF;");
    assert_eq!(
        sql[1],
        "CREATE TABLE `__new_table` (\n\t`id1` INTEGER,\n\t`id2` INTEGER,\n\tCONSTRAINT `table_pk` PRIMARY KEY(`id1`, `id2`)\n);"
    );
    assert_eq!(
        sql[2],
        "INSERT INTO `__new_table`(`id1`, `id2`) SELECT `id1`, `id2` FROM `table`;"
    );
    assert_eq!(sql[3], "DROP TABLE `table`;");
    assert_eq!(sql[4], "ALTER TABLE `__new_table` RENAME TO `table`;");
    assert_eq!(sql[5], "PRAGMA foreign_keys=ON;");
}

// =============================================================================
// Generated Column Tests
// =============================================================================

/// Test: Add generated stored column (requires table recreation)
#[test]
fn test_add_generated_stored_column() {
    let mut from = SQLiteDDL::default();
    from.tables.push(TableDef::new("users").into_table());
    from.columns
        .push(ColumnDef::new("users", "id", "integer").into_column());

    let mut to = SQLiteDDL::default();
    to.tables.push(TableDef::new("users").into_table());
    to.columns
        .push(ColumnDef::new("users", "id", "integer").into_column());
    to.columns.push(
        ColumnDef::new("users", "gen_name", "text")
            .generated_stored("123")
            .into_column(),
    );

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

    assert_eq!(sql.len(), 6, "Expected 6 SQL statements, got: {:?}", sql);
    assert_eq!(sql[0], "PRAGMA foreign_keys=OFF;");
    assert_eq!(
        sql[1],
        "CREATE TABLE `__new_users` (\n\t`id` INTEGER,\n\t`gen_name` TEXT GENERATED ALWAYS AS (123) STORED\n);"
    );
    assert_eq!(
        sql[2],
        "INSERT INTO `__new_users`(`id`) SELECT `id` FROM `users`;"
    );
    assert_eq!(sql[3], "DROP TABLE `users`;");
    assert_eq!(sql[4], "ALTER TABLE `__new_users` RENAME TO `users`;");
    assert_eq!(sql[5], "PRAGMA foreign_keys=ON;");
}

/// Test: Add generated virtual column (can use ALTER TABLE ADD)
#[test]
fn test_add_generated_virtual_column() {
    let mut from = SQLiteDDL::default();
    from.tables.push(TableDef::new("users").into_table());
    from.columns
        .push(ColumnDef::new("users", "id", "integer").into_column());

    let mut to = SQLiteDDL::default();
    to.tables.push(TableDef::new("users").into_table());
    to.columns
        .push(ColumnDef::new("users", "id", "integer").into_column());
    to.columns.push(
        ColumnDef::new("users", "gen_name", "text")
            .generated_virtual("123")
            .into_column(),
    );

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

    assert_eq!(
        sql.len(),
        1,
        "Virtual columns can be added via ALTER TABLE ADD"
    );
    assert_eq!(
        sql[0],
        "ALTER TABLE `users` ADD `gen_name` TEXT GENERATED ALWAYS AS (123) VIRTUAL;"
    );
}

// =============================================================================
// Combined alteration tests (multiple tables)
// =============================================================================

/// Test: Alter multiple tables simultaneously
#[test]
fn test_alter_column_multiple_tables() {
    let mut from = SQLiteDDL::default();
    from.tables.push(TableDef::new("users").into_table());
    from.columns.push(
        ColumnDef::new("users", "id", "integer")
            .primary_key()
            .autoincrement()
            .into_column(),
    );
    from.columns.push(
        ColumnDef::new("users", "name", "text")
            .not_null()
            .into_column(),
    );

    from.tables.push(TableDef::new("posts").into_table());
    from.columns.push(
        ColumnDef::new("posts", "id", "integer")
            .primary_key()
            .autoincrement()
            .into_column(),
    );
    from.columns
        .push(ColumnDef::new("posts", "name", "text").into_column());
    from.columns
        .push(ColumnDef::new("posts", "user_id", "integer").into_column());

    let mut to = SQLiteDDL::default();
    // users: make name nullable
    to.tables.push(TableDef::new("users").into_table());
    to.columns.push(
        ColumnDef::new("users", "id", "integer")
            .primary_key()
            .autoincrement()
            .into_column(),
    );
    to.columns
        .push(ColumnDef::new("users", "name", "text").into_column()); // nullable now

    // posts: make name NOT NULL
    to.tables.push(TableDef::new("posts").into_table());
    to.columns.push(
        ColumnDef::new("posts", "id", "integer")
            .primary_key()
            .autoincrement()
            .into_column(),
    );
    to.columns.push(
        ColumnDef::new("posts", "name", "text")
            .not_null()
            .into_column(),
    ); // NOT NULL now
    to.columns
        .push(ColumnDef::new("posts", "user_id", "integer").into_column());

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

    // Both tables are recreated: 6 statements per table = 12 total.
    // Recreations are emitted in sorted table order (posts before users), so
    // the whole sequence is deterministic and asserted exactly.
    assert_eq!(
        sql,
        vec![
            // posts recreation
            "PRAGMA foreign_keys=OFF;",
            "CREATE TABLE `__new_posts` (\n\t`id` INTEGER PRIMARY KEY AUTOINCREMENT,\n\t`name` TEXT NOT NULL,\n\t`user_id` INTEGER\n);",
            "INSERT INTO `__new_posts`(`id`, `name`, `user_id`) SELECT `id`, `name`, `user_id` FROM `posts`;",
            "DROP TABLE `posts`;",
            "ALTER TABLE `__new_posts` RENAME TO `posts`;",
            "PRAGMA foreign_keys=ON;",
            // users recreation
            "PRAGMA foreign_keys=OFF;",
            "CREATE TABLE `__new_users` (\n\t`id` INTEGER PRIMARY KEY AUTOINCREMENT,\n\t`name` TEXT\n);",
            "INSERT INTO `__new_users`(`id`, `name`) SELECT `id`, `name` FROM `users`;",
            "DROP TABLE `users`;",
            "ALTER TABLE `__new_users` RENAME TO `users`;",
            "PRAGMA foreign_keys=ON;",
        ]
    );
}

// =============================================================================
// Data Preservation Tests
// =============================================================================

/// Test: Recreation preserves data columns
#[test]
fn test_recreate_preserves_columns() {
    let mut from = SQLiteDDL::default();
    from.tables.push(TableDef::new("users").into_table());
    from.columns
        .push(ColumnDef::new("users", "id", "integer").into_column());
    from.columns
        .push(ColumnDef::new("users", "name", "text").into_column());
    from.columns
        .push(ColumnDef::new("users", "age", "integer").into_column());

    let mut to = SQLiteDDL::default();
    to.tables.push(TableDef::new("users").into_table());
    to.columns
        .push(ColumnDef::new("users", "id", "integer").into_column());
    to.columns.push(
        ColumnDef::new("users", "name", "text")
            .not_null()
            .into_column(),
    ); // Change
    to.columns
        .push(ColumnDef::new("users", "age", "integer").into_column());

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

    assert_eq!(sql.len(), 6, "Expected 6 SQL statements, got: {:?}", sql);
    assert_eq!(sql[0], "PRAGMA foreign_keys=OFF;");
    assert_eq!(
        sql[1],
        "CREATE TABLE `__new_users` (\n\t`id` INTEGER,\n\t`name` TEXT NOT NULL,\n\t`age` INTEGER\n);"
    );
    assert_eq!(
        sql[2],
        "INSERT INTO `__new_users`(`id`, `name`, `age`) SELECT `id`, `name`, `age` FROM `users`;"
    );
    assert_eq!(sql[3], "DROP TABLE `users`;");
    assert_eq!(sql[4], "ALTER TABLE `__new_users` RENAME TO `users`;");
    assert_eq!(sql[5], "PRAGMA foreign_keys=ON;");
}

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

/// Test: Indexes are recreated after table recreation
#[test]
fn test_recreate_with_indexes() {
    let mut from = SQLiteDDL::default();
    from.tables.push(TableDef::new("table").into_table());
    from.columns
        .push(ColumnDef::new("table", "name", "text").into_column());

    const IDX_COLS: &[IndexColumnDef] = &[IndexColumnDef::new("name")];
    from.indexes.push(
        IndexDef::new("table", "index_name")
            .columns(IDX_COLS)
            .into_index(),
    );

    let mut to = SQLiteDDL::default();
    to.tables.push(TableDef::new("table").into_table());
    to.columns.push(
        ColumnDef::new("table", "name", "text")
            .not_null()
            .default_value("'dan'")
            .into_column(),
    );

    const IDX_COLS2: &[IndexColumnDef] = &[IndexColumnDef::new("name")];
    to.indexes.push(
        IndexDef::new("table", "index_name")
            .columns(IDX_COLS2)
            .into_index(),
    );

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

    assert_eq!(sql.len(), 7, "Expected 7 SQL statements, got: {:?}", sql);
    assert_eq!(sql[0], "PRAGMA foreign_keys=OFF;");
    assert_eq!(
        sql[1],
        "CREATE TABLE `__new_table` (\n\t`name` TEXT DEFAULT 'dan' NOT NULL\n);"
    );
    assert_eq!(
        sql[2],
        "INSERT INTO `__new_table`(`name`) SELECT `name` FROM `table`;"
    );
    assert_eq!(sql[3], "DROP TABLE `table`;");
    assert_eq!(sql[4], "ALTER TABLE `__new_table` RENAME TO `table`;");
    assert_eq!(sql[5], "PRAGMA foreign_keys=ON;");
    assert_eq!(sql[6], "CREATE INDEX `index_name` ON `table`(`name`);");
}

// =============================================================================
// Edge Cases
// =============================================================================

/// Test: No changes produces no SQL
#[test]
fn test_no_changes_no_sql() {
    let mut schema = SQLiteDDL::default();
    schema.tables.push(TableDef::new("users").into_table());
    schema.columns.push(
        ColumnDef::new("users", "id", "integer")
            .primary_key()
            .into_column(),
    );
    schema.columns.push(
        ColumnDef::new("users", "name", "text")
            .not_null()
            .into_column(),
    );

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

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

/// Test: Recreate table with nested references
#[test]
fn test_recreate_table_with_nested_references() {
    // Create schema with nested FK references:
    // subscriptions_metadata -> subscriptions -> users

    let mut from = SQLiteDDL::default();

    // Users table
    from.tables.push(TableDef::new("users").into_table());
    from.columns.push(
        ColumnDef::new("users", "id", "integer")
            .primary_key()
            .autoincrement()
            .into_column(),
    );
    from.columns
        .push(ColumnDef::new("users", "name", "text").into_column());
    from.columns
        .push(ColumnDef::new("users", "age", "integer").into_column());

    // Subscriptions table
    from.tables
        .push(TableDef::new("subscriptions").into_table());
    from.columns.push(
        ColumnDef::new("subscriptions", "id", "integer")
            .primary_key()
            .autoincrement()
            .into_column(),
    );
    from.columns
        .push(ColumnDef::new("subscriptions", "user_id", "integer").into_column());
    from.columns
        .push(ColumnDef::new("subscriptions", "customer_id", "text").into_column());

    // Subscriptions metadata table
    from.tables
        .push(TableDef::new("subscriptions_metadata").into_table());
    from.columns.push(
        ColumnDef::new("subscriptions_metadata", "id", "integer")
            .primary_key()
            .autoincrement()
            .into_column(),
    );
    from.columns
        .push(ColumnDef::new("subscriptions_metadata", "subscription_id", "text").into_column());

    // Add FK: subscriptions.user_id -> users.id
    const SUB_FK_COLS: &[Cow<'static, str>] = &[Cow::Borrowed("user_id")];
    const SUB_FK_REFS: &[Cow<'static, str>] = &[Cow::Borrowed("id")];
    from.fks.push(
        ForeignKeyDef::new("subscriptions", "fk_subscriptions_user_id_users_id_fk")
            .columns(SUB_FK_COLS)
            .references("users", SUB_FK_REFS)
            .into_foreign_key(),
    );

    // Add FK: subscriptions_metadata.subscription_id -> subscriptions.id
    const META_FK_COLS: &[Cow<'static, str>] = &[Cow::Borrowed("subscription_id")];
    const META_FK_REFS: &[Cow<'static, str>] = &[Cow::Borrowed("id")];
    from.fks.push(
        ForeignKeyDef::new(
            "subscriptions_metadata",
            "fk_subscriptions_metadata_subscription_id_subscriptions_id_fk",
        )
        .columns(META_FK_COLS)
        .references("subscriptions", META_FK_REFS)
        .into_foreign_key(),
    );

    // Create "to" schema: change users.id autoincrement to false
    let mut to = from.clone();
    // Find and update the users id column
    for col in to.columns.list_mut() {
        if col.table == "users" && col.name == "id" {
            col.autoincrement = None; // Remove autoincrement
        }
    }

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

    assert_eq!(sql.len(), 6, "Expected 6 SQL statements, got: {:?}", sql);
    assert_eq!(sql[0], "PRAGMA foreign_keys=OFF;");
    assert_eq!(
        sql[1],
        "CREATE TABLE `__new_users` (\n\t`id` INTEGER PRIMARY KEY,\n\t`name` TEXT,\n\t`age` INTEGER\n);"
    );
    assert_eq!(
        sql[2],
        "INSERT INTO `__new_users`(`id`, `name`, `age`) SELECT `id`, `name`, `age` FROM `users`;"
    );
    assert_eq!(sql[3], "DROP TABLE `users`;");
    assert_eq!(sql[4], "ALTER TABLE `__new_users` RENAME TO `users`;");
    assert_eq!(sql[5], "PRAGMA foreign_keys=ON;");
}