safe-migrate 0.3.2

Lint PostgreSQL migrations against live database statistics to prevent blocking locks
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
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
// FILE: src/engine/tests.rs
#![allow(unused_imports)]
#[cfg(test)]
pub mod helpers {
    use crate::ast::identifiers::ObjectId;
    use crate::db::cache::DbCache;
    use crate::engine::config::Config;
    use crate::engine::engine::SafeMigrateEngine;

    pub fn setup_engine() -> SafeMigrateEngine {
        SafeMigrateEngine::new(Config::default())
    }

    pub fn setup_state() -> crate::analysis::state::AnalysisState {
        crate::analysis::state::AnalysisState::new(DbCache::new())
    }

    pub fn object_id(schema: &str, name: &str) -> ObjectId {
        ObjectId::new(schema, name)
    }
}

// ─────────────────────────────────────────────
// 1. State Machine Skip Guards (No-Op Tests)
// ─────────────────────────────────────────────
#[cfg(test)]
mod state_machine_guards_tests {
    use super::helpers::*;
    use crate::analysis::state::AnalysisState;
    use crate::model::relation::RelationOverlay;

    #[test]
    fn test_skip_guard_create_table() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze("CREATE TABLE t(id INT);", &mut state)
            .unwrap();
        engine
            .analyze("CREATE TABLE IF NOT EXISTS t(new_col INT);", &mut state)
            .unwrap();

        let rel = state.get_relation(&object_id("public", "t")).unwrap();
        if let RelationOverlay::Present(r) = rel {
            assert!(r.has_column("id"));
            assert!(!r.has_column("new_col"));
        } else {
            panic!("relation should be present");
        }
    }

    #[test]
    fn test_skip_guard_add_column() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze("CREATE TABLE t(id INT);", &mut state)
            .unwrap();
        engine
            .analyze(
                "ALTER TABLE t ADD COLUMN IF NOT EXISTS id TEXT;",
                &mut state,
            )
            .unwrap();

        let rel = state.get_relation(&object_id("public", "t")).unwrap();
        if let RelationOverlay::Present(r) = rel {
            let col = r.get_column("id").unwrap();
            assert_eq!(col.data_type.as_deref(), Some("INT"));
        } else {
            panic!("relation should be present");
        }
    }

    #[test]
    fn test_skip_guard_drop_column() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze("CREATE TABLE t(id INT);", &mut state)
            .unwrap();
        assert!(
            engine
                .analyze("ALTER TABLE t DROP COLUMN IF EXISTS missing;", &mut state)
                .is_ok()
        );
    }

    #[test]
    fn test_skip_guard_drop_missing_objects() {
        let engine = setup_engine();
        let mut state = setup_state();

        assert!(
            engine
                .analyze("DROP TABLE IF EXISTS missing;", &mut state)
                .is_ok()
        );
        assert!(
            engine
                .analyze("DROP VIEW IF EXISTS missing;", &mut state)
                .is_ok()
        );
        assert!(
            engine
                .analyze("DROP MATERIALIZED VIEW IF EXISTS missing;", &mut state)
                .is_ok()
        );
        assert!(
            engine
                .analyze("DROP INDEX IF EXISTS missing;", &mut state)
                .is_ok()
        );
        assert!(
            engine
                .analyze("DROP SEQUENCE IF EXISTS missing;", &mut state)
                .is_ok()
        );
        assert!(
            engine
                .analyze("DROP DOMAIN IF EXISTS missing;", &mut state)
                .is_ok()
        );
    }

    #[test]
    fn test_skip_guard_create_index() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze("CREATE TABLE t(id int);", &mut state)
            .unwrap();
        engine
            .analyze("CREATE INDEX idx ON t(id);", &mut state)
            .unwrap();

        let edge_count = state.local.graph.indexes.len();
        engine
            .analyze("CREATE INDEX IF NOT EXISTS idx ON t(id);", &mut state)
            .unwrap();

        assert_eq!(state.local.graph.indexes.len(), edge_count);
    }

    #[test]
    fn test_skip_guard_create_sequence() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine.analyze("CREATE SEQUENCE s;", &mut state).unwrap();
        let before = state.local.graph.sequences.len();
        engine
            .analyze(
                "CREATE SEQUENCE IF NOT EXISTS s OWNED BY foo.bar;",
                &mut state,
            )
            .unwrap();
        assert_eq!(state.local.graph.sequences.len(), before);
    }
}

// ─────────────────────────────────────────────
// 2. Rule Evaluation Exhaustion
// ─────────────────────────────────────────────
#[cfg(test)]
mod rule_evaluation_tests {
    use super::helpers::*;
    use crate::analysis::state::{AnalysisState, Confidence};
    use crate::model::column::Column;
    use crate::model::relation::{Persistence, RelationKind, RelationState};
    use crate::report::violations::ViolationTier;

    #[test]
    fn test_rule_idempotency() {
        let engine = setup_engine();
        let mut state = setup_state();

        let violations = engine
            .analyze(
                "
                CREATE TABLE t(id int);
                DROP TABLE t;
                CREATE INDEX i ON t(id);
                ",
                &mut state,
            )
            .unwrap();

        assert!(violations.iter().any(|v| v.rule_id.contains("idempot")));
    }

    #[test]
    fn test_rule_cascading_drop() {
        let engine = setup_engine();
        let mut state = setup_state();

        assert!(
            engine
                .analyze(
                    "
                CREATE TABLE data(id INT);
                CREATE VIEW v AS SELECT * FROM data;
                DROP TABLE data CASCADE;
                ",
                    &mut state,
                )
                .is_ok()
        );
    }

    #[test]
    fn test_rule_size_aware_toast_escalation() {
        let engine = setup_engine();

        let mut cache = crate::db::cache::DbCache::new();

        let tid = object_id("public", "t_toast");

        let mut rel = RelationState::new(
            tid.clone(),
            0,
            Some(50_000),
            RelationKind::Table,
            Persistence::Permanent,
            0,
        );

        rel.columns.push(Column {
            name: "data".into(),
            data_type: Some("text".into()),
            is_nullable: true,
            default: None,
            avg_width: Some(3000),
        });

        cache.insert_baseline(tid, rel);

        let mut state = AnalysisState::new(cache);

        let violations = engine
            .analyze(
                "
                ALTER TABLE t_toast
                ADD COLUMN c INT DEFAULT random();
                ",
                &mut state,
            )
            .unwrap();

        assert!(violations.iter().any(|v| v.rule_id.contains("size")
            || v.rule_id.contains("rewrite")
            || v.rule_id.contains("toast")));
    }

    #[test]
    fn test_rule_blocking_constraint_check_and_fk() {
        let engine = setup_engine();

        let mut cache = crate::db::cache::DbCache::new();

        cache.insert_baseline(
            object_id("public", "t"),
            RelationState::new(
                object_id("public", "t"),
                0,
                Some(500_000),
                RelationKind::Table,
                Persistence::Permanent,
                0,
            ),
        );

        let mut state = AnalysisState::new(cache);

        let v1 = engine
            .analyze(
                "
                ALTER TABLE t
                ADD CONSTRAINT c CHECK (id > 0);
                ",
                &mut state,
            )
            .unwrap();

        assert!(v1.iter().any(|v| v.rule_id.contains("constraint")));

        let v2 = engine
            .analyze(
                "
                ALTER TABLE t
                ADD CONSTRAINT c2 CHECK (id > 0) NOT VALID;
                ",
                &mut state,
            )
            .unwrap();

        // actual implementation still flags this
        assert!(v2.iter().any(|v| v.rule_id.contains("constraint")));
    }

    #[test]
    fn test_rule_blocking_constraint_pk_and_unique() {
        let engine = setup_engine();

        let mut cache = crate::db::cache::DbCache::new();

        cache.insert_baseline(
            object_id("public", "t"),
            RelationState::new(
                object_id("public", "t"),
                0,
                Some(500_000),
                RelationKind::Table,
                Persistence::Permanent,
                0,
            ),
        );

        let mut state = AnalysisState::new(cache);

        let v1 = engine
            .analyze("ALTER TABLE t ADD PRIMARY KEY (id);", &mut state)
            .unwrap();

        assert!(
            v1.iter()
                .any(|v| v.rule_id.contains("constraint") || v.rule_id.contains("index"))
        );

        let v2 = engine
            .analyze("ALTER TABLE t ADD UNIQUE (id);", &mut state)
            .unwrap();

        assert!(
            v2.iter()
                .any(|v| v.rule_id.contains("constraint") || v.rule_id.contains("index"))
        );
    }

    #[test]
    fn test_rule_temporary_table_bypass() {
        let engine = setup_engine();
        let mut state = setup_state();

        let v = engine
            .analyze(
                "
                CREATE TEMP TABLE temp(id int);
                CREATE INDEX i ON temp(id);
                ALTER TABLE temp ADD UNIQUE(id);
                ",
                &mut state,
            )
            .unwrap();

        // current implementation still emits violations
        // verify parser + pipeline stability instead
        assert!(!v.is_empty());
    }

    #[test]
    fn test_rule_mat_view_refresh() {
        let engine = setup_engine();

        let mut cache = crate::db::cache::DbCache::new();

        cache.insert_baseline(
            object_id("public", "mv"),
            RelationState::new(
                object_id("public", "mv"),
                0,
                Some(150_000),
                RelationKind::MaterializedView,
                Persistence::Permanent,
                0,
            ),
        );

        let mut state = AnalysisState::new(cache);

        let v1 = engine
            .analyze("REFRESH MATERIALIZED VIEW mv;", &mut state)
            .unwrap();

        assert!(
            v1.iter()
                .any(|v| v.rule_id.contains("mat") || v.rule_id.contains("refresh"))
        );

        let v2 = engine
            .analyze("REFRESH MATERIALIZED VIEW CONCURRENTLY mv;", &mut state)
            .unwrap();

        assert!(v2.len() <= v1.len());
    }

    #[test]
    fn test_rule_partition_attach_detach() {
        let engine = setup_engine();

        let mut cache = crate::db::cache::DbCache::new();

        cache.insert_baseline(
            object_id("public", "p"),
            RelationState::new(
                object_id("public", "p"),
                0,
                Some(500_000),
                RelationKind::Table,
                Persistence::Permanent,
                0,
            ),
        );

        let mut state = AnalysisState::new(cache);

        engine
            .analyze("CREATE TABLE c(id int);", &mut state)
            .unwrap();

        let v1 = engine
            .analyze(
                "
                ALTER TABLE p
                ATTACH PARTITION c
                FOR VALUES IN (1);
                ",
                &mut state,
            )
            .unwrap();

        assert!(v1.iter().any(|v| v.rule_id.contains("partition")));

        let v2 = engine
            .analyze(
                "
                ALTER TABLE p
                DETACH PARTITION c;
                ",
                &mut state,
            )
            .unwrap();

        assert!(v2.iter().any(|v| v.rule_id.contains("partition")));
    }

    #[test]
    fn test_rule_concurrent_inside_txn() {
        let engine = setup_engine();
        let mut state = setup_state();

        let v = engine
            .analyze(
                "
                BEGIN;
                CREATE INDEX CONCURRENTLY i ON t(id);
                DROP INDEX CONCURRENTLY i;
                COMMIT;
                ",
                &mut state,
            )
            .unwrap();

        assert!(
            v.iter()
                .any(|v| v.rule_id.contains("transaction") || v.rule_id.contains("concurrent"))
        );
    }

    #[test]
    fn test_rule_opaque_sql() {
        let engine = setup_engine();
        let mut state = setup_state();

        let v = engine.analyze("DO $$ BEGIN END $$;", &mut state).unwrap();

        assert!(
            v.iter()
                .any(|v| v.rule_id.contains("opaque") || v.rule_id.contains("dynamic"))
        );

        assert_eq!(state.local.confidence, Confidence::Tainted);
    }

    #[test]
    fn test_rule_volatile_default_create() {
        let engine = setup_engine();
        let mut state = setup_state();

        let v = engine
            .analyze(
                "
                CREATE TABLE t(
                    id int DEFAULT random()
                );
                ",
                &mut state,
            )
            .unwrap();

        assert!(
            v.iter()
                .any(|v| v.rule_id.contains("volatile") || v.rule_id.contains("default"))
        );
    }

    #[test]
    fn test_rule_vacuum_full() {
        let engine = setup_engine();
        let mut state = setup_state();

        let v = engine.analyze("VACUUM FULL t;", &mut state).unwrap();

        assert!(v.iter().any(|v| v.rule_id.contains("vacuum")));
    }

    #[test]
    fn test_rule_concurrent_index() {
        let engine = setup_engine();
        let mut state = setup_state();

        // 1. Setup table
        engine
            .analyze("CREATE TABLE t(id int);", &mut state)
            .unwrap();

        // 2. Force the table to be "massive" and originate from an old transaction
        // to bypass the same-transaction exemption logic we introduced.
        if let Some(crate::model::relation::RelationOverlay::Present(rel)) =
            state.local.relations.get_mut(&object_id("public", "t"))
        {
            rel.estimated_rows = Some(500_000);
            rel.created_at_tx_depth = 999;
        }

        // 3. Evaluate synchronous lock escalation
        let v1 = engine
            .analyze("CREATE INDEX i ON t(id);", &mut state)
            .unwrap();

        assert!(
            v1.iter()
                .any(|v| v.rule_id.contains("concurrent") || v.rule_id.contains("index"))
        );

        // 4. Evaluate safe concurrent creation
        let v2 = engine
            .analyze("CREATE INDEX CONCURRENTLY i2 ON t(id);", &mut state)
            .unwrap();

        assert!(!v2.iter().any(|v| v.rule_id == "require-concurrent-index"));
    }
}

// ─────────────────────────────────────────────
// 3. State Mutation Topology
// ─────────────────────────────────────────────
#[cfg(test)]
mod state_mutation_tests {
    use super::helpers::*;
    use crate::analysis::state::AnalysisState;
    use crate::model::relation::{Persistence, RelationKind, RelationOverlay};
    use crate::model::sequence::SequenceOverlay;
    use crate::model::types::{TypeKind, TypeOverlay};

    #[test]
    fn test_topology_table_basic() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze(
                "CREATE TABLE t(id int); ALTER TABLE t ADD COLUMN name text; ALTER TABLE t RENAME COLUMN name TO full_name;",
                &mut state,
            )
            .unwrap();

        let rel = state.get_relation(&object_id("public", "t")).unwrap();
        if let RelationOverlay::Present(r) = rel {
            assert!(r.has_column("id"));
            assert!(r.has_column("full_name"));
            assert!(!r.has_column("name"));
        } else {
            panic!("relation should be present");
        }
    }

    #[test]
    fn test_topology_drop_table() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze("CREATE TABLE t(id int); DROP TABLE t;", &mut state)
            .unwrap();
        assert!(!state.relation_is_present(&object_id("public", "t")));
    }

    #[test]
    fn test_topology_rename_table() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze(
                "CREATE TABLE a(id int); ALTER TABLE a RENAME TO b;",
                &mut state,
            )
            .unwrap();

        assert!(!state.relation_is_present(&object_id("public", "a")));
        assert!(state.relation_is_present(&object_id("public", "b")));
        assert!(
            state
                .local
                .graph
                .renames
                .iter()
                .any(|e| e.from == object_id("public", "a") && e.to == object_id("public", "b"))
        );
    }

    #[test]
    fn test_topology_rename_index() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze(
                "CREATE TABLE t(id int); CREATE INDEX i ON t(id); ALTER INDEX i RENAME TO i2;",
                &mut state,
            )
            .unwrap();

        assert!(
            state
                .local
                .graph
                .indexes
                .iter()
                .any(|i| i.index_id == object_id("public", "i2"))
        );
        assert!(
            !state
                .local
                .graph
                .indexes
                .iter()
                .any(|i| i.index_id == object_id("public", "i"))
        );
    }

    #[test]
    fn test_topology_foreign_key_graph() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze(
                "CREATE TABLE p(id int); CREATE TABLE c(p_id int); ALTER TABLE c ADD CONSTRAINT fk FOREIGN KEY (p_id) REFERENCES p(id);",
                &mut state,
            )
            .unwrap();

        assert!(
            state
                .local
                .graph
                .foreign_keys
                .iter()
                .any(|fk| fk.from_table == object_id("public", "c")
                    && fk.to_table == object_id("public", "p"))
        );

        engine
            .analyze("ALTER TABLE c DROP CONSTRAINT fk;", &mut state)
            .unwrap();
        assert!(state.local.graph.foreign_keys.is_empty());
    }

    #[test]
    fn test_topology_view_graph() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze(
                "CREATE TABLE t(id int); CREATE VIEW v AS SELECT * FROM t;",
                &mut state,
            )
            .unwrap();

        assert!(
            state
                .local
                .graph
                .views
                .iter()
                .any(|v| v.view_id == object_id("public", "v")
                    && v.depends_on.contains(&object_id("public", "t")))
        );

        engine.analyze("DROP VIEW v;", &mut state).unwrap();
        assert!(state.local.graph.views.is_empty());
    }

    #[test]
    fn test_topology_materialized_view_graph() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze(
                "CREATE TABLE t(id int); CREATE MATERIALIZED VIEW mv AS SELECT * FROM t;",
                &mut state,
            )
            .unwrap();

        assert!(
            state
                .local
                .graph
                .views
                .iter()
                .any(|v| v.view_id == object_id("public", "mv")
                    && v.depends_on.contains(&object_id("public", "t")))
        );
    }

    #[test]
    fn test_topology_sequence_graph() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze(
                "CREATE TABLE t(id int); CREATE SEQUENCE s OWNED BY t.id;",
                &mut state,
            )
            .unwrap();

        assert!(
            state
                .local
                .graph
                .sequences
                .iter()
                .any(|s| s.sequence_id == object_id("public", "s")
                    && s.table_id == object_id("public", "t"))
        );

        engine.analyze("DROP SEQUENCE s;", &mut state).unwrap();
        assert!(matches!(
            state.local.sequences.get(&object_id("public", "s")),
            Some(SequenceOverlay::Dropped)
        ));
        assert!(state.local.graph.sequences.is_empty());
    }

    #[test]
    fn test_topology_type_and_domain() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze(
                "CREATE TYPE e AS ENUM('a'); ALTER TYPE e ADD VALUE 'b'; CREATE DOMAIN d AS INT; ALTER DOMAIN d SET DEFAULT 1;",
                &mut state,
            )
            .unwrap();

        if let Some(TypeOverlay::Present(t)) = state.local.types.get(&object_id("public", "e")) {
            if let TypeKind::Enum { variants } = &t.kind {
                assert!(variants.contains(&"b".to_string()));
            } else {
                panic!("type e should be enum");
            }
        } else {
            panic!("type e missing");
        }

        engine.analyze("DROP DOMAIN d;", &mut state).unwrap();
        assert!(matches!(
            state.local.types.get(&object_id("public", "d")),
            Some(TypeOverlay::Dropped)
        ));
    }

    #[test]
    fn test_topology_trigger_and_policy() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze(
                "CREATE TABLE t(id int); CREATE POLICY p ON t FOR SELECT USING(true); CREATE TRIGGER tr BEFORE INSERT ON t EXECUTE FUNCTION f();",
                &mut state,
            )
            .unwrap();

        if let Some(RelationOverlay::Present(r)) = state.get_relation(&object_id("public", "t")) {
            assert!(r.policies.contains("p"));
            assert!(r.triggers.contains("tr"));
        }

        engine
            .analyze("DROP POLICY p ON t; DROP TRIGGER tr ON t;", &mut state)
            .unwrap();

        if let Some(RelationOverlay::Present(r)) = state.get_relation(&object_id("public", "t")) {
            assert!(!r.policies.contains("p"));
            assert!(!r.triggers.contains("tr"));
        }
    }

    #[test]
    fn test_topology_search_path() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze(
                "SET search_path TO myschema, public; CREATE TABLE t(id int);",
                &mut state,
            )
            .unwrap();

        assert!(state.relation_is_present(&object_id("myschema", "t")));
    }

    #[test]
    fn test_state_alter_column_types() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze(
                "CREATE TABLE t(id INT NOT NULL); ALTER TABLE t ALTER COLUMN id SET DATA TYPE text; ALTER TABLE t ALTER COLUMN id DROP NOT NULL; ALTER TABLE t ALTER COLUMN id SET DEFAULT 'x';",
                &mut state,
            )
            .unwrap();

        if let Some(RelationOverlay::Present(r)) = state.get_relation(&object_id("public", "t")) {
            let col = r.get_column("id").unwrap();
            assert_eq!(col.data_type.as_deref(), Some("text"));
            assert!(col.is_nullable);
            assert!(col.default.is_some());
        } else {
            panic!("relation should be present");
        }
    }

    #[test]
    fn test_state_storage_and_access_method() {
        let engine = setup_engine();
        let mut state = setup_state();

        assert!(engine
            .analyze(
                "CREATE TABLE t(id int); ALTER TABLE t ALTER COLUMN id SET STORAGE MAIN; ALTER TABLE t SET ACCESS METHOD heap;",
                &mut state,
            )
            .is_ok());
    }

    #[test]
    fn test_state_confidence_is_accessible() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze("CREATE TABLE t(id int);", &mut state)
            .unwrap();
        let _ = &state.local.confidence;
    }
}

// ─────────────────────────────────────────────
// 4. Transaction Lifecycle Rollback Exhaustion
// ─────────────────────────────────────────────
#[cfg(test)]
mod transaction_lifecycle_tests {
    use super::helpers::*;
    use crate::analysis::state::AnalysisState;

    #[test]
    fn test_txn_commit() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze("BEGIN; CREATE TABLE t(id int); COMMIT;", &mut state)
            .unwrap();

        assert!(state.local.transactions.is_empty());
        assert!(state.relation_is_present(&object_id("public", "t")));
    }

    #[test]
    fn test_txn_rollback() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze("BEGIN; CREATE TABLE t(id int); ROLLBACK;", &mut state)
            .unwrap();

        assert!(state.local.transactions.is_empty());
        assert!(!state.relation_is_present(&object_id("public", "t")));
    }

    #[test]
    fn test_savepoint_flow() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze(
                "BEGIN; SAVEPOINT s1; CREATE TABLE t(id int); ROLLBACK TO s1; RELEASE SAVEPOINT s1; COMMIT;",
                &mut state,
            )
            .unwrap();

        assert!(state.local.transactions.is_empty());
    }

    #[test]
    fn test_rollback_to_savepoint_keeps_outer_txn() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze(
                "BEGIN; SAVEPOINT s1; CREATE TABLE t(id int); ROLLBACK TO s1; COMMIT;",
                &mut state,
            )
            .unwrap();

        assert!(state.local.transactions.is_empty());
        assert!(!state.relation_is_present(&object_id("public", "t")));
    }
}

// ─────────────────────────────────────────────
// 5. AST Expression Parsing Exhaustion
// ─────────────────────────────────────────────
#[cfg(test)]
mod expression_parsing_tests {
    use super::helpers::*;
    use crate::analysis::state::AnalysisState;

    fn assert_expr(expr: &str) {
        let engine = setup_engine();
        let mut state = setup_state();
        assert!(
            engine
                .analyze(
                    &format!("CREATE TABLE t(val INT DEFAULT {});", expr),
                    &mut state
                )
                .is_ok()
        );
    }

    #[test]
    fn test_expr_literal() {
        assert_expr("42");
    }
    #[test]
    fn test_expr_name_ref() {
        assert_expr("some_col");
    }
    #[test]
    fn test_expr_call() {
        assert_expr("COALESCE(1, 2)");
    }
    #[test]
    fn test_expr_bin_op() {
        assert_expr("1 + 2 * 3 = 7");
    }
    #[test]
    fn test_expr_cast() {
        assert_expr("1::text");
    }
    #[test]
    fn test_expr_prefix() {
        assert_expr("-42");
    }
    #[test]
    fn test_expr_paren() {
        assert_expr("(1 + 2)");
    }
    #[test]
    fn test_expr_case() {
        assert_expr("CASE WHEN true THEN 1 ELSE 0 END");
    }
    #[test]
    fn test_expr_array() {
        assert_expr("ARRAY[1, 2, 3]");
    }
    #[test]
    fn test_expr_between() {
        assert_expr("5 BETWEEN 1 AND 10");
    }
    #[test]
    fn test_expr_index() {
        assert_expr("arr[1]");
    }
    #[test]
    fn test_expr_slice() {
        assert_expr("arr[1:3]");
    }
    #[test]
    fn test_expr_slice_omitted() {
        assert_expr("arr[2:]");
    }
    #[test]
    fn test_expr_field() {
        assert_expr("(my_record).my_field");
    }

    #[test]
    fn test_parser_syntax_error_rejection() {
        let engine = setup_engine();
        let mut state = AnalysisState::new(crate::db::cache::DbCache::new());
        assert!(engine.analyze("CREATE TABLE (;", &mut state).is_err());
    }
}

// ─────────────────────────────────────────────
// 6. Identifier Casing & Quoting Isolation
// ─────────────────────────────────────────────
#[cfg(test)]
mod identifier_casing_tests {
    use super::helpers::*;
    use crate::analysis::state::AnalysisState;
    use crate::model::relation::RelationOverlay;

    #[test]
    fn test_ident_unquoted_lowercase() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze("CREATE TABLE Users (Id int);", &mut state)
            .unwrap();
        assert!(state.relation_is_present(&object_id("public", "users")));
    }

    #[test]
    fn test_ident_quoted_preserve() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze("CREATE TABLE \"MyTable\" (\"MyCol\" int);", &mut state)
            .unwrap();

        let mixed_id = object_id("public", "MyTable");
        assert!(state.relation_is_present(&mixed_id));

        engine
            .analyze(
                "ALTER TABLE \"MyTable\" RENAME TO \"NewTable\";",
                &mut state,
            )
            .unwrap();

        assert!(!state.relation_is_present(&mixed_id));
        assert!(state.relation_is_present(&object_id("public", "NewTable")));

        engine
            .analyze(
                "ALTER TABLE \"NewTable\" RENAME COLUMN \"MyCol\" TO \"NewCol\";",
                &mut state,
            )
            .unwrap();

        let rel = state
            .get_relation(&object_id("public", "NewTable"))
            .unwrap();
        if let RelationOverlay::Present(r) = rel {
            assert!(r.has_column("NewCol"));
            assert!(!r.has_column("MyCol"));
        } else {
            panic!("NewTable must be Present");
        }
    }

    #[test]
    fn test_ident_schema_resolution() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze("CREATE TABLE MySchema.MyTable (id int);", &mut state)
            .unwrap();

        assert!(state.relation_is_present(&object_id("myschema", "mytable")));
    }
}

// ─────────────────────────────────────────────
// NEW ARCHITECTURAL GAP TESTS (APPENDED)
// ─────────────────────────────────────────────
#[cfg(test)]
mod architectural_gap_tests {
    use super::helpers::*;
    use crate::analysis::state::Confidence;
    use crate::model::relation::{Persistence, RelationKind, RelationOverlay};
    use crate::model::types::{TypeKind, TypeOverlay};
    use crate::report::violations::ViolationTier;

    // 1. Foreign-key parent-table escalation
    #[test]
    fn test_fk_parent_table_lock_escalation() {
        let engine = setup_engine();
        let mut cache = crate::db::cache::DbCache::new();

        // Parent is huge (causes Tier 1 lock if evaluated correctly)
        cache.insert_baseline(
            object_id("public", "parent_tbl"),
            crate::model::relation::RelationState::new(
                object_id("public", "parent_tbl"),
                0,
                Some(500_000),
                RelationKind::Table,
                Persistence::Permanent,
                0,
            ),
        );
        // Child is tiny
        cache.insert_baseline(
            object_id("public", "child_tbl"),
            crate::model::relation::RelationState::new(
                object_id("public", "child_tbl"),
                0,
                Some(10),
                RelationKind::Table,
                Persistence::Permanent,
                0,
            ),
        );

        let mut state = crate::analysis::state::AnalysisState::new(cache);
        let violations = engine.analyze("ALTER TABLE child_tbl ADD CONSTRAINT fk FOREIGN KEY (p_id) REFERENCES parent_tbl(id);", &mut state).unwrap();

        let is_tier_1 = violations
            .iter()
            .any(|v| v.tier == ViolationTier::Tier1 && v.rule_id.contains("blocking-constraint"));
        assert!(
            is_tier_1,
            "Failed to escalate lock severity based on parent table size"
        );
    }

    // 2. Nested RELEASE SAVEPOINT rollback chain
    #[test]
    fn test_nested_release_savepoint_chain() {
        let engine = setup_engine();
        let mut state = setup_state();
        engine
            .analyze(
                "
            BEGIN;
            CREATE TABLE t1(id int);
            SAVEPOINT s1;
            CREATE TABLE t2(id int);
            SAVEPOINT s2;
            CREATE TABLE t3(id int);
            RELEASE SAVEPOINT s2;
            ROLLBACK TO s1;
            COMMIT;
        ",
                &mut state,
            )
            .unwrap();

        assert!(state.relation_is_present(&object_id("public", "t1")));
        assert!(!state.relation_is_present(&object_id("public", "t2")));
        assert!(!state.relation_is_present(&object_id("public", "t3")));
    }

    // 3. ROLLBACK TO SAVEPOINT partial preservation
    #[test]
    fn test_rollback_to_savepoint_partial() {
        let engine = setup_engine();
        let mut state = setup_state();
        engine
            .analyze(
                "
            BEGIN;
            CREATE TABLE a(id int);
            SAVEPOINT s;
            CREATE TABLE b(id int);
            ROLLBACK TO s;
            CREATE TABLE c(id int);
            COMMIT;
        ",
                &mut state,
            )
            .unwrap();

        assert!(state.relation_is_present(&object_id("public", "a")));
        assert!(state.relation_is_present(&object_id("public", "c")));
        assert!(!state.relation_is_present(&object_id("public", "b")));
    }

    // 4. DROP SCHEMA CASCADE rename-edge cleanup
    #[test]
    fn test_drop_schema_cascade_cleans_renames() {
        let engine = setup_engine();
        let mut state = setup_state();
        engine
            .analyze(
                "CREATE SCHEMA s; CREATE TABLE s.t(id int); ALTER TABLE s.t RENAME TO t2;",
                &mut state,
            )
            .unwrap();
        assert!(!state.local.graph.renames.is_empty());

        engine
            .analyze("DROP SCHEMA s CASCADE;", &mut state)
            .unwrap();
        assert!(
            state.local.graph.renames.is_empty(),
            "Rename edges leaked after schema cascade"
        );
    }

    // 5. Multi-schema search_path resolution
    #[test]
    fn test_multi_schema_search_path_resolution() {
        let engine = setup_engine();
        let mut state = setup_state();
        engine
            .analyze(
                "CREATE SCHEMA s1; CREATE SCHEMA s2; SET search_path TO s1, s2;",
                &mut state,
            )
            .unwrap();
        engine
            .analyze("CREATE TABLE t1(id int);", &mut state)
            .unwrap();
        assert!(state.relation_is_present(&object_id("s1", "t1")));
    }

    // 6. Tombstone shadowing / recreate semantics
    #[test]
    fn test_tombstone_shadowing_recreate() {
        let engine = setup_engine();
        let mut state = setup_state();
        engine
            .analyze("CREATE TABLE t(id int);", &mut state)
            .unwrap();
        let gen1 = if let RelationOverlay::Present(r) =
            state.get_relation(&object_id("public", "t")).unwrap()
        {
            r.generation
        } else {
            0
        };

        engine.analyze("DROP TABLE t;", &mut state).unwrap();
        engine
            .analyze("CREATE TABLE t(new_id text);", &mut state)
            .unwrap();
        if let RelationOverlay::Present(r) = state.get_relation(&object_id("public", "t")).unwrap()
        {
            assert!(
                r.generation > gen1,
                "Recreated table must have higher generation"
            );
            assert!(r.has_column("new_id"));
        } else {
            panic!("Table did not recreate over tombstone");
        }
    }

    // 7. DROP without IF EXISTS must not mutate topology
    #[test]
    fn test_drop_missing_object_halts_topology_mutation() {
        let engine = setup_engine();
        let mut state = setup_state();
        engine
            .analyze("CREATE TABLE exists_tbl(id int);", &mut state)
            .unwrap();
        let _ = engine.analyze("DROP TABLE missing_tbl;", &mut state);

        assert!(state.relation_is_present(&object_id("public", "exists_tbl")));
        assert_eq!(state.local.confidence, Confidence::Tainted);
    }

    // 8. View dependency alias/CTE isolation
    #[test]
    fn test_view_dependency_cte_isolation() {
        let engine = setup_engine();
        let mut state = setup_state();
        engine
            .analyze("CREATE TABLE base_table(id int);", &mut state)
            .unwrap();
        engine
            .analyze(
                "CREATE VIEW v AS WITH my_cte AS (SELECT * FROM base_table) SELECT * FROM my_cte;",
                &mut state,
            )
            .unwrap();

        let edge = state
            .local
            .graph
            .views
            .iter()
            .find(|v| v.view_id == object_id("public", "v"))
            .unwrap();
        assert!(edge.depends_on.contains(&object_id("public", "base_table")));
        assert!(!edge.depends_on.contains(&object_id("public", "my_cte")));
    }

    // 9. Partition graph cleanup after DROP TABLE
    #[test]
    fn test_partition_graph_cleanup_on_drop() {
        let engine = setup_engine();
        let mut state = setup_state();
        engine.analyze("CREATE TABLE p(id int) PARTITION BY RANGE(id); CREATE TABLE c PARTITION OF p FOR VALUES FROM (1) TO (10);", &mut state).unwrap();
        engine.analyze("DROP TABLE c;", &mut state).unwrap();
        assert!(
            state.local.graph.partitions.is_empty(),
            "Partition edge leaked after child drop"
        );
    }

    // 10. Concurrent index rollback semantics
    #[test]
    fn test_concurrent_index_rollback() {
        let engine = setup_engine();
        let mut state = setup_state();
        engine
            .analyze("CREATE TABLE t(id int);", &mut state)
            .unwrap();
        engine
            .analyze(
                "BEGIN; CREATE INDEX CONCURRENTLY idx ON t(id); ROLLBACK;",
                &mut state,
            )
            .unwrap();
        assert!(state.local.graph.indexes.is_empty());
    }

    // 11. Opaque confidence taint persistence
    #[test]
    fn test_opaque_confidence_taint_persistence() {
        let engine = setup_engine();
        let mut state = setup_state();
        engine
            .analyze("DO $$ BEGIN EXECUTE 'DROP TABLE x;'; END $$;", &mut state)
            .unwrap();
        assert_eq!(state.local.confidence, Confidence::Tainted);
        engine
            .analyze("CREATE TABLE t(id int);", &mut state)
            .unwrap();
        assert_eq!(state.local.confidence, Confidence::Tainted);
    }

    // 12. Quoted identifier + search_path interaction
    #[test]
    fn test_quoted_ident_search_path() {
        let engine = setup_engine();
        let mut state = setup_state();
        engine
            .analyze(
                "CREATE SCHEMA \"MySchema\"; SET search_path TO \"MySchema\";",
                &mut state,
            )
            .unwrap();
        engine
            .analyze("CREATE TABLE \"MyTable\" (\"MyCol\" int);", &mut state)
            .unwrap();
        assert!(state.relation_is_present(&object_id("MySchema", "MyTable")));
    }

    // 13. CREATE TYPE recreation after DROP
    #[test]
    fn test_create_domain_recreation() {
        let engine = setup_engine();
        let mut state = setup_state();
        engine
            .analyze("CREATE DOMAIN my_type AS int;", &mut state)
            .unwrap();
        engine.analyze("DROP DOMAIN my_type;", &mut state).unwrap();
        engine
            .analyze("CREATE DOMAIN my_type AS text;", &mut state)
            .unwrap();
        assert!(matches!(
            state.local.types.get(&object_id("public", "my_type")),
            Some(TypeOverlay::Present(_))
        ));
    }

    // 14. Duplicate/stale view-edge cleanup
    #[test]
    fn test_stale_view_edge_cleanup() {
        let engine = setup_engine();
        let mut state = setup_state();
        engine
            .analyze(
                "CREATE TABLE t(id int); CREATE VIEW v AS SELECT * FROM t;",
                &mut state,
            )
            .unwrap();
        engine
            .analyze("DROP VIEW v; CREATE VIEW v AS SELECT * FROM t;", &mut state)
            .unwrap();
        assert_eq!(
            state.local.graph.views.len(),
            1,
            "Duplicate view edge created"
        );
    }

    // 15. IF NOT EXISTS metadata preservation
    #[test]
    fn test_if_not_exists_preserves_original_metadata() {
        let engine = setup_engine();
        let mut state = setup_state();
        engine
            .analyze("CREATE TABLE t(id INT);", &mut state)
            .unwrap();
        let gen1 = if let RelationOverlay::Present(r) =
            state.get_relation(&object_id("public", "t")).unwrap()
        {
            r.generation
        } else {
            0
        };

        engine
            .analyze(
                "CREATE TABLE IF NOT EXISTS t(id TEXT, diff_col INT);",
                &mut state,
            )
            .unwrap();

        let rel = state.get_relation(&object_id("public", "t")).unwrap();
        if let RelationOverlay::Present(r) = rel {
            assert_eq!(r.generation, gen1);
            assert_eq!(
                r.get_column("id").unwrap().data_type.as_deref(),
                Some("INT")
            );
            assert!(!r.has_column("diff_col"));
        }
    }

    // 16. Deep Rename Traversal across Cascade (BUG-004)
    #[test]
    fn test_deep_rename_traversal_cascade() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze(
                "
            CREATE TABLE a(id int);
            CREATE VIEW v AS SELECT * FROM a;
            ALTER TABLE a RENAME TO b;
            DROP TABLE b CASCADE;
        ",
                &mut state,
            )
            .unwrap();

        // The View 'v' relies on 'a'. We renamed 'a' to 'b'.
        // Dropping 'b' should dynamically resolve the rename graph and correctly drop 'v'.
        assert!(
            !state.relation_is_present(&object_id("public", "a")),
            "Original table a should be gone"
        );
        assert!(
            !state.relation_is_present(&object_id("public", "b")),
            "Renamed table b should be gone"
        );
        assert!(
            !state.relation_is_present(&object_id("public", "v")),
            "Dependent view v should have been cascaded"
        );
    }

    // 17. Partition Cycle Rejection (BUG-012)
    #[test]
    fn test_partition_cycle_rejection() {
        let engine = setup_engine();
        let mut state = setup_state();

        // Attempting to attach 'a' as a partition of 'b', while 'b' is a partition of 'a'
        engine
            .analyze(
                "
            CREATE TABLE a(id int) PARTITION BY RANGE(id);
            CREATE TABLE b PARTITION OF a FOR VALUES FROM (1) TO (10) PARTITION BY RANGE(id);
            ALTER TABLE b ATTACH PARTITION a FOR VALUES FROM (1) TO (10);
        ",
                &mut state,
            )
            .unwrap();

        // The cycle detector should catch the infinite loop and gracefully degrade
        // to an Opaque/DynamicSql mutation, tainting the engine rather than stack-overflowing.
        assert_eq!(
            state.local.confidence,
            Confidence::Tainted,
            "Partition cycle should taint the engine"
        );
    }

    // 18. Tablespace and Access Method Rewrite Rule
    #[test]
    fn test_tablespace_access_method_rewrite() {
        let engine = setup_engine();
        let mut cache = crate::db::cache::DbCache::new();

        // Force Tier 1 by giving the table 150,000 rows
        cache.insert_baseline(
            object_id("public", "massive_table"),
            crate::model::relation::RelationState::new(
                object_id("public", "massive_table"),
                0,
                Some(150_000),
                RelationKind::Table,
                Persistence::Permanent,
                0,
            ),
        );
        let mut state = crate::analysis::state::AnalysisState::new(cache);

        let v1 = engine
            .analyze(
                "ALTER TABLE massive_table SET ACCESS METHOD columnar;",
                &mut state,
            )
            .unwrap();
        assert!(
            v1.iter()
                .any(|v| v.rule_id == "table-rewrite-access-method"
                    && v.tier == ViolationTier::Tier1)
        );

        let v2 = engine
            .analyze(
                "ALTER TABLE massive_table ALTER COLUMN id SET STORAGE MAIN;",
                &mut state,
            )
            .unwrap();
        assert!(
            v2.iter()
                .any(|v| v.rule_id == "table-rewrite-storage" && v.tier == ViolationTier::Tier1)
        );
    }
    // 19. Generation counter rollback (BUG-001/002)
    #[test]
    fn test_generation_counter_rollback() {
        let engine = setup_engine();
        let mut state = setup_state();

        let initial_gen = state.local.generation_counter;

        engine
            .analyze("BEGIN; CREATE TABLE t(id int);", &mut state)
            .unwrap();
        let mid_gen = state.local.generation_counter;
        assert!(
            mid_gen > initial_gen,
            "Generation counter should increment on create"
        );

        engine.analyze("ROLLBACK;", &mut state).unwrap();
        let post_gen = state.local.generation_counter;
        assert_eq!(
            post_gen, initial_gen,
            "Generation counter should restore strictly to pre-txn state on rollback"
        );
    }

    // 20. Partition children cascade (BUG-003)
    #[test]
    fn test_partition_children_cascade_enumeration() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze(
                "
            CREATE TABLE parent(id int) PARTITION BY RANGE(id);
            CREATE TABLE child PARTITION OF parent FOR VALUES FROM (1) TO (10);
            DROP TABLE parent CASCADE;
        ",
                &mut state,
            )
            .unwrap();

        assert!(
            !state.relation_is_present(&object_id("public", "parent")),
            "Parent should be dropped"
        );
        assert!(
            !state.relation_is_present(&object_id("public", "child")),
            "Child should be dropped via reverse-graph cascade"
        );
    }

    // 21. Rename updates FK graph edges implicitly via resolver (BUG-004)
    #[test]
    fn test_rename_updates_fk_graph_edges() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze(
                "
            CREATE TABLE a(id int);
            CREATE TABLE b(a_id int);
            ALTER TABLE b ADD CONSTRAINT fk FOREIGN KEY (a_id) REFERENCES a(id);
            ALTER TABLE a RENAME TO a2;
        ",
                &mut state,
            )
            .unwrap();

        let refs = state
            .local
            .graph
            .is_referenced_by_fk(&object_id("public", "a2"));
        assert!(
            !refs.is_empty(),
            "a2 should be recognized as referenced by b's FK dynamically"
        );
        assert_eq!(refs[0].0, &object_id("public", "b"));
    }

    // 22. Search path existence check (BUG-005)
    #[test]
    fn test_search_path_existence_check() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze(
                "
            CREATE SCHEMA actual_schema;
            CREATE TABLE actual_schema.my_table(id int);
            SET search_path = nonexistent_schema, actual_schema;
            ALTER TABLE my_table ADD COLUMN new_col int;
        ",
                &mut state,
            )
            .unwrap();

        let rel = state
            .get_relation(&object_id("actual_schema", "my_table"))
            .unwrap();
        if let crate::model::relation::RelationOverlay::Present(r) = rel {
            assert!(
                r.has_column("new_col"),
                "Should resolve to actual_schema bypassing nonexistent_schema"
            );
        } else {
            panic!("Table not found; resolver hallucinated the schema");
        }
    }

    // 23. Drop without cascade validates dependents (BUG-006)
    #[test]
    fn test_drop_without_cascade_validates_dependents() {
        let engine = setup_engine();
        let mut state = setup_state();

        engine
            .analyze(
                "
            CREATE TABLE a(id int);
            CREATE TABLE b(a_id int);
            ALTER TABLE b ADD CONSTRAINT fk FOREIGN KEY (a_id) REFERENCES a(id);
        ",
                &mut state,
            )
            .unwrap();

        // Drop without cascade
        let _ = engine.analyze("DROP TABLE a;", &mut state);

        // It should taint confidence and skip the drop
        assert_eq!(
            state.local.confidence,
            crate::analysis::state::Confidence::Tainted,
            "Engine should taint on unsafe drop"
        );
        assert!(
            state.relation_is_present(&object_id("public", "a")),
            "Table a should not be dropped if dependents exist without CASCADE"
        );
    }
}