autumn-cli 0.6.0

CLI tool for the Autumn web framework
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
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
//! The declarative-schema **diff engine** (slice 4 of tracking issue #1975).
//!
//! Given a **desired** state (the app's `#[model]` structs, lifted by the
//! slice-2 [parser](crate::schema::parse)) and a **baseline** (the checked-in,
//! dialect-tagged [snapshot](crate::schema::snapshot) from slice 3), this module
//! computes the pending migration — `desired − baseline` — as a structured
//! [`MigrationPlan`] and renders it as a diesel `up.sql` / `down.sql` pair.
//!
//! It is a **pure, DB-free, IO-free** library module: [`diff_schema`] is a pure
//! function of two in-memory schema states, [`guard_plan`] is a pure policy
//! check, and [`emit_up_sql`] / [`emit_down_sql`] are pure renderers. All IO
//! (loading the snapshot, parsing the models directory, writing the migration
//! files) lives in the command wiring ([`crate::schema::run`]'s `run_diff`), not
//! here.
//!
//! # Conservatism over completeness (the load-bearing rule)
//!
//! The slice-2 parser is a **partial** view of the schema: it documents three
//! gaps it cannot represent — (a) it never fabricates a `CHECK` for an enum
//! column, (b) only an explicit `#[references]` yields a foreign key (association
//! FKs are invisible), and (c) only convention `#[default]`s are recovered. A
//! migration derived from a partial desired state must therefore **never emit a
//! destructive op for a facet the parser simply cannot see** — doing so would
//! delete hand-written constraints that live only in the (richer) baseline.
//!
//! This module encodes that as the deliberate **absence** of `DropCheck`,
//! `DropForeignKey`, and `DropDefault` variants on [`SchemaChange`]: a baseline
//! check / FK / default absent from the desired side is treated as *unknown,
//! retained* — not *removed*. An enum column the parser skipped (recorded as a
//! [`SchemaDiagnostic`](crate::schema::parse::SchemaDiagnostic)) is likewise not
//! dropped. The **accepted trade-off** is that the diff is intentionally
//! conservative and will *miss* a genuine removal of one of those facets; that is
//! preferable to ever destroying parser-invisible or hand-written state, and the
//! genuine-removal case is recovered by later slices (`#[renamed_from]`, richer
//! parsing, a shadow-DB oracle).
//!
//! # Invisible `#[belongs_to(...)]` association foreign keys (offline limitation)
//!
//! The slice-2 parser cannot see a generated `#[belongs_to(...)]` association
//! foreign key: real generator output models it as a plain `<name>_id: i64`
//! column plus a **struct-level** `#[belongs_to(...)]` attribute, and the parser
//! lifts the `i64` field as an ordinary `Int64` column with `references: None` and
//! **no diagnostic** (only an *unresolvable field type* — a generated enum, or an
//! association written as a bare struct-typed field `pub user: User` — records a
//! [`SchemaDiagnostic`](crate::schema::parse::SchemaDiagnostic), and even that
//! carries no target-table). So the diff engine has **no offline signal** for the
//! presence, column, or target of an association FK. This produces two
//! consequences the engine handles conservatively:
//!
//! 1. **Adding a foreign key to a pre-existing column is refused**
//!    ([`DiffError::AddForeignKeyToPreexistingColumn`]). When a column present on
//!    both sides gains an explicit `#[references]` where the baseline recorded
//!    none, the baseline `references: None` is *unknown*, not proof the database
//!    lacks a constraint — the column may already carry an inline `REFERENCES`
//!    named `<table>_<column>_fkey` from the original association-FK generation, so
//!    a fresh `ADD CONSTRAINT <table>_<column>_fkey` would collide and the
//!    migration would not apply. The engine refuses (no override) rather than emit
//!    it; the fix is a manual migration or an authoritative re-snapshot. A
//!    **brand-new** FK column (an `AddColumn` whose `REFERENCES` renders inline) is
//!    safe and is emitted normally — there is no pre-existing constraint to hit.
//!
//! 2. **`DROP TABLE` cannot be checked against invisible inbound association
//!    FKs.** The inbound-reference scan ([`detect_inbound_fk_blocks`]) refuses a
//!    drop whenever a retained table holds a **visible** `references` to the
//!    dropped table (rounds 2/3/5, unchanged and still enforced). But an invisible
//!    `#[belongs_to(...)]` association FK on a retained table produces no
//!    `Column.references` and no diagnostic, so it cannot be detected offline —
//!    the resulting `DROP TABLE` (already `--allow-destructive`-gated) may fail to
//!    apply because the real `<retained>_<col>_fkey` constraint still depends on
//!    the dropped table. A precise guard is impossible without schema introspection
//!    (a future slice's shadow-DB / `--dev-url` oracle); a blanket "refuse every
//!    table drop" would make the common case useless and is deliberately **not**
//!    done. Instead every emitted `DROP TABLE` carries an advisory
//!    `-- autumn-safety:` comment naming this exact gap so the operator verifies
//!    (introspection or a manual FK drop) before applying. This is a documented
//!    limitation of the offline approach, not a bug.
//!
//! # Uniqueness is diffed only through indexes
//!
//! `Column.unique` is treated as informational metadata and is **not** separately
//! diffed. The slice-2 parser always emits a `unique` column together with its
//! `idx_<table>_<field>_unique` unique index, so the index set already carries
//! the uniqueness signal; diffing both would double-count.
//!
//! # Required-column additions need a default
//!
//! Adding a `NOT NULL` column **without a default** to an *existing* table is
//! refused ([`DiffError::RequiredColumnWithoutDefault`]): Postgres validates the
//! constraint against existing rows the instant the column is added, so the
//! `ALTER TABLE ... ADD COLUMN ... NOT NULL` fails on any table that already has
//! rows, and the offline diff engine has no backfill value to synthesize (the
//! safe nullable → backfill → `SET NOT NULL` sequence is a manual multi-step
//! migration). Give the field a `#[default(...)]` (including a synthesized one
//! like `created_at DEFAULT NOW()`) or make it nullable (`Option<...>`). A
//! `NOT NULL`, no-default column inside a brand-new `CreateTable` is fine — the
//! table is empty — and is not refused.
//!
//! Its exact sibling — turning an *existing* nullable column non-null
//! (`SET NOT NULL`) — is refused for the same reason
//! ([`DiffError::SetNotNullRequiresBackfill`]): Postgres validates the
//! constraint against every existing row the instant the `ALTER COLUMN ... SET
//! NOT NULL` runs, so it fails on any pre-existing NULL, and the offline engine
//! has no backfill value to synthesize. The only appliable form would pair a
//! default with a backfill, which is not expressible offline. The inverse
//! (`DROP NOT NULL`, making a column nullable) is always safe and is emitted
//! normally.
//!
//! # Generated identifiers must fit Postgres's 63-byte limit
//!
//! This engine derives some identifiers by unbounded interpolation — the foreign-key
//! constraint name `{table}_{column}_fkey` (`ADD CONSTRAINT` up, `DROP CONSTRAINT`
//! down — both derive it identically, so they always agree) — and emits the
//! parser-provided index names (`idx_<table>_<field>`) verbatim. Postgres silently
//! truncates any identifier to 63 bytes (`NAMEDATALEN - 1`). A generated name over
//! that limit is therefore (a) *silently renamed* on apply, risking a mismatch with
//! hand-written SQL that spells the untruncated name, and (b) a *collision* hazard:
//! if two generated names in the same migration share their first 63 bytes, PG
//! accepts the first `ADD CONSTRAINT`/`CREATE INDEX` and rejects the second as a
//! duplicate relation — an unappliable migration.
//!
//! The **engine-generated FK-constraint name** is purely internal (Postgres would
//! otherwise auto-name the constraint), so it is safe to rename: when
//! `{table}_{column}_fkey` would exceed 63 bytes it is passed through
//! [`bounded_pg_identifier`], which truncates the head and appends a short,
//! deterministic hex suffix (a digest of the full untruncated name) so the result
//! is a valid `≤ 63`-byte identifier. The **same** helper drives both the up
//! `ADD CONSTRAINT` and the down `DROP CONSTRAINT`, and the [`guard_plan`] length
//! check, so all three always agree on the emitted name. A short FK name (the
//! common case) is returned unchanged, so Postgres output is byte-stable.
//!
//! Parser-provided index names (`idx_<table>_<field>`) are **not** renamed — the
//! app spells them elsewhere — so [`guard_plan`] still refuses (no override — the
//! SQL is unappliable, not merely lossy) any Postgres plan that generates an index
//! identifier **longer than 63 bytes**, plus (defensively) any pair of generated
//! names that collide after truncation ([`DiffError::GeneratedIdentifierTooLong`]).
//! The check is **Postgres-only**: `SQLite` has no comparably short identifier
//! limit and does not truncate.
//!
//! # `SQLite` boundary
//!
//! Slice 5 renders both dialects. Postgres emits the direct `ALTER`-family
//! statements; `SQLite` — which has no `ALTER COLUMN TYPE` / `SET`/`DROP NOT NULL`
//! / `SET DEFAULT` / `ADD CHECK` / `ADD CONSTRAINT` — realises those via the
//! **table-recreate** strategy ([`emit_up_sql_with_context`]): `CREATE` a new table
//! with the desired shape, `INSERT .. SELECT` the surviving rows, `DROP` the old
//! table, `RENAME` the new one into place, and recreate the desired indexes,
//! wrapped with `PRAGMA foreign_keys` + a `PRAGMA foreign_key_check`. The recreate
//! needs a table's full desired (up) / baseline (down) shape, which the per-change
//! [`SchemaChange`] deltas do not carry, so it is threaded in via a
//! [`SchemaContext`]; the context-free [`emit_up_sql`] / [`emit_down_sql`] cover
//! Postgres and the portable `SQLite` subset (`CREATE TABLE`, `DROP TABLE`,
//! `ADD COLUMN`, `CREATE`/`DROP INDEX`) and return [`EmitError::SqliteRebuildUnsupported`]
//! if a `SQLite` rebuild is required without the shapes to build it.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;

use autumn_schema_core::{
    Backend, CheckConstraint, Column, ColumnDefault, ColumnType, IdKind, Index, SerialKind,
    SqliteAffinity, Table,
};

use crate::schema::parse::ParsedSchema;

/// The computed migration: an ordered list of structural changes plus the
/// dialect they render against. Deterministic — same inputs ⇒ same plan ⇒ same
/// SQL.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MigrationPlan {
    /// The dialect the plan renders against (its provider-lock).
    pub backend: Backend,
    /// The structural changes, in a stable order.
    pub changes: Vec<SchemaChange>,
}

impl MigrationPlan {
    /// True when there is nothing to migrate (the no-op case).
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.changes.is_empty()
    }
}

/// One structural change. Variants that DROP existing state carry the full
/// baseline object so `down.sql` can reconstruct it; `Alter*` carry both
/// endpoints so the down leg can invert.
///
/// **Deliberately-absent variants (conservatism):** there is no `DropDefault`,
/// no `DropForeignKey`, no `DropCheck`, and no `AlterUnique`. Those would fire on
/// facets the slice-2 parser cannot fully observe, so emitting them risks
/// destroying hand-written state — their absence is the conservatism mechanism,
/// not an oversight (see the module docs).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SchemaChange {
    // ---- table level ----
    /// A managed table present in the desired state but not the baseline.
    CreateTable(Table),
    /// A managed table present in the baseline but not the desired state.
    /// DESTRUCTIVE; carries the full baseline [`Table`] so `down.sql` can rebuild
    /// it.
    DropTable(Table),

    // ---- column level (keyed on column NAME, never position) ----
    /// A column present in the desired table but not the baseline.
    AddColumn {
        /// The owning table name.
        table: String,
        /// The new column.
        column: Column,
    },
    /// A column present in the baseline table but not the desired one.
    /// DESTRUCTIVE; carries the full baseline [`Column`] so `down.sql` can re-add
    /// it.
    DropColumn {
        /// The owning table name.
        table: String,
        /// The baseline column being dropped.
        column: Column,
    },
    /// A same-named column whose logical type changed.
    AlterColumnType {
        /// The owning table name.
        table: String,
        /// The column name.
        column: String,
        /// The baseline type (for the down leg).
        from: ColumnType,
        /// The desired type.
        to: ColumnType,
    },
    /// A same-named column that gained a `NOT NULL` constraint.
    SetNotNull {
        /// The owning table name.
        table: String,
        /// The column name.
        column: String,
    },
    /// A same-named column that dropped its `NOT NULL` constraint.
    DropNotNull {
        /// The owning table name.
        table: String,
        /// The column name.
        column: String,
    },
    /// A same-named column whose default was set or changed. Carries the baseline
    /// default so the down leg can restore or drop it.
    SetDefault {
        /// The owning table name.
        table: String,
        /// The column name.
        column: String,
        /// The desired default.
        to: ColumnDefault,
        /// The baseline default, if any (for the down leg).
        from: Option<ColumnDefault>,
    },
    /// An explicit foreign key added as a **standalone** `ADD CONSTRAINT ...
    /// FOREIGN KEY` statement.
    ///
    /// Not currently produced by [`diff_schema`]: a **new** FK column renders its
    /// `REFERENCES` inline in the `ADD COLUMN`, and adding an FK to a
    /// **pre-existing** column is refused (see
    /// [`SchemaChange::AddForeignKeyToExistingColumn`] — the parser cannot see a
    /// generated association FK, so it cannot prove the constraint is absent). The
    /// variant and its renderer are retained for the future slice that can observe
    /// FK constraints reliably (schema introspection / a shadow-DB oracle) and can
    /// therefore safely emit a standalone FK add on an existing column.
    #[allow(dead_code)]
    AddForeignKey {
        /// The owning table name.
        table: String,
        /// The column name.
        column: String,
        /// The referenced table/column.
        foreign_key: autumn_schema_core::ForeignKey,
    },

    // ---- index / check level (add/remove by NAME) ----
    /// A secondary index present in the desired table but not the baseline.
    AddIndex {
        /// The owning table name.
        table: String,
        /// The new index.
        index: Index,
    },
    /// A secondary index present in the baseline table but not the desired one.
    /// Carries the full baseline [`Index`] so `down.sql` can recreate it. Not in
    /// the destructive tier (it drops no rows).
    DropIndex {
        /// The owning table name.
        table: String,
        /// The baseline index being dropped.
        index: Index,
    },
    /// A `CHECK` constraint present in the desired table but not the baseline.
    /// (There is deliberately no `DropCheck` — see the module docs.)
    AddCheck {
        /// The owning table name.
        table: String,
        /// The new check constraint.
        check: CheckConstraint,
    },

    /// A managed both-present table whose primary key differs. A non-emittable
    /// marker: [`guard_plan`] refuses any plan containing it (with no override),
    /// so it never reaches the emitters in the command flow. It exists so the
    /// plan-only `guard_plan` signature can detect the change — a PK migration is
    /// exotic, backend-divergent, and out of scope for this slice.
    PrimaryKeyChange {
        /// The table whose primary key changed.
        table: String,
    },

    /// A same-named column whose **existing** explicit foreign key changed target
    /// (e.g. `author_id` from `users(id)` to `accounts(id)`). A non-emittable
    /// marker: [`guard_plan`] refuses any plan containing it (with no override).
    ///
    /// It exists because a conservative engine cannot safely retarget an FK: it
    /// has no `DropForeignKey` variant to remove the baseline constraint (whose
    /// name is PG's default `<table>_<column>_fkey`), so blindly emitting an
    /// `AddForeignKey` would collide on that constraint name and the migration
    /// would fail. Retargeting an FK is deferred (a later slice can drop+recreate
    /// once it can observe FK constraints reliably); until then it is refused.
    ForeignKeyChange {
        /// The owning table name.
        table: String,
        /// The column whose FK target changed.
        column: String,
    },

    /// A same-named column whose `GENERATED … AS IDENTITY` clause changed between
    /// two authoritative introspections — e.g. the live database dropped the
    /// identity (`GENERATED ALWAYS AS IDENTITY` → a plain column) or flipped its
    /// generation (`ALWAYS` ↔ `BY DEFAULT`). A non-emittable marker: [`guard_plan`]
    /// refuses any plan containing it (with **no override**).
    ///
    /// It exists so an identity-generation change surfaces as real drift in the
    /// introspection diff (doctor's `database-schema-drift` and `pull --dry-run`)
    /// instead of being silently ignored — changing an identity clause requires
    /// `ADD`/`DROP`/`SET GENERATED …`, an exotic, out-of-scope operation this slice
    /// does not auto-emit (mirroring the serial-PK id-generation refusal). It is
    /// produced **only** in an authoritative diff (`definitions_authoritative`):
    /// the model parser cannot express an identity clause, so in a model diff a
    /// desired `identity: None` is "unknown, retained" (never drift), exactly like a
    /// baseline `definition` index the DSL cannot describe.
    IdentityChange {
        /// The owning table name.
        table: String,
        /// The column whose identity clause changed.
        column: String,
    },

    /// A managed table is dropped while a **retained** table still holds a
    /// baseline foreign key pointing at it (e.g. drop `users` while
    /// `posts.user_id REFERENCES users(id)` survives). A non-emittable marker:
    /// [`guard_plan`] refuses any plan containing it, with **no override** — even
    /// `--allow-destructive` cannot permit it, because that flag authorizes losing
    /// the dropped table's own data, not silently breaking another table's
    /// referential integrity (PG rejects the bare `DROP TABLE`, and this engine has
    /// no `DropForeignKey` variant to clear the constraint first). Self-referential
    /// FKs and FKs from a table that is itself being dropped do **not** produce
    /// this marker — those constraints go away with their table.
    DropTableBlockedByInboundFk {
        /// The table being dropped.
        table: String,
        /// The retained table whose FK references the dropped table.
        referencing_table: String,
        /// The column on `referencing_table` carrying the blocking FK.
        referencing_column: String,
    },

    /// A same-named column whose logical type changed *and* which participates in
    /// a foreign-key constraint that this engine cannot drop and recreate — either
    /// the column is itself a referencing FK column, or another retained table has
    /// a baseline FK targeting it. A non-emittable marker: [`guard_plan`] refuses
    /// any plan containing it with **no override**, because Postgres rejects
    /// `ALTER COLUMN ... TYPE` on a column bound by an FK constraint, and this
    /// engine has no `DropForeignKey`/re-add path to clear it first. It sits on top
    /// of the [`DiffError::NonImplicitTypeConversion`] guard, catching even the
    /// implicit widenings (`int4`→`int8`, `float4`→`float8`) that guard allows.
    AlterColumnTypeBlockedByFk {
        /// The owning table name.
        table: String,
        /// The column whose type change is blocked by an FK constraint.
        column: String,
    },

    /// A **pre-existing** baseline column (present on both sides) that gained an
    /// explicit `#[references]` where the baseline recorded no foreign key. A
    /// non-emittable marker: [`guard_plan`] refuses any plan containing it (with
    /// **no override**).
    ///
    /// It exists because the slice-2 parser cannot see a generated
    /// `#[belongs_to(...)]` association FK — a `<name>_id: i64` column is parsed as
    /// a plain `Int64` with `references: None`, producing *no* diagnostic. So a
    /// baseline `references: None` on a pre-existing column is **unknown**, not
    /// proof the database has no constraint: the column may already carry an inline
    /// `REFERENCES` constraint named `<table>_<column>_fkey` from the original
    /// association-FK generation. Emitting `AddForeignKey` would
    /// `ADD CONSTRAINT <table>_<column>_fkey` a second time and collide with that
    /// existing constraint — an unappliable migration. A **newly-added** FK column
    /// (an [`SchemaChange::AddColumn`], which renders its `REFERENCES` inline) is
    /// safe and is never flagged; only a pre-existing column gaining an FK is.
    AddForeignKeyToExistingColumn {
        /// The owning table name.
        table: String,
        /// The pre-existing column that gained an explicit foreign key.
        column: String,
    },

    /// A brand-new managed table whose model has one or more fields the parser
    /// could not represent (a generated enum, a bare `pub user: User` association)
    /// and therefore recorded a [`SchemaDiagnostic`](crate::schema::parse::SchemaDiagnostic)
    /// for instead of a column. A non-emittable marker: [`guard_plan`] refuses any
    /// plan containing it (with **no override**).
    ///
    /// It exists because emitting `CREATE TABLE` from the partial parser output
    /// would produce DDL that OMITS the skipped column(s) — the generated model
    /// still queries them, so the app would hit "column does not exist" at runtime
    /// the moment it touches the new table. A table missing a column the app
    /// queries is as broken as unappliable SQL, so the conservative stance refuses
    /// and directs the user to a manual migration rather than emit incomplete DDL.
    /// This fires ONLY for a table being CREATED; an existing table with a skipped
    /// column is handled by the `DropColumn`/`DropIndex` suppressions instead.
    CreateTableBlockedBySkippedField {
        /// The table that cannot be safely created.
        table: String,
        /// The parser-skipped field name(s) that would be missing from the DDL.
        fields: Vec<String>,
    },
}

/// Diff policy knobs.
#[derive(Debug, Clone, Copy, Default)]
pub struct DiffOptions {
    /// Second-tier destructive escape hatch. When `false` (the default), a plan
    /// containing a `DropColumn`/`DropTable` — or an ambiguous rename — is refused
    /// by [`guard_plan`]. When `true`, both are permitted (the rename is treated
    /// as an independent drop+add).
    pub allow_destructive: bool,

    /// Whether the DESIRED side can authoritatively express expression/partial
    /// indexes (an [`Index`] carrying a raw `definition`).
    ///
    /// `false` (the **default**) is the *model diff* case (`schema diff` /
    /// `--write-migration`, and doctor's model-vs-snapshot `compute_drift`): the
    /// desired side is parsed from the model DSL, which can only ever produce a
    /// plain `Index { definition: None, .. }` — it *cannot* express an
    /// expression/partial index. A baseline index carrying a `definition` is
    /// therefore an unmodellable/adopted construct, and [`diff_indexes`] **retains**
    /// it (never `DropIndex`/replace) — exactly like an unmanaged/adopted table.
    /// This retention is independent of `allow_destructive`: the declarative tool
    /// never drops what it cannot express.
    ///
    /// `true` is the *introspection diff* case (doctor's
    /// `database-schema-drift` `compute_db_schema_drift`, and `pull --dry-run`),
    /// where BOTH sides are complete introspections, so a `definition` index IS
    /// authoritative — a dropped/changed expression index is real drift and is
    /// still reported (via [`indexes_equivalent`]).
    pub definitions_authoritative: bool,
}

/// Why a computed plan is refused for emission (policy, not structure).
#[derive(Debug, thiserror::Error)]
pub enum DiffError {
    /// The plan drops a table or column and `--allow-destructive` was not passed.
    #[error(
        "refusing to emit a destructive migration: {summary}. \
         Re-run with --allow-destructive to generate it anyway."
    )]
    Destructive {
        /// A human-readable list of the destructive ops.
        summary: String,
        /// The destructive ops, for programmatic inspection.
        ops: Vec<DestructiveOp>,
    },

    /// A single table both dropped and added column(s) — possibly a rename.
    #[error(
        "ambiguous change on table `{table}`: column(s) [{}] disappeared and [{}] appeared. \
         If this is a rename, use #[renamed_from] (not yet supported — slice 5+); \
         refusing to emit a drop+add. Re-run with --allow-destructive to treat them \
         as independent drop/add.",
        .dropped.join(", "),
        .added.join(", ")
    )]
    PossibleRename {
        /// The table with the ambiguous change.
        table: String,
        /// The dropped column names.
        dropped: Vec<String>,
        /// The added column names.
        added: Vec<String>,
    },

    /// A both-present table's primary key changed (unsupported this slice, no
    /// override).
    #[error("primary-key change on table `{table}` is not supported in this slice")]
    PrimaryKeyChange {
        /// The table whose primary key changed.
        table: String,
    },

    /// An existing explicit foreign key changed its target (unsupported this
    /// slice, no override — see [`SchemaChange::ForeignKeyChange`]).
    #[error(
        "foreign-key retarget on `{table}.{column}` is not supported in this slice: \
         the baseline already has a foreign key on this column, and this engine has no \
         way to drop it before adding the new one without colliding on the \
         `{table}_{column}_fkey` constraint name. Retargeting a foreign key is deferred \
         to a later slice."
    )]
    ForeignKeyChange {
        /// The owning table name.
        table: String,
        /// The column whose FK target changed.
        column: String,
    },

    /// A column's `GENERATED … AS IDENTITY` clause changed between two authoritative
    /// introspections (unsupported this slice, **no override** — see
    /// [`SchemaChange::IdentityChange`]).
    #[error(
        "identity-generation change on `{table}.{column}` is not supported in this slice: \
         changing or dropping a `GENERATED … AS IDENTITY` clause requires an \
         `ADD`/`DROP`/`SET GENERATED` migration this engine does not auto-emit."
    )]
    IdentityChange {
        /// The owning table name.
        table: String,
        /// The column whose identity clause changed.
        column: String,
    },

    /// A table is dropped while another table (a retained baseline table, or a
    /// new/retained desired table) references it (unsupported this slice, **no
    /// override** — `--allow-destructive` does not permit it).
    #[error(
        "cannot drop table `{table}`: `{referencing_table}.{referencing_column}` \
         has a foreign key referencing it. Dropping `{table}` would violate that constraint, \
         and this engine has no way to drop the inbound foreign key first. Drop or retarget \
         `{referencing_table}.{referencing_column}` first. (--allow-destructive does not override \
         this: it authorizes losing this table's data, not breaking another table's integrity.)"
    )]
    DropTableInboundReference {
        /// The table that cannot be dropped.
        table: String,
        /// The table holding the inbound foreign key.
        referencing_table: String,
        /// The column carrying the inbound foreign key.
        referencing_column: String,
    },

    /// A column type change PG cannot cast implicitly (needs a manual `USING`
    /// clause), so a bare `ALTER COLUMN ... TYPE` would be rejected (unsupported
    /// this slice, **no override** — the SQL is unappliable, not merely lossy).
    #[error(
        "non-implicit type conversion on `{table}.{column}` from {from} to {to} requires a manual \
         migration with a USING clause — not supported in this slice"
    )]
    NonImplicitTypeConversion {
        /// The owning table name.
        table: String,
        /// The column name.
        column: String,
        /// The baseline SQL type.
        from: String,
        /// The desired SQL type.
        to: String,
    },

    /// An `ADD COLUMN` of a `NOT NULL` column without a default, to an existing
    /// table (unsupported this slice, **no override** — the SQL is unappliable on
    /// a table that already has rows, not merely lossy). Postgres validates the
    /// `NOT NULL` against existing rows the moment the column is added, so
    /// `ALTER TABLE t ADD COLUMN c <type> NOT NULL` fails on any non-empty table;
    /// the offline diff engine has no backfill value to synthesize. A brand-new
    /// [`SchemaChange::CreateTable`] carrying such a column is fine (the table is
    /// empty) and is **not** refused.
    #[error(
        "cannot add required column `{table}.{column}`: a NOT NULL column without a default \
         fails on a table that already has rows. Add a default (`#[default(...)]`) or make the \
         column nullable (`Option<...>`)."
    )]
    RequiredColumnWithoutDefault {
        /// The table gaining the column.
        table: String,
        /// The required column name.
        column: String,
    },

    /// A `SET NOT NULL` on an existing (previously-nullable) column (unsupported
    /// this slice, **no override** — the SQL is unappliable on a table whose
    /// column already holds NULLs, not merely lossy). Postgres validates the
    /// constraint against every existing row the instant `ALTER COLUMN ... SET
    /// NOT NULL` runs, so it fails on any pre-existing NULL; the offline diff
    /// engine has no backfill value to synthesize. This is the exact sibling of
    /// [`DiffError::RequiredColumnWithoutDefault`] (adding a required column) —
    /// the only appliable form would be a simultaneous default plus a backfill,
    /// which is not expressible offline, so the engine refuses rather than emit
    /// an unappliable migration. The inverse [`SchemaChange::DropNotNull`]
    /// (non-null → nullable) is always safe and is never refused.
    #[error(
        "cannot set `{table}.{column}` NOT NULL: existing NULL rows would fail the constraint. \
         Backfill the column and apply the change manually, or keep it nullable (`Option<...>`)."
    )]
    SetNotNullRequiresBackfill {
        /// The owning table.
        table: String,
        /// The column being made non-null.
        column: String,
    },

    /// A unique-index add whose columns ALL pre-existed on an existing table
    /// (unsupported this slice, **no override** — the SQL is unappliable on a
    /// table whose existing rows may already hold duplicate values, not merely
    /// lossy). Postgres validates uniqueness against every existing row the
    /// instant `CREATE UNIQUE INDEX` runs, so it fails on any pre-existing
    /// duplicate; the offline diff engine cannot dedup the data. This is the
    /// index-level sibling of [`DiffError::SetNotNullRequiresBackfill`]. It fires
    /// only for an [`SchemaChange::AddIndex`] with `unique: true` on a
    /// pre-existing table where **none** of the indexed columns is being added in
    /// the same plan — a unique index on a brand-new [`SchemaChange::CreateTable`]
    /// (empty table) or one touching a newly-added column (whose existing rows are
    /// all NULL, which Postgres treats as distinct) is always safe and is never
    /// refused. A non-unique `AddIndex` is likewise never refused.
    #[error(
        "cannot add unique index `{index}` on `{table}`: existing rows may contain duplicate \
         values that would fail `CREATE UNIQUE INDEX`. Resolve duplicates and apply this \
         manually, or drop the uniqueness requirement."
    )]
    UniqueIndexRequiresDedup {
        /// The owning table.
        table: String,
        /// The unique index being added.
        index: String,
    },

    /// A column type change on a column that participates in a foreign-key
    /// constraint (unsupported this slice, **no override** — the SQL is
    /// unappliable, not merely lossy). Postgres rejects `ALTER COLUMN ... TYPE` on
    /// a column bound by an FK constraint (as either the referencing column or the
    /// referenced key), and this engine has no `DropForeignKey`/re-add path to
    /// clear the constraint first. This applies even to the implicit widenings the
    /// [`DiffError::NonImplicitTypeConversion`] guard would otherwise allow.
    #[error(
        "cannot change the type of `{table}.{column}`: it participates in a foreign-key \
         constraint, which this engine cannot drop and recreate. Change the type via a manual \
         migration that drops and recreates the foreign key."
    )]
    TypeChangeOnForeignKeyColumn {
        /// The owning table name.
        table: String,
        /// The column whose type change is blocked by an FK constraint.
        column: String,
    },

    /// An explicit foreign key was added to a **pre-existing** column whose
    /// baseline recorded no foreign key (unsupported this slice, **no override** —
    /// the SQL may be unappliable, not merely lossy). Because the slice-2 parser
    /// cannot see a generated `#[belongs_to(...)]` association FK (a `<name>_id`
    /// column parses as a plain `Int64` with `references: None` and no diagnostic),
    /// a baseline `references: None` on a pre-existing column is *unknown*, not
    /// proof the database lacks a constraint: the column may already carry an
    /// inline `REFERENCES` named `<table>_<column>_fkey`, so a fresh
    /// `ADD CONSTRAINT` of that same name would collide. A brand-new FK column (an
    /// `ADD COLUMN` with an inline `REFERENCES`) is safe and is never refused.
    #[error(
        "cannot add a foreign key to the pre-existing column `{table}.{column}`: the offline \
         snapshot cannot confirm whether the database already has a constraint for it (e.g. a \
         generated association foreign key), and adding a duplicate `{table}_{column}_fkey` would \
         fail. Add the foreign key via a manual migration, or re-snapshot from an authoritative \
         source."
    )]
    AddForeignKeyToPreexistingColumn {
        /// The owning table name.
        table: String,
        /// The pre-existing column that gained an explicit foreign key.
        column: String,
    },

    /// A generated FK-constraint or index identifier is emitted more than once, or
    /// exceeds Postgres's 63-byte identifier limit, or collides with another
    /// generated name after PG truncates both to 63 bytes (unsupported this slice,
    /// **no override** — the SQL is unappliable, not merely lossy). Postgres
    /// silently truncates any identifier to `NAMEDATALEN - 1` (63) bytes, so an
    /// over-long generated name is both renamed on apply (risking a mismatch with
    /// hand-written SQL) and a duplicate-relation hazard when two names share their
    /// first 63 bytes. A second, distinct hazard: two generated names that are
    /// *exactly* identical (e.g. a `#[unique] foo` field and a separate field named
    /// `foo_unique` both yield `idx_<table>_foo_unique`) — PG accepts the first
    /// `CREATE INDEX`/`ADD CONSTRAINT` and rejects the second as a duplicate
    /// relation. Postgres-only: `SQLite` has no comparable short limit.
    #[error(
        "generated constraint/index name `{name}` is emitted more than once, or exceeds \
         PostgreSQL's 63-byte identifier limit (colliding with another generated name after \
         truncation to 63 bytes); rename the offending field or shorten the table/column names."
    )]
    GeneratedIdentifierTooLong {
        /// The offending generated identifier.
        name: String,
    },

    /// A brand-new managed table whose model has field(s) the schema parser could
    /// not represent (a generated enum, a bare association like `pub user: User`),
    /// so the parser recorded a diagnostic and skipped the column(s) (unsupported
    /// this slice, **no override** — the DDL would be incomplete, not merely lossy).
    /// Emitting `CREATE TABLE` from that partial output would omit the skipped
    /// column(s), but the generated model still queries them, so the app would fail
    /// with "column does not exist" at runtime. A table missing a queried column is
    /// as broken as unappliable SQL, so the engine refuses rather than emit
    /// incomplete DDL. This applies only to a table being CREATED — an existing
    /// table with a skipped column keeps that column via the drop suppressions.
    #[error(
        "cannot generate `CREATE TABLE {table}`: the model has field(s) the schema parser \
         could not represent ({}), so the generated DDL would omit those column(s) and the \
         application would query a missing column at runtime. Write this table's migration \
         manually.",
        .fields.join(", ")
    )]
    CreateTableWithSkippedField {
        /// The table that cannot be safely created.
        table: String,
        /// The parser-skipped field name(s) that would be missing from the DDL.
        fields: Vec<String>,
    },
}

/// A single destructive operation, for [`DiffError::Destructive`] inspection.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DestructiveOp {
    /// `DROP TABLE <name>`.
    Table(String),
    /// `DROP COLUMN <table>.<column>`.
    Column {
        /// The owning table.
        table: String,
        /// The dropped column.
        column: String,
    },
}

/// Why a plan cannot be rendered to SQL on its backend.
#[derive(Debug, thiserror::Error)]
pub enum EmitError {
    /// A change kind that this slice cannot render on `backend` (slice 5 owns the
    /// full `SQLite` `ALTER` path).
    #[error("change kind `{kind}` is not renderable on {backend:?} yet (slice 5 owns full SQLite)")]
    UnsupportedOnBackend {
        /// The unrenderable change kind.
        kind: &'static str,
        /// The backend it could not be rendered on.
        backend: Backend,
    },

    /// Two or more newly-created tables reference each other through inline
    /// foreign keys, so no `CREATE TABLE` order satisfies all of them. Inline
    /// `REFERENCES` cannot express a cycle (it needs a deferred `ALTER TABLE ADD
    /// CONSTRAINT` after all the `CREATE`s, deferred to a later slice), so this
    /// slice refuses rather than emitting a migration that cannot apply.
    #[error(
        "cannot order the new tables for creation: a foreign-key dependency cycle exists among \
         [{}]. Inline-FK cycles are not supported in this slice.",
        .tables.join(", ")
    )]
    CyclicTableDependencies {
        /// The tables participating in the cycle (sorted, for a stable message).
        tables: Vec<String>,
    },

    /// A `SQLite` `ALTER`-family change needs the table-recreate strategy, but the
    /// full table shape required to rebuild it is unavailable (the context-free
    /// [`emit_up_sql`] / [`emit_down_sql`] were used, or the shape is missing from
    /// the [`SchemaContext`]). Use [`emit_up_sql_with_context`] /
    /// [`emit_down_sql_with_context`] with a populated context.
    #[error("cannot rebuild SQLite table `{table}` for change `{kind}`: {reason}")]
    SqliteRebuildUnsupported {
        /// The table that could not be rebuilt.
        table: String,
        /// The kind of rebuild that was attempted.
        kind: &'static str,
        /// Why the rebuild could not be rendered.
        reason: String,
    },
}

// ---------------------------------------------------------------------------
// Structural diff
// ---------------------------------------------------------------------------

/// Pure structural diff: `desired − baseline` → [`MigrationPlan`]. NEVER refuses,
/// NEVER does IO. Applies the module's conservatism suppressions and
/// managed-table scoping.
///
/// `desired` is the whole [`ParsedSchema`] (tables **and** diagnostics) because
/// the diagnostics drive the enum-skipped-column suppression (a column the parser
/// skipped must not be diffed as a drop).
///
/// `opts` is accepted for API stability; refusal is [`guard_plan`]'s job, so the
/// pure diff does not consult it.
#[must_use]
pub fn diff_schema(baseline: &[Table], desired: &ParsedSchema, opts: DiffOptions) -> MigrationPlan {
    let backend = plan_backend(baseline, desired);
    let mut changes = Vec::new();

    let baseline_by_name: BTreeMap<&str, &Table> =
        baseline.iter().map(|t| (t.name.as_str(), t)).collect();
    let desired_by_name: BTreeMap<&str, &Table> = desired
        .tables
        .iter()
        .map(|t| (t.name.as_str(), t))
        .collect();

    // Iterate the union of table names in a stable (sorted) order.
    let mut names: Vec<&str> = baseline_by_name
        .keys()
        .chain(desired_by_name.keys())
        .copied()
        .collect();
    names.sort_unstable();
    names.dedup();

    for name in names {
        match (baseline_by_name.get(name), desired_by_name.get(name)) {
            // Present on both sides — diff only Autumn-managed tables.
            (Some(base), Some(want)) => {
                if want.managed {
                    diff_table(base, want, desired, opts, backend, &mut changes);
                }
            }
            // Desired only — create it if Autumn owns it. But if the parser
            // skipped any of the model's fields (a diagnostic for this table), the
            // parsed `Table` is incomplete: emitting `CREATE TABLE` from it would
            // omit those column(s) while the generated model still queries them, so
            // refuse via a non-emittable marker rather than emit broken DDL.
            (None, Some(want)) => {
                if want.managed {
                    let skipped = skipped_columns(&want.name, desired);
                    if skipped.is_empty() {
                        changes.push(SchemaChange::CreateTable((*want).clone()));
                    } else {
                        changes.push(SchemaChange::CreateTableBlockedBySkippedField {
                            table: want.name.clone(),
                            fields: skipped.into_iter().collect(),
                        });
                    }
                }
            }
            // Baseline only — drop it only if Autumn ever owned it.
            (Some(base), None) => {
                if base.managed {
                    changes.push(SchemaChange::DropTable((*base).clone()));
                }
            }
            (None, None) => unreachable!("name came from one of the two maps"),
        }
    }

    detect_inbound_fk_blocks(baseline, desired, &mut changes);
    detect_fk_type_change_blocks(baseline, desired, &mut changes);

    MigrationPlan { backend, changes }
}

/// Post-pass: for every dropped table, flag any table that still holds a foreign
/// key referencing it. Such a `DROP TABLE` is unappliable (PG rejects it and this
/// engine has no `DropForeignKey`), so a non-emittable
/// [`SchemaChange::DropTableBlockedByInboundFk`] marker is appended for
/// [`guard_plan`] to refuse.
///
/// Two referencer sources are scanned: the **baseline** side (a retained table
/// whose pre-existing FK targets a dropped table) and the **desired** side (a new
/// table, or a retained table with a newly-added FK column, referencing a dropped
/// table — the case the baseline scan cannot see, e.g. drop `users` while adding
/// `posts.author_id #[references(table = "users")]`). A dropped table is absent
/// from `desired`, so a self-referential FK and an FK from a co-dropped table are
/// excluded structurally on the desired side; the baseline scan excludes a
/// referencer that is itself being dropped — either way those constraints go away
/// with their table. The baseline scan additionally excludes a referencing
/// **column** that is itself being dropped in the same plan: `up_ordered` emits
/// every `DropColumn` (which removes the FK constraint) before every `DropTable`,
/// so dropping `posts.user_id` *and* `users` together is valid SQL and must not be
/// over-refused (a common combined cleanup). Markers are deduplicated (a
/// pre-existing FK on a retained table appears on both sides) and, via the
/// `BTreeSet`, deterministically sorted by (dropped, referencing table,
/// referencing column).
fn detect_inbound_fk_blocks(
    baseline: &[Table],
    desired: &ParsedSchema,
    changes: &mut Vec<SchemaChange>,
) {
    let dropped: BTreeSet<&str> = changes
        .iter()
        .filter_map(|c| match c {
            SchemaChange::DropTable(t) => Some(t.name.as_str()),
            _ => None,
        })
        .collect();
    if dropped.is_empty() {
        return;
    }

    // (referencing table, referencing column) pairs being dropped in this plan.
    // Such a column carries its FK constraint away with it — and `up_ordered`
    // emits every `DropColumn` before every `DropTable`, so the constraint is gone
    // before the referenced table is dropped. Excluding these avoids over-refusing
    // a valid combined "drop the FK column and its target table" cleanup.
    let dropped_columns: BTreeSet<(&str, &str)> = changes
        .iter()
        .filter_map(|c| match c {
            SchemaChange::DropColumn { table, column } => {
                Some((table.as_str(), column.name.as_str()))
            }
            _ => None,
        })
        .collect();

    // (dropped table, referencing table, referencing column); BTreeSet dedups the
    // baseline/desired overlap and keeps the emission order deterministic.
    let mut blocks: BTreeSet<(String, String, String)> = BTreeSet::new();

    // Baseline side: a retained table whose baseline FK targets a dropped table.
    for table in baseline {
        // A referencer that is itself being dropped takes its FK with it.
        if dropped.contains(table.name.as_str()) {
            continue;
        }
        for column in &table.columns {
            // A referencing column being dropped in this same plan takes its FK
            // constraint with it (emitted before the DROP TABLE), so it never
            // blocks the drop.
            if dropped_columns.contains(&(table.name.as_str(), column.name.as_str())) {
                continue;
            }
            if let Some(fk) = &column.references
                && dropped.contains(fk.table.as_str())
            {
                blocks.insert((fk.table.clone(), table.name.clone(), column.name.clone()));
            }
        }
    }

    // Desired side: a managed new-or-retained table whose FK targets a dropped
    // table (only managed desired tables emit any SQL). Dropped tables are absent
    // from `desired`, so self-references and co-dropped referencers never appear.
    for table in &desired.tables {
        if !table.managed {
            continue;
        }
        for column in &table.columns {
            if let Some(fk) = &column.references
                && dropped.contains(fk.table.as_str())
            {
                blocks.insert((fk.table.clone(), table.name.clone(), column.name.clone()));
            }
        }
    }

    changes.extend(
        blocks
            .into_iter()
            .map(|(table, referencing_table, referencing_column)| {
                SchemaChange::DropTableBlockedByInboundFk {
                    table,
                    referencing_table,
                    referencing_column,
                }
            }),
    );
}

/// Post-pass: for every `AlterColumnType` change, flag it when the column
/// participates in a foreign-key constraint this engine cannot drop and recreate.
/// Postgres rejects `ALTER COLUMN ... TYPE` on a column bound by an FK — whether
/// the column is the **referencing** column (its own `references` is set) or the
/// **referenced key** (another table's FK targets it) — so the bare
/// `ALTER COLUMN ... TYPE` this engine would emit is unappliable. A non-emittable
/// [`SchemaChange::AlterColumnTypeBlockedByFk`] marker is appended for
/// [`guard_plan`] to refuse (no override). This composes on top of the
/// [`DiffError::NonImplicitTypeConversion`] guard: that guard already refuses
/// non-implicit casts, and this one additionally refuses the implicit widenings
/// (`int4`→`int8`, `float4`→`float8`) it allows, whenever the column is FK-bound.
///
/// The FK scan mirrors [`detect_inbound_fk_blocks`]: baseline retained tables and
/// managed desired tables are both scanned for a referencing column so a
/// pre-existing or newly-declared FK constraint is seen either way. `AlterColumnType`
/// is only produced for a both-present managed table, so the altered column's own
/// table is always retained.
fn detect_fk_type_change_blocks(
    baseline: &[Table],
    desired: &ParsedSchema,
    changes: &mut Vec<SchemaChange>,
) {
    // (table, column) pairs undergoing a type change.
    let type_changes: BTreeSet<(&str, &str)> = changes
        .iter()
        .filter_map(|c| match c {
            SchemaChange::AlterColumnType { table, column, .. } => {
                Some((table.as_str(), column.as_str()))
            }
            _ => None,
        })
        .collect();
    if type_changes.is_empty() {
        return;
    }

    let mut blocks: BTreeSet<(String, String)> = BTreeSet::new();
    for &(table, column) in &type_changes {
        if column_participates_in_fk(table, column, baseline, desired) {
            blocks.insert((table.to_owned(), column.to_owned()));
        }
    }

    changes.extend(
        blocks
            .into_iter()
            .map(|(table, column)| SchemaChange::AlterColumnTypeBlockedByFk { table, column }),
    );
}

/// True when `table.column` participates in a foreign-key constraint — either as
/// the **referencing** column (it carries a `references`, baseline or desired) or
/// as the **referenced key** (some other table's FK targets `table.column`). Both
/// the baseline (existing constraints) and the managed desired tables (declared
/// constraints) are scanned, so a constraint that is present in the database, or
/// that the plan adds, both count. Used only to decide the FK-bound type-change
/// refusal, so it is deliberately conservative.
fn column_participates_in_fk(
    table: &str,
    column: &str,
    baseline: &[Table],
    desired: &ParsedSchema,
) -> bool {
    // Referencing side: the altered column itself carries an FK, in the baseline
    // (the constraint exists in the DB) or the desired managed table.
    let is_referencing = baseline
        .iter()
        .filter(|t| t.name == table)
        .flat_map(|t| &t.columns)
        .chain(
            desired
                .tables
                .iter()
                .filter(|t| t.managed && t.name == table)
                .flat_map(|t| &t.columns),
        )
        .any(|c| c.name == column && c.references.is_some());
    if is_referencing {
        return true;
    }

    // Referenced side: any baseline table, or any managed desired table, whose FK
    // targets `table.column`.
    baseline
        .iter()
        .flat_map(|t| &t.columns)
        .chain(
            desired
                .tables
                .iter()
                .filter(|t| t.managed)
                .flat_map(|t| &t.columns),
        )
        .any(|c| {
            c.references
                .as_ref()
                .is_some_and(|fk| fk.table == table && fk.column == column)
        })
}

/// Diff a table present on both sides (already known Autumn-managed on the
/// desired side), pushing column / index / check changes.
fn diff_table(
    base: &Table,
    want: &Table,
    desired: &ParsedSchema,
    opts: DiffOptions,
    backend: Backend,
    changes: &mut Vec<SchemaChange>,
) {
    // A primary-key change is refused wholesale (guarded); emit only the marker
    // and skip the rest of this table's diff. A change to the id-generation
    // strategy of the single-column PK (a plain `BIGINT PRIMARY KEY` becoming a
    // `BIGSERIAL`, or vice versa — surfaced by the [`SerialKind`] marker) is
    // likewise a primary-key change: converting one into the other requires
    // creating/dropping an owned sequence, which is deliberately out of scope for
    // an auto-generated migration, so it is refused through the same marker.
    if base.primary_key != want.primary_key || serial_kinds_conflict(base, want) {
        changes.push(SchemaChange::PrimaryKeyChange {
            table: want.name.clone(),
        });
        return;
    }

    let base_cols: BTreeMap<&str, &Column> =
        base.columns.iter().map(|c| (c.name.as_str(), c)).collect();
    let want_col_names: std::collections::BTreeSet<&str> =
        want.columns.iter().map(|c| c.name.as_str()).collect();

    // Columns the parser skipped for this table (rule D/E): a baseline column
    // whose name is skipped is "present but unmodelled" and must not be dropped.
    let skipped = skipped_columns(&want.name, desired);

    // Adds and same-name alters, in desired declared order.
    for want_col in &want.columns {
        match base_cols.get(want_col.name.as_str()) {
            None => changes.push(SchemaChange::AddColumn {
                table: want.name.clone(),
                column: want_col.clone(),
            }),
            Some(base_col) => diff_column(&want.name, base_col, want_col, opts, backend, changes),
        }
    }

    // Drops, in baseline declared order — suppressing parser-skipped columns.
    for base_col in &base.columns {
        if !want_col_names.contains(base_col.name.as_str())
            && !skipped.contains(base_col.name.as_str())
        {
            changes.push(SchemaChange::DropColumn {
                table: want.name.clone(),
                column: base_col.clone(),
            });
        }
    }

    diff_indexes(&want.name, base, want, &skipped, opts, backend, changes);
    diff_checks(&want.name, base, want, changes);
}

/// Diff a single same-named column (keyed on name, never position).
/// Whether two column types are equivalent for drift purposes on `backend`.
///
/// On **Postgres** this is exact [`ColumnType`] equality — `INTEGER` vs `BIGINT`
/// (int4 vs int8) is a genuine, distinct type change that must still diff.
///
/// On **`SQLite`** the emitter renders several distinct IR types to the same
/// declared type (`Int32`/`Int64`/`Bool` → `INTEGER`, `Float32`/`Float64` →
/// `REAL`, `Text`/`Uuid`/`Timestamp`/`TimestampTz`/`Decimal`/`Attachment`/`Enum` →
/// `TEXT`, `Bytes` → `BLOB`), and a pull cannot recover the original variant — so
/// comparing by exact `ColumnType` would report a spurious type change (and a
/// table-recreate) for every `bool`/`i32`/`f32`/plain-`Timestamp` column on every
/// pull. Instead they are compared by [`SqliteAffinity`] class, so a matching
/// model↔pull round-trips CLEAN while a genuine class change (e.g. `INTEGER`→`TEXT`)
/// still drifts. An [`Opaque`](ColumnType::Opaque) type (a verbatim, pull-only type
/// with no clean class) or the ambiguous [`Numeric`](SqliteAffinity::Numeric)
/// catch-all falls back to exact equality so distinct verbatim types are never
/// conflated. This rule is strictly `SQLite`-gated and never affects the pg lane.
fn column_types_equivalent(base: &ColumnType, want: &ColumnType, backend: Backend) -> bool {
    if base == want {
        return true;
    }
    if backend != Backend::Sqlite {
        return false;
    }
    // An Opaque (verbatim, pull-only) type must match exactly — never conflate two
    // distinct raw types by affinity.
    if matches!(base, ColumnType::Opaque { .. }) || matches!(want, ColumnType::Opaque { .. }) {
        return false;
    }
    let base_class = base.sqlite_affinity();
    // Only the four unambiguous storage classes collapse; the NUMERIC catch-all
    // requires exact equality (already failed the `base == want` check above).
    base_class == want.sqlite_affinity() && base_class != SqliteAffinity::Numeric
}

fn diff_column(
    table: &str,
    base: &Column,
    want: &Column,
    opts: DiffOptions,
    backend: Backend,
    changes: &mut Vec<SchemaChange>,
) {
    if !column_types_equivalent(&base.ty, &want.ty, backend) {
        changes.push(SchemaChange::AlterColumnType {
            table: table.to_owned(),
            column: want.name.clone(),
            from: base.ty.clone(),
            to: want.ty.clone(),
        });
    }

    match (base.nullable, want.nullable) {
        (true, false) => changes.push(SchemaChange::SetNotNull {
            table: table.to_owned(),
            column: want.name.clone(),
        }),
        (false, true) => changes.push(SchemaChange::DropNotNull {
            table: table.to_owned(),
            column: want.name.clone(),
        }),
        _ => {}
    }

    // Rule C: only emit when the desired side has a default that differs. A
    // desired `None` is "unknown, retained" — never a DropDefault.
    if let Some(to) = &want.default
        && base.default.as_ref() != Some(to)
    {
        changes.push(SchemaChange::SetDefault {
            table: table.to_owned(),
            column: want.name.clone(),
            to: to.clone(),
            from: base.default.clone(),
        });
    }

    // Rule B: only the *add* direction is ever considered (a desired `None` is
    // "unknown, retained" — never a DropForeignKey). `diff_column` only runs for a
    // column present on BOTH sides — i.e. a pre-existing column — so an added FK
    // here is on a pre-existing column, which is unsafe: the parser cannot see a
    // generated `#[belongs_to(...)]` association FK, so a baseline `references:
    // None` is *unknown*, not proof the DB has no `<table>_<column>_fkey`
    // constraint — emitting `ADD CONSTRAINT` could collide with an existing one.
    //
    // The three sub-cases when the desired side has an explicit FK on a
    // pre-existing column:
    //   * baseline had none            → the FK may (invisibly) already exist →
    //     the refused `AddForeignKeyToExistingColumn` marker (no override).
    //   * baseline had the same FK     → no change.
    //   * baseline had a *different* FK → a retarget we cannot safely emit
    //     (there is no `DropForeignKey`, and re-`ADD CONSTRAINT`-ing the default
    //     `<table>_<column>_fkey` name would collide) → the refused
    //     `ForeignKeyChange` marker, mirroring `PrimaryKeyChange`.
    //
    // A genuinely-new FK column arrives as an `AddColumn` (whose `REFERENCES` is
    // rendered inline, never as a separate `AddForeignKey`), so it never reaches
    // this branch and is emitted normally.
    if let Some(fk) = &want.references {
        match &base.references {
            None => changes.push(SchemaChange::AddForeignKeyToExistingColumn {
                table: table.to_owned(),
                column: want.name.clone(),
            }),
            Some(existing) if existing == fk => {}
            Some(_) => changes.push(SchemaChange::ForeignKeyChange {
                table: table.to_owned(),
                column: want.name.clone(),
            }),
        }
    }

    // Identity clause: an id-generation change (`GENERATED ALWAYS AS IDENTITY` →
    // plain, or `ALWAYS` ↔ `BY DEFAULT`) is compared ONLY in an authoritative diff
    // (both sides introspected — doctor's `database-schema-drift` and
    // `pull --dry-run`). The model parser cannot express an identity clause, so in a
    // model diff a desired `identity: None` is "unknown, retained" (never drift),
    // exactly like a baseline `definition` index the DSL cannot describe — comparing
    // it there would spuriously refuse every model against an identity-column DB.
    // In an authoritative diff both sides carry the clause faithfully, so a genuine
    // change surfaces as the refused `IdentityChange` marker instead of being
    // silently dropped.
    if opts.definitions_authoritative && base.identity != want.identity {
        changes.push(SchemaChange::IdentityChange {
            table: table.to_owned(),
            column: want.name.clone(),
        });
    }
    // NOTE: `Column.unique` is deliberately NOT diffed. On Postgres a single-column
    // unique is ALSO recorded as an `Index`, so a uniqueness change surfaces through
    // `diff_indexes` (comparing the flag too would double-report). On SQLite a
    // brownfield inline `col TEXT UNIQUE` is not modeled at all (#1975 deferral — see
    // `introspect::sqlite::collapse_indexes`), so there is no flag to diff.
}

/// Diff a table's indexes by name. A same-named index whose shape changed is a
/// drop-then-add (neither is destructive — an index drops no rows).
///
/// A `DropIndex` is **suppressed** when the baseline index references ANY column in
/// `skipped` (a parser-skipped column, per [`skipped_columns`]): the parser never
/// saw the column, so it never saw the column's indexes either — their absence from
/// the desired side is a parser gap, not proof the index was removed. Dropping such
/// an index would silently lose a constraint (e.g. a UNIQUE index → duplicate data
/// becomes possible) the same way an unsuppressed `DropColumn` would lose the
/// column. This mirrors the `DropColumn` suppression in [`diff_table`]. A composite
/// index touching even one skipped column is suppressed whole, since the parser
/// cannot authoritatively say it was removed.
/// Whether two same-named indexes are equivalent for drift purposes. When either
/// carries a raw `definition` (an expression/partial index preserved verbatim by
/// introspection), they are compared by that canonical `pg_get_indexdef` text and
/// `unique` — the `columns` list is only a partial, display-oriented view of such
/// an index. Otherwise (ordinary column indexes) they compare by `columns` +
/// `unique`, identical to the pre-`definition` behavior.
fn indexes_equivalent(a: &Index, b: &Index) -> bool {
    if a.definition.is_some() || b.definition.is_some() {
        a.definition == b.definition && a.unique == b.unique
    } else {
        a.columns == b.columns && a.unique == b.unique
    }
}

/// Whether `index` depends on column `col` — i.e. dropping `col` via
/// `ALTER TABLE … DROP COLUMN` would leave the index referencing a missing column
/// (so the index must be dropped/pruned first).
///
/// **Postgres**: dependency is EXACT `columns` membership. For a retained
/// (`definition`-carrying) expression/partial/constraint-owned index `columns` is
/// the **exact `pg_depend` dependent-column set** captured by introspection (key,
/// expression-referenced, AND predicate columns — the same set Postgres cascades on
/// a `DROP COLUMN`), so a text scan is unnecessary and deliberately avoided (it would
/// false-positive on a column name that merely appears in a string literal, e.g. a
/// partial index `WHERE kind = 'email'` while dropping an unrelated `email` column).
///
/// **`SQLite`**: a retained partial/expression index records only its KEY columns in
/// `columns` (its WHERE-predicate / key-expression columns are NOT captured there —
/// `SQLite`'s catalog exposes no `pg_depend` equivalent), so exact `columns`
/// membership misses a predicate/expression column. To avoid emitting an
/// invalid `DROP COLUMN` that orphans such an index, the verbatim `definition` is
/// **word-bounded token-scanned** for `col`: any occurrence counts as a dependency,
/// so the index is pruned before the column drop. This is the conservative
/// over-include-is-safe direction (a false positive from a string literal at worst
/// prunes an index that a rebuild would recreate anyway — never invalid SQL).
///
/// Both `project_plan_target` (snapshot projection) and [`emit_down_sql_pg`] use this
/// single test so they cannot drift.
pub fn index_depends_on_column(index: &Index, col: &str, backend: Backend) -> bool {
    if index.columns.iter().any(|c| c == col) {
        return true;
    }
    if backend == Backend::Sqlite
        && let Some(def) = &index.definition
    {
        return definition_references_column(def, col);
    }
    false
}

/// Whether the verbatim index `definition` references the identifier `col` as a
/// **word-bounded** token (case-insensitive; word chars are `[A-Za-z0-9_]`), so a
/// quoted `"col"`, a bare `col`, or `col` inside an expression/predicate matches, but
/// a longer identifier that merely contains it (`col_backup`, `old_col`) does not.
fn definition_references_column(definition: &str, col: &str) -> bool {
    if col.is_empty() {
        return false;
    }
    let hay = definition.to_ascii_lowercase();
    let needle = col.to_ascii_lowercase();
    let hb = hay.as_bytes();
    let is_word = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
    let mut from = 0;
    while let Some(rel) = hay[from..].find(&needle) {
        let start = from + rel;
        let end = start + needle.len();
        let before_ok = start == 0 || !is_word(hb[start - 1]);
        let after_ok = end == hb.len() || !is_word(hb[end]);
        if before_ok && after_ok {
            return true;
        }
        from = start + 1;
    }
    false
}

///
/// ## Unmodellable (expression/partial) indexes
///
/// An [`Index`] carrying a raw `definition` (an expression or partial index,
/// preserved verbatim by `schema pull` introspection) **cannot be produced by the
/// model parser** — `#[indexed]`/`#[unique]` only ever yield
/// `Index { definition: None, .. }`. So in a *model diff*
/// (`opts.definitions_authoritative == false`) a baseline `definition` index is an
/// adopted construct the desired side is simply unable to describe, and it is
/// **retained** — never `DropIndex`'d or replaced — exactly like an
/// unmanaged/adopted table. This retention is independent of `allow_destructive`:
/// the declarative tool never drops what it cannot express. In an *introspection
/// diff* (`opts.definitions_authoritative == true`, from
/// [`compute_db_schema_drift`](super::doctor::compute_db_schema_drift) and
/// `pull --dry-run`) BOTH sides are complete introspections, so a `definition`
/// index IS authoritative and a dropped/changed one is reported as real drift via
/// [`indexes_equivalent`]. Plain (`definition: None`) indexes are diffed
/// identically in both modes — a model may always ADD a brand-new plain index.
///
/// ## Model `#[unique]` satisfied by an existing unique index (brownfield adoption)
///
/// In a *model diff* only, a desired UNIQUE index whose name is absent from the
/// baseline is nonetheless treated as **already satisfied** when the baseline
/// carries some `unique` index (under ANY name — including a `definition`-carrying
/// constraint index a brownfield `UNIQUE` produced, e.g. `accounts_email_key`)
/// over the **exact same column set** ([`baseline_unique_index_covers`]). This is
/// the brownfield-adoption case: the user pulls `email TEXT UNIQUE`, then writes
/// the natural model `Account { id, email }` with `#[unique]` on `email`. The
/// parser emits `idx_accounts_email_unique` (a differently-named unique index over
/// `{email}`); without this recognition `diff_indexes` would emit a redundant
/// `AddIndex`, which `guard_plan`'s dedup refusal would then reject on a populated
/// table — leaving the user unable to keep the annotation. Instead the desired
/// unique index is suppressed (no `AddIndex`, and no `DropIndex` for the retained
/// baseline index), so the model resolves to a clean, empty diff. Uniqueness must
/// match: a desired unique index over `{email}` is NOT satisfied by a baseline
/// *non-unique* index over `{email}` (it still emits `AddIndex`). Authoritative
/// diffs are unaffected — a brownfield constraint index shares its name on both
/// introspected sides and already matches by name, so real drift stays intact.
/// Whether the baseline table already carries a `unique` index whose covered
/// column set is **exactly** `want_columns` (order-insensitive) — used only in the
/// model-diff path to recognize that a desired `#[unique]` index is already
/// enforced by a differently-named brownfield constraint/unique index.
///
/// ## Why exact **key**-set-equality on a FULL, NON-PARTIAL index
///
/// Only a baseline unique index that actually enforces table-wide uniqueness of the
/// desired columns may suppress the `AddIndex`. Two catalog shapes look like they
/// cover the set but do **not**, and are deliberately rejected:
///
/// - A **partial** unique index (`… ON t(email) WHERE …`) enforces uniqueness only
///   for rows matching its predicate — duplicates can exist outside it — so it does
///   NOT guarantee the model's table-wide `#[unique] email`. Rejected via
///   [`Index::is_partial`].
/// - An **expression** unique index (`UNIQUE (lower(email))`) enforces uniqueness of
///   the *expression*, not the column, so it does NOT guarantee `#[unique] email`
///   either. Introspection records an expression index with an EMPTY
///   [`Index::key_columns`], which is rejected.
///
/// The comparison is therefore against the index's real **key** columns
/// ([`Index::key_columns`]), which excludes a covering index's non-key `INCLUDE`
/// columns — so `UNIQUE(a) INCLUDE(b)` (key `{a}`) satisfies `#[unique] a` but not
/// `#[unique] {a, b}`. For a plain simple index introspection leaves `key_columns`
/// empty (its key columns are exactly [`Index::columns`]); such a `definition`-less
/// index falls back to comparing `columns`. A `definition`-carrying index with an
/// empty `key_columns` is an expression index (or an older snapshot we cannot vouch
/// for) and never satisfies — the conservative direction (emit the `AddIndex`), not
/// a wrongful suppression.
fn baseline_unique_index_covers(base: &Table, want_columns: &[String]) -> bool {
    let want_set: BTreeSet<&str> = want_columns.iter().map(String::as_str).collect();
    // A single-column baseline `column.unique = true` fully enforces uniqueness of
    // that column. This covers the SQLite brownfield inline-`col TEXT UNIQUE` case:
    // its constraint auto-index (`sqlite_autoindex_*`) is deliberately folded into the
    // column flag (not recorded as an `Index` — its name is un-creatable/un-droppable,
    // see `introspect::sqlite::collapse_indexes`), so the flag is the signal that the
    // model's `#[unique]` is already satisfied (no redundant `AddIndex` that
    // `guard_plan` would refuse on a populated table). On Postgres the constraint ALSO
    // produces a retained unique index, so this clause is redundant-but-correct there.
    if want_columns.len() == 1
        && base
            .columns
            .iter()
            .any(|c| c.unique && c.name == want_columns[0])
    {
        return true;
    }
    base.indexes.iter().any(|idx| {
        if !idx.unique || idx.is_partial {
            return false;
        }
        // Effective KEY columns: an explicit `key_columns` (recorded for every
        // `definition`-carrying index; empty ⇒ expression key ⇒ reject) wins;
        // otherwise, for a plain `definition`-less index, its `columns` ARE its key
        // columns. A `definition`-carrying index with no recorded key columns cannot
        // be vouched for and is rejected.
        let key: BTreeSet<&str> = if !idx.key_columns.is_empty() {
            idx.key_columns.iter().map(String::as_str).collect()
        } else if idx.definition.is_none() {
            idx.columns.iter().map(String::as_str).collect()
        } else {
            return false;
        };
        key == want_set
    })
}

/// The single suppression predicate shared by **both** [`diff_indexes`] branches
/// (the same-name match and the desired-only `AddIndex`), so they can never
/// drift: a desired UNIQUE index is already satisfied — and may be suppressed —
/// only when SOME baseline index provides **full** coverage, i.e. a non-partial,
/// non-expression unique index over exactly its key columns (see
/// [`baseline_unique_index_covers`]). A non-unique desired index is never
/// suppressed by this rule, and a merely same-named baseline index that is
/// partial, an expression index (empty key columns), or keyed on a different
/// column set does **not** count as coverage.
fn baseline_satisfies_desired_unique(base: &Table, want_idx: &Index) -> bool {
    want_idx.unique && baseline_unique_index_covers(base, &want_idx.columns)
}

/// The full (non-partial) unique KEY column set of `idx`, or `None` when `idx` is not
/// a vouchable full-unique index (non-unique, partial, or an expression key with no
/// recorded key columns). Mirrors the key resolution in
/// [`baseline_unique_index_covers`].
fn full_unique_key_columns(idx: &Index) -> Option<BTreeSet<&str>> {
    if !idx.unique || idx.is_partial {
        return None;
    }
    if !idx.key_columns.is_empty() {
        Some(idx.key_columns.iter().map(String::as_str).collect())
    } else if idx.definition.is_none() {
        Some(idx.columns.iter().map(String::as_str).collect())
    } else {
        None
    }
}

/// Whether a baseline-only index `base_idx` (in a MODEL diff) is the covering index
/// for a desired `#[unique]` requirement whose own `AddIndex` was suppressed as
/// already-satisfied — i.e. the SAME uniqueness enforced under a DIFFERENT name (a
/// pulled `accounts_email_uq` vs the model's `idx_accounts_email_unique`). Such an
/// index must be RETAINED: dropping it would remove the only enforcement while the
/// model's matching `AddIndex` stays suppressed. The symmetric counterpart to
/// [`baseline_satisfies_desired_unique`] (which suppresses the add side).
fn base_index_covers_suppressed_model_unique(base: &Table, base_idx: &Index, want: &Table) -> bool {
    let Some(base_key) = full_unique_key_columns(base_idx) else {
        return false;
    };
    want.indexes.iter().any(|w| {
        // A same-named desired index is matched by name (not suppressed by coverage),
        // so only a DIFFERENTLY-named desired unique over the same key set counts.
        w.unique
            && !base.indexes.iter().any(|b| b.name == w.name)
            && full_unique_key_columns(w).is_some_and(|wk| wk == base_key)
    })
}

fn diff_indexes(
    table: &str,
    base: &Table,
    want: &Table,
    skipped: &BTreeSet<String>,
    opts: DiffOptions,
    backend: Backend,
    changes: &mut Vec<SchemaChange>,
) {
    let base_by_name: BTreeMap<&str, &Index> =
        base.indexes.iter().map(|i| (i.name.as_str(), i)).collect();
    let want_by_name: BTreeMap<&str, &Index> =
        want.indexes.iter().map(|i| (i.name.as_str(), i)).collect();
    // Columns that this diff DROPS (present in the baseline, absent from the desired
    // side, and not a parser-skipped column). An index — even a retained one — that
    // depends on such a column CANNOT survive the drop (SQLite rejects DROP COLUMN on
    // a referenced column), so it must be dropped BEFORE the column (`DropIndex` is
    // ordered ahead of `DropColumn`).
    let want_col_names: BTreeSet<&str> = want.columns.iter().map(|c| c.name.as_str()).collect();
    let dropped_columns: Vec<&str> = base
        .columns
        .iter()
        .map(|c| c.name.as_str())
        .filter(|n| !want_col_names.contains(n) && !skipped.contains(*n))
        .collect();

    for want_idx in &want.indexes {
        match base_by_name.get(want_idx.name.as_str()) {
            None => {
                // In a MODEL diff (`!definitions_authoritative`), a desired UNIQUE
                // index whose column SET is already enforced by an existing baseline
                // unique index — under ANY name, including a `definition`-carrying
                // constraint index a brownfield `UNIQUE` produced (`accounts_email_key`)
                // — is already satisfied. The differently-named baseline index enforces
                // the exact uniqueness the model's `#[unique]` asks for, so emitting an
                // `AddIndex` here would be redundant AND would trip `guard_plan`'s
                // unique-index-on-populated-table dedup refusal, blocking the user from
                // ever keeping the annotation. Suppress it (and leave the retained
                // baseline index in place — no `DropIndex`). Matching is by EXACT column
                // set (see [`baseline_unique_index_covers`]). Authoritative diffs are
                // untouched: a brownfield constraint index has the same name on both
                // sides there and already matches by name, so real drift stays detected.
                if !opts.definitions_authoritative
                    && baseline_satisfies_desired_unique(base, want_idx)
                {
                    continue;
                }
                changes.push(SchemaChange::AddIndex {
                    table: table.to_owned(),
                    index: want_idx.clone(),
                });
            }
            Some(base_idx) => {
                // A same-named pair where EITHER carries a `definition`: in a model
                // diff the desired side cannot express the definition, so retain
                // the baseline index (emit nothing) rather than emit a destructive
                // DropIndex + plain replacement. In an introspection diff both
                // sides are authoritative, so fall through to the equivalence check.
                let involves_definition =
                    base_idx.definition.is_some() || want_idx.definition.is_some();
                if involves_definition && !opts.definitions_authoritative {
                    // Model diff: the desired side cannot express B's
                    // definition, so the same-named definition-carrying baseline
                    // index B is retained (the drop loop below skips a name still
                    // present in `want`). But a unique D whose uniqueness B does
                    // NOT fully cover — B is partial, an expression index (empty
                    // key columns), or keyed on a different column set — leaves
                    // the model's table-wide `#[unique]` UNENFORCED even though a
                    // conventionally-named index exists. Emit `AddIndex(D)` so the
                    // full unique index is created ALONGSIDE the retained B;
                    // suppress D only when SOME baseline index fully covers it
                    // (or D is non-unique).
                    if want_idx.unique && !baseline_satisfies_desired_unique(base, want_idx) {
                        changes.push(SchemaChange::AddIndex {
                            table: table.to_owned(),
                            index: want_idx.clone(),
                        });
                    }
                    continue;
                }
                if !indexes_equivalent(base_idx, want_idx) {
                    changes.push(SchemaChange::DropIndex {
                        table: table.to_owned(),
                        index: (*base_idx).clone(),
                    });
                    changes.push(SchemaChange::AddIndex {
                        table: table.to_owned(),
                        index: want_idx.clone(),
                    });
                }
            }
        }
    }

    for base_idx in &base.indexes {
        if want_by_name.contains_key(base_idx.name.as_str())
            || base_idx.columns.iter().any(|c| skipped.contains(c))
        {
            continue;
        }
        // SQLite ONLY: an index that depends on a column being DROPPED must be
        // dropped first — even a retained (`definition`) one the model cannot express
        // — else it would reference a missing column (SQLite rejects the
        // `DROP COLUMN`). This OVERRIDES the retention rule below; its down leg
        // recreates the index verbatim (after the column is re-added), so the
        // rollback is faithful. Postgres is EXCLUDED: it cascade-drops the dependent
        // index automatically on `DROP COLUMN` and restores it on rollback via
        // `retained_indexes_depending_on_any`, so an explicit `DropIndex` there would
        // double-drop and break that mechanism.
        let orphaned_by_column_drop = backend == Backend::Sqlite
            && dropped_columns
                .iter()
                .any(|c| index_depends_on_column(base_idx, c, backend));
        // Retain (never DropIndex) — in a MODEL diff, and only when the index is not
        // being orphaned by a SQLite column drop — when EITHER:
        //   (a) it carries a `definition` the model DSL cannot express (an
        //       expression/partial/constraint-owned index), OR
        //   (b) it is a plain unique index that COVERS a model `#[unique]` whose own
        //       `AddIndex` was suppressed as already-satisfied (the SAME uniqueness
        //       under a different name — e.g. a pulled `accounts_email_uq` vs the
        //       model's `idx_accounts_email_unique`). Dropping it would remove the
        //       ONLY uniqueness enforcement with no replacement — a silent
        //       data-integrity loss. This is the symmetric counterpart to the add
        //       branch's `baseline_satisfies_desired_unique` suppression.
        // In an introspection diff both sides are authoritative (indexes match by
        // name), so neither retention applies and a genuinely-dropped index drops.
        let retain = !opts.definitions_authoritative
            && !orphaned_by_column_drop
            && (base_idx.definition.is_some()
                || base_index_covers_suppressed_model_unique(base, base_idx, want));
        if retain {
            continue;
        }
        changes.push(SchemaChange::DropIndex {
            table: table.to_owned(),
            index: base_idx.clone(),
        });
    }
}

/// Diff a table's checks — **add only** (rule A: a baseline-only check is never
/// dropped, because the parser cannot fabricate enum checks and so cannot prove
/// the check was removed).
fn diff_checks(table: &str, base: &Table, want: &Table, changes: &mut Vec<SchemaChange>) {
    for want_check in &want.checks {
        if !base.checks.iter().any(|c| c == want_check) {
            changes.push(SchemaChange::AddCheck {
                table: table.to_owned(),
                check: want_check.clone(),
            });
        }
    }
}

/// The set of column names the parser skipped for `table` (rule E): a
/// [`SchemaDiagnostic`](crate::schema::parse::SchemaDiagnostic) whose resolved
/// table name equals `table` contributes its field name. Such a baseline column
/// is "present but unmodelled" and must not be diffed as a drop.
///
/// The match is on the diagnostic's resolved `table` (the `#[model(table =
/// "...")]` override or the convention name), recorded at parse time — never a
/// re-derivation of the convention name from `model`, which would miss a custom
/// table name and let a real baseline column be diffed as a data-losing drop.
fn skipped_columns(table: &str, desired: &ParsedSchema) -> std::collections::BTreeSet<String> {
    desired
        .diagnostics
        .iter()
        .filter(|d| d.table == table)
        .map(|d| d.field.clone())
        .collect()
}

/// Infer the plan's backend from the (provider-locked) tables. The caller
/// guarantees both sides share a backend via `ensure_backend_matches`; defaulting
/// to Postgres only matters for the (backendless) empty-vs-empty case.
fn plan_backend(baseline: &[Table], desired: &ParsedSchema) -> Backend {
    desired
        .tables
        .first()
        .or_else(|| baseline.first())
        .map_or(Backend::Postgres, |t| t.backend)
}

// ---------------------------------------------------------------------------
// Policy guard
// ---------------------------------------------------------------------------

/// Policy guard, run AFTER [`diff_schema`] by the command. Refuses a plan that is
/// structurally computable but unsafe to emit unless permitted.
///
/// Guard order (most specific / most dangerous first, so the user sees the most
/// actionable message): **`PrimaryKeyChange` → `ForeignKeyChange` →
/// `PossibleRename` → `Destructive`**. `--allow-destructive` overrides the rename
/// and destructive tiers; a primary-key change and a foreign-key retarget have no
/// override.
///
/// # Errors
///
/// Returns a [`DiffError`] describing the first refusal; `Ok(())` for an
/// emittable plan (including the empty no-op plan).
pub fn guard_plan(plan: &MigrationPlan, opts: DiffOptions) -> Result<(), DiffError> {
    // 1. Primary-key change — no override.
    if let Some(table) = plan.changes.iter().find_map(|c| match c {
        SchemaChange::PrimaryKeyChange { table } => Some(table.clone()),
        _ => None,
    }) {
        return Err(DiffError::PrimaryKeyChange { table });
    }

    // 2. Foreign-key retarget — no override (there is no safe drop+recreate).
    if let Some((table, column)) = plan.changes.iter().find_map(|c| match c {
        SchemaChange::ForeignKeyChange { table, column } => Some((table.clone(), column.clone())),
        _ => None,
    }) {
        return Err(DiffError::ForeignKeyChange { table, column });
    }

    // 2a. Identity-generation change — no override (needs ADD/DROP/SET GENERATED,
    //     out of scope this slice). Only produced by an authoritative diff.
    if let Some(err) = find_identity_change_block(plan) {
        return Err(err);
    }

    // 2b. Foreign key added to a pre-existing column — no override. A baseline
    //     `references: None` is *unknown* (the parser cannot see an association
    //     FK), so the DB may already carry the `<table>_<column>_fkey` constraint;
    //     emitting `ADD CONSTRAINT` would collide. A new FK column (an `AddColumn`
    //     with an inline `REFERENCES`) is safe and never reaches this marker.
    if let Some((table, column)) = plan.changes.iter().find_map(|c| match c {
        SchemaChange::AddForeignKeyToExistingColumn { table, column } => {
            Some((table.clone(), column.clone()))
        }
        _ => None,
    }) {
        return Err(DiffError::AddForeignKeyToPreexistingColumn { table, column });
    }

    // 2c. Create of a table whose model has parser-skipped field(s) — no override.
    //     The parsed table omits the skipped column(s), so emitting `CREATE TABLE`
    //     from it would produce DDL missing a column the generated model queries →
    //     runtime "column does not exist". Incomplete DDL is as broken as
    //     unappliable SQL, so it refuses and directs to a manual migration. Only a
    //     table being CREATED carries this marker (an existing table's skipped
    //     column is retained by the drop suppressions, not this refusal).
    if let Some((table, fields)) = plan.changes.iter().find_map(|c| match c {
        SchemaChange::CreateTableBlockedBySkippedField { table, fields } => {
            Some((table.clone(), fields.clone()))
        }
        _ => None,
    }) {
        return Err(DiffError::CreateTableWithSkippedField { table, fields });
    }

    // 3. Drop of a table a retained table still references — no override (even
    //    --allow-destructive cannot break another table's integrity).
    if let Some(err) = find_inbound_fk_block(plan) {
        return Err(err);
    }

    // 4. Non-implicit column type conversion (pg) — no override; the bare
    //    `ALTER COLUMN ... TYPE` is unappliable without a `USING` clause.
    if let Some(err) = find_non_implicit_conversion(plan) {
        return Err(err);
    }

    // 4b. Column type change on an FK-bound column — no override. PG rejects
    //     `ALTER COLUMN ... TYPE` on a column bound by a foreign key (as either the
    //     referencing column or the referenced key), and this engine has no
    //     drop+recreate path for the constraint. Composes on top of guard 4: it
    //     catches even the implicit widenings that guard allows.
    if let Some(err) = find_fk_type_change_block(plan) {
        return Err(err);
    }

    // 4c. Generated identifier over Postgres's 63-byte limit (or a post-truncation
    //     collision) — no override. PG silently truncates identifiers to 63 bytes,
    //     so an over-long FK-constraint / index name is renamed on apply and can
    //     collide with a sibling generated name (duplicate-relation error). Unappliable
    //     SQL, not merely lossy, so it always refuses. Postgres-only (SQLite does not
    //     truncate). See the module docs' 63-byte-limit section.
    if let Some(err) = find_identifier_limit_violation(plan) {
        return Err(err);
    }

    // 5. Possible rename — a single table that both dropped and added columns.
    //    Overridable, so it is only enforced when destructive changes are not
    //    allowed. Deliberately checked *before* the required-column guard below so
    //    a rename-shaped drop+add reports the more-actionable `#[renamed_from]`
    //    guidance rather than "add a default".
    if !opts.allow_destructive
        && let Some(err) = find_possible_rename(plan)
    {
        return Err(err);
    }

    // 6. Add of a required column (NOT NULL, no default) to an existing table —
    //    no override. Postgres validates the NOT NULL against existing rows the
    //    instant the column is added, so `ADD COLUMN ... NOT NULL` fails on any
    //    non-empty table; the offline engine has no backfill value to synthesize,
    //    so it refuses rather than emit an unappliable migration. This matches
    //    only `AddColumn` (altering an existing baseline table) — a NOT NULL,
    //    no-default column inlined in a brand-new `CreateTable` is empty-table-safe
    //    and is never matched here. It is not destructive, so it always refuses,
    //    regardless of `--allow-destructive` (checked in both branches: the
    //    `allow_destructive` short-circuit below is only reached after this guard).
    if let Some((table, column)) = plan.changes.iter().find_map(|c| match c {
        SchemaChange::AddColumn { table, column }
            if !column.nullable && column.default.is_none() =>
        {
            Some((table.clone(), column.name.clone()))
        }
        _ => None,
    }) {
        return Err(DiffError::RequiredColumnWithoutDefault { table, column });
    }

    // 6b. `SET NOT NULL` on an existing nullable column — no override. Postgres
    //     validates the constraint against every existing row the instant the
    //     ALTER runs, so it fails on any pre-existing NULL; the offline engine
    //     has no backfill value to synthesize. The exact sibling of the
    //     required-column refusal above. It is not destructive, so it always
    //     refuses, regardless of `--allow-destructive` (checked here, before the
    //     `allow_destructive` short-circuit below). The inverse `DropNotNull`
    //     (nullable-ing a column) is always safe and is never matched here.
    if let Some((table, column)) = plan.changes.iter().find_map(|c| match c {
        SchemaChange::SetNotNull { table, column } => Some((table.clone(), column.clone())),
        _ => None,
    }) {
        return Err(DiffError::SetNotNullRequiresBackfill { table, column });
    }

    // 6c. A unique index added to a pre-existing table where ALL its indexed
    //     columns already existed — no override. `CREATE UNIQUE INDEX` validates
    //     uniqueness against every existing row the instant it runs, so it fails
    //     on any pre-existing duplicate; the offline engine cannot dedup the data.
    //     The index-level sibling of the `SET NOT NULL` refusal above. It is not
    //     destructive, so it always refuses, regardless of `--allow-destructive`
    //     (checked here, before the `allow_destructive` short-circuit below). A
    //     unique index on a brand-new `CreateTable` (empty) rides inline on that
    //     change and never reaches `AddIndex`; a unique index touching a
    //     newly-added column (whose existing rows are all NULL, treated as
    //     distinct) and any non-unique index are safe and are never matched here.
    if let Some(err) = find_unique_index_requires_dedup(plan) {
        return Err(err);
    }

    if opts.allow_destructive {
        return Ok(());
    }

    // 7. Destructive drops.
    let destructive_ops: Vec<DestructiveOp> = plan
        .changes
        .iter()
        .filter_map(|c| match c {
            SchemaChange::DropTable(t) => Some(DestructiveOp::Table(t.name.clone())),
            SchemaChange::DropColumn { table, column } => Some(DestructiveOp::Column {
                table: table.clone(),
                column: column.name.clone(),
            }),
            _ => None,
        })
        .collect();
    if !destructive_ops.is_empty() {
        let summary = destructive_ops
            .iter()
            .map(|op| match op {
                DestructiveOp::Table(t) => format!("DROP TABLE {t}"),
                DestructiveOp::Column { table, column } => {
                    format!("DROP COLUMN {table}.{column}")
                }
            })
            .collect::<Vec<_>>()
            .join("; ");
        return Err(DiffError::Destructive {
            summary,
            ops: destructive_ops,
        });
    }

    Ok(())
}

/// The [`DiffError::IdentityChange`] refusal for the first
/// [`SchemaChange::IdentityChange`] marker in `plan`, if any.
fn find_identity_change_block(plan: &MigrationPlan) -> Option<DiffError> {
    plan.changes.iter().find_map(|c| match c {
        SchemaChange::IdentityChange { table, column } => Some(DiffError::IdentityChange {
            table: table.clone(),
            column: column.clone(),
        }),
        _ => None,
    })
}

/// The [`DiffError::DropTableInboundReference`] refusal for the first
/// [`SchemaChange::DropTableBlockedByInboundFk`] marker in `plan`, if any.
fn find_inbound_fk_block(plan: &MigrationPlan) -> Option<DiffError> {
    plan.changes.iter().find_map(|c| match c {
        SchemaChange::DropTableBlockedByInboundFk {
            table,
            referencing_table,
            referencing_column,
        } => Some(DiffError::DropTableInboundReference {
            table: table.clone(),
            referencing_table: referencing_table.clone(),
            referencing_column: referencing_column.clone(),
        }),
        _ => None,
    })
}

/// The [`DiffError::TypeChangeOnForeignKeyColumn`] refusal for the first
/// [`SchemaChange::AlterColumnTypeBlockedByFk`] marker in `plan`, if any.
/// Postgres-only: on `SQLite` an FK-bound type change is safely expressed by the
/// table-recreate path (the plan still carries the real `AlterColumnType`
/// alongside the blocked marker, and the rebuild applies it while preserving the
/// inline `REFERENCES`), so the guard stays out of the `SQLite` boundary.
fn find_fk_type_change_block(plan: &MigrationPlan) -> Option<DiffError> {
    if plan.backend != Backend::Postgres {
        return None;
    }
    plan.changes.iter().find_map(|c| match c {
        SchemaChange::AlterColumnTypeBlockedByFk { table, column } => {
            Some(DiffError::TypeChangeOnForeignKeyColumn {
                table: table.clone(),
                column: column.clone(),
            })
        }
        _ => None,
    })
}

/// The [`DiffError::UniqueIndexRequiresDedup`] refusal for the first unique
/// `AddIndex` in `plan` whose indexed columns ALL pre-existed on the table — none
/// is a column being added in this same plan.
///
/// An `AddIndex` is produced by [`diff_indexes`] only for a both-present
/// (pre-existing) table; a brand-new table's indexes ride inline on its
/// [`SchemaChange::CreateTable`] and never reach this path — so a unique
/// `AddIndex` already implies the table pre-exists and may hold rows. It is unsafe
/// (existing rows may contain duplicates that fail `CREATE UNIQUE INDEX`) UNLESS
/// at least one indexed column is newly added in this plan (an `AddColumn`): a
/// new column is NULL in every existing row, and Postgres treats NULLs as
/// distinct in a unique index, so the existing rows cannot conflict.
fn find_unique_index_requires_dedup(plan: &MigrationPlan) -> Option<DiffError> {
    let added: BTreeSet<(&str, &str)> = plan
        .changes
        .iter()
        .filter_map(|c| match c {
            SchemaChange::AddColumn { table, column } => {
                Some((table.as_str(), column.name.as_str()))
            }
            _ => None,
        })
        .collect();
    plan.changes.iter().find_map(|c| match c {
        SchemaChange::AddIndex { table, index } if index.unique => {
            let touches_new_column = index
                .columns
                .iter()
                .any(|col| added.contains(&(table.as_str(), col.as_str())));
            (!touches_new_column).then(|| DiffError::UniqueIndexRequiresDedup {
                table: table.clone(),
                index: index.name.clone(),
            })
        }
        _ => None,
    })
}

/// Postgres's identifier byte limit (`NAMEDATALEN - 1`). Names longer than this are
/// silently truncated on apply.
const PG_MAX_IDENTIFIER_BYTES: usize = 63;

/// The identifiers this engine generates for a plan, in change order: the
/// `{table}_{column}_fkey` FK-constraint name for each [`SchemaChange::AddForeignKey`]
/// (rendered as `ADD CONSTRAINT` up / `DROP CONSTRAINT` down, both from this same
/// derivation), and every index name emitted as a top-level `CREATE INDEX` — the
/// [`SchemaChange::AddIndex`] index name plus each index on a [`SchemaChange::CreateTable`].
/// These are exactly the names Postgres would truncate to 63 bytes.
fn generated_identifiers(plan: &MigrationPlan) -> Vec<String> {
    let mut names = Vec::new();
    for change in &plan.changes {
        match change {
            SchemaChange::AddForeignKey { table, column, .. } => {
                // The FK-constraint name is engine-generated and safe to rename, so it
                // goes through `bounded_pg_identifier` (matching the `ADD`/`DROP
                // CONSTRAINT` emitters). A short name is returned unchanged; only an
                // over-limit one is truncate+hashed — so this never trips the guard.
                names.push(bounded_pg_identifier(&format!("{table}_{column}_fkey")));
            }
            SchemaChange::AddIndex { index, .. } => names.push(index.name.clone()),
            SchemaChange::CreateTable(table) => {
                names.extend(table.indexes.iter().map(|i| i.name.clone()));
            }
            _ => {}
        }
    }
    names
}

/// `name` truncated to at most `max` bytes, on a UTF-8 char boundary.
fn truncate_to_bytes(name: &str, max: usize) -> &str {
    if name.len() <= max {
        return name;
    }
    let mut end = max;
    while !name.is_char_boundary(end) {
        end -= 1;
    }
    &name[..end]
}

/// `name` truncated to Postgres's 63-byte identifier limit, on a UTF-8 char boundary
/// (PG truncates by byte; generated names are ASCII, but stay codepoint-safe anyway).
fn truncate_pg_identifier(name: &str) -> &str {
    truncate_to_bytes(name, PG_MAX_IDENTIFIER_BYTES)
}

/// A short, deterministic 8-hex-char digest of `raw`, for collision-resistant
/// identifier suffixing.
///
/// Uses a hand-rolled FNV-1a 64-bit hash (fully specified, dependency-free) rather
/// than `DefaultHasher`, whose output is not guaranteed stable across Rust versions —
/// this schema emitter must derive the same suffix on every toolchain, and the up and
/// down renderers must agree.
fn short_identifier_hash(raw: &str) -> String {
    let digest = fnv1a_64(raw.as_bytes());
    format!("{digest:016x}")[..8].to_owned()
}

/// FNV-1a 64-bit hash of `bytes` (offset basis `0xcbf29ce484222325`, prime
/// `0x100000001b3`), fully specified so the digest is deterministic everywhere.
const fn fnv1a_64(bytes: &[u8]) -> u64 {
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    let prime: u64 = 0x0000_0100_0000_01b3;
    let mut i = 0;
    while i < bytes.len() {
        hash ^= bytes[i] as u64;
        hash = hash.wrapping_mul(prime);
        i += 1;
    }
    hash
}

/// A Postgres-safe (`≤ 63`-byte) identifier for `raw`.
///
/// Returns `raw` unchanged when it already fits, so short names — the common case —
/// are byte-stable. An over-limit name is truncated and suffixed with
/// `_<8-hex-hash>` of the **full untruncated** name, yielding a deterministic,
/// collision-resistant identifier that always fits. Applied only to
/// engine-generated FK-constraint names (safe to rename), never to parser-provided
/// index names.
fn bounded_pg_identifier(raw: &str) -> String {
    if raw.len() <= PG_MAX_IDENTIFIER_BYTES {
        return raw.to_owned();
    }
    let hash = short_identifier_hash(raw);
    // suffix is "_" + 8 hex chars = 9 bytes; leave room for it within the 63 limit.
    let head_budget = PG_MAX_IDENTIFIER_BYTES - (hash.len() + 1);
    let head = truncate_to_bytes(raw, head_budget);
    format!("{head}_{hash}")
}

/// The [`DiffError::GeneratedIdentifierTooLong`] refusal when the plan generates an
/// FK-constraint or index identifier over Postgres's 63-byte limit, two distinct
/// generated names that collide after truncation to 63 bytes, or two generated names
/// that are *exactly* identical. Postgres-only — `SQLite` does not truncate identifiers
/// to a short limit, so the truncation hazard does not apply there (an exact-duplicate
/// relation name would still be rejected, but the parser only produces the colliding
/// `idx_<table>_<field>_unique` shape for a Postgres plan).
fn find_identifier_limit_violation(plan: &MigrationPlan) -> Option<DiffError> {
    if plan.backend != Backend::Postgres {
        return None;
    }
    let mut by_truncated: BTreeMap<String, String> = BTreeMap::new();
    for name in generated_identifiers(plan) {
        // Over the limit: PG truncates it silently — refuse outright (this alone
        // catches every *distinct*-name post-truncation collision, since such a
        // collision requires at least one name to exceed 63 bytes).
        if name.len() > PG_MAX_IDENTIFIER_BYTES {
            return Some(DiffError::GeneratedIdentifierTooLong { name });
        }
        // Any collision on the on-apply (truncated) identifier is a duplicate-relation
        // hazard: PG accepts the first `CREATE INDEX`/`ADD CONSTRAINT` and rejects the
        // second. Because over-limit names are refused above, every name here truncates
        // to itself — so this fires on an *exact duplicate* generated name (e.g. a
        // `#[unique] foo` field plus a separate field named `foo_unique`, both yielding
        // `idx_<table>_foo_unique`), which PG would reject as a duplicate relation. This
        // must NOT dedup or skip the `prev == name` case: identical names are precisely
        // the hazard.
        if by_truncated
            .insert(truncate_pg_identifier(&name).to_owned(), name.clone())
            .is_some()
        {
            return Some(DiffError::GeneratedIdentifierTooLong { name });
        }
    }
    None
}

/// The [`DiffError::PossibleRename`] refusal for the first both-present table that
/// both dropped and added column(s) — the ambiguous drop+add that might be a
/// rename. Grouped in a `BTreeMap` so the reported table is deterministic
/// (sorted). The caller only consults this when `--allow-destructive` is off.
fn find_possible_rename(plan: &MigrationPlan) -> Option<DiffError> {
    let mut per_table: BTreeMap<String, (Vec<String>, Vec<String>)> = BTreeMap::new();
    for change in &plan.changes {
        match change {
            SchemaChange::DropColumn { table, column } => {
                per_table
                    .entry(table.clone())
                    .or_default()
                    .0
                    .push(column.name.clone());
            }
            SchemaChange::AddColumn { table, column } => {
                per_table
                    .entry(table.clone())
                    .or_default()
                    .1
                    .push(column.name.clone());
            }
            _ => {}
        }
    }
    per_table
        .into_iter()
        .find(|(_, (dropped, added))| !dropped.is_empty() && !added.is_empty())
        .map(|(table, (dropped, added))| DiffError::PossibleRename {
            table,
            dropped,
            added,
        })
}

/// The [`DiffError::NonImplicitTypeConversion`] refusal for the first
/// non-implicit `AlterColumnType` in `plan`, if any. Postgres-only: on `SQLite`
/// every `AlterColumnType` is realised by the table-recreate path (which restates
/// the whole column shape, so an implicit-vs-explicit cast distinction does not
/// apply), so the classifier stays out of the `SQLite` boundary.
fn find_non_implicit_conversion(plan: &MigrationPlan) -> Option<DiffError> {
    if plan.backend != Backend::Postgres {
        return None;
    }
    plan.changes.iter().find_map(|c| match c {
        SchemaChange::AlterColumnType {
            table,
            column,
            from,
            to,
        } if !is_implicit_pg_type_cast(from, to) => Some(DiffError::NonImplicitTypeConversion {
            table: table.clone(),
            column: column.clone(),
            from: from.sql_type(plan.backend),
            to: to.sql_type(plan.backend),
        }),
        _ => None,
    })
}

/// True when PG casts `from` → `to` **implicitly**, without a `USING`
/// clause — the only type changes this slice renders as a bare
/// `ALTER COLUMN ... TYPE`. Deliberately conservative: only the lossless numeric
/// widenings PG auto-casts (`int4` → `int8`, `float4` → `float8`). Every other
/// pair (e.g. `TEXT` → `INTEGER`/`UUID`, `BOOLEAN` → `INTEGER`, `NUMERIC`
/// narrowing) needs a manual `USING` migration and is refused by [`guard_plan`].
/// The IR does not distinguish `TEXT` from a `VARCHAR` family, so no string
/// widening pair exists to admit here.
const fn is_implicit_pg_type_cast(from: &ColumnType, to: &ColumnType) -> bool {
    matches!(
        (from, to),
        (ColumnType::Int32, ColumnType::Int64) | (ColumnType::Float32, ColumnType::Float64)
    )
}

// ---------------------------------------------------------------------------
// SQL emission (pg + sqlite)
// ---------------------------------------------------------------------------

/// Full desired + baseline table shapes, keyed by table name.
///
/// The `SQLite` table-recreate path needs a table's complete shape (all columns,
/// PK, checks, indexes), which the per-change [`SchemaChange`] deltas don't carry,
/// so the schema-aware [`emit_up_sql_with_context`] / [`emit_down_sql_with_context`]
/// entry points thread it in. Postgres never rebuilds and so ignores it.
#[derive(Debug, Clone, Default)]
pub struct SchemaContext {
    /// Desired (post-migration) tables, by name — the "new shape" for an up rebuild.
    pub desired: BTreeMap<String, Table>,
    /// Baseline (pre-migration) tables, by name — the "new shape" for a down rebuild.
    pub baseline: BTreeMap<String, Table>,
}

impl SchemaContext {
    /// Build a context from the desired + baseline table lists (as passed to
    /// [`diff_schema`]).
    #[must_use]
    pub fn from_tables(desired: &[Table], baseline: &[Table]) -> Self {
        Self {
            desired: desired
                .iter()
                .map(|t| (t.name.clone(), t.clone()))
                .collect(),
            baseline: baseline
                .iter()
                .map(|t| (t.name.clone(), t.clone()))
                .collect(),
        }
    }
}

/// Render the plan's forward SQL without a schema context.
///
/// Sufficient for Postgres and the portable `SQLite` subset. If the plan needs a
/// `SQLite` table rebuild, prefer [`emit_up_sql_with_context`].
///
/// # Errors
///
/// Returns [`EmitError::SqliteRebuildUnsupported`] when a `SQLite` `ALTER`-family
/// change needs a table rebuild but no shape context was supplied, or
/// [`EmitError::CyclicTableDependencies`] on an unorderable new-table FK cycle.
// Retained context-free public API (the command wiring and the SQLite rebuild path
// use the `_with_context` entry points; this signature is consumed by the parallel
// slice-6 lane and the diff tests).
#[allow(dead_code)]
pub fn emit_up_sql(plan: &MigrationPlan) -> Result<String, EmitError> {
    emit_up_sql_with_context(plan, &SchemaContext::default())
}

/// Render the plan's reverse SQL without a schema context.
///
/// # Errors
///
/// See [`emit_up_sql`].
#[allow(dead_code)]
pub fn emit_down_sql(plan: &MigrationPlan) -> Result<String, EmitError> {
    emit_down_sql_with_context(plan, &SchemaContext::default())
}

/// Render the plan's forward SQL, using `ctx` for any `SQLite` table rebuild.
///
/// Postgres emits the per-change `ALTER`-family statements directly; `SQLite`
/// coalesces every `ALTER`-family change on a table into a single table-recreate
/// block built from `ctx.desired`.
///
/// # Errors
///
/// Returns [`EmitError::SqliteRebuildUnsupported`] when a rebuild is required but
/// the table's desired/baseline shape is missing from `ctx`, or
/// [`EmitError::CyclicTableDependencies`] on an unorderable new-table FK cycle.
pub fn emit_up_sql_with_context(
    plan: &MigrationPlan,
    ctx: &SchemaContext,
) -> Result<String, EmitError> {
    match plan.backend {
        Backend::Postgres => emit_up_sql_pg(plan),
        Backend::Sqlite => emit_up_sql_sqlite(plan, ctx),
    }
}

/// Render the plan's reverse SQL, using `ctx` for any `SQLite` table rebuild.
///
/// # Errors
///
/// See [`emit_up_sql_with_context`].
pub fn emit_down_sql_with_context(
    plan: &MigrationPlan,
    ctx: &SchemaContext,
) -> Result<String, EmitError> {
    match plan.backend {
        Backend::Postgres => emit_down_sql_pg(plan, ctx),
        Backend::Sqlite => emit_down_sql_sqlite(plan, ctx),
    }
}

/// The Postgres forward path: one statement group per change, canonical up-order,
/// groups blank-line separated. Unchanged from the pg-first slice.
fn emit_up_sql_pg(plan: &MigrationPlan) -> Result<String, EmitError> {
    let ordered = up_ordered(&plan.changes)?;
    let mut groups = Vec::new();
    for change in ordered {
        let sql = emit_change_up(change, plan.backend)?;
        let sql = sql.trim_end();
        if !sql.is_empty() {
            groups.push(sql.to_owned());
        }
    }
    Ok(join_groups(&groups))
}

/// The Postgres reverse path: changes reversed and individually inverted, with
/// `-- irreversible:` markers where data cannot round-trip.
///
/// A `DropColumn` on a column covered by a RETAINED (`definition`-carrying)
/// baseline index — the expression/partial/constraint-owned indexes `schema pull`
/// preserves and the model diff never `DropIndex`'s — cascade-drops that index in
/// Postgres along with the column (the up path is a bare `ALTER TABLE … DROP
/// COLUMN`, never a failing `DROP INDEX` on a constraint-backed index). So after
/// re-adding the column the down path must recreate each such index from its
/// verbatim `definition`, else rollback silently loses the uniqueness/index. This
/// needs the baseline shapes carried in `ctx`; ordinary model-managed indexes are
/// restored via their own `DropIndex → AddIndex` inversion and are skipped here.
///
/// Recreation is **delayed and deduped**: a retained index can depend on more than
/// one dropped column (e.g. a partial index
/// `... ON t (lower(email)) WHERE tenant_id IS NOT NULL` when the model drops BOTH
/// `email` and `tenant_id`). Recreating it inline after re-adding only the *first*
/// dependent column would (a) fail — the other dependent column is still absent, so
/// Postgres rejects the `CREATE INDEX` — and (b) re-emit the same `CREATE INDEX`
/// again for the second column. So the down path first emits ALL the column
/// re-adds (and every other reversed change), then recreates each cascade-dropped
/// retained index EXACTLY ONCE, keyed by `(table, index name)`, after all of its
/// dropped columns have been restored.
fn emit_down_sql_pg(plan: &MigrationPlan, ctx: &SchemaContext) -> Result<String, EmitError> {
    let mut ordered = up_ordered(&plan.changes)?;
    ordered.reverse();
    let mut groups = Vec::new();
    // Per-table set of columns this migration drops (and the down path re-adds),
    // gathered so a multi-column retained index is recreated only after ALL its
    // dependent dropped columns are back.
    let mut dropped_by_table: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    for change in ordered {
        let sql = emit_change_down(change, plan.backend)?;
        let sql = sql.trim_end();
        if !sql.is_empty() {
            groups.push(sql.to_owned());
        }
        if let SchemaChange::DropColumn { table, column } = change {
            dropped_by_table
                .entry(table.clone())
                .or_default()
                .insert(column.name.clone());
        }
    }
    // Every column re-add is now emitted. Recreate each retained index whose
    // dependent-column set intersects this table's dropped columns — once per
    // (table, index name) — so a multi-column index is created exactly once, after
    // all of its dropped columns are restored.
    for (table, dropped) in &dropped_by_table {
        for idx in retained_indexes_depending_on_any(ctx, table, dropped) {
            groups.push(index_sql(table, idx).trim_end().to_owned());
        }
    }
    Ok(join_groups(&groups))
}

/// The RETAINED (`definition`-carrying) baseline indexes of `table` whose
/// dependent-column set intersects `dropped_columns` — the
/// expression/partial/constraint-owned indexes Postgres cascade-drops when ANY of
/// those columns is dropped and that carry no `DropIndex` in the plan, so the down
/// migration must recreate them verbatim. Each qualifying index appears once (the
/// baseline lists each index once), so a retained index depending on two dropped
/// columns is returned — and thus recreated — exactly once. Returns empty when the
/// table is absent from `ctx.baseline` (e.g. context-free emit).
fn retained_indexes_depending_on_any<'a>(
    ctx: &'a SchemaContext,
    table: &str,
    dropped_columns: &BTreeSet<String>,
) -> Vec<&'a Index> {
    ctx.baseline.get(table).map_or_else(Vec::new, |t| {
        t.indexes
            .iter()
            .filter(|i| {
                i.definition.is_some()
                    && dropped_columns
                        .iter()
                        // pg-only rollback path (`emit_down_sql_pg`) — exact `columns`
                        // membership; the SQLite definition-scan branch never runs here.
                        .any(|c| index_depends_on_column(i, c, Backend::Postgres))
            })
            .collect()
    })
}

/// The change kinds whose `SQLite` realisation is a full table recreate: the
/// `ALTER`-family Postgres would express as `ALTER COLUMN` / `ADD CHECK` /
/// `ADD CONSTRAINT`, none of which `SQLite` supports.
fn sqlite_rebuild_tables(changes: &[SchemaChange]) -> BTreeSet<String> {
    changes
        .iter()
        .filter_map(|c| match c {
            SchemaChange::AlterColumnType { table, .. }
            | SchemaChange::DropNotNull { table, .. }
            | SchemaChange::SetDefault { table, .. }
            | SchemaChange::AddCheck { table, .. }
            | SchemaChange::AddForeignKey { table, .. } => Some(table.clone()),
            _ => None,
        })
        .collect()
}

/// The sorted, de-duplicated column names of every
/// [`SchemaChange::AlterColumnTypeBlockedByFk`] marker in `changes` that targets
/// `table`. Non-empty only when this table's `SQLite` rebuild is (partly) driven
/// by an FK-bound type change — the trigger for the FK type-consistency advisory.
fn fk_type_change_columns(changes: &[&SchemaChange], table: &str) -> Vec<String> {
    changes
        .iter()
        .filter_map(|c| match c {
            SchemaChange::AlterColumnTypeBlockedByFk { table: t, column } if t == table => {
                Some(column.clone())
            }
            _ => None,
        })
        .collect::<BTreeSet<String>>()
        .into_iter()
        .collect()
}

/// The table a change targets, for rebuild-membership tests.
const fn change_table_name(change: &SchemaChange) -> &str {
    match change {
        SchemaChange::CreateTable(t) | SchemaChange::DropTable(t) => t.name.as_str(),
        SchemaChange::AddColumn { table, .. }
        | SchemaChange::DropColumn { table, .. }
        | SchemaChange::AlterColumnType { table, .. }
        | SchemaChange::SetNotNull { table, .. }
        | SchemaChange::DropNotNull { table, .. }
        | SchemaChange::SetDefault { table, .. }
        | SchemaChange::AddForeignKey { table, .. }
        | SchemaChange::AddIndex { table, .. }
        | SchemaChange::DropIndex { table, .. }
        | SchemaChange::AddCheck { table, .. }
        | SchemaChange::PrimaryKeyChange { table }
        | SchemaChange::ForeignKeyChange { table, .. }
        | SchemaChange::IdentityChange { table, .. }
        | SchemaChange::DropTableBlockedByInboundFk { table, .. }
        | SchemaChange::AlterColumnTypeBlockedByFk { table, .. }
        | SchemaChange::AddForeignKeyToExistingColumn { table, .. }
        | SchemaChange::CreateTableBlockedBySkippedField { table, .. } => table.as_str(),
    }
}

/// The `SQLite` forward path. Every `ALTER`-family change on a table is coalesced
/// into a single table-recreate block (emitted once, at the first change touching
/// that table); all of that table's other changes are folded into the recreate,
/// which already targets its full desired shape. Non-rebuild tables emit through
/// the portable per-change path unchanged.
fn emit_up_sql_sqlite(plan: &MigrationPlan, ctx: &SchemaContext) -> Result<String, EmitError> {
    let ordered = up_ordered(&plan.changes)?;
    let rebuild = sqlite_rebuild_tables(&plan.changes);
    let mut emitted: BTreeSet<String> = BTreeSet::new();
    let mut groups = Vec::new();
    for change in &ordered {
        let table = change_table_name(change);
        if rebuild.contains(table) {
            if emitted.insert(table.to_owned()) {
                let block = emit_sqlite_rebuild(table, ctx, &ordered, RebuildLeg::Up)?;
                let block = block.trim_end();
                if !block.is_empty() {
                    groups.push(block.to_owned());
                }
            }
            continue;
        }
        let sql = emit_change_up(change, plan.backend)?;
        let sql = sql.trim_end();
        if !sql.is_empty() {
            groups.push(sql.to_owned());
        }
    }
    Ok(join_groups(&groups))
}

/// The `SQLite` reverse path: the mirror of [`emit_up_sql_sqlite`], with each
/// rebuild block rolled back to the table's baseline shape.
fn emit_down_sql_sqlite(plan: &MigrationPlan, ctx: &SchemaContext) -> Result<String, EmitError> {
    let mut ordered = up_ordered(&plan.changes)?;
    ordered.reverse();
    let rebuild = sqlite_rebuild_tables(&plan.changes);
    let mut emitted: BTreeSet<String> = BTreeSet::new();
    let mut groups = Vec::new();
    for change in &ordered {
        let table = change_table_name(change);
        if rebuild.contains(table) {
            if emitted.insert(table.to_owned()) {
                let block = emit_sqlite_rebuild(table, ctx, &ordered, RebuildLeg::Down)?;
                let block = block.trim_end();
                if !block.is_empty() {
                    groups.push(block.to_owned());
                }
            }
            continue;
        }
        let sql = emit_change_down(change, plan.backend)?;
        let sql = sql.trim_end();
        if !sql.is_empty() {
            groups.push(sql.to_owned());
        }
    }
    Ok(join_groups(&groups))
}

/// Which leg a `SQLite` rebuild renders — governs the target shape and the leading
/// marker.
#[derive(Debug, Clone, Copy)]
enum RebuildLeg {
    /// Rebuild to the post-migration shape (`ctx.baseline` + diff deltas).
    Up,
    /// Rebuild back to the baseline shape (`ctx.baseline`).
    Down,
}

/// Render the `SQLite` table-recreate block for `table` on the given leg, drawing
/// the target and source shapes from `ctx` and, on the up leg, the plan's own
/// `changes`.
///
/// The block `CREATE`s a `{table}__autumn_new` staging table with the target shape,
/// copies the columns common to both shapes, drops the old table, renames the
/// staging table into place, recreates the target shape's indexes, and validates
/// referential integrity — all wrapped in `PRAGMA foreign_keys` toggles.
///
/// The **up** leg's target shape is the rich baseline table with this table's
/// explicit diff deltas folded in ([`baseline_with_changes_applied`]) — **not** the
/// parser's partial `ctx.desired` table — so any baseline facet the parser cannot
/// see (a non-convention default, a skipped `CHECK`/enum, an association foreign
/// key) survives a rebuild triggered by an unrelated change. The **down** leg
/// targets the baseline shape directly and copies from the actual post-migration
/// shape (`baseline` + this table's diff deltas — the same value the up leg builds
/// as its target), **not** the parser's partial `ctx.desired`, so a
/// retained-but-parser-invisible column is copied back on rollback rather than
/// dropped.
fn emit_sqlite_rebuild(
    table: &str,
    ctx: &SchemaContext,
    changes: &[&SchemaChange],
    leg: RebuildLeg,
) -> Result<String, EmitError> {
    // The `{table}__autumn_new` staging name is not guaranteed collision-free: if a
    // real table already carries that name, the rebuild's CREATE/RENAME would clobber
    // it. Refuse rather than emit unappliable SQL.
    let staging = format!("{table}__autumn_new");
    if ctx.desired.contains_key(&staging) || ctx.baseline.contains_key(&staging) {
        return Err(EmitError::SqliteRebuildUnsupported {
            table: table.to_owned(),
            kind: "table rebuild",
            reason: format!(
                "staging table name `{staging}` collides with an existing table; \
                 rename the model to free that name"
            ),
        });
    }
    // Fetched as a validated precondition (a missing desired shape is a directed
    // error, exercised by the up leg's missing-context path); neither leg copies
    // from the parser's partial desired table any more.
    let _desired = ctx
        .desired
        .get(table)
        .ok_or_else(|| missing_rebuild_shape(table, "desired"))?;
    let baseline = ctx
        .baseline
        .get(table)
        .ok_or_else(|| missing_rebuild_shape(table, "baseline"))?;
    match leg {
        // Build the up-leg target from the rich baseline with this table's explicit
        // diff deltas applied, preserving every unchanged baseline facet the parser
        // could not observe; the source (INSERT..SELECT) columns are the baseline's,
        // i.e. the actual existing table.
        RebuildLeg::Up => {
            let new_shape = baseline_with_changes_applied(baseline, changes, table);
            let fk_cols = fk_type_change_columns(changes, table);
            Ok(render_sqlite_rebuild(
                table, &new_shape, baseline, leg, &fk_cols,
            ))
        }
        // The down leg rolls back to the rich baseline shape. Its copy SOURCE is the
        // actual post-migration table — `baseline + this table's diff deltas`, the same
        // shape the up leg built as its target — NOT the parser's partial `ctx.desired`:
        // a retained-but-parser-invisible column (a skipped enum/association) is absent
        // from `desired`, so sourcing from it would drop that column from the rollback
        // INSERT..SELECT and lose its data. Intersecting the baseline target with the
        // post-migration source copies back every baseline column the up migration did
        // not drop, in baseline order.
        RebuildLeg::Down => {
            let post_migration = baseline_with_changes_applied(baseline, changes, table);
            let fk_cols = fk_type_change_columns(changes, table);
            Ok(render_sqlite_rebuild(
                table,
                baseline,
                &post_migration,
                leg,
                &fk_cols,
            ))
        }
    }
}

/// Apply the table's own plan changes to its baseline shape, preserving every
/// baseline facet the diff did not explicitly change (parser-invisible defaults,
/// `CHECK`s, and so on) — the `SQLite` recreate's "new shape" for the up leg.
///
/// The slice-2 parser is deliberately partial (see the module header): it cannot
/// see a non-convention `#[default]`, some `CHECK`/enum facets, or an association
/// foreign key, and this engine has no `DropDefault` / `DropCheck` /
/// `DropForeignKey` variant. Rebuilding the whole table from the raw `ctx.desired`
/// (partial) shape would therefore silently drop any baseline facet the parser
/// could not observe. Folding the explicit diff deltas into the rich baseline
/// clone instead leaves every unchanged baseline facet intact, upholding the
/// engine's "never destroy parser-invisible state" invariant that the Postgres
/// per-change `ALTER` path already honours.
///
/// Only changes whose table is `table` are folded in; anything else (including the
/// non-emittable guard markers) is ignored.
fn baseline_with_changes_applied(
    baseline: &Table,
    changes: &[&SchemaChange],
    table: &str,
) -> Table {
    let mut shape = baseline.clone();
    for change in changes {
        if change_table_name(change) != table {
            continue;
        }
        match change {
            SchemaChange::AddColumn { column, .. } => shape.columns.push(column.clone()),
            SchemaChange::DropColumn { column, .. } => {
                shape.columns.retain(|c| c.name != column.name);
                shape.primary_key.retain(|n| n != &column.name);
                // Prune any index depending on the dropped column — including a
                // retained partial/expression index that references the column only
                // in its `definition` predicate/expression (SQLite rejects DROP
                // COLUMN on a referenced column, and this rebuild must NOT recreate an
                // orphaned index on the new table). This is the SQLite rebuild path.
                shape
                    .indexes
                    .retain(|i| !index_depends_on_column(i, &column.name, Backend::Sqlite));
            }
            SchemaChange::AlterColumnType { column, to, .. } => {
                if let Some(c) = shape.columns.iter_mut().find(|c| &c.name == column) {
                    c.ty = to.clone();
                }
            }
            SchemaChange::DropNotNull { column, .. } => {
                if let Some(c) = shape.columns.iter_mut().find(|c| &c.name == column) {
                    c.nullable = true;
                }
            }
            SchemaChange::SetNotNull { column, .. } => {
                if let Some(c) = shape.columns.iter_mut().find(|c| &c.name == column) {
                    c.nullable = false;
                }
            }
            SchemaChange::SetDefault { column, to, .. } => {
                if let Some(c) = shape.columns.iter_mut().find(|c| &c.name == column) {
                    c.default = Some(to.clone());
                }
            }
            SchemaChange::AddCheck { check, .. } => shape.checks.push(check.clone()),
            SchemaChange::AddForeignKey {
                column,
                foreign_key,
                ..
            } => {
                if let Some(c) = shape.columns.iter_mut().find(|c| &c.name == column) {
                    c.references = Some(foreign_key.clone());
                }
            }
            SchemaChange::AddIndex { index, .. } => shape.indexes.push(index.clone()),
            SchemaChange::DropIndex { index, .. } => {
                shape.indexes.retain(|i| i.name != index.name);
            }
            _ => {}
        }
    }
    shape
}

/// The [`EmitError::SqliteRebuildUnsupported`] for a rebuild whose `which`
/// (`"desired"` / `"baseline"`) table shape is absent from the context.
fn missing_rebuild_shape(table: &str, which: &'static str) -> EmitError {
    EmitError::SqliteRebuildUnsupported {
        table: table.to_owned(),
        kind: "table rebuild",
        reason: format!(
            "the {which} table shape is unavailable — call \
             emit_up_sql_with_context / emit_down_sql_with_context with a \
             SchemaContext populated from the desired and baseline tables"
        ),
    }
}

/// Render the recreate block: staging `CREATE`, `INSERT .. SELECT` of the columns
/// common to both shapes (in `new_shape` order), `DROP`, `RENAME`, index recreate,
/// and the integrity check. `leg` only prepends the down-leg irreversibility marker.
fn render_sqlite_rebuild(
    table: &str,
    new_shape: &Table,
    source_shape: &Table,
    leg: RebuildLeg,
    fk_type_change_cols: &[String],
) -> String {
    let new_table = format!("{table}__autumn_new");
    let source_cols: BTreeSet<&str> = source_shape
        .columns
        .iter()
        .map(|c| c.name.as_str())
        .collect();
    let common: Vec<&str> = new_shape
        .columns
        .iter()
        .map(|c| c.name.as_str())
        .filter(|n| source_cols.contains(n))
        .collect();
    let col_list = common.join(", ");

    let mut out = String::new();
    if matches!(leg, RebuildLeg::Down) {
        let _ = writeln!(
            out,
            "-- irreversible: a SQLite table rebuild rolled back to the prior shape may not restore data lost by a narrowing type change or dropped column"
        );
    }
    let _ = writeln!(
        out,
        "-- autumn: SQLite table rebuild for `{table}` — ALTER-family changes require a full table recreate."
    );
    let _ = writeln!(
        out,
        "-- Transaction semantics: this migration must run inside a single transaction (diesel wraps each"
    );
    let _ = writeln!(
        out,
        "-- migration in one). NOTE: `PRAGMA foreign_keys` is a no-op inside a transaction, so the harness"
    );
    let _ = writeln!(
        out,
        "-- must ensure foreign-key enforcement is disabled around the migration."
    );
    let _ = writeln!(
        out,
        "-- autumn-safety: this recreate copies columns and re-creates indexes only. DROP TABLE drops the table's TRIGGERS (not restored here); VIEWS that reference the table are not dropped and may be left dangling or block the rename — re-create triggers and repair dependent views in a manual migration."
    );
    let _ = writeln!(
        out,
        "-- autumn-safety: `PRAGMA foreign_key_check` below only REPORTS violation rows (it does not raise); the recreate copies existing values verbatim and introduces no new orphans, but the migration runner must inspect the pragma's output to treat any pre-existing orphan as an error."
    );
    // When an FK-bound column's type is changed by this recreate, warn that SQLite
    // (unlike Postgres, which refuses the change outright) does not enforce that the
    // column still matches the referenced key's type — that consistency is now the
    // author's responsibility.
    if !fk_type_change_cols.is_empty() {
        let cols = fk_type_change_cols.join(", ");
        let _ = writeln!(
            out,
            "-- autumn-safety: foreign-key column(s) {cols} have their type changed by this recreate; SQLite does not enforce that they still match the referenced key's type, so ensure the referenced column stays type-compatible (Postgres rejects this change outright, which is why it is emitted only for SQLite)."
        );
    }
    // Preserve the AUTOINCREMENT high-water mark only when BOTH the copy SOURCE and
    // the target shape's single PK are `BigSerial` (an `INTEGER PRIMARY KEY
    // AUTOINCREMENT` column). Such a source table has a `sqlite_sequence` row that
    // `DROP TABLE` would discard, resetting the high-water to the max surviving id and
    // letting a later insert reuse an id that was previously issued and deleted.
    // Gating on the source too is load-bearing: `sqlite_sequence` is created LAZILY by
    // SQLite (only once some AUTOINCREMENT table exists), so a migration that
    // INTRODUCES autoincrement (an `i32`->`i64` PK change) on a database with no prior
    // AUTOINCREMENT table has no `sqlite_sequence` table, and the capture SELECT would
    // fail with `no such table: sqlite_sequence`. The high-water only needs preserving
    // when the SOURCE was already AUTOINCREMENT — and in that case its `sqlite_sequence`
    // row is guaranteed to exist, so the capture can't fail. When the source is not
    // AUTOINCREMENT there is no prior high-water to preserve (the new autoincrement
    // table correctly starts fresh from the max copied id), so skipping is also correct.
    // Uuid / composite / non-single PK tables have no `sqlite_sequence` entry either, so
    // they emit none of these statements.
    let preserve_seq = matches!(single_pk_column(source_shape), Some((_, IdKind::BigSerial)))
        && matches!(single_pk_column(new_shape), Some((_, IdKind::BigSerial)));

    let _ = writeln!(out, "PRAGMA foreign_keys=OFF;");
    if preserve_seq {
        let _ = writeln!(
            out,
            "-- preserve the AUTOINCREMENT high-water mark so IDs issued-then-deleted are never reused"
        );
        let _ = writeln!(
            out,
            "CREATE TEMP TABLE _autumn_seq_{table} AS SELECT seq FROM sqlite_sequence WHERE name = '{table}';"
        );
    }
    out.push_str(&render_create_table_body(
        &new_table,
        new_shape,
        Backend::Sqlite,
    ));
    let _ = writeln!(out, "INSERT INTO {new_table} ({col_list})");
    let _ = writeln!(out, "    SELECT {col_list} FROM {table};");
    let _ = writeln!(out, "DROP TABLE {table};");
    // Wrap the staging rename in `PRAGMA legacy_alter_table=ON`…`OFF`. Under the modern
    // default (`legacy_alter_table=OFF`), `ALTER TABLE ... RENAME` descends into every
    // dependent VIEW to rewrite references and aborts because the just-dropped table no
    // longer resolves ("error in view v: no such table"). The offline emitter cannot see
    // or recreate views, so it emits this blind, always-present pragma pair: it makes the
    // rename a "dumb" rename that does not validate views, so the migration applies and
    // the view re-validates against the recreated table. Unlike `foreign_keys`, this
    // pragma is honoured inside a transaction (proven by `sqlite_rebuild_survives_dependent_view`).
    let _ = writeln!(out, "PRAGMA legacy_alter_table=ON;");
    let _ = writeln!(out, "ALTER TABLE {new_table} RENAME TO {table};");
    let _ = writeln!(out, "PRAGMA legacy_alter_table=OFF;");
    let mut indexes: Vec<&Index> = new_shape.indexes.iter().collect();
    indexes.sort_by(|a, b| a.name.cmp(&b.name));
    for index in indexes {
        let _ = writeln!(out, "{}", index_sql(table, index));
    }
    if preserve_seq {
        let _ = writeln!(
            out,
            "UPDATE sqlite_sequence SET seq = (SELECT seq FROM _autumn_seq_{table})\n    WHERE name = '{table}' AND (SELECT seq FROM _autumn_seq_{table}) IS NOT NULL;"
        );
        let _ = writeln!(
            out,
            "INSERT INTO sqlite_sequence (name, seq)\n    SELECT '{table}', (SELECT seq FROM _autumn_seq_{table})\n    WHERE (SELECT seq FROM _autumn_seq_{table}) IS NOT NULL\n      AND NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = '{table}');"
        );
        let _ = writeln!(out, "DROP TABLE _autumn_seq_{table};");
    }
    let _ = writeln!(out, "PRAGMA foreign_key_check;");
    let _ = writeln!(out, "PRAGMA foreign_keys=ON;");
    out
}

/// Join statement groups with a blank line and a trailing newline (empty for an
/// empty plan).
fn join_groups(groups: &[String]) -> String {
    if groups.is_empty() {
        return String::new();
    }
    let mut out = groups.join("\n\n");
    out.push('\n');
    out
}

/// Order the changes into the canonical up-buckets (a valid dependency order),
/// stable within a bucket (`diff_schema` already emits a deterministic order).
///
/// Two orderings need context the plain per-change bucket cannot provide, so they
/// are handled here rather than in [`up_bucket`]:
///
/// * **New-table FK dependencies** — `CREATE TABLE`s are **topologically** sorted
///   so a table referenced by an inline `REFERENCES` is created before the table
///   that references it (a cycle is [`EmitError::CyclicTableDependencies`]).
/// * **Replaced indexes** — a same-named index that is both dropped and re-added
///   (a shape change) must `DROP INDEX` **before** the `CREATE INDEX`, else the
///   create collides with the still-existing old index; such a "replacement drop"
///   is ordered just before the `AddIndex` bucket instead of in the general
///   `DropIndex` bucket.
///
/// # Errors
///
/// Returns [`EmitError::CyclicTableDependencies`] when the new tables reference
/// each other in a cycle that inline foreign keys cannot express.
fn up_ordered(changes: &[SchemaChange]) -> Result<Vec<&SchemaChange>, EmitError> {
    let replaced = replaced_index_names(changes);

    // `CreateTable`s are the first bucket; order them topologically so referenced
    // tables precede their referencers.
    let mut creates: Vec<&SchemaChange> = changes
        .iter()
        .filter(|c| matches!(c, SchemaChange::CreateTable(_)))
        .collect();
    topo_sort_creates(&mut creates)?;

    // `DropTable`s are the last bucket; order them in REVERSE topological order so
    // a table that references another (via its baseline inline FK) is dropped
    // before the table it references. `emit_down_sql` reverses the whole plan, so
    // this reverse-topo up-order becomes a forward-topo (referenced-first) recreate
    // on the down leg.
    let mut drops: Vec<&SchemaChange> = changes
        .iter()
        .filter(|c| matches!(c, SchemaChange::DropTable(_)))
        .collect();
    topo_sort_drops(&mut drops)?;

    // Everything else keeps its bucket order; the replacement-drop key threads
    // through so a replaced index drops before its re-add.
    let mut rest: Vec<&SchemaChange> = changes
        .iter()
        .filter(|c| !matches!(c, SchemaChange::CreateTable(_) | SchemaChange::DropTable(_)))
        .collect();
    rest.sort_by_key(|c| up_sort_key(c, &replaced));

    let mut ordered = creates;
    ordered.extend(rest);
    ordered.extend(drops);
    Ok(ordered)
}

/// The set of index names that appear in **both** an `AddIndex` and a `DropIndex`
/// in the same plan — i.e. a same-named index whose shape changed
/// ([`diff_indexes`] emits it as a drop + a re-add). Such a drop must precede its
/// re-add in `up.sql`.
fn replaced_index_names(changes: &[SchemaChange]) -> BTreeSet<String> {
    let added: BTreeSet<&str> = changes
        .iter()
        .filter_map(|c| match c {
            SchemaChange::AddIndex { index, .. } => Some(index.name.as_str()),
            _ => None,
        })
        .collect();
    changes
        .iter()
        .filter_map(|c| match c {
            SchemaChange::DropIndex { index, .. } if added.contains(index.name.as_str()) => {
                Some(index.name.clone())
            }
            _ => None,
        })
        .collect()
}

/// The up-order sort key for a non-`CreateTable` change. A two-level key so a
/// **replacement** `DropIndex` (its name is also re-added) sorts *just before* the
/// `AddIndex` bucket while every other change keeps its plain bucket.
fn up_sort_key(change: &SchemaChange, replaced: &BTreeSet<String>) -> (u8, u8) {
    match change {
        // Replacement drop: same bucket as AddIndex, but ordered before it.
        SchemaChange::DropIndex { index, .. } if replaced.contains(&index.name) => (3, 0),
        SchemaChange::AddIndex { .. } => (3, 1),
        other => (up_bucket(other), 1),
    }
}

/// Topologically order `creates` (all `CreateTable` changes) so a table referenced
/// by another's inline `REFERENCES` is created first. Only intra-batch
/// dependencies matter — a reference to a pre-existing baseline table imposes no
/// ordering. Deterministic (Kahn's algorithm, always taking the
/// lexicographically-smallest ready table).
///
/// # Errors
///
/// Returns [`EmitError::CyclicTableDependencies`] if the new tables form a
/// reference cycle (inline foreign keys cannot express one).
fn topo_sort_creates(creates: &mut [&SchemaChange]) -> Result<(), EmitError> {
    if creates.len() < 2 {
        return Ok(());
    }
    let tables: BTreeMap<&str, &Table> = creates
        .iter()
        .filter_map(|c| match c {
            SchemaChange::CreateTable(t) => Some((t.name.as_str(), t)),
            _ => None,
        })
        .collect();
    let names: BTreeSet<&str> = tables.keys().copied().collect();

    // deps[name] = the in-batch tables `name` references (must be created first).
    let mut deps: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
    for (&name, table) in &tables {
        let mut d = BTreeSet::new();
        for col in &table.columns {
            if let Some(fk) = &col.references {
                let target = fk.table.as_str();
                if target != name && names.contains(target) {
                    d.insert(target);
                }
            }
        }
        deps.insert(name, d);
    }

    // Kahn: repeatedly place the smallest name whose deps are all already placed.
    let mut remaining: BTreeSet<&str> = names;
    let mut order: BTreeMap<&str, usize> = BTreeMap::new();
    while !remaining.is_empty() {
        let ready = remaining
            .iter()
            .copied()
            .find(|n| deps[n].iter().all(|d| !remaining.contains(d)));
        if let Some(n) = ready {
            order.insert(n, order.len());
            remaining.remove(n);
        } else {
            let mut cyc: Vec<String> = remaining.iter().map(|s| (*s).to_owned()).collect();
            cyc.sort();
            return Err(EmitError::CyclicTableDependencies { tables: cyc });
        }
    }

    creates.sort_by_key(|c| match c {
        SchemaChange::CreateTable(t) => order.get(t.name.as_str()).copied().unwrap_or(usize::MAX),
        _ => usize::MAX,
    });
    Ok(())
}

/// Topologically order `drops` (all `DropTable` changes) in **reverse** dependency
/// order so a table that references another (via its own baseline inline FK) is
/// dropped **before** the table it references — PG rejects dropping a referenced
/// table while a referencing one still exists. The dependency graph is built from
/// the dropped tables' baseline FKs (carried on the [`SchemaChange::DropTable`]
/// payload). Only intra-batch dependencies matter: a retained referencer is a
/// separate concern handled by [`guard_plan`]'s inbound-FK refusal. Deterministic
/// (Kahn's algorithm, always taking the lexicographically-smallest ready table).
///
/// # Errors
///
/// Returns [`EmitError::CyclicTableDependencies`] if the dropped tables form a
/// reference cycle (the same refusal the [`SchemaChange::CreateTable`] path uses).
fn topo_sort_drops(drops: &mut [&SchemaChange]) -> Result<(), EmitError> {
    if drops.len() < 2 {
        return Ok(());
    }
    let tables: BTreeMap<&str, &Table> = drops
        .iter()
        .filter_map(|c| match c {
            SchemaChange::DropTable(t) => Some((t.name.as_str(), t)),
            _ => None,
        })
        .collect();
    let names: BTreeSet<&str> = tables.keys().copied().collect();

    // deps[name] = the in-batch tables that must be dropped BEFORE `name`, i.e.
    // the tables that reference `name` (referencers drop first). This is the edge
    // set of `topo_sort_creates` inverted.
    let mut deps: BTreeMap<&str, BTreeSet<&str>> =
        names.iter().map(|&n| (n, BTreeSet::new())).collect();
    for (&name, table) in &tables {
        for col in &table.columns {
            if let Some(fk) = &col.references {
                let target = fk.table.as_str();
                if target != name && names.contains(target) {
                    // `name` references `target` ⇒ `name` must drop before `target`.
                    deps.get_mut(target)
                        .expect("target is an in-batch name")
                        .insert(name);
                }
            }
        }
    }

    // Kahn: repeatedly place the smallest name whose deps are all already placed.
    let mut remaining: BTreeSet<&str> = names;
    let mut order: BTreeMap<&str, usize> = BTreeMap::new();
    while !remaining.is_empty() {
        let ready = remaining
            .iter()
            .copied()
            .find(|n| deps[n].iter().all(|d| !remaining.contains(d)));
        if let Some(n) = ready {
            order.insert(n, order.len());
            remaining.remove(n);
        } else {
            let mut cyc: Vec<String> = remaining.iter().map(|s| (*s).to_owned()).collect();
            cyc.sort();
            return Err(EmitError::CyclicTableDependencies { tables: cyc });
        }
    }

    drops.sort_by_key(|c| match c {
        SchemaChange::DropTable(t) => order.get(t.name.as_str()).copied().unwrap_or(usize::MAX),
        _ => usize::MAX,
    });
    Ok(())
}

/// The canonical up-order bucket for a change (lower = earlier).
const fn up_bucket(change: &SchemaChange) -> u8 {
    match change {
        SchemaChange::CreateTable(_) => 0,
        SchemaChange::AddColumn { .. } => 1,
        SchemaChange::AlterColumnType { .. }
        | SchemaChange::SetNotNull { .. }
        | SchemaChange::DropNotNull { .. }
        | SchemaChange::SetDefault { .. } => 2,
        SchemaChange::AddIndex { .. } => 3,
        SchemaChange::AddCheck { .. } | SchemaChange::AddForeignKey { .. } => 4,
        SchemaChange::DropIndex { .. } => 5,
        SchemaChange::DropColumn { .. } => 6,
        SchemaChange::DropTable(_) => 7,
        // Non-emittable markers; the guard refuses them before emission is reached.
        SchemaChange::PrimaryKeyChange { .. }
        | SchemaChange::ForeignKeyChange { .. }
        | SchemaChange::IdentityChange { .. }
        | SchemaChange::DropTableBlockedByInboundFk { .. }
        | SchemaChange::AlterColumnTypeBlockedByFk { .. }
        | SchemaChange::AddForeignKeyToExistingColumn { .. }
        | SchemaChange::CreateTableBlockedBySkippedField { .. } => 9,
    }
}

/// Render a single change's forward SQL.
fn emit_change_up(change: &SchemaChange, backend: Backend) -> Result<String, EmitError> {
    match change {
        SchemaChange::CreateTable(table) => Ok(emit_create_table(table, backend)),
        SchemaChange::DropTable(table) => Ok(format!(
            "-- autumn-safety: this DROP TABLE is not checked against generated \
             #[belongs_to(...)] association foreign keys, which the offline snapshot cannot see; \
             if a retained table has an invisible association FK to `{0}`, this will fail to apply \
             -- verify with schema introspection or drop the FK manually first\n\
             DROP TABLE {0};\n",
            table.name
        )),
        SchemaChange::AddColumn { table, column } => emit_add_column(table, column, backend),
        SchemaChange::DropColumn { table, column } => Ok(format!(
            "ALTER TABLE {table} DROP COLUMN {};\n",
            column.name
        )),
        SchemaChange::AlterColumnType {
            table, column, to, ..
        } => {
            require_pg(backend, "AlterColumnType")?;
            Ok(format!(
                "ALTER TABLE {table} ALTER COLUMN {column} TYPE {};\n",
                to.sql_type(backend)
            ))
        }
        SchemaChange::SetNotNull { table, column } => {
            require_pg(backend, "SetNotNull")?;
            Ok(format!(
                "-- autumn-safety: potentially-blocking -- existing NULLs must be backfilled first\n\
                 ALTER TABLE {table} ALTER COLUMN {column} SET NOT NULL;\n"
            ))
        }
        SchemaChange::DropNotNull { table, column } => {
            require_pg(backend, "DropNotNull")?;
            Ok(format!(
                "ALTER TABLE {table} ALTER COLUMN {column} DROP NOT NULL;\n"
            ))
        }
        SchemaChange::SetDefault {
            table, column, to, ..
        } => {
            require_pg(backend, "SetDefault")?;
            Ok(format!(
                "ALTER TABLE {table} ALTER COLUMN {column} SET DEFAULT {};\n",
                default_sql(to, backend)
            ))
        }
        SchemaChange::AddIndex { table, index } => Ok(format!("{}\n", index_sql(table, index))),
        SchemaChange::DropIndex { index, .. } => Ok(format!("DROP INDEX {};\n", index.name)),
        SchemaChange::AddCheck { table, check } => {
            require_pg(backend, "AddCheck")?;
            Ok(check.name.as_ref().map_or_else(
                || format!("ALTER TABLE {table} ADD CHECK ({});\n", check.expression),
                |name| {
                    format!(
                        "ALTER TABLE {table} ADD CONSTRAINT {name} CHECK ({});\n",
                        check.expression
                    )
                },
            ))
        }
        SchemaChange::AddForeignKey {
            table,
            column,
            foreign_key,
        } => {
            require_pg(backend, "AddForeignKey")?;
            let constraint = bounded_pg_identifier(&format!("{table}_{column}_fkey"));
            Ok(format!(
                "ALTER TABLE {table} ADD CONSTRAINT {constraint} \
                 FOREIGN KEY ({column}) REFERENCES {}({});\n",
                foreign_key.table, foreign_key.column
            ))
        }
        // Non-emittable markers: the guard refuses them, so they never reach here
        // in the command flow. Render nothing defensively rather than panicking.
        SchemaChange::PrimaryKeyChange { .. }
        | SchemaChange::ForeignKeyChange { .. }
        | SchemaChange::IdentityChange { .. }
        | SchemaChange::DropTableBlockedByInboundFk { .. }
        | SchemaChange::AlterColumnTypeBlockedByFk { .. }
        | SchemaChange::AddForeignKeyToExistingColumn { .. }
        | SchemaChange::CreateTableBlockedBySkippedField { .. } => Ok(String::new()),
    }
}

/// Render a single change's reverse SQL, with an `-- irreversible:` / `-- manual:`
/// marker where the round-trip is not clean.
fn emit_change_down(change: &SchemaChange, backend: Backend) -> Result<String, EmitError> {
    match change {
        SchemaChange::CreateTable(table) => Ok(format!("DROP TABLE {};\n", table.name)),
        SchemaChange::DropTable(table) => {
            let recreate = emit_create_table(table, backend);
            Ok(format!(
                "-- irreversible: table data dropped by this migration cannot be restored\n\
                 {recreate}"
            ))
        }
        SchemaChange::AddColumn { table, column } => Ok(format!(
            "ALTER TABLE {table} DROP COLUMN {};\n",
            column.name
        )),
        SchemaChange::DropColumn { table, column } => {
            let readd = emit_add_column(table, column, backend)?;
            Ok(format!(
                "-- irreversible: column data dropped by this migration cannot be restored\n\
                 {readd}"
            ))
        }
        SchemaChange::AlterColumnType {
            table,
            column,
            from,
            ..
        } => {
            require_pg(backend, "AlterColumnType")?;
            Ok(format!(
                "-- irreversible: a narrowing type change may have lost data; review before rolling back\n\
                 ALTER TABLE {table} ALTER COLUMN {column} TYPE {};\n",
                from.sql_type(backend)
            ))
        }
        SchemaChange::SetNotNull { table, column } => {
            require_pg(backend, "SetNotNull")?;
            Ok(format!(
                "ALTER TABLE {table} ALTER COLUMN {column} DROP NOT NULL;\n"
            ))
        }
        SchemaChange::DropNotNull { table, column } => {
            require_pg(backend, "DropNotNull")?;
            Ok(format!(
                "-- potentially-blocking: rolling back re-adds NOT NULL; existing NULL rows will block it\n\
                 ALTER TABLE {table} ALTER COLUMN {column} SET NOT NULL;\n"
            ))
        }
        SchemaChange::SetDefault {
            table,
            column,
            from,
            ..
        } => {
            require_pg(backend, "SetDefault")?;
            Ok(from.as_ref().map_or_else(
                || format!("ALTER TABLE {table} ALTER COLUMN {column} DROP DEFAULT;\n"),
                |d| {
                    format!(
                        "ALTER TABLE {table} ALTER COLUMN {column} SET DEFAULT {};\n",
                        default_sql(d, backend)
                    )
                },
            ))
        }
        SchemaChange::AddIndex { index, .. } => Ok(format!("DROP INDEX {};\n", index.name)),
        SchemaChange::DropIndex { table, index } => Ok(format!("{}\n", index_sql(table, index))),
        SchemaChange::AddCheck { table, check } => Ok(check.name.as_ref().map_or_else(
            || "-- manual: unnamed CHECK cannot be auto-dropped\n".to_owned(),
            |name| format!("ALTER TABLE {table} DROP CONSTRAINT {name};\n"),
        )),
        SchemaChange::AddForeignKey { table, column, .. } => {
            let constraint = bounded_pg_identifier(&format!("{table}_{column}_fkey"));
            Ok(format!(
                "ALTER TABLE {table} DROP CONSTRAINT {constraint};\n"
            ))
        }
        SchemaChange::PrimaryKeyChange { .. }
        | SchemaChange::ForeignKeyChange { .. }
        | SchemaChange::IdentityChange { .. }
        | SchemaChange::DropTableBlockedByInboundFk { .. }
        | SchemaChange::AlterColumnTypeBlockedByFk { .. }
        | SchemaChange::AddForeignKeyToExistingColumn { .. }
        | SchemaChange::CreateTableBlockedBySkippedField { .. } => Ok(String::new()),
    }
}

/// Guard the pg-only `ALTER`-family renderers: `SQLite` needs slice 5's
/// table-rebuild, so it is an explicit unsupported error here.
const fn require_pg(backend: Backend, kind: &'static str) -> Result<(), EmitError> {
    match backend {
        Backend::Postgres => Ok(()),
        Backend::Sqlite => Err(EmitError::UnsupportedOnBackend { kind, backend }),
    }
}

/// Render a `CREATE TABLE` (reconstructing a single int/uuid PK via
/// [`IdKind::pk_sql`] so `BIGSERIAL` / `gen_random_uuid()` are not lost), followed
/// by one `CREATE [UNIQUE] INDEX` per index (name-sorted).
///
/// A `CREATE TABLE` is always renderable (the portable `SQLite` subset covers it),
/// so this is infallible.
fn emit_create_table(table: &Table, backend: Backend) -> String {
    let mut out = render_create_table_body(&table.name, table, backend);

    // Indexes, name-sorted for determinism.
    let mut indexes: Vec<&Index> = table.indexes.iter().collect();
    indexes.sort_by(|a, b| a.name.cmp(&b.name));
    for index in indexes {
        let _ = writeln!(out, "{}", index_sql(&table.name, index));
    }
    out
}

/// Render just the `CREATE TABLE {name} (…columns/PK/checks…);` statement (no index
/// `CREATE`s) for `table`'s shape, under an arbitrary `name`.
///
/// Split out of [`emit_create_table`] so the `SQLite` table-rebuild path can emit
/// the `{table}__autumn_new` staging table (whose indexes are recreated separately,
/// after the rename). [`emit_create_table`] recomposes this body plus its indexes,
/// so its output is unchanged.
fn render_create_table_body(name: &str, table: &Table, backend: Backend) -> String {
    let single_pk = single_pk_column(table);
    let mut lines: Vec<String> = Vec::with_capacity(table.columns.len() + 2);

    for col in &table.columns {
        if let Some((pk_col, kind)) = &single_pk
            && pk_col.name == col.name
        {
            lines.push(format!("    {} {}", col.name, kind.pk_sql(backend)));
        } else {
            // Render inline `UNIQUE` for a `Column.unique` column whose uniqueness is
            // NOT already owned by a separate index (the SQLite inline-`UNIQUE` fold),
            // so a rebuild/rollback preserves it without double-emitting for a model
            // `#[unique]` field (which has a covering named index).
            let render_unique = col.unique && !column_covered_by_unique_index(table, &col.name);
            lines.push(format!(
                "    {}",
                render_column_def(col, backend, render_unique)
            ));
        }
    }

    // Composite / exotic PK: a trailing table-level clause, columns rendered
    // normally above.
    if single_pk.is_none() && !table.primary_key.is_empty() {
        lines.push(format!(
            "    PRIMARY KEY ({})",
            table.primary_key.join(", ")
        ));
    }

    // Table-level checks (rare — the parser emits none today).
    for check in &table.checks {
        match &check.name {
            Some(cname) => lines.push(format!(
                "    CONSTRAINT {cname} CHECK ({})",
                check.expression
            )),
            None => lines.push(format!("    CHECK ({})", check.expression)),
        }
    }

    format!("CREATE TABLE {name} (\n{}\n);\n", lines.join(",\n"))
}

/// Render an `ALTER TABLE … ADD COLUMN`, mirroring the generator's house
/// convention for the `-- autumn-safety` comment on a `NOT NULL`-without-default
/// column.
///
/// **Index ownership:** this renderer emits **only** the column, never a
/// `CREATE INDEX`. A reference column's auto-index (`idx_<table>_<column>`) is
/// folded into the parser's table index set, so it arrives as its own
/// [`SchemaChange::AddIndex`] and is rendered by [`index_sql`] exactly once. If
/// `ADD COLUMN` also rendered the index inline it would be created twice and the
/// migration would fail. `diff_indexes`/`AddIndex` (and, for a brand-new table,
/// [`emit_create_table`]) is the single owner of index creation.
fn emit_add_column(table: &str, column: &Column, backend: Backend) -> Result<String, EmitError> {
    // `SQLite` rejects `ADD COLUMN … NOT NULL` without a DEFAULT — a slice-5 concern.
    if backend == Backend::Sqlite && !column.nullable && column.default.is_none() {
        return Err(EmitError::UnsupportedOnBackend {
            kind: "AddColumn (NOT NULL without a default on SQLite)",
            backend,
        });
    }

    let mut out = String::new();
    if !column.nullable && column.default.is_none() {
        let _ = writeln!(
            out,
            "-- autumn-safety: potentially-blocking -- add a DEFAULT or backfill existing rows before enforcing NOT NULL"
        );
    }
    let _ = writeln!(
        out,
        "ALTER TABLE {table} ADD COLUMN {};",
        // ADD COLUMN never renders inline UNIQUE: a model `#[unique]` column arrives
        // with a separate `AddIndex` that owns the uniqueness (SQLite column changes
        // go through the table-rebuild path, not ADD COLUMN).
        render_column_def(column, backend, false)
    );
    Ok(out)
}

/// Render a column definition body: `{name} {type} {NOT NULL|NULL} [REFERENCES
/// t(c)] [DEFAULT d]`. Shared by `CREATE TABLE` (non-PK columns) and `ADD
/// COLUMN`.
fn render_column_def(column: &Column, backend: Backend, render_unique: bool) -> String {
    let mut def = format!(
        "{} {} {}",
        column.name,
        column.ty.sql_type(backend),
        nullability(column.nullable)
    );
    // Inline single-column `UNIQUE` — rendered ONLY when the caller says so. It is
    // emitted for a `Column.unique` column that is NOT already covered by a separate
    // unique `Index` in the table (the SQLite brownfield inline-`UNIQUE` fold, whose
    // constraint auto-index is deliberately not an `Index`). For a model `#[unique]`
    // field — which carries BOTH `Column.unique` AND a covering named `Index` — the
    // caller passes `false`, so the index owns the uniqueness and it is never
    // double-emitted (zero golden churn).
    if render_unique {
        def.push_str(" UNIQUE");
    }
    if let Some(fk) = &column.references {
        let _ = write!(def, " REFERENCES {}({})", fk.table, fk.column);
    }
    if let Some(default) = &column.default {
        let _ = write!(def, " DEFAULT {}", default_sql(default, backend));
    }
    def
}

/// Whether some unique, non-partial `Index` in `table` keys on **exactly** the single
/// column `col` — i.e. the column's uniqueness is already owned by a separate index,
/// so it must NOT also be rendered as an inline `UNIQUE` (double-emit).
fn column_covered_by_unique_index(table: &Table, col: &str) -> bool {
    table
        .indexes
        .iter()
        .any(|idx| full_unique_key_columns(idx).is_some_and(|k| k.len() == 1 && k.contains(col)))
}

/// `CREATE [UNIQUE] INDEX {name} ON {table} ({cols});`.
///
/// When the index carries a raw `definition` (an expression/partial index
/// preserved verbatim by introspection), that full `pg_get_indexdef` statement is
/// emitted verbatim — with exactly one trailing `;` appended, since
/// `pg_get_indexdef` output has none — instead of reconstructing a
/// `CREATE INDEX … (columns)` form that cannot express the expression/predicate.
fn index_sql(table: &str, index: &Index) -> String {
    if let Some(def) = &index.definition {
        let def = def.trim_end().trim_end_matches(';');
        return format!("{def};");
    }
    let unique = if index.unique { "UNIQUE " } else { "" };
    format!(
        "CREATE {unique}INDEX {} ON {table} ({});",
        index.name,
        index.columns.join(", ")
    )
}

/// The nullability clause for a column.
const fn nullability(nullable: bool) -> &'static str {
    if nullable { "NULL" } else { "NOT NULL" }
}

/// Render a column default to SQL for `backend` (`Now` → `NOW()` on Postgres,
/// `CURRENT_TIMESTAMP` on `SQLite`; `Sql(s)` verbatim).
fn default_sql(default: &ColumnDefault, backend: Backend) -> String {
    match default {
        ColumnDefault::Now => match backend {
            Backend::Postgres => "NOW()".to_owned(),
            Backend::Sqlite => "CURRENT_TIMESTAMP".to_owned(),
        },
        ColumnDefault::Sql(sql) => sql.clone(),
    }
}

/// The single-column primary key column and its reconstructed [`IdKind`], if the
/// table has exactly one PK column that is an int/uuid id.
///
/// The IR does not store `IdKind` on `Table` (a `BigSerial` PK is a
/// `Column { ty: Int64, primary_key: true, default: None }`), so naively emitting
/// it as `BIGINT` would silently drop auto-increment. This mirrors the
/// generator + parser conventions to recover it. Returns `None` for a composite
/// PK or a non-int/uuid PK → the caller falls back to a table-level `PRIMARY KEY
/// (…)` clause.
fn single_pk_column(table: &Table) -> Option<(&Column, IdKind)> {
    if table.primary_key.len() != 1 {
        return None;
    }
    let name = &table.primary_key[0];
    let column = table.columns.iter().find(|c| &c.name == name)?;
    pk_kind_for(column).map(|kind| (column, kind))
}

/// The [`SerialKind`] marker of a table's single-column primary key, or `None` for
/// a composite PK, no PK, a UUID single PK, or a legacy/unknown snapshot (the marker
/// predates the field). A plain integer PK carries `Some(Plain)`; an owned-sequence
/// id carries `Some(Serial)`/`Some(BigSerial)`. Used by [`serial_kinds_conflict`] /
/// [`diff_table`] to detect a plain-int-PK ↔ serial-PK id-generation change (which
/// is refused like any other primary-key change) while a legacy `None` never drifts.
fn single_pk_serial(table: &Table) -> Option<SerialKind> {
    if table.primary_key.len() != 1 {
        return None;
    }
    let name = &table.primary_key[0];
    table.columns.iter().find(|c| &c.name == name)?.serial
}

/// Whether the two tables' single-column-PK [`SerialKind`] markers CONFLICT — i.e.
/// both sides carry an **explicit** marker and they differ.
///
/// The marker is three-state: `None` is *unknown* (a snapshot written before the
/// field existed — serde default — or a non-integer/composite PK), while
/// `Some(_)` is an explicit introspected/parsed id-generation strategy. A conflict
/// is flagged ONLY when both sides are `Some(_)` and differ, so:
///   * a legacy snapshot (`None`) vs the parser's `Some(BigSerial)` → NO drift
///     (backward-compatibility: an existing project's pre-marker snapshot keeps
///     round-tripping clean instead of a spurious refused primary-key change);
///   * a fresh `BIGSERIAL` pull (`Some(BigSerial)`) vs model `Some(BigSerial)` →
///     no drift;
///   * a genuine plain-`BIGINT`-PK pull (`Some(Plain)`) vs model `Some(BigSerial)`
///     → drift (fidelity preserved).
fn serial_kinds_conflict(base: &Table, want: &Table) -> bool {
    matches!(
        (single_pk_serial(base), single_pk_serial(want)),
        (Some(a), Some(b)) if a != b
    )
}

/// Derive the id-generation strategy for a single-column PK:
///   `Int64` PK, no default                      → `BigSerial`
///   `Int32` PK, `nextval(...)` default           → `Serial` (a brownfield `SERIAL` id)
///   `Uuid`  PK, `gen_random_uuid()` default      → `Uuid`
/// Any other PK column → `None` (rendered normally with a table-level clause).
///
/// The `Int32`/`Serial` case only ever arises for a **brownfield-introspected**
/// table: the model DSL never produces an int4 PK, so this cannot conflict with a
/// model diff. Introspection deliberately preserves the `nextval(...)` default on an
/// int4 PK (see `introspect::normalize_serial_pk_default`) precisely so it is
/// recognized here and recreated as `SERIAL PRIMARY KEY` (auto-increment) rather
/// than a plain `INTEGER PRIMARY KEY`. An int4 PK with NO default falls through to
/// `None` → a plain integer PK (no auto-increment), which is correct.
///
/// The `Uuid` convention is likewise **default-gated**: the `IdKind::Uuid` shape
/// renders `UUID PRIMARY KEY DEFAULT gen_random_uuid()`, so it is only applied when
/// the pulled column's stored default is *exactly* that convention (the value the
/// model parser records — see `parse::convention_default` — so the round-trip stays
/// clean). A brownfield UUID PK whose default is a different expression (e.g.
/// `uuid_generate_v4()`) or is absent entirely falls through to `None`: it renders
/// as an ordinary `UUID` column preserving its real default (or lack of one), with
/// its primary key expressed via the trailing table-level `PRIMARY KEY (col)` clause
/// — so recreation (e.g. the down migration for a dropped table) never silently
/// swaps its UUID-generation behavior for `gen_random_uuid()` or adds a default
/// where none existed.
fn pk_kind_for(column: &Column) -> Option<IdKind> {
    // An EXPLICIT `Plain` serial marker (a brownfield plain `BIGINT`/`INTEGER
    // PRIMARY KEY` with no owned sequence — populated by both introspectors, never
    // by the model parser) must NOT reconstruct as `BIGSERIAL`/`AUTOINCREMENT`: that
    // would fabricate auto-increment (and a `sqlite_sequence` row) on a table
    // rebuild or `DropTable` rollback, silently changing id-generation behavior. The
    // `None` path renders it as an ordinary integer column plus a table-level
    // `PRIMARY KEY (col)` clause — a plain PK with no sequence/AUTOINCREMENT. A
    // legacy/unknown `None` marker keeps the historical `BigSerial` behavior for
    // back-compat (`serial_kinds_conflict` treats a legacy `None` as compatible, so
    // this only ever fires for an explicitly-`Plain`-marked pull).
    if column.serial == Some(SerialKind::Plain) {
        return None;
    }
    match &column.ty {
        ColumnType::Int64 if column.default.is_none() => Some(IdKind::BigSerial),
        ColumnType::Int32 if is_nextval_default(column) => Some(IdKind::Serial),
        ColumnType::Uuid if is_convention_uuid_default(column) => Some(IdKind::Uuid),
        _ => None,
    }
}

/// Whether a UUID primary-key column's stored default is *exactly* the Autumn model
/// convention `gen_random_uuid()` — the value `parse::convention_default` records for
/// a Postgres UUID `#[id]` and the string introspection preserves verbatim
/// (`normalize_default` keeps it as-is). Only then may the DDL emitter collapse the
/// column into the `IdKind::Uuid` shape (`UUID PRIMARY KEY DEFAULT
/// gen_random_uuid()`); a UUID PK with any other default — or none — is rendered as an
/// ordinary column so its true generation behavior is never silently rewritten.
fn is_convention_uuid_default(column: &Column) -> bool {
    matches!(
        &column.default,
        Some(ColumnDefault::Sql(sql)) if sql.trim() == "gen_random_uuid()"
    )
}

/// Whether a column's default is a `nextval(...)` sequence default (a `SERIAL`
/// auto-increment default), which the DDL emitter reconstructs by suppressing the
/// explicit default and rendering the `SERIAL`/`BIGSERIAL` keyword instead.
fn is_nextval_default(column: &Column) -> bool {
    matches!(
        &column.default,
        Some(ColumnDefault::Sql(sql)) if sql.trim_start().to_ascii_lowercase().starts_with("nextval(")
    )
}

// ---------------------------------------------------------------------------
// Human-readable summary
// ---------------------------------------------------------------------------

/// A human-readable plan summary for the default (no `--write-migration`) output.
#[must_use]
pub fn describe_plan(plan: &MigrationPlan) -> String {
    let backend = match plan.backend {
        Backend::Postgres => "postgres",
        Backend::Sqlite => "sqlite",
    };
    let mut out = format!(
        "Migration plan ({backend}): {} change(s)\n",
        plan.changes.len()
    );
    for change in &plan.changes {
        let _ = writeln!(out, "  {}", describe_change(change));
    }
    out
}

/// A one-line description of a single change.
fn describe_change(change: &SchemaChange) -> String {
    match change {
        SchemaChange::CreateTable(t) => format!("+ CREATE TABLE {}", t.name),
        SchemaChange::DropTable(t) => format!("- DROP TABLE {}", t.name),
        SchemaChange::AddColumn { table, column } => {
            format!("+ ADD COLUMN {table}.{}", column.name)
        }
        SchemaChange::DropColumn { table, column } => {
            format!("- DROP COLUMN {table}.{}", column.name)
        }
        SchemaChange::AlterColumnType {
            table,
            column,
            from,
            to,
        } => format!(
            "~ ALTER COLUMN {table}.{column} TYPE {} (was {})",
            to.sql_type(Backend::Postgres),
            from.sql_type(Backend::Postgres)
        ),
        SchemaChange::SetNotNull { table, column } => {
            format!("~ SET NOT NULL {table}.{column}")
        }
        SchemaChange::DropNotNull { table, column } => {
            format!("~ DROP NOT NULL {table}.{column}")
        }
        SchemaChange::SetDefault { table, column, .. } => {
            format!("~ SET DEFAULT {table}.{column}")
        }
        SchemaChange::AddForeignKey { table, column, .. } => {
            format!("+ ADD FOREIGN KEY {table}.{column}")
        }
        SchemaChange::AddIndex { table, index } => {
            format!("+ ADD INDEX {} ON {table}", index.name)
        }
        SchemaChange::DropIndex { table, index } => {
            format!("- DROP INDEX {} ON {table}", index.name)
        }
        SchemaChange::AddCheck { table, check } => format!(
            "+ ADD CHECK {} ON {table}",
            check.name.as_deref().unwrap_or("(unnamed)")
        ),
        SchemaChange::PrimaryKeyChange { table } => {
            format!("! PRIMARY KEY CHANGE on {table} (refused)")
        }
        SchemaChange::ForeignKeyChange { table, column } => {
            format!("! FOREIGN KEY RETARGET on {table}.{column} (refused)")
        }
        SchemaChange::IdentityChange { table, column } => {
            format!("! IDENTITY CHANGE on {table}.{column} (refused)")
        }
        SchemaChange::DropTableBlockedByInboundFk {
            table,
            referencing_table,
            referencing_column,
        } => format!(
            "! DROP TABLE {table} blocked by retained FK {referencing_table}.{referencing_column} (refused)"
        ),
        SchemaChange::AlterColumnTypeBlockedByFk { table, column } => {
            format!(
                "! ALTER COLUMN {table}.{column} TYPE blocked by foreign-key constraint (refused)"
            )
        }
        SchemaChange::AddForeignKeyToExistingColumn { table, column } => {
            format!("! ADD FOREIGN KEY on pre-existing column {table}.{column} (refused)")
        }
        SchemaChange::CreateTableBlockedBySkippedField { table, fields } => {
            format!(
                "! CREATE TABLE {table} blocked by parser-skipped field(s) [{}] (refused)",
                fields.join(", ")
            )
        }
    }
}

#[cfg(test)]
#[allow(clippy::needless_raw_string_hashes)]
mod tests {
    use super::*;
    use autumn_schema_core::{ForeignKey, Table};

    use crate::schema::parse::SchemaDiagnostic;

    // -- fixture helpers -----------------------------------------------------

    fn col(name: &str, ty: ColumnType) -> Column {
        Column::new(name, ty)
    }

    /// A `posts` table with an `id` `BigSerial` PK plus the given extra columns.
    fn posts_with(columns: Vec<Column>) -> Table {
        let mut t = Table::new("posts", Backend::Postgres);
        let mut id = col("id", ColumnType::Int64);
        id.primary_key = true;
        t.primary_key.push("id".to_owned());
        t.columns.push(id);
        t.columns.extend(columns);
        t
    }

    /// A managed table `name` with a `BigSerial` `id` PK plus one extra column
    /// (used to build cross-referencing new tables in the topo-order tests).
    fn posts_ref_table(name: &str, extra: Column) -> Table {
        let mut t = Table::new(name, Backend::Postgres);
        let mut id = col("id", ColumnType::Int64);
        id.primary_key = true;
        t.primary_key.push("id".to_owned());
        t.columns.push(id);
        t.columns.push(extra);
        t
    }

    fn parsed(tables: Vec<Table>, diagnostics: Vec<SchemaDiagnostic>) -> ParsedSchema {
        ParsedSchema {
            tables,
            diagnostics,
        }
    }

    fn diag(model: &str, table: &str, field: &str) -> SchemaDiagnostic {
        SchemaDiagnostic {
            model: model.to_owned(),
            table: table.to_owned(),
            field: field.to_owned(),
            rust_type: "Unknown".to_owned(),
            message: format!("skipped {model}.{field}"),
        }
    }

    const DEFAULT_OPTS: DiffOptions = DiffOptions {
        allow_destructive: false,
        definitions_authoritative: false,
    };
    const ALLOW: DiffOptions = DiffOptions {
        allow_destructive: true,
        definitions_authoritative: false,
    };
    const AUTHORITATIVE: DiffOptions = DiffOptions {
        allow_destructive: false,
        definitions_authoritative: true,
    };

    /// `posts` with an explicit `serial` marker on its `id` PK (index 0).
    fn posts_with_id_serial(kind: Option<SerialKind>) -> Table {
        let mut t = posts_with(vec![]);
        t.columns[0].serial = kind;
        t
    }

    // -- serial-marker three-state compatibility -----------------------------

    #[test]
    fn serial_marker_legacy_none_is_compatible_with_parser_bigserial() {
        // A pre-marker (legacy) snapshot deserializes `id.serial = None`; the parser
        // marks the model `#[id]` as `Some(BigSerial)`. This must NOT flag a
        // primary-key change — otherwise every existing project breaks until it
        // rewrites its snapshot. Verified in BOTH diff modes.
        let legacy = vec![posts_with_id_serial(None)];
        let model = posts_with_id_serial(Some(SerialKind::BigSerial));
        for opts in [DEFAULT_OPTS, AUTHORITATIVE] {
            let plan = diff_schema(&legacy, &parsed(vec![model.clone()], vec![]), opts);
            assert!(
                !plan
                    .changes
                    .iter()
                    .any(|c| matches!(c, SchemaChange::PrimaryKeyChange { .. })),
                "legacy None vs Some(BigSerial) must be compatible ({opts:?}): {:?}",
                plan.changes
            );
        }
    }

    #[test]
    fn serial_marker_matching_bigserial_is_clean() {
        let base = vec![posts_with_id_serial(Some(SerialKind::BigSerial))];
        let want = posts_with_id_serial(Some(SerialKind::BigSerial));
        let plan = diff_schema(&base, &parsed(vec![want], vec![]), DEFAULT_OPTS);
        assert!(
            plan.changes.is_empty(),
            "matching markers: {:?}",
            plan.changes
        );
    }

    #[test]
    fn serial_marker_plain_conflicts_with_bigserial() {
        // A genuine plain-BIGINT-PK pull (`Some(Plain)`) vs a `BigSerial` model —
        // BOTH explicit — is a real id-generation change → refused primary-key change
        // (fidelity preserved).
        let base = vec![posts_with_id_serial(Some(SerialKind::Plain))];
        let want = posts_with_id_serial(Some(SerialKind::BigSerial));
        let plan = diff_schema(&base, &parsed(vec![want], vec![]), DEFAULT_OPTS);
        assert_eq!(
            plan.changes,
            vec![SchemaChange::PrimaryKeyChange {
                table: "posts".to_owned(),
            }]
        );
    }

    // -- identity-clause drift -----------------------------------------------

    #[test]
    fn identity_change_flagged_only_in_authoritative_diff() {
        // Two both-present introspections whose `id` identity clause differs
        // (`ALWAYS` dropped to a plain column). In an authoritative diff (doctor /
        // pull --dry-run) this is real drift → the refused `IdentityChange` marker;
        // in a model diff the parser cannot express identity, so a desired `None` is
        // "unknown, retained" (never drift).
        let mut base_id = posts_with_id_serial(Some(SerialKind::BigSerial));
        base_id.columns[0].identity = Some("ALWAYS".to_owned());
        let base = vec![base_id];
        let want = posts_with_id_serial(Some(SerialKind::BigSerial)); // identity: None

        let auth = diff_schema(&base, &parsed(vec![want.clone()], vec![]), AUTHORITATIVE);
        assert!(
            auth.changes.iter().any(|c| matches!(
                c,
                SchemaChange::IdentityChange { table, column } if table == "posts" && column == "id"
            )),
            "authoritative diff flags the identity change: {:?}",
            auth.changes
        );
        // The refused marker is rejected by the guard (no override).
        assert!(matches!(
            guard_plan(&auth, AUTHORITATIVE).unwrap_err(),
            DiffError::IdentityChange { .. }
        ));

        let model = diff_schema(&base, &parsed(vec![want], vec![]), DEFAULT_OPTS);
        assert!(
            !model
                .changes
                .iter()
                .any(|c| matches!(c, SchemaChange::IdentityChange { .. })),
            "model diff never flags an identity change: {:?}",
            model.changes
        );
    }

    // -- 13.1 structural diff ------------------------------------------------

    #[test]
    fn no_op_identical_returns_empty_plan() {
        let base = vec![posts_with(vec![col("body", ColumnType::Text)])];
        let want = parsed(
            vec![posts_with(vec![col("body", ColumnType::Text)])],
            vec![],
        );
        let plan = diff_schema(&base, &want, DEFAULT_OPTS);
        assert!(plan.is_empty(), "identical schemas → empty plan: {plan:?}");
    }

    #[test]
    fn add_column_emits_add_column() {
        let base = vec![posts_with(vec![])];
        let mut bio = col("bio", ColumnType::Text);
        bio.nullable = true;
        let want = parsed(vec![posts_with(vec![bio.clone()])], vec![]);
        let plan = diff_schema(&base, &want, DEFAULT_OPTS);
        assert_eq!(plan.changes.len(), 1);
        match &plan.changes[0] {
            SchemaChange::AddColumn { table, column } => {
                assert_eq!(table, "posts");
                assert_eq!(column, &bio);
            }
            other => panic!("expected AddColumn, got {other:?}"),
        }
    }

    #[test]
    fn drop_column_present_in_plan_carries_baseline_column() {
        let nickname = col("nickname", ColumnType::Text);
        let base = vec![posts_with(vec![nickname.clone()])];
        let want = parsed(vec![posts_with(vec![])], vec![]);
        let plan = diff_schema(&base, &want, DEFAULT_OPTS);
        assert_eq!(plan.changes.len(), 1);
        match &plan.changes[0] {
            SchemaChange::DropColumn { table, column } => {
                assert_eq!(table, "posts");
                assert_eq!(column, &nickname, "carries the baseline column for down");
            }
            other => panic!("expected DropColumn, got {other:?}"),
        }
    }

    #[test]
    fn alter_column_type_int32_to_int64() {
        let base = vec![posts_with(vec![col("views", ColumnType::Int32)])];
        let want = parsed(
            vec![posts_with(vec![col("views", ColumnType::Int64)])],
            vec![],
        );
        let plan = diff_schema(&base, &want, DEFAULT_OPTS);
        assert_eq!(
            plan.changes,
            vec![SchemaChange::AlterColumnType {
                table: "posts".to_owned(),
                column: "views".to_owned(),
                from: ColumnType::Int32,
                to: ColumnType::Int64,
            }]
        );
    }

    #[test]
    fn nullable_to_not_null_emits_set_not_null() {
        let mut nullable_bio = col("bio", ColumnType::Text);
        nullable_bio.nullable = true;
        let base = vec![posts_with(vec![nullable_bio])];
        let want = parsed(vec![posts_with(vec![col("bio", ColumnType::Text)])], vec![]);
        let plan = diff_schema(&base, &want, DEFAULT_OPTS);
        assert_eq!(
            plan.changes,
            vec![SchemaChange::SetNotNull {
                table: "posts".to_owned(),
                column: "bio".to_owned(),
            }]
        );
    }

    #[test]
    fn not_null_to_nullable_emits_drop_not_null() {
        let base = vec![posts_with(vec![col("bio", ColumnType::Text)])];
        let mut nullable_bio = col("bio", ColumnType::Text);
        nullable_bio.nullable = true;
        let want = parsed(vec![posts_with(vec![nullable_bio])], vec![]);
        let plan = diff_schema(&base, &want, DEFAULT_OPTS);
        assert_eq!(
            plan.changes,
            vec![SchemaChange::DropNotNull {
                table: "posts".to_owned(),
                column: "bio".to_owned(),
            }]
        );
    }

    #[test]
    fn set_default_added() {
        let base = vec![posts_with(vec![col("created_at", ColumnType::Timestamp)])];
        let mut created = col("created_at", ColumnType::Timestamp);
        created.default = Some(ColumnDefault::Now);
        let want = parsed(vec![posts_with(vec![created])], vec![]);
        let plan = diff_schema(&base, &want, DEFAULT_OPTS);
        assert_eq!(
            plan.changes,
            vec![SchemaChange::SetDefault {
                table: "posts".to_owned(),
                column: "created_at".to_owned(),
                to: ColumnDefault::Now,
                from: None,
            }]
        );
    }

    #[test]
    fn add_index_and_drop_index_by_name() {
        let idx = Index {
            name: "idx_posts_body".to_owned(),
            columns: vec!["body".to_owned()],
            unique: false,
            definition: None,
            is_partial: false,
            key_columns: Vec::new(),
        };
        // desired gains the index.
        let base = vec![posts_with(vec![col("body", ColumnType::Text)])];
        let mut want_table = posts_with(vec![col("body", ColumnType::Text)]);
        want_table.indexes.push(idx.clone());
        let plan = diff_schema(&base, &parsed(vec![want_table], vec![]), DEFAULT_OPTS);
        assert_eq!(
            plan.changes,
            vec![SchemaChange::AddIndex {
                table: "posts".to_owned(),
                index: idx.clone(),
            }]
        );

        // baseline has it, desired dropped it — DropIndex carries the baseline.
        let mut base_table = posts_with(vec![col("body", ColumnType::Text)]);
        base_table.indexes.push(idx.clone());
        let want = parsed(
            vec![posts_with(vec![col("body", ColumnType::Text)])],
            vec![],
        );
        let plan = diff_schema(&[base_table], &want, DEFAULT_OPTS);
        assert_eq!(
            plan.changes,
            vec![SchemaChange::DropIndex {
                table: "posts".to_owned(),
                index: idx,
            }]
        );
    }

    /// A `definition`-carrying (expression/partial) index that the model DSL can
    /// never express: an expression index on `lower(email)`.
    fn expr_index() -> Index {
        Index {
            name: "idx_posts_lower_body".to_owned(),
            columns: vec!["body".to_owned()],
            unique: false,
            definition: Some("CREATE INDEX idx_posts_lower_body ON posts (lower(body))".to_owned()),
            is_partial: false,
            key_columns: Vec::new(),
        }
    }

    /// Model diff (`DEFAULT_OPTS`, `definitions_authoritative: false`): a
    /// baseline-only `definition` index absent from the desired (model) side is
    /// **retained** — the model DSL cannot express it, so its absence is a parser
    /// gap, not a removal. NO `DropIndex` is emitted.
    #[test]
    fn model_diff_retains_baseline_only_definition_index() {
        let mut base_table = posts_with(vec![col("body", ColumnType::Text)]);
        base_table.indexes.push(expr_index());
        let want = parsed(
            vec![posts_with(vec![col("body", ColumnType::Text)])],
            vec![],
        );
        let plan = diff_schema(&[base_table], &want, DEFAULT_OPTS);
        assert!(
            !plan
                .changes
                .iter()
                .any(|c| matches!(c, SchemaChange::DropIndex { .. })),
            "model diff must retain (not drop) an unmodellable definition index; got {:?}",
            plan.changes
        );
    }

    /// Model diff: a baseline constraint-owned index (a brownfield `UNIQUE`
    /// constraint's auto-created index, retained by `schema pull` via its
    /// `definition`) absent from the desired (model) side is **retained** — no
    /// `DropIndex`. This is the load-bearing case: Postgres rejects dropping an
    /// index that backs a constraint, so emitting a `DROP INDEX` would produce a
    /// failing migration. Retention is purely `definition`-based, so the same code
    /// path that preserves expression/partial indexes preserves this one.
    #[test]
    fn model_diff_retains_constraint_owned_unique_index() {
        let constraint_idx = Index {
            name: "users_email_key".to_owned(),
            columns: vec!["email".to_owned()],
            unique: true,
            definition: Some(
                "CREATE UNIQUE INDEX users_email_key ON public.users USING btree (email)"
                    .to_owned(),
            ),
            is_partial: false,
            key_columns: vec!["email".to_owned()],
        };
        let mut base_table = posts_with(vec![col("email", ColumnType::Text)]);
        base_table.indexes.push(constraint_idx);
        let want = parsed(
            vec![posts_with(vec![col("email", ColumnType::Text)])],
            vec![],
        );
        let plan = diff_schema(&[base_table], &want, DEFAULT_OPTS);
        assert!(
            !plan
                .changes
                .iter()
                .any(|c| matches!(c, SchemaChange::DropIndex { .. })),
            "model diff must retain (not drop) a constraint-owned index; got {:?}",
            plan.changes
        );
    }

    /// Brownfield adoption (the P2 fix): a table pulled with `email TEXT UNIQUE`
    /// retains the constraint-owned unique index Postgres named `accounts_email_key`
    /// (`definition: Some(..)`, `unique`, columns `[email]`). The user then writes
    /// the natural model `Account { id, email }` with `#[unique]` on `email`, whose
    /// parser emits a differently-named unique index `idx_accounts_email_unique`
    /// over `[email]` (`definition: None`). A model diff must recognize the existing
    /// unique index as already satisfying the desired `#[unique]` — emitting NEITHER
    /// an `AddIndex` (which `guard_plan` would reject on a populated table) NOR a
    /// `DropIndex` for the retained constraint index. The plan must be clean.
    #[test]
    fn model_diff_existing_unique_index_satisfies_model_unique_by_columns() {
        let constraint_idx = Index {
            name: "accounts_email_key".to_owned(),
            columns: vec!["email".to_owned()],
            unique: true,
            definition: Some(
                "CREATE UNIQUE INDEX accounts_email_key ON public.accounts USING btree (email)"
                    .to_owned(),
            ),
            is_partial: false,
            key_columns: vec!["email".to_owned()],
        };
        let mut base_table = posts_with(vec![col("email", ColumnType::Text)]);
        base_table.indexes.push(constraint_idx);

        // Desired (model): the parser-emitted, differently-named unique index.
        let mut want_table = posts_with(vec![col("email", ColumnType::Text)]);
        want_table.indexes.push(Index {
            name: "idx_posts_email_unique".to_owned(),
            columns: vec!["email".to_owned()],
            unique: true,
            definition: None,
            is_partial: false,
            key_columns: Vec::new(),
        });
        let plan = diff_schema(
            &[base_table],
            &parsed(vec![want_table], vec![]),
            DEFAULT_OPTS,
        );
        assert!(
            plan.changes.is_empty(),
            "existing unique index over the same column set must satisfy the model \
             #[unique]; expected a clean plan, got {:?}",
            plan.changes
        );
        // And the whole plan must pass the policy guard (no dedup refusal).
        assert!(
            guard_plan(&plan, DEFAULT_OPTS).is_ok(),
            "clean plan must not trip guard_plan"
        );
    }

    /// P1 (retain covering unique): a baseline **definition-less** unique index under
    /// a NON-model name (`accounts_email_uq`) that covers the model's `#[unique]`
    /// (whose own `AddIndex` is suppressed as already-satisfied) must be RETAINED — a
    /// `DropIndex` would remove the only uniqueness enforcement with no replacement.
    /// The plan must be clean (no `DropIndex`, no `AddIndex`).
    #[test]
    fn model_diff_retains_differently_named_covering_unique_index() {
        let covering = Index {
            name: "accounts_email_uq".to_owned(),
            columns: vec!["email".to_owned()],
            unique: true,
            definition: None, // a plain CREATE UNIQUE INDEX, not a constraint index
            is_partial: false,
            key_columns: Vec::new(),
        };
        let mut base_table = posts_with(vec![col("email", ColumnType::Text)]);
        base_table.indexes.push(covering);
        // Model `#[unique] email` → a differently-named unique index.
        let mut want_table = posts_with(vec![col("email", ColumnType::Text)]);
        want_table.indexes.push(Index {
            name: "idx_posts_email_unique".to_owned(),
            columns: vec!["email".to_owned()],
            unique: true,
            definition: None,
            is_partial: false,
            key_columns: Vec::new(),
        });
        let plan = diff_schema(
            &[base_table],
            &parsed(vec![want_table], vec![]),
            DEFAULT_OPTS,
        );
        assert!(
            plan.changes.is_empty(),
            "a differently-named covering unique index is RETAINED and the model's \
             matching AddIndex suppressed (same uniqueness, different name): {:?}",
            plan.changes
        );
    }

    /// The retention is coverage-scoped: a baseline unique index the model does NOT
    /// cover (no matching `#[unique]`) still DROPS — the user removed the annotation.
    #[test]
    fn model_diff_unmatched_baseline_unique_index_still_drops() {
        let orphan = Index {
            name: "posts_nickname_uq".to_owned(),
            columns: vec!["nickname".to_owned()],
            unique: true,
            definition: None,
            is_partial: false,
            key_columns: Vec::new(),
        };
        let mut base_table = posts_with(vec![col("nickname", ColumnType::Text)]);
        base_table.indexes.push(orphan);
        // Model keeps the column but declares NO `#[unique]` on it.
        let want_table = posts_with(vec![col("nickname", ColumnType::Text)]);
        let plan = diff_schema(
            &[base_table],
            &parsed(vec![want_table], vec![]),
            DEFAULT_OPTS,
        );
        assert!(
            plan.changes.iter().any(|c| matches!(
                c,
                SchemaChange::DropIndex { index, .. } if index.name == "posts_nickname_uq"
            )),
            "an unmatched baseline unique index must still drop: {:?}",
            plan.changes
        );
    }

    /// The satisfaction is uniqueness-aware: a desired UNIQUE index over `[email]`
    /// is NOT satisfied by a baseline **non-unique** index over `[email]`, so the
    /// `AddIndex` is still emitted (the uniqueness is genuinely new).
    #[test]
    fn model_diff_nonunique_baseline_does_not_satisfy_unique_model_index() {
        let nonunique = Index {
            name: "idx_posts_email".to_owned(),
            columns: vec!["email".to_owned()],
            unique: false,
            definition: None,
            is_partial: false,
            key_columns: Vec::new(),
        };
        let mut base_table = posts_with(vec![col("email", ColumnType::Text)]);
        base_table.indexes.push(nonunique);

        let mut want_table = posts_with(vec![col("email", ColumnType::Text)]);
        want_table.indexes.push(Index {
            name: "idx_posts_email_unique".to_owned(),
            columns: vec!["email".to_owned()],
            unique: true,
            definition: None,
            is_partial: false,
            key_columns: Vec::new(),
        });
        let plan = diff_schema(
            &[base_table],
            &parsed(vec![want_table], vec![]),
            DEFAULT_OPTS,
        );
        assert!(
            plan.changes.iter().any(|c| matches!(
                c,
                SchemaChange::AddIndex { index, .. } if index.name == "idx_posts_email_unique"
            )),
            "a unique model index over a column with only a non-unique baseline index \
             must still emit AddIndex; got {:?}",
            plan.changes
        );
    }

    /// Authoritative mode (doctor drift / `pull --dry-run`, both sides introspected)
    /// is unaffected: a differently-named desired unique index is NOT suppressed by a
    /// column-set match, so real drift (a renamed/added unique index) is still
    /// detected. There the brownfield constraint index has the same name on both
    /// sides and would match by name; a genuinely new name is genuine drift.
    #[test]
    fn authoritative_diff_still_emits_add_for_differently_named_unique_index() {
        let constraint_idx = Index {
            name: "accounts_email_key".to_owned(),
            columns: vec!["email".to_owned()],
            unique: true,
            definition: Some(
                "CREATE UNIQUE INDEX accounts_email_key ON public.accounts USING btree (email)"
                    .to_owned(),
            ),
            is_partial: false,
            key_columns: vec!["email".to_owned()],
        };
        let mut base_table = posts_with(vec![col("email", ColumnType::Text)]);
        base_table.indexes.push(constraint_idx);

        let mut want_table = posts_with(vec![col("email", ColumnType::Text)]);
        want_table.indexes.push(Index {
            name: "idx_posts_email_unique".to_owned(),
            columns: vec!["email".to_owned()],
            unique: true,
            definition: None,
            is_partial: false,
            key_columns: Vec::new(),
        });
        let plan = diff_schema(
            &[base_table],
            &parsed(vec![want_table], vec![]),
            AUTHORITATIVE,
        );
        assert!(
            plan.changes.iter().any(|c| matches!(
                c,
                SchemaChange::AddIndex { index, .. } if index.name == "idx_posts_email_unique"
            )),
            "authoritative diff must still emit AddIndex for a differently-named unique \
             index (column-set suppression is model-diff-only); got {:?}",
            plan.changes
        );
    }

    /// A **partial** unique index (`… ON t(email) WHERE …`) enforces uniqueness only
    /// for rows matching its predicate, so it does NOT satisfy a model `#[unique]
    /// email` (table-wide) — even though its key columns equal `{email}`. The
    /// `AddIndex` must still be emitted.
    #[test]
    fn baseline_partial_unique_index_does_not_satisfy_model_unique() {
        let partial = Index {
            name: "accounts_email_active_key".to_owned(),
            columns: vec!["email".to_owned()],
            unique: true,
            definition: Some(
                "CREATE UNIQUE INDEX accounts_email_active_key ON accounts (email) WHERE active"
                    .to_owned(),
            ),
            is_partial: true,
            key_columns: vec!["email".to_owned()],
        };
        let mut base = posts_with(vec![col("email", ColumnType::Text)]);
        base.indexes.push(partial);
        assert!(
            !baseline_unique_index_covers(&base, &["email".to_owned()]),
            "a partial unique index must NOT satisfy a table-wide #[unique]"
        );

        // End-to-end: the model #[unique] still emits an AddIndex (not suppressed).
        let mut want_table = posts_with(vec![col("email", ColumnType::Text)]);
        want_table.indexes.push(Index {
            name: "idx_posts_email_unique".to_owned(),
            columns: vec!["email".to_owned()],
            unique: true,
            definition: None,
            is_partial: false,
            key_columns: Vec::new(),
        });
        let plan = diff_schema(&[base], &parsed(vec![want_table], vec![]), DEFAULT_OPTS);
        assert!(
            plan.changes.iter().any(|c| matches!(
                c,
                SchemaChange::AddIndex { index, .. } if index.name == "idx_posts_email_unique"
            )),
            "partial baseline unique index must not suppress the model AddIndex; got {:?}",
            plan.changes
        );
    }

    /// An **expression** unique index (`UNIQUE (lower(email))`) enforces uniqueness of
    /// the expression, not the column, so it does NOT satisfy `#[unique] email`.
    /// Introspection records it with an EMPTY `key_columns` (its dependency `columns`
    /// still names `email`), which must be rejected — the `AddIndex` is emitted.
    #[test]
    fn baseline_expression_unique_index_does_not_satisfy_model_unique() {
        let expr = Index {
            name: "accounts_lower_email_key".to_owned(),
            // `columns` is the pg_depend dependency set (references `email`)...
            columns: vec!["email".to_owned()],
            unique: true,
            definition: Some(
                "CREATE UNIQUE INDEX accounts_lower_email_key ON accounts (lower(email))"
                    .to_owned(),
            ),
            is_partial: false,
            // ...but its KEY is an expression, so no plain key columns are recorded.
            key_columns: Vec::new(),
        };
        let mut base = posts_with(vec![col("email", ColumnType::Text)]);
        base.indexes.push(expr);
        assert!(
            !baseline_unique_index_covers(&base, &["email".to_owned()]),
            "an expression unique index (empty key_columns) must NOT satisfy #[unique]"
        );

        let mut want_table = posts_with(vec![col("email", ColumnType::Text)]);
        want_table.indexes.push(Index {
            name: "idx_posts_email_unique".to_owned(),
            columns: vec!["email".to_owned()],
            unique: true,
            definition: None,
            is_partial: false,
            key_columns: Vec::new(),
        });
        let plan = diff_schema(&[base], &parsed(vec![want_table], vec![]), DEFAULT_OPTS);
        assert!(
            plan.changes.iter().any(|c| matches!(
                c,
                SchemaChange::AddIndex { index, .. } if index.name == "idx_posts_email_unique"
            )),
            "expression baseline unique index must not suppress the model AddIndex; got {:?}",
            plan.changes
        );
    }

    /// Regression guard for the last commit's fix: a plain, FULL, non-partial unique
    /// constraint index whose key columns exactly equal the target STILL satisfies the
    /// model `#[unique]` (no `AddIndex`). Covers both a `definition`-carrying
    /// constraint index (key columns recorded) and a plain `definition`-less unique
    /// index (key columns derived from `columns`).
    #[test]
    fn baseline_full_unique_constraint_index_still_satisfies_model_unique() {
        // (c1) constraint-owned (definition-carrying) unique index, key == [email].
        let constraint = Index {
            name: "accounts_email_key".to_owned(),
            columns: vec!["email".to_owned()],
            unique: true,
            definition: Some(
                "CREATE UNIQUE INDEX accounts_email_key ON accounts (email)".to_owned(),
            ),
            is_partial: false,
            key_columns: vec!["email".to_owned()],
        };
        let mut base = posts_with(vec![col("email", ColumnType::Text)]);
        base.indexes.push(constraint);
        assert!(
            baseline_unique_index_covers(&base, &["email".to_owned()]),
            "a full non-partial unique constraint index over the exact key set must satisfy #[unique]"
        );

        // (c2) plain definition-less unique index: key columns derived from `columns`.
        let plain = Index {
            name: "idx_accounts_email_unique".to_owned(),
            columns: vec!["email".to_owned()],
            unique: true,
            definition: None,
            is_partial: false,
            key_columns: Vec::new(),
        };
        let mut base2 = posts_with(vec![col("email", ColumnType::Text)]);
        base2.indexes.push(plain);
        assert!(
            baseline_unique_index_covers(&base2, &["email".to_owned()]),
            "a plain full unique index must satisfy #[unique] via its columns"
        );
    }

    /// Retention holds even under `--allow-destructive`: the declarative tool
    /// never drops a construct it cannot express.
    #[test]
    fn model_diff_retains_definition_index_even_with_allow_destructive() {
        let mut base_table = posts_with(vec![col("body", ColumnType::Text)]);
        base_table.indexes.push(expr_index());
        let want = parsed(
            vec![posts_with(vec![col("body", ColumnType::Text)])],
            vec![],
        );
        let plan = diff_schema(&[base_table], &want, ALLOW);
        assert!(
            !plan
                .changes
                .iter()
                .any(|c| matches!(c, SchemaChange::DropIndex { .. })),
            "--allow-destructive must still retain an unmodellable definition index; got {:?}",
            plan.changes
        );
    }

    /// Model diff: a baseline `definition` index sharing a NAME with a desired
    /// (model-parsed, `definition: None`) index is **retained** — no
    /// `DropIndex`/replacement that would clobber the expression/partial index with
    /// a plain column index.
    #[test]
    fn model_diff_retains_definition_index_sharing_name_with_plain_desired() {
        // Baseline: an expression index named `idx_posts_body`.
        let base_expr = Index {
            name: "idx_posts_body".to_owned(),
            columns: vec!["body".to_owned()],
            unique: false,
            definition: Some("CREATE INDEX idx_posts_body ON posts (lower(body))".to_owned()),
            is_partial: false,
            key_columns: Vec::new(),
        };
        let mut base_table = posts_with(vec![col("body", ColumnType::Text)]);
        base_table.indexes.push(base_expr);

        // Desired (model): a plain column index of the SAME name (definition: None).
        let mut want_table = posts_with(vec![col("body", ColumnType::Text)]);
        want_table.indexes.push(Index {
            name: "idx_posts_body".to_owned(),
            columns: vec!["body".to_owned()],
            unique: false,
            definition: None,
            is_partial: false,
            key_columns: Vec::new(),
        });
        let plan = diff_schema(
            &[base_table],
            &parsed(vec![want_table], vec![]),
            DEFAULT_OPTS,
        );
        assert!(
            plan.changes.is_empty(),
            "model diff must retain the definition index and emit no drop/replace; got {:?}",
            plan.changes
        );
    }

    /// A model-parsed unique index over `[email]` on the `posts` table, carrying
    /// the parser's conventional name `idx_posts_email_unique` (`definition: None`).
    fn desired_posts_email_unique() -> Index {
        Index {
            name: "idx_posts_email_unique".to_owned(),
            columns: vec!["email".to_owned()],
            unique: true,
            definition: None,
            is_partial: false,
            key_columns: Vec::new(),
        }
    }

    /// Fix 1 (a): a baseline **partial** unique index that happens to carry the
    /// model's conventional name (`idx_posts_email_unique`) hits the same-NAME
    /// match branch but does NOT provide table-wide coverage. It must NOT suppress
    /// the model's `#[unique]` — the full unique `AddIndex` is emitted — while the
    /// partial index (definition-carrying) is itself RETAINED (no `DropIndex`).
    #[test]
    fn model_diff_same_named_partial_unique_does_not_suppress_and_retains_partial() {
        let partial = Index {
            name: "idx_posts_email_unique".to_owned(),
            columns: vec!["email".to_owned()],
            unique: true,
            definition: Some(
                "CREATE UNIQUE INDEX idx_posts_email_unique ON posts (email) \
                 WHERE email IS NOT NULL"
                    .to_owned(),
            ),
            is_partial: true,
            key_columns: vec!["email".to_owned()],
        };
        let mut base = posts_with(vec![col("email", ColumnType::Text)]);
        base.indexes.push(partial);

        let mut want_table = posts_with(vec![col("email", ColumnType::Text)]);
        want_table.indexes.push(desired_posts_email_unique());
        let plan = diff_schema(&[base], &parsed(vec![want_table], vec![]), DEFAULT_OPTS);
        assert!(
            plan.changes.iter().any(|c| matches!(
                c,
                SchemaChange::AddIndex { index, .. }
                    if index.name == "idx_posts_email_unique" && index.definition.is_none()
            )),
            "a same-named PARTIAL unique index must not suppress the model's full \
             #[unique]; got {:?}",
            plan.changes
        );
        assert!(
            !plan
                .changes
                .iter()
                .any(|c| matches!(c, SchemaChange::DropIndex { .. })),
            "the retained partial index must not be dropped; got {:?}",
            plan.changes
        );
    }

    /// Fix 1 (b): a baseline **expression** unique index (empty `key_columns`)
    /// carrying the model's conventional name must NOT suppress the model's
    /// `#[unique]` — the full unique `AddIndex` is emitted, and the expression
    /// index is retained (no `DropIndex`).
    #[test]
    fn model_diff_same_named_expression_unique_does_not_suppress() {
        let expr = Index {
            name: "idx_posts_email_unique".to_owned(),
            columns: vec!["email".to_owned()],
            unique: true,
            definition: Some(
                "CREATE UNIQUE INDEX idx_posts_email_unique ON posts (lower(email))".to_owned(),
            ),
            is_partial: false,
            key_columns: Vec::new(),
        };
        let mut base = posts_with(vec![col("email", ColumnType::Text)]);
        base.indexes.push(expr);

        let mut want_table = posts_with(vec![col("email", ColumnType::Text)]);
        want_table.indexes.push(desired_posts_email_unique());
        let plan = diff_schema(&[base], &parsed(vec![want_table], vec![]), DEFAULT_OPTS);
        assert!(
            plan.changes.iter().any(|c| matches!(
                c,
                SchemaChange::AddIndex { index, .. }
                    if index.name == "idx_posts_email_unique" && index.definition.is_none()
            )),
            "a same-named EXPRESSION unique index must not suppress the model's \
             #[unique]; got {:?}",
            plan.changes
        );
        assert!(
            !plan
                .changes
                .iter()
                .any(|c| matches!(c, SchemaChange::DropIndex { .. })),
            "the retained expression index must not be dropped; got {:?}",
            plan.changes
        );
    }

    /// Fix 1 (c) regression guard: a baseline **full plain** unique index
    /// (`definition: None`) over exactly the model's key, sharing its name, STILL
    /// suppresses the model `#[unique]` — a clean, empty plan (no `AddIndex`, no
    /// `DropIndex`).
    #[test]
    fn model_diff_same_named_full_plain_unique_still_suppresses() {
        let plain_index = Index {
            name: "idx_posts_email_unique".to_owned(),
            columns: vec!["email".to_owned()],
            unique: true,
            definition: None,
            is_partial: false,
            key_columns: Vec::new(),
        };
        let mut base = posts_with(vec![col("email", ColumnType::Text)]);
        base.indexes.push(plain_index);

        let mut want_table = posts_with(vec![col("email", ColumnType::Text)]);
        want_table.indexes.push(desired_posts_email_unique());
        let plan = diff_schema(&[base], &parsed(vec![want_table], vec![]), DEFAULT_OPTS);
        assert!(
            plan.changes.is_empty(),
            "a same-named FULL plain unique index over the same key must still \
             suppress the model #[unique]; got {:?}",
            plan.changes
        );
    }

    /// Fix 1 (d): a baseline **full constraint** (definition-carrying) unique index
    /// over exactly the model's key, sharing its name, fully covers the model
    /// `#[unique]` — so it is retained and the model index is suppressed (empty
    /// plan). This exercises the same-NAME branch's "B fully covers → suppress D"
    /// path.
    #[test]
    fn model_diff_same_named_full_constraint_unique_suppresses() {
        let constraint = Index {
            name: "idx_posts_email_unique".to_owned(),
            columns: vec!["email".to_owned()],
            unique: true,
            definition: Some(
                "CREATE UNIQUE INDEX idx_posts_email_unique ON posts USING btree (email)"
                    .to_owned(),
            ),
            is_partial: false,
            key_columns: vec!["email".to_owned()],
        };
        let mut base = posts_with(vec![col("email", ColumnType::Text)]);
        base.indexes.push(constraint);

        let mut want_table = posts_with(vec![col("email", ColumnType::Text)]);
        want_table.indexes.push(desired_posts_email_unique());
        let plan = diff_schema(&[base], &parsed(vec![want_table], vec![]), DEFAULT_OPTS);
        assert!(
            plan.changes.is_empty(),
            "a same-named FULL constraint unique index that fully covers the key \
             must suppress the model #[unique] (retained, no add); got {:?}",
            plan.changes
        );
    }

    /// Introspection diff (`AUTHORITATIVE`, `definitions_authoritative: true`): a
    /// baseline-only `definition` index absent from the desired side IS a genuine
    /// drop and MUST emit `DropIndex` — this proves doctor's `database-schema-drift`
    /// / `pull --dry-run` still catches a dropped expression/partial index.
    #[test]
    fn authoritative_diff_drops_baseline_only_definition_index() {
        let mut base_table = posts_with(vec![col("body", ColumnType::Text)]);
        base_table.indexes.push(expr_index());
        let want = parsed(
            vec![posts_with(vec![col("body", ColumnType::Text)])],
            vec![],
        );
        let plan = diff_schema(&[base_table], &want, AUTHORITATIVE);
        assert_eq!(
            plan.changes,
            vec![SchemaChange::DropIndex {
                table: "posts".to_owned(),
                index: expr_index(),
            }],
            "authoritative introspection diff must report a dropped definition index as drift"
        );
    }

    #[test]
    fn add_check_emitted_but_no_drop_check() {
        let check = CheckConstraint {
            name: Some("posts_body_len".to_owned()),
            expression: "length(body) > 0".to_owned(),
        };
        // desired gains a check → AddCheck.
        let base = vec![posts_with(vec![col("body", ColumnType::Text)])];
        let mut want_table = posts_with(vec![col("body", ColumnType::Text)]);
        want_table.checks.push(check.clone());
        let plan = diff_schema(&base, &parsed(vec![want_table], vec![]), DEFAULT_OPTS);
        assert_eq!(
            plan.changes,
            vec![SchemaChange::AddCheck {
                table: "posts".to_owned(),
                check,
            }]
        );

        // baseline-only check → NO change (rule A: never drop a check).
        let mut base_table = posts_with(vec![col("body", ColumnType::Text)]);
        base_table.checks.push(CheckConstraint {
            name: Some("posts_body_len".to_owned()),
            expression: "length(body) > 0".to_owned(),
        });
        let want = parsed(
            vec![posts_with(vec![col("body", ColumnType::Text)])],
            vec![],
        );
        let plan = diff_schema(&[base_table], &want, DEFAULT_OPTS);
        assert!(
            plan.is_empty(),
            "baseline-only check must not be dropped: {plan:?}"
        );
    }

    #[test]
    fn new_table_creates() {
        let base: Vec<Table> = vec![];
        let want_table = posts_with(vec![col("body", ColumnType::Text)]);
        let plan = diff_schema(
            &base,
            &parsed(vec![want_table.clone()], vec![]),
            DEFAULT_OPTS,
        );
        assert_eq!(plan.changes, vec![SchemaChange::CreateTable(want_table)]);
    }

    #[test]
    fn missing_table_drops_carrying_baseline() {
        let base_table = posts_with(vec![col("body", ColumnType::Text)]);
        let want = parsed(vec![], vec![]);
        let plan = diff_schema(std::slice::from_ref(&base_table), &want, DEFAULT_OPTS);
        assert_eq!(plan.changes, vec![SchemaChange::DropTable(base_table)]);
    }

    #[test]
    fn key_columns_diff_by_name_not_position() {
        // Same columns, reordered → empty plan (name-keyed, not positional).
        let base = vec![posts_with(vec![
            col("a", ColumnType::Text),
            col("b", ColumnType::Int32),
        ])];
        let want = parsed(
            vec![posts_with(vec![
                col("b", ColumnType::Int32),
                col("a", ColumnType::Text),
            ])],
            vec![],
        );
        let plan = diff_schema(&base, &want, DEFAULT_OPTS);
        assert!(plan.is_empty(), "reordered columns → no change: {plan:?}");
    }

    // -- 13.2 parser-gap conservatism (rules A–E) ----------------------------

    #[test]
    fn baseline_enum_check_not_dropped() {
        let mut base_table = posts_with(vec![col("status", ColumnType::Text)]);
        base_table.checks.push(CheckConstraint {
            name: Some("posts_status_check".to_owned()),
            expression: "status IN ('draft','live')".to_owned(),
        });
        // desired (parser output) has no checks.
        let want = parsed(
            vec![posts_with(vec![col("status", ColumnType::Text)])],
            vec![],
        );
        let plan = diff_schema(&[base_table], &want, DEFAULT_OPTS);
        assert!(plan.is_empty(), "rule A: enum CHECK not dropped: {plan:?}");
    }

    #[test]
    fn baseline_association_fk_not_dropped() {
        let mut author = col("author_id", ColumnType::Int64);
        author.references = Some(ForeignKey::new("users", "id"));
        let base = vec![posts_with(vec![author])];
        // desired same column, references None (parser can't resolve association FK).
        let want = parsed(
            vec![posts_with(vec![col("author_id", ColumnType::Int64)])],
            vec![],
        );
        let plan = diff_schema(&base, &want, DEFAULT_OPTS);
        assert!(
            plan.is_empty(),
            "rule B: association FK not dropped: {plan:?}"
        );
    }

    #[test]
    fn baseline_non_convention_default_not_dropped() {
        let mut status = col("status", ColumnType::Text);
        status.default = Some(ColumnDefault::Sql("'draft'".to_owned()));
        let base = vec![posts_with(vec![status])];
        let want = parsed(
            vec![posts_with(vec![col("status", ColumnType::Text)])],
            vec![],
        );
        let plan = diff_schema(&base, &want, DEFAULT_OPTS);
        assert!(
            plan.is_empty(),
            "rule C: non-convention default not dropped: {plan:?}"
        );
    }

    #[test]
    fn enum_skipped_column_not_dropped_via_diagnostic() {
        // baseline has an enum-ish `status` column; desired omits it but records a
        // diagnostic for Post.status → pluralize(pascal_to_snake("Post")) == "posts".
        let base = vec![posts_with(vec![col(
            "status",
            ColumnType::Enum {
                variants: vec!["draft".into(), "live".into()],
            },
        )])];
        let want = parsed(
            vec![posts_with(vec![])],
            vec![diag("Post", "posts", "status")],
        );
        let plan = diff_schema(&base, &want, DEFAULT_OPTS);
        assert!(
            plan.is_empty(),
            "rules D+E: parser-skipped column not dropped: {plan:?}"
        );
    }

    #[test]
    fn custom_table_name_skipped_column_not_dropped_via_diagnostic() {
        // A managed model `#[model(table = "app_users")]` with a skipped
        // enum/assoc field records a diagnostic whose resolved `table` is the
        // CUSTOM name `app_users` — NOT the convention name `users`. The baseline
        // `app_users` carries the extra unmodelled `role` column; the suppression
        // must match on the resolved table name so the column is treated as
        // "present but unmodelled" and NOT dropped — even under
        // `--allow-destructive`, which would otherwise DROP the real column and
        // its data.
        let mut base_table = Table::new("app_users", Backend::Postgres);
        base_table.managed = true;
        let mut id = col("id", ColumnType::Int64);
        id.primary_key = true;
        base_table.columns.push(id);
        base_table.primary_key.push("id".to_owned());
        base_table.columns.push(col(
            "role",
            ColumnType::Enum {
                variants: vec!["admin".into(), "member".into()],
            },
        ));

        let mut desired_table = Table::new("app_users", Backend::Postgres);
        desired_table.managed = true;
        let mut did = col("id", ColumnType::Int64);
        did.primary_key = true;
        desired_table.columns.push(did);
        desired_table.primary_key.push("id".to_owned());

        // Model `User` → convention table `users`, but the resolved table is the
        // `#[model(table = "app_users")]` override.
        let want = parsed(vec![desired_table], vec![diag("User", "app_users", "role")]);

        // Destructive-allowed: proves the suppression, not the destructive guard,
        // is what keeps the column.
        let plan = diff_schema(&[base_table], &want, ALLOW);
        assert!(
            plan.is_empty(),
            "custom-table diagnostic must suppress the DropColumn: {plan:?}"
        );
    }

    #[test]
    fn drop_still_fires_without_matching_diagnostic() {
        // A genuinely-removed column (no diagnostic) is still a DropColumn — the
        // suppression is exact, not blanket.
        let base = vec![posts_with(vec![col("legacy", ColumnType::Text)])];
        let want = parsed(
            vec![posts_with(vec![])],
            vec![diag("Post", "posts", "something_else")],
        );
        let plan = diff_schema(&base, &want, DEFAULT_OPTS);
        assert_eq!(plan.changes.len(), 1);
        assert!(matches!(plan.changes[0], SchemaChange::DropColumn { .. }));
    }

    #[test]
    fn index_on_diagnostic_skipped_column_is_not_dropped() {
        // baseline: an enum `status` column carrying a UNIQUE index. The parser
        // skips the enum field (diagnostic) so desired omits BOTH the column and
        // its index. The `DropColumn` is already suppressed; the `DropIndex` must
        // be too — otherwise the retained column silently loses its UNIQUE
        // constraint and duplicate data becomes possible.
        let mut base_table = posts_with(vec![col(
            "status",
            ColumnType::Enum {
                variants: vec!["draft".into(), "live".into()],
            },
        )]);
        base_table.indexes.push(Index {
            name: "idx_posts_status".to_owned(),
            columns: vec!["status".to_owned()],
            unique: true,
            definition: None,
            is_partial: false,
            key_columns: Vec::new(),
        });
        let want = parsed(
            vec![posts_with(vec![])],
            vec![diag("Post", "posts", "status")],
        );
        let plan = diff_schema(&[base_table], &want, DEFAULT_OPTS);
        assert!(
            !plan
                .changes
                .iter()
                .any(|c| matches!(c, SchemaChange::DropIndex { .. })),
            "index on a parser-skipped column must not be dropped: {plan:?}"
        );
        assert!(
            plan.is_empty(),
            "column and its index both suppressed → empty plan: {plan:?}"
        );
    }

    #[test]
    fn index_on_normal_column_still_dropped() {
        // Control: an ordinary removed index (no diagnostic) still drops — the
        // suppression is exact, not blanket.
        let idx = Index {
            name: "idx_posts_body".to_owned(),
            columns: vec!["body".to_owned()],
            unique: false,
            definition: None,
            is_partial: false,
            key_columns: Vec::new(),
        };
        let mut base_table = posts_with(vec![col("body", ColumnType::Text)]);
        base_table.indexes.push(idx.clone());
        let want = parsed(
            vec![posts_with(vec![col("body", ColumnType::Text)])],
            vec![],
        );
        let plan = diff_schema(&[base_table], &want, DEFAULT_OPTS);
        assert_eq!(
            plan.changes,
            vec![SchemaChange::DropIndex {
                table: "posts".to_owned(),
                index: idx,
            }]
        );
    }

    #[test]
    fn composite_index_touching_skipped_column_is_not_dropped() {
        // A composite UNIQUE index over (author_id, status) where `status` is
        // parser-skipped. If ANY column is skipped the whole drop is suppressed —
        // the parser cannot authoritatively say the index was removed, and
        // dropping it would silently lose the multi-column uniqueness.
        let mut base_table = posts_with(vec![
            col("author_id", ColumnType::Int64),
            col(
                "status",
                ColumnType::Enum {
                    variants: vec!["draft".into(), "live".into()],
                },
            ),
        ]);
        base_table.indexes.push(Index {
            name: "idx_posts_author_status".to_owned(),
            columns: vec!["author_id".to_owned(), "status".to_owned()],
            unique: true,
            definition: None,
            is_partial: false,
            key_columns: Vec::new(),
        });
        // desired retains `author_id` but the enum `status` is skipped (diagnostic),
        // so the parser never sees the composite index either.
        let want = parsed(
            vec![posts_with(vec![col("author_id", ColumnType::Int64)])],
            vec![diag("Post", "posts", "status")],
        );
        let plan = diff_schema(&[base_table], &want, DEFAULT_OPTS);
        assert!(
            !plan
                .changes
                .iter()
                .any(|c| matches!(c, SchemaChange::DropIndex { .. })),
            "composite index touching a skipped column must not be dropped: {plan:?}"
        );
    }

    #[test]
    fn create_table_with_diagnostic_skipped_field_is_refused() {
        // A brand-new managed table whose model has a skipped enum field parses to
        // a `Table` OMITTING that column (only a diagnostic is recorded). Emitting
        // `CREATE TABLE` from that partial output would create a table missing a
        // column the generated model queries → runtime "column does not exist". The
        // diff must surface the refused marker, and `guard_plan` must reject it
        // (with no override) naming the missing field.
        let mut new_table = Table::new("events", Backend::Postgres);
        new_table.managed = true;
        let mut id = col("id", ColumnType::Int64);
        id.primary_key = true;
        new_table.columns.push(id);
        new_table.primary_key.push("id".to_owned());
        // The `kind` enum field is skipped by the parser → not a column, only a diag.
        let want = parsed(vec![new_table], vec![diag("Event", "events", "kind")]);
        let plan = diff_schema(&[], &want, DEFAULT_OPTS);
        assert_eq!(
            plan.changes,
            vec![SchemaChange::CreateTableBlockedBySkippedField {
                table: "events".to_owned(),
                fields: vec!["kind".to_owned()],
            }],
            "a diagnostic-skipped new table must not emit CREATE TABLE: {plan:?}"
        );
        match guard_plan(&plan, DEFAULT_OPTS) {
            Err(DiffError::CreateTableWithSkippedField { table, fields }) => {
                assert_eq!(table, "events");
                assert_eq!(fields, vec!["kind".to_owned()]);
            }
            other => panic!("expected CreateTableWithSkippedField refusal, got {other:?}"),
        }
        // No override — even --allow-destructive refuses (incomplete DDL, not lossy).
        assert!(matches!(
            guard_plan(&plan, ALLOW),
            Err(DiffError::CreateTableWithSkippedField { .. })
        ));
        // The message names both the table and the missing field.
        let msg = guard_plan(&plan, DEFAULT_OPTS).unwrap_err().to_string();
        assert!(
            msg.contains("events") && msg.contains("kind"),
            "refusal message names table + field: {msg}"
        );
    }

    #[test]
    fn create_table_without_diagnostics_is_allowed() {
        // Control: a clean new managed table (no skipped fields) still emits
        // CREATE TABLE and passes the guard.
        let new_table = posts_ref_table("events", col("title", ColumnType::Text));
        let want = parsed(vec![new_table.clone()], vec![]);
        let plan = diff_schema(&[], &want, DEFAULT_OPTS);
        assert_eq!(plan.changes, vec![SchemaChange::CreateTable(new_table)]);
        assert!(
            guard_plan(&plan, DEFAULT_OPTS).is_ok(),
            "a clean new table is emittable"
        );
    }

    #[test]
    fn add_fk_to_preexisting_column_is_refused() {
        // Finding 902: a PRE-EXISTING generated association column (`author_id`,
        // present in the baseline with `references: None` because the parser cannot
        // see the `#[belongs_to(...)]` association FK) is changed to an explicit
        // `#[references]`. The DB may already carry the inline `posts_author_id_fkey`
        // constraint from the original association-FK generation, so emitting
        // `ADD CONSTRAINT posts_author_id_fkey` would collide → an unappliable
        // migration. The diff must surface the refused marker, never an
        // `AddForeignKey`.
        let base = vec![posts_with(vec![col("author_id", ColumnType::Int64)])];
        let mut author = col("author_id", ColumnType::Int64);
        author.references = Some(ForeignKey::new("users", "id"));
        let want = parsed(vec![posts_with(vec![author])], vec![]);
        let plan = diff_schema(&base, &want, DEFAULT_OPTS);
        assert_eq!(
            plan.changes,
            vec![SchemaChange::AddForeignKeyToExistingColumn {
                table: "posts".to_owned(),
                column: "author_id".to_owned(),
            }],
            "an FK added to a pre-existing column is the refused marker, never an AddForeignKey: \
             {plan:?}"
        );
        assert!(
            !plan
                .changes
                .iter()
                .any(|c| matches!(c, SchemaChange::AddForeignKey { .. })),
            "must never emit an AddForeignKey on a pre-existing column"
        );

        // The guard refuses it — with no override (the SQL may be unappliable).
        let err = guard_plan(&plan, DEFAULT_OPTS).unwrap_err();
        assert!(
            matches!(err, DiffError::AddForeignKeyToPreexistingColumn { .. }),
            "guard refuses the pre-existing-column FK add: {err:?}"
        );
        assert!(
            err.to_string().contains("posts_author_id_fkey"),
            "the error explains the constraint-name collision: {err}"
        );
        // --allow-destructive does NOT override it (no safe way to skip a duplicate).
        assert!(matches!(
            guard_plan(&plan, ALLOW).unwrap_err(),
            DiffError::AddForeignKeyToPreexistingColumn { .. }
        ));
    }

    #[test]
    fn add_fk_on_new_column_is_allowed() {
        // Control for finding 902: a BRAND-NEW FK column (absent from the baseline)
        // is safe — there is no pre-existing constraint to collide with. It arrives
        // as an `AddColumn` whose `REFERENCES` renders inline in the `ADD COLUMN`
        // (never as a separate `AddForeignKey`), so it is neither refused nor a
        // marker, and the emitted SQL carries the foreign key.
        let base = vec![posts_with(vec![])];
        let mut author = col("author_id", ColumnType::Int64);
        author.nullable = true;
        author.references = Some(ForeignKey::new("users", "id"));
        let want = parsed(vec![posts_with(vec![author.clone()])], vec![]);
        let plan = diff_schema(&base, &want, DEFAULT_OPTS);
        assert_eq!(
            plan.changes,
            vec![SchemaChange::AddColumn {
                table: "posts".to_owned(),
                column: author,
            }],
            "a new FK column is a plain AddColumn, not a refused marker: {plan:?}"
        );
        // It passes the guard and emits the inline REFERENCES.
        guard_plan(&plan, DEFAULT_OPTS).expect("a new FK column is emittable");
        let up = emit_up_sql(&plan).expect("emit up");
        assert!(
            up.contains("ADD COLUMN author_id BIGINT NULL REFERENCES users(id)"),
            "the new FK column emits its inline REFERENCES: {up}"
        );
    }

    #[test]
    fn fk_retarget_is_a_refused_marker_not_a_duplicate_add() {
        // Regression (finding 1): baseline `author_id` already has an explicit FK
        // to users(id); desired retargets it to accounts(id). Emitting a plain
        // `AddForeignKey` would `ADD CONSTRAINT posts_author_id_fkey` a second
        // time and collide with the baseline constraint of the same name. The diff
        // must instead surface the refused `ForeignKeyChange` marker (never an
        // `AddForeignKey`).
        let mut base_author = col("author_id", ColumnType::Int64);
        base_author.references = Some(ForeignKey::new("users", "id"));
        let base = vec![posts_with(vec![base_author])];

        let mut want_author = col("author_id", ColumnType::Int64);
        want_author.references = Some(ForeignKey::new("accounts", "id"));
        let want = parsed(vec![posts_with(vec![want_author])], vec![]);

        let plan = diff_schema(&base, &want, DEFAULT_OPTS);
        assert_eq!(
            plan.changes,
            vec![SchemaChange::ForeignKeyChange {
                table: "posts".to_owned(),
                column: "author_id".to_owned(),
            }],
            "an FK retarget is the refused marker, not an AddForeignKey: {plan:?}"
        );
        assert!(
            !plan
                .changes
                .iter()
                .any(|c| matches!(c, SchemaChange::AddForeignKey { .. })),
            "must never emit a duplicate AddForeignKey on retarget"
        );

        // The guard refuses it — with no override, like a PK change.
        let err = guard_plan(&plan, DEFAULT_OPTS).unwrap_err();
        assert!(
            matches!(err, DiffError::ForeignKeyChange { .. }),
            "guard refuses the retarget: {err:?}"
        );
        assert!(
            err.to_string().contains("posts_author_id_fkey"),
            "the error explains the constraint-name collision: {err}"
        );
        // --allow-destructive does NOT override it (no safe drop+recreate).
        assert!(matches!(
            guard_plan(&plan, ALLOW).unwrap_err(),
            DiffError::ForeignKeyChange { .. }
        ));
    }

    #[test]
    fn fk_unchanged_target_is_no_change() {
        // Same explicit FK on both sides → nothing to do (not a retarget marker).
        let mut base_author = col("author_id", ColumnType::Int64);
        base_author.references = Some(ForeignKey::new("users", "id"));
        let mut want_author = col("author_id", ColumnType::Int64);
        want_author.references = Some(ForeignKey::new("users", "id"));
        let plan = diff_schema(
            &[posts_with(vec![base_author])],
            &parsed(vec![posts_with(vec![want_author])], vec![]),
            DEFAULT_OPTS,
        );
        assert!(plan.is_empty(), "unchanged FK → empty plan: {plan:?}");
    }

    #[test]
    fn colliding_over_long_fk_names_get_distinct_bounded_names() {
        // Deferred item #4: a >63-byte table name plus two added FK columns whose
        // raw `{table}_{column}_fkey` names share their first 63 bytes would, under
        // plain PG truncation, collide into one duplicate relation. The bounded
        // scheme appends a hash of the FULL untruncated name, so the two now get
        // DISTINCT valid ≤63-byte names and the plan is accepted, not refused.
        let long_table = "a".repeat(60); // {table}_{col}_fkey is well over 63 bytes.
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![
                SchemaChange::AddForeignKey {
                    table: long_table.clone(),
                    column: "author_id".to_owned(),
                    foreign_key: ForeignKey::new("users", "id"),
                },
                SchemaChange::AddForeignKey {
                    table: long_table.clone(),
                    column: "editor_id".to_owned(),
                    foreign_key: ForeignKey::new("users", "id"),
                },
            ],
        };
        guard_plan(&plan, DEFAULT_OPTS).expect("distinct bounded FK names are no longer refused");

        let author = bounded_pg_identifier(&format!("{long_table}_author_id_fkey"));
        let editor = bounded_pg_identifier(&format!("{long_table}_editor_id_fkey"));
        assert!(
            author.len() <= PG_MAX_IDENTIFIER_BYTES && editor.len() <= PG_MAX_IDENTIFIER_BYTES,
            "both bounded names fit the limit: {author} / {editor}"
        );
        assert_ne!(
            author, editor,
            "the hash suffix keeps the two colliding-prefix names distinct"
        );

        let up = emit_up_sql(&plan).expect("emit up");
        assert!(up.contains(&format!("ADD CONSTRAINT {author} ")), "{up}");
        assert!(up.contains(&format!("ADD CONSTRAINT {editor} ")), "{up}");
    }

    #[test]
    fn normal_length_fk_names_are_allowed() {
        // Ordinary table/column names produce a `posts_author_id_fkey` well under
        // 63 bytes — the guard passes and the plan emits.
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::AddForeignKey {
                table: "posts".to_owned(),
                column: "author_id".to_owned(),
                foreign_key: ForeignKey::new("users", "id"),
            }],
        };
        assert!(
            guard_plan(&plan, DEFAULT_OPTS).is_ok(),
            "normal-length FK names must not be refused"
        );
    }

    #[test]
    fn over_long_index_name_is_refused() {
        // The same 63-byte hazard applies to generated index names emitted as
        // top-level `CREATE INDEX`. An index name over the limit is refused.
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::AddIndex {
                table: "posts".to_owned(),
                index: Index {
                    name: format!("idx_{}", "x".repeat(70)),
                    columns: vec!["body".to_owned()],
                    unique: false,
                    definition: None,
                    is_partial: false,
                    key_columns: Vec::new(),
                },
            }],
        };
        let err = guard_plan(&plan, DEFAULT_OPTS).unwrap_err();
        assert!(
            matches!(err, DiffError::GeneratedIdentifierTooLong { .. }),
            "over-long index name is refused: {err:?}"
        );
    }

    #[test]
    fn over_long_generated_name_is_allowed_on_sqlite() {
        // SQLite has no comparable short identifier limit, so the check is
        // Postgres-only. (AddForeignKey does not render on SQLite anyway, but the
        // guard must not refuse the plan on backend grounds.)
        let plan = MigrationPlan {
            backend: Backend::Sqlite,
            changes: vec![SchemaChange::AddIndex {
                table: "posts".to_owned(),
                index: Index {
                    name: format!("idx_{}", "x".repeat(70)),
                    columns: vec!["body".to_owned()],
                    unique: false,
                    definition: None,
                    is_partial: false,
                    key_columns: Vec::new(),
                },
            }],
        };
        assert!(
            guard_plan(&plan, DEFAULT_OPTS).is_ok(),
            "the 63-byte guard is Postgres-only"
        );
    }

    #[test]
    fn duplicate_generated_index_names_are_refused() {
        // A `#[unique] foo` field yields `idx_<table>_foo_unique` while a separate
        // field literally named `foo_unique` yields the *same* `idx_<table>_foo_unique`
        // (parse.rs). Both are within 63 bytes, so the truncation-collision path never
        // fires — but PG accepts the first `CREATE INDEX` and rejects the second as a
        // duplicate relation. The guard must refuse the plan and name the duplicate.
        let dup = "idx_posts_foo_unique".to_owned();
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![
                SchemaChange::AddIndex {
                    table: "posts".to_owned(),
                    index: Index {
                        name: dup.clone(),
                        columns: vec!["foo".to_owned()],
                        unique: true,
                        definition: None,
                        is_partial: false,
                        key_columns: Vec::new(),
                    },
                },
                SchemaChange::AddIndex {
                    table: "posts".to_owned(),
                    index: Index {
                        name: dup.clone(),
                        columns: vec!["foo_unique".to_owned()],
                        unique: false,
                        definition: None,
                        is_partial: false,
                        key_columns: Vec::new(),
                    },
                },
            ],
        };
        let err = guard_plan(&plan, DEFAULT_OPTS).unwrap_err();
        assert!(
            matches!(err, DiffError::GeneratedIdentifierTooLong { .. }),
            "an exact-duplicate generated index name is refused: {err:?}"
        );
        assert!(
            err.to_string().contains(&dup),
            "the error names the duplicated identifier: {err}"
        );
        // No override — the SQL is unappliable, not merely lossy.
        assert!(matches!(
            guard_plan(&plan, ALLOW).unwrap_err(),
            DiffError::GeneratedIdentifierTooLong { .. }
        ));
    }

    #[test]
    fn duplicate_generated_names_on_create_table_are_refused() {
        // The same collision emitted inline on a brand-new table's `CREATE TABLE`
        // (both indexes live on `table.indexes`) is likewise refused.
        let dup = "idx_posts_foo_unique".to_owned();
        let mut table = posts_with(vec![
            col("foo", ColumnType::Text),
            col("foo_unique", ColumnType::Text),
        ]);
        table.indexes = vec![
            Index {
                name: dup.clone(),
                columns: vec!["foo".to_owned()],
                unique: true,
                definition: None,
                is_partial: false,
                key_columns: Vec::new(),
            },
            Index {
                name: dup.clone(),
                columns: vec!["foo_unique".to_owned()],
                unique: false,
                definition: None,
                is_partial: false,
                key_columns: Vec::new(),
            },
        ];
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::CreateTable(table)],
        };
        let err = guard_plan(&plan, DEFAULT_OPTS).unwrap_err();
        assert!(
            matches!(err, DiffError::GeneratedIdentifierTooLong { .. }),
            "duplicate inline index names on CREATE TABLE are refused: {err:?}"
        );
        assert!(err.to_string().contains(&dup), "names the duplicate: {err}");
    }

    #[test]
    fn distinct_index_names_are_allowed() {
        // Control: two legitimately-distinct index names (both well under 63 bytes)
        // must not be treated as a collision.
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![
                SchemaChange::AddIndex {
                    table: "posts".to_owned(),
                    index: Index {
                        name: "idx_posts_foo".to_owned(),
                        columns: vec!["foo".to_owned()],
                        unique: false,
                        definition: None,
                        is_partial: false,
                        key_columns: Vec::new(),
                    },
                },
                SchemaChange::AddIndex {
                    table: "posts".to_owned(),
                    index: Index {
                        name: "idx_posts_bar".to_owned(),
                        columns: vec!["bar".to_owned()],
                        unique: false,
                        definition: None,
                        is_partial: false,
                        key_columns: Vec::new(),
                    },
                },
            ],
        };
        assert!(
            guard_plan(&plan, DEFAULT_OPTS).is_ok(),
            "distinct index names must not be refused as a collision"
        );
    }

    #[test]
    fn unique_index_add_on_existing_column_is_refused() {
        // Marking a pre-existing column `#[unique]` yields a unique `AddIndex`
        // whose only column (`email`) already existed — `CREATE UNIQUE INDEX`
        // would fail if the table's existing rows hold duplicate emails. The
        // engine cannot dedup offline, so it refuses (no override — unappliable,
        // not merely destructive).
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::AddIndex {
                table: "posts".to_owned(),
                index: Index {
                    name: "idx_posts_email_unique".to_owned(),
                    columns: vec!["email".to_owned()],
                    unique: true,
                    definition: None,
                    is_partial: false,
                    key_columns: Vec::new(),
                },
            }],
        };
        let err = guard_plan(&plan, DEFAULT_OPTS).unwrap_err();
        assert!(
            matches!(err, DiffError::UniqueIndexRequiresDedup { .. }),
            "a unique index on a pre-existing column is refused: {err:?}"
        );
        assert!(
            err.to_string().contains("idx_posts_email_unique") && err.to_string().contains("posts"),
            "the error names the index and table: {err}"
        );
        // No override — the SQL is unappliable, not merely lossy.
        assert!(
            matches!(
                guard_plan(&plan, ALLOW).unwrap_err(),
                DiffError::UniqueIndexRequiresDedup { .. }
            ),
            "--allow-destructive does not override an unappliable unique-index add"
        );
    }

    #[test]
    fn unique_index_add_on_new_column_is_allowed() {
        // A brand-new nullable column that also carries `#[unique]` arrives as an
        // `AddColumn` plus a unique `AddIndex` on that same new column. Every
        // existing row is NULL in the new column, and Postgres treats NULLs as
        // distinct in a unique index, so `CREATE UNIQUE INDEX` cannot conflict —
        // the plan is emittable.
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![
                SchemaChange::AddColumn {
                    table: "posts".to_owned(),
                    column: {
                        let mut c = col("email", ColumnType::Text);
                        c.nullable = true;
                        c
                    },
                },
                SchemaChange::AddIndex {
                    table: "posts".to_owned(),
                    index: Index {
                        name: "idx_posts_email_unique".to_owned(),
                        columns: vec!["email".to_owned()],
                        unique: true,
                        definition: None,
                        is_partial: false,
                        key_columns: Vec::new(),
                    },
                },
            ],
        };
        assert!(
            guard_plan(&plan, DEFAULT_OPTS).is_ok(),
            "a unique index on a newly-added column must not be refused"
        );
    }

    #[test]
    fn unique_index_on_new_table_is_allowed() {
        // A unique index on a brand-new table rides inline on `CreateTable` (an
        // empty table — no rows to conflict), never as a top-level `AddIndex`, so
        // it is never refused.
        let mut table = posts_with(vec![col("email", ColumnType::Text)]);
        table.indexes = vec![Index {
            name: "idx_posts_email_unique".to_owned(),
            columns: vec!["email".to_owned()],
            unique: true,
            definition: None,
            is_partial: false,
            key_columns: Vec::new(),
        }];
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::CreateTable(table)],
        };
        assert!(
            guard_plan(&plan, DEFAULT_OPTS).is_ok(),
            "a unique index on a brand-new table must not be refused"
        );
    }

    #[test]
    fn non_unique_index_add_on_existing_column_still_allowed() {
        // Control: a plain (non-unique) index on a pre-existing column is always
        // appliable and must still emit.
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::AddIndex {
                table: "posts".to_owned(),
                index: Index {
                    name: "idx_posts_email".to_owned(),
                    columns: vec!["email".to_owned()],
                    unique: false,
                    definition: None,
                    is_partial: false,
                    key_columns: Vec::new(),
                },
            }],
        };
        assert!(
            guard_plan(&plan, DEFAULT_OPTS).is_ok(),
            "a non-unique index on a pre-existing column must not be refused"
        );
    }

    // -- 13.3 guards ---------------------------------------------------------

    fn drop_column_plan() -> MigrationPlan {
        MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::DropColumn {
                table: "users".to_owned(),
                column: col("nickname", ColumnType::Text),
            }],
        }
    }

    #[test]
    fn drop_column_refused_without_flag() {
        let err = guard_plan(&drop_column_plan(), DEFAULT_OPTS).unwrap_err();
        match err {
            DiffError::Destructive { summary, ops } => {
                assert!(
                    summary.contains("users.nickname"),
                    "names the column: {summary}"
                );
                assert_eq!(
                    ops,
                    vec![DestructiveOp::Column {
                        table: "users".to_owned(),
                        column: "nickname".to_owned(),
                    }]
                );
            }
            other => panic!("expected Destructive, got {other:?}"),
        }
    }

    #[test]
    fn drop_column_allowed_with_flag() {
        assert!(guard_plan(&drop_column_plan(), ALLOW).is_ok());
    }

    #[test]
    fn drop_table_refused_then_allowed() {
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::DropTable(posts_with(vec![]))],
        };
        let err = guard_plan(&plan, DEFAULT_OPTS).unwrap_err();
        assert!(matches!(err, DiffError::Destructive { .. }));
        assert!(guard_plan(&plan, ALLOW).is_ok());
    }

    #[test]
    fn possible_rename_refused() {
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![
                SchemaChange::DropColumn {
                    table: "users".to_owned(),
                    column: col("nickname", ColumnType::Text),
                },
                SchemaChange::AddColumn {
                    table: "users".to_owned(),
                    column: col("handle", ColumnType::Text),
                },
            ],
        };
        let err = guard_plan(&plan, DEFAULT_OPTS).unwrap_err();
        match err {
            DiffError::PossibleRename {
                table,
                dropped,
                added,
            } => {
                assert_eq!(table, "users");
                assert_eq!(dropped, vec!["nickname".to_owned()]);
                assert_eq!(added, vec!["handle".to_owned()]);
                assert!(
                    err_message_mentions_renamed_from(&DiffError::PossibleRename {
                        table: "users".to_owned(),
                        dropped: vec!["nickname".to_owned()],
                        added: vec!["handle".to_owned()],
                    }),
                    "message mentions #[renamed_from]"
                );
            }
            other => panic!("expected PossibleRename, got {other:?}"),
        }
    }

    fn err_message_mentions_renamed_from(err: &DiffError) -> bool {
        err.to_string().contains("#[renamed_from]")
    }

    #[test]
    fn possible_rename_overridden_by_allow_destructive() {
        // The added `handle` is nullable so it is itself appliable — this test
        // exercises the rename→independent-drop/add override in isolation, not the
        // orthogonal required-column guard (an independent add of a NOT NULL,
        // no-default column is unappliable and is refused even under --allow-destructive;
        // see `add_not_null_column_without_default_is_refused`).
        let mut handle = col("handle", ColumnType::Text);
        handle.nullable = true;
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![
                SchemaChange::DropColumn {
                    table: "users".to_owned(),
                    column: col("nickname", ColumnType::Text),
                },
                SchemaChange::AddColumn {
                    table: "users".to_owned(),
                    column: handle,
                },
            ],
        };
        assert!(guard_plan(&plan, ALLOW).is_ok());
    }

    #[test]
    fn primary_key_change_refused() {
        // PK ["id"] → ["uuid_id"] on a both-present managed table.
        let base = vec![posts_with(vec![])];
        let mut want_table = Table::new("posts", Backend::Postgres);
        let mut uuid_id = col("uuid_id", ColumnType::Uuid);
        uuid_id.primary_key = true;
        want_table.primary_key.push("uuid_id".to_owned());
        want_table.columns.push(uuid_id);
        let plan = diff_schema(&base, &parsed(vec![want_table], vec![]), DEFAULT_OPTS);
        assert_eq!(
            plan.changes,
            vec![SchemaChange::PrimaryKeyChange {
                table: "posts".to_owned(),
            }]
        );
        let err = guard_plan(&plan, DEFAULT_OPTS).unwrap_err();
        assert!(matches!(err, DiffError::PrimaryKeyChange { .. }));
        // No override — even --allow-destructive refuses.
        let err = guard_plan(&plan, ALLOW).unwrap_err();
        assert!(matches!(err, DiffError::PrimaryKeyChange { .. }));
    }

    // -- 13.4 managed scoping ------------------------------------------------

    #[test]
    fn unmanaged_desired_table_not_created() {
        let mut t = posts_with(vec![]);
        t.managed = false;
        let plan = diff_schema(&[], &parsed(vec![t], vec![]), DEFAULT_OPTS);
        assert!(
            plan.is_empty(),
            "unmanaged desired table not created: {plan:?}"
        );
    }

    #[test]
    fn unmanaged_baseline_table_not_dropped() {
        let mut t = posts_with(vec![]);
        t.managed = false;
        let plan = diff_schema(&[t], &parsed(vec![], vec![]), DEFAULT_OPTS);
        assert!(
            plan.is_empty(),
            "unmanaged baseline table not dropped: {plan:?}"
        );
    }

    // -- 13.5 SQL emission ---------------------------------------------------

    #[test]
    fn create_table_bigserial_pk_renders_bigserial() {
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::CreateTable(posts_with(vec![col(
                "body",
                ColumnType::Text,
            )]))],
        };
        let up = emit_up_sql(&plan).expect("emit");
        assert!(
            up.contains("id BIGSERIAL PRIMARY KEY"),
            "bigserial PK: {up}"
        );
        assert!(
            !up.contains("id BIGINT"),
            "must not render BIGINT for the id PK: {up}"
        );
        assert!(up.contains("body TEXT NOT NULL"), "body column: {up}");
    }

    #[test]
    fn create_table_uuid_pk_renders_gen_random_uuid() {
        let mut t = Table::new("posts", Backend::Postgres);
        let mut id = col("id", ColumnType::Uuid);
        id.primary_key = true;
        // The model convention default — the exact string `parse::convention_default`
        // records and introspection preserves — is required for the `IdKind::Uuid`
        // shape to render.
        id.default = Some(ColumnDefault::Sql("gen_random_uuid()".to_owned()));
        t.primary_key.push("id".to_owned());
        t.columns.push(id);
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::CreateTable(t)],
        };
        let up = emit_up_sql(&plan).expect("emit");
        assert!(
            up.contains("id UUID PRIMARY KEY DEFAULT gen_random_uuid()"),
            "uuid PK: {up}"
        );
    }

    #[test]
    fn pk_kind_for_uuid_is_gated_on_the_convention_default() {
        // Convention `gen_random_uuid()` default → the `IdKind::Uuid` shape.
        let mut conv = col("id", ColumnType::Uuid);
        conv.primary_key = true;
        conv.default = Some(ColumnDefault::Sql("gen_random_uuid()".to_owned()));
        assert_eq!(pk_kind_for(&conv), Some(IdKind::Uuid));
        // A leading/trailing whitespace variant still resolves (trim-tolerant).
        let mut conv_ws = col("id", ColumnType::Uuid);
        conv_ws.primary_key = true;
        conv_ws.default = Some(ColumnDefault::Sql("  gen_random_uuid()  ".to_owned()));
        assert_eq!(pk_kind_for(&conv_ws), Some(IdKind::Uuid));

        // A non-convention default (`uuid_generate_v4()`) → None (ordinary column).
        let mut v4 = col("id", ColumnType::Uuid);
        v4.primary_key = true;
        v4.default = Some(ColumnDefault::Sql("uuid_generate_v4()".to_owned()));
        assert_eq!(pk_kind_for(&v4), None);

        // No default → None (ordinary column; the PK is expressed table-level).
        let mut none = col("id", ColumnType::Uuid);
        none.primary_key = true;
        assert_eq!(pk_kind_for(&none), None);
    }

    #[test]
    fn pk_kind_for_honors_plain_serial_marker() {
        // An explicit `Some(Plain)` Int64 PK must NOT reconstruct as BigSerial (that
        // would fabricate auto-increment on a rebuild/rollback).
        let mut plain = col("id", ColumnType::Int64);
        plain.primary_key = true;
        plain.serial = Some(SerialKind::Plain);
        assert_eq!(pk_kind_for(&plain), None, "a Plain PK is a plain column");

        // A `BigSerial`-marked (or legacy `None`) Int64 PK keeps the BigSerial shape.
        let mut big = col("id", ColumnType::Int64);
        big.primary_key = true;
        big.serial = Some(SerialKind::BigSerial);
        assert_eq!(pk_kind_for(&big), Some(IdKind::BigSerial));
        let mut legacy = col("id", ColumnType::Int64);
        legacy.primary_key = true; // serial: None (legacy/unknown)
        assert_eq!(pk_kind_for(&legacy), Some(IdKind::BigSerial));
    }

    #[test]
    fn plain_pk_reconstructs_without_bigserial_or_autoincrement() {
        for (backend, forbidden) in [
            (Backend::Postgres, "BIGSERIAL"),
            (Backend::Sqlite, "AUTOINCREMENT"),
        ] {
            let mut t = Table::new("ledger", backend);
            let mut id = col("id", ColumnType::Int64);
            id.primary_key = true;
            id.serial = Some(SerialKind::Plain);
            t.primary_key.push("id".to_owned());
            t.columns.push(id);
            let body = render_create_table_body("ledger", &t, backend);
            assert!(
                !body.contains(forbidden),
                "a Plain PK must not render {forbidden} on {backend:?}: {body}"
            );
            assert!(
                body.contains("PRIMARY KEY (id)"),
                "a Plain PK renders a table-level primary key on {backend:?}: {body}"
            );
        }
    }

    // -- SQLite affinity-aware type comparison -------------------------------

    #[test]
    fn sqlite_type_comparison_is_affinity_aware_but_pg_stays_exact() {
        // On SQLite, types that collapse to the same declared type are equivalent.
        for (a, b) in [
            (ColumnType::Int32, ColumnType::Int64),
            (ColumnType::Int64, ColumnType::Bool),
            (ColumnType::Float32, ColumnType::Float64),
            (ColumnType::Text, ColumnType::Timestamp),
            (ColumnType::Timestamp, ColumnType::TimestampTz),
        ] {
            assert!(
                column_types_equivalent(&a, &b, Backend::Sqlite),
                "{a:?} and {b:?} share a SQLite affinity class"
            );
            // Postgres keeps exact equality — these are genuinely distinct there.
            assert!(
                !column_types_equivalent(&a, &b, Backend::Postgres),
                "{a:?} vs {b:?} must still differ on Postgres"
            );
        }
        // A genuine class change still drifts on SQLite.
        assert!(!column_types_equivalent(
            &ColumnType::Int64,
            &ColumnType::Text,
            Backend::Sqlite
        ));
        assert!(!column_types_equivalent(
            &ColumnType::Bytes,
            &ColumnType::Text,
            Backend::Sqlite
        ));
        // Opaque (verbatim) types require exact equality even on SQLite.
        let a = ColumnType::Opaque {
            pg_type: "citext".to_owned(),
        };
        let b = ColumnType::Opaque {
            pg_type: "hstore".to_owned(),
        };
        assert!(!column_types_equivalent(&a, &b, Backend::Sqlite));
        assert!(column_types_equivalent(&a, &a.clone(), Backend::Sqlite));
    }

    #[test]
    fn sqlite_diff_no_alter_within_affinity_class_but_drifts_across() {
        // Baseline `views: Int64` (pulled), model `views: Int32` — same INTEGER class
        // on SQLite → NO AlterColumnType.
        let mut base = Table::new("posts", Backend::Sqlite);
        base.managed = true;
        base.columns.push(col("views", ColumnType::Int64));
        let mut want = Table::new("posts", Backend::Sqlite);
        want.managed = true;
        want.columns.push(col("views", ColumnType::Int32));
        let plan = diff_schema(
            std::slice::from_ref(&base),
            &parsed(vec![want], vec![]),
            AUTHORITATIVE,
        );
        assert!(
            !plan
                .changes
                .iter()
                .any(|c| matches!(c, SchemaChange::AlterColumnType { .. })),
            "same-class INTEGER change must not drift on SQLite: {:?}",
            plan.changes
        );

        // A cross-class change (Int64 → Text) still drifts.
        let mut want2 = Table::new("posts", Backend::Sqlite);
        want2.managed = true;
        want2.columns.push(col("views", ColumnType::Text));
        let plan2 = diff_schema(&[base], &parsed(vec![want2], vec![]), AUTHORITATIVE);
        assert!(
            plan2
                .changes
                .iter()
                .any(|c| matches!(c, SchemaChange::AlterColumnType { .. })),
            "a cross-class change must still drift on SQLite: {:?}",
            plan2.changes
        );
    }

    /// A convention UUID PK (`DEFAULT gen_random_uuid()`) renders the `IdKind::Uuid`
    /// shape verbatim — the `gen_random_uuid()` default is not double-emitted.
    #[test]
    fn create_table_convention_uuid_pk_renders_id_kind_shape() {
        let mut t = Table::new("sessions", Backend::Postgres);
        let mut id = col("id", ColumnType::Uuid);
        id.primary_key = true;
        id.default = Some(ColumnDefault::Sql("gen_random_uuid()".to_owned()));
        t.primary_key.push("id".to_owned());
        t.columns.push(id);
        let body = render_create_table_body("sessions", &t, Backend::Postgres);
        assert!(
            body.contains("id UUID PRIMARY KEY DEFAULT gen_random_uuid()"),
            "convention UUID PK renders the IdKind::Uuid shape: {body}"
        );
        // Exactly one `gen_random_uuid()` — the explicit column default is not also
        // appended alongside the `IdKind::Uuid` shape's own default.
        assert_eq!(
            body.matches("gen_random_uuid()").count(),
            1,
            "the convention default is emitted exactly once: {body}"
        );
    }

    /// A UUID PK with NO default must NOT gain a `gen_random_uuid()` default on
    /// recreation: it renders as an ordinary `UUID` column plus a table-level
    /// `PRIMARY KEY (id)` clause, preserving "no default".
    #[test]
    fn create_table_uuid_pk_without_default_renders_ordinary_column_with_pk() {
        let mut t = Table::new("tokens", Backend::Postgres);
        let mut id = col("id", ColumnType::Uuid);
        id.primary_key = true;
        t.primary_key.push("id".to_owned());
        t.columns.push(id);
        t.columns.push(col("label", ColumnType::Text));
        let body = render_create_table_body("tokens", &t, Backend::Postgres);
        assert!(
            body.contains("id UUID NOT NULL"),
            "no-default UUID PK renders as an ordinary UUID column: {body}"
        );
        assert!(
            !body.contains("gen_random_uuid()"),
            "no default must be invented on recreation: {body}"
        );
        assert!(
            body.contains("PRIMARY KEY (id)"),
            "the PK is still expressed via the table-level clause: {body}"
        );
    }

    /// A brownfield UUID PK whose default is a NON-convention expression
    /// (`uuid_generate_v4()`) renders that default verbatim — recreation preserves the
    /// real UUID-generation behavior rather than silently swapping it for
    /// `gen_random_uuid()`.
    #[test]
    fn create_table_uuid_pk_with_non_convention_default_renders_it_verbatim() {
        let mut t = Table::new("tokens", Backend::Postgres);
        let mut id = col("id", ColumnType::Uuid);
        id.primary_key = true;
        id.default = Some(ColumnDefault::Sql("uuid_generate_v4()".to_owned()));
        t.primary_key.push("id".to_owned());
        t.columns.push(id);
        let body = render_create_table_body("tokens", &t, Backend::Postgres);
        assert!(
            body.contains("id UUID NOT NULL DEFAULT uuid_generate_v4()"),
            "the real non-convention default renders verbatim: {body}"
        );
        assert!(
            !body.contains("gen_random_uuid()"),
            "the convention default is never substituted: {body}"
        );
        assert!(
            body.contains("PRIMARY KEY (id)"),
            "the PK is still expressed via the table-level clause: {body}"
        );
    }

    /// A brownfield single-column `Int32` PK whose default is a `nextval(...)`
    /// sequence (a `SERIAL PRIMARY KEY`) recreates as `SERIAL PRIMARY KEY` — the
    /// explicit default is suppressed and auto-increment is preserved, mirroring the
    /// `Int64` → `BIGSERIAL` path. It must NOT render `INTEGER … DEFAULT nextval`.
    #[test]
    fn create_table_int4_serial_pk_renders_serial() {
        let mut t = Table::new("counters", Backend::Postgres);
        let mut id = col("id", ColumnType::Int32);
        id.primary_key = true;
        id.default = Some(ColumnDefault::Sql(
            "nextval('counters_id_seq'::regclass)".to_owned(),
        ));
        t.primary_key.push("id".to_owned());
        t.columns.push(id);
        t.columns.push(col("label", ColumnType::Text));
        let body = render_create_table_body("counters", &t, Backend::Postgres);
        assert!(
            body.contains("id SERIAL PRIMARY KEY"),
            "int4 SERIAL PK renders SERIAL: {body}"
        );
        assert!(
            !body.contains("nextval") && !body.contains("id INTEGER"),
            "the explicit nextval default is suppressed (no INTEGER … DEFAULT nextval): {body}"
        );
    }

    /// A single-column `Int32` PK with NO default is a plain integer PK (no
    /// auto-increment): it renders `INTEGER` with a table-level `PRIMARY KEY` clause,
    /// never `SERIAL`.
    #[test]
    fn create_table_int4_pk_without_default_renders_plain_integer() {
        let mut t = Table::new("counters", Backend::Postgres);
        let mut id = col("id", ColumnType::Int32);
        id.primary_key = true;
        t.primary_key.push("id".to_owned());
        t.columns.push(id);
        let body = render_create_table_body("counters", &t, Backend::Postgres);
        assert!(
            !body.contains("SERIAL"),
            "a plain int4 PK must not become SERIAL: {body}"
        );
        assert!(
            body.contains("id INTEGER NOT NULL") && body.contains("PRIMARY KEY (id)"),
            "a plain int4 PK renders a plain INTEGER column with a table-level PRIMARY KEY: {body}"
        );
    }

    /// The existing `Int64` PK path is unchanged: `BIGSERIAL PRIMARY KEY`.
    #[test]
    fn create_table_int8_pk_still_renders_bigserial() {
        let t = posts_with(vec![col("body", ColumnType::Text)]);
        let body = render_create_table_body("posts", &t, Backend::Postgres);
        assert!(
            body.contains("id BIGSERIAL PRIMARY KEY"),
            "int8 PK renders BIGSERIAL: {body}"
        );
    }

    #[test]
    fn create_table_composite_pk_uses_table_clause() {
        let mut t = Table::new("memberships", Backend::Postgres);
        let mut a = col("user_id", ColumnType::Int64);
        a.primary_key = true;
        let mut b = col("group_id", ColumnType::Int64);
        b.primary_key = true;
        t.columns.push(a);
        t.columns.push(b);
        t.primary_key.push("user_id".to_owned());
        t.primary_key.push("group_id".to_owned());
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::CreateTable(t)],
        };
        let up = emit_up_sql(&plan).expect("emit");
        assert!(
            up.contains("user_id BIGINT NOT NULL"),
            "columns rendered normally: {up}"
        );
        assert!(
            up.contains("PRIMARY KEY (user_id, group_id)"),
            "table-level PK: {up}"
        );
    }

    #[test]
    fn add_column_not_null_no_default_has_safety_comment() {
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::AddColumn {
                table: "posts".to_owned(),
                column: col("title", ColumnType::Text),
            }],
        };
        let up = emit_up_sql(&plan).expect("emit");
        assert!(
            up.contains("-- autumn-safety: potentially-blocking"),
            "safety comment: {up}"
        );
        assert!(
            up.contains("ALTER TABLE posts ADD COLUMN title TEXT NOT NULL;"),
            "{up}"
        );
    }

    #[test]
    fn add_column_nullable_no_safety_comment() {
        let mut bio = col("bio", ColumnType::Text);
        bio.nullable = true;
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::AddColumn {
                table: "posts".to_owned(),
                column: bio,
            }],
        };
        let up = emit_up_sql(&plan).expect("emit");
        assert!(
            !up.contains("autumn-safety"),
            "no safety comment for nullable: {up}"
        );
        assert!(
            up.contains("ALTER TABLE posts ADD COLUMN bio TEXT NULL;"),
            "{up}"
        );
    }

    #[test]
    fn add_not_null_column_without_default_is_refused() {
        // Adding a NOT NULL, no-default column to an *existing* table is unappliable
        // on a table that already has rows — refused, with no override.
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::AddColumn {
                table: "posts".to_owned(),
                column: col("title", ColumnType::Text),
            }],
        };
        let err = guard_plan(&plan, DEFAULT_OPTS).unwrap_err();
        match &err {
            DiffError::RequiredColumnWithoutDefault { table, column } => {
                assert_eq!(table, "posts");
                assert_eq!(column, "title");
            }
            other => panic!("expected RequiredColumnWithoutDefault, got {other:?}"),
        }
        assert!(
            err.to_string()
                .contains("cannot add required column `posts.title`"),
            "message: {err}"
        );
        // No override — --allow-destructive does not permit it (it is unappliable,
        // not merely destructive).
        assert!(
            matches!(
                guard_plan(&plan, ALLOW).unwrap_err(),
                DiffError::RequiredColumnWithoutDefault { .. }
            ),
            "must refuse even with --allow-destructive"
        );
    }

    #[test]
    fn add_not_null_column_with_default_is_allowed() {
        // A NOT NULL column WITH a default is appliable (existing rows get the
        // default) — emit it normally, do not refuse.
        let mut created = col("created_at", ColumnType::Timestamp);
        created.default = Some(ColumnDefault::Now);
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::AddColumn {
                table: "posts".to_owned(),
                column: created,
            }],
        };
        guard_plan(&plan, DEFAULT_OPTS).expect("NOT NULL with a default is appliable");
        let up = emit_up_sql(&plan).expect("emit");
        assert!(
            up.contains(
                "ALTER TABLE posts ADD COLUMN created_at TIMESTAMP NOT NULL DEFAULT NOW();"
            ),
            "{up}"
        );
    }

    #[test]
    fn add_nullable_column_is_allowed() {
        // A nullable added column is always appliable.
        let mut bio = col("bio", ColumnType::Text);
        bio.nullable = true;
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::AddColumn {
                table: "posts".to_owned(),
                column: bio,
            }],
        };
        guard_plan(&plan, DEFAULT_OPTS).expect("nullable add is appliable");
        let up = emit_up_sql(&plan).expect("emit");
        assert!(
            up.contains("ALTER TABLE posts ADD COLUMN bio TEXT NULL;"),
            "{up}"
        );
    }

    #[test]
    fn create_table_with_not_null_no_default_column_is_not_refused() {
        // A NOT NULL, no-default column inside a brand-new CreateTable is fine —
        // the table is empty — so the required-column guard must NOT fire on it.
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::CreateTable(posts_with(vec![col(
                "title",
                ColumnType::Text,
            )]))],
        };
        guard_plan(&plan, DEFAULT_OPTS).expect("CreateTable with a NOT NULL column is empty-safe");
        let up = emit_up_sql(&plan).expect("emit");
        assert!(up.contains("title TEXT NOT NULL"), "{up}");
    }

    #[test]
    fn set_not_null_on_existing_column_is_refused() {
        // Turning an existing nullable column non-null is unappliable on a table
        // whose column already holds NULLs — refused, with no override (the exact
        // sibling of the required-column refusal).
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::SetNotNull {
                table: "posts".to_owned(),
                column: "bio".to_owned(),
            }],
        };
        let err = guard_plan(&plan, DEFAULT_OPTS).unwrap_err();
        match &err {
            DiffError::SetNotNullRequiresBackfill { table, column } => {
                assert_eq!(table, "posts");
                assert_eq!(column, "bio");
            }
            other => panic!("expected SetNotNullRequiresBackfill, got {other:?}"),
        }
        assert!(
            err.to_string().contains("cannot set `posts.bio` NOT NULL"),
            "message: {err}"
        );
        // No override — --allow-destructive does not permit it (it is unappliable,
        // not merely destructive).
        assert!(
            matches!(
                guard_plan(&plan, ALLOW).unwrap_err(),
                DiffError::SetNotNullRequiresBackfill { .. }
            ),
            "must refuse even with --allow-destructive"
        );
    }

    #[test]
    fn drop_not_null_is_allowed() {
        // The inverse (non-null → nullable) is always appliable — emit it
        // normally, never refuse.
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::DropNotNull {
                table: "posts".to_owned(),
                column: "bio".to_owned(),
            }],
        };
        guard_plan(&plan, DEFAULT_OPTS).expect("DROP NOT NULL is always appliable");
        let up = emit_up_sql(&plan).expect("emit");
        assert!(
            up.contains("ALTER TABLE posts ALTER COLUMN bio DROP NOT NULL;"),
            "{up}"
        );
    }

    #[test]
    fn add_column_renders_only_the_column_not_the_index() {
        // The `AddColumn` renderer is NOT the index owner: a lone `AddColumn` for a
        // reference column emits the column + its FK clause but no `CREATE INDEX`.
        // The reference auto-index arrives as a separate `AddIndex` (see
        // `add_reference_column_emits_index_exactly_once`), so rendering it inline
        // here would double it and the migration would fail.
        let mut author = col("author_id", ColumnType::Int64);
        author.nullable = true;
        author.references = Some(ForeignKey::new("users", "id"));
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::AddColumn {
                table: "posts".to_owned(),
                column: author,
            }],
        };
        let up = emit_up_sql(&plan).expect("emit");
        assert!(up.contains("REFERENCES users(id)"), "fk clause: {up}");
        assert!(
            !up.contains("CREATE INDEX"),
            "the reference index is a separate AddIndex change, not inline: {up}"
        );
    }

    #[test]
    fn add_reference_column_emits_index_exactly_once() {
        // Regression (finding 2): the slice-2 parser folds `idx_<t>_<c>` into
        // `table.indexes` AND the column carries `references`. Diffing a new
        // reference column onto an existing table therefore yields both an
        // `AddColumn` and an `AddIndex` for that index — the emitted up.sql must
        // contain the `CREATE INDEX` exactly once, never a duplicate.
        let base = vec![posts_with(vec![])];
        let mut author = col("author_id", ColumnType::Int64);
        author.nullable = true;
        author.references = Some(ForeignKey::new("users", "id"));
        let mut want_table = posts_with(vec![author]);
        want_table.indexes.push(Index {
            name: "idx_posts_author_id".to_owned(),
            columns: vec!["author_id".to_owned()],
            unique: false,
            definition: None,
            is_partial: false,
            key_columns: Vec::new(),
        });
        let plan = diff_schema(&base, &parsed(vec![want_table], vec![]), DEFAULT_OPTS);
        let up = emit_up_sql(&plan).expect("emit");
        assert_eq!(
            up.matches("CREATE INDEX idx_posts_author_id").count(),
            1,
            "the reference index must be emitted exactly once: {up}"
        );
        // And the column itself is still added.
        assert!(
            up.contains("ALTER TABLE posts ADD COLUMN author_id BIGINT NULL REFERENCES users(id);"),
            "the column is still added: {up}"
        );
    }

    #[test]
    fn alter_type_and_set_not_null_templates() {
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![
                SchemaChange::AlterColumnType {
                    table: "posts".to_owned(),
                    column: "views".to_owned(),
                    from: ColumnType::Int32,
                    to: ColumnType::Int64,
                },
                SchemaChange::SetNotNull {
                    table: "posts".to_owned(),
                    column: "views".to_owned(),
                },
            ],
        };
        let up = emit_up_sql(&plan).expect("emit");
        assert!(
            up.contains("ALTER TABLE posts ALTER COLUMN views TYPE BIGINT;"),
            "{up}"
        );
        assert!(
            up.contains("ALTER TABLE posts ALTER COLUMN views SET NOT NULL;"),
            "{up}"
        );
    }

    #[test]
    fn create_unique_index_and_drop_index_templates() {
        let up = index_sql(
            "posts",
            &Index {
                name: "idx_posts_slug_unique".to_owned(),
                columns: vec!["slug".to_owned()],
                unique: true,
                definition: None,
                is_partial: false,
                key_columns: Vec::new(),
            },
        );
        assert_eq!(
            up,
            "CREATE UNIQUE INDEX idx_posts_slug_unique ON posts (slug);"
        );

        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::DropIndex {
                table: "posts".to_owned(),
                index: Index {
                    name: "idx_posts_slug".to_owned(),
                    columns: vec!["slug".to_owned()],
                    unique: false,
                    definition: None,
                    is_partial: false,
                    key_columns: Vec::new(),
                },
            }],
        };
        // DropIndex is not destructive, so it emits without a guard.
        let sql = emit_up_sql(&plan).expect("emit");
        assert_eq!(sql, "DROP INDEX idx_posts_slug;\n");
    }

    #[test]
    fn up_ordering_is_canonical() {
        // A mixed plan should render create → add col → drop col → drop table.
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![
                SchemaChange::DropTable(Table::new("legacy", Backend::Postgres)),
                SchemaChange::DropColumn {
                    table: "posts".to_owned(),
                    column: col("old", ColumnType::Text),
                },
                SchemaChange::AddIndex {
                    table: "posts".to_owned(),
                    index: Index {
                        name: "idx_posts_new".to_owned(),
                        columns: vec!["new".to_owned()],
                        unique: false,
                        definition: None,
                        is_partial: false,
                        key_columns: Vec::new(),
                    },
                },
                SchemaChange::AddColumn {
                    table: "posts".to_owned(),
                    column: {
                        let mut c = col("new", ColumnType::Text);
                        c.nullable = true;
                        c
                    },
                },
                SchemaChange::CreateTable(posts_with(vec![])),
            ],
        };
        let up = emit_up_sql(&plan).expect("emit");
        let create = up.find("CREATE TABLE posts").expect("create present");
        let add = up.find("ADD COLUMN new").expect("add present");
        let index = up.find("idx_posts_new").expect("index present");
        let drop_col = up.find("DROP COLUMN old").expect("drop col present");
        let drop_table = up.find("DROP TABLE legacy").expect("drop table present");
        assert!(create < add, "create before add");
        assert!(add < index, "add before index");
        assert!(index < drop_col, "index before drop col");
        assert!(drop_col < drop_table, "drop col before drop table");
    }

    #[test]
    fn replaced_index_drops_before_add_in_up_and_inverts_in_down() {
        // Regression (finding 3): a same-named index whose shape changed becomes a
        // DropIndex(old) + AddIndex(new). In up.sql the DROP must precede the
        // CREATE (same name) or PG rejects the create; in down.sql the inverse
        // must drop the new before recreating the old.
        let old = Index {
            name: "idx_posts_slug".to_owned(),
            columns: vec!["slug".to_owned()],
            unique: false,
            definition: None,
            is_partial: false,
            key_columns: Vec::new(),
        };
        let new = Index {
            name: "idx_posts_slug".to_owned(),
            columns: vec!["slug".to_owned()],
            unique: true,
            definition: None,
            is_partial: false,
            key_columns: Vec::new(),
        };
        let mut base_table = posts_with(vec![col("slug", ColumnType::Text)]);
        base_table.indexes.push(old);
        let mut want_table = posts_with(vec![col("slug", ColumnType::Text)]);
        want_table.indexes.push(new);

        let plan = diff_schema(
            &[base_table],
            &parsed(vec![want_table], vec![]),
            DEFAULT_OPTS,
        );
        // Sanity: it really is a drop+add of the same name.
        assert_eq!(plan.changes.len(), 2, "drop+add of the same name: {plan:?}");

        let up = emit_up_sql(&plan).expect("emit");
        let drop = up
            .find("DROP INDEX idx_posts_slug;")
            .expect("up drop present");
        let create = up
            .find("CREATE UNIQUE INDEX idx_posts_slug")
            .expect("up create present");
        assert!(
            drop < create,
            "DROP must precede CREATE for a replaced index: {up}"
        );

        let down = emit_down_sql(&plan).expect("emit");
        let d_drop = down
            .find("DROP INDEX idx_posts_slug;")
            .expect("down drop present");
        let d_create = down
            .find("CREATE INDEX idx_posts_slug ON posts (slug);")
            .expect("down recreate (old, non-unique) present");
        assert!(
            d_drop < d_create,
            "down: drop the new before recreating the old: {down}"
        );
    }

    #[test]
    fn unrelated_drop_index_still_after_add_index() {
        // A DropIndex whose name is NOT re-added keeps the general (late) drop
        // bucket, so an unrelated add still renders before it.
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![
                SchemaChange::DropIndex {
                    table: "posts".to_owned(),
                    index: Index {
                        name: "idx_posts_old".to_owned(),
                        columns: vec!["old".to_owned()],
                        unique: false,
                        definition: None,
                        is_partial: false,
                        key_columns: Vec::new(),
                    },
                },
                SchemaChange::AddIndex {
                    table: "posts".to_owned(),
                    index: Index {
                        name: "idx_posts_new".to_owned(),
                        columns: vec!["new".to_owned()],
                        unique: false,
                        definition: None,
                        is_partial: false,
                        key_columns: Vec::new(),
                    },
                },
            ],
        };
        let up = emit_up_sql(&plan).expect("emit");
        let add = up.find("CREATE INDEX idx_posts_new").expect("add present");
        let drop = up.find("DROP INDEX idx_posts_old;").expect("drop present");
        assert!(
            add < drop,
            "an unrelated add still precedes an unrelated drop: {up}"
        );
    }

    #[test]
    fn create_tables_topologically_ordered_by_fk() {
        // Regression (finding 4): two new managed tables where `comments`
        // references `posts`. Lexically `comments` < `posts`, so a naive sort
        // would CREATE comments (REFERENCES posts) before posts exists → invalid.
        // The referenced table must be created first, and dropped last.
        let posts = posts_with(vec![col("body", ColumnType::Text)]);
        let mut post_ref = col("post_id", ColumnType::Int64);
        post_ref.references = Some(ForeignKey::new("posts", "id"));
        let comments = posts_ref_table("comments", post_ref);

        let plan = diff_schema(&[], &parsed(vec![comments, posts], vec![]), DEFAULT_OPTS);
        let up = emit_up_sql(&plan).expect("emit");
        let p = up.find("CREATE TABLE posts").expect("posts present");
        let c = up.find("CREATE TABLE comments").expect("comments present");
        assert!(
            p < c,
            "referenced `posts` must be created before referencing `comments`: {up}"
        );

        let down = emit_down_sql(&plan).expect("emit");
        let dp = down.find("DROP TABLE posts").expect("down posts");
        let dc = down.find("DROP TABLE comments").expect("down comments");
        assert!(
            dc < dp,
            "down: drop referencing `comments` before referenced `posts`: {down}"
        );
    }

    #[test]
    fn create_table_fk_cycle_is_refused() {
        // Two new tables referencing each other via inline FKs → unsatisfiable
        // (inline REFERENCES cannot express a cycle) → refused, not invalid SQL.
        let mut a_b = col("b_id", ColumnType::Int64);
        a_b.references = Some(ForeignKey::new("b", "id"));
        let table_a = posts_ref_table("a", a_b);
        let mut b_a = col("a_id", ColumnType::Int64);
        b_a.references = Some(ForeignKey::new("a", "id"));
        let table_b = posts_ref_table("b", b_a);

        let plan = diff_schema(&[], &parsed(vec![table_a, table_b], vec![]), DEFAULT_OPTS);
        let err = emit_up_sql(&plan).unwrap_err();
        let EmitError::CyclicTableDependencies { tables } = &err else {
            panic!("expected CyclicTableDependencies, got {err:?}");
        };
        assert_eq!(
            *tables,
            vec!["a".to_owned(), "b".to_owned()],
            "names the cycle"
        );
    }

    #[test]
    fn down_add_column_inverts_to_drop_clean() {
        let mut bio = col("bio", ColumnType::Text);
        bio.nullable = true;
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::AddColumn {
                table: "posts".to_owned(),
                column: bio,
            }],
        };
        let down = emit_down_sql(&plan).expect("emit");
        assert_eq!(down, "ALTER TABLE posts DROP COLUMN bio;\n");
        assert!(!down.contains("irreversible"), "clean, no marker: {down}");
    }

    #[test]
    fn down_drop_column_reads_add_with_irreversible_marker() {
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::DropColumn {
                table: "posts".to_owned(),
                column: {
                    let mut c = col("nickname", ColumnType::Text);
                    c.nullable = true;
                    c
                },
            }],
        };
        let down = emit_down_sql(&plan).expect("emit");
        assert!(
            down.contains("-- irreversible: column data dropped"),
            "irreversible marker: {down}"
        );
        assert!(
            down.contains("ALTER TABLE posts ADD COLUMN nickname TEXT NULL;"),
            "re-adds from baseline: {down}"
        );
    }

    #[test]
    fn down_drop_table_recreates_with_marker() {
        let mut t = posts_with(vec![col("body", ColumnType::Text)]);
        t.indexes.push(Index {
            name: "idx_posts_body".to_owned(),
            columns: vec!["body".to_owned()],
            unique: false,
            definition: None,
            is_partial: false,
            key_columns: Vec::new(),
        });
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::DropTable(t)],
        };
        let down = emit_down_sql(&plan).expect("emit");
        assert!(
            down.contains("-- irreversible: table data dropped"),
            "marker: {down}"
        );
        assert!(
            down.contains("CREATE TABLE posts"),
            "recreates the table: {down}"
        );
        assert!(
            down.contains("id BIGSERIAL PRIMARY KEY"),
            "recreates PK: {down}"
        );
        assert!(
            down.contains("CREATE INDEX idx_posts_body ON posts (body);"),
            "recreates its indexes: {down}"
        );
    }

    #[test]
    fn down_alter_type_marked_irreversible() {
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::AlterColumnType {
                table: "posts".to_owned(),
                column: "views".to_owned(),
                from: ColumnType::Int32,
                to: ColumnType::Int64,
            }],
        };
        let down = emit_down_sql(&plan).expect("emit");
        assert!(
            down.contains("-- irreversible: a narrowing type change"),
            "marker: {down}"
        );
        assert!(
            down.contains("ALTER TABLE posts ALTER COLUMN views TYPE INTEGER;"),
            "structural inverse restores the `from` type: {down}"
        );
    }

    #[test]
    fn down_set_default_from_none_drops_default() {
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::SetDefault {
                table: "posts".to_owned(),
                column: "created_at".to_owned(),
                to: ColumnDefault::Now,
                from: None,
            }],
        };
        let down = emit_down_sql(&plan).expect("emit");
        assert_eq!(
            down,
            "ALTER TABLE posts ALTER COLUMN created_at DROP DEFAULT;\n"
        );
    }

    #[test]
    fn down_set_default_from_some_restores_it() {
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::SetDefault {
                table: "posts".to_owned(),
                column: "status".to_owned(),
                to: ColumnDefault::Sql("'live'".to_owned()),
                from: Some(ColumnDefault::Sql("'draft'".to_owned())),
            }],
        };
        let down = emit_down_sql(&plan).expect("emit");
        assert_eq!(
            down,
            "ALTER TABLE posts ALTER COLUMN status SET DEFAULT 'draft';\n"
        );
    }

    #[test]
    fn clean_plan_down_has_no_markers() {
        let mut bio = col("bio", ColumnType::Text);
        bio.nullable = true;
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![
                SchemaChange::CreateTable(posts_with(vec![])),
                SchemaChange::AddColumn {
                    table: "posts".to_owned(),
                    column: bio,
                },
                SchemaChange::AddIndex {
                    table: "posts".to_owned(),
                    index: Index {
                        name: "idx_posts_bio".to_owned(),
                        columns: vec!["bio".to_owned()],
                        unique: false,
                        definition: None,
                        is_partial: false,
                        key_columns: Vec::new(),
                    },
                },
            ],
        };
        let down = emit_down_sql(&plan).expect("emit");
        assert!(!down.contains("irreversible"), "no markers: {down}");
        assert!(!down.contains("manual"), "no markers: {down}");
    }

    #[test]
    fn down_add_check_named_drops_constraint_unnamed_is_manual() {
        let named = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::AddCheck {
                table: "posts".to_owned(),
                check: CheckConstraint {
                    name: Some("posts_body_len".to_owned()),
                    expression: "length(body) > 0".to_owned(),
                },
            }],
        };
        assert_eq!(
            emit_down_sql(&named).expect("emit"),
            "ALTER TABLE posts DROP CONSTRAINT posts_body_len;\n"
        );

        let unnamed = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::AddCheck {
                table: "posts".to_owned(),
                check: CheckConstraint {
                    name: None,
                    expression: "length(body) > 0".to_owned(),
                },
            }],
        };
        assert!(
            emit_down_sql(&unnamed)
                .expect("emit")
                .contains("-- manual: unnamed CHECK cannot be auto-dropped"),
            "unnamed check → manual note"
        );
    }

    #[test]
    fn add_foreign_key_up_and_down() {
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::AddForeignKey {
                table: "posts".to_owned(),
                column: "author_id".to_owned(),
                foreign_key: ForeignKey::new("users", "id"),
            }],
        };
        let up = emit_up_sql(&plan).expect("emit");
        assert_eq!(
            up,
            "ALTER TABLE posts ADD CONSTRAINT posts_author_id_fkey \
             FOREIGN KEY (author_id) REFERENCES users(id);\n"
        );
        let down = emit_down_sql(&plan).expect("emit");
        assert_eq!(
            down,
            "ALTER TABLE posts DROP CONSTRAINT posts_author_id_fkey;\n"
        );
    }

    /// A `SQLite`-tagged table: a `BigSerial` `id` PK plus the given extra columns
    /// and indexes.
    fn sqlite_table(name: &str, extra: Vec<Column>, indexes: Vec<Index>) -> Table {
        let mut t = Table::new(name, Backend::Sqlite);
        let mut id = col("id", ColumnType::Int64);
        id.primary_key = true;
        t.primary_key.push("id".to_owned());
        t.columns.push(id);
        t.columns.extend(extra);
        t.indexes = indexes;
        t
    }

    /// The shared fixture for the `SQLite` rebuild golden/coalescing/real-DB tests:
    /// `posts` alters `views` `Int32` → `Int64` and adds an index on `body`.
    fn sqlite_rebuild_fixture() -> (MigrationPlan, SchemaContext) {
        let idx = Index {
            name: "idx_posts_body".to_owned(),
            columns: vec!["body".to_owned()],
            unique: false,
            definition: None,
            is_partial: false,
            key_columns: Vec::new(),
        };
        let baseline = sqlite_table(
            "posts",
            vec![
                col("views", ColumnType::Int32),
                col("body", ColumnType::Text),
            ],
            vec![],
        );
        let desired = sqlite_table(
            "posts",
            vec![
                col("views", ColumnType::Int64),
                col("body", ColumnType::Text),
            ],
            vec![idx.clone()],
        );
        let plan = MigrationPlan {
            backend: Backend::Sqlite,
            changes: vec![
                SchemaChange::AlterColumnType {
                    table: "posts".to_owned(),
                    column: "views".to_owned(),
                    from: ColumnType::Int32,
                    to: ColumnType::Int64,
                },
                SchemaChange::AddIndex {
                    table: "posts".to_owned(),
                    index: idx,
                },
            ],
        };
        let ctx = SchemaContext::from_tables(
            std::slice::from_ref(&desired),
            std::slice::from_ref(&baseline),
        );
        (plan, ctx)
    }

    #[test]
    fn sqlite_alter_type_renders_table_rebuild_up_golden() {
        let (plan, ctx) = sqlite_rebuild_fixture();
        let up = emit_up_sql_with_context(&plan, &ctx).expect("emit up");
        let expected = "\
-- autumn: SQLite table rebuild for `posts` — ALTER-family changes require a full table recreate.
-- Transaction semantics: this migration must run inside a single transaction (diesel wraps each
-- migration in one). NOTE: `PRAGMA foreign_keys` is a no-op inside a transaction, so the harness
-- must ensure foreign-key enforcement is disabled around the migration.
-- autumn-safety: this recreate copies columns and re-creates indexes only. DROP TABLE drops the table's TRIGGERS (not restored here); VIEWS that reference the table are not dropped and may be left dangling or block the rename — re-create triggers and repair dependent views in a manual migration.
-- autumn-safety: `PRAGMA foreign_key_check` below only REPORTS violation rows (it does not raise); the recreate copies existing values verbatim and introduces no new orphans, but the migration runner must inspect the pragma's output to treat any pre-existing orphan as an error.
PRAGMA foreign_keys=OFF;
-- preserve the AUTOINCREMENT high-water mark so IDs issued-then-deleted are never reused
CREATE TEMP TABLE _autumn_seq_posts AS SELECT seq FROM sqlite_sequence WHERE name = 'posts';
CREATE TABLE posts__autumn_new (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    views INTEGER NOT NULL,
    body TEXT NOT NULL
);
INSERT INTO posts__autumn_new (id, views, body)
    SELECT id, views, body FROM posts;
DROP TABLE posts;
PRAGMA legacy_alter_table=ON;
ALTER TABLE posts__autumn_new RENAME TO posts;
PRAGMA legacy_alter_table=OFF;
CREATE INDEX idx_posts_body ON posts (body);
UPDATE sqlite_sequence SET seq = (SELECT seq FROM _autumn_seq_posts)
    WHERE name = 'posts' AND (SELECT seq FROM _autumn_seq_posts) IS NOT NULL;
INSERT INTO sqlite_sequence (name, seq)
    SELECT 'posts', (SELECT seq FROM _autumn_seq_posts)
    WHERE (SELECT seq FROM _autumn_seq_posts) IS NOT NULL
      AND NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = 'posts');
DROP TABLE _autumn_seq_posts;
PRAGMA foreign_key_check;
PRAGMA foreign_keys=ON;
";
        assert_eq!(up, expected, "SQLite up rebuild golden:\n{up}");
    }

    #[test]
    fn sqlite_alter_type_renders_table_rebuild_down_golden() {
        let (plan, ctx) = sqlite_rebuild_fixture();
        let down = emit_down_sql_with_context(&plan, &ctx).expect("emit down");
        let expected = "\
-- irreversible: a SQLite table rebuild rolled back to the prior shape may not restore data lost by a narrowing type change or dropped column
-- autumn: SQLite table rebuild for `posts` — ALTER-family changes require a full table recreate.
-- Transaction semantics: this migration must run inside a single transaction (diesel wraps each
-- migration in one). NOTE: `PRAGMA foreign_keys` is a no-op inside a transaction, so the harness
-- must ensure foreign-key enforcement is disabled around the migration.
-- autumn-safety: this recreate copies columns and re-creates indexes only. DROP TABLE drops the table's TRIGGERS (not restored here); VIEWS that reference the table are not dropped and may be left dangling or block the rename — re-create triggers and repair dependent views in a manual migration.
-- autumn-safety: `PRAGMA foreign_key_check` below only REPORTS violation rows (it does not raise); the recreate copies existing values verbatim and introduces no new orphans, but the migration runner must inspect the pragma's output to treat any pre-existing orphan as an error.
PRAGMA foreign_keys=OFF;
-- preserve the AUTOINCREMENT high-water mark so IDs issued-then-deleted are never reused
CREATE TEMP TABLE _autumn_seq_posts AS SELECT seq FROM sqlite_sequence WHERE name = 'posts';
CREATE TABLE posts__autumn_new (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    views INTEGER NOT NULL,
    body TEXT NOT NULL
);
INSERT INTO posts__autumn_new (id, views, body)
    SELECT id, views, body FROM posts;
DROP TABLE posts;
PRAGMA legacy_alter_table=ON;
ALTER TABLE posts__autumn_new RENAME TO posts;
PRAGMA legacy_alter_table=OFF;
UPDATE sqlite_sequence SET seq = (SELECT seq FROM _autumn_seq_posts)
    WHERE name = 'posts' AND (SELECT seq FROM _autumn_seq_posts) IS NOT NULL;
INSERT INTO sqlite_sequence (name, seq)
    SELECT 'posts', (SELECT seq FROM _autumn_seq_posts)
    WHERE (SELECT seq FROM _autumn_seq_posts) IS NOT NULL
      AND NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = 'posts');
DROP TABLE _autumn_seq_posts;
PRAGMA foreign_key_check;
PRAGMA foreign_keys=ON;
";
        assert_eq!(down, expected, "SQLite down rebuild golden:\n{down}");
    }

    #[test]
    fn sqlite_down_rebuild_preserves_parser_invisible_column() {
        // A rebuild triggered by an UNRELATED change (`views` Int32 -> Int64) must,
        // on the DOWN leg, copy back a baseline column the partial parser cannot see
        // (here `status`, absent from `ctx.desired`). The post-migration table (what
        // is actually in the DB at rollback time) is `baseline + deltas`, which still
        // carries `status`, so the down-leg INSERT..SELECT source must be that shape —
        // not `ctx.desired`, whose partial view would omit `status` and lose its data.
        let mut status_baseline = col("status", ColumnType::Text);
        status_baseline.default = Some(ColumnDefault::Sql("'draft'".to_owned()));
        let baseline = sqlite_table(
            "posts",
            vec![
                col("views", ColumnType::Int32),
                col("body", ColumnType::Text),
                status_baseline,
            ],
            vec![],
        );
        // The parser's blind spot: `status` is absent from the desired view entirely.
        let desired = sqlite_table(
            "posts",
            vec![
                col("views", ColumnType::Int64),
                col("body", ColumnType::Text),
            ],
            vec![],
        );
        let plan = MigrationPlan {
            backend: Backend::Sqlite,
            changes: vec![SchemaChange::AlterColumnType {
                table: "posts".to_owned(),
                column: "views".to_owned(),
                from: ColumnType::Int32,
                to: ColumnType::Int64,
            }],
        };
        let ctx = SchemaContext::from_tables(
            std::slice::from_ref(&desired),
            std::slice::from_ref(&baseline),
        );

        let down = emit_down_sql_with_context(&plan, &ctx).expect("emit down");
        assert!(
            down.contains(
                "INSERT INTO posts__autumn_new (id, views, body, status)\n    \
                 SELECT id, views, body, status FROM posts;"
            ),
            "the down rollback copies back the parser-invisible retained column: {down}"
        );

        // Pin the up leg too: it copies from the baseline (which carries `status`) into
        // the baseline+deltas shape (which also carries it), so `status` round-trips.
        let up = emit_up_sql_with_context(&plan, &ctx).expect("emit up");
        assert!(
            up.contains(
                "INSERT INTO posts__autumn_new (id, views, body, status)\n    \
                 SELECT id, views, body, status FROM posts;"
            ),
            "the up rebuild also carries the parser-invisible retained column: {up}"
        );
    }

    #[test]
    fn postgres_alter_type_still_emits_plain_alter_column() {
        // The same logical change on Postgres emits the direct ALTER, never a rebuild.
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::AlterColumnType {
                table: "posts".to_owned(),
                column: "views".to_owned(),
                from: ColumnType::Int32,
                to: ColumnType::Int64,
            }],
        };
        let up = emit_up_sql(&plan).expect("emit up");
        assert_eq!(
            up, "ALTER TABLE posts ALTER COLUMN views TYPE BIGINT;\n",
            "{up}"
        );
        assert!(!up.contains("__autumn_new"), "no rebuild on Postgres: {up}");
    }

    #[test]
    fn sqlite_rebuild_coalesces_alter_and_index_into_one_block() {
        // An AlterColumnType and an AddIndex on the same table produce exactly ONE
        // rebuild block; the index is recreated inside it (after the rename), never
        // as a separate top-level CREATE INDEX.
        let (plan, ctx) = sqlite_rebuild_fixture();
        let up = emit_up_sql_with_context(&plan, &ctx).expect("emit up");
        assert_eq!(
            up.matches("CREATE TABLE posts__autumn_new").count(),
            1,
            "exactly one rebuild block: {up}"
        );
        assert_eq!(
            up.matches("CREATE INDEX idx_posts_body").count(),
            1,
            "the index is created exactly once: {up}"
        );
        let rename = up.find("RENAME TO posts").expect("rename present");
        let index = up
            .find("CREATE INDEX idx_posts_body ON posts (body);")
            .expect("index recreated");
        assert!(
            index > rename,
            "the index is recreated as part of the rebuild, after the rename: {up}"
        );
    }

    #[test]
    fn sqlite_rebuild_copies_only_surviving_columns() {
        // A rebuild that also drops a column copies only the columns common to both
        // shapes — the dropped `legacy` column is never named in INSERT..SELECT.
        let mut legacy = col("legacy", ColumnType::Text);
        legacy.nullable = true;
        let baseline = sqlite_table(
            "posts",
            vec![col("views", ColumnType::Int32), legacy.clone()],
            vec![],
        );
        let desired = sqlite_table("posts", vec![col("views", ColumnType::Int64)], vec![]);
        let plan = MigrationPlan {
            backend: Backend::Sqlite,
            changes: vec![
                SchemaChange::AlterColumnType {
                    table: "posts".to_owned(),
                    column: "views".to_owned(),
                    from: ColumnType::Int32,
                    to: ColumnType::Int64,
                },
                SchemaChange::DropColumn {
                    table: "posts".to_owned(),
                    column: legacy,
                },
            ],
        };
        let ctx = SchemaContext::from_tables(
            std::slice::from_ref(&desired),
            std::slice::from_ref(&baseline),
        );
        let up = emit_up_sql_with_context(&plan, &ctx).expect("emit up");
        assert!(
            up.contains(
                "INSERT INTO posts__autumn_new (id, views)\n    SELECT id, views FROM posts;"
            ),
            "copies only the surviving columns: {up}"
        );
        // The dropped column is absent from the recreated table shape (and therefore
        // never copied). Match `legacy TEXT` (the column definition) specifically rather
        // than the bare substring `legacy`, which now also appears in the unrelated
        // `PRAGMA legacy_alter_table` rename guard.
        assert!(
            !up.contains("legacy TEXT"),
            "dropped column is absent from the recreated shape: {up}"
        );
    }

    #[test]
    fn sqlite_rebuild_preserves_parser_invisible_baseline_default() {
        // A rebuild triggered by an UNRELATED change (here `views` Int32 -> Int64)
        // must not silently drop a baseline facet the partial parser cannot see. The
        // baseline `status` column carries a non-convention default (`'draft'`) and
        // the table a hand-written CHECK; the desired (parser) view records neither
        // and emits NO SetDefault/DropDefault/DropCheck (the engine has no such
        // variant). Building the up-leg recreate shape from `baseline + deltas`
        // instead of the raw `desired` table preserves both.
        let mut status_baseline = col("status", ColumnType::Text);
        status_baseline.default = Some(ColumnDefault::Sql("'draft'".to_owned()));
        let mut baseline = sqlite_table(
            "posts",
            vec![col("views", ColumnType::Int32), status_baseline],
            vec![],
        );
        baseline.checks.push(CheckConstraint {
            name: None,
            expression: "length(status) > 0".to_owned(),
        });

        // The parser's blind spot: `status.default` recorded as None and the CHECK
        // absent, plus the unrelated `views` widening that triggers the rebuild.
        let desired = sqlite_table(
            "posts",
            vec![
                col("views", ColumnType::Int64),
                col("status", ColumnType::Text),
            ],
            vec![],
        );

        let plan = MigrationPlan {
            backend: Backend::Sqlite,
            changes: vec![SchemaChange::AlterColumnType {
                table: "posts".to_owned(),
                column: "views".to_owned(),
                from: ColumnType::Int32,
                to: ColumnType::Int64,
            }],
        };
        let ctx = SchemaContext::from_tables(
            std::slice::from_ref(&desired),
            std::slice::from_ref(&baseline),
        );

        let up = emit_up_sql_with_context(&plan, &ctx).expect("emit up");
        assert!(
            up.contains("status TEXT NOT NULL DEFAULT 'draft'"),
            "the parser-invisible baseline default is preserved in the recreate: {up}"
        );
        assert!(
            up.contains("CHECK (length(status) > 0)"),
            "the parser-invisible baseline CHECK is preserved in the recreate: {up}"
        );
    }

    #[test]
    fn sqlite_rebuild_without_context_is_a_clear_error() {
        // The context-free entry cannot build a rebuild; it returns a directed error
        // rather than a broken/partial rebuild.
        let (plan, _ctx) = sqlite_rebuild_fixture();
        let err = emit_up_sql(&plan).unwrap_err();
        assert!(
            matches!(err, EmitError::SqliteRebuildUnsupported { .. }),
            "missing-context rebuild is a clear error: {err:?}"
        );
        assert!(
            err.to_string().contains("emit_up_sql_with_context"),
            "the error directs the caller to the context-aware entry: {err}"
        );
    }

    #[test]
    fn sqlite_rebuild_refuses_on_staging_name_collision() {
        // A real table already named `posts__autumn_new` would be clobbered by the
        // rebuild's staging CREATE/RENAME, so the emitter refuses rather than emit
        // unappliable SQL.
        let (plan, ctx) = sqlite_rebuild_fixture();
        let collider = sqlite_table(
            "posts__autumn_new",
            vec![col("body", ColumnType::Text)],
            vec![],
        );
        let mut ctx = ctx;
        ctx.desired.insert(collider.name.clone(), collider.clone());
        ctx.baseline.insert(collider.name.clone(), collider);

        let err = emit_up_sql_with_context(&plan, &ctx).unwrap_err();
        assert!(
            matches!(err, EmitError::SqliteRebuildUnsupported { .. }),
            "staging-name collision is refused: {err:?}"
        );
        assert!(
            err.to_string().contains("posts__autumn_new") && err.to_string().contains("collides"),
            "the error names the colliding staging table: {err}"
        );
    }

    #[test]
    fn sqlite_rebuild_preserves_rows_on_real_sqlite() {
        // Exercise the generated UP rebuild against a real in-memory SQLite DB
        // (diesel's `sqlite` backend is a workspace dependency), asserting the rows
        // survive with the new shape and the integrity/foreign-key checks are clean.
        use diesel::connection::SimpleConnection as _;
        use diesel::prelude::*;

        #[derive(QueryableByName)]
        struct PostRow {
            #[diesel(sql_type = diesel::sql_types::BigInt)]
            id: i64,
            #[diesel(sql_type = diesel::sql_types::BigInt)]
            views: i64,
            #[diesel(sql_type = diesel::sql_types::Text)]
            body: String,
        }

        // `PRAGMA foreign_key_check` REPORTS violation rows (child table / rowid /
        // parent / fkid); an empty result set means no violations.
        #[derive(QueryableByName)]
        struct FkViolation {
            #[diesel(sql_type = diesel::sql_types::Text, column_name = "table")]
            _child_table: String,
        }

        // `PRAGMA integrity_check` returns a single `TEXT` row; a clean DB reports `ok`.
        #[derive(QueryableByName)]
        struct IntegrityRow {
            #[diesel(sql_type = diesel::sql_types::Text, column_name = "integrity_check")]
            status: String,
        }

        let mut conn = SqliteConnection::establish(":memory:").expect("open in-memory sqlite");
        conn.batch_execute(
            "CREATE TABLE posts (\n    id INTEGER PRIMARY KEY AUTOINCREMENT,\n    \
             views INTEGER NOT NULL,\n    body TEXT NOT NULL\n);\n\
             INSERT INTO posts (views, body) VALUES (3, 'hello'), (7, 'world');",
        )
        .expect("seed the original table");

        let (plan, ctx) = sqlite_rebuild_fixture();
        let up = emit_up_sql_with_context(&plan, &ctx).expect("emit up");
        conn.batch_execute(&up)
            .expect("apply the generated rebuild");

        let rows: Vec<PostRow> = diesel::sql_query("SELECT id, views, body FROM posts ORDER BY id")
            .load(&mut conn)
            .expect("query the rebuilt table");
        assert_eq!(rows.len(), 2, "both rows survived the rebuild");
        assert_eq!(
            (rows[0].id, rows[0].views, rows[0].body.as_str()),
            (1, 3, "hello")
        );
        assert_eq!(
            (rows[1].id, rows[1].views, rows[1].body.as_str()),
            (2, 7, "world")
        );

        // `PRAGMA foreign_key_check` only REPORTS violation rows — it does not raise —
        // so actually READ its output and assert it is empty, rather than firing it via
        // `batch_execute`, which discards the rows and would pass even on a violation.
        let violations: Vec<FkViolation> = diesel::sql_query("PRAGMA foreign_key_check")
            .load(&mut conn)
            .expect("run PRAGMA foreign_key_check");
        assert!(
            violations.is_empty(),
            "foreign_key_check reported {} violation row(s)",
            violations.len()
        );

        let integrity: Vec<IntegrityRow> = diesel::sql_query("PRAGMA integrity_check")
            .load(&mut conn)
            .expect("run PRAGMA integrity_check");
        assert_eq!(integrity.len(), 1, "integrity_check returns one row");
        assert_eq!(integrity[0].status, "ok", "integrity_check is clean");
    }

    #[test]
    fn sqlite_rebuild_survives_dependent_view() {
        // A SQLite view referencing the rebuilt table makes the post-`DROP TABLE`
        // `ALTER TABLE ... RENAME` fail ("error in view v: no such table: main.posts")
        // under the modern default `legacy_alter_table=OFF`. The offline emitter cannot
        // see or recreate views, so the rebuild wraps the rename with
        // `PRAGMA legacy_alter_table=ON`…`OFF`, a blind "dumb" rename that does not
        // descend into / validate views — so the migration applies and the view
        // re-validates against the recreated table. This exercises the REAL in-transaction
        // path (diesel wraps each migration in one) to confirm the pragma is not a
        // mid-transaction no-op like `foreign_keys`.
        use diesel::connection::SimpleConnection as _;
        use diesel::prelude::*;

        #[derive(QueryableByName)]
        struct ViewRow {
            #[diesel(sql_type = diesel::sql_types::BigInt)]
            id: i64,
            #[diesel(sql_type = diesel::sql_types::Text)]
            body: String,
        }

        let mut conn = SqliteConnection::establish(":memory:").expect("open in-memory sqlite");
        conn.batch_execute(
            "CREATE TABLE posts (\n    id INTEGER PRIMARY KEY AUTOINCREMENT,\n    \
             views INTEGER NOT NULL,\n    body TEXT NOT NULL\n);\n\
             INSERT INTO posts (views, body) VALUES (3, 'hello');\n\
             CREATE VIEW posts_v AS SELECT id, body FROM posts;",
        )
        .expect("seed the original table and a dependent view");

        let (plan, ctx) = sqlite_rebuild_fixture();
        let up = emit_up_sql_with_context(&plan, &ctx).expect("emit up");

        // Run the generated rebuild INSIDE an explicit transaction — the real path diesel
        // uses — so a mid-transaction pragma no-op would surface here as a rename error.
        conn.transaction::<_, diesel::result::Error, _>(|conn| conn.batch_execute(&up))
            .expect("the rebuild applies inside a transaction with a dependent view present");

        // The view is still valid against the recreated table and the row survived.
        let rows: Vec<ViewRow> = diesel::sql_query("SELECT id, body FROM posts_v ORDER BY id")
            .load(&mut conn)
            .expect("the dependent view is still queryable after the rebuild");
        assert_eq!(rows.len(), 1, "the view still resolves one row");
        assert_eq!((rows[0].id, rows[0].body.as_str()), (1, "hello"));
    }

    #[test]
    fn sqlite_rebuild_uuid_pk_emits_no_sequence_preservation() {
        // A table whose single PK is `Uuid` has no `sqlite_sequence` row, so the
        // rebuild must emit none of the high-water preservation statements — those
        // apply only to `BigSerial` (`INTEGER PRIMARY KEY AUTOINCREMENT`) PKs.
        let uuid_table = |name: &str| -> Table {
            let mut t = Table::new(name, Backend::Sqlite);
            let mut id = col("id", ColumnType::Uuid);
            id.primary_key = true;
            t.primary_key.push("id".to_owned());
            t.columns.push(id);
            t.columns.push(col("body", ColumnType::Text));
            t
        };
        let baseline = uuid_table("posts");
        let desired = uuid_table("posts");
        // A default-less UUID PK is no longer the `IdKind::Uuid` convention shape
        // (that is gated on the `gen_random_uuid()` default): it resolves to `None`
        // and is rendered as an ordinary column with a table-level PK. Either way it
        // is not an autoincrement PK, so no sequence preservation is emitted.
        assert!(
            single_pk_column(&desired).is_none(),
            "a default-less UUID PK is not the IdKind::Uuid convention shape"
        );
        for leg in [RebuildLeg::Up, RebuildLeg::Down] {
            let sql = render_sqlite_rebuild("posts", &desired, &baseline, leg, &[]);
            assert!(
                !sql.contains("sqlite_sequence"),
                "no sqlite_sequence statements for a Uuid PK ({leg:?}): {sql}"
            );
            assert!(
                !sql.contains("_autumn_seq_"),
                "no high-water temp table for a Uuid PK ({leg:?}): {sql}"
            );
        }
    }

    #[test]
    fn sqlite_rebuild_preserves_autoincrement_sequence() {
        // The definitive non-reuse proof: after a table recreate, an id that was
        // issued-then-deleted must NOT be handed out again. Seed ids 1..5, delete
        // 2..5 (the `sqlite_sequence` high-water stays 5), apply the generated
        // rebuild, then insert a new row and assert its id is 6 — not the reused 2.
        use diesel::connection::SimpleConnection as _;
        use diesel::prelude::*;

        #[derive(QueryableByName)]
        struct BigRow {
            #[diesel(sql_type = diesel::sql_types::BigInt, column_name = "v")]
            v: i64,
        }

        // `PRAGMA integrity_check` returns a single `TEXT` row; a clean DB reports `ok`.
        #[derive(QueryableByName)]
        struct IntegrityRow {
            #[diesel(sql_type = diesel::sql_types::Text, column_name = "integrity_check")]
            status: String,
        }

        let mut conn = SqliteConnection::establish(":memory:").expect("open in-memory sqlite");
        conn.batch_execute(
            "CREATE TABLE posts (\n    id INTEGER PRIMARY KEY AUTOINCREMENT,\n    \
             views INTEGER NOT NULL,\n    body TEXT NOT NULL\n);\n\
             INSERT INTO posts (views, body) VALUES \
             (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e');",
        )
        .expect("seed five rows -> ids 1..5");

        // The AUTOINCREMENT high-water is 5 after five inserts.
        let seq: Vec<BigRow> =
            diesel::sql_query("SELECT seq AS v FROM sqlite_sequence WHERE name = 'posts'")
                .load(&mut conn)
                .expect("read sqlite_sequence");
        assert_eq!(seq.len(), 1, "sqlite_sequence has a row for posts");
        assert_eq!(seq[0].v, 5, "high-water is 5 before the delete");

        // Delete every row but id=1; the high-water in sqlite_sequence stays 5.
        conn.batch_execute("DELETE FROM posts WHERE id > 1;")
            .expect("delete ids 2..5");

        let (plan, ctx) = sqlite_rebuild_fixture();
        let up = emit_up_sql_with_context(&plan, &ctx).expect("emit up");
        conn.batch_execute(&up)
            .expect("apply the generated rebuild");

        // A fresh insert must NOT reuse a deleted id: the next id is 6, not 2.
        conn.batch_execute("INSERT INTO posts (views, body) VALUES (9, 'new');")
            .expect("insert a new row after the rebuild");
        let max: Vec<BigRow> = diesel::sql_query("SELECT MAX(id) AS v FROM posts")
            .load(&mut conn)
            .expect("max id after rebuild");
        assert_eq!(
            max[0].v, 6,
            "the next id after the rebuild does not reuse a deleted id"
        );

        // The surviving id=1 row is untouched by the rebuild.
        let survivors: Vec<BigRow> =
            diesel::sql_query("SELECT COUNT(*) AS v FROM posts WHERE id = 1")
                .load(&mut conn)
                .expect("count id=1");
        assert_eq!(survivors[0].v, 1, "the surviving id=1 row is intact");

        let integrity: Vec<IntegrityRow> = diesel::sql_query("PRAGMA integrity_check")
            .load(&mut conn)
            .expect("run PRAGMA integrity_check");
        assert_eq!(integrity.len(), 1, "integrity_check returns one row");
        assert_eq!(integrity[0].status, "ok", "integrity_check is clean");
    }

    #[test]
    fn sqlite_rebuild_skips_sequence_when_source_not_autoincrement() {
        // A migration that INTRODUCES autoincrement (an `id` Int32 -> Int64 primary-key
        // change) must NOT emit the `sqlite_sequence` high-water capture/restore: the
        // copy SOURCE is not AUTOINCREMENT, so there is no prior high-water to preserve,
        // and — because SQLite creates `sqlite_sequence` LAZILY — capturing from it on a
        // database with no existing AUTOINCREMENT table would fail with
        // `no such table: sqlite_sequence`, aborting an otherwise-valid migration.
        use diesel::connection::SimpleConnection as _;
        use diesel::{Connection as _, RunQueryDsl as _, SqliteConnection};

        #[derive(diesel::QueryableByName)]
        struct BigRow {
            #[diesel(sql_type = diesel::sql_types::BigInt, column_name = "v")]
            v: i64,
        }

        let int32_pk_table = |name: &str| -> Table {
            let mut t = Table::new(name, Backend::Sqlite);
            let mut id = col("id", ColumnType::Int32);
            id.primary_key = true;
            t.primary_key.push("id".to_owned());
            t.columns.push(id);
            t.columns.push(col("views", ColumnType::Int32));
            t.columns.push(col("body", ColumnType::Text));
            t
        };
        let baseline = int32_pk_table("posts");
        // The desired shape only changes the `id` column type Int32 -> Int64 (BigSerial).
        let mut desired = int32_pk_table("posts");
        desired.columns[0].ty = ColumnType::Int64;

        // Sanity: the copy source (baseline) is NOT BigSerial; the target IS.
        assert!(
            !matches!(single_pk_column(&baseline), Some((_, IdKind::BigSerial))),
            "the baseline (copy source) PK is Int32, not BigSerial"
        );
        assert!(
            matches!(single_pk_column(&desired), Some((_, IdKind::BigSerial))),
            "the target PK resolves to BigSerial"
        );

        let plan = MigrationPlan {
            backend: Backend::Sqlite,
            changes: vec![SchemaChange::AlterColumnType {
                table: "posts".to_owned(),
                column: "id".to_owned(),
                from: ColumnType::Int32,
                to: ColumnType::Int64,
            }],
        };
        let ctx = SchemaContext::from_tables(
            std::slice::from_ref(&desired),
            std::slice::from_ref(&baseline),
        );
        let up = emit_up_sql_with_context(&plan, &ctx).expect("emit up");

        // The gate is false (source not BigSerial), so no capture/restore is emitted.
        assert!(
            !up.contains("sqlite_sequence"),
            "no sqlite_sequence statements when the source is not AUTOINCREMENT:\n{up}"
        );
        assert!(
            !up.contains("_autumn_seq_"),
            "no high-water temp table when the source is not AUTOINCREMENT:\n{up}"
        );

        // Real SQLite: a fresh DB with a non-AUTOINCREMENT `posts` (`INTEGER PRIMARY KEY`
        // WITHOUT `AUTOINCREMENT`, so `sqlite_sequence` does not exist) and a seeded row.
        let mut conn = SqliteConnection::establish(":memory:").expect("open in-memory sqlite");
        conn.batch_execute(
            "CREATE TABLE posts (\n    id INTEGER PRIMARY KEY,\n    \
             views INTEGER NOT NULL,\n    body TEXT NOT NULL\n);\n\
             INSERT INTO posts (id, views, body) VALUES (1, 9, 'a');",
        )
        .expect("seed a non-AUTOINCREMENT table");

        // The generated rebuild applies without `no such table: sqlite_sequence`.
        conn.batch_execute(&up)
            .expect("apply the generated rebuild");

        // The seeded row survived the rebuild.
        let survivors: Vec<BigRow> =
            diesel::sql_query("SELECT COUNT(*) AS v FROM posts WHERE id = 1 AND views = 9")
                .load(&mut conn)
                .expect("count the surviving row");
        assert_eq!(
            survivors[0].v, 1,
            "the seeded id=1 row survives the rebuild"
        );
    }

    #[test]
    fn sqlite_create_table_and_add_column_render() {
        // CreateTable + a nullable AddColumn are within the portable `SQLite` subset.
        let mut t = Table::new("posts", Backend::Sqlite);
        let mut id = col("id", ColumnType::Int64);
        id.primary_key = true;
        t.primary_key.push("id".to_owned());
        t.columns.push(id);
        t.columns.push(col("body", ColumnType::Text));
        let mut bio = col("bio", ColumnType::Text);
        bio.nullable = true;
        let plan = MigrationPlan {
            backend: Backend::Sqlite,
            changes: vec![
                SchemaChange::CreateTable(t),
                SchemaChange::AddColumn {
                    table: "posts".to_owned(),
                    column: bio,
                },
            ],
        };
        let up = emit_up_sql(&plan).expect("emit");
        assert!(
            up.contains("id INTEGER PRIMARY KEY AUTOINCREMENT"),
            "sqlite PK: {up}"
        );
        assert!(up.contains("ADD COLUMN bio TEXT NULL"), "{up}");
    }

    #[test]
    fn sqlite_add_not_null_without_default_is_unsupported() {
        let plan = MigrationPlan {
            backend: Backend::Sqlite,
            changes: vec![SchemaChange::AddColumn {
                table: "posts".to_owned(),
                column: col("title", ColumnType::Text),
            }],
        };
        assert!(matches!(
            emit_up_sql(&plan).unwrap_err(),
            EmitError::UnsupportedOnBackend { .. }
        ));
    }

    #[test]
    fn down_drops_fk_column_before_dropping_referenced_table() {
        // Deferred item #1: baseline `posts(id)` only; desired adds a `target` table
        // plus `posts.target_id` (nullable FK → target.id). The down leg must DROP
        // COLUMN target_id BEFORE DROP TABLE target, else the rollback is unappliable.
        // Pins `emit_down_sql` as a pure reverse of `up_ordered` for the create-table
        // + add-FK-column pattern.
        let baseline = vec![posts_with(vec![])];

        let mut target_id = col("target_id", ColumnType::Int64);
        target_id.nullable = true;
        target_id.references = Some(ForeignKey::new("target", "id"));
        let desired_posts = posts_with(vec![target_id]);

        let mut target = Table::new("target", Backend::Postgres);
        let mut tid = col("id", ColumnType::Int64);
        tid.primary_key = true;
        target.primary_key.push("id".to_owned());
        target.columns.push(tid);

        let desired = parsed(vec![desired_posts, target], vec![]);
        let plan = diff_schema(&baseline, &desired, DEFAULT_OPTS);
        guard_plan(&plan, DEFAULT_OPTS).expect("emittable");
        let down = emit_down_sql(&plan).expect("emit down");

        let drop_col = down
            .find("ALTER TABLE posts DROP COLUMN target_id")
            .expect("down drops the FK column");
        let drop_table = down
            .find("DROP TABLE target")
            .expect("down drops the referenced table");
        assert!(
            drop_col < drop_table,
            "DROP COLUMN target_id must precede DROP TABLE target:\n{down}"
        );
    }

    #[test]
    fn over_long_fkey_constraint_name_is_bounded_not_refused() {
        // Deferred item #4: an engine-generated FK-constraint name over 63 bytes is
        // truncate+hashed to a valid ≤63-byte identifier — the SAME name in the up
        // ADD and the down DROP — and the guard no longer refuses it.
        let table = "a".repeat(40);
        let column = "b".repeat(40);
        let raw = format!("{table}_{column}_fkey");
        assert!(
            raw.len() > PG_MAX_IDENTIFIER_BYTES,
            "the raw name is over the limit"
        );

        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::AddForeignKey {
                table,
                column,
                foreign_key: ForeignKey::new("targets", "id"),
            }],
        };
        guard_plan(&plan, DEFAULT_OPTS)
            .expect("the length guard no longer refuses a bounded FK name");

        let bounded = bounded_pg_identifier(&raw);
        assert!(
            bounded.len() <= PG_MAX_IDENTIFIER_BYTES,
            "the bounded name fits the limit: {bounded}"
        );
        assert_ne!(bounded, raw, "the over-long name is actually shortened");

        let up = emit_up_sql(&plan).expect("emit up");
        let down = emit_down_sql(&plan).expect("emit down");
        assert!(
            up.contains(&format!("ADD CONSTRAINT {bounded} ")),
            "up uses the bounded name: {up}"
        );
        assert!(
            down.contains(&format!("DROP CONSTRAINT {bounded};")),
            "down uses the SAME bounded name: {down}"
        );
    }

    #[test]
    fn short_fkey_constraint_name_is_unchanged() {
        // A normal (short) FK-constraint name passes through unchanged, so Postgres
        // output stays byte-stable.
        assert_eq!(
            bounded_pg_identifier("posts_author_id_fkey"),
            "posts_author_id_fkey"
        );
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::AddForeignKey {
                table: "posts".to_owned(),
                column: "author_id".to_owned(),
                foreign_key: ForeignKey::new("users", "id"),
            }],
        };
        let up = emit_up_sql(&plan).expect("emit up");
        assert!(
            up.contains(
                "ADD CONSTRAINT posts_author_id_fkey FOREIGN KEY (author_id) REFERENCES users(id);"
            ),
            "{up}"
        );
        let down = emit_down_sql(&plan).expect("emit down");
        assert!(
            down.contains("DROP CONSTRAINT posts_author_id_fkey;"),
            "{down}"
        );
    }

    #[test]
    fn describe_plan_lists_each_change() {
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![
                SchemaChange::CreateTable(posts_with(vec![])),
                SchemaChange::AddColumn {
                    table: "posts".to_owned(),
                    column: col("body", ColumnType::Text),
                },
            ],
        };
        let text = describe_plan(&plan);
        assert!(text.contains("postgres"), "names the backend: {text}");
        assert!(text.contains("2 change(s)"), "counts changes: {text}");
        assert!(text.contains("CREATE TABLE posts"), "{text}");
        assert!(text.contains("ADD COLUMN posts.body"), "{text}");
    }

    // -- 13.6 Codex round-2 regressions -------------------------------------

    /// Finding A: dropping a table while a RETAINED table still holds a baseline
    /// FK to it emits an unappliable `DROP TABLE`. Must be refused — even under
    /// `--allow-destructive` (that flag permits losing the dropped table's own
    /// data, not breaking another table's referential integrity).
    #[test]
    fn drop_table_with_retained_inbound_fk_is_refused_even_with_allow_destructive() {
        // baseline: users (dropped) + posts (retained) with posts.user_id → users.
        let users = Table::new("users", Backend::Postgres);
        let mut user_fk = col("user_id", ColumnType::Int64);
        user_fk.references = Some(ForeignKey::new("users", "id"));
        let posts = posts_ref_table("posts", user_fk);
        let baseline = vec![users, posts.clone()];
        // desired keeps posts unchanged; users is gone.
        let plan = diff_schema(&baseline, &parsed(vec![posts], vec![]), ALLOW);
        let err = guard_plan(&plan, ALLOW)
            .expect_err("retained posts.user_id → users blocks DROP TABLE users");
        let msg = err.to_string();
        assert!(
            msg.contains("users") && msg.contains("posts.user_id"),
            "names the dropped table and the retained referencer: {msg}"
        );
    }

    /// Finding 667 (documented limitation): the slice-2 parser cannot see a
    /// generated `#[belongs_to(...)]` association FK — a `<name>_id: i64` column is
    /// lifted as a plain `Int64` with `references: None` and NO diagnostic — so an
    /// invisible inbound association FK on a *retained* table cannot be detected
    /// offline, and this engine emits an unchecked `DROP TABLE` for it. A precise
    /// guard is impossible without schema introspection (a future slice); a blanket
    /// refuse-all-drops would make the common case useless. Instead every emitted
    /// `DROP TABLE` carries an advisory `-- autumn-safety:` comment naming this gap.
    /// This test pins that advisory (no behavioral test is possible for the
    /// invisible case — by definition the engine has no signal for it). The
    /// *visible*-FK protection is unaffected — see
    /// `drop_table_with_retained_inbound_fk_is_refused_even_with_allow_destructive`
    /// above, which still refuses a drop blocked by an observable `references`.
    #[test]
    fn drop_table_emits_invisible_association_fk_advisory() {
        let plan = MigrationPlan {
            backend: Backend::Postgres,
            changes: vec![SchemaChange::DropTable(posts_with(vec![]))],
        };
        guard_plan(&plan, ALLOW).expect("a plain DROP TABLE (no visible inbound FK) is allowed");
        let up = emit_up_sql(&plan).expect("emit up");
        assert!(
            up.contains("-- autumn-safety:")
                && up.contains("#[belongs_to(...)]")
                && up.contains("the offline snapshot cannot see"),
            "the DROP TABLE carries the invisible-association-FK advisory: {up}"
        );
        // The advisory precedes the statement, and the real statement is still emitted.
        let advisory = up.find("-- autumn-safety:").expect("advisory present");
        let stmt = up.find("DROP TABLE posts;").expect("statement present");
        assert!(
            advisory < stmt,
            "advisory comment precedes the DROP TABLE: {up}"
        );
    }

    /// Finding A: a self-referential FK on the dropped table does NOT block its
    /// own drop, and neither does an FK from another table that is also dropped.
    #[test]
    fn drop_table_self_ref_and_co_dropped_ref_do_not_block() {
        // users has a self-FK (parent_id → users) and is dropped alone.
        let mut parent = col("parent_id", ColumnType::Int64);
        parent.references = Some(ForeignKey::new("users", "id"));
        let users = posts_ref_table("users", parent);
        let plan = diff_schema(&[users], &parsed(vec![], vec![]), ALLOW);
        guard_plan(&plan, ALLOW).expect("self-referential FK goes away with the table");
    }

    /// Round 3 / Finding Y: a DESIRED-side FK to a table being dropped in the
    /// same plan is refused. Drop `users` while adding `posts.author_id ->
    /// users`; the emitted `CREATE TABLE posts ... REFERENCES users` would depend
    /// on the dropped `users`, so PG rejects. The round-2 baseline-only guard
    /// missed this — only desired-side references catch it.
    #[test]
    fn desired_side_fk_to_dropped_table_is_refused() {
        // baseline: users (managed, no inbound FK). desired: users gone, new
        // posts.author_id -> users.
        let users = Table::new("users", Backend::Postgres);
        let mut author_fk = col("author_id", ColumnType::Int64);
        author_fk.references = Some(ForeignKey::new("users", "id"));
        let posts = posts_ref_table("posts", author_fk);
        let plan = diff_schema(&[users], &parsed(vec![posts], vec![]), ALLOW);
        let err = guard_plan(&plan, ALLOW)
            .expect_err("new posts.author_id -> users blocks DROP TABLE users");
        let msg = err.to_string();
        assert!(
            msg.contains("users") && msg.contains("posts.author_id"),
            "names the dropped table and the desired-side referencer: {msg}"
        );
    }

    /// Round 3 / Finding Y control: a desired-side FK pointing at a RETAINED
    /// table is NOT a blocker even while an unrelated table is dropped — only
    /// references to a *dropped* table are refused (no over-refusal).
    #[test]
    fn desired_side_fk_to_retained_table_is_allowed() {
        // baseline: users (retained) + stale (dropped). desired: users retained,
        // stale gone, new posts.author_id -> users (a retained table).
        let users = Table::new("users", Backend::Postgres);
        let stale = Table::new("stale", Backend::Postgres);
        let mut author_fk = col("author_id", ColumnType::Int64);
        author_fk.references = Some(ForeignKey::new("users", "id"));
        let posts = posts_ref_table("posts", author_fk);
        let plan = diff_schema(
            &[users.clone(), stale],
            &parsed(vec![users, posts], vec![]),
            ALLOW,
        );
        guard_plan(&plan, ALLOW)
            .expect("FK to a retained table is fine even while another table is dropped");
    }

    /// Finding B: a non-implicit type change (`TEXT` → `INTEGER`) has no implicit
    /// PG cast, so a bare `ALTER COLUMN ... TYPE` is unappliable. Must be refused
    /// (needs a manual `USING`), regardless of `--allow-destructive`.
    #[test]
    fn non_implicit_type_conversion_is_refused() {
        let base = vec![posts_with(vec![col("views", ColumnType::Text)])];
        let want = parsed(
            vec![posts_with(vec![col("views", ColumnType::Int32)])],
            vec![],
        );
        let plan = diff_schema(&base, &want, DEFAULT_OPTS);
        let err = guard_plan(&plan, ALLOW).expect_err("TEXT→INTEGER needs a USING clause");
        let msg = err.to_string();
        assert!(
            msg.contains("USING") && msg.contains("views"),
            "explains the USING requirement and names the column: {msg}"
        );
    }

    /// Finding B: an implicit widening (`Int32` → `Int64`, i.e. int4 → int8) IS
    /// emittable as a bare `ALTER COLUMN ... TYPE` — the classifier must not
    /// over-refuse.
    #[test]
    fn implicit_widening_type_conversion_is_allowed() {
        let base = vec![posts_with(vec![col("views", ColumnType::Int32)])];
        let want = parsed(
            vec![posts_with(vec![col("views", ColumnType::Int64)])],
            vec![],
        );
        let plan = diff_schema(&base, &want, DEFAULT_OPTS);
        guard_plan(&plan, DEFAULT_OPTS).expect("Int32→Int64 is an implicit widening");
        let up = emit_up_sql(&plan).expect("emit");
        assert!(
            up.contains("ALTER TABLE posts ALTER COLUMN views TYPE BIGINT;"),
            "emits the bare ALTER TYPE for the widening: {up}"
        );
    }

    /// Finding S: a type change on a **referencing** FK column
    /// (`posts.account_id` → `accounts.id`, widened `Int32` → `Int64`) is an
    /// implicit widening the round-2 classifier ALLOWS, but PG rejects
    /// `ALTER COLUMN ... TYPE` on a column bound by an FK. Must be refused (no
    /// override) — the bare ALTER is unappliable.
    #[test]
    fn type_change_on_referencing_fk_column_is_refused() {
        let accounts = posts_ref_table("accounts", col("name", ColumnType::Text));
        let mut fk_base = col("account_id", ColumnType::Int32);
        fk_base.references = Some(ForeignKey::new("accounts", "id"));
        let base = vec![accounts.clone(), posts_with(vec![fk_base])];
        let mut fk_want = col("account_id", ColumnType::Int64);
        fk_want.references = Some(ForeignKey::new("accounts", "id"));
        let want = parsed(vec![accounts, posts_with(vec![fk_want])], vec![]);
        let plan = diff_schema(&base, &want, ALLOW);
        let err = guard_plan(&plan, ALLOW)
            .expect_err("type change on a referencing FK column is unappliable");
        let msg = err.to_string();
        assert!(
            msg.contains("posts.account_id") && msg.contains("foreign-key"),
            "names the FK column and the FK reason: {msg}"
        );
    }

    /// Finding S: a type change on a **referenced key** column (`accounts.id`
    /// widened `Int32` → `Int64`) while a retained `posts.account_id` → `accounts`
    /// FK survives is likewise refused — PG rejects altering the referenced key
    /// while the inbound FK exists, and this engine cannot drop+recreate it.
    #[test]
    fn type_change_on_referenced_key_column_is_refused() {
        // accounts.id: Int32 → Int64 (PK unchanged, so no PrimaryKeyChange).
        let mut acc_id_base = col("id", ColumnType::Int32);
        acc_id_base.primary_key = true;
        let mut accounts_base = Table::new("accounts", Backend::Postgres);
        accounts_base.primary_key.push("id".to_owned());
        accounts_base.columns.push(acc_id_base);

        let mut acc_id_want = col("id", ColumnType::Int64);
        acc_id_want.primary_key = true;
        let mut accounts_want = Table::new("accounts", Backend::Postgres);
        accounts_want.primary_key.push("id".to_owned());
        accounts_want.columns.push(acc_id_want);

        let mut fk = col("account_id", ColumnType::Int64);
        fk.references = Some(ForeignKey::new("accounts", "id"));
        let posts = posts_ref_table("posts", fk);

        let base = vec![accounts_base, posts.clone()];
        let want = parsed(vec![accounts_want, posts], vec![]);
        let plan = diff_schema(&base, &want, ALLOW);
        let err = guard_plan(&plan, ALLOW)
            .expect_err("type change on a referenced key column is unappliable");
        let msg = err.to_string();
        assert!(
            msg.contains("accounts.id") && msg.contains("foreign-key"),
            "names the referenced key column and the FK reason: {msg}"
        );
    }

    /// Finding S control: an implicit widening on a **plain** (non-FK) column
    /// still emits the bare `ALTER COLUMN ... TYPE` — the FK guard must not
    /// over-refuse.
    #[test]
    fn type_change_on_plain_column_still_allowed() {
        let base = vec![posts_with(vec![col("views", ColumnType::Int32)])];
        let want = parsed(
            vec![posts_with(vec![col("views", ColumnType::Int64)])],
            vec![],
        );
        let plan = diff_schema(&base, &want, DEFAULT_OPTS);
        guard_plan(&plan, DEFAULT_OPTS).expect("plain-column widening is not FK-bound");
        let up = emit_up_sql(&plan).expect("emit");
        assert!(
            up.contains("ALTER TABLE posts ALTER COLUMN views TYPE BIGINT;"),
            "emits the bare ALTER TYPE for the plain-column widening: {up}"
        );
    }

    /// A `users(id)` table for the `SQLite` FK-type-change fixtures.
    fn sqlite_users_table() -> Table {
        let mut t = Table::new("users", Backend::Sqlite);
        let mut id = col("id", ColumnType::Int64);
        id.primary_key = true;
        t.primary_key.push("id".to_owned());
        t.columns.push(id);
        t
    }

    /// A `posts(id, author_id -> users.id)` `SQLite` table whose `author_id` FK
    /// column carries `ty`, for the `SQLite` FK-type-change fixtures.
    fn sqlite_posts_with_author(ty: ColumnType) -> Table {
        let mut t = Table::new("posts", Backend::Sqlite);
        let mut id = col("id", ColumnType::Int64);
        id.primary_key = true;
        t.primary_key.push("id".to_owned());
        t.columns.push(id);
        let mut author = col("author_id", ty);
        author.nullable = true;
        author.references = Some(ForeignKey::new("users", "id"));
        t.columns.push(author);
        t
    }

    /// The `SQLite` counterpart to `type_change_on_referencing_fk_column_is_refused`:
    /// the FK-bound-type-change guard is `Postgres`-only, so on `SQLite` an FK
    /// column's type change (`posts.author_id` `Int64` → `Text`, still
    /// `REFERENCES users(id)`) is NOT refused — it flows to the table-recreate,
    /// which applies the new type, preserves the inline `REFERENCES`, and emits the
    /// FK type-consistency advisory naming the column. (A GENUINE cross-affinity-class
    /// change is used because on `SQLite` a same-class change like `Int32` → `Int64`
    /// is now a no-op — both are `INTEGER` affinity — see the affinity-aware
    /// comparison in [`column_types_equivalent`].) The `Postgres` plan with an int4→
    /// int8 change still refuses with `TypeChangeOnForeignKeyColumn` (the backend
    /// contrast).
    #[test]
    fn sqlite_fk_column_type_change_recreates_with_advisory() {
        let baseline = vec![
            sqlite_users_table(),
            sqlite_posts_with_author(ColumnType::Int64),
        ];
        let desired = vec![
            sqlite_users_table(),
            sqlite_posts_with_author(ColumnType::Text),
        ];
        let plan = diff_schema(&baseline, &parsed(desired.clone(), vec![]), ALLOW);

        // The plan is a SQLite plan carrying the real (cross-class) type change AND
        // the blocked marker appended alongside it.
        assert_eq!(plan.backend, Backend::Sqlite);
        assert!(
            plan.changes.iter().any(|c| matches!(
                c,
                SchemaChange::AlterColumnType { table, column, to, .. }
                    if table == "posts" && column == "author_id" && *to == ColumnType::Text
            )),
            "the real AlterColumnType (→ Text) rides in the plan: {:?}",
            plan.changes
        );
        assert!(
            plan.changes.iter().any(|c| matches!(
                c,
                SchemaChange::AlterColumnTypeBlockedByFk { table, column }
                    if table == "posts" && column == "author_id"
            )),
            "the FK-bound type-change marker is still recorded: {:?}",
            plan.changes
        );

        // (a) The Postgres-only gate lets SQLite through the guard.
        guard_plan(&plan, ALLOW)
            .expect("SQLite FK-column type change flows to the table recreate, not a refusal");

        // (b) The recreate applies the new type (Int64 → SQLite INTEGER), preserves
        //     the inline REFERENCES, and carries the FK type-consistency advisory.
        let ctx = SchemaContext::from_tables(&desired, &baseline);
        let up = emit_up_sql_with_context(&plan, &ctx).expect("emit sqlite rebuild");
        assert!(
            up.contains("author_id TEXT NULL REFERENCES users(id)"),
            "the recreate expresses author_id with its (changed) type and keeps the \
             inline REFERENCES: {up}"
        );
        assert!(
            up.contains(
                "-- autumn-safety: foreign-key column(s) author_id have their type \
                 changed by this recreate; SQLite does not enforce that they still \
                 match the referenced key's type, so ensure the referenced column \
                 stays type-compatible (Postgres rejects this change outright, which \
                 is why it is emitted only for SQLite)."
            ),
            "emits the FK type-consistency advisory naming the column: {up}"
        );
        // The down leg carries it too.
        let down = emit_down_sql_with_context(&plan, &ctx).expect("emit sqlite down rebuild");
        assert!(
            down.contains("-- autumn-safety: foreign-key column(s) author_id have their type"),
            "the down rebuild also carries the FK type-consistency advisory: {down}"
        );

        // (c) The Postgres plan with the same change still refuses (backend contrast).
        let mut users_pg = Table::new("users", Backend::Postgres);
        let mut uid = col("id", ColumnType::Int64);
        uid.primary_key = true;
        users_pg.primary_key.push("id".to_owned());
        users_pg.columns.push(uid);
        let mut author_base = col("author_id", ColumnType::Int32);
        author_base.nullable = true;
        author_base.references = Some(ForeignKey::new("users", "id"));
        let mut author_want = col("author_id", ColumnType::Int64);
        author_want.nullable = true;
        author_want.references = Some(ForeignKey::new("users", "id"));
        let pg_baseline = vec![users_pg.clone(), posts_with(vec![author_base])];
        let pg_desired = parsed(vec![users_pg, posts_with(vec![author_want])], vec![]);
        let pg_plan = diff_schema(&pg_baseline, &pg_desired, ALLOW);
        let err = guard_plan(&pg_plan, ALLOW)
            .expect_err("Postgres still refuses the FK-column type change");
        assert!(
            matches!(
                err,
                DiffError::TypeChangeOnForeignKeyColumn { ref table, ref column }
                    if table == "posts" && column == "author_id"
            ),
            "Postgres refuses with TypeChangeOnForeignKeyColumn: {err:?}"
        );
    }

    /// An ordinary `SQLite` rebuild (no FK-bound type change) must NOT carry the FK
    /// type-consistency advisory — the line is emitted only when a blocked marker
    /// for that table is present.
    #[test]
    fn sqlite_plain_rebuild_omits_fk_type_advisory() {
        // A plain (non-FK) column widening on `posts` triggers a table rebuild but
        // no `AlterColumnTypeBlockedByFk` marker.
        let mut base = Table::new("posts", Backend::Sqlite);
        let mut id = col("id", ColumnType::Int64);
        id.primary_key = true;
        base.primary_key.push("id".to_owned());
        base.columns.push(id);
        base.columns.push(col("views", ColumnType::Int32));
        let mut want = base.clone();
        want.columns[1].ty = ColumnType::Int64;

        let baseline = vec![base];
        let desired = vec![want];
        let plan = diff_schema(&baseline, &parsed(desired.clone(), vec![]), ALLOW);
        let ctx = SchemaContext::from_tables(&desired, &baseline);
        let up = emit_up_sql_with_context(&plan, &ctx).expect("emit sqlite rebuild");
        assert!(
            !up.contains("foreign-key column(s)"),
            "a rebuild with no FK-type-change marker carries no FK advisory: {up}"
        );
    }

    /// A real in-memory `SQLite` database applies the generated FK-column-type-change
    /// recreate without error and the seeded referencing row survives.
    #[test]
    fn sqlite_fk_column_type_change_recreate_applies_in_memory() {
        use diesel::connection::SimpleConnection as _;
        use diesel::{Connection as _, RunQueryDsl as _, SqliteConnection};

        #[derive(diesel::QueryableByName)]
        struct BigRow {
            #[diesel(sql_type = diesel::sql_types::BigInt, column_name = "v")]
            v: i64,
        }
        #[derive(diesel::QueryableByName)]
        struct FkRow {
            #[diesel(sql_type = diesel::sql_types::Text, column_name = "table")]
            table: String,
        }

        let baseline = vec![
            sqlite_users_table(),
            sqlite_posts_with_author(ColumnType::Int32),
        ];
        let desired = vec![
            sqlite_users_table(),
            sqlite_posts_with_author(ColumnType::Int64),
        ];
        let plan = diff_schema(&baseline, &parsed(desired.clone(), vec![]), ALLOW);
        guard_plan(&plan, ALLOW).expect("SQLite FK-column type change is emittable");
        let ctx = SchemaContext::from_tables(&desired, &baseline);
        let up = emit_up_sql_with_context(&plan, &ctx).expect("emit up");

        let mut conn = SqliteConnection::establish(":memory:").expect("open in-memory sqlite");
        conn.batch_execute(
            "CREATE TABLE users (\n    id INTEGER PRIMARY KEY AUTOINCREMENT\n);\n\
             CREATE TABLE posts (\n    id INTEGER PRIMARY KEY AUTOINCREMENT,\n    \
             author_id BIGINT NULL REFERENCES users(id)\n);\n\
             INSERT INTO users (id) VALUES (1);\n\
             INSERT INTO posts (id, author_id) VALUES (1, 1);",
        )
        .expect("seed the referenced + referencing tables and a row");

        // Apply the generated recreate inside a single transaction (as diesel runs a
        // migration).
        conn.transaction::<_, diesel::result::Error, _>(|conn| conn.batch_execute(&up))
            .expect("apply the FK-column-type-change recreate in a transaction");

        // The seeded referencing row survived the rebuild, still pointing at users(1).
        let survivors: Vec<BigRow> =
            diesel::sql_query("SELECT COUNT(*) AS v FROM posts WHERE id = 1 AND author_id = 1")
                .load(&mut conn)
                .expect("count the surviving row");
        assert_eq!(
            survivors[0].v, 1,
            "the seeded post row survives the FK-column type-change recreate"
        );

        // The recreated `posts` still declares the foreign key to `users`.
        let fks: Vec<FkRow> = diesel::sql_query("PRAGMA foreign_key_list(posts)")
            .load(&mut conn)
            .expect("read posts foreign keys");
        assert!(
            fks.iter().any(|f| f.table == "users"),
            "the recreate preserves the posts.author_id -> users foreign key"
        );
    }

    /// Finding R: dropping a retained table's FK column AND its referenced table in
    /// the SAME plan is a valid combined cleanup — `up_ordered` emits every
    /// `DROP COLUMN` (which removes the FK constraint) before every `DROP TABLE`,
    /// so `DROP COLUMN posts.user_id` runs before `DROP TABLE users`. The
    /// inbound-FK guard must NOT over-refuse it under `--allow-destructive`.
    #[test]
    fn drop_fk_column_and_target_table_together_is_allowed_with_allow_destructive() {
        let users = Table::new("users", Backend::Postgres);
        let mut user_fk = col("user_id", ColumnType::Int64);
        user_fk.references = Some(ForeignKey::new("users", "id"));
        let baseline = vec![users, posts_with(vec![user_fk])];
        // desired: users gone, posts.user_id dropped.
        let desired = parsed(vec![posts_with(vec![])], vec![]);
        let plan = diff_schema(&baseline, &desired, ALLOW);
        guard_plan(&plan, ALLOW)
            .expect("co-dropping the FK column and its target table is valid SQL");
        let up = emit_up_sql(&plan).expect("emit");
        let drop_col = up
            .find("DROP COLUMN user_id")
            .expect("emits DROP COLUMN user_id");
        let drop_tbl = up.find("DROP TABLE users").expect("emits DROP TABLE users");
        assert!(
            drop_col < drop_tbl,
            "DROP COLUMN posts.user_id must precede DROP TABLE users:\n{up}"
        );
    }

    /// Finding C: two managed tables both dropped, `audit_logs.account_id` →
    /// `accounts`. Lexically `accounts` < `audit_logs`, so a naive order would
    /// `DROP TABLE accounts` (referenced) before `audit_logs` (referencing) → PG
    /// rejects. Drops must be REVERSE-topological (referencing first); the down
    /// leg recreates FORWARD (referenced first).
    #[test]
    fn drop_tables_reverse_topologically_ordered_by_fk() {
        let accounts = posts_ref_table("accounts", col("name", ColumnType::Text));
        let mut acct_fk = col("account_id", ColumnType::Int64);
        acct_fk.references = Some(ForeignKey::new("accounts", "id"));
        let audit = posts_ref_table("audit_logs", acct_fk);
        let baseline = vec![accounts, audit];
        let plan = diff_schema(&baseline, &parsed(vec![], vec![]), ALLOW);
        // Both tables are dropped, so nothing retained references either.
        guard_plan(&plan, ALLOW).expect("both dropped — no retained inbound reference");

        let up = emit_up_sql(&plan).expect("emit");
        let referenced = up.find("DROP TABLE accounts").expect("accounts dropped");
        let referencing = up
            .find("DROP TABLE audit_logs")
            .expect("audit_logs dropped");
        assert!(
            referencing < referenced,
            "drop referencing `audit_logs` before referenced `accounts`: {up}"
        );

        let down = emit_down_sql(&plan).expect("emit");
        let d_referenced = down.find("CREATE TABLE accounts").expect("down accounts");
        let d_referencing = down
            .find("CREATE TABLE audit_logs")
            .expect("down audit_logs");
        assert!(
            d_referenced < d_referencing,
            "down recreates referenced `accounts` before referencing `audit_logs`: {down}"
        );
    }

    /// Finding C: a cycle among dropped tables is refused (reuses the existing
    /// `CyclicTableDependencies` error), never emitted as unorderable SQL.
    #[test]
    fn drop_tables_fk_cycle_is_refused() {
        let mut a_b = col("b_id", ColumnType::Int64);
        a_b.references = Some(ForeignKey::new("b", "id"));
        let table_a = posts_ref_table("a", a_b);
        let mut b_a = col("a_id", ColumnType::Int64);
        b_a.references = Some(ForeignKey::new("a", "id"));
        let table_b = posts_ref_table("b", b_a);
        let plan = diff_schema(&[table_a, table_b], &parsed(vec![], vec![]), ALLOW);
        // (The inbound-FK guard excludes co-dropped referencers, so the cycle
        // surfaces at emission, mirroring the CreateTable cycle case.)
        guard_plan(&plan, ALLOW).expect("co-dropped tables never trip the inbound guard");
        let err = emit_up_sql(&plan).unwrap_err();
        let EmitError::CyclicTableDependencies { tables } = &err else {
            panic!("expected CyclicTableDependencies, got {err:?}");
        };
        assert_eq!(
            *tables,
            vec!["a".to_owned(), "b".to_owned()],
            "names the cycle"
        );
    }

    // -- Part B: rollback restores a cascade-dropped retained index ----------

    /// The `index_depends_on_column` contract: dependency is EXACT `columns`
    /// membership (the introspected `pg_depend` set), never a `definition`-text
    /// scan. A column name that merely appears in the `definition` string — e.g.
    /// as a string literal in a partial-index predicate — is NOT a dependency, so
    /// the projection can't wrongly prune an index Postgres actually keeps.
    #[test]
    fn index_dependency_detection_is_exact_column_membership() {
        // A partial index on `id` whose predicate string literal mentions `email`,
        // but which does NOT depend on the `email` column (its `pg_depend` set is
        // just `id`). Dropping `email` must NOT be read as a dependency.
        let partial = Index {
            name: "t_id_email_kind".to_owned(),
            columns: vec!["id".to_owned()],
            unique: false,
            definition: Some(
                "CREATE INDEX t_id_email_kind ON t (id) WHERE kind = 'email'".to_owned(),
            ),
            is_partial: false,
            key_columns: Vec::new(),
        };
        assert!(
            !index_depends_on_column(&partial, "email", Backend::Postgres),
            "a column name in a definition string literal is NOT a dependency (no false positive)"
        );
        assert!(
            index_depends_on_column(&partial, "id", Backend::Postgres),
            "the true dependent column (in `columns`) IS a dependency"
        );

        // An expression index carrying its exact `pg_depend` dependent set.
        let expr = Index {
            name: "u_lower_email".to_owned(),
            columns: vec!["email".to_owned()],
            unique: false,
            definition: Some("CREATE INDEX u_lower_email ON users (lower(email))".to_owned()),
            is_partial: false,
            key_columns: Vec::new(),
        };
        assert!(
            index_depends_on_column(&expr, "email", Backend::Postgres),
            "the expression-referenced `email` is captured in `columns`"
        );
        assert!(
            !index_depends_on_column(&expr, "mail", Backend::Postgres),
            "a column absent from `columns` is not a dependency"
        );

        let plain = Index {
            name: "u_email".to_owned(),
            columns: vec!["email".to_owned()],
            unique: true,
            definition: None,
            is_partial: false,
            key_columns: Vec::new(),
        };
        assert!(
            index_depends_on_column(&plain, "email", Backend::Postgres),
            "columns membership counts as a dependency"
        );
    }

    /// On `SQLite` a retained partial/expression index records only its KEY columns in
    /// `columns`, so a WHERE-predicate / key-expression column is detected via a
    /// word-bounded `definition` scan — otherwise dropping it would orphan the index
    /// and `SQLite` rejects the `DROP COLUMN`.
    #[test]
    fn sqlite_index_dependency_includes_predicate_and_expression_columns() {
        // A partial index whose KEY is `email` but whose predicate references
        // `deleted_at` (only in the definition text, NOT in `columns`).
        let partial = Index {
            name: "t_email_active".to_owned(),
            columns: vec!["email".to_owned()],
            unique: false,
            definition: Some(
                "CREATE INDEX t_email_active ON t (email) WHERE deleted_at IS NULL".to_owned(),
            ),
            is_partial: true,
            key_columns: Vec::new(),
        };
        assert!(
            index_depends_on_column(&partial, "deleted_at", Backend::Sqlite),
            "the WHERE-predicate column is a dependency on SQLite (definition scan)"
        );
        assert!(
            index_depends_on_column(&partial, "email", Backend::Sqlite),
            "the key column is still a dependency"
        );
        // Word-bounded: a longer identifier that merely contains the name is NOT a hit.
        assert!(!index_depends_on_column(
            &partial,
            "deleted",
            Backend::Sqlite
        ));
        assert!(!index_depends_on_column(&partial, "at", Backend::Sqlite));
        // The SAME index on Postgres keeps exact `columns` semantics (its real deps
        // would be in `columns`), so the definition text is never scanned.
        assert!(!index_depends_on_column(
            &partial,
            "deleted_at",
            Backend::Postgres
        ));
    }

    #[test]
    fn definition_references_column_is_word_bounded_and_case_insensitive() {
        let def = "CREATE INDEX i ON t (email) WHERE Deleted_At IS NULL AND kind = 'deleted_at_x'";
        assert!(definition_references_column(def, "email"));
        assert!(
            definition_references_column(def, "deleted_at"),
            "case-insensitive match against `Deleted_At`"
        );
        // A quoted identifier still matches (quotes are non-word boundaries).
        assert!(definition_references_column(
            "CREATE INDEX i ON t (\"email\")",
            "email"
        ));
        // Substring of a longer token does NOT match.
        assert!(!definition_references_column(
            "CREATE INDEX i ON t (email_verified)",
            "email"
        ));
        assert!(!definition_references_column(def, ""));
    }

    #[test]
    fn drop_column_up_drops_column_and_down_restores_retained_index() {
        // Baseline `users(id, email)` with a RETAINED constraint-owned unique
        // index on `email` (definition-carrying, no paired DropIndex). The model
        // removes `email`, so the plan carries only a DropColumn.
        let mut email_col = col("email", ColumnType::Text);
        email_col.nullable = false;
        let mut baseline = posts_ref_table("users", email_col);
        baseline.indexes.push(Index {
            name: "users_email_key".to_owned(),
            columns: vec!["email".to_owned()],
            unique: true,
            definition: Some("CREATE UNIQUE INDEX users_email_key ON users (email)".to_owned()),
            is_partial: false,
            key_columns: Vec::new(),
        });
        // Desired side: `email` removed. `diff_indexes` retains the definition
        // index (no DropIndex), so the plan is a lone DropColumn.
        let desired = posts_ref_table("users", col("keep", ColumnType::Text));
        let plan = diff_schema(
            std::slice::from_ref(&baseline),
            &parsed(vec![desired.clone()], vec![]),
            ALLOW,
        );
        assert!(
            plan.changes.iter().any(
                |c| matches!(c, SchemaChange::DropColumn { column, .. } if column.name == "email")

            ),
            "plan must drop `email`: {:?}",
            plan.changes
        );
        assert!(
            !plan
                .changes
                .iter()
                .any(|c| matches!(c, SchemaChange::DropIndex { index, .. } if index.name == "users_email_key")),
            "the retained definition index must NOT get a DropIndex: {:?}",
            plan.changes
        );

        let ctx = SchemaContext::from_tables(
            std::slice::from_ref(&desired),
            std::slice::from_ref(&baseline),
        );
        let up = emit_up_sql_with_context(&plan, &ctx).expect("emit up");
        let down = emit_down_sql_with_context(&plan, &ctx).expect("emit down");

        // UP: a bare DROP COLUMN (Postgres cascade-drops the index), never a
        // failing DROP INDEX on the constraint-backed index.
        assert!(
            up.contains("ALTER TABLE users DROP COLUMN email"),
            "up must drop the column: {up}"
        );
        assert!(
            !up.contains("DROP INDEX users_email_key"),
            "up must NOT emit DROP INDEX for the cascade-dropped retained index: {up}"
        );

        // DOWN: re-add the column, THEN recreate the retained index verbatim.
        assert!(
            down.contains("ADD COLUMN email"),
            "down must re-add the column: {down}"
        );
        assert!(
            down.contains("CREATE UNIQUE INDEX users_email_key ON users (email)"),
            "down must restore the cascade-dropped retained index: {down}"
        );
        let readd_at = down.find("ADD COLUMN email").expect("re-add present");
        let index_at = down
            .find("CREATE UNIQUE INDEX users_email_key")
            .expect("index restore present");
        assert!(
            readd_at < index_at,
            "column must be re-added before its dependent index is recreated: {down}"
        );
        // No regression: a single-column retained index is restored EXACTLY ONCE.
        assert_eq!(
            down.matches("CREATE UNIQUE INDEX users_email_key").count(),
            1,
            "the single-column retained index must be recreated exactly once: {down}"
        );
    }

    /// A retained index depending on TWO columns, both dropped, must have its
    /// recreation DELAYED until BOTH columns are restored and emitted EXACTLY ONCE
    /// (never once per dependent dropped column). Recreating it inline after the
    /// first re-add would fail (the second dependent column is still absent) and
    /// duplicate the `CREATE INDEX`.
    #[test]
    fn drop_two_columns_down_restores_multicol_retained_index_once_after_both() {
        // Baseline `users(id, keep, email, tenant_id)` with a RETAINED partial +
        // expression index depending on BOTH `email` and `tenant_id`
        // (definition-carrying, no paired DropIndex).
        let mut baseline = Table::new("users", Backend::Postgres);
        let mut id = col("id", ColumnType::Int64);
        id.primary_key = true;
        baseline.primary_key.push("id".to_owned());
        baseline.columns.push(id);
        baseline.columns.push(col("keep", ColumnType::Text));
        let mut email = col("email", ColumnType::Text);
        email.nullable = false;
        baseline.columns.push(email);
        baseline.columns.push(col("tenant_id", ColumnType::Int64));
        baseline.indexes.push(Index {
            name: "users_active".to_owned(),
            // The exact `pg_depend` dependent set: expression column + predicate
            // column (sorted by name, as introspection records it).
            columns: vec!["email".to_owned(), "tenant_id".to_owned()],
            unique: false,
            definition: Some(
                "CREATE INDEX users_active ON users (lower(email)) WHERE tenant_id IS NOT NULL"
                    .to_owned(),
            ),
            is_partial: false,
            key_columns: Vec::new(),
        });

        // Desired side: BOTH `email` and `tenant_id` removed. The model diff
        // retains the definition index (no DropIndex), so the plan is two
        // DropColumns.
        let mut desired = Table::new("users", Backend::Postgres);
        let mut did = col("id", ColumnType::Int64);
        did.primary_key = true;
        desired.primary_key.push("id".to_owned());
        desired.columns.push(did);
        desired.columns.push(col("keep", ColumnType::Text));

        let plan = diff_schema(
            std::slice::from_ref(&baseline),
            &parsed(vec![desired.clone()], vec![]),
            ALLOW,
        );
        assert_eq!(
            plan.changes
                .iter()
                .filter(|c| matches!(c, SchemaChange::DropColumn { .. }))
                .count(),
            2,
            "plan must drop both columns: {:?}",
            plan.changes
        );
        assert!(
            !plan
                .changes
                .iter()
                .any(|c| matches!(c, SchemaChange::DropIndex { index, .. } if index.name == "users_active")),
            "the retained definition index must NOT get a DropIndex: {:?}",
            plan.changes
        );

        let ctx = SchemaContext::from_tables(
            std::slice::from_ref(&desired),
            std::slice::from_ref(&baseline),
        );
        let down = emit_down_sql_with_context(&plan, &ctx).expect("emit down");

        // DOWN re-adds BOTH columns and recreates the index EXACTLY ONCE.
        let email_at = down.find("ADD COLUMN email").expect("email re-add present");
        let tenant_at = down
            .find("ADD COLUMN tenant_id")
            .expect("tenant_id re-add present");
        assert_eq!(
            down.matches("CREATE INDEX users_active").count(),
            1,
            "the multi-column retained index must be recreated exactly once (deduped): {down}"
        );
        let index_at = down
            .find("CREATE INDEX users_active")
            .expect("index restore present");
        assert!(
            email_at < index_at && tenant_at < index_at,
            "both dependent columns must be re-added BEFORE the index is recreated: {down}"
        );
    }
}