pgevolve-core 0.3.4

Postgres declarative schema management — core library (parser, IR, diff, planner) powering the pgevolve CLI.
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
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
//! Three-phase ordering with FK cycle extraction.
//!
//! `order(target, source, changes)` partitions an unordered [`ChangeSet`]
//! into [`OrderedChangeSet`]'s three buckets and sorts each by the appropriate
//! dependency graph. FK cycles in the create graph are broken by removing
//! offending FK constraints into [`OrderedChangeSet::deferred_fks`].

use std::collections::{HashMap, HashSet};

use crate::diff::ChangeSet;
use crate::diff::change::{
    Change, ChangeEntry, FunctionChange, MvChange, ProcedureChange, TableChange, TriggerChange,
    UserTypeChange, ViewChange,
};
use crate::diff::destructiveness::Destructiveness;
use crate::diff::table_op::TableOp;
use crate::identifier::{Identifier, QualifiedName};
use crate::ir::catalog::Catalog;
use crate::ir::constraint::{Constraint, ConstraintKind};
use crate::ir::index::IndexColumnExpr;
use crate::plan::edges::{NodeId, build_create_graph, build_drop_graph};
use crate::plan::error::PlanError;
use crate::plan::ordered::{DeferredFkAdd, OrderedChangeSet};
use crate::plan::policy::PlannerPolicy;
use crate::plan::recreate_views;

/// Order a `ChangeSet` into an [`OrderedChangeSet`] for plan emission.
///
/// `target` is the live database catalog; `source` is the desired one. The
/// create / modify graphs are built from `source`; the drop graph from `target`.
///
/// `policy` gates the dependent-view recreation walk: when
/// `policy.view_drop_create_dependents()` is `false` and any change would
/// force dependent views to be recreated, this function returns
/// [`PlanError::DependentViewsBlocked`] naming the affected views.
pub fn order(
    target: &Catalog,
    source: &Catalog,
    changes: ChangeSet,
    policy: &PlannerPolicy,
) -> Result<OrderedChangeSet, PlanError> {
    // Elide DropIndex changes whose target index will be cascade-dropped by
    // an upstream `ALTER TABLE ... DROP COLUMN` in the same plan. Postgres
    // implicitly drops any index that references a dropped column (in its
    // key list or `INCLUDE` list); leaving the explicit `DROP INDEX` in the
    // plan causes the executor to fail with SQLSTATE 42704.
    let changes = elide_cascaded_index_drops(target, changes);

    // Extend the changeset with explicit DROP + CREATE steps for every
    // transitively-affected view (never CASCADE). This must happen before
    // partitioning so the new ReplaceBody entries flow through the normal
    // ordering pipeline.
    //
    // `extend_with_dependent_recreations` only appends to `raw_changes`; it
    // never modifies existing entries. We preserve the original
    // `Destructiveness` values for all original entries and assign `Safe` to
    // any newly-appended ones (dependent view recreation is not destructive —
    // the view body itself is unchanged).
    let original_entries: Vec<crate::diff::change::ChangeEntry> = changes.entries;
    let mut raw_changes: Vec<Change> = original_entries.iter().map(|e| e.change.clone()).collect();
    recreate_views::extend_with_dependent_recreations(&mut raw_changes, target, policy)
        .map_err(|views| PlanError::DependentViewsBlocked { views })?;
    // Re-assemble ChangeSet preserving original destructiveness for original
    // entries, and using Safe for any newly-added recreation entries.
    let entries: Vec<crate::diff::change::ChangeEntry> = raw_changes
        .into_iter()
        .enumerate()
        .map(|(i, change)| {
            let destructiveness = original_entries
                .get(i)
                .map_or(Destructiveness::Safe, |e| e.destructiveness.clone());
            crate::diff::change::ChangeEntry {
                change,
                destructiveness,
            }
        })
        .collect();
    let changes = ChangeSet {
        entries,
        ..ChangeSet::new()
    };

    // 1. Bucket entries by phase. Returns Err if any UnsupportedDiff is present.
    let (creates, modifies, drops) = partition(changes)?;

    // 2. Try to topo-sort the create graph; extract FK cycles if needed.
    let mut working_source: Option<Catalog> = None;
    let create_graph = build_create_graph(source);
    let (sorted_create_nodes, deferred_fks) = match create_graph.topological_sort() {
        Ok(order) => (order, Vec::new()),
        Err(cycle) => {
            let (reduced, deferred) = extract_fk_cycles(source, &cycle.nodes);
            let g = build_create_graph(&reduced);
            let order = g.topological_sort().map_err(|c| {
                PlanError::UnbreakableCycle(c.nodes.iter().map(render_node).collect())
            })?;
            working_source = Some(reduced);
            (order, deferred)
        }
    };

    // The graph used for modify ordering is the same as the (possibly reduced)
    // create graph — modify ops live on already-existing objects whose
    // structural dependencies match the source-side picture.
    let modify_graph = working_source
        .as_ref()
        .map_or(create_graph, build_create_graph);
    let sorted_modify_nodes = modify_graph.topological_sort().map_err(|c| {
        PlanError::UnexpectedCycleAfterFkExtraction(c.nodes.iter().map(render_node).collect())
    })?;

    let drop_graph = build_drop_graph(target);
    let sorted_drop_nodes = drop_graph
        .reverse_topological_sort()
        .map_err(|c| PlanError::UnexpectedDropCycle(c.nodes.iter().map(render_node).collect()))?;

    // Strip deferred FKs from any CreateTable change so they aren't emitted
    // both inline and as a post-pass `ADD CONSTRAINT`.
    let creates = strip_deferred_fks(creates, &deferred_fks);

    let creates = sort_changes_by_order(creates, &sorted_create_nodes);
    let modifies = sort_changes_by_order(modifies, &sorted_modify_nodes);
    let drops = sort_changes_by_order(drops, &sorted_drop_nodes);

    Ok(OrderedChangeSet {
        creates_and_adds: creates,
        modifies,
        drops,
        deferred_fks,
    })
}

/// Remove every constraint named in `deferred` from any matching `CreateTable`
/// change. The deferred FK will be emitted as a post-pass `ADD CONSTRAINT`.
fn strip_deferred_fks(creates: Vec<ChangeEntry>, deferred: &[DeferredFkAdd]) -> Vec<ChangeEntry> {
    if deferred.is_empty() {
        return creates;
    }
    creates
        .into_iter()
        .map(|mut entry| {
            if let Change::CreateTable(table) = &mut entry.change {
                table.constraints.retain(|c| {
                    !deferred
                        .iter()
                        .any(|d| d.table == table.qname && d.constraint.qname == c.qname)
                });
            }
            entry
        })
        .collect()
}

/// Remove `DropIndex` changes whose target index will be implicitly dropped
/// by an upstream `ALTER TABLE ... DROP COLUMN` on a column the index
/// references (in its key column list or `INCLUDE` list).
///
/// Postgres cascade-drops such indexes as part of the column drop, so the
/// explicit `DROP INDEX` in a later step would fail with
/// `42704 (undefined_object)`. The elision keeps the audit trail attached
/// to the column-drop step that does the actual work.
///
/// Limitations: expression-key indexes and partial-index predicates are not
/// analyzed; their `DropIndex` is retained even if the predicate or
/// expression references the dropped column. The executor will surface
/// those (still rare) cases as the same 42704 until expression analysis is
/// added.
fn elide_cascaded_index_drops(target: &Catalog, mut changes: ChangeSet) -> ChangeSet {
    let dropped_columns = collect_dropped_columns(&changes);
    if dropped_columns.is_empty() {
        return changes;
    }
    let target_indexes: HashMap<&QualifiedName, &crate::ir::index::Index> =
        target.indexes.iter().map(|i| (&i.qname, i)).collect();
    changes.entries.retain(|entry| {
        let Change::DropIndex(qname) = &entry.change else {
            return true;
        };
        let Some(idx) = target_indexes.get(qname) else {
            return true;
        };
        let cascades = idx
            .columns
            .iter()
            .filter_map(|ic| match &ic.expr {
                IndexColumnExpr::Column(name) => Some(name),
                IndexColumnExpr::Expression(_) => None,
            })
            .chain(idx.include.iter())
            .any(|col| dropped_columns.contains(&(idx.on.qname().clone(), col.clone())));
        !cascades
    });
    changes
}

fn collect_dropped_columns(changes: &ChangeSet) -> HashSet<(QualifiedName, Identifier)> {
    let mut out = HashSet::new();
    for entry in &changes.entries {
        let Change::AlterTable { qname, ops } = &entry.change else {
            continue;
        };
        for op_entry in ops {
            if let TableOp::DropColumn { name, .. } = &op_entry.op {
                out.insert((qname.clone(), name.clone()));
            }
        }
    }
    out
}

/// Three-bucket output of [`partition`]: (creates, modifies, drops).
type PartitionResult = Result<(Vec<ChangeEntry>, Vec<ChangeEntry>, Vec<ChangeEntry>), PlanError>;

/// Split a `ChangeSet` into (creates, modifies, drops) buckets.
///
/// Returns `Err(PlanError::Internal)` immediately if any entry is a
/// `Change::UnsupportedDiff` — the plan cannot proceed.
#[allow(clippy::too_many_lines)] // One arm per Change variant; extraction would obscure intent.
fn partition(changes: ChangeSet) -> PartitionResult {
    let mut creates = Vec::new();
    let mut modifies = Vec::new();
    let mut drops = Vec::new();
    for entry in changes.entries {
        match &entry.change {
            // Creates: structural objects that need to be ordered dependencies-first.
            // Views and MVs are included here; T7 will wire their dep edges.
            Change::CreateSchema(_)
            | Change::CreateTable(_)
            | Change::CreateIndex(_)
            | Change::CreateSequence(_)
            | Change::View(ViewChange::Create(_))
            | Change::Mv(MvChange::Create(_))
            | Change::CreatePublication(_) => creates.push(entry),
            // Drops: ordered by reverse-dependency (deepest dependents first).
            Change::DropSchema(_)
            | Change::DropTable { .. }
            | Change::DropIndex(_)
            | Change::DropSequence(_)
            | Change::View(ViewChange::Drop(_))
            | Change::Mv(MvChange::Drop(_)) => drops.push(entry),
            // Modifies: ALTER / REPLACE / COMMENT / drift-recovery / grant / owner.
            Change::AlterTable { .. }
            | Change::AlterSchema { .. }
            | Change::AlterSequence { .. }
            | Change::ReplaceIndex { .. }
            | Change::ValidateConstraint { .. }
            | Change::RecreateIndex { .. }
            | Change::View(
                ViewChange::ReplaceBody { .. }
                | ViewChange::SetReloption { .. }
                | ViewChange::SetComment { .. }
                | ViewChange::SetColumnComment { .. },
            )
            | Change::Mv(
                MvChange::ReplaceBody { .. }
                | MvChange::SetComment { .. }
                | MvChange::SetColumnComment { .. },
            )
            // Grant / revoke / owner changes: always non-destructive modifications.
            | Change::GrantObjectPrivilege { .. }
            | Change::RevokeObjectPrivilege { .. }
            | Change::GrantColumnPrivilege { .. }
            | Change::RevokeColumnPrivilege { .. }
            | Change::AlterObjectOwner(_)
            | Change::AlterDefaultPrivileges { .. } => modifies.push(entry),
            // UserType changes: bucket by lifecycle phase.
            Change::UserType(utc) => match utc {
                UserTypeChange::Create(_) => creates.push(entry),
                UserTypeChange::Drop(_) | UserTypeChange::ReplaceWithCascade { .. } => {
                    drops.push(entry);
                }
                UserTypeChange::EnumAddValue { .. }
                | UserTypeChange::EnumRenameValue { .. }
                | UserTypeChange::DomainAddCheck { .. }
                | UserTypeChange::DomainDropCheck { .. }
                | UserTypeChange::DomainSetDefault { .. }
                | UserTypeChange::DomainSetNotNull { .. }
                | UserTypeChange::CompositeAddAttribute { .. }
                | UserTypeChange::CompositeDropAttribute { .. }
                | UserTypeChange::CompositeAlterAttributeType { .. }
                | UserTypeChange::SetComment { .. } => modifies.push(entry),
            },
            // Function changes: bucket by lifecycle phase.
            Change::Function(fc) => match fc {
                FunctionChange::Create(_) => creates.push(entry),
                FunctionChange::Drop { .. } | FunctionChange::ReplaceWithCascade { .. } => {
                    drops.push(entry);
                }
                FunctionChange::CreateOrReplace(_) | FunctionChange::SetComment { .. } => {
                    modifies.push(entry);
                }
            },
            // Procedure changes: bucket by lifecycle phase.
            Change::Procedure(pc) => match pc {
                ProcedureChange::Create(_) => creates.push(entry),
                ProcedureChange::Drop(_) => drops.push(entry),
                ProcedureChange::CreateOrReplace(_) | ProcedureChange::SetComment { .. } => {
                    modifies.push(entry);
                }
            },
            // Extension changes: bucket by lifecycle phase (NodeId::Extension added in EXT6).
            Change::Extension(ec) => match ec {
                crate::diff::change::ExtensionChange::Create(_) => creates.push(entry),
                crate::diff::change::ExtensionChange::Drop(_)
                | crate::diff::change::ExtensionChange::ReplaceWithCascade(_) => {
                    drops.push(entry);
                }
                crate::diff::change::ExtensionChange::AlterUpdate { .. }
                | crate::diff::change::ExtensionChange::CommentOn { .. } => modifies.push(entry),
            },
            // Trigger changes: bucket by lifecycle phase.
            Change::Trigger(tc) => match tc {
                TriggerChange::Create(_) => creates.push(entry),
                // Replace emits drop+create; both land in drops so the emitter
                // can sequence them correctly.
                TriggerChange::Drop { .. } | TriggerChange::Replace(_) => drops.push(entry),
                TriggerChange::CommentOn { .. } => modifies.push(entry),
            },
            // Partition changes: alter partition membership, not the table's existence.
            // Policy + RLS changes: metadata-only, always non-destructive modifications.
            // Stage 6 will emit real SQL for the policy variants; for now they land in modifies.
            // Storage reloption changes: ALTER TABLE/INDEX/MV SET (...) — always modifies.
            Change::Table(
                TableChange::AttachPartition { .. } | TableChange::DetachPartition { .. },
            )
            | Change::CreatePolicy { .. }
            | Change::DropPolicy { .. }
            | Change::AlterPolicy { .. }
            | Change::SetTableRowSecurity { .. }
            | Change::SetTableForceRowSecurity { .. }
            | Change::SetTableStorage { .. }
            | Change::SetIndexStorage { .. }
            | Change::SetMaterializedViewStorage { .. }
            // Publication alter/comment changes: metadata-only, always modifies.
            | Change::AlterPublicationAddTable { .. }
            | Change::AlterPublicationDropTable { .. }
            | Change::AlterPublicationSetTable { .. }
            | Change::AlterPublicationAddSchema { .. }
            | Change::AlterPublicationDropSchema { .. }
            | Change::AlterPublicationSetPublish { .. }
            | Change::AlterPublicationSetViaRoot { .. }
            | Change::CommentOnPublication { .. } => {
                modifies.push(entry);
            }
            // Publication drops/replaces: destructive, goes in drops bucket.
            Change::DropPublication { .. } | Change::ReplacePublication { .. } => {
                drops.push(entry);
            }
            // UnsupportedDiff: abort the plan immediately.
            Change::UnsupportedDiff { reason } => {
                return Err(PlanError::Internal(reason.clone()));
            }
        }
    }
    Ok((creates, modifies, drops))
}

/// Map a `Change` to the [`NodeId`] that represents it in the dependency graph.
///
/// Returns the schema/table/index/sequence node for top-level operations.
/// `AlterTable` maps to its target table node; per-op constraint changes
/// inside it are not separately ordered (they ride with the table).
#[allow(clippy::match_same_arms)] // View and Mv arms share the body shape but not the inner type.
#[allow(clippy::too_many_lines)]
fn change_node(change: &Change) -> NodeId {
    match change {
        Change::CreateSchema(s) => NodeId::Schema(s.name.clone()),
        Change::DropSchema(name) | Change::AlterSchema { name, .. } => NodeId::Schema(name.clone()),
        Change::CreateTable(t) => NodeId::Table(t.qname.clone()),
        Change::DropTable { qname, .. } | Change::AlterTable { qname, .. } => {
            NodeId::Table(qname.clone())
        }
        Change::CreateIndex(i) => NodeId::Index(i.qname.clone()),
        // RecreateIndex maps to the same index node as DropIndex.
        Change::DropIndex(qname) | Change::RecreateIndex { qname } => NodeId::Index(qname.clone()),
        Change::ReplaceIndex { to, .. } => NodeId::Index(to.qname.clone()),
        Change::CreateSequence(s) => NodeId::Sequence(s.qname.clone()),
        Change::DropSequence(qname) | Change::AlterSequence { qname, .. } => {
            NodeId::Sequence(qname.clone())
        }
        // Drift-recovery changes: map to the table they affect.
        Change::ValidateConstraint { table, .. } => NodeId::Table(table.clone()),
        // View changes: use NodeId::View for correct topological ordering.
        Change::View(ViewChange::Create(v)) => NodeId::View(v.qname.clone()),
        Change::View(ViewChange::ReplaceBody { source, .. }) => NodeId::View(source.qname.clone()),
        Change::View(
            ViewChange::Drop(qname)
            | ViewChange::SetReloption { qname, .. }
            | ViewChange::SetComment { qname, .. }
            | ViewChange::SetColumnComment { qname, .. },
        ) => NodeId::View(qname.clone()),
        // MV changes: use NodeId::Mv for correct topological ordering.
        Change::Mv(MvChange::Create(mv)) => NodeId::Mv(mv.qname.clone()),
        Change::Mv(MvChange::ReplaceBody { source, .. }) => NodeId::Mv(source.qname.clone()),
        Change::Mv(
            MvChange::Drop(qname)
            | MvChange::SetComment { qname, .. }
            | MvChange::SetColumnComment { qname, .. },
        ) => NodeId::Mv(qname.clone()),
        // UserType changes: extract the qualified name and return NodeId::Type.
        Change::UserType(utc) => {
            let qname = match utc {
                UserTypeChange::Create(ut) => &ut.qname,
                UserTypeChange::Drop(q) => q,
                UserTypeChange::ReplaceWithCascade { source, .. } => &source.qname,
                UserTypeChange::EnumAddValue { qname: q, .. }
                | UserTypeChange::EnumRenameValue { qname: q, .. }
                | UserTypeChange::DomainAddCheck { qname: q, .. }
                | UserTypeChange::DomainDropCheck { qname: q, .. }
                | UserTypeChange::DomainSetDefault { qname: q, .. }
                | UserTypeChange::DomainSetNotNull { qname: q, .. }
                | UserTypeChange::CompositeAddAttribute { qname: q, .. }
                | UserTypeChange::CompositeDropAttribute { qname: q, .. }
                | UserTypeChange::CompositeAlterAttributeType { qname: q, .. }
                | UserTypeChange::SetComment { qname: q, .. } => q,
            };
            NodeId::Type(qname.clone())
        }
        // Function node mapping.
        Change::Function(fc) => match fc {
            FunctionChange::Create(f) | FunctionChange::CreateOrReplace(f) => {
                NodeId::Function(f.qname.clone(), f.arg_types_normalized.clone())
            }
            FunctionChange::ReplaceWithCascade { source: f, .. } => {
                NodeId::Function(f.qname.clone(), f.arg_types_normalized.clone())
            }
            FunctionChange::Drop { qname, args } => NodeId::Function(qname.clone(), args.clone()),
            FunctionChange::SetComment { qname, args, .. } => {
                NodeId::Function(qname.clone(), args.clone())
            }
        },
        // Procedure node mapping.
        Change::Procedure(pc) => {
            let qname = match pc {
                ProcedureChange::Create(p) | ProcedureChange::CreateOrReplace(p) => &p.qname,
                ProcedureChange::Drop(q) | ProcedureChange::SetComment { qname: q, .. } => q,
            };
            NodeId::Procedure(qname.clone())
        }
        // Extension node mapping.
        Change::Extension(ec) => {
            use crate::diff::change::ExtensionChange;
            let name = match ec {
                ExtensionChange::Create(e) | ExtensionChange::ReplaceWithCascade(e) => {
                    e.name.clone()
                }
                ExtensionChange::Drop(n)
                | ExtensionChange::AlterUpdate { name: n, .. }
                | ExtensionChange::CommentOn { name: n, .. } => n.clone(),
            };
            NodeId::Extension(name)
        }
        // Trigger node mapping.
        Change::Trigger(tc) => match tc {
            TriggerChange::Create(t) | TriggerChange::Replace(t) => {
                NodeId::Trigger(t.qname.clone())
            }
            TriggerChange::Drop { qname, .. } | TriggerChange::CommentOn { qname, .. } => {
                NodeId::Trigger(qname.clone())
            }
        },
        // Partition change node mapping: use the child partition table.
        Change::Table(
            TableChange::AttachPartition { child, .. } | TableChange::DetachPartition { child, .. },
        ) => NodeId::Table(child.clone()),
        // Grant / revoke / owner: map to the object's primary node.
        Change::GrantObjectPrivilege { qname, .. }
        | Change::RevokeObjectPrivilege { qname, .. }
        | Change::GrantColumnPrivilege { qname, .. }
        | Change::RevokeColumnPrivilege { qname, .. } => NodeId::Table(qname.clone()),
        Change::AlterObjectOwner(op) => NodeId::Table(op.qname.clone()),
        Change::AlterDefaultPrivileges { target_role, .. } => {
            // Default-privilege changes have no natural node; use a Schema node
            // keyed by the target_role name as a stable ordering anchor.
            NodeId::Schema(target_role.clone())
        }
        // Policy + RLS changes: scoped to the owning table.
        Change::CreatePolicy { table, .. }
        | Change::DropPolicy { table, .. }
        | Change::AlterPolicy { table, .. } => NodeId::Table(table.clone()),
        Change::SetTableRowSecurity { qname, .. }
        | Change::SetTableForceRowSecurity { qname, .. } => NodeId::Table(qname.clone()),
        // Storage reloption changes: scoped to the named object.
        Change::SetTableStorage { qname, .. } => NodeId::Table(qname.clone()),
        Change::SetIndexStorage { qname, .. } => NodeId::Index(qname.clone()),
        Change::SetMaterializedViewStorage { qname, .. } => NodeId::Mv(qname.clone()),
        // Publication changes: use NodeId::Publication keyed by publication name.
        Change::CreatePublication(p) => NodeId::Publication(p.name.clone()),
        Change::DropPublication { name } | Change::CommentOnPublication { name, .. } => {
            NodeId::Publication(name.clone())
        }
        Change::ReplacePublication { to, .. } => NodeId::Publication(to.name.clone()),
        Change::AlterPublicationAddTable { publication, .. }
        | Change::AlterPublicationDropTable { publication, .. }
        | Change::AlterPublicationSetTable { publication, .. }
        | Change::AlterPublicationAddSchema { publication, .. }
        | Change::AlterPublicationDropSchema { publication, .. }
        | Change::AlterPublicationSetPublish { publication, .. }
        | Change::AlterPublicationSetViaRoot { publication, .. } => {
            NodeId::Publication(publication.clone())
        }
        // UnsupportedDiff is intercepted in `partition()` before `change_node` is called.
        Change::UnsupportedDiff { .. } => {
            unreachable!("UnsupportedDiff must never reach change_node")
        }
    }
}

/// Sort `entries` by the position of their associated `NodeId` in `order`.
///
/// Entries whose node is missing from `order` (which would indicate a bug
/// in graph construction) are placed at the end in their original order.
fn sort_changes_by_order(entries: Vec<ChangeEntry>, order: &[NodeId]) -> Vec<ChangeEntry> {
    let position: HashMap<&NodeId, usize> = order.iter().enumerate().map(|(i, n)| (n, i)).collect();
    let mut indexed: Vec<(usize, ChangeEntry)> = entries
        .into_iter()
        .map(|e| {
            let node = change_node(&e.change);
            let pos = position.get(&node).copied().unwrap_or(usize::MAX);
            (pos, e)
        })
        .collect();
    // Stable sort preserves tie-broken input order; primary key is graph index.
    indexed.sort_by_key(|(p, _)| *p);
    indexed.into_iter().map(|(_, e)| e).collect()
}

/// Identify FK constraints inside a cycle and return a reduced catalog plus
/// the extracted FK list for the planner's post-pass.
///
/// An FK is extracted iff its owning-table and referenced-table nodes both
/// appear in `cycle_nodes` and the two tables are distinct (a self-referential
/// FK never induces a graph-level cycle, by construction in `edges.rs`).
fn extract_fk_cycles(source: &Catalog, cycle_nodes: &[NodeId]) -> (Catalog, Vec<DeferredFkAdd>) {
    let in_cycle: std::collections::HashSet<&NodeId> = cycle_nodes.iter().collect();
    let mut reduced = source.clone();
    let mut deferred = Vec::new();

    for table in &mut reduced.tables {
        let table_node = NodeId::Table(table.qname.clone());
        if !in_cycle.contains(&table_node) {
            continue;
        }
        let owner_qname = table.qname.clone();
        let mut keep = Vec::with_capacity(table.constraints.len());
        for c in std::mem::take(&mut table.constraints) {
            if let Some(ref_table) = fk_referenced_table(&c) {
                let ref_node = NodeId::Table(ref_table.clone());
                if *ref_table != owner_qname && in_cycle.contains(&ref_node) {
                    deferred.push(DeferredFkAdd {
                        table: owner_qname.clone(),
                        constraint: c,
                    });
                    continue;
                }
            }
            keep.push(c);
        }
        table.constraints = keep;
    }
    // Stable, deterministic order: deferred FKs are produced in iteration
    // order over `tables` (which is `Catalog::canonicalize`-sorted upstream).
    (reduced, deferred)
}

const fn fk_referenced_table(c: &Constraint) -> Option<&QualifiedName> {
    match &c.kind {
        ConstraintKind::ForeignKey(fk) => Some(&fk.referenced_table),
        _ => None,
    }
}

fn render_node(n: &NodeId) -> String {
    match n {
        NodeId::Schema(s) => format!("schema:{s}"),
        NodeId::Table(q) => format!("table:{q}"),
        NodeId::Index(q) => format!("index:{q}"),
        NodeId::Sequence(q) => format!("sequence:{q}"),
        NodeId::Constraint { table, name } => format!("constraint:{table}.{name}"),
        NodeId::View(q) => format!("view:{q}"),
        NodeId::Mv(q) => format!("mv:{q}"),
        NodeId::Type(q) => format!("type:{q}"),
        NodeId::Procedure(q) => format!("procedure:{q}"),
        NodeId::Extension(name) => format!("extension:{name}"),
        NodeId::Trigger(q) => format!("trigger:{q}"),
        NodeId::Publication(name) => format!("publication:{name}"),
        NodeId::Function(q, args) => format!(
            "function:{}({})",
            q,
            args.types
                .iter()
                .map(crate::ir::column_type::ColumnType::render_sql)
                .collect::<Vec<_>>()
                .join(",")
        ),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::diff::change::Change;
    use crate::diff::destructiveness::Destructiveness;
    use crate::diff::table_op::{TableOp, TableOpEntry};
    use crate::identifier::Identifier;
    use crate::ir::column::Column;
    use crate::ir::column_type::ColumnType;
    use crate::ir::constraint::{
        Constraint, Deferrable, FkMatchType, ForeignKey, ReferentialAction,
    };
    use crate::ir::index::{
        Index, IndexColumn, IndexColumnExpr, IndexMethod, IndexParent, NullsOrder, SortOrder,
    };
    use crate::ir::schema::Schema;
    use crate::ir::table::Table;

    fn id(s: &str) -> Identifier {
        Identifier::from_unquoted(s).unwrap()
    }

    fn qn(schema: &str, name: &str) -> QualifiedName {
        QualifiedName::new(id(schema), id(name))
    }

    fn col(name: &str, ty: ColumnType, nullable: bool) -> Column {
        Column {
            name: id(name),
            ty,
            nullable,
            default: None,
            identity: None,
            generated: None,
            collation: None,
            storage: None,
            compression: None,
            comment: None,
        }
    }

    fn pk(name: &str, cols: &[&str]) -> Constraint {
        Constraint {
            qname: qn("app", name),
            kind: ConstraintKind::PrimaryKey {
                columns: cols.iter().map(|c| id(c)).collect(),
                include: vec![],
            },
            deferrable: Deferrable::NotDeferrable,
            comment: None,
        }
    }

    fn fk(name: &str, cols: &[&str], ref_table: QualifiedName, ref_cols: &[&str]) -> Constraint {
        Constraint {
            qname: qn("app", name),
            kind: ConstraintKind::ForeignKey(ForeignKey {
                columns: cols.iter().map(|c| id(c)).collect(),
                referenced_table: ref_table,
                referenced_columns: ref_cols.iter().map(|c| id(c)).collect(),
                on_update: ReferentialAction::NoAction,
                on_delete: ReferentialAction::NoAction,
                match_type: FkMatchType::Simple,
            }),
            deferrable: Deferrable::NotDeferrable,
            comment: None,
        }
    }

    fn make_index(name: &str, table: QualifiedName) -> Index {
        Index {
            qname: qn("app", name),
            on: IndexParent::Table(table),
            method: IndexMethod::BTree,
            columns: vec![IndexColumn {
                expr: IndexColumnExpr::Column(id("id")),
                collation: None,
                opclass: None,
                sort_order: SortOrder::Asc,
                nulls_order: NullsOrder::NullsLast,
            }],
            include: vec![],
            unique: false,
            nulls_not_distinct: false,
            predicate: None,
            tablespace: None,
            comment: None,
            storage: crate::ir::reloptions::IndexStorageOptions::default(),
        }
    }

    fn safe(change: Change) -> ChangeEntry {
        ChangeEntry {
            change,
            destructiveness: Destructiveness::Safe,
        }
    }

    fn drop(change: Change) -> ChangeEntry {
        ChangeEntry {
            change,
            destructiveness: Destructiveness::RequiresApproval {
                reason: "drop".into(),
            },
        }
    }

    /// Helper: position of an entry's node in a slice of entries.
    fn pos<F: Fn(&Change) -> bool>(entries: &[ChangeEntry], pred: F) -> usize {
        entries
            .iter()
            .position(|e| pred(&e.change))
            .expect("entry not found")
    }

    #[test]
    fn empty_changeset_yields_empty_ordered_set() {
        let target = Catalog::empty();
        let source = Catalog::empty();
        let result = order(
            &target,
            &source,
            ChangeSet::new(),
            &PlannerPolicy::default(),
        )
        .unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn linear_schema_table_index_orders_in_dependency_order() {
        // source has schema app, table users in app, index users_idx on users
        let mut source = Catalog::empty();
        source.schemas.push(Schema::new(id("app")));
        source.tables.push(Table {
            qname: qn("app", "users"),
            columns: vec![col("id", ColumnType::BigInt, false)],
            constraints: vec![],
            partition_by: None,
            partition_of: None,
            comment: None,
            owner: None,
            grants: vec![],
            rls_enabled: false,
            rls_forced: false,
            policies: vec![],
            storage: crate::ir::reloptions::TableStorageOptions::default(),
        });
        source
            .indexes
            .push(make_index("users_idx", qn("app", "users")));

        let mut cs = ChangeSet::new();
        // Push in deliberately wrong order to confirm the planner sorts.
        cs.push(
            Change::CreateIndex(make_index("users_idx", qn("app", "users"))),
            Destructiveness::Safe,
        );
        cs.push(
            Change::CreateTable(source.tables[0].clone()),
            Destructiveness::Safe,
        );
        cs.push(
            Change::CreateSchema(Schema::new(id("app"))),
            Destructiveness::Safe,
        );

        let result = order(&Catalog::empty(), &source, cs, &PlannerPolicy::default()).unwrap();
        assert_eq!(result.creates_and_adds.len(), 3);

        let schema_pos = pos(&result.creates_and_adds, |c| {
            matches!(c, Change::CreateSchema(_))
        });
        let table_pos = pos(&result.creates_and_adds, |c| {
            matches!(c, Change::CreateTable(_))
        });
        let index_pos = pos(&result.creates_and_adds, |c| {
            matches!(c, Change::CreateIndex(_))
        });
        assert!(schema_pos < table_pos);
        assert!(table_pos < index_pos);
    }

    #[test]
    fn fk_between_independent_tables_orders_referenced_first() {
        // source: orgs (referenced) and users (with FK to orgs).
        let mut source = Catalog::empty();
        source.schemas.push(Schema::new(id("app")));
        source.tables.push(Table {
            qname: qn("app", "orgs"),
            columns: vec![col("id", ColumnType::BigInt, false)],
            constraints: vec![pk("orgs_pkey", &["id"])],
            partition_by: None,
            partition_of: None,
            comment: None,
            owner: None,
            grants: vec![],
            rls_enabled: false,
            rls_forced: false,
            policies: vec![],
            storage: crate::ir::reloptions::TableStorageOptions::default(),
        });
        source.tables.push(Table {
            qname: qn("app", "users"),
            columns: vec![
                col("id", ColumnType::BigInt, false),
                col("org_id", ColumnType::BigInt, false),
            ],
            constraints: vec![
                pk("users_pkey", &["id"]),
                fk("users_org_fk", &["org_id"], qn("app", "orgs"), &["id"]),
            ],
            partition_by: None,
            partition_of: None,
            comment: None,
            owner: None,
            grants: vec![],
            rls_enabled: false,
            rls_forced: false,
            policies: vec![],
            storage: crate::ir::reloptions::TableStorageOptions::default(),
        });

        let mut cs = ChangeSet::new();
        cs.push(
            Change::CreateTable(source.tables[1].clone()), // users first
            Destructiveness::Safe,
        );
        cs.push(
            Change::CreateTable(source.tables[0].clone()), // orgs second
            Destructiveness::Safe,
        );
        cs.push(
            Change::CreateSchema(Schema::new(id("app"))),
            Destructiveness::Safe,
        );

        let result = order(&Catalog::empty(), &source, cs, &PlannerPolicy::default()).unwrap();
        assert!(result.deferred_fks.is_empty());
        let orgs_pos = result
            .creates_and_adds
            .iter()
            .position(
                |e| matches!(&e.change, Change::CreateTable(t) if t.qname == qn("app", "orgs")),
            )
            .unwrap();
        let users_pos = result
            .creates_and_adds
            .iter()
            .position(
                |e| matches!(&e.change, Change::CreateTable(t) if t.qname == qn("app", "users")),
            )
            .unwrap();
        assert!(orgs_pos < users_pos);
    }

    #[test]
    fn two_table_fk_cycle_extracts_one_or_more_fks() {
        // a.id, a.ref_id (FK -> b); b.id, b.ref_id (FK -> a).
        let mut source = Catalog::empty();
        source.schemas.push(Schema::new(id("app")));
        source.tables.push(Table {
            qname: qn("app", "a"),
            columns: vec![
                col("id", ColumnType::BigInt, false),
                col("ref_id", ColumnType::BigInt, false),
            ],
            constraints: vec![
                pk("a_pk", &["id"]),
                fk("a_to_b", &["ref_id"], qn("app", "b"), &["id"]),
            ],
            partition_by: None,
            partition_of: None,
            comment: None,
            owner: None,
            grants: vec![],
            rls_enabled: false,
            rls_forced: false,
            policies: vec![],
            storage: crate::ir::reloptions::TableStorageOptions::default(),
        });
        source.tables.push(Table {
            qname: qn("app", "b"),
            columns: vec![
                col("id", ColumnType::BigInt, false),
                col("ref_id", ColumnType::BigInt, false),
            ],
            constraints: vec![
                pk("b_pk", &["id"]),
                fk("b_to_a", &["ref_id"], qn("app", "a"), &["id"]),
            ],
            partition_by: None,
            partition_of: None,
            comment: None,
            owner: None,
            grants: vec![],
            rls_enabled: false,
            rls_forced: false,
            policies: vec![],
            storage: crate::ir::reloptions::TableStorageOptions::default(),
        });

        let mut cs = ChangeSet::new();
        cs.push(
            Change::CreateSchema(Schema::new(id("app"))),
            Destructiveness::Safe,
        );
        cs.push(
            Change::CreateTable(source.tables[0].clone()),
            Destructiveness::Safe,
        );
        cs.push(
            Change::CreateTable(source.tables[1].clone()),
            Destructiveness::Safe,
        );

        let result = order(&Catalog::empty(), &source, cs, &PlannerPolicy::default()).unwrap();
        // Both tables present in creates_and_adds, schema first.
        assert_eq!(result.creates_and_adds.len(), 3);
        // At least one FK was extracted.
        assert!(!result.deferred_fks.is_empty());
        // Each deferred entry is in fact a ForeignKey constraint.
        for d in &result.deferred_fks {
            assert!(matches!(d.constraint.kind, ConstraintKind::ForeignKey(_)));
        }
        // Total deferred + remaining FKs == original FK count (2).
        let remaining_fks: usize = result
            .creates_and_adds
            .iter()
            .map(|e| match &e.change {
                Change::CreateTable(t) => t
                    .constraints
                    .iter()
                    .filter(|c| matches!(c.kind, ConstraintKind::ForeignKey(_)))
                    .count(),
                _ => 0,
            })
            .sum();
        assert_eq!(remaining_fks + result.deferred_fks.len(), 2);
    }

    #[test]
    fn drops_run_in_reverse_dependency_order() {
        // target: schema app, table users, index users_idx
        let mut target = Catalog::empty();
        target.schemas.push(Schema::new(id("app")));
        target.tables.push(Table {
            qname: qn("app", "users"),
            columns: vec![col("id", ColumnType::BigInt, false)],
            constraints: vec![],
            partition_by: None,
            partition_of: None,
            comment: None,
            owner: None,
            grants: vec![],
            rls_enabled: false,
            rls_forced: false,
            policies: vec![],
            storage: crate::ir::reloptions::TableStorageOptions::default(),
        });
        target
            .indexes
            .push(make_index("users_idx", qn("app", "users")));

        let mut cs = ChangeSet::new();
        cs.push(
            Change::DropSchema(id("app")),
            Destructiveness::RequiresApproval { reason: "x".into() },
        );
        cs.push(
            Change::DropTable {
                qname: qn("app", "users"),
                row_count_estimate: None,
            },
            Destructiveness::RequiresApprovalAndDataLossWarning {
                reason: "drop users".into(),
            },
        );
        cs.push(
            Change::DropIndex(qn("app", "users_idx")),
            Destructiveness::Safe,
        );

        let result = order(&target, &Catalog::empty(), cs, &PlannerPolicy::default()).unwrap();
        assert_eq!(result.drops.len(), 3);
        let idx_pos = pos(&result.drops, |c| matches!(c, Change::DropIndex(_)));
        let table_pos = pos(&result.drops, |c| matches!(c, Change::DropTable { .. }));
        let schema_pos = pos(&result.drops, |c| matches!(c, Change::DropSchema(_)));
        // Reverse dependency: index dropped before table; table before schema.
        assert!(idx_pos < table_pos);
        assert!(table_pos < schema_pos);
    }

    #[test]
    fn drop_fk_constraint_handled_via_alter_table_modify_bucket() {
        // ALTER TABLE entries land in `modifies`. Confirm modify-bucket
        // ordering follows source-side dependencies.
        let mut source = Catalog::empty();
        source.schemas.push(Schema::new(id("app")));
        source.tables.push(Table {
            qname: qn("app", "users"),
            columns: vec![col("id", ColumnType::BigInt, false)],
            constraints: vec![pk("users_pkey", &["id"])],
            partition_by: None,
            partition_of: None,
            comment: None,
            owner: None,
            grants: vec![],
            rls_enabled: false,
            rls_forced: false,
            policies: vec![],
            storage: crate::ir::reloptions::TableStorageOptions::default(),
        });

        let mut cs = ChangeSet::new();
        cs.push(
            Change::AlterTable {
                qname: qn("app", "users"),
                ops: vec![],
            },
            Destructiveness::Safe,
        );

        let result = order(&Catalog::empty(), &source, cs, &PlannerPolicy::default()).unwrap();
        assert_eq!(result.modifies.len(), 1);
        assert!(result.creates_and_adds.is_empty());
        assert!(result.drops.is_empty());
    }

    #[test]
    fn deterministic_under_input_permutation() {
        // Same source, two different changeset orderings; outputs must match.
        let mut source = Catalog::empty();
        source.schemas.push(Schema::new(id("app")));
        source.tables.push(Table {
            qname: qn("app", "orgs"),
            columns: vec![col("id", ColumnType::BigInt, false)],
            constraints: vec![pk("orgs_pkey", &["id"])],
            partition_by: None,
            partition_of: None,
            comment: None,
            owner: None,
            grants: vec![],
            rls_enabled: false,
            rls_forced: false,
            policies: vec![],
            storage: crate::ir::reloptions::TableStorageOptions::default(),
        });
        source.tables.push(Table {
            qname: qn("app", "users"),
            columns: vec![col("id", ColumnType::BigInt, false)],
            constraints: vec![pk("users_pkey", &["id"])],
            partition_by: None,
            partition_of: None,
            comment: None,
            owner: None,
            grants: vec![],
            rls_enabled: false,
            rls_forced: false,
            policies: vec![],
            storage: crate::ir::reloptions::TableStorageOptions::default(),
        });

        let mk_cs = |reversed: bool| {
            let mut cs = ChangeSet::new();
            let entries = [
                Change::CreateSchema(Schema::new(id("app"))),
                Change::CreateTable(source.tables[0].clone()),
                Change::CreateTable(source.tables[1].clone()),
            ];
            let iter: Box<dyn Iterator<Item = &Change>> = if reversed {
                Box::new(entries.iter().rev())
            } else {
                Box::new(entries.iter())
            };
            for c in iter {
                cs.push(c.clone(), Destructiveness::Safe);
            }
            cs
        };

        let policy = PlannerPolicy::default();
        let r1 = order(&Catalog::empty(), &source, mk_cs(false), &policy).unwrap();
        let r2 = order(&Catalog::empty(), &source, mk_cs(true), &policy).unwrap();
        assert_eq!(r1, r2);
    }

    #[test]
    fn replace_index_lands_in_modifies() {
        let mut source = Catalog::empty();
        source.schemas.push(Schema::new(id("app")));
        source.tables.push(Table {
            qname: qn("app", "users"),
            columns: vec![col("id", ColumnType::BigInt, false)],
            constraints: vec![],
            partition_by: None,
            partition_of: None,
            comment: None,
            owner: None,
            grants: vec![],
            rls_enabled: false,
            rls_forced: false,
            policies: vec![],
            storage: crate::ir::reloptions::TableStorageOptions::default(),
        });
        source
            .indexes
            .push(make_index("users_idx", qn("app", "users")));

        let mut cs = ChangeSet::new();
        cs.push(
            Change::ReplaceIndex {
                from: make_index("users_idx", qn("app", "users")),
                to: make_index("users_idx", qn("app", "users")),
            },
            Destructiveness::Safe,
        );

        let result = order(&Catalog::empty(), &source, cs, &PlannerPolicy::default()).unwrap();
        assert_eq!(result.modifies.len(), 1);
    }

    #[test]
    fn alter_sequence_lands_in_modifies() {
        use crate::ir::sequence::Sequence;
        let mut source = Catalog::empty();
        source.sequences.push(Sequence {
            qname: qn("app", "s1"),
            data_type: ColumnType::BigInt,
            start: 1,
            increment: 1,
            min_value: None,
            max_value: None,
            cache: 1,
            cycle: false,
            owned_by: None,
            comment: None,
            owner: None,
            grants: vec![],
        });

        let mut cs = ChangeSet::new();
        cs.push(
            Change::AlterSequence {
                qname: qn("app", "s1"),
                ops: vec![],
            },
            Destructiveness::Safe,
        );

        let result = order(&Catalog::empty(), &source, cs, &PlannerPolicy::default()).unwrap();
        assert_eq!(result.modifies.len(), 1);
    }

    #[test]
    fn three_way_fk_cycle_breaks_at_least_one() {
        // a -> b -> c -> a
        let mut source = Catalog::empty();
        source.schemas.push(Schema::new(id("app")));
        for n in ["a", "b", "c"] {
            source.tables.push(Table {
                qname: qn("app", n),
                columns: vec![
                    col("id", ColumnType::BigInt, false),
                    col("ref_id", ColumnType::BigInt, false),
                ],
                constraints: vec![pk(&format!("{n}_pk"), &["id"])],
                partition_by: None,
                partition_of: None,
                comment: None,
                owner: None,
                grants: vec![],
                rls_enabled: false,
                rls_forced: false,
                policies: vec![],
                storage: crate::ir::reloptions::TableStorageOptions::default(),
            });
        }
        // Add FKs forming a cycle: a -> b, b -> c, c -> a.
        let pairs = [("a", "b"), ("b", "c"), ("c", "a")];
        for (from, to) in pairs {
            let table = source
                .tables
                .iter_mut()
                .find(|t| t.qname == qn("app", from))
                .unwrap();
            table.constraints.push(fk(
                &format!("{from}_to_{to}"),
                &["ref_id"],
                qn("app", to),
                &["id"],
            ));
        }

        let mut cs = ChangeSet::new();
        cs.push(
            Change::CreateSchema(Schema::new(id("app"))),
            Destructiveness::Safe,
        );
        for t in &source.tables {
            cs.push(Change::CreateTable(t.clone()), Destructiveness::Safe);
        }

        let result = order(&Catalog::empty(), &source, cs, &PlannerPolicy::default()).unwrap();
        assert_eq!(result.creates_and_adds.len(), 4);
        assert!(!result.deferred_fks.is_empty());
    }

    #[test]
    fn drops_with_independent_objects_use_target_graph() {
        // Target has two independent schemas + tables; drop them all.
        let mut target = Catalog::empty();
        target.schemas.push(Schema::new(id("a")));
        target.schemas.push(Schema::new(id("b")));
        target.tables.push(Table {
            qname: QualifiedName::new(id("a"), id("t1")),
            columns: vec![col("id", ColumnType::BigInt, false)],
            constraints: vec![],
            partition_by: None,
            partition_of: None,
            comment: None,
            owner: None,
            grants: vec![],
            rls_enabled: false,
            rls_forced: false,
            policies: vec![],
            storage: crate::ir::reloptions::TableStorageOptions::default(),
        });
        target.tables.push(Table {
            qname: QualifiedName::new(id("b"), id("t2")),
            columns: vec![col("id", ColumnType::BigInt, false)],
            constraints: vec![],
            partition_by: None,
            partition_of: None,
            comment: None,
            owner: None,
            grants: vec![],
            rls_enabled: false,
            rls_forced: false,
            policies: vec![],
            storage: crate::ir::reloptions::TableStorageOptions::default(),
        });

        let mut cs = ChangeSet::new();
        for t in &target.tables {
            cs.push(
                Change::DropTable {
                    qname: t.qname.clone(),
                    row_count_estimate: None,
                },
                Destructiveness::RequiresApprovalAndDataLossWarning {
                    reason: "drop".into(),
                },
            );
        }
        for s in &target.schemas {
            cs.push(
                Change::DropSchema(s.name.clone()),
                Destructiveness::RequiresApproval {
                    reason: "drop".into(),
                },
            );
        }

        let result = order(&target, &Catalog::empty(), cs, &PlannerPolicy::default()).unwrap();
        assert_eq!(result.drops.len(), 4);
        // Every DropTable must precede the corresponding DropSchema.
        for table in &target.tables {
            let table_pos = result
                .drops
                .iter()
                .position(|e| matches!(&e.change, Change::DropTable { qname, .. } if qname == &table.qname))
                .unwrap();
            let schema_pos = result
                .drops
                .iter()
                .position(
                    |e| matches!(&e.change, Change::DropSchema(s) if s == &table.qname.schema),
                )
                .unwrap();
            assert!(table_pos < schema_pos);
        }
    }

    // ---- Suppress dead-code warnings for the `drop` helper used in tests. ----
    #[test]
    fn _drop_helper_is_used() {
        let _ = drop(Change::DropSchema(id("x")));
        let _ = safe(Change::CreateSchema(Schema::new(id("y"))));
    }

    #[test]
    fn drop_index_elided_when_alter_table_drops_indexed_column() {
        // Postgres cascade-drops any index whose column list references a
        // column being dropped by `ALTER TABLE ... DROP COLUMN`. If the
        // planner emits a separate `DROP INDEX` in the drops phase that runs
        // after the column drop, the explicit DROP fails with
        // `42704 (undefined_object): index "..." does not exist`.
        //
        // The planner must therefore elide such DropIndex changes — the
        // cascade is implicit in the column drop.
        let mut target = Catalog::empty();
        target.schemas.push(Schema::new(id("app")));
        target.tables.push(Table {
            qname: qn("app", "users"),
            columns: vec![
                col("id", ColumnType::BigInt, false),
                col("deleted_at", ColumnType::Text, true),
            ],
            constraints: vec![pk("users_pkey", &["id"])],
            partition_by: None,
            partition_of: None,
            comment: None,
            owner: None,
            grants: vec![],
            rls_enabled: false,
            rls_forced: false,
            policies: vec![],
            storage: crate::ir::reloptions::TableStorageOptions::default(),
        });
        target.indexes.push(Index {
            qname: qn("app", "users_deleted_at_idx"),
            on: IndexParent::Table(qn("app", "users")),
            method: IndexMethod::BTree,
            columns: vec![IndexColumn {
                expr: IndexColumnExpr::Column(id("deleted_at")),
                collation: None,
                opclass: None,
                sort_order: SortOrder::Asc,
                nulls_order: NullsOrder::NullsLast,
            }],
            include: vec![],
            unique: false,
            nulls_not_distinct: false,
            predicate: None,
            tablespace: None,
            comment: None,
            storage: crate::ir::reloptions::IndexStorageOptions::default(),
        });

        let mut source = Catalog::empty();
        source.schemas.push(Schema::new(id("app")));
        source.tables.push(Table {
            qname: qn("app", "users"),
            columns: vec![col("id", ColumnType::BigInt, false)],
            constraints: vec![pk("users_pkey", &["id"])],
            partition_by: None,
            partition_of: None,
            comment: None,
            owner: None,
            grants: vec![],
            rls_enabled: false,
            rls_forced: false,
            policies: vec![],
            storage: crate::ir::reloptions::TableStorageOptions::default(),
        });

        let mut cs = ChangeSet::new();
        cs.push(
            Change::AlterTable {
                qname: qn("app", "users"),
                ops: vec![TableOpEntry {
                    op: TableOp::DropColumn {
                        name: id("deleted_at"),
                        is_populated: false,
                    },
                    destructiveness: Destructiveness::RequiresApproval {
                        reason: "drops column".into(),
                    },
                }],
            },
            Destructiveness::RequiresApproval {
                reason: "drops column".into(),
            },
        );
        cs.push(
            Change::DropIndex(qn("app", "users_deleted_at_idx")),
            Destructiveness::RequiresApproval {
                reason: "drops index".into(),
            },
        );

        let result = order(&target, &source, cs, &PlannerPolicy::default()).unwrap();
        assert_eq!(result.modifies.len(), 1, "AlterTable must stay in modifies");
        assert!(
            result.drops.is_empty(),
            "DropIndex must be elided when the indexed column is dropped in \
             the same plan; got: {:?}",
            result.drops.iter().map(|e| &e.change).collect::<Vec<_>>()
        );
    }

    #[test]
    fn drop_index_retained_when_column_drop_unrelated() {
        // Sanity check on the elision logic: if the column being dropped is
        // not in the index's column list, the DropIndex must NOT be elided.
        let mut target = Catalog::empty();
        target.schemas.push(Schema::new(id("app")));
        target.tables.push(Table {
            qname: qn("app", "users"),
            columns: vec![
                col("id", ColumnType::BigInt, false),
                col("email", ColumnType::Text, true),
                col("unused", ColumnType::Text, true),
            ],
            constraints: vec![pk("users_pkey", &["id"])],
            partition_by: None,
            partition_of: None,
            comment: None,
            owner: None,
            grants: vec![],
            rls_enabled: false,
            rls_forced: false,
            policies: vec![],
            storage: crate::ir::reloptions::TableStorageOptions::default(),
        });
        // Index on `email`, but the column being dropped is `unused`.
        target.indexes.push(Index {
            qname: qn("app", "users_email_idx"),
            on: IndexParent::Table(qn("app", "users")),
            method: IndexMethod::BTree,
            columns: vec![IndexColumn {
                expr: IndexColumnExpr::Column(id("email")),
                collation: None,
                opclass: None,
                sort_order: SortOrder::Asc,
                nulls_order: NullsOrder::NullsLast,
            }],
            include: vec![],
            unique: false,
            nulls_not_distinct: false,
            predicate: None,
            tablespace: None,
            comment: None,
            storage: crate::ir::reloptions::IndexStorageOptions::default(),
        });

        let mut source = Catalog::empty();
        source.schemas.push(Schema::new(id("app")));
        source.tables.push(Table {
            qname: qn("app", "users"),
            columns: vec![
                col("id", ColumnType::BigInt, false),
                col("email", ColumnType::Text, true),
            ],
            constraints: vec![pk("users_pkey", &["id"])],
            partition_by: None,
            partition_of: None,
            comment: None,
            owner: None,
            grants: vec![],
            rls_enabled: false,
            rls_forced: false,
            policies: vec![],
            storage: crate::ir::reloptions::TableStorageOptions::default(),
        });
        // Source still has the email index, but it's being dropped from the
        // source for an unrelated reason (simulate user removing it).

        let mut cs = ChangeSet::new();
        cs.push(
            Change::AlterTable {
                qname: qn("app", "users"),
                ops: vec![TableOpEntry {
                    op: TableOp::DropColumn {
                        name: id("unused"),
                        is_populated: false,
                    },
                    destructiveness: Destructiveness::RequiresApproval {
                        reason: "drops column".into(),
                    },
                }],
            },
            Destructiveness::RequiresApproval {
                reason: "drops column".into(),
            },
        );
        cs.push(
            Change::DropIndex(qn("app", "users_email_idx")),
            Destructiveness::RequiresApproval {
                reason: "drops index".into(),
            },
        );

        let result = order(&target, &source, cs, &PlannerPolicy::default()).unwrap();
        assert_eq!(result.modifies.len(), 1);
        assert_eq!(
            result.drops.len(),
            1,
            "DropIndex must be retained when the dropped column is unrelated"
        );
    }

    #[test]
    fn drop_index_elided_when_indexed_column_is_in_include_list() {
        // INCLUDE columns participate in the index's storage and dropping
        // them also cascades the index.
        let mut target = Catalog::empty();
        target.schemas.push(Schema::new(id("app")));
        target.tables.push(Table {
            qname: qn("app", "users"),
            columns: vec![
                col("id", ColumnType::BigInt, false),
                col("email", ColumnType::Text, true),
                col("payload", ColumnType::Text, true),
            ],
            constraints: vec![pk("users_pkey", &["id"])],
            partition_by: None,
            partition_of: None,
            comment: None,
            owner: None,
            grants: vec![],
            rls_enabled: false,
            rls_forced: false,
            policies: vec![],
            storage: crate::ir::reloptions::TableStorageOptions::default(),
        });
        target.indexes.push(Index {
            qname: qn("app", "users_email_idx"),
            on: IndexParent::Table(qn("app", "users")),
            method: IndexMethod::BTree,
            columns: vec![IndexColumn {
                expr: IndexColumnExpr::Column(id("email")),
                collation: None,
                opclass: None,
                sort_order: SortOrder::Asc,
                nulls_order: NullsOrder::NullsLast,
            }],
            include: vec![id("payload")],
            unique: false,
            nulls_not_distinct: false,
            predicate: None,
            tablespace: None,
            comment: None,
            storage: crate::ir::reloptions::IndexStorageOptions::default(),
        });

        let mut source = Catalog::empty();
        source.schemas.push(Schema::new(id("app")));
        source.tables.push(Table {
            qname: qn("app", "users"),
            columns: vec![
                col("id", ColumnType::BigInt, false),
                col("email", ColumnType::Text, true),
            ],
            constraints: vec![pk("users_pkey", &["id"])],
            partition_by: None,
            partition_of: None,
            comment: None,
            owner: None,
            grants: vec![],
            rls_enabled: false,
            rls_forced: false,
            policies: vec![],
            storage: crate::ir::reloptions::TableStorageOptions::default(),
        });

        let mut cs = ChangeSet::new();
        cs.push(
            Change::AlterTable {
                qname: qn("app", "users"),
                ops: vec![TableOpEntry {
                    op: TableOp::DropColumn {
                        name: id("payload"),
                        is_populated: false,
                    },
                    destructiveness: Destructiveness::RequiresApproval {
                        reason: "drops column".into(),
                    },
                }],
            },
            Destructiveness::RequiresApproval {
                reason: "drops column".into(),
            },
        );
        cs.push(
            Change::DropIndex(qn("app", "users_email_idx")),
            Destructiveness::RequiresApproval {
                reason: "drops index".into(),
            },
        );

        let result = order(&target, &source, cs, &PlannerPolicy::default()).unwrap();
        assert!(
            result.drops.is_empty(),
            "DropIndex must be elided when an INCLUDEd column is dropped; got: {:?}",
            result.drops.iter().map(|e| &e.change).collect::<Vec<_>>()
        );
    }

    // ── UserType partition / change_node tests ────────────────────────────────

    use crate::diff::change::UserTypeChange;
    use crate::ir::user_type::{UserType, UserTypeKind};

    fn make_enum_type(schema: &str, name: &str) -> UserType {
        UserType {
            qname: qn(schema, name),
            kind: UserTypeKind::Enum { values: vec![] },
            comment: None,
            owner: None,
            grants: vec![],
        }
    }

    #[test]
    fn user_type_create_lands_in_creates() {
        let ut = make_enum_type("app", "status");
        let mut source = Catalog::empty();
        source.types.push(ut.clone());

        let mut cs = ChangeSet::new();
        cs.push(
            Change::UserType(UserTypeChange::Create(ut)),
            Destructiveness::Safe,
        );

        let result = order(&Catalog::empty(), &source, cs, &PlannerPolicy::default()).unwrap();
        assert_eq!(
            result.creates_and_adds.len(),
            1,
            "Create must land in creates_and_adds"
        );
        assert!(result.modifies.is_empty());
        assert!(result.drops.is_empty());
    }

    #[test]
    fn user_type_drop_lands_in_drops() {
        let ut = make_enum_type("app", "status");
        let mut target = Catalog::empty();
        target.types.push(ut);

        let mut cs = ChangeSet::new();
        cs.push(
            Change::UserType(UserTypeChange::Drop(qn("app", "status"))),
            Destructiveness::RequiresApproval {
                reason: "drop type".into(),
            },
        );

        let result = order(&target, &Catalog::empty(), cs, &PlannerPolicy::default()).unwrap();
        assert_eq!(result.drops.len(), 1, "Drop must land in drops");
        assert!(result.creates_and_adds.is_empty());
        assert!(result.modifies.is_empty());
    }

    #[test]
    fn user_type_replace_with_cascade_lands_in_drops() {
        let ut = make_enum_type("app", "status");
        let mut target = Catalog::empty();
        target.types.push(ut.clone());

        let mut cs = ChangeSet::new();
        cs.push(
            Change::UserType(UserTypeChange::ReplaceWithCascade {
                source: ut.clone(),
                catalog: ut,
            }),
            Destructiveness::RequiresApproval {
                reason: "cascade replace".into(),
            },
        );

        let result = order(&target, &Catalog::empty(), cs, &PlannerPolicy::default()).unwrap();
        assert_eq!(
            result.drops.len(),
            1,
            "ReplaceWithCascade must land in drops"
        );
        assert!(result.creates_and_adds.is_empty());
        assert!(result.modifies.is_empty());
    }

    #[test]
    fn user_type_enum_add_value_lands_in_modifies() {
        let ut = make_enum_type("app", "status");
        let mut source = Catalog::empty();
        source.types.push(ut);

        let mut cs = ChangeSet::new();
        cs.push(
            Change::UserType(UserTypeChange::EnumAddValue {
                qname: qn("app", "status"),
                value: "archived".into(),
                before: None,
                after: None,
            }),
            Destructiveness::Safe,
        );

        let result = order(&Catalog::empty(), &source, cs, &PlannerPolicy::default()).unwrap();
        assert_eq!(
            result.modifies.len(),
            1,
            "EnumAddValue must land in modifies"
        );
        assert!(result.creates_and_adds.is_empty());
        assert!(result.drops.is_empty());
    }

    #[test]
    fn user_type_create_before_table_using_it() {
        // When both a type create and a table create are in the changeset,
        // the type must come first (table depends on it in the source graph).
        use crate::ir::column::Column;

        let ut = make_enum_type("app", "status");
        let mut source = Catalog::empty();
        source.types.push(ut.clone());
        source.tables.push(Table {
            qname: qn("app", "orders"),
            columns: vec![Column {
                name: id("status"),
                ty: ColumnType::UserDefined(qn("app", "status")),
                nullable: false,
                default: None,
                identity: None,
                generated: None,
                collation: None,
                storage: None,
                compression: None,
                comment: None,
            }],
            constraints: vec![],
            partition_by: None,
            partition_of: None,
            comment: None,
            owner: None,
            grants: vec![],
            rls_enabled: false,
            rls_forced: false,
            policies: vec![],
            storage: crate::ir::reloptions::TableStorageOptions::default(),
        });

        let mut cs = ChangeSet::new();
        // Deliberately push table first to verify sorting.
        cs.push(
            Change::CreateTable(source.tables[0].clone()),
            Destructiveness::Safe,
        );
        cs.push(
            Change::UserType(UserTypeChange::Create(ut)),
            Destructiveness::Safe,
        );

        let result = order(&Catalog::empty(), &source, cs, &PlannerPolicy::default()).unwrap();
        let type_pos = result
            .creates_and_adds
            .iter()
            .position(|e| matches!(&e.change, Change::UserType(UserTypeChange::Create(_))))
            .expect("type create not found");
        let table_pos = result
            .creates_and_adds
            .iter()
            .position(|e| matches!(&e.change, Change::CreateTable(_)))
            .expect("table create not found");
        assert!(
            type_pos < table_pos,
            "type must be created before the table that uses it"
        );
    }
}