vespertide-query 0.1.61

Converts migration actions into SQL statements with bind parameters
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
use sea_query::{Alias, Index, Query, Table};

use vespertide_core::{ColumnType, TableConstraint, TableDef};

use super::helpers::{
    build_drop_enum_type_sql, build_sqlite_temp_table_create, recreate_indexes_after_rebuild,
};
use super::rename_table::build_rename_table;
use super::types::{BuiltQuery, DatabaseBackend};

/// Build SQL to delete a column, optionally with DROP TYPE for enum columns (PostgreSQL)
///
/// For SQLite: Handles constraint removal before dropping the column:
/// - Unique/Index constraints: Dropped via DROP INDEX
/// - ForeignKey/PrimaryKey constraints: Uses temp table approach (recreate table without column)
///
/// SQLite doesn't cascade constraint drops when a column is dropped.
pub fn build_delete_column(
    backend: &DatabaseBackend,
    table: &str,
    column: &str,
    column_type: Option<&ColumnType>,
    current_schema: &[TableDef],
    pending_constraints: &[vespertide_core::TableConstraint],
) -> Vec<BuiltQuery> {
    let mut stmts = Vec::new();

    // SQLite: Check if we need special handling for constraints
    if *backend == DatabaseBackend::Sqlite
        && let Some(table_def) = current_schema.iter().find(|t| t.name == table)
    {
        // If the column has an enum type, SQLite embeds a CHECK constraint in CREATE TABLE.
        // ALTER TABLE DROP COLUMN fails if the column is referenced by any CHECK.
        // Must use temp table approach.
        if let Some(col_def) = table_def.columns.iter().find(|c| c.name == column)
            && let ColumnType::Complex(vespertide_core::ComplexColumnType::Enum { .. }) =
                &col_def.r#type
        {
            return build_delete_column_sqlite_temp_table(
                table,
                column,
                table_def,
                column_type,
                pending_constraints,
            );
        }

        // Handle constraints referencing the deleted column
        for constraint in &table_def.constraints {
            match constraint {
                // Check constraints may reference the column in their expression.
                // SQLite can't DROP COLUMN if a CHECK references it — use temp table.
                TableConstraint::Check { expr, .. } => {
                    // Check if the expression references the column (e.g. "status" IN (...))
                    if expr.contains(&format!("\"{}\"", column)) || expr.contains(column) {
                        return build_delete_column_sqlite_temp_table(
                            table,
                            column,
                            table_def,
                            column_type,
                            pending_constraints,
                        );
                    }
                    continue;
                }
                // For column-based constraints, check if they reference the deleted column
                _ if !constraint.columns().iter().any(|c| c == column) => continue,
                // FK/PK require temp table approach - return immediately
                TableConstraint::ForeignKey { .. } | TableConstraint::PrimaryKey { .. } => {
                    return build_delete_column_sqlite_temp_table(
                        table,
                        column,
                        table_def,
                        column_type,
                        pending_constraints,
                    );
                }
                // Unique/Index: drop the index first, then drop column below
                TableConstraint::Unique { name, columns } => {
                    let index_name = vespertide_naming::build_unique_constraint_name(
                        table,
                        columns,
                        name.as_deref(),
                    );
                    let drop_idx = Index::drop()
                        .name(&index_name)
                        .table(Alias::new(table))
                        .to_owned();
                    stmts.push(BuiltQuery::DropIndex(Box::new(drop_idx)));
                }
                TableConstraint::Index { name, columns } => {
                    let index_name =
                        vespertide_naming::build_index_name(table, columns, name.as_deref());
                    let drop_idx = Index::drop()
                        .name(&index_name)
                        .table(Alias::new(table))
                        .to_owned();
                    stmts.push(BuiltQuery::DropIndex(Box::new(drop_idx)));
                }
            }
        }
    }

    // Drop the column
    let stmt = Table::alter()
        .table(Alias::new(table))
        .drop_column(Alias::new(column))
        .to_owned();
    stmts.push(BuiltQuery::AlterTable(Box::new(stmt)));

    // If column type is an enum, drop the type after (PostgreSQL only)
    // Note: Only drop if this is the last column using this enum type
    if let Some(col_type) = column_type
        && let Some(drop_type_sql) = build_drop_enum_type_sql(table, col_type)
    {
        stmts.push(BuiltQuery::Raw(drop_type_sql));
    }

    stmts
}

/// SQLite temp table approach for deleting a column that has FK or PK constraints.
///
/// Steps:
/// 1. Create temp table without the column (and without constraints referencing it)
/// 2. Copy data (excluding the deleted column)
/// 3. Drop original table
/// 4. Rename temp table to original name
/// 5. Recreate indexes that don't reference the deleted column
fn build_delete_column_sqlite_temp_table(
    table: &str,
    column: &str,
    table_def: &TableDef,
    column_type: Option<&ColumnType>,
    pending_constraints: &[vespertide_core::TableConstraint],
) -> Vec<BuiltQuery> {
    let mut stmts = Vec::new();
    let temp_table = format!("{}_temp", table);

    // Build new columns list without the deleted column
    let new_columns: Vec<_> = table_def
        .columns
        .iter()
        .filter(|c| c.name != column)
        .cloned()
        .collect();

    // Build new constraints list without constraints referencing the deleted column
    let new_constraints: Vec<_> = table_def
        .constraints
        .iter()
        .filter(|c| {
            // For CHECK constraints, check if expression references the column
            if let TableConstraint::Check { expr, .. } = c {
                return !expr.contains(&format!("\"{}\"", column)) && !expr.contains(column);
            }
            !c.columns().iter().any(|col| col == column)
        })
        .cloned()
        .collect();

    // 1. Create temp table without the column + CHECK constraints
    let create_query = build_sqlite_temp_table_create(
        &DatabaseBackend::Sqlite,
        &temp_table,
        table,
        &new_columns,
        &new_constraints,
    );
    stmts.push(create_query);

    // 2. Copy data (excluding the deleted column)
    let column_aliases: Vec<Alias> = new_columns.iter().map(|c| Alias::new(&c.name)).collect();
    let mut select_query = Query::select();
    for col_alias in &column_aliases {
        select_query = select_query.column(col_alias.clone()).to_owned();
    }
    select_query = select_query.from(Alias::new(table)).to_owned();

    let insert_stmt = Query::insert()
        .into_table(Alias::new(&temp_table))
        .columns(column_aliases.clone())
        .select_from(select_query)
        .unwrap()
        .to_owned();
    stmts.push(BuiltQuery::Insert(Box::new(insert_stmt)));

    // 3. Drop original table
    let drop_table = Table::drop().table(Alias::new(table)).to_owned();
    stmts.push(BuiltQuery::DropTable(Box::new(drop_table)));

    // 4. Rename temp table to original name
    stmts.push(build_rename_table(&temp_table, table));

    // 5. Recreate indexes (both regular and UNIQUE) that don't reference the deleted column
    stmts.extend(recreate_indexes_after_rebuild(
        table,
        &new_constraints,
        pending_constraints,
    ));

    // If column type is an enum, drop the type after (PostgreSQL only, but include for completeness)
    if let Some(col_type) = column_type
        && let Some(drop_type_sql) = build_drop_enum_type_sql(table, col_type)
    {
        stmts.push(BuiltQuery::Raw(drop_type_sql));
    }

    stmts
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sql::types::DatabaseBackend;
    use insta::{assert_snapshot, with_settings};
    use rstest::rstest;
    use vespertide_core::{ColumnDef, ComplexColumnType, SimpleColumnType};

    fn col(name: &str, ty: ColumnType) -> ColumnDef {
        ColumnDef {
            name: name.to_string(),
            r#type: ty,
            nullable: true,
            default: None,
            comment: None,
            primary_key: None,
            unique: None,
            index: None,
            foreign_key: None,
        }
    }

    #[rstest]
    #[case::delete_column_postgres(
        "delete_column_postgres",
        DatabaseBackend::Postgres,
        &["ALTER TABLE \"users\" DROP COLUMN \"email\""]
    )]
    #[case::delete_column_mysql(
        "delete_column_mysql",
        DatabaseBackend::MySql,
        &["ALTER TABLE `users` DROP COLUMN `email`"]
    )]
    #[case::delete_column_sqlite(
        "delete_column_sqlite",
        DatabaseBackend::Sqlite,
        &["ALTER TABLE \"users\" DROP COLUMN \"email\""]
    )]
    fn test_delete_column(
        #[case] title: &str,
        #[case] backend: DatabaseBackend,
        #[case] expected: &[&str],
    ) {
        let result = build_delete_column(&backend, "users", "email", None, &[], &[]);
        let sql = result[0].build(backend);
        for exp in expected {
            assert!(
                sql.contains(exp),
                "Expected SQL to contain '{}', got: {}",
                exp,
                sql
            );
        }

        with_settings!({ snapshot_suffix => format!("delete_column_{}", title) }, {
            assert_snapshot!(sql);
        });
    }

    #[test]
    fn test_delete_enum_column_postgres() {
        use vespertide_core::EnumValues;

        let enum_type = ColumnType::Complex(ComplexColumnType::Enum {
            name: "status".into(),
            values: EnumValues::String(vec!["active".into(), "inactive".into()]),
        });
        let result = build_delete_column(
            &DatabaseBackend::Postgres,
            "users",
            "status",
            Some(&enum_type),
            &[],
            &[],
        );

        // Should have 2 statements: ALTER TABLE and DROP TYPE
        assert_eq!(result.len(), 2);

        let alter_sql = result[0].build(DatabaseBackend::Postgres);
        assert!(alter_sql.contains("DROP COLUMN"));

        let drop_type_sql = result[1].build(DatabaseBackend::Postgres);
        assert!(drop_type_sql.contains("DROP TYPE \"users_status\""));

        // MySQL and SQLite should have empty DROP TYPE
        let drop_type_mysql = result[1].build(DatabaseBackend::MySql);
        assert!(drop_type_mysql.is_empty());
    }

    #[test]
    fn test_delete_non_enum_column_no_drop_type() {
        let text_type = ColumnType::Simple(SimpleColumnType::Text);
        let result = build_delete_column(
            &DatabaseBackend::Postgres,
            "users",
            "name",
            Some(&text_type),
            &[],
            &[],
        );

        // Should only have 1 statement: ALTER TABLE
        assert_eq!(result.len(), 1);
    }

    #[test]
    fn test_delete_column_sqlite_drops_unique_constraint_first() {
        // SQLite should drop unique constraint index before dropping the column
        let schema = vec![TableDef {
            name: "gift".into(),
            description: None,
            columns: vec![
                col("id", ColumnType::Simple(SimpleColumnType::Integer)),
                col("gift_code", ColumnType::Simple(SimpleColumnType::Text)),
            ],
            constraints: vec![TableConstraint::Unique {
                name: None,
                columns: vec!["gift_code".into()],
            }],
        }];

        let result = build_delete_column(
            &DatabaseBackend::Sqlite,
            "gift",
            "gift_code",
            None,
            &schema,
            &[],
        );

        // Should have 2 statements: DROP INDEX then ALTER TABLE DROP COLUMN
        assert_eq!(result.len(), 2);

        let drop_index_sql = result[0].build(DatabaseBackend::Sqlite);
        assert!(
            drop_index_sql.contains("DROP INDEX"),
            "Expected DROP INDEX, got: {}",
            drop_index_sql
        );
        assert!(
            drop_index_sql.contains("uq_gift__gift_code"),
            "Expected index name uq_gift__gift_code, got: {}",
            drop_index_sql
        );

        let drop_column_sql = result[1].build(DatabaseBackend::Sqlite);
        assert!(
            drop_column_sql.contains("DROP COLUMN"),
            "Expected DROP COLUMN, got: {}",
            drop_column_sql
        );
    }

    #[test]
    fn test_delete_column_sqlite_drops_index_constraint_first() {
        // SQLite should drop index before dropping the column
        let schema = vec![TableDef {
            name: "users".into(),
            description: None,
            columns: vec![
                col("id", ColumnType::Simple(SimpleColumnType::Integer)),
                col("email", ColumnType::Simple(SimpleColumnType::Text)),
            ],
            constraints: vec![TableConstraint::Index {
                name: None,
                columns: vec!["email".into()],
            }],
        }];

        let result = build_delete_column(
            &DatabaseBackend::Sqlite,
            "users",
            "email",
            None,
            &schema,
            &[],
        );

        // Should have 2 statements: DROP INDEX then ALTER TABLE DROP COLUMN
        assert_eq!(result.len(), 2);

        let drop_index_sql = result[0].build(DatabaseBackend::Sqlite);
        assert!(drop_index_sql.contains("DROP INDEX"));
        assert!(drop_index_sql.contains("ix_users__email"));

        let drop_column_sql = result[1].build(DatabaseBackend::Sqlite);
        assert!(drop_column_sql.contains("DROP COLUMN"));
    }

    #[test]
    fn test_delete_column_postgres_does_not_drop_constraints() {
        // PostgreSQL cascades constraint drops, so we shouldn't emit extra DROP INDEX
        let schema = vec![TableDef {
            name: "gift".into(),
            description: None,
            columns: vec![
                col("id", ColumnType::Simple(SimpleColumnType::Integer)),
                col("gift_code", ColumnType::Simple(SimpleColumnType::Text)),
            ],
            constraints: vec![TableConstraint::Unique {
                name: None,
                columns: vec!["gift_code".into()],
            }],
        }];

        let result = build_delete_column(
            &DatabaseBackend::Postgres,
            "gift",
            "gift_code",
            None,
            &schema,
            &[],
        );

        // Should have only 1 statement: ALTER TABLE DROP COLUMN
        assert_eq!(result.len(), 1);

        let drop_column_sql = result[0].build(DatabaseBackend::Postgres);
        assert!(drop_column_sql.contains("DROP COLUMN"));
    }

    #[test]
    fn test_delete_column_sqlite_with_named_unique_constraint() {
        // Test with a named unique constraint
        let schema = vec![TableDef {
            name: "gift".into(),
            description: None,
            columns: vec![
                col("id", ColumnType::Simple(SimpleColumnType::Integer)),
                col("gift_code", ColumnType::Simple(SimpleColumnType::Text)),
            ],
            constraints: vec![TableConstraint::Unique {
                name: Some("gift_code".into()),
                columns: vec!["gift_code".into()],
            }],
        }];

        let result = build_delete_column(
            &DatabaseBackend::Sqlite,
            "gift",
            "gift_code",
            None,
            &schema,
            &[],
        );

        assert_eq!(result.len(), 2);

        let drop_index_sql = result[0].build(DatabaseBackend::Sqlite);
        // Named constraint: uq_gift__gift_code (name is "gift_code")
        assert!(
            drop_index_sql.contains("uq_gift__gift_code"),
            "Expected uq_gift__gift_code, got: {}",
            drop_index_sql
        );
    }

    #[test]
    fn test_delete_column_sqlite_with_fk_uses_temp_table() {
        // SQLite should use temp table approach when deleting a column with FK constraint
        let schema = vec![TableDef {
            name: "gift".into(),
            description: None,
            columns: vec![
                col("id", ColumnType::Simple(SimpleColumnType::Integer)),
                col("sender_id", ColumnType::Simple(SimpleColumnType::BigInt)),
                col("message", ColumnType::Simple(SimpleColumnType::Text)),
            ],
            constraints: vec![TableConstraint::ForeignKey {
                name: None,
                columns: vec!["sender_id".into()],
                ref_table: "user".into(),
                ref_columns: vec!["id".into()],
                on_delete: None,
                on_update: None,
            }],
        }];

        let result = build_delete_column(
            &DatabaseBackend::Sqlite,
            "gift",
            "sender_id",
            None,
            &schema,
            &[],
        );

        // Should use temp table approach:
        // 1. CREATE TABLE gift_temp (without sender_id column)
        // 2. INSERT INTO gift_temp SELECT ... FROM gift
        // 3. DROP TABLE gift
        // 4. ALTER TABLE gift_temp RENAME TO gift
        assert!(
            result.len() >= 4,
            "Expected at least 4 statements for temp table approach, got: {}",
            result.len()
        );

        let all_sql: Vec<String> = result
            .iter()
            .map(|q| q.build(DatabaseBackend::Sqlite))
            .collect();
        let combined_sql = all_sql.join("\n");

        // Verify temp table creation
        assert!(
            combined_sql.contains("CREATE TABLE") && combined_sql.contains("gift_temp"),
            "Expected CREATE TABLE gift_temp, got: {}",
            combined_sql
        );

        // Verify the new table doesn't have sender_id column
        assert!(
            !combined_sql.contains("\"sender_id\"") || combined_sql.contains("DROP TABLE"),
            "New table should not contain sender_id column"
        );

        // Verify data copy (INSERT ... SELECT)
        assert!(
            combined_sql.contains("INSERT INTO"),
            "Expected INSERT INTO for data copy, got: {}",
            combined_sql
        );

        // Verify original table drop
        assert!(
            combined_sql.contains("DROP TABLE") && combined_sql.contains("\"gift\""),
            "Expected DROP TABLE gift, got: {}",
            combined_sql
        );

        // Verify rename
        assert!(
            combined_sql.contains("RENAME"),
            "Expected RENAME for temp table, got: {}",
            combined_sql
        );
    }

    #[test]
    fn test_delete_column_sqlite_with_fk_preserves_other_columns() {
        // When using temp table approach, other columns should be preserved
        let schema = vec![TableDef {
            name: "gift".into(),
            description: None,
            columns: vec![
                col("id", ColumnType::Simple(SimpleColumnType::Integer)),
                col("sender_id", ColumnType::Simple(SimpleColumnType::BigInt)),
                col("receiver_id", ColumnType::Simple(SimpleColumnType::BigInt)),
                col("message", ColumnType::Simple(SimpleColumnType::Text)),
            ],
            constraints: vec![
                TableConstraint::ForeignKey {
                    name: None,
                    columns: vec!["sender_id".into()],
                    ref_table: "user".into(),
                    ref_columns: vec!["id".into()],
                    on_delete: None,
                    on_update: None,
                },
                TableConstraint::Index {
                    name: None,
                    columns: vec!["receiver_id".into()],
                },
            ],
        }];

        let result = build_delete_column(
            &DatabaseBackend::Sqlite,
            "gift",
            "sender_id",
            None,
            &schema,
            &[],
        );

        let all_sql: Vec<String> = result
            .iter()
            .map(|q| q.build(DatabaseBackend::Sqlite))
            .collect();
        let combined_sql = all_sql.join("\n");

        // Should preserve other columns
        assert!(combined_sql.contains("\"id\""), "Should preserve id column");
        assert!(
            combined_sql.contains("\"receiver_id\""),
            "Should preserve receiver_id column"
        );
        assert!(
            combined_sql.contains("\"message\""),
            "Should preserve message column"
        );

        // Should recreate index on receiver_id (not on sender_id)
        assert!(
            combined_sql.contains("CREATE INDEX") && combined_sql.contains("ix_gift__receiver_id"),
            "Should recreate index on receiver_id, got: {}",
            combined_sql
        );
    }

    #[test]
    fn test_delete_column_postgres_with_fk_does_not_use_temp_table() {
        // PostgreSQL should NOT use temp table - just drop column directly
        let schema = vec![TableDef {
            name: "gift".into(),
            description: None,
            columns: vec![
                col("id", ColumnType::Simple(SimpleColumnType::Integer)),
                col("sender_id", ColumnType::Simple(SimpleColumnType::BigInt)),
            ],
            constraints: vec![TableConstraint::ForeignKey {
                name: None,
                columns: vec!["sender_id".into()],
                ref_table: "user".into(),
                ref_columns: vec!["id".into()],
                on_delete: None,
                on_update: None,
            }],
        }];

        let result = build_delete_column(
            &DatabaseBackend::Postgres,
            "gift",
            "sender_id",
            None,
            &schema,
            &[],
        );

        // Should have only 1 statement: ALTER TABLE DROP COLUMN
        assert_eq!(
            result.len(),
            1,
            "PostgreSQL should only have 1 statement, got: {}",
            result.len()
        );

        let sql = result[0].build(DatabaseBackend::Postgres);
        assert!(
            sql.contains("DROP COLUMN"),
            "Expected DROP COLUMN, got: {}",
            sql
        );
        assert!(
            !sql.contains("gift_temp"),
            "PostgreSQL should not use temp table"
        );
    }

    #[test]
    fn test_delete_column_sqlite_with_pk_uses_temp_table() {
        // SQLite should use temp table approach when deleting a column that's part of PK
        let schema = vec![TableDef {
            name: "order_items".into(),
            description: None,
            columns: vec![
                col("order_id", ColumnType::Simple(SimpleColumnType::Integer)),
                col("product_id", ColumnType::Simple(SimpleColumnType::Integer)),
                col("quantity", ColumnType::Simple(SimpleColumnType::Integer)),
            ],
            constraints: vec![TableConstraint::PrimaryKey {
                auto_increment: false,
                columns: vec!["order_id".into(), "product_id".into()],
            }],
        }];

        let result = build_delete_column(
            &DatabaseBackend::Sqlite,
            "order_items",
            "product_id",
            None,
            &schema,
            &[],
        );

        // Should use temp table approach
        assert!(
            result.len() >= 4,
            "Expected at least 4 statements for temp table approach, got: {}",
            result.len()
        );

        let all_sql: Vec<String> = result
            .iter()
            .map(|q| q.build(DatabaseBackend::Sqlite))
            .collect();
        let combined_sql = all_sql.join("\n");

        assert!(
            combined_sql.contains("order_items_temp"),
            "Should use temp table approach for PK column deletion"
        );
    }

    #[test]
    fn test_delete_column_sqlite_unique_on_different_column_not_dropped() {
        // When deleting a column in SQLite, UNIQUE constraints on OTHER columns should NOT be dropped
        // This tests line 46's condition: only drop constraints that reference the deleted column
        let schema = vec![TableDef {
            name: "users".into(),
            description: None,
            columns: vec![
                col("id", ColumnType::Simple(SimpleColumnType::Integer)),
                col("email", ColumnType::Simple(SimpleColumnType::Text)),
                col("nickname", ColumnType::Simple(SimpleColumnType::Text)),
            ],
            constraints: vec![
                // UNIQUE on email (the column we're NOT deleting)
                TableConstraint::Unique {
                    name: None,
                    columns: vec!["email".into()],
                },
            ],
        }];

        // Delete nickname, which does NOT have the unique constraint
        let result = build_delete_column(
            &DatabaseBackend::Sqlite,
            "users",
            "nickname",
            None,
            &schema,
            &[],
        );

        // Should only have 1 statement: ALTER TABLE DROP COLUMN (no DROP INDEX needed)
        assert_eq!(
            result.len(),
            1,
            "Should not drop UNIQUE on email when deleting nickname, got: {} statements",
            result.len()
        );

        let sql = result[0].build(DatabaseBackend::Sqlite);
        assert!(
            sql.contains("DROP COLUMN"),
            "Expected DROP COLUMN, got: {}",
            sql
        );
        assert!(
            !sql.contains("DROP INDEX"),
            "Should NOT drop the email UNIQUE constraint when deleting nickname"
        );
    }

    #[test]
    fn test_delete_column_sqlite_temp_table_filters_constraints_correctly() {
        // When using temp table approach, constraints referencing the deleted column should be excluded,
        // but constraints on OTHER columns should be preserved
        // This tests lines 122-124: filter constraints by column reference
        let schema = vec![TableDef {
            name: "orders".into(),
            description: None,
            columns: vec![
                col("id", ColumnType::Simple(SimpleColumnType::Integer)),
                col("user_id", ColumnType::Simple(SimpleColumnType::BigInt)),
                col("status", ColumnType::Simple(SimpleColumnType::Text)),
                col(
                    "created_at",
                    ColumnType::Simple(SimpleColumnType::Timestamp),
                ),
            ],
            constraints: vec![
                // FK on user_id (column we're deleting) - should be excluded
                TableConstraint::ForeignKey {
                    name: None,
                    columns: vec!["user_id".into()],
                    ref_table: "users".into(),
                    ref_columns: vec!["id".into()],
                    on_delete: None,
                    on_update: None,
                },
                // Index on created_at (different column) - should be preserved and recreated
                TableConstraint::Index {
                    name: None,
                    columns: vec!["created_at".into()],
                },
                // Another FK on a different column - should be preserved
                TableConstraint::ForeignKey {
                    name: None,
                    columns: vec!["status".into()],
                    ref_table: "statuses".into(),
                    ref_columns: vec!["code".into()],
                    on_delete: None,
                    on_update: None,
                },
            ],
        }];

        let result = build_delete_column(
            &DatabaseBackend::Sqlite,
            "orders",
            "user_id",
            None,
            &schema,
            &[],
        );

        let all_sql: Vec<String> = result
            .iter()
            .map(|q| q.build(DatabaseBackend::Sqlite))
            .collect();
        let combined_sql = all_sql.join("\n");

        // Should use temp table approach (FK triggers it)
        assert!(
            combined_sql.contains("orders_temp"),
            "Should use temp table approach for FK column deletion"
        );

        // Index on created_at should be recreated after rename
        assert!(
            combined_sql.contains("ix_orders__created_at"),
            "Index on created_at should be recreated, got: {}",
            combined_sql
        );

        // The FK on user_id should NOT appear (deleted column)
        // But the FK on status should be preserved
        assert!(
            combined_sql.contains("REFERENCES \"statuses\""),
            "FK on status should be preserved, got: {}",
            combined_sql
        );

        // Count FK references - should only be 1 (status FK, not user_id FK)
        let fk_patterns = combined_sql.matches("REFERENCES").count();
        assert_eq!(
            fk_patterns, 1,
            "Only the FK on status should exist (not the one on user_id), got: {}",
            combined_sql
        );
    }

    // ==================== Snapshot Tests ====================

    fn build_sql_snapshot(result: &[BuiltQuery], backend: DatabaseBackend) -> String {
        result
            .iter()
            .map(|q| q.build(backend))
            .collect::<Vec<_>>()
            .join(";\n")
    }

    #[rstest]
    #[case::postgres("postgres", DatabaseBackend::Postgres)]
    #[case::mysql("mysql", DatabaseBackend::MySql)]
    #[case::sqlite("sqlite", DatabaseBackend::Sqlite)]
    fn test_delete_column_with_unique_constraint(
        #[case] title: &str,
        #[case] backend: DatabaseBackend,
    ) {
        let schema = vec![TableDef {
            name: "users".into(),
            description: None,
            columns: vec![
                col("id", ColumnType::Simple(SimpleColumnType::Integer)),
                col("email", ColumnType::Simple(SimpleColumnType::Text)),
                col("name", ColumnType::Simple(SimpleColumnType::Text)),
            ],
            constraints: vec![TableConstraint::Unique {
                name: None,
                columns: vec!["email".into()],
            }],
        }];

        let result = build_delete_column(&backend, "users", "email", None, &schema, &[]);
        let sql = build_sql_snapshot(&result, backend);

        with_settings!({ snapshot_suffix => format!("delete_column_with_unique_{}", title) }, {
            assert_snapshot!(sql);
        });
    }

    #[rstest]
    #[case::postgres("postgres", DatabaseBackend::Postgres)]
    #[case::mysql("mysql", DatabaseBackend::MySql)]
    #[case::sqlite("sqlite", DatabaseBackend::Sqlite)]
    fn test_delete_column_with_index_constraint(
        #[case] title: &str,
        #[case] backend: DatabaseBackend,
    ) {
        let schema = vec![TableDef {
            name: "posts".into(),
            description: None,
            columns: vec![
                col("id", ColumnType::Simple(SimpleColumnType::Integer)),
                col(
                    "created_at",
                    ColumnType::Simple(SimpleColumnType::Timestamp),
                ),
                col("title", ColumnType::Simple(SimpleColumnType::Text)),
            ],
            constraints: vec![TableConstraint::Index {
                name: None,
                columns: vec!["created_at".into()],
            }],
        }];

        let result = build_delete_column(&backend, "posts", "created_at", None, &schema, &[]);
        let sql = build_sql_snapshot(&result, backend);

        with_settings!({ snapshot_suffix => format!("delete_column_with_index_{}", title) }, {
            assert_snapshot!(sql);
        });
    }

    #[rstest]
    #[case::postgres("postgres", DatabaseBackend::Postgres)]
    #[case::mysql("mysql", DatabaseBackend::MySql)]
    #[case::sqlite("sqlite", DatabaseBackend::Sqlite)]
    fn test_delete_column_with_fk_constraint(
        #[case] title: &str,
        #[case] backend: DatabaseBackend,
    ) {
        let schema = vec![TableDef {
            name: "orders".into(),
            description: None,
            columns: vec![
                col("id", ColumnType::Simple(SimpleColumnType::Integer)),
                col("user_id", ColumnType::Simple(SimpleColumnType::BigInt)),
                col("total", ColumnType::Simple(SimpleColumnType::Integer)),
            ],
            constraints: vec![TableConstraint::ForeignKey {
                name: None,
                columns: vec!["user_id".into()],
                ref_table: "users".into(),
                ref_columns: vec!["id".into()],
                on_delete: None,
                on_update: None,
            }],
        }];

        let result = build_delete_column(&backend, "orders", "user_id", None, &schema, &[]);
        let sql = build_sql_snapshot(&result, backend);

        with_settings!({ snapshot_suffix => format!("delete_column_with_fk_{}", title) }, {
            assert_snapshot!(sql);
        });
    }

    #[rstest]
    #[case::postgres("postgres", DatabaseBackend::Postgres)]
    #[case::mysql("mysql", DatabaseBackend::MySql)]
    #[case::sqlite("sqlite", DatabaseBackend::Sqlite)]
    fn test_delete_column_with_pk_constraint(
        #[case] title: &str,
        #[case] backend: DatabaseBackend,
    ) {
        let schema = vec![TableDef {
            name: "order_items".into(),
            description: None,
            columns: vec![
                col("order_id", ColumnType::Simple(SimpleColumnType::Integer)),
                col("product_id", ColumnType::Simple(SimpleColumnType::Integer)),
                col("quantity", ColumnType::Simple(SimpleColumnType::Integer)),
            ],
            constraints: vec![TableConstraint::PrimaryKey {
                auto_increment: false,
                columns: vec!["order_id".into(), "product_id".into()],
            }],
        }];

        let result = build_delete_column(&backend, "order_items", "product_id", None, &schema, &[]);
        let sql = build_sql_snapshot(&result, backend);

        with_settings!({ snapshot_suffix => format!("delete_column_with_pk_{}", title) }, {
            assert_snapshot!(sql);
        });
    }

    #[rstest]
    #[case::postgres("postgres", DatabaseBackend::Postgres)]
    #[case::mysql("mysql", DatabaseBackend::MySql)]
    #[case::sqlite("sqlite", DatabaseBackend::Sqlite)]
    fn test_delete_column_with_fk_and_index_constraints(
        #[case] title: &str,
        #[case] backend: DatabaseBackend,
    ) {
        // Complex case: FK on the deleted column + Index on another column
        let schema = vec![TableDef {
            name: "orders".into(),
            description: None,
            columns: vec![
                col("id", ColumnType::Simple(SimpleColumnType::Integer)),
                col("user_id", ColumnType::Simple(SimpleColumnType::BigInt)),
                col(
                    "created_at",
                    ColumnType::Simple(SimpleColumnType::Timestamp),
                ),
                col("total", ColumnType::Simple(SimpleColumnType::Integer)),
            ],
            constraints: vec![
                TableConstraint::ForeignKey {
                    name: None,
                    columns: vec!["user_id".into()],
                    ref_table: "users".into(),
                    ref_columns: vec!["id".into()],
                    on_delete: None,
                    on_update: None,
                },
                TableConstraint::Index {
                    name: None,
                    columns: vec!["created_at".into()],
                },
            ],
        }];

        let result = build_delete_column(&backend, "orders", "user_id", None, &schema, &[]);
        let sql = build_sql_snapshot(&result, backend);

        with_settings!({ snapshot_suffix => format!("delete_column_with_fk_and_index_{}", title) }, {
            assert_snapshot!(sql);
        });
    }

    #[test]
    fn test_delete_column_sqlite_temp_table_with_enum_column() {
        // SQLite temp table approach with enum column type
        // This tests lines 122-124: enum type drop in temp table function
        use vespertide_core::EnumValues;

        let enum_type = ColumnType::Complex(ComplexColumnType::Enum {
            name: "order_status".into(),
            values: EnumValues::String(vec![
                "pending".into(),
                "shipped".into(),
                "delivered".into(),
            ]),
        });

        let schema = vec![TableDef {
            name: "orders".into(),
            description: None,
            columns: vec![
                col("id", ColumnType::Simple(SimpleColumnType::Integer)),
                col("user_id", ColumnType::Simple(SimpleColumnType::BigInt)),
                col("status", enum_type.clone()),
            ],
            constraints: vec![TableConstraint::ForeignKey {
                name: None,
                columns: vec!["user_id".into()],
                ref_table: "users".into(),
                ref_columns: vec!["id".into()],
                on_delete: None,
                on_update: None,
            }],
        }];

        // Delete the FK column (user_id) with an enum type - triggers temp table AND enum drop
        let result = build_delete_column(
            &DatabaseBackend::Sqlite,
            "orders",
            "user_id",
            Some(&enum_type),
            &schema,
            &[],
        );

        // Should use temp table approach (FK triggers it) + DROP TYPE at end
        assert!(
            result.len() >= 4,
            "Expected at least 4 statements for temp table approach, got: {}",
            result.len()
        );

        let all_sql: Vec<String> = result
            .iter()
            .map(|q| q.build(DatabaseBackend::Sqlite))
            .collect();
        let combined_sql = all_sql.join("\n");

        // Verify temp table approach
        assert!(
            combined_sql.contains("orders_temp"),
            "Should use temp table approach"
        );

        // The DROP TYPE statement should be empty for SQLite (only applies to PostgreSQL)
        // but the code path should still be executed
        let last_stmt = result.last().unwrap();
        let last_sql = last_stmt.build(DatabaseBackend::Sqlite);
        // SQLite doesn't have DROP TYPE, so it should be empty string
        assert!(
            last_sql.is_empty() || !last_sql.contains("DROP TYPE"),
            "SQLite should not emit DROP TYPE"
        );

        // Verify it DOES emit DROP TYPE for PostgreSQL
        let pg_last_sql = last_stmt.build(DatabaseBackend::Postgres);
        assert!(
            pg_last_sql.contains("DROP TYPE"),
            "PostgreSQL should emit DROP TYPE, got: {}",
            pg_last_sql
        );
    }

    #[test]
    fn test_delete_column_sqlite_with_check_constraint_referencing_column() {
        // When a CHECK constraint references the column being deleted,
        // SQLite can't use ALTER TABLE DROP COLUMN — must use temp table approach.
        let schema = vec![TableDef {
            name: "orders".into(),
            description: None,
            columns: vec![
                col("id", ColumnType::Simple(SimpleColumnType::Integer)),
                col("amount", ColumnType::Simple(SimpleColumnType::Integer)),
            ],
            constraints: vec![TableConstraint::Check {
                name: "check_positive".into(),
                expr: "amount > 0".into(),
            }],
        }];

        // Delete amount column — CHECK references it, so temp table is needed
        let result = build_delete_column(
            &DatabaseBackend::Sqlite,
            "orders",
            "amount",
            None,
            &schema,
            &[],
        );

        // Should use temp table approach (CREATE temp, INSERT, DROP, RENAME)
        assert!(
            result.len() >= 4,
            "Expected temp table approach (>=4 stmts), got: {} statements",
            result.len()
        );

        let sql = result[0].build(DatabaseBackend::Sqlite);
        assert!(
            sql.contains("orders_temp"),
            "Expected temp table creation, got: {}",
            sql
        );
        // The CHECK constraint referencing "amount" should NOT be in the temp table
        assert!(
            !sql.contains("check_positive"),
            "CHECK referencing deleted column should be removed, got: {}",
            sql
        );
    }

    #[test]
    fn test_delete_column_sqlite_with_check_constraint_not_referencing_column() {
        // When a CHECK constraint does NOT reference the column being deleted,
        // simple DROP COLUMN should work.
        let schema = vec![TableDef {
            name: "orders".into(),
            description: None,
            columns: vec![
                col("id", ColumnType::Simple(SimpleColumnType::Integer)),
                col("amount", ColumnType::Simple(SimpleColumnType::Integer)),
                col("note", ColumnType::Simple(SimpleColumnType::Text)),
            ],
            constraints: vec![TableConstraint::Check {
                name: "check_positive".into(),
                expr: "amount > 0".into(),
            }],
        }];

        // Delete "note" column — CHECK only references "amount", not "note"
        let result = build_delete_column(
            &DatabaseBackend::Sqlite,
            "orders",
            "note",
            None,
            &schema,
            &[],
        );

        assert_eq!(
            result.len(),
            1,
            "Unrelated CHECK should be skipped, got: {} statements",
            result.len()
        );

        let sql = result[0].build(DatabaseBackend::Sqlite);
        assert!(
            sql.contains("DROP COLUMN"),
            "Expected DROP COLUMN, got: {}",
            sql
        );
    }
}