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
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
//! Schema diff types and logic for `SQLite` v7 DDL format
//!
//! This module provides diffing between DDL collections and
//! generates migration statements from schema changes.

use super::SQLiteSnapshot;
use super::collection::{DiffType, EntityDiff, SQLiteDDL, diff_ddl};
use super::ddl::SqliteEntity;
use super::statements::{
    AddColumnStatement, CreateIndexStatement, CreateTableStatement, CreateViewStatement,
    DropColumnStatement, DropIndexStatement, DropTableStatement, DropViewStatement, JsonStatement,
    RecreateTableStatement, RenameColumnStatement, RenameTableStatement, TableFull, from_json,
};
use crate::traits::EntityKind;
use std::collections::{BTreeMap, BTreeSet, HashSet};

// Re-export diff types from collection
pub use super::collection::{DiffType as SchemaDiffType, EntityDiff as SchemaEntityDiff};

/// Complete schema diff between two snapshots
#[derive(Debug, Clone, Default)]
pub struct SchemaDiff {
    /// All entity diffs
    pub diffs: Vec<EntityDiff>,
}

impl SchemaDiff {
    /// Check if there are any changes
    #[must_use]
    pub const fn has_changes(&self) -> bool {
        !self.diffs.is_empty()
    }

    /// Check if this diff is empty (no changes)
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.diffs.is_empty()
    }

    /// Get created entities
    #[must_use]
    pub fn created(&self) -> Vec<&EntityDiff> {
        self.diffs
            .iter()
            .filter(|d| d.diff_type == DiffType::Create)
            .collect()
    }

    /// Get dropped entities
    #[must_use]
    pub fn dropped(&self) -> Vec<&EntityDiff> {
        self.diffs
            .iter()
            .filter(|d| d.diff_type == DiffType::Drop)
            .collect()
    }

    /// Get altered entities
    #[must_use]
    pub fn altered(&self) -> Vec<&EntityDiff> {
        self.diffs
            .iter()
            .filter(|d| d.diff_type == DiffType::Alter)
            .collect()
    }

    /// Get diffs filtered by entity kind
    #[must_use]
    pub fn by_kind(&self, kind: EntityKind) -> Vec<&EntityDiff> {
        self.diffs.iter().filter(|d| d.kind == kind).collect()
    }

    /// Get created tables
    #[must_use]
    pub fn created_tables(&self) -> Vec<&EntityDiff> {
        self.diffs
            .iter()
            .filter(|d| d.diff_type == DiffType::Create && d.kind == EntityKind::Table)
            .collect()
    }

    /// Get dropped tables
    #[must_use]
    pub fn dropped_tables(&self) -> Vec<&EntityDiff> {
        self.diffs
            .iter()
            .filter(|d| d.diff_type == DiffType::Drop && d.kind == EntityKind::Table)
            .collect()
    }
}

/// Compare two `SQLite` snapshots and return the diff
#[must_use]
pub fn diff_snapshots(prev: &SQLiteSnapshot, cur: &SQLiteSnapshot) -> SchemaDiff {
    let prev_ddl = SQLiteDDL::from_entities(prev.ddl.clone());
    let cur_ddl = SQLiteDDL::from_entities(cur.ddl.clone());

    SchemaDiff {
        diffs: diff_ddl(&prev_ddl, &cur_ddl),
    }
}

/// Compare two DDL collections directly
#[must_use]
pub fn diff_collections(prev: &SQLiteDDL, cur: &SQLiteDDL) -> SchemaDiff {
    SchemaDiff {
        diffs: diff_ddl(prev, cur),
    }
}

// =============================================================================
// Migration Diff Result
// =============================================================================

/// A table rename operation
#[derive(Debug, Clone)]
pub struct TableRename {
    pub from: String,
    pub to: String,
}

/// A column rename operation
#[derive(Debug, Clone)]
pub struct ColumnRename {
    pub table: String,
    pub from: String,
    pub to: String,
}

/// Result of computing a migration diff
#[derive(Debug, Clone, Default)]
pub struct MigrationDiff {
    /// JSON statements for the migration
    pub statements: Vec<JsonStatement>,
    /// Generated SQL statements
    pub sql_statements: Vec<String>,
    /// Renames that occurred (for tracking in snapshot)
    pub renames: Vec<String>,
    /// Warning messages
    pub warnings: Vec<String>,
}

/// Build a `TableFull` from DDL for a given table name
#[must_use]
pub fn table_from_ddl(table_name: &str, ddl: &SQLiteDDL) -> TableFull {
    let entities = ddl.table_entities(table_name);

    // Get table-level options (strict, without_rowid)
    let (strict, without_rowid) = ddl
        .tables
        .one(table_name)
        .map_or((false, false), |t| (t.strict, t.without_rowid));

    TableFull {
        name: table_name.to_string(),
        columns: entities.columns.into_iter().cloned().collect(),
        pk: entities.pk.cloned(),
        fks: entities.fks.into_iter().cloned().collect(),
        uniques: entities.uniques.into_iter().cloned().collect(),
        checks: entities.checks.into_iter().cloned().collect(),
        strict,
        without_rowid,
    }
}

fn entity_table_name(entity: &SqliteEntity) -> Option<String> {
    match entity {
        SqliteEntity::Column(c) => Some(c.table.to_string()),
        SqliteEntity::ForeignKey(fk) => Some(fk.table.to_string()),
        SqliteEntity::PrimaryKey(pk) => Some(pk.table.to_string()),
        SqliteEntity::UniqueConstraint(uc) => Some(uc.table.to_string()),
        SqliteEntity::CheckConstraint(cc) => Some(cc.table.to_string()),
        _ => None,
    }
}

fn collect_tables_to_recreate(
    schema_diff: &SchemaDiff,
    created: &HashSet<String>,
    dropped: &HashSet<String>,
) -> BTreeSet<String> {
    // BTreeSet: iteration order reaches the emitted SQL, so it must be
    // deterministic.
    let mut out: BTreeSet<String> = BTreeSet::new();

    // Table-level option changes (STRICT / WITHOUT ROWID) can only be applied
    // by recreating the table.
    for table_diff in schema_diff.by_kind(EntityKind::Table) {
        if table_diff.diff_type == DiffType::Alter
            && let Some(SqliteEntity::Table(table)) = &table_diff.right
            && !created.contains(table.name.as_ref())
            && !dropped.contains(table.name.as_ref())
        {
            out.insert(table.name.to_string());
        }
    }

    // Column alterations trigger recreation (SQLite has no ALTER COLUMN).
    for col_diff in schema_diff.by_kind(EntityKind::Column) {
        if col_diff.diff_type == DiffType::Alter
            && let Some(SqliteEntity::Column(col)) = &col_diff.right
            && !created.contains(col.table.as_ref())
            && !dropped.contains(col.table.as_ref())
        {
            out.insert(col.table.to_string());
        }
    }

    // New STORED generated columns - SQLite doesn't allow ALTER TABLE ADD COLUMN for STORED
    // See: https://www.sqlite.org/gencol.html
    for col_diff in schema_diff.by_kind(EntityKind::Column) {
        if col_diff.diff_type == DiffType::Create
            && let Some(SqliteEntity::Column(col)) = &col_diff.right
            && col
                .generated
                .as_ref()
                .is_some_and(|g| g.gen_type == super::ddl::GeneratedType::Stored)
            && !created.contains(col.table.as_ref())
            && !dropped.contains(col.table.as_ref())
        {
            out.insert(col.table.to_string());
        }
    }

    // FK, PK, unique, check constraint changes all require recreation.
    for kind in [
        EntityKind::ForeignKey,
        EntityKind::PrimaryKey,
        EntityKind::UniqueConstraint,
        EntityKind::CheckConstraint,
    ] {
        for diff in schema_diff.by_kind(kind) {
            if !matches!(
                diff.diff_type,
                DiffType::Create | DiffType::Drop | DiffType::Alter
            ) {
                continue;
            }
            let table = diff
                .right
                .as_ref()
                .and_then(entity_table_name)
                .or_else(|| diff.left.as_ref().and_then(entity_table_name));
            if let Some(table) = table
                && !created.contains(&table)
                && !dropped.contains(&table)
            {
                out.insert(table);
            }
        }
    }

    out
}

/// Compute a full migration diff between two DDL states
///
/// This is a simplified version of the TypeScript ddlDiff function.
/// For a fully interactive migration with rename detection, you would
/// need to provide resolver callbacks.
#[must_use]
pub fn compute_migration(prev: &SQLiteDDL, cur: &SQLiteDDL) -> MigrationDiff {
    // Heuristic rename detection (non-interactive):
    // - detect exact table renames (same schema, identical entities)
    // - detect exact column renames (same table, identical column properties)
    let mut prev_normalized = prev.clone();
    let mut rename_statements: Vec<JsonStatement> = Vec::new();
    let mut table_renames: Vec<TableRename> = Vec::new();
    let mut column_renames: Vec<ColumnRename> = Vec::new();
    let mut warnings = Vec::new();

    detect_and_apply_renames(
        &mut prev_normalized,
        cur,
        &mut rename_statements,
        &mut table_renames,
        &mut column_renames,
        &mut warnings,
    );

    let schema_diff = diff_collections(&prev_normalized, cur);
    let mut statements = Vec::new();
    let renames = prepare_migration_renames(&table_renames, &column_renames);

    // Emit rename statements first so subsequent diffs apply to the renamed schema.
    statements.extend(rename_statements);

    // Track created/dropped table names
    let created_table_names: HashSet<String> = schema_diff
        .created_tables()
        .iter()
        .map(|d| d.name.clone())
        .collect();

    let dropped_table_names: HashSet<String> = schema_diff
        .dropped_tables()
        .iter()
        .map(|d| d.name.clone())
        .collect();

    // Collect tables that need recreation due to column alterations
    // SQLite doesn't support ALTER COLUMN, so we need to recreate the table
    let tables_to_recreate =
        collect_tables_to_recreate(&schema_diff, &created_table_names, &dropped_table_names);

    append_table_create_recreate_stmts(
        &mut statements,
        &schema_diff,
        prev,
        cur,
        &tables_to_recreate,
    );
    append_add_column_stmts(
        &mut statements,
        &schema_diff,
        cur,
        &created_table_names,
        &tables_to_recreate,
    );
    append_index_stmts(&mut statements, &schema_diff, cur, &tables_to_recreate);
    append_drop_column_and_view_stmts(
        &mut statements,
        &schema_diff,
        &dropped_table_names,
        &tables_to_recreate,
    );
    append_drop_table_stmts(&mut statements, &schema_diff);
    collect_stored_generated_warnings(&mut warnings, &schema_diff);

    // Convert to SQL
    let result = from_json(statements.clone());

    MigrationDiff {
        statements,
        sql_statements: result.sql_statements,
        renames,
        warnings,
    }
}

fn append_table_create_recreate_stmts(
    statements: &mut Vec<JsonStatement>,
    schema_diff: &SchemaDiff,
    prev: &SQLiteDDL,
    cur: &SQLiteDDL,
    tables_to_recreate: &BTreeSet<String>,
) {
    // 1. Create tables
    for table_diff in schema_diff.created_tables() {
        if let Some(SqliteEntity::Table(table)) = &table_diff.right {
            let table_full = table_from_ddl(&table.name, cur);
            statements.push(JsonStatement::CreateTable(CreateTableStatement {
                table: table_full,
            }));
        }
    }

    // 2. Recreate tables that have column alterations
    for table_name in tables_to_recreate {
        let from_table = table_from_ddl(table_name, prev);
        let to_table = table_from_ddl(table_name, cur);
        statements.push(JsonStatement::RecreateTable(RecreateTableStatement {
            from: from_table,
            to: to_table,
            data: None,
        }));
    }
}

fn append_add_column_stmts(
    statements: &mut Vec<JsonStatement>,
    schema_diff: &SchemaDiff,
    cur: &SQLiteDDL,
    created_table_names: &HashSet<String>,
    tables_to_recreate: &BTreeSet<String>,
) {
    // 3. Add columns (for existing tables only, skip tables being recreated)
    for col_diff in schema_diff.by_kind(EntityKind::Column) {
        if col_diff.diff_type == DiffType::Create
            && let Some(SqliteEntity::Column(col)) = &col_diff.right
            // Skip columns for newly created tables
            && !created_table_names.contains(col.table.as_ref())
            // Skip columns for tables being recreated
            && !tables_to_recreate.contains(col.table.as_ref())
        {
            // Find associated FK if any
            let fk = cur
                .fks
                .for_table(&col.table)
                .into_iter()
                .find(|fk| fk.columns.len() == 1 && fk.columns[0] == col.name)
                .cloned();

            statements.push(JsonStatement::AddColumn(AddColumnStatement {
                column: col.clone(),
                fk,
            }));
        }
    }
}

fn append_index_stmts(
    statements: &mut Vec<JsonStatement>,
    schema_diff: &SchemaDiff,
    cur: &SQLiteDDL,
    tables_to_recreate: &BTreeSet<String>,
) {
    // 4. Drop indexes (skip tables being recreated - indexes will be recreated with table)
    for idx_diff in schema_diff.by_kind(EntityKind::Index) {
        if idx_diff.diff_type == DiffType::Drop
            && let Some(SqliteEntity::Index(idx)) = &idx_diff.left
            && !tables_to_recreate.contains(idx.table.as_ref())
        {
            statements.push(JsonStatement::DropIndex(DropIndexStatement {
                index: idx.clone(),
            }));
        }
    }

    // 5. Create indexes (including for newly created tables, skip tables being recreated)
    for idx_diff in schema_diff.by_kind(EntityKind::Index) {
        if idx_diff.diff_type == DiffType::Create
            && let Some(SqliteEntity::Index(idx)) = &idx_diff.right
            && !tables_to_recreate.contains(idx.table.as_ref())
        {
            statements.push(JsonStatement::CreateIndex(CreateIndexStatement {
                index: idx.clone(),
            }));
        }
    }

    // 5b. Recreate indexes for tables that were recreated
    // When a table is recreated, all its indexes are dropped, so we need to recreate them
    for table_name in tables_to_recreate {
        for idx in cur.indexes.for_table(table_name) {
            statements.push(JsonStatement::CreateIndex(CreateIndexStatement {
                index: idx.clone(),
            }));
        }
    }

    // 6. Alter indexes (drop old, create new, skip tables being recreated)
    for idx_diff in schema_diff.by_kind(EntityKind::Index) {
        if idx_diff.diff_type == DiffType::Alter {
            if let Some(SqliteEntity::Index(old_idx)) = &idx_diff.left
                && !tables_to_recreate.contains(old_idx.table.as_ref())
            {
                statements.push(JsonStatement::DropIndex(DropIndexStatement {
                    index: old_idx.clone(),
                }));
            }
            if let Some(SqliteEntity::Index(new_idx)) = &idx_diff.right
                && !tables_to_recreate.contains(new_idx.table.as_ref())
            {
                statements.push(JsonStatement::CreateIndex(CreateIndexStatement {
                    index: new_idx.clone(),
                }));
            }
        }
    }
}

fn append_drop_column_and_view_stmts(
    statements: &mut Vec<JsonStatement>,
    schema_diff: &SchemaDiff,
    dropped_table_names: &HashSet<String>,
    tables_to_recreate: &BTreeSet<String>,
) {
    // 7. Drop columns (for non-dropped tables, skip tables being recreated)
    for col_diff in schema_diff.by_kind(EntityKind::Column) {
        if col_diff.diff_type == DiffType::Drop
            && let Some(SqliteEntity::Column(col)) = &col_diff.left
            // Skip columns for dropped tables
            && !dropped_table_names.contains(col.table.as_ref())
            // Skip columns for tables being recreated
            && !tables_to_recreate.contains(col.table.as_ref())
        {
            statements.push(JsonStatement::DropColumn(DropColumnStatement {
                column: col.clone(),
            }));
        }
    }

    // 8. Drop views
    for view_diff in schema_diff.by_kind(EntityKind::View) {
        if view_diff.diff_type == DiffType::Drop
            && let Some(SqliteEntity::View(view)) = &view_diff.left
            && !view.is_existing
        {
            statements.push(JsonStatement::DropView(DropViewStatement {
                view: view.clone(),
            }));
        }
    }

    // 9. Create views
    for view_diff in schema_diff.by_kind(EntityKind::View) {
        if view_diff.diff_type == DiffType::Create
            && let Some(SqliteEntity::View(view)) = &view_diff.right
            && !view.is_existing
        {
            statements.push(JsonStatement::CreateView(CreateViewStatement {
                view: view.clone(),
            }));
        }
    }

    // 10. Alter views (drop and recreate)
    for view_diff in schema_diff.by_kind(EntityKind::View) {
        if view_diff.diff_type == DiffType::Alter {
            if let Some(SqliteEntity::View(old_view)) = &view_diff.left {
                statements.push(JsonStatement::DropView(DropViewStatement {
                    view: old_view.clone(),
                }));
            }
            if let Some(SqliteEntity::View(new_view)) = &view_diff.right {
                statements.push(JsonStatement::CreateView(CreateViewStatement {
                    view: new_view.clone(),
                }));
            }
        }
    }
}

fn append_drop_table_stmts(statements: &mut Vec<JsonStatement>, schema_diff: &SchemaDiff) {
    // 11. Drop tables
    for table_diff in schema_diff.dropped_tables() {
        statements.push(JsonStatement::DropTable(DropTableStatement {
            table_name: table_diff.name.clone(),
        }));
    }
}

fn collect_stored_generated_warnings(warnings: &mut Vec<String>, schema_diff: &SchemaDiff) {
    // Add warnings for STORED generated columns
    for col_diff in schema_diff.by_kind(EntityKind::Column) {
        if col_diff.diff_type == DiffType::Alter
            && let Some(SqliteEntity::Column(col)) = &col_diff.right
            && col
                .generated
                .as_ref()
                .is_some_and(|g| g.gen_type == super::ddl::GeneratedType::Stored)
        {
            warnings.push(format!(
                "Column '{}' in table '{}' has STORED generated column which requires table recreation",
                col.name, col.table
            ));
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct TableColumnFingerprint {
    name: String,
    sql_type: String,
    not_null: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct TableFingerprint {
    columns: Vec<TableColumnFingerprint>,
    pk_columns: Vec<String>,
}

fn table_fingerprint(table_name: &str, ddl: &SQLiteDDL) -> TableFingerprint {
    let mut columns: Vec<_> = ddl
        .columns
        .for_table(table_name)
        .into_iter()
        .map(|c| TableColumnFingerprint {
            name: c.name.to_string(),
            sql_type: c.sql_type.to_string(),
            not_null: c.not_null,
        })
        .collect();
    columns.sort();

    let pk_columns = if let Some(pk) = ddl.pks.for_table(table_name) {
        pk.columns.iter().map(ToString::to_string).collect()
    } else {
        let mut inline_pk_columns: Vec<_> = ddl
            .columns
            .for_table(table_name)
            .into_iter()
            .filter(|c| c.primary_key.unwrap_or(false))
            .map(|c| (c.ordinal_position.unwrap_or(i32::MAX), c.name.to_string()))
            .collect();
        inline_pk_columns.sort();
        inline_pk_columns
            .into_iter()
            .map(|(_, name)| name)
            .collect()
    };

    TableFingerprint {
        columns,
        pk_columns,
    }
}

fn detect_and_apply_renames(
    prev: &mut SQLiteDDL,
    cur: &SQLiteDDL,
    rename_statements: &mut Vec<JsonStatement>,
    table_renames: &mut Vec<TableRename>,
    column_renames: &mut Vec<ColumnRename>,
    warnings: &mut Vec<String>,
) {
    // Table renames: exact match of columns (name/type/nullability) and PK shape.
    let prev_tables: Vec<String> = prev
        .tables
        .list()
        .iter()
        .map(|t| t.name.to_string())
        .collect();
    let cur_tables: Vec<String> = cur
        .tables
        .list()
        .iter()
        .map(|t| t.name.to_string())
        .collect();

    let dropped: Vec<String> = prev_tables
        .iter()
        .filter(|t| !cur_tables.contains(t))
        .cloned()
        .collect();
    let created: Vec<String> = cur_tables
        .iter()
        .filter(|t| !prev_tables.contains(t))
        .cloned()
        .collect();

    let mut candidates: BTreeMap<TableFingerprint, (Vec<String>, Vec<String>)> = BTreeMap::new();
    for from in dropped {
        candidates
            .entry(table_fingerprint(&from, prev))
            .or_default()
            .0
            .push(from);
    }
    for to in created {
        candidates
            .entry(table_fingerprint(&to, cur))
            .or_default()
            .1
            .push(to);
    }

    for (_, (mut dropped, mut created)) in candidates {
        if dropped.is_empty() || created.is_empty() {
            continue;
        }

        dropped.sort();
        created.sort();

        if dropped.len() == 1 && created.len() == 1 {
            let from = &dropped[0];
            let to = &created[0];
            table_renames.push(TableRename {
                from: from.clone(),
                to: to.clone(),
            });
            rename_statements.push(JsonStatement::RenameTable(RenameTableStatement {
                from: from.clone(),
                to: to.clone(),
            }));
            apply_table_rename(prev, from, to);
        } else {
            warnings.push(format!(
                "Ambiguous SQLite table rename candidates between dropped tables [{}] and created tables [{}]; no rename was inferred. Use DiffOptions::rename_table(...) with diff_with or diff_schemas_with to provide an explicit rename hint.",
                dropped.join(", "),
                created.join(", ")
            ));
        }
    }

    // Column renames (within tables that exist in both): exact property match, different name.
    let common_tables: Vec<String> = prev
        .tables
        .list()
        .iter()
        .map(|t| t.name.to_string())
        .filter(|t| cur.tables.one(t).is_some())
        .collect();

    for table in common_tables {
        let prev_cols: Vec<_> = prev.columns.for_table(&table);
        let cur_cols: Vec<_> = cur.columns.for_table(&table);

        let prev_names: Vec<String> = prev_cols.iter().map(|c| c.name.to_string()).collect();
        let cur_names: Vec<String> = cur_cols.iter().map(|c| c.name.to_string()).collect();

        let dropped_cols: Vec<String> = prev_names
            .iter()
            .filter(|c| !cur_names.contains(c))
            .cloned()
            .collect();
        let created_cols: Vec<String> = cur_names
            .iter()
            .filter(|c| !prev_names.contains(c))
            .cloned()
            .collect();

        if dropped_cols.len() != 1 || created_cols.len() != 1 {
            continue;
        }

        let from = &dropped_cols[0];
        let to = &created_cols[0];

        let prev_col = prev.columns.one(&table, from);
        let cur_col = cur.columns.one(&table, to);
        if let (Some(prev_col), Some(cur_col)) = (prev_col, cur_col) {
            let mut prev_cmp = prev_col.clone();
            prev_cmp.name.clone_from(&cur_col.name);
            if prev_cmp == *cur_col {
                column_renames.push(ColumnRename {
                    table: table.clone(),
                    from: from.clone(),
                    to: to.clone(),
                });
                rename_statements.push(JsonStatement::RenameColumn(RenameColumnStatement {
                    table: table.clone(),
                    from: from.clone(),
                    to: to.clone(),
                }));
                apply_column_rename(prev, &table, from, to);
            }
        }
    }
}

fn apply_table_rename(ddl: &mut SQLiteDDL, from: &str, to: &str) {
    let to = to.to_string();
    // Tables
    if let Some(t) = ddl
        .tables
        .list_mut()
        .iter_mut()
        .find(|t| t.name.as_ref() == from)
    {
        t.name = to.clone().into();
    }
    // Columns
    for c in ddl
        .columns
        .list_mut()
        .iter_mut()
        .filter(|c| c.table.as_ref() == from)
    {
        c.table = to.clone().into();
    }
    // PKs
    for pk in ddl
        .pks
        .list_mut()
        .iter_mut()
        .filter(|pk| pk.table.as_ref() == from)
    {
        pk.table = to.clone().into();
    }
    // Uniques
    for u in ddl
        .uniques
        .list_mut()
        .iter_mut()
        .filter(|u| u.table.as_ref() == from)
    {
        u.table = to.clone().into();
    }
    // FKs (table side and referenced side)
    for fk in ddl.fks.list_mut().iter_mut() {
        if fk.table.as_ref() == from {
            fk.table = to.clone().into();
        }
        if fk.table_to.as_ref() == from {
            fk.table_to = to.clone().into();
        }
    }
    // Indexes
    for idx in ddl
        .indexes
        .list_mut()
        .iter_mut()
        .filter(|i| i.table.as_ref() == from)
    {
        idx.table = to.clone().into();
    }
    // Checks
    for chk in ddl
        .checks
        .list_mut()
        .iter_mut()
        .filter(|c| c.table.as_ref() == from)
    {
        chk.table = to.clone().into();
    }
}

fn apply_column_rename(ddl: &mut SQLiteDDL, table: &str, from: &str, to: &str) {
    let to = to.to_string();
    // Columns
    if let Some(c) = ddl
        .columns
        .list_mut()
        .iter_mut()
        .find(|c| c.table.as_ref() == table && c.name.as_ref() == from)
    {
        c.name = to.clone().into();
    }
    // PK columns
    for pk in ddl
        .pks
        .list_mut()
        .iter_mut()
        .filter(|pk| pk.table.as_ref() == table)
    {
        for col in pk.columns.to_mut().iter_mut() {
            if col.as_ref() == from {
                *col = to.clone().into();
            }
        }
    }
    // Unique columns
    for u in ddl
        .uniques
        .list_mut()
        .iter_mut()
        .filter(|u| u.table.as_ref() == table)
    {
        for col in u.columns.to_mut().iter_mut() {
            if col.as_ref() == from {
                *col = to.clone().into();
            }
        }
    }
    // FK columns
    for fk in ddl.fks.list_mut().iter_mut() {
        if fk.table.as_ref() == table {
            for col in fk.columns.to_mut().iter_mut() {
                if col.as_ref() == from {
                    *col = to.clone().into();
                }
            }
        }
        if fk.table_to.as_ref() == table {
            for col in fk.columns_to.to_mut().iter_mut() {
                if col.as_ref() == from {
                    *col = to.clone().into();
                }
            }
        }
    }
    // Index columns (only non-expression)
    for idx in ddl
        .indexes
        .list_mut()
        .iter_mut()
        .filter(|i| i.table.as_ref() == table)
    {
        for col in &mut idx.columns {
            if !col.is_expression && col.value.as_ref() == from {
                col.value = to.clone().into();
            }
        }
    }
}

/// Prepare rename tracking strings for snapshot storage
#[must_use]
pub fn prepare_migration_renames(
    table_renames: &[TableRename],
    column_renames: &[ColumnRename],
) -> Vec<String> {
    let mut renames = Vec::new();

    for tr in table_renames {
        renames.push(format!("table:{}:{}", tr.from, tr.to));
    }

    for cr in column_renames {
        renames.push(format!("column:{}:{}:{}", cr.table, cr.from, cr.to));
    }

    renames
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sqlite::ddl::{Column, ForeignKey, Index, IndexColumn, SqliteEntity, Table};
    use std::borrow::Cow;

    #[test]
    fn test_empty_diff() {
        let prev = SQLiteSnapshot::new();
        let cur = SQLiteSnapshot::new();

        let diff = diff_snapshots(&prev, &cur);
        assert!(!diff.has_changes());
    }

    #[test]
    fn test_table_creation() {
        let prev = SQLiteSnapshot::new();
        let mut cur = SQLiteSnapshot::new();

        cur.add_entity(SqliteEntity::Table(Table::new("users")));
        cur.add_entity(SqliteEntity::Column(
            Column::new("users", "id", "integer").not_null(),
        ));

        let diff = diff_snapshots(&prev, &cur);
        assert!(diff.has_changes());
        assert_eq!(diff.created_tables().len(), 1);
    }

    #[test]
    fn test_table_deletion() {
        let mut prev = SQLiteSnapshot::new();
        let cur = SQLiteSnapshot::new();

        prev.add_entity(SqliteEntity::Table(Table::new("users")));

        let diff = diff_snapshots(&prev, &cur);
        assert!(diff.has_changes());
        assert_eq!(diff.dropped_tables().len(), 1);
    }

    fn sqlite_table_with_id(table: &str) -> SQLiteDDL {
        let mut ddl = SQLiteDDL::new();
        ddl.tables.push(Table::new(table.to_string()));
        ddl.columns
            .push(Column::new(table.to_string(), "id", "integer").not_null());
        ddl
    }

    #[test]
    fn pure_table_rename_emits_single_rename_statement() {
        let prev = sqlite_table_with_id("users");
        let cur = sqlite_table_with_id("accounts");

        let migration = compute_migration(&prev, &cur);

        assert_eq!(migration.statements.len(), 1);
        assert!(matches!(
            migration.statements[0],
            JsonStatement::RenameTable(_)
        ));
        assert_eq!(
            migration.sql_statements,
            vec!["ALTER TABLE `users` RENAME TO `accounts`;"]
        );
        assert!(
            !migration
                .statements
                .iter()
                .any(|statement| matches!(statement, JsonStatement::DropTable(_)))
        );
    }

    #[test]
    fn table_rename_rewrites_indexes_and_foreign_keys() {
        let mut prev = sqlite_table_with_id("users");
        prev.tables.push(Table::new("posts"));
        prev.columns
            .push(Column::new("posts", "id", "integer").not_null());
        prev.columns
            .push(Column::new("posts", "user_id", "integer").not_null());
        prev.indexes.push(Index::new(
            "users",
            "idx_users_id",
            vec![IndexColumn::new("id")],
        ));
        prev.fks.push(ForeignKey::new(
            "posts",
            "fk_posts_user",
            vec![Cow::Borrowed("user_id")],
            "users",
            vec![Cow::Borrowed("id")],
        ));

        let mut cur = sqlite_table_with_id("accounts");
        cur.tables.push(Table::new("posts"));
        cur.columns
            .push(Column::new("posts", "id", "integer").not_null());
        cur.columns
            .push(Column::new("posts", "user_id", "integer").not_null());
        cur.indexes.push(Index::new(
            "accounts",
            "idx_users_id",
            vec![IndexColumn::new("id")],
        ));
        cur.fks.push(ForeignKey::new(
            "posts",
            "fk_posts_user",
            vec![Cow::Borrowed("user_id")],
            "accounts",
            vec![Cow::Borrowed("id")],
        ));

        let migration = compute_migration(&prev, &cur);

        assert_eq!(
            migration.sql_statements,
            vec!["ALTER TABLE `users` RENAME TO `accounts`;"]
        );
        assert!(
            !migration.sql_statements.iter().any(|statement| {
                statement.starts_with("DROP")
                    || statement.starts_with("CREATE INDEX")
                    || statement.contains("fk_posts_user")
            }),
            "unexpected dependent churn: {:?}",
            migration.sql_statements
        );
    }

    #[test]
    fn ambiguous_table_rename_does_not_guess_and_warns() {
        let mut prev = sqlite_table_with_id("users");
        let mut admins = sqlite_table_with_id("admins");
        prev.tables.list_mut().append(admins.tables.list_mut());
        prev.columns.list_mut().append(admins.columns.list_mut());
        let cur = sqlite_table_with_id("accounts");

        let migration = compute_migration(&prev, &cur);

        assert!(
            migration.warnings.iter().any(|warning| warning
                .contains("Ambiguous SQLite table rename candidates")
                && warning.contains("rename_table")),
            "expected ambiguous rename warning, got {:?}",
            migration.warnings
        );
        assert!(
            !migration
                .statements
                .iter()
                .any(|statement| matches!(statement, JsonStatement::RenameTable(_)))
        );
    }

    #[test]
    fn test_column_nullable_change() {
        // Test that changing Option<String> to String (nullable to not null) is detected
        let mut prev = SQLiteSnapshot::new();
        prev.add_entity(SqliteEntity::Table(Table::new("users")));
        prev.add_entity(SqliteEntity::Column(Column::new("users", "email", "text"))); // nullable

        let mut cur = SQLiteSnapshot::new();
        cur.add_entity(SqliteEntity::Table(Table::new("users")));
        cur.add_entity(SqliteEntity::Column(
            Column::new("users", "email", "text").not_null(),
        )); // not null

        let diff = diff_snapshots(&prev, &cur);
        assert!(diff.has_changes(), "Should detect nullable change");

        // Should be an Alter diff for the column
        let altered = diff.altered();
        assert_eq!(altered.len(), 1, "Should have one altered entity");
        assert_eq!(altered[0].kind, crate::traits::EntityKind::Column);
        assert_eq!(altered[0].name, "users:email");
    }

    #[test]
    fn test_column_not_null_to_nullable() {
        // Test that changing String to Option<String> (not null to nullable) is detected
        let mut prev = SQLiteSnapshot::new();
        prev.add_entity(SqliteEntity::Table(Table::new("users")));
        prev.add_entity(SqliteEntity::Column(
            Column::new("users", "email", "text").not_null(),
        )); // not null

        let mut cur = SQLiteSnapshot::new();
        cur.add_entity(SqliteEntity::Table(Table::new("users")));
        cur.add_entity(SqliteEntity::Column(Column::new("users", "email", "text"))); // nullable

        let diff = diff_snapshots(&prev, &cur);
        assert!(diff.has_changes(), "Should detect nullable change");

        // Should be an Alter diff for the column
        let altered = diff.altered();
        assert_eq!(altered.len(), 1, "Should have one altered entity");
        assert_eq!(altered[0].kind, crate::traits::EntityKind::Column);
    }

    #[test]
    fn test_column_nullable_change_generates_sql() {
        // Test that changing nullable to not null generates RecreateTable SQL
        let mut prev_ddl = SQLiteDDL::new();
        prev_ddl.tables.push(Table::new("users"));
        prev_ddl
            .columns
            .push(Column::new("users", "id", "integer").not_null());
        prev_ddl.columns.push(Column::new("users", "email", "text")); // nullable

        let mut cur_ddl = SQLiteDDL::new();
        cur_ddl.tables.push(Table::new("users"));
        cur_ddl
            .columns
            .push(Column::new("users", "id", "integer").not_null());
        cur_ddl
            .columns
            .push(Column::new("users", "email", "text").not_null()); // not null

        let migration = compute_migration(&prev_ddl, &cur_ddl);

        // Should have generated SQL statements
        assert!(
            !migration.sql_statements.is_empty(),
            "Should generate SQL statements"
        );

        // Should have a RecreateTable statement
        let has_recreate = migration
            .statements
            .iter()
            .any(|s| matches!(s, JsonStatement::RecreateTable(_)));
        assert!(
            has_recreate,
            "Should have RecreateTable statement for column alteration"
        );

        // Verify individual SQL statements for table recreation pattern
        assert_eq!(migration.sql_statements[0], "PRAGMA foreign_keys=OFF;");
        assert!(
            migration.sql_statements[1].starts_with("CREATE TABLE `__new_users`"),
            "Expected CREATE TABLE `__new_users`, got: {}",
            migration.sql_statements[1]
        );
        assert!(
            migration.sql_statements[1].contains("`email` TEXT NOT NULL"),
            "New table should have NOT NULL on email: {}",
            migration.sql_statements[1]
        );
        assert_eq!(
            migration.sql_statements[2],
            "INSERT INTO `__new_users`(`id`, `email`) SELECT `id`, `email` FROM `users`;"
        );
        assert_eq!(migration.sql_statements[3], "DROP TABLE `users`;");
        assert_eq!(
            migration.sql_statements[4],
            "ALTER TABLE `__new_users` RENAME TO `users`;"
        );
        assert_eq!(migration.sql_statements[5], "PRAGMA foreign_keys=ON;");
    }

    #[test]
    fn strict_toggle_generates_table_recreate() {
        let mut prev = SQLiteDDL::new();
        prev.tables.push(Table::new("users"));
        prev.columns
            .push(Column::new("users", "id", "integer").not_null());

        let mut cur = SQLiteDDL::new();
        cur.tables.push(Table::new("users").strict());
        cur.columns
            .push(Column::new("users", "id", "integer").not_null());

        let migration = compute_migration(&prev, &cur);

        let has_recreate = migration
            .statements
            .iter()
            .any(|s| matches!(s, JsonStatement::RecreateTable(_)));
        assert!(
            has_recreate,
            "toggling STRICT must recreate the table, got: {:?}",
            migration.statements
        );
        assert!(
            migration.sql_statements.iter().any(|sql| sql
                .starts_with("CREATE TABLE `__new_users`")
                && sql.ends_with("STRICT;")),
            "recreated table must carry STRICT: {:?}",
            migration.sql_statements
        );
    }

    #[test]
    fn partial_index_predicate_change_recreates_index() {
        let mut prev = sqlite_table_with_id("jobs");
        let mut previous_index =
            Index::new("jobs", "idx_jobs_unclaimed", vec![IndexColumn::new("id")]);
        previous_index.where_clause = Some(Cow::Borrowed("builder IS NULL"));
        prev.indexes.push(previous_index);

        let mut cur = sqlite_table_with_id("jobs");
        let mut current_index =
            Index::new("jobs", "idx_jobs_unclaimed", vec![IndexColumn::new("id")]);
        current_index.where_clause = Some(Cow::Borrowed("builder IS NOT NULL"));
        cur.indexes.push(current_index);

        let migration = compute_migration(&prev, &cur);
        assert_eq!(
            migration.sql_statements,
            vec![
                "DROP INDEX IF EXISTS `idx_jobs_unclaimed`;",
                "CREATE INDEX `idx_jobs_unclaimed` ON `jobs`(`id`) WHERE builder IS NOT NULL;",
            ]
        );
    }

    #[test]
    fn without_rowid_toggle_generates_table_recreate() {
        let mut prev = SQLiteDDL::new();
        prev.tables.push(Table::new("kv"));
        prev.columns
            .push(Column::new("kv", "key", "text").not_null());

        let mut cur = SQLiteDDL::new();
        cur.tables.push(Table::new("kv").without_rowid());
        cur.columns
            .push(Column::new("kv", "key", "text").not_null());

        let migration = compute_migration(&prev, &cur);

        assert!(
            migration
                .statements
                .iter()
                .any(|s| matches!(s, JsonStatement::RecreateTable(_))),
            "toggling WITHOUT ROWID must recreate the table, got: {:?}",
            migration.statements
        );
    }

    #[test]
    fn multi_table_recreation_order_is_deterministic() {
        let make = |not_null: bool| {
            let mut ddl = SQLiteDDL::new();
            for table in ["zeta", "alpha", "midway"] {
                ddl.tables.push(Table::new(table.to_string()));
                let col = Column::new(table.to_string(), "name", "text");
                ddl.columns
                    .push(if not_null { col.not_null() } else { col });
            }
            ddl
        };

        let migration = compute_migration(&make(false), &make(true));
        let recreate_order: Vec<String> = migration
            .statements
            .iter()
            .filter_map(|s| match s {
                JsonStatement::RecreateTable(st) => Some(st.to.name.clone()),
                _ => None,
            })
            .collect();
        assert_eq!(
            recreate_order,
            vec!["alpha", "midway", "zeta"],
            "table recreation must be emitted in sorted order"
        );
    }

    #[test]
    fn test_column_type_change_generates_recreate() {
        // Test that changing column type generates RecreateTable
        let mut prev_ddl = SQLiteDDL::new();
        prev_ddl.tables.push(Table::new("users"));
        prev_ddl.columns.push(Column::new("users", "age", "text")); // text

        let mut cur_ddl = SQLiteDDL::new();
        cur_ddl.tables.push(Table::new("users"));
        cur_ddl.columns.push(Column::new("users", "age", "integer")); // integer

        let migration = compute_migration(&prev_ddl, &cur_ddl);

        // Should have a RecreateTable statement
        let has_recreate = migration
            .statements
            .iter()
            .any(|s| matches!(s, JsonStatement::RecreateTable(_)));
        assert!(
            has_recreate,
            "Should have RecreateTable statement for type change"
        );
    }
}