umbral-core 0.0.12

umbral internals: ORM, migrations, routing, DB backends, the Plugin trait. Do not depend on this directly; use the `umbral` facade.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
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
//! The migration engine — the north star.
//!
//! Implements the **declare → migrate → change → migrate** cycle from
//! `arch.md §0`. Users declare or change a model, run `migrate`, and the
//! framework either generates the missing migration file (via `make`)
//! or applies pending migration files (via `run`).
//!
//! At M5 (this milestone) the surface ships:
//!
//! - A process-wide [`ModelRegistry`] populated by
//!   `App::builder().model::<T>()`.
//! - A [`Snapshot`] of every registered model's metadata, JSON-
//!   serialisable so it can live inside a migration file's
//!   `snapshot_after`.
//! - An [`Operation`] enum with the two minimum-viable ops:
//!   [`Operation::CreateTable`] and [`Operation::DropTable`]. Column-
//!   level ops (`AddColumn`, `DropColumn`, `AlterColumn`) land at M8
//!   alongside rename detection (per `arch.md §7` and
//!   `docs/specs/06-migration-engine.md`). The "M5.1" label in the
//!   `UnsupportedChange` error message is shorthand for the same slot.
//! - A [`MigrationFile`] format (one JSON file per migration) carrying
//!   `id`, `operations`, and `snapshot_after`.
//! - The `umbral_migrations` tracking table (one row per applied
//!   migration, keyed by `(plugin, name)`).
//! - High-level entry points: [`make`], [`run`], [`show`].
//!
//! Reserved for M5.1+:
//!
//! - Column-level ops (`AddColumn`, `DropColumn`, `AlterColumn`).
//! - Rename-detection vs drop+add disambiguation (spec 06 §M8).
//! - `RunSql` / `RunCode` data-migration ops.
//! - Squashing, `--fake`, `--fake-initial` (PRD F-MIG-6 P2).
//! - Cross-plugin migration dependencies (needs M7 Plugin contract).
//!
//! See `docs/specs/06-migration-engine.md` for the full target shape.

use std::path::{Path, PathBuf};
use std::sync::OnceLock;

use serde::{Deserialize, Serialize};

use crate::backend::DatabaseBackend;
use crate::orm::{FieldSpec, Model, SqlType};

/// Per-process model registry. Published by `AppBuilder::build()`
/// after `.model::<T>()` calls and `.plugin(...)` registrations
/// collected metadata into the builder.
///
/// Stored as a flat vector of `(plugin_name, model)` pairs so M5's
/// existing `registered_models()` keeps working (drop the plugin
/// names) and the M7 plugin-aware walks (`registered_plugins`,
/// `models_for_plugin`) can read the same source of truth without a
/// second registry. The plugin name `"app"` covers models registered
/// via `.model::<T>()`; every other name is a real Plugin's.
static REGISTRY: OnceLock<Vec<(String, ModelMeta)>> = OnceLock::new();

/// Initialize the registry with one entry per plugin.
///
/// `App::build()` calls this after collecting `.model::<T>()` into the
/// implicit `"app"` plugin and walking every registered plugin's
/// `Plugin::models()`. Plugins missing from the map contribute zero
/// models (default-noop `models()` returns an empty vec; the entry
/// can be omitted).
pub(crate) fn init_plugins(per_plugin: std::collections::HashMap<String, Vec<ModelMeta>>) {
    let mut flat: Vec<(String, ModelMeta)> = Vec::new();
    let mut plugin_names: Vec<String> = per_plugin.keys().cloned().collect();
    plugin_names.sort();
    for plugin in plugin_names {
        for m in per_plugin.get(&plugin).cloned().unwrap_or_default() {
            flat.push((plugin.clone(), m));
        }
    }
    REGISTRY
        .set(flat)
        .expect("umbral::migrate::init_plugins called more than once");
}

/// Return every registered model, flat. Drops the per-plugin grouping;
/// useful when the caller only needs the model set (e.g. M5's `make`
/// when the codebase only had a single `"app"` plugin).
///
/// # Panics
///
/// Panics if `App::build()` hasn't run.
pub fn registered_models() -> Vec<ModelMeta> {
    registered_models_opt()
        .expect("umbral: model registry not initialised — did you call App::build()?")
}

/// [`registered_models`] without the panic: `None` when the registry hasn't been
/// initialised yet.
///
/// For callers that legitimately run before (or without) `App::build()` — the
/// boot system checks are the case in point, and a check that panics is a check
/// that can never report anything.
pub fn registered_models_opt() -> Option<Vec<ModelMeta>> {
    Some(REGISTRY.get()?.iter().map(|(_, m)| m.clone()).collect())
}

/// Whether the model registry has been initialised. False before
/// `App::build()` has run; true after the phase-3 `init_plugins`
/// call publishes the per-plugin map. Used by system checks that
/// walk the registry — they return an empty result when the
/// registry isn't ready rather than panicking (so low-level tests
/// that drive `check::run_all` without booting an App keep working).
pub fn is_initialised() -> bool {
    REGISTRY.get().is_some()
}

/// PK lift Pass E — cached `(pk_column_name, pk_sql_type)` lookup
/// keyed by table name. Used by the FK decode path
/// (`fk_target_pk_sql_type` in `orm/dynamic.rs`) and the
/// select_related hydrators, both of which previously cloned the
/// full `Vec<ModelMeta>` per call and linear-scanned for the
/// target's PK column.
///
/// REGISTRY is a `OnceLock` set once during `App::build`; this cache
/// reads from it the first time anyone asks for a PK lookup AFTER
/// initialisation, then serves from a `HashMap` for every
/// subsequent call. Eliminates the per-row `registered_models()`
/// clone in hot decode loops.
///
/// Returns `None` when the registry isn't initialised (the cache
/// stays uninstantiated so a follow-up call after `App::build`
/// gets the real table set), OR when the named table isn't in the
/// registry (orphan / system / typo).
pub fn pk_meta_for_table(table: &str) -> Option<(String, crate::orm::SqlType)> {
    if !is_initialised() {
        // Defer cache init until App::build has populated REGISTRY.
        // The cache MUST NOT memoize an empty map; otherwise
        // post-init callers would see no PK metadata forever.
        return None;
    }
    static CACHE: std::sync::OnceLock<
        std::collections::HashMap<String, (String, crate::orm::SqlType)>,
    > = std::sync::OnceLock::new();
    let map = CACHE.get_or_init(|| {
        let mut out = std::collections::HashMap::new();
        for m in registered_models() {
            if let Some(pk) = m.pk_column() {
                out.insert(m.table.clone(), (pk.name.clone(), pk.ty));
            }
        }
        out
    });
    map.get(table).cloned()
}

/// Cached model lookup by SQL table name.
///
/// Unlike [`registered_models`], this does not deep-clone the full
/// registry on every call. It clones only the matched [`ModelMeta`],
/// which keeps row-by-row dynamic serializers from paying
/// O(registry-size) per row.
pub fn model_meta_for_table(table: &str) -> Option<ModelMeta> {
    if !is_initialised() {
        return None;
    }
    static CACHE: std::sync::OnceLock<std::collections::HashMap<String, ModelMeta>> =
        std::sync::OnceLock::new();
    let map = CACHE.get_or_init(|| {
        registered_models()
            .into_iter()
            .map(|m| (m.table.clone(), m))
            .collect()
    });
    map.get(table).cloned()
}

/// The SQL type a column's value actually binds / decodes as (PK lift).
/// Equals `col.ty` for everything except a `ForeignKey`, where it resolves
/// to the referenced model's PK type via [`pk_meta_for_table`] — so an FK
/// pointing at a `String`-slug- or `Uuid`-PK target is handled as text /
/// uuid instead of being forced through i64. Falls back to `BigInt` (the
/// historical default) when the target can't be resolved (registry not yet
/// initialised, or an unregistered target table).
///
/// The single source of truth for "what shape is this FK really?", used by
/// `backup` (dump/load) and the dynamic filter helpers.
pub fn fk_effective_type(col: &Column) -> crate::orm::SqlType {
    if matches!(col.ty, crate::orm::SqlType::ForeignKey) {
        col.fk_target
            .as_deref()
            .and_then(pk_meta_for_table)
            .map(|(_, ty)| ty)
            .unwrap_or(crate::orm::SqlType::BigInt)
    } else {
        col.ty
    }
}

/// Return the registered plugin names that contributed at least one
/// model. Sorted deterministically. Used as a fallback when no
/// topological order is published; the M7 walk used this directly,
/// and M8 prefers [`plugin_order`] when it's been set.
pub fn registered_plugins() -> Vec<String> {
    let mut names: Vec<String> = REGISTRY
        .get()
        .expect("umbral: model registry not initialised — did you call App::build()?")
        .iter()
        .map(|(p, _)| p.clone())
        .collect();
    names.sort();
    names.dedup();
    names
}

/// The topological plugin order published by `App::build()` after its
/// phase 1.5 sort. `None` until that runs; the CLI subcommands
/// (`makemigrations`, `migrate`, `showmigrations`) call `App::build()`
/// via `boot_for_management` before reaching the migration engine.
static PLUGIN_ORDER: OnceLock<Vec<String>> = OnceLock::new();

/// Per-model database alias (`Model::NAME -> alias`) published by
/// `App::build()` after walking each registered plugin's
/// `Plugin::database()`. Models whose plugin returned `None` are
/// absent from the map; QuerySet's `resolve_pool` falls back to the
/// `"default"` alias for those. Lookup is `O(1)` on a `HashMap`.
static MODEL_ALIASES: OnceLock<std::collections::HashMap<String, String>> = OnceLock::new();

/// Publish the topological plugin order. Called by `App::build()` once
/// the phase 1.5 sort has produced the order. Must include the
/// implicit `"app"` plugin even when no real plugins are registered.
pub(crate) fn init_plugin_order(order: Vec<String>) {
    PLUGIN_ORDER
        .set(order)
        .expect("umbral::migrate::init_plugin_order called more than once");
}

/// Return the topological plugin order if `App::build()` published
/// one; otherwise fall back to [`registered_plugins`] (sorted by
/// name). The fallback keeps existing M5 / M6 tests working without
/// requiring them to wire a full plugin sort.
pub fn plugin_order() -> Vec<String> {
    PLUGIN_ORDER
        .get()
        .cloned()
        .unwrap_or_else(registered_plugins)
}

/// The client-facing API endpoints every registered plugin advertised
/// via `Plugin::api_endpoints()`, collected by `App::build()`. `None`
/// until that runs; an app with no advertising plugins publishes an
/// empty vec.
static API_ENDPOINTS: OnceLock<Vec<crate::plugin::ApiEndpoint>> = OnceLock::new();

/// Publish the collected `Plugin::api_endpoints()`. Called once by
/// `App::build()` after walking every registered plugin.
pub(crate) fn init_api_endpoints(endpoints: Vec<crate::plugin::ApiEndpoint>) {
    let _ = API_ENDPOINTS.set(endpoints);
}

/// Every callable endpoint registered plugins advertised for service
/// discovery, in plugin-registration order. Empty until `App::build()`
/// has run. A REST API root (or any discovery surface) reads this to
/// list plugin endpoints without depending on those plugins' crates.
pub fn registered_api_endpoints() -> Vec<crate::plugin::ApiEndpoint> {
    API_ENDPOINTS.get().cloned().unwrap_or_default()
}

/// Publish the per-model alias routing. Called by `App::build()`
/// during phase 3 after walking every plugin's `Plugin::database()`.
/// Plugins that returned `None` contribute no entries; only the
/// explicit overrides land here.
pub(crate) fn init_model_aliases(map: std::collections::HashMap<String, String>) {
    MODEL_ALIASES
        .set(map)
        .expect("umbral::migrate::init_model_aliases called more than once");
}

/// Look up the database alias for a SQL table name — the reverse of
/// the `Model::NAME → alias` lookup that [`model_alias`] does. Walks
/// the registered model metas to find the one whose `table` matches
/// (snake_case of the struct name + any `#[umbral(table = "...")]`
/// override) and returns its alias if set. Falls back to `"default"`
/// when no model owns the table (e.g. orphan schema, the
/// `umbral_migrations` table itself) — those land on the main pool.
///
/// Used by the migration engine's per-DB dispatch in [`run_in`] to
/// route each operation to the right pool.
pub fn table_alias(table_name: &str) -> String {
    for meta in registered_models() {
        if meta.table == table_name {
            return model_alias(&meta.name).unwrap_or_else(|| "default".to_string());
        }
    }
    "default".to_string()
}

/// Look up the database alias for one model. Returns `None` if the
/// model isn't routed explicitly (the caller falls back to the
/// `"default"` pool); returns `None` even when the alias map hasn't
/// been initialised so low-level tests that drive `init_plugins`
/// directly don't have to wire a second call.
pub fn model_alias(model_name: &str) -> Option<String> {
    MODEL_ALIASES.get()?.get(model_name).cloned()
}

static MODEL_META_BY_NAME: OnceLock<std::collections::HashMap<String, ModelMeta>> = OnceLock::new();

/// Cached `&ModelMeta` lookup by model name. Returns `None` before
/// `App::build` populates the registry (low-level tests), which the routing
/// seam treats as "fall back to legacy static routing".
pub fn model_meta_ref(name: &str) -> Option<&'static ModelMeta> {
    if !is_initialised() {
        return None;
    }
    MODEL_META_BY_NAME
        .get_or_init(|| {
            registered_models()
                .into_iter()
                .map(|m| (m.name.clone(), m))
                .collect()
        })
        .get(name)
}

/// Return the models registered against a specific plugin. Empty if
/// no plugin by that name registered models.
pub fn models_for_plugin(plugin: &str) -> Vec<ModelMeta> {
    REGISTRY
        .get()
        .expect("umbral: model registry not initialised — did you call App::build()?")
        .iter()
        .filter(|(p, _)| p == plugin)
        .map(|(_, m)| m.clone())
        .collect()
}

/// Static metadata for one registered model, copied off the `Model`
/// trait's `const`s when the user calls `App::builder().model::<T>()`.
///
/// Owned (no lifetimes) so the registry can hold an arbitrary number
/// without the lifetime contortions a slice of trait references would
/// need. The cost is one Vec at `App::build` time; the win is
/// `registered_models()` having a plain `&'static [ModelMeta]` signature.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ModelMeta {
    /// The struct name (`Model::NAME`). Identifies the model across
    /// snapshot diffs even if the table is renamed.
    pub name: String,
    /// The SQL table name (`Model::TABLE`).
    pub table: String,
    /// One owned column descriptor per field, in declaration order.
    /// Owned (`Column`, not the underlying static `FieldSpec`) so the
    /// snapshot round-trips cleanly through serde.
    pub fields: Vec<Column>,
    /// Human-readable display name from `Model::DISPLAY`. Defaults to
    /// `Model::NAME` when no `#[umbral(display = "...")]` is present.
    #[serde(default)]
    pub display: String,
    /// Lucide icon slug from `Model::ICON`. Defaults to `"database"`.
    #[serde(default = "default_icon")]
    pub icon: String,
    /// Database alias from `Model::DATABASE`, when set. `None` means
    /// "fall back to the owning plugin's `Plugin::database()`, then
    /// the `default` pool." Captured here so `App::build`'s alias
    /// routing can read it without re-reaching into the trait at a
    /// later phase.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub database: Option<String>,
    /// Mirrors `Model::SINGLETON`. Closes BUG-9 in
    /// `bugs/tests/testBugs.md`. Default `false`; admin renderers
    /// read it to auto-redirect list-view to the edit form.
    #[serde(default, skip_serializing_if = "is_false")]
    pub singleton: bool,
    /// Mirrors `Model::UNIQUE_TOGETHER`. Composite-UNIQUE constraints,
    /// each inner `Vec<String>` listing the columns of one constraint.
    /// Closes BUG-6.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub unique_together: Vec<Vec<String>>,
    /// Mirrors `Model::INDEXES`. Each inner `Vec<String>` lists the
    /// columns of one multi-column index. Closes BUG-7.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub indexes: Vec<Vec<String>>,
    /// Mirrors `Model::ORDERING`. Each tuple is `(column, descending)`
    /// — `descending == true` lowers to `ORDER BY col DESC`. Closes
    /// BUG-8.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub ordering: Vec<(String, bool)>,
    /// Mirrors `Model::M2M_RELATIONS`. Many-to-many relations declared
    /// on this model. The migration engine uses this to auto-generate
    /// junction tables. Closes BUG-16.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub m2m_relations: Vec<M2MRelation>,
    /// Mirrors `Model::SOFT_DELETE` (`#[umbral(soft_delete)]`). The
    /// dynamic / annotate paths read this to auto-exclude
    /// `deleted_at IS NULL` children from correlated counts and to
    /// drive trash-aware admin views without re-reaching into the
    /// typed trait. Shared enabler for gaps2 #35 + #39a.
    #[serde(default, skip_serializing_if = "is_false")]
    pub soft_delete: bool,
    /// `#[umbral(audited)]`. Lives on `ModelMeta` (not re-derived per path) so
    /// the DYNAMIC write path — which is what admin and REST run on — reads the
    /// same source of truth the typed one does.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub audited: bool,
    /// features #73 — `#[umbral(view = "...")]`. `Some(sql)` means this model is
    /// backed by a database VIEW whose body is `sql`; the migration engine emits
    /// `CREATE VIEW` for it and never `CREATE TABLE`. Carried on `ModelMeta` (not
    /// just the trait) because the *snapshot* is what `makemigrations` diffs — a
    /// view whose SQL changed has to be detectable without the model being in scope.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub view: Option<String>,
    /// features #73 — the view is MATERIALIZED (Postgres-only). Meaningless unless
    /// `view` is `Some`.
    #[serde(default, skip_serializing_if = "is_false")]
    pub materialized: bool,
    /// The app label (the owning plugin's name), mirrors `Model::APP_LABEL`.
    /// Sourced from `#[umbral(plugin = "...")]`; `"app"` when absent.
    /// Authoritative for permission codenames (gaps2 #80g): replaces the
    /// old table-name-split heuristic that collided distinct models. The
    /// `#[serde(default)]` keeps pre-#80g snapshot JSON round-tripping.
    #[serde(default = "default_app_label")]
    pub app_label: String,
}

fn default_app_label() -> String {
    "app".to_string()
}

impl Default for ModelMeta {
    fn default() -> Self {
        Self {
            name: String::new(),
            table: String::new(),
            fields: Vec::new(),
            display: String::new(),
            icon: default_icon(),
            database: None,
            singleton: false,
            unique_together: Vec::new(),
            indexes: Vec::new(),
            ordering: Vec::new(),
            m2m_relations: Vec::new(),
            soft_delete: false,
            audited: false,
            view: None,
            materialized: false,
            app_label: default_app_label(),
        }
    }
}

impl Default for Column {
    /// A nullable-free `BigInt` column with every optional marker off, so a
    /// hand-built fixture can name the two or three fields it cares about and
    /// `..Column::default()` the rest.
    ///
    /// `db_constraint` defaults to `true`, matching the serde default: an FK
    /// emits a physical `REFERENCES` clause unless the field opts out. Getting
    /// this backwards would silently drop constraints AND the plugin ordering
    /// edges derived from them (see `app::fk_plugin_edges`).
    fn default() -> Self {
        Self {
            name: String::new(),
            ty: crate::orm::SqlType::BigInt,
            primary_key: false,
            nullable: false,
            fk_target: None,
            noform: false,
            privileged: false,
            private: false,
            secret: false,
            db_constraint: true,
            noedit: false,
            is_string_repr: false,
            max_length: 0,
            choices: Vec::new(),
            choice_labels: Vec::new(),
            default: String::new(),
            is_multichoice: false,
            unique: false,
            on_delete: crate::orm::FkAction::NoAction,
            on_update: crate::orm::FkAction::NoAction,
            index: false,
            auto_now_add: false,
            auto_uuid: false,
            auto_now: false,
            auto_user_add: false,
            auto_user: false,
            trim: false,
            lowercase: false,
            case_insensitive: false,
            help: String::new(),
            example: String::new(),
            widget: None,
            supported_backends: Vec::new(),
            min: None,
            max: None,
            text_format: None,
            slug_from: None,
        }
    }
}

/// Owned mirror of `orm::M2MRelationSpec` so `ModelMeta` can be
/// serialised into migration JSON without lifetimes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct M2MRelation {
    pub field_name: String,
    pub target_table: String,
    pub target_name: String,
}

fn default_icon() -> String {
    "database".to_string()
}

/// Serde default for [`Operation::CreateM2MTable`]'s `parent_ty` /
/// `child_ty` fields. Older snapshot files (pre-phase-2) had no
/// per-side PK type and assumed `BigInt` on both ends — this keeps
/// them round-tripping without rewrites.
fn default_bigint() -> crate::orm::SqlType {
    crate::orm::SqlType::BigInt
}

impl ModelMeta {
    /// The primary-key column on this model. Every umbral model
    /// has exactly one PK by construction (the derive enforces
    /// it), but the lookup is `Option`-shaped because nothing
    /// stops a hand-written `ModelMeta` (test fixtures, etc.)
    /// from omitting it.
    pub fn pk_column(&self) -> Option<&Column> {
        self.fields.iter().find(|c| c.primary_key)
    }

    /// Read static metadata off `T: Model` into an owned `ModelMeta`.
    /// Called from `AppBuilder::model::<T>()`.
    pub fn for_<T: Model>() -> Self {
        Self {
            name: T::NAME.to_string(),
            table: T::TABLE.to_string(),
            fields: T::FIELDS.iter().map(Column::from).collect(),
            display: T::DISPLAY.to_string(),
            icon: T::ICON.to_string(),
            database: T::DATABASE.map(|s| s.to_string()),
            singleton: T::SINGLETON,
            unique_together: T::UNIQUE_TOGETHER
                .iter()
                .map(|group| group.iter().map(|s| s.to_string()).collect())
                .collect(),
            indexes: T::INDEXES
                .iter()
                .map(|group| group.iter().map(|s| s.to_string()).collect())
                .collect(),
            ordering: T::ORDERING
                .iter()
                .map(|(col, desc)| (col.to_string(), *desc))
                .collect(),
            m2m_relations: T::M2M_RELATIONS
                .iter()
                .map(|r| M2MRelation {
                    field_name: r.field_name.to_string(),
                    target_table: r.target_table.to_string(),
                    target_name: r.target_name.to_string(),
                })
                .collect(),
            soft_delete: T::SOFT_DELETE,
            audited: T::AUDITED,
            view: T::VIEW.map(|s| s.to_string()),
            materialized: T::MATERIALIZED,
            app_label: T::APP_LABEL.to_string(),
        }
    }
}

/// A snapshot of every registered model at a point in time.
///
/// Serialised into the `snapshot_after` field of a migration file so
/// future `makemigrations` runs can diff against it without replaying
/// every prior migration's operations.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct Snapshot {
    /// Models sorted by name so the JSON is deterministic and the
    /// snapshot_hash is stable across runs that produce equivalent
    /// content.
    pub models: Vec<ModelMeta>,
}

impl Snapshot {
    /// Build a snapshot from the live registry (the current state of
    /// the application's models, post-`App::build`).
    pub fn current() -> Self {
        let mut models = registered_models().to_vec();
        models.sort_by(|a, b| a.name.cmp(&b.name));
        Self { models }
    }

    /// Build a snapshot containing only the models registered
    /// against the given plugin. Used by `make_in` to diff each
    /// plugin's migrations independently against its own prior
    /// snapshot, so cross-plugin model sets don't bleed into one
    /// migration file.
    pub fn current_for(plugin: &str) -> Self {
        let mut models = models_for_plugin(plugin);
        models.sort_by(|a, b| a.name.cmp(&b.name));
        Self { models }
    }

    /// Compute the snapshot's SHA-256 hash, hex-encoded. Stored in the
    /// `umbral_migrations.snapshot_hash` column for drift detection.
    pub fn hash(&self) -> String {
        use sha2::{Digest, Sha256};
        let json = serde_json::to_string(self).expect("Snapshot serializes");
        let digest = Sha256::digest(json.as_bytes());
        hex(&digest[..])
    }
}

fn hex(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        s.push(HEX[(b >> 4) as usize] as char);
        s.push(HEX[(b & 0x0f) as usize] as char);
    }
    s
}

/// One operation inside a migration. The migration engine renders each
/// operation to SQL via the active backend (M4 `DatabaseBackend::
/// map_type`) and runs them in declaration order inside one
/// transaction per migration file.
///
/// Shipped: table-level ops (`CreateTable` / `DropTable`), `AddColumn` /
/// `DropColumn`, `AlterColumn` (nullable flips), index / constraint ops
/// (`AddIndex` / `DropIndex`), rename detection (`RenameTable` /
/// `RenameColumn`), database views (`CreateView` / `DropView`), M2M junction
/// tables (`CreateM2MTable` / `DropM2MTable`), column comments
/// (`SetColumnComment`), and the `RunSql` data-migration escape hatch.
/// Still deferred: `AlterColumn` **type changes**, primary-key flips, and the
/// `RunCode` Rust data-migration op. See `docs/specs/06-migration-engine.md`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind")]
pub enum Operation {
    /// Create a new table. `columns` is in declaration order; the
    /// engine builds a sea-query `Table::create()` over them and runs
    /// the rendered DDL. `unique_together` lowers to inline
    /// `UNIQUE (col1, col2)` clauses; `indexes` lowers to follow-up
    /// `CREATE INDEX` statements after the table is created. Both
    /// default to empty for backward-compat with older snapshots.
    CreateTable {
        table: String,
        columns: Vec<Column>,
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        unique_together: Vec<Vec<String>>,
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        indexes: Vec<Vec<String>>,
    },
    /// Drop an existing table.
    DropTable { table: String },
    /// features #73 — create a database VIEW from `#[umbral(view = "...")]`.
    ///
    /// There is no `AlterView`, and there never will be: a view holds no rows, so
    /// changing one is a drop and a recreate. That is why views escape every hard
    /// problem the table side of this engine spent its life on — no data-preserving
    /// ALTER, no rename-vs-drop disambiguation, nothing to back up.
    CreateView {
        /// The view's name in the database (the model's `TABLE`).
        name: String,
        /// The SELECT body, verbatim from the attribute. Opaque to the engine.
        sql: String,
        /// `CREATE MATERIALIZED VIEW` (Postgres-only) rather than `CREATE VIEW`.
        #[serde(default, skip_serializing_if = "is_false")]
        materialized: bool,
    },
    /// features #73 — drop a database VIEW.
    DropView {
        /// The view's name in the database.
        name: String,
        /// Whether it was created as MATERIALIZED — the DROP statement differs.
        #[serde(default, skip_serializing_if = "is_false")]
        materialized: bool,
    },
    /// Add a new column to an existing table. Rendered as
    /// `ALTER TABLE x ADD COLUMN y TYPE [NOT NULL]`. SQLite refuses a
    /// non-nullable add against a populated table without a default;
    /// the engine surfaces that as a sqlx error at apply time (M8 v1).
    /// A future op `AddColumnWithDefault` lifts the restriction once
    /// the `#[umbral(default = ...)]` attribute lands.
    AddColumn { table: String, column: Column },
    /// Drop a column from an existing table. Rendered as
    /// `ALTER TABLE x DROP COLUMN y`. SQLite 3.35+ and Postgres
    /// support this natively; older SQLite would need a table-
    /// recreation dance the engine doesn't implement.
    DropColumn { table: String, column: String },
    /// Alter a column's nullable flag (the only safe in-place change
    /// the engine ships at M5.1). Self-contained: carries the full
    /// new column list so the SQLite table-recreation dance can
    /// rebuild the schema without re-reading the snapshot. The
    /// `column` field names the specific column that triggered the
    /// alter (used for the filename suffix and diagnostics); the
    /// `new_columns` list is the post-change schema.
    AlterColumn {
        table: String,
        column: String,
        new_columns: Vec<Column>,
        /// The table's composite UNIQUE groups (audit_2 core-migrate #10). The
        /// SQLite recreation dance rebuilds the table from scratch, so it must
        /// re-emit these — otherwise a nullable-flip / safe-cast alter silently
        /// DROPS every composite UNIQUE constraint (duplicates become
        /// insertable — integrity loss). Postgres alters in place and ignores
        /// this. `serde(default)` keeps older on-disk migrations deserialising.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        unique_together: Vec<Vec<String>>,
        /// The table's composite (multi-column) index groups (audit_2
        /// core-migrate #10). Re-created by the SQLite dance after the rebuild,
        /// for the same reason as `unique_together`. Single-column / FK /
        /// soft-delete indexes are re-derived from `new_columns`.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        indexes: Vec<Vec<String>>,
        /// Snapshot of the table's columns *before* this alter. Carried
        /// so the Postgres renderer can decide per-column whether it
        /// needs a TYPE/USING clause vs a SET/DROP NOT NULL — without
        /// re-walking the snapshot file. `Option` + `serde(default)`
        /// keeps older on-disk migrations deserialising cleanly; ops
        /// produced before this field existed get `None` and fall back
        /// to the legacy nullable-only Postgres path.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        prev_columns: Option<Vec<Column>>,
    },
    /// Rename an existing table. Emitted by `diff` when a model's table
    /// name changes but its `Model::NAME` (the Rust struct name) stays
    /// the same (first-pass detection), or when the column shapes are
    /// bit-identical and the struct name changed too (second-pass
    /// heuristic detection). Both SQLite and Postgres render as
    /// `ALTER TABLE "<from>" RENAME TO "<to>"`.
    ///
    /// The migration tracking table records `(plugin, name)` of each
    /// applied migration — it is not affected by a table rename inside
    /// the migration.
    RenameTable { from: String, to: String },
    /// Create a many-to-many junction table. Auto-emitted when a model
    /// gains an `M2M<T>` field. Closes BUG-16 phase 2.
    ///
    /// The junction table name is `parent_table_field_name`. Columns:
    /// `parent_id` (FK to parent), `child_id` (FK to target), both with
    /// `ON DELETE CASCADE`. Composite PK `(parent_id, child_id)`.
    ///
    /// `parent_ty` and `child_ty` carry the SQL types of the
    /// referenced PK columns — `BigInt` for an `i64` PK, `Text` for a
    /// `String` slug, `Uuid` for a `uuid::Uuid`. The renderer maps
    /// these to the right column type per backend; without them the
    /// junction's `child_id INTEGER` would reject a string codename
    /// at insert time. `#[serde(default)]` keeps older snapshot files
    /// (pre-phase-2) round-tripping — they default to `BigInt`,
    /// matching the original i64-only behaviour.
    CreateM2MTable {
        junction_table: String,
        parent_table: String,
        parent_col: String,
        child_table: String,
        child_col: String,
        #[serde(default = "default_bigint")]
        parent_ty: crate::orm::SqlType,
        #[serde(default = "default_bigint")]
        child_ty: crate::orm::SqlType,
    },
    /// Drop a many-to-many junction table. Auto-emitted when an `M2M<T>`
    /// field is removed from a model.
    DropM2MTable { junction_table: String },
    /// Gap 88: rename a column on an existing table. Emitted by the
    /// diff engine when a single column with one shape was dropped
    /// and one with the same shape was added in the same diff —
    /// the heuristic match for "the user renamed `title` to
    /// `headline`." Both SQLite (3.25+) and Postgres render as
    /// `ALTER TABLE "<t>" RENAME COLUMN "<from>" TO "<to>"`.
    ///
    /// `column` carries the post-rename column shape so the
    /// snapshot stays in sync. The migration only renames; never
    /// alters other column attributes — a rename combined with a
    /// type change emits a RenameColumn AND a follow-on AlterColumn
    /// against the new name.
    RenameColumn {
        table: String,
        from: String,
        to: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        column: Option<Column>,
    },
    /// gaps3 #43: set (or clear) a column's database comment from
    /// `#[umbral(help = "...")]`. Renders as `COMMENT ON COLUMN "<t>"."<c>" IS
    /// '<comment>'` on Postgres, and to *nothing* on SQLite, which has no
    /// comment facility. An empty `comment` clears it with `IS NULL` — Postgres
    /// distinguishes "no comment" from "the empty comment".
    ///
    /// `CreateTable` and `AddColumn` emit their own comments inline, so this op
    /// exists for the case they can't cover: the help text on an *existing*
    /// column changed. It touches no rows and takes no lock worth naming, so it
    /// classifies as `OpSafety::Safe`.
    SetColumnComment {
        table: String,
        column: String,
        /// Empty string means "remove the comment".
        comment: String,
    },
    /// Gap #69: a raw-SQL **data** migration. Unlike every other
    /// variant it changes *rows*, not the schema model — so the
    /// autodetector NEVER emits it (it has no model-state effect), and
    /// a migration carrying only `RunSql` ops has
    /// `snapshot_after == snapshot_before`. It is always hand-authored:
    /// generate an empty migration with `makemigrations --empty
    /// <plugin>`, then add the `RunSql` op by editing the file.
    ///
    /// `sql` is the forward statement(s), executed verbatim on the
    /// per-migration transaction — same string on both backends (raw
    /// SQL the renderer passes through untouched), so the author owns
    /// portability. `reverse_sql` is the optional un-apply statement
    /// (used by a future `migrate --reverse`); `None` means
    /// irreversible.
    ///
    /// Under schema-per-tenant the op runs **per tenant schema** (the
    /// schema-migrate loop applies every op under the
    /// `<schema>, public` search_path), so a tenant-app `RunSql` writes
    /// tenant rows while reading shared `public` lookup tables — the
    /// boundary-spanning data migration. A shared-app `RunSql` runs once
    /// in `public` via the normal `migrate`.
    RunSql {
        sql: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        reverse_sql: Option<String>,
    },
    /// Create a composite index, or a composite UNIQUE constraint, on an
    /// EXISTING table. Emitted by `diff` when a model gains a
    /// `unique_together` group or a multi-column `indexes` entry with no
    /// accompanying column change — a case that previously produced NO
    /// migration at all, so the constraint was silently never created.
    ///
    /// `unique` selects `CREATE UNIQUE INDEX` (a `unique_together` group)
    /// vs a plain `CREATE INDEX` (an `indexes` group). The index NAME is
    /// deterministic — `uniq_<table>_<cols>` when unique, `idx_<table>_<cols>`
    /// otherwise — so the matching [`DropIndex`](Operation::DropIndex) can
    /// name it. Rendered `IF NOT EXISTS` on both backends, so it is a safe
    /// no-op when a same-migration `AlterColumn` already rebuilt the table
    /// with the constraint (the SQLite dance) — the two never conflict.
    AddIndex {
        table: String,
        columns: Vec<String>,
        #[serde(default)]
        unique: bool,
    },
    /// Drop a composite index / UNIQUE constraint previously created by an
    /// [`AddIndex`](Operation::AddIndex), or by a `CreateTable` that renders
    /// its `unique_together`/`indexes` as the same deterministically-named
    /// indexes. Emitted by `diff` when a model LOSES a `unique_together`
    /// group or `indexes` entry. Rendered `DROP INDEX IF EXISTS <name>` on
    /// both backends (the name is recomputed from `table` + `columns` +
    /// `unique`, matching `AddIndex`).
    DropIndex {
        table: String,
        columns: Vec<String>,
        #[serde(default)]
        unique: bool,
    },
}

impl Operation {
    /// The primary table this operation targets. For `RenameTable`,
    /// returns the source name (the post-rename `to` lives in the new
    /// snapshot, but routing decisions look up the model meta by its
    /// pre-rename `from`).
    ///
    /// Used by `run_in`'s per-DB dispatch loop to route each op to the
    /// pool where its table actually lives.
    pub fn table_name(&self) -> &str {
        match self {
            Operation::CreateView { name, .. } | Operation::DropView { name, .. } => name,
            Operation::CreateTable { table, .. }
            | Operation::DropTable { table }
            | Operation::AddColumn { table, .. }
            | Operation::DropColumn { table, .. }
            | Operation::AlterColumn { table, .. }
            | Operation::RenameColumn { table, .. }
            | Operation::SetColumnComment { table, .. }
            | Operation::AddIndex { table, .. }
            | Operation::DropIndex { table, .. } => table,
            Operation::RenameTable { from, .. } => from,
            Operation::CreateM2MTable { junction_table, .. }
            | Operation::DropM2MTable { junction_table } => junction_table,
            // A data migration targets no single table. The empty name
            // routes it to the `"default"` alias via `table_alias`'s
            // fallback (see `op_targets_alias`).
            Operation::RunSql { .. } => "",
        }
    }
}

/// One column inside a [`Operation::CreateTable`].
///
/// Mirrors the structure of [`FieldSpec`] but is fully owned for
/// serialisation. Reconstructed from a `FieldSpec` at diff time.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Column {
    pub name: String,
    pub ty: SqlType,
    pub primary_key: bool,
    pub nullable: bool,
    /// For `SqlType::ForeignKey` columns: the SQL table name of the
    /// referenced model. `None` for all non-FK columns.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fk_target: Option<String>,
    /// When `true`, this field is never shown on any admin form (create or
    /// edit). Propagated from `FieldSpec::noform`.
    #[serde(default)]
    pub noform: bool,
    /// When `true`, this field is a privileged/server-managed column that the
    /// untrusted JSON write path (`insert_json`/`update_json`, i.e. REST
    /// create/update + admin form-submit) strips UNLESS the caller explicitly
    /// authorizes it via [`DynQuerySet::allow_privileged`]. Propagated from
    /// `FieldSpec::privileged`. This is the default-DENY guard for mass
    /// assignment of fields like `is_superuser`/`is_staff`/ownership FKs
    /// (audit_2 H3): they can't be set by an unprivileged writer even if the
    /// model exposes them on its create/update surface. Purely a write-auth
    /// concern — never part of the schema shape, so it is skipped from
    /// migration snapshots when at its `false` default.
    #[serde(default, skip_serializing_if = "is_false")]
    pub privileged: bool,
    /// Confidential: stripped from serialized output unless the read unlocks it via
    /// `DynQuerySet::allow_private`. Propagated from `FieldSpec::private`. Purely a
    /// read-auth concern — never part of the schema shape, so it is skipped from migration
    /// snapshots at its `false` default, exactly like `privileged`.
    #[serde(default, skip_serializing_if = "is_false")]
    pub private: bool,
    /// Never serialized to a client, with no unlock. Propagated from `FieldSpec::secret`
    /// (and set automatically for every `Masked<T>` field). Also not schema shape.
    #[serde(default, skip_serializing_if = "is_false")]
    pub secret: bool,
    /// For FK columns: whether to emit a physical `FOREIGN KEY ...
    /// REFERENCES` constraint. Propagated from `FieldSpec::db_constraint`.
    /// `false` (set via `#[umbral(db_constraint = false)]`) keeps the
    /// logical FK (column + `fk_target`) but renders no `REFERENCES`
    /// clause — the only valid shape for a cross-database FK. Closes
    /// gaps2 #22. Defaults to `true` so existing migration JSON
    /// round-trips unchanged (omitted from JSON when at its default).
    #[serde(default = "default_true", skip_serializing_if = "is_true")]
    pub db_constraint: bool,
    /// When `true`, this field appears on the edit form as read-only.
    /// Propagated from `FieldSpec::noedit`.
    #[serde(default)]
    pub noedit: bool,
    /// Display-string marker — propagated from
    /// `FieldSpec::is_string_repr`. The admin uses the first column
    /// with this flag as the default `list_display` label when no
    /// explicit one is configured.
    #[serde(default)]
    pub is_string_repr: bool,
    /// Display truncation cap — propagated from `FieldSpec::max_length`.
    /// `0` means no truncation.
    #[serde(default)]
    pub max_length: u32,
    /// Closed-set DB values for a choices column. Propagated from
    /// `FieldSpec::choices`. Non-empty when the model field carries
    /// `#[umbral(choices)]`; the migration engine emits a Postgres
    /// `CHECK (col IN (...))` constraint when this slice is non-empty.
    /// Empty for every non-choices column.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub choices: Vec<String>,
    /// Human labels matching `choices` position-for-position. Carried
    /// alongside `choices` so the admin's `<select>` widget has labels
    /// without the runtime needing to reflect on the model type.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub choice_labels: Vec<String>,
    /// SQL `DEFAULT` value — propagated from `FieldSpec::default`.
    /// Empty string means no default. The migration engine reads this
    /// at DDL-emit time for both `CREATE TABLE` and `ALTER TABLE ADD
    /// COLUMN`. Set via `#[umbral(default = "...")]` on the model field.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub default: String,
    /// Distinguishes a multi-valued [`MultiChoice<E>`] column from a
    /// single-valued choices column. Both share `ty: Text` plus the same
    /// `choices` / `choice_labels` metadata; this flag is the only
    /// signal that the value is a CSV. Empty / false for every other
    /// column.
    ///
    /// [`MultiChoice<E>`]: crate::orm::MultiChoice
    #[serde(default, skip_serializing_if = "is_false")]
    pub is_multichoice: bool,

    /// Carries `FieldSpec::unique` into the migration snapshot. The
    /// DDL builders emit a `UNIQUE` clause on this column at
    /// `CREATE TABLE` time when set. Default `false` keeps existing
    /// migration JSON files round-tripping unchanged (the field is
    /// omitted on serialise when default).
    #[serde(default, skip_serializing_if = "is_false")]
    pub unique: bool,

    /// Carries `FieldSpec::on_delete` into the migration snapshot.
    /// FK columns only — the DDL builders emit
    /// `ON DELETE <action>` when this is anything other than
    /// `NoAction`. Default `NoAction` is omitted from JSON so
    /// existing migration files round-trip without churn.
    #[serde(default, skip_serializing_if = "is_no_action")]
    pub on_delete: crate::orm::FkAction,

    /// Carries `FieldSpec::on_update` into the migration snapshot.
    /// Same shape as `on_delete`; emits `ON UPDATE <action>`.
    #[serde(default, skip_serializing_if = "is_no_action")]
    pub on_update: crate::orm::FkAction,

    /// Carries `FieldSpec::index` into the migration snapshot. The
    /// CreateTable + AddColumn render paths emit a matching
    /// `CREATE INDEX idx_<table>_<col>` for every column whose
    /// flag is set. Default `false` keeps existing migration JSON
    /// round-tripping unchanged.
    #[serde(default, skip_serializing_if = "is_false")]
    pub index: bool,

    /// Carries `FieldSpec::auto_now_add` into the migration
    /// snapshot. The dynamic write path (`DynQuerySet::insert_json`)
    /// auto-populates the column with `Utc::now()` when the body
    /// omits it. Default `false` so existing migration JSON
    /// round-trips unchanged.
    #[serde(default, skip_serializing_if = "is_false")]
    pub auto_now_add: bool,
    /// Carries `FieldSpec::auto_user_add` to the runtime (dyn) write path, so
    /// admin and REST stamp the author too — they run on `DynQuerySet`, not the
    /// typed one. Not a schema property: skipped in snapshots.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub auto_user_add: bool,
    /// Carries `FieldSpec::auto_user`.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub auto_user: bool,

    /// Carries `FieldSpec::auto_now` into the migration snapshot.
    /// Same shape as `auto_now_add` but fires on update too.
    #[serde(default, skip_serializing_if = "is_false")]
    pub auto_now: bool,

    /// Carries `FieldSpec::auto_uuid` to the runtime write paths, which
    /// generate a fresh `Uuid::new_v4()` when the column is omitted/nil on
    /// create. A write-behaviour, not a schema property, so it's skipped in
    /// snapshots (like `auto_user_add`).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub auto_uuid: bool,

    /// Carries `FieldSpec::trim` into the snapshot. Behavioral (dynamic write
    /// path strips surrounding whitespace), not schema-affecting — excluded
    /// from the schema diff like `auto_now`. Default `false` so existing
    /// migration JSON round-trips unchanged.
    #[serde(default, skip_serializing_if = "is_false")]
    pub trim: bool,

    /// Carries `FieldSpec::lowercase` into the snapshot. Behavioral (dynamic
    /// write path lowercases the value), not schema-affecting. Default `false`
    /// so existing migration JSON round-trips unchanged.
    #[serde(default, skip_serializing_if = "is_false")]
    pub lowercase: bool,

    /// Carries `FieldSpec::case_insensitive` into the snapshot. Schema-affecting
    /// (Postgres `citext` / SQLite `COLLATE NOCASE`), but — like `unique` — the
    /// diff comparator (`column_shape`) does NOT watch it, so it applies at
    /// CREATE TABLE and toggling it on a live column needs a hand-written
    /// migration. Default `false` so existing migration JSON round-trips.
    #[serde(default, skip_serializing_if = "is_false")]
    pub case_insensitive: bool,

    /// Carries `FieldSpec::help` into the migration snapshot.
    /// Default empty string is omitted from JSON so existing
    /// migration files round-trip unchanged.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub help: String,

    /// Carries `FieldSpec::example` into the migration snapshot.
    /// Same shape as `help`.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub example: String,

    /// Carries `FieldSpec::widget` into the migration snapshot — the
    /// form-renderer presentation hint (features.md #4). Presentation
    /// only, no DB effect, so it's excluded from the schema diff the
    /// same way `help` / `example` are. `None` is omitted from JSON so
    /// existing migration files round-trip unchanged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub widget: Option<String>,

    /// Carries `FieldSpec::supported_backends` into the migration
    /// snapshot. When non-empty, the boot system check rejects the
    /// model on any backend not listed. Closes IMP-5 from
    /// `bugs/tests/testBugs.md`. Default empty (works on every
    /// backend); JSON skip-when-empty so existing migration files
    /// don't churn.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub supported_backends: Vec<String>,

    /// IMP-3: numeric lower bound. `None` means "no minimum"; the
    /// DDL emits a `CHECK (col >= N)` constraint when set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min: Option<i64>,

    /// IMP-3: numeric upper bound. Same shape as `min`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max: Option<i64>,

    /// BUG-11/12/13: constrained-text marker. `None` is plain text;
    /// `Some("slug" | "email" | "url")` flags the column as a
    /// `Slug` / `Email` / `Url` wrapper. OpenAPI emits the
    /// corresponding `format` / `pattern`; the REST plugin
    /// pre-validates the body via `validate_text_format`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub text_format: Option<String>,

    /// Gap 109: auto-derive source. When `Some("title")`, the slug is
    /// computed from the row's `title` column at write time if the
    /// slug column itself is empty / missing on the body. Pure
    /// runtime behaviour — has no DDL effect, so the diff engine
    /// ignores changes to this field. `#[serde(default)]` keeps
    /// older snapshots round-tripping.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub slug_from: Option<String>,
}

fn is_no_action(a: &crate::orm::FkAction) -> bool {
    matches!(a, crate::orm::FkAction::NoAction)
}

/// Postgres `COMMENT ON COLUMN` for one column (gaps3 #43).
///
/// An empty `comment` renders `IS NULL`, which is Postgres's "this column has no
/// comment" — distinct from `IS ''`, an empty comment that `\d+` would print as
/// a blank line.
///
/// Help text is prose, and prose has apostrophes, so the literal is escaped by
/// doubling single quotes. The value originates in a `#[umbral(help = "...")]`
/// attribute (a compile-time literal, not user input), but a migration file is
/// hand-editable and an unescaped quote would produce a syntax error at apply
/// time rather than a diagnostic at generate time.
fn comment_on_column_stmt(table: &str, column: &str, comment: &str) -> String {
    let t = table.replace('"', "\"\"");
    let c = column.replace('"', "\"\"");
    if comment.is_empty() {
        return format!("COMMENT ON COLUMN \"{t}\".\"{c}\" IS NULL");
    }
    let body = comment.replace('\'', "''");
    format!("COMMENT ON COLUMN \"{t}\".\"{c}\" IS '{body}'")
}

/// Build a portable `CREATE INDEX IF NOT EXISTS idx_<table>_<col>
/// ON "<table>" ("<col>")` statement. Same DDL on SQLite and
/// Postgres — both accept `CREATE INDEX IF NOT EXISTS` and the
/// `idx_<table>_<col>` name convention is unique enough that the
/// migration engine can re-emit it idempotently on subsequent
/// applies. Used by [`render_operation_sqlite`] / `_postgres`
/// after a `CreateTable` or `AddColumn` op whose column carries
/// the `#[umbral(index)]` flag. Closes BUG-4.
fn create_index_stmt(table: &str, column: &str) -> String {
    let t = table.replace('"', "\"\"");
    let c = column.replace('"', "\"\"");
    format!(
        "CREATE INDEX IF NOT EXISTS \"idx_{table}_{column}\" ON \"{t}\" (\"{c}\")",
        table = table.replace('"', ""),
        column = column.replace('"', ""),
    )
}

/// `CREATE UNIQUE INDEX` for a column. Used when a new `#[umbral(unique)]`
/// column is ADDed on SQLite: SQLite rejects `ALTER TABLE ADD COLUMN …
/// UNIQUE` outright, so the uniqueness is applied as a separate unique
/// index instead (semantically identical, and it applies cleanly).
fn create_unique_index_stmt(table: &str, column: &str) -> String {
    let t = table.replace('"', "\"\"");
    let c = column.replace('"', "\"\"");
    format!(
        "CREATE UNIQUE INDEX IF NOT EXISTS \"uniq_{table}_{column}\" ON \"{t}\" (\"{c}\")",
        table = table.replace('"', ""),
        column = column.replace('"', ""),
    )
}

/// Build a Postgres `CREATE INDEX ... USING GIN` for a `tsvector`
/// (`SqlType::FullText`) column (#33). A tsvector column is useless for
/// search without a GIN index, so the migration engine emits one
/// automatically for every full-text column — the caller never has to
/// hand-write it. **Postgres-only**: GIN is Postgres syntax and FullText
/// columns are system-check-gated to Postgres, so this only ever renders
/// from `render_operation_postgres`. The `_gin` name suffix keeps it
/// distinct from any plain index on the same column.
fn create_gin_index_stmt(table: &str, column: &str) -> String {
    let t = table.replace('"', "\"\"");
    let c = column.replace('"', "\"\"");
    format!(
        "CREATE INDEX IF NOT EXISTS \"idx_{table}_{column}_gin\" ON \"{t}\" USING GIN (\"{c}\")",
        table = table.replace('"', ""),
        column = column.replace('"', ""),
    )
}

/// Build a Postgres `CREATE INDEX ... USING GIST` for a PostGIS spatial
/// (`SqlType::Geometry` / `SqlType::Geography`) column. Spatial predicates
/// (`ST_DWithin`, `&&`, …) are only index-accelerated by a GiST index; a plain
/// B-tree does nothing for them. So an `#[umbral(index)]` on a geometry column
/// emits GiST rather than the default B-tree. **Postgres-only** — spatial
/// columns are system-check-gated to Postgres, so this only renders from
/// `render_operation_postgres`.
fn create_gist_index_stmt(table: &str, column: &str) -> String {
    let t = table.replace('"', "\"\"");
    let c = column.replace('"', "\"\"");
    format!(
        "CREATE INDEX IF NOT EXISTS \"idx_{table}_{column}_gist\" ON \"{t}\" USING GIST (\"{c}\")",
        table = table.replace('"', ""),
        column = column.replace('"', ""),
    )
}

/// Multi-column variant of [`create_index_stmt`]. Closes BUG-7.
/// Renders `CREATE INDEX IF NOT EXISTS idx_<table>_<col1>_<col2>
/// ON "<table>" ("<col1>", "<col2>")`. Both backends accept the
/// same form. Empty groups render no statement (defensive — the
/// macro layer rejects them before the engine sees them, but the
/// helper still returns a no-op SQL string to keep the caller
/// simple).
fn create_multi_index_stmt(table: &str, columns: &[String]) -> String {
    // A plain composite index IS an `AddIndex { unique: false }` render —
    // delegate so the NAME (`idx_<table>_<cols>`) is defined in exactly one
    // place and a `CreateTable`'s composite index and a later `DropIndex`
    // always agree on it.
    add_index_stmt(table, columns, false)
}

/// Deterministic name for a composite index. `unique` selects the `uniq_`
/// prefix (a `unique_together` group), otherwise `idx_`. Derived purely
/// from the quote-stripped table + column list so an [`Operation::AddIndex`]
/// and the later [`Operation::DropIndex`] that reverses it always compute
/// the same name. The `uniq_`/`idx_` split means a UNIQUE and a plain index
/// on the SAME columns never collide.
fn index_name(table: &str, columns: &[String], unique: bool) -> String {
    let t = table.replace('"', "");
    let suffix = columns
        .iter()
        .map(|c| c.replace('"', ""))
        .collect::<Vec<_>>()
        .join("_");
    let prefix = if unique { "uniq" } else { "idx" };
    format!("{prefix}_{t}_{suffix}")
}

/// `CREATE [UNIQUE] INDEX IF NOT EXISTS "<name>" ON "<table>" (cols)` —
/// identical syntax on SQLite and Postgres. The index NAME is a bare
/// identifier (via [`index_name`]); the ON-clause table reference is a
/// *quoted* identifier with inner quotes doubled. An empty column list
/// renders an empty string (defensive no-op; the macro layer rejects
/// empty groups upstream).
fn add_index_stmt(table: &str, columns: &[String], unique: bool) -> String {
    if columns.is_empty() {
        return String::new();
    }
    let name = index_name(table, columns, unique);
    let t_esc = table.replace('"', "\"\"");
    let col_list = columns
        .iter()
        .map(|c| format!("\"{}\"", c.replace('"', "\"\"")))
        .collect::<Vec<_>>()
        .join(", ");
    let unique_kw = if unique { "UNIQUE " } else { "" };
    format!("CREATE {unique_kw}INDEX IF NOT EXISTS \"{name}\" ON \"{t_esc}\" ({col_list})")
}

/// `DROP INDEX IF EXISTS "<name>"` — same on both backends. Postgres
/// resolves the unqualified name via the search_path (so a schema-per-tenant
/// migrate drops the index inside the active schema).
fn drop_index_stmt(name: &str) -> String {
    let n = name.replace('"', "\"\"");
    format!("DROP INDEX IF EXISTS \"{n}\"")
}

/// Lower an M2M junction column's PK type into the SQLite column
/// declaration string used inside the raw `CREATE TABLE` template.
/// SQLite has affinity types: every integer width stores as `INTEGER`
/// (one ROWID-aliased column), and TEXT covers `String` / `Uuid`.
/// Closes BUG-16 phase 2.
fn m2m_pk_sql_type_sqlite(ty: crate::orm::SqlType) -> &'static str {
    use crate::orm::SqlType;
    match ty {
        SqlType::SmallInt | SqlType::Integer | SqlType::BigInt | SqlType::ForeignKey => "INTEGER",
        // A junction's `child_id` must be declared as whatever the CHILD's primary key
        // actually is, or the `REFERENCES` clause points at a column of a different type.
        // sqlx stores a `Uuid` as its 16 raw bytes on SQLite, so that is BLOB (gaps3 #80).
        SqlType::Uuid => "BLOB",
        SqlType::Text => "TEXT",
        // The macro-side classifier only sets these for PK columns
        // when the user wrote a non-standard PK type. If we ever
        // see one here that doesn't make sense as a junction column
        // (Boolean, Date, Real, …), TEXT is the safest catch-all
        // affinity — SQLite will accept it and the rest of the
        // ORM will surface the deeper "this can't be a PK" error
        // through the system check.
        _ => "TEXT",
    }
}

/// Lower an M2M junction column's PK type into the Postgres column
/// declaration string. Postgres is strict about types — `BIGINT` for
/// 64-bit integers, `INTEGER` for 32-bit, `SMALLINT` for 16-bit,
/// `TEXT` for `String`, `UUID` for `uuid::Uuid`. Mirrors the choices
/// `build_column_def_postgres` makes for the same `SqlType` variants.
fn m2m_pk_sql_type_postgres(ty: crate::orm::SqlType) -> &'static str {
    use crate::orm::SqlType;
    match ty {
        SqlType::SmallInt => "SMALLINT",
        SqlType::Integer => "INTEGER",
        SqlType::BigInt | SqlType::ForeignKey => "BIGINT",
        SqlType::Text => "TEXT",
        SqlType::Uuid => "UUID",
        _ => "TEXT",
    }
}

/// Build the ` ON DELETE <action> ON UPDATE <action>` suffix for a
/// FK column. Each half is emitted only when its action is anything
/// other than `NoAction` — keeps the generated DDL minimal and
/// matches the SQL standard's default (NO ACTION when the clause is
/// omitted).
///
/// Closes gap #68. Shared between the SQLite and Postgres builders
/// because the REFERENCES tail syntax is identical on both.
fn fk_action_suffix(col: &Column) -> String {
    let mut s = String::new();
    if let Some(kw) = col.on_delete.sql_keyword() {
        s.push_str(" ON DELETE ");
        s.push_str(kw);
    }
    if let Some(kw) = col.on_update.sql_keyword() {
        s.push_str(" ON UPDATE ");
        s.push_str(kw);
    }
    s
}

/// Suffix that makes a Postgres FK constraint `DEFERRABLE INITIALLY IMMEDIATE`:
/// checked per-statement by default (identical behaviour to a plain FK), but
/// allowing `SET CONSTRAINTS ALL DEFERRED` inside a transaction to hold the
/// check until commit. The data-transfer engine relies on this to load
/// mutually-referential (cyclic) tables on Postgres. SQLite needs no equivalent
/// — its `PRAGMA defer_foreign_keys` defers any FK regardless of declaration.
const PG_FK_DEFERRABLE: &str = " DEFERRABLE INITIALLY IMMEDIATE";

fn is_false(b: &bool) -> bool {
    !*b
}

/// serde default for `Column::db_constraint`: a FK emits its physical
/// `REFERENCES` constraint unless the model opts out. Older migration
/// JSON predating gaps2 #22 has no `db_constraint` key, so it must
/// deserialize as `true` to preserve the historical "always emit"
/// behaviour.
fn default_true() -> bool {
    true
}

fn is_true(b: &bool) -> bool {
    *b
}

impl From<&FieldSpec> for Column {
    fn from(f: &FieldSpec) -> Self {
        Self {
            name: f.name.to_string(),
            ty: f.ty,
            primary_key: f.primary_key,
            nullable: f.nullable,
            fk_target: f.fk_target.map(|s| s.to_string()),
            noform: f.noform,
            privileged: f.privileged,
            private: f.private,
            secret: f.secret,
            db_constraint: f.db_constraint,
            noedit: f.noedit,
            is_string_repr: f.is_string_repr,
            max_length: f.max_length,
            choices: f.choices.iter().map(|s| s.to_string()).collect(),
            choice_labels: f.choice_labels.iter().map(|s| s.to_string()).collect(),
            default: f.default.to_string(),
            is_multichoice: f.is_multichoice,
            unique: f.unique,
            on_delete: f.on_delete,
            on_update: f.on_update,
            index: f.index,
            auto_now_add: f.auto_now_add,
            auto_uuid: f.auto_uuid,
            auto_user_add: f.auto_user_add,
            auto_user: f.auto_user,
            auto_now: f.auto_now,
            trim: f.trim,
            lowercase: f.lowercase,
            case_insensitive: f.case_insensitive,
            help: f.help.to_string(),
            example: f.example.to_string(),
            widget: f.widget.map(|s| s.to_string()),
            supported_backends: f.supported_backends.iter().map(|s| s.to_string()).collect(),
            min: f.min,
            max: f.max,
            text_format: f.text_format.map(|s| s.to_string()),
            slug_from: f.slug_from.map(|s| s.to_string()),
        }
    }
}

/// The on-disk shape of one migration. Files in `migrations/<plugin>/`
/// deserialize into this struct.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MigrationFile {
    /// Stable id, matches the filename minus `.json`.
    pub id: String,
    /// The plugin that owns this migration. M5 hardcodes `"app"` for
    /// the user's binary; M7 generalises to one directory per plugin.
    pub plugin: String,
    /// Predecessor migrations, in `(plugin, id)` form. Within-plugin
    /// predecessors are implicit (the prior numeric file); cross-
    /// plugin predecessors land at M7.
    #[serde(default)]
    pub depends_on: Vec<MigrationRef>,
    /// Ordered operations applied when this migration runs.
    pub operations: Vec<Operation>,
    /// The full snapshot of every model after this migration has run.
    /// Source of truth for the next `make` to diff against.
    pub snapshot_after: Snapshot,
    /// gaps2 #100: when non-empty, this is a *squash* — it collapses the
    /// listed predecessor migrations into one optimized file. The originals
    /// are kept on disk (non-destructive) so older deploys still migrate; the
    /// runner treats the squash and its replaced set as mutually exclusive
    /// (see [`squash_plan`]). Empty for an ordinary migration; `#[serde(default)]`
    /// so every pre-squash file on disk deserializes unchanged.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub replaces: Vec<MigrationRef>,
}

/// A pointer to one (plugin, migration_id) pair.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MigrationRef {
    pub plugin: String,
    pub migration: String,
}

/// gaps2 #100 — what the runner does with one on-disk migration file, given the
/// tracking-table's applied-set. The decision is pure and backend-agnostic; the
/// only DB-specific step downstream is *how* a tracking row is written, never
/// *whether* the file's operations run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ApplyDecision {
    /// Run the file's operations, then record it in the tracking table. The
    /// normal "pending migration" path.
    Apply,
    /// Do nothing: the migration is already applied, or it's an original that a
    /// squash the runner is using has shadowed (running it too would
    /// double-apply the schema the squash already built).
    Skip,
    /// A squash whose entire replaced set is already applied. Its operations
    /// would rebuild schema that already exists, so DON'T run them — but insert
    /// a tracking row so future runs treat the squash as applied and the now
    /// redundant original files can be deleted.
    RecordOnly,
}

/// gaps2 #100 — decide, per on-disk migration file for ONE plugin, whether to
/// [`Apply`](ApplyDecision::Apply) / [`Skip`](ApplyDecision::Skip) /
/// [`RecordOnly`](ApplyDecision::RecordOnly) it, honoring squash `replaces`.
///
/// `files` is every migration file for the plugin (the returned Vec is in the
/// same order). `applied` is the `(plugin, id)` set from the tracking table.
/// The function is pure: no DB, no IO — so both the SQLite and Postgres apply
/// loops route through it and inherit identical squash semantics.
///
/// For a squash `S` replacing set `R`:
/// - **all of `R` applied** → `S` is `RecordOnly` (or `Skip` if `S` itself is
///   already recorded); every member of `R` is `Skip` (already applied).
/// - **none of `R` applied** → `S` is `Apply` (or `Skip` if already recorded);
///   every member of `R` is `Skip` (the squash builds their schema).
/// - **some of `R` applied** (an interrupted transition) → fall back to the
///   individual originals if they are ALL still on disk: `S` is `Skip` and each
///   unapplied member of `R` applies as usual. If any original is gone, the
///   history can't be reconciled → [`MigrateError::SquashInconsistent`].
///
/// A plain migration (empty `replaces`) is `Skip` if applied or shadowed by an
/// active squash, else `Apply`.
fn squash_plan(
    files: &[MigrationFile],
    applied: &std::collections::HashSet<(String, String)>,
) -> Result<Vec<ApplyDecision>, MigrateError> {
    use std::collections::HashSet;

    let is_applied =
        |plugin: &str, id: &str| applied.contains(&(plugin.to_string(), id.to_string()));
    let on_disk: HashSet<&str> = files.iter().map(|f| f.id.as_str()).collect();

    let mut decisions = vec![ApplyDecision::Apply; files.len()];
    // Ids covered by a squash the runner is USING (fully-applied or fully-
    // unapplied). Their originals must be skipped so they don't double-apply.
    let mut shadowed: HashSet<String> = HashSet::new();

    // First pass: classify every squash and collect the shadow set.
    for (i, f) in files.iter().enumerate() {
        if f.replaces.is_empty() {
            continue;
        }
        let applied_in_r = f
            .replaces
            .iter()
            .filter(|m| is_applied(&m.plugin, &m.migration))
            .count();
        let self_applied = is_applied(&f.plugin, &f.id);

        if applied_in_r == f.replaces.len() {
            // Whole history already applied: adopt the squash without running it.
            decisions[i] = if self_applied {
                ApplyDecision::Skip
            } else {
                ApplyDecision::RecordOnly
            };
            for m in &f.replaces {
                shadowed.insert(m.migration.clone());
            }
        } else if applied_in_r == 0 {
            // Fresh: the squash builds the whole schema in one shot.
            decisions[i] = if self_applied {
                ApplyDecision::Skip
            } else {
                ApplyDecision::Apply
            };
            for m in &f.replaces {
                shadowed.insert(m.migration.clone());
            }
        } else {
            // Partial transition: prefer the originals if they all survive.
            let missing: Vec<String> = f
                .replaces
                .iter()
                .filter(|m| !on_disk.contains(m.migration.as_str()))
                .map(|m| format!("{}/{}", m.plugin, m.migration))
                .collect();
            if missing.is_empty() {
                // Inactive squash: skip it, let the originals run individually.
                decisions[i] = ApplyDecision::Skip;
            } else {
                return Err(MigrateError::SquashInconsistent {
                    plugin: f.plugin.clone(),
                    squash: f.id.clone(),
                    missing,
                });
            }
        }
    }

    // Second pass: plain migrations (applied or shadowed → Skip, else Apply).
    for (i, f) in files.iter().enumerate() {
        if !f.replaces.is_empty() {
            continue;
        }
        if shadowed.contains(&f.id) || is_applied(&f.plugin, &f.id) {
            decisions[i] = ApplyDecision::Skip;
        }
    }

    // A squash can itself be shadowed by a larger squash (squash-of-squashes):
    // an active outer squash covers it, so it must not run either.
    for (i, f) in files.iter().enumerate() {
        if shadowed.contains(&f.id) {
            decisions[i] = ApplyDecision::Skip;
        }
    }

    Ok(decisions)
}

/// At M5 every migration belongs to a single placeholder plugin. M7's
/// Plugin contract replaces this with `Plugin::name()`.
pub const APP_PLUGIN_NAME: &str = "app";

/// Default directory for migration files. `make` writes into
/// `migrations/<plugin>/`; `run` reads from the same place. Override
/// with `--migrations-dir` once the CLI grows real arg parsing (M5+).
pub const MIGRATIONS_DIR: &str = "migrations";

/// The state of a single migration from the perspective of drift detection.
/// Returned inside [`DriftReport`] so callers can decide how to handle each
/// state independently.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MigrationStatus {
    /// The migration is recorded in the tracking table AND the file
    /// exists on disk. Normal applied state.
    Applied,
    /// The migration is recorded in the tracking table BUT the
    /// corresponding file is missing from disk. The database is ahead
    /// of what version control has; recovering requires restoring the
    /// file or running with `--allow-drift`.
    AppliedButMissing,
    /// The migration file exists on disk AND its sequence number is
    /// lower than the highest applied migration for this plugin, but it
    /// is not recorded in the tracking table. Looks like someone dropped
    /// a migration file back into a directory after a teammate already
    /// applied later ones. Should warn, not error.
    OutOfOrder,
    /// Normal pending state: the file is on disk and its sequence number
    /// is higher than anything applied. Ready to apply.
    Pending,
}

/// Per-migration entry inside a [`DriftReport`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MigrationEntry {
    pub plugin: String,
    pub name: String,
    pub status: MigrationStatus,
}

/// The output of [`detect_drift`]: one entry per migration (applied or
/// on-disk), categorised into the four states above.
///
/// The caller inspects `has_critical_drift()` to decide whether to abort
/// before applying migrations. Surfaced by `show_in_with_drift` for
/// `showmigrations` and checked by `run_in_with_drift_check` before
/// executing any SQL.
#[derive(Debug, Clone, Default)]
pub struct DriftReport {
    pub entries: Vec<MigrationEntry>,
}

impl DriftReport {
    /// Returns true when at least one migration is `AppliedButMissing`.
    /// This state means the tracking table references a file that no
    /// longer exists on disk — the operator needs to act before it is
    /// safe to continue applying new migrations.
    pub fn has_critical_drift(&self) -> bool {
        self.entries
            .iter()
            .any(|e| e.status == MigrationStatus::AppliedButMissing)
    }

    /// All migrations with `AppliedButMissing` status. Convenience
    /// accessor for building the error message.
    pub fn missing_on_disk(&self) -> Vec<&MigrationEntry> {
        self.entries
            .iter()
            .filter(|e| e.status == MigrationStatus::AppliedButMissing)
            .collect()
    }

    /// Migrations on disk this binary knows about that the database has NOT
    /// applied yet — the readiness blocker (Kikosi #5 / gaps3 #38). Empty means
    /// the schema is at least as new as this binary's code.
    ///
    /// Deliberately excludes `AppliedButMissing` (the database is *ahead*: a
    /// valid rollback / backward-compatible-migration state where an older
    /// binary should keep serving) and `OutOfOrder` (a stray file the migrate
    /// engine only warns about). Only `Pending` — "the schema is behind the
    /// code" — should hold traffic off a freshly-booted pod.
    pub fn pending(&self) -> Vec<&MigrationEntry> {
        self.entries
            .iter()
            .filter(|e| e.status == MigrationStatus::Pending)
            .collect()
    }
}

/// Errors the migration engine can produce.
#[derive(Debug)]
pub enum MigrateError {
    /// IO error reading or writing a migration file or directory.
    Io(std::io::Error),
    /// JSON parse error on a migration file.
    Json(serde_json::Error),
    /// sqlx error executing a migration's SQL or touching the
    /// tracking table.
    Sqlx(sqlx::Error),
    /// `make` ran but found no differences against the latest snapshot,
    /// so there's nothing to write. Surfaced so the CLI can print
    /// "no changes detected" instead of an empty migration file.
    NoChanges,
    /// The current models diverge from the snapshot in a way M5 v1
    /// can't represent yet (anything other than create/drop table).
    /// M5.1 lifts this when column-level ops land.
    UnsupportedChange(String),
    /// A column-level change the engine can't apply automatically:
    /// type change, or a nullable flip on a populated SQLite table.
    /// Surfaces from `diff` so the build stops before producing a
    /// migration that would lose data or fail to apply. The user
    /// resolves by hand-writing the migration with the appropriate
    /// data-preserving steps. Carries the model / column / reason.
    UnsafeAlter {
        model: String,
        column: String,
        reason: String,
    },
    /// The tracking table records migrations that no longer have
    /// corresponding files on disk. Carries the list of missing names.
    /// The operator must either restore the files from VCS or run with
    /// `--allow-drift` to proceed despite the inconsistency.
    DriftDetected { missing: Vec<(String, String)> },
    /// A schema-scoped migration ([`run_for_schema`]) was requested against a
    /// SQLite pool. SQLite has no schemas, so schema-per-tenant is Postgres-only
    /// (mirrors how `Inet`/`Cidr` gate on backend). Carries the schema name.
    SchemaUnsupportedOnSqlite { schema: String },
    /// `makemigrations --empty <plugin>` named a plugin that isn't
    /// registered. Carries the requested name and the registered set so
    /// the CLI can list the valid choices.
    UnknownPlugin {
        requested: String,
        known: Vec<String>,
    },
    /// audit_2 H23 — the column-shape rename heuristic found an unpaired
    /// dropped model and an unpaired created model with **identical** column
    /// shapes. That's genuinely ambiguous: it's either a model rename (move the
    /// old table's rows to the new name) or two unrelated models that happen to
    /// share a shape (drop the old, create the new empty). Auto-applying either
    /// silently loses or mis-associates data, so `diff` refuses to guess and
    /// fails closed. The operator resolves it explicitly via
    /// `UMBRAL_MIGRATIONS_ASSUME_RENAMES` (`assume` → rename, `independent` →
    /// drop+create) or by hand-writing the op. Carries the two table names.
    AmbiguousRename {
        from_table: String,
        to_table: String,
    },
    /// audit_2 core-migrate #7 — couldn't acquire the Postgres migration
    /// advisory lock within the timeout: another process has been holding it
    /// (running a long migration, or wedged). Carries the alias/schema the lock
    /// was keyed on and the seconds waited. The operator retries once the other
    /// migrator finishes, or investigates a stuck migration.
    MigrationLockTimeout {
        discriminator: String,
        waited_secs: u64,
    },
    /// gaps2 #100 — a squash migration is stuck in a partially-applied state:
    /// SOME of the migrations it replaces are recorded as applied and others
    /// aren't, and the unapplied originals are no longer on disk to fall back
    /// to. The engine can't safely apply the squash (it would re-run schema the
    /// applied originals already built) nor complete the originals (their files
    /// are gone). Carries the plugin and squash id. The operator restores the
    /// missing original files from VCS (finish the transition), or resets the
    /// tracking rows for this plugin to a consistent point.
    SquashInconsistent {
        plugin: String,
        squash: String,
        missing: Vec<String>,
    },
    /// gaps2 #100 — `squashmigrations <plugin>` couldn't produce a squash:
    /// fewer than two squashable migrations, an unknown plugin, or the history
    /// already contains a squash (nested squashing isn't supported yet). Carries
    /// the plugin and a human-readable reason.
    CannotSquash { plugin: String, reason: String },
}

impl std::fmt::Display for MigrateError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MigrateError::Io(e) => write!(f, "umbral migrate: io: {e}"),
            MigrateError::Json(e) => write!(f, "umbral migrate: json: {e}"),
            MigrateError::Sqlx(e) => write!(f, "umbral migrate: sqlx: {e}"),
            MigrateError::NoChanges => write!(
                f,
                "umbral migrate: no changes detected; declare or change a model first"
            ),
            MigrateError::UnsupportedChange(msg) => {
                write!(f, "umbral migrate: unsupported change at M5 v1: {msg}")
            }
            MigrateError::UnsafeAlter {
                model,
                column,
                reason,
            } => write!(
                f,
                "umbral migrate: unsafe column change on `{model}.{column}`: {reason}; \
                 hand-write the migration with a data-preserving step"
            ),
            MigrateError::DriftDetected { missing } => {
                let names: Vec<String> = missing
                    .iter()
                    .map(|(plugin, name)| format!("{plugin}/{name}"))
                    .collect();
                write!(
                    f,
                    "umbral migrate: drift detected — the following migrations are recorded in \
                     the tracking table but their files are missing from disk:\n  {}\n\
                     Restore the files from VCS or run `umbral migrate --allow-drift` to \
                     proceed despite the inconsistency.",
                    names.join("\n  ")
                )
            }
            MigrateError::SchemaUnsupportedOnSqlite { schema } => write!(
                f,
                "umbral migrate: schema-per-tenant migration into `{schema}` requires \
                 Postgres; SQLite has no schemas. Point the app at a Postgres pool."
            ),
            MigrateError::UnknownPlugin { requested, known } => write!(
                f,
                "umbral makemigrations --empty: no registered plugin named `{requested}`. \
                 Known plugins: {}",
                known.join(", ")
            ),
            MigrateError::AmbiguousRename {
                from_table,
                to_table,
            } => write!(
                f,
                "umbral makemigrations: ambiguous rename — the dropped model `{from_table}` and \
                 the new model `{to_table}` have identical column shapes, so this is either a \
                 rename (move `{from_table}`'s rows to `{to_table}`) or two unrelated models. \
                 Refusing to guess: auto-renaming would hand one model's rows to another and skip \
                 the intended drop, while auto-dropping would delete `{from_table}`'s rows — both \
                 silent data bugs. Resolve it: set UMBRAL_MIGRATIONS_ASSUME_RENAMES=assume to \
                 treat every shape match as a rename, or =independent to treat them as unrelated \
                 (drop + create), or hand-write the intended op into the migration file."
            ),
            MigrateError::MigrationLockTimeout {
                discriminator,
                waited_secs,
            } => write!(
                f,
                "umbral migrate: timed out after {waited_secs}s waiting for the Postgres \
                 migration lock (alias/schema `{discriminator}`). Another process is holding it — \
                 a long-running migration on another replica, or a wedged migrator. Retry once it \
                 finishes; if nothing is migrating, check for a stuck backend holding \
                 pg_advisory_lock."
            ),
            MigrateError::SquashInconsistent {
                plugin,
                squash,
                missing,
            } => write!(
                f,
                "umbral migrate: squash `{plugin}/{squash}` is half-applied — some of the \
                 migrations it replaces are recorded as applied and the unapplied ones are \
                 missing from disk:\n  {}\nRestore those original migration files from VCS so \
                 the transition can finish, then re-run migrate.",
                missing.join("\n  ")
            ),
            MigrateError::CannotSquash { plugin, reason } => write!(
                f,
                "umbral squashmigrations: can't squash `{plugin}`: {reason}"
            ),
        }
    }
}

impl std::error::Error for MigrateError {}

impl From<std::io::Error> for MigrateError {
    fn from(e: std::io::Error) -> Self {
        Self::Io(e)
    }
}

impl From<serde_json::Error> for MigrateError {
    fn from(e: serde_json::Error) -> Self {
        Self::Json(e)
    }
}

impl From<sqlx::Error> for MigrateError {
    fn from(e: sqlx::Error) -> Self {
        Self::Sqlx(e)
    }
}

// =========================================================================
// Top-level entry points.
// =========================================================================

/// Generate one migration file per registered plugin that has changes,
/// diffing each plugin's current model set against the latest snapshot
/// in `migrations/<plugin>/`. Each new file lands inside its own
/// plugin directory with the next sequence number and a `_<short_name>`
/// suffix derived from the dominant operation.
///
/// Returns the paths of every file written, one per plugin that had a
/// non-empty diff. Returns `MigrateError::NoChanges` if no plugin
/// produced any changes at all.
pub async fn make() -> Result<Vec<PathBuf>, MigrateError> {
    make_in(Path::new(MIGRATIONS_DIR)).await
}

/// Same as [`make`] but takes an explicit base directory. Used by
/// tests to avoid touching the cwd.
///
/// Iterates [`plugin_order`], which is the topological order
/// published by `App::build()`'s phase 1.5 sort. Cross-plugin FKs
/// land in dependency order this way (a plugin's `CreateTable` for
/// the FK target runs before the dependent plugin's `CreateTable`).
/// Falls back to [`registered_plugins`] when no order has been
/// published (e.g. low-level tests that init the registry directly).
pub async fn make_in(dir: &Path) -> Result<Vec<PathBuf>, MigrateError> {
    let mut written: Vec<PathBuf> = Vec::new();

    for plugin in plugin_order() {
        let plugin_dir = dir.join(&plugin);

        // The previous snapshot is the `snapshot_after` of the highest-
        // numbered migration file (filenames are zero-padded so lexical
        // sort matches numeric order). An empty or missing directory
        // means "no prior state", the first-run case for this plugin.
        let existing = list_migration_files(&plugin_dir)?;
        let previous = match existing.last() {
            Some(path) => read_migration_file(path)?.snapshot_after,
            None => Snapshot::default(),
        };

        let current = Snapshot::current_for(&plugin);
        let operations = diff(&previous, &current)?;
        if operations.is_empty() {
            continue;
        }

        let seq = (existing.len() + 1) as u32;
        let suffix = suffix_for(&operations);
        let id = format!("{seq:04}_{suffix}");
        let filename = format!("{id}.json");

        let file = MigrationFile {
            id: id.clone(),
            plugin: plugin.clone(),
            depends_on: Vec::new(),
            operations,
            snapshot_after: current,
            replaces: Vec::new(),
        };

        std::fs::create_dir_all(&plugin_dir)?;
        let path = plugin_dir.join(filename);
        let json = serde_json::to_string_pretty(&file)?;
        std::fs::write(&path, json)?;
        written.push(path);
    }

    if written.is_empty() {
        return Err(MigrateError::NoChanges);
    }
    Ok(written)
}

/// Write an **empty** migration for one plugin: the current snapshot
/// with an empty `operations` list, the authoring stub for a
/// hand-written data migration (`Operation::RunSql`). The developer
/// opens the file and adds a `RunSql { sql, reverse_sql }` op.
///
/// The empty op-list means `snapshot_after == snapshot_before`, so the
/// next `make` diffs against the same state and produces nothing — a
/// data migration never disturbs the schema-snapshot chain. Mirror of
/// [`make`] for the `--empty <plugin>` CLI path.
pub async fn make_empty(plugin: &str) -> Result<PathBuf, MigrateError> {
    make_empty_in(Path::new(MIGRATIONS_DIR), plugin).await
}

/// Same as [`make_empty`] but takes an explicit base directory. The
/// seam tests drive.
pub async fn make_empty_in(dir: &Path, plugin: &str) -> Result<PathBuf, MigrateError> {
    // The plugin must be registered, else the snapshot/sequence would be
    // meaningless. Fail loudly with the known set.
    let known = plugin_order();
    if !known.iter().any(|p| p == plugin) {
        return Err(MigrateError::UnknownPlugin {
            requested: plugin.to_string(),
            known,
        });
    }

    let plugin_dir = dir.join(plugin);

    // Carry the latest snapshot forward verbatim: an empty migration has
    // NO schema effect, so `snapshot_after` equals the previous one. The
    // current model snapshot is the same as the prior file's
    // `snapshot_after` (no model changed); use the current registry state
    // so the file is self-consistent even on a plugin's very first
    // migration.
    let existing = list_migration_files(&plugin_dir)?;
    let snapshot = match existing.last() {
        Some(path) => read_migration_file(path)?.snapshot_after,
        None => Snapshot::current_for(plugin),
    };

    let seq = (existing.len() + 1) as u32;
    let id = format!("{seq:04}_empty");
    let filename = format!("{id}.json");

    let file = MigrationFile {
        id: id.clone(),
        plugin: plugin.to_string(),
        depends_on: Vec::new(),
        operations: Vec::new(),
        snapshot_after: snapshot,
        replaces: Vec::new(),
    };

    std::fs::create_dir_all(&plugin_dir)?;
    let path = plugin_dir.join(filename);
    let json = serde_json::to_string_pretty(&file)?;
    std::fs::write(&path, json)?;
    Ok(path)
}

/// The numeric sequence prefix of a migration id (`0003_add_x` → `0003`),
/// used to name a squash `0001_squashed_0003`.
fn seq_prefix(id: &str) -> &str {
    id.split('_').next().unwrap_or(id)
}

/// Outcome of [`squash_in`]: where the squash landed and what it collapsed.
pub struct SquashOutcome {
    /// Path of the written squash file.
    pub path: PathBuf,
    /// Id of the new squash migration (e.g. `0001_squashed_0005`).
    pub id: String,
    /// Ids of the original migrations it replaces — kept on disk, non-destructive.
    pub replaced: Vec<String>,
}

/// gaps2 #100 — collapse a plugin's entire linear migration history into ONE
/// optimized squash file, **non-destructively**: the originals stay on disk so
/// older deploys still migrate, and the runner ([`squash_plan`]) treats the
/// squash and its originals as mutually exclusive.
///
/// The squash's operations are the diff from an empty schema to the last
/// migration's `snapshot_after` — i.e. one `CreateTable` per model with every
/// intermediate `AlterColumn` already folded into the final column set. That's
/// the minimal replay of the whole history, which is the entire point (a 20-file
/// history with repeated alters collapses to N clean creates).
///
/// Refuses (with [`MigrateError::CannotSquash`]) when it can't produce a safe
/// squash: fewer than two migrations, a history that already contains a squash
/// (nested squashing is out of scope), or a history containing a `RunSql` data
/// migration — a snapshot diff can't see hand-written data steps, so squashing
/// across one would silently drop it. The operator squashes the schema-only
/// prefix, or leaves that history intact.
pub fn squash_in(dir: &Path, plugin: &str) -> Result<SquashOutcome, MigrateError> {
    let plugin_dir = dir.join(plugin);
    let paths = list_migration_files(&plugin_dir)?;
    let files: Vec<MigrationFile> = paths
        .iter()
        .map(|p| read_migration_file(p))
        .collect::<Result<_, _>>()?;

    if files.len() < 2 {
        return Err(MigrateError::CannotSquash {
            plugin: plugin.to_string(),
            reason: format!(
                "need at least 2 migrations to squash, found {}",
                files.len()
            ),
        });
    }
    if files.iter().any(|f| !f.replaces.is_empty()) {
        return Err(MigrateError::CannotSquash {
            plugin: plugin.to_string(),
            reason: "this history already contains a squash; nested squashing isn't supported \
                     yet. Delete the now-redundant original files once every deploy has migrated, \
                     then squash again"
                .to_string(),
        });
    }
    if files.iter().any(|f| {
        f.operations
            .iter()
            .any(|op| matches!(op, Operation::RunSql { .. }))
    }) {
        return Err(MigrateError::CannotSquash {
            plugin: plugin.to_string(),
            reason: "this history contains a RunSql data migration, which a snapshot diff can't \
                     reconstruct — squashing across it would silently drop the data step. Squash \
                     the schema-only migrations before/after it, or leave this history intact"
                .to_string(),
        });
    }

    let first = &files[0];
    let last = files.last().expect("len >= 2 checked above");

    // Optimal from-scratch replay: empty schema → final snapshot. Every
    // intermediate alter is already baked into `snapshot_after`.
    let empty = Snapshot { models: Vec::new() };
    let operations = diff(&empty, &last.snapshot_after)?;

    let id = format!(
        "{}_squashed_{}",
        seq_prefix(&first.id),
        seq_prefix(&last.id)
    );
    let replaced: Vec<String> = files.iter().map(|f| f.id.clone()).collect();
    let squash = MigrationFile {
        id: id.clone(),
        plugin: plugin.to_string(),
        // Preserve the first migration's cross-plugin predecessors: the squash
        // stands in for the whole run, so it inherits the run's external deps.
        depends_on: first.depends_on.clone(),
        operations,
        snapshot_after: last.snapshot_after.clone(),
        replaces: replaced
            .iter()
            .map(|mid| MigrationRef {
                plugin: plugin.to_string(),
                migration: mid.clone(),
            })
            .collect(),
    };

    let path = plugin_dir.join(format!("{id}.json"));
    let json = serde_json::to_string_pretty(&squash)?;
    std::fs::write(&path, json)?;
    Ok(SquashOutcome { path, id, replaced })
}

/// Create a table for every registered model, deriving the schema from the
/// models themselves. **For tests.**
///
/// This is the migration engine pointed at an empty database: diff `Snapshot`
/// nothing against [`Snapshot::current`], render the resulting `CreateTable`
/// operations for the ambient backend, and run them. Same `ModelMeta` the ORM
/// reads, same renderer [`run`] uses — so the schema it produces cannot
/// disagree with your models.
///
/// # Why this exists
///
/// The alternative, and what most test suites reach for, is a hand-written
/// `CREATE TABLE` in the test file. That is a **second source of truth** for the
/// schema, and it drifts: add a column to the model and the test's table
/// silently lacks it. The ORM then queries a column that does not exist, and any
/// error-swallowing on the path (an `unwrap_or(false)`) turns that failure into a
/// test that *passes with the wrong answer* rather than failing. That is not a
/// hypothetical — a soft-delete column drifting out of a fixture is exactly what
/// made an authorization test report that a user was already a moderator when
/// they were not.
///
/// # Not a substitute for `migrate`
///
/// It writes no ledger row and runs no migration file. It cannot ALTER an
/// existing table, so it will not carry a database from one shape to another —
/// which is the entire job of [`run`] and the reason `makemigrations` exists.
/// Point it at a throwaway database, never a real one.
///
/// Idempotent: an "already exists" error is skipped, so a shared test boot that
/// runs twice is harmless. Returns the number of statements executed.
pub async fn create_tables_for_tests() -> Result<u64, MigrateError> {
    create_tables_for_tests_on("default").await
}

/// [`create_tables_for_tests`], against a named database alias.
///
/// A read/write-split or multi-database test registers more than one pool
/// (`.database("default", ..).database("replica", ..)`) and needs the schema on
/// each of them — a replica with no tables is not a replica. The ambient-pool
/// variant only ever reaches `"default"`.
pub async fn create_tables_for_tests_on(alias: &str) -> Result<u64, MigrateError> {
    let ops = diff(&Snapshot { models: Vec::new() }, &Snapshot::current())?;
    let pool = crate::db::pool_for_dispatched(alias);
    let backend = match pool {
        crate::db::DbPool::Sqlite(_) => "sqlite",
        crate::db::DbPool::Postgres(_) => "postgres",
    };

    let mut executed = 0u64;
    for op in &ops {
        for sql in render_operation_for(op, backend) {
            let res = match crate::db::pool_for_dispatched(alias) {
                crate::db::DbPool::Sqlite(p) => sqlx::query(&sql).execute(p).await.map(|_| ()),
                crate::db::DbPool::Postgres(p) => sqlx::query(&sql).execute(p).await.map(|_| ()),
            };
            match res {
                Ok(()) => executed += 1,
                // A shared `OnceCell` boot may land here twice; a test that dies
                // on its own setup is worse than useless.
                Err(e) if e.to_string().to_lowercase().contains("already exists") => {}
                Err(e) => return Err(MigrateError::Sqlx(e)),
            }
        }
    }
    Ok(executed)
}

/// Apply every pending migration across every registered plugin's
/// `migrations/<plugin>/` directory to the ambient pool. Reads the
/// `umbral_migrations` tracking table to determine "pending"; each
/// migration runs in its own transaction along with its tracking-table
/// insert.
///
/// Returns the total number of migrations applied (zero if every
/// plugin's migrations were already in the tracking table).
///
/// This variant performs a drift check before executing any SQL. If
/// any migration is `AppliedButMissing` (in the DB but not on disk),
/// the call returns [`MigrateError::DriftDetected`] listing the
/// missing names. Pass `allow_drift = true` (via [`run_checked_in`])
/// to suppress the error and proceed anyway (with a warning printed to
/// stderr).
pub async fn run() -> Result<u64, MigrateError> {
    run_checked(false).await
}

/// Same as [`run`] but controls drift handling.
/// `allow_drift = true` corresponds to the `--allow-drift` CLI flag:
/// the command logs a warning and proceeds even if some applied
/// migrations are missing on disk.
pub async fn run_checked(allow_drift: bool) -> Result<u64, MigrateError> {
    run_checked_in(Path::new(MIGRATIONS_DIR), allow_drift).await
}

/// Same as [`run_checked`] but takes an explicit base directory.
pub async fn run_checked_in(dir: &Path, allow_drift: bool) -> Result<u64, MigrateError> {
    let mut total: u64 = 0;
    // Walk every registered DB. Drift-detection on the default pool
    // is the dominant flow; secondary pools currently use the same
    // tracking-table-vs-disk comparison but only against the
    // migration files whose ops actually targeted that DB. A future
    // pass can teach `detect_all_drift` to be alias-aware so drift
    // warnings name the offending pool — today it warns once per
    // checked DB if the issue is present in any.
    for alias in crate::db::registered_aliases() {
        match crate::db::pool_for_dispatched(&alias) {
            crate::db::DbPool::Sqlite(p) => {
                total += run_in_sqlite_checked(dir, p, allow_drift, &alias).await?
            }
            crate::db::DbPool::Postgres(p) => {
                total += run_in_postgres_checked(dir, p, allow_drift, &alias).await?
            }
        }
    }
    Ok(total)
}

/// Same as [`run`] but takes an explicit base directory. Used by
/// tests to avoid touching the cwd.
///
/// Iterates `registered_plugins()` in sorted-by-name order. M7 v1
/// accepts this as a limitation: cross-plugin FK ordering wants
/// topological order across plugins (the FK target's `CreateTable`
/// applies before the dependent plugin's `CreateTable`), but the
/// engine doesn't see `Plugin::dependencies()` from inside this
/// standalone function. M8 lifts the limitation via a registry that
/// remembers the toposorted order computed at `App::build()` time.
///
/// This legacy entry point does NOT perform drift checking so the
/// existing tests (which bypass drift by design) keep passing. New
/// callers should prefer [`run_checked_in`].
pub async fn run_in(dir: &Path) -> Result<u64, MigrateError> {
    let mut total: u64 = 0;
    // Walk every registered DB so each pool gets its own
    // `umbral_migrations` table and runs only the operations targeting
    // tables routed to it. Order is alphabetical for determinism;
    // the "default" pool is always present.
    for alias in crate::db::registered_aliases() {
        match crate::db::pool_for_dispatched(&alias) {
            crate::db::DbPool::Sqlite(p) => {
                total += run_in_sqlite_for_alias(dir, &alias, p, None).await?
            }
            crate::db::DbPool::Postgres(p) => {
                total += run_in_postgres_for_alias(dir, &alias, p, None).await?
            }
        }
    }
    Ok(total)
}

/// Apply only the **SHARED** apps' pending migrations to the default pool —
/// the `public`/shared half of schema-per-tenant multitenancy. This is the
/// mirror of [`run_for_schema_in`] (which migrates the *tenant* apps into a
/// tenant schema): here only plugins IN `shared_apps` migrate into `public`,
/// so a tenant app's tables — and crucially its M2M junctions — are NEVER
/// created in `public`. They live only in each tenant schema, where a junction's
/// FK to a SHARED child resolves via the `<schema>, public` search-path.
///
/// Use this instead of the unfiltered [`run`]/[`run_in`] when running a
/// schema-per-tenant app: `run_shared` (shared → public) then `migrate_schemas`
/// (tenant apps → each schema). On a non-multitenant app the two are equivalent
/// only if every app is shared; otherwise prefer plain [`run`].
pub async fn run_shared(
    shared_apps: &std::collections::HashSet<String>,
) -> Result<u64, MigrateError> {
    run_shared_in(Path::new(MIGRATIONS_DIR), shared_apps).await
}

/// [`run_shared`] against an explicit migrations directory (tests / tooling).
pub async fn run_shared_in(
    dir: &Path,
    shared_apps: &std::collections::HashSet<String>,
) -> Result<u64, MigrateError> {
    let mut total: u64 = 0;
    for alias in crate::db::registered_aliases() {
        match crate::db::pool_for_dispatched(&alias) {
            crate::db::DbPool::Sqlite(p) => {
                total += run_in_sqlite_for_alias(dir, &alias, p, Some(shared_apps)).await?
            }
            crate::db::DbPool::Postgres(p) => {
                total += run_in_postgres_for_alias(dir, &alias, p, Some(shared_apps)).await?
            }
        }
    }
    Ok(total)
}

/// Predicate: does `op` target a table that lives on `alias`?
///
/// Routing rule: look up the table → alias mapping via
/// [`table_alias`]. Tables not owned by any registered model fall
/// through to `"default"` so the migration engine's own
/// `umbral_migrations` book-keeping stays in the main DB.
///
/// A second gate consults the installed [`DatabaseRouter`]: if the
/// router's [`allow_migrate`](crate::db::DatabaseRouter::allow_migrate)
/// returns `false` for this (alias, model) pair the operation is
/// excluded from the alias's run. Junction / unowned tables (no
/// registered `ModelMeta`) are always allowed — the router has no
/// model to inspect.
fn op_targets_alias(op: &Operation, alias: &str) -> bool {
    if table_alias(op.table_name()) != alias {
        return false;
    }
    // Let the router veto migrating this table on this alias.
    match model_meta_for_table(op.table_name()) {
        Some(meta) => crate::db::router::router().allow_migrate(alias, &meta),
        None => true, // junction / unowned table — migrate on its alias
    }
}

/// SQLite per-alias variant. Same shape as the legacy `run_in_sqlite`
/// but: filters ops to those routed to `alias`; skips files whose op
/// list contains nothing for this DB (so we don't stuff orphan
/// tracking rows into pools that didn't run any SQL).
async fn run_in_sqlite_for_alias(
    dir: &Path,
    alias: &str,
    pool: &sqlx::SqlitePool,
    shared_only: Option<&std::collections::HashSet<String>>,
) -> Result<u64, MigrateError> {
    ensure_tracking_table_sqlite(pool).await?;
    let applied = applied_names_sqlite(pool).await?;

    let mut applied_count: u64 = 0;
    for plugin in plugin_order() {
        if let Some(shared) = shared_only {
            if !shared.contains(&plugin) {
                continue;
            }
        }
        let plugin_dir = dir.join(&plugin);
        let paths = list_migration_files(&plugin_dir)?;

        // Read the plugin's full file set, then plan squash decisions in one
        // pass (gaps2 #100). `squash_plan` decides Apply / Skip / RecordOnly per
        // file, honoring `replaces` so a squash and its originals never both
        // apply. Pure and backend-agnostic — the Postgres runner plans the same.
        let files: Vec<MigrationFile> = paths
            .iter()
            .map(|p| read_migration_file(p))
            .collect::<Result<_, _>>()?;
        let plan = squash_plan(&files, &applied)?;

        for (file, decision) in files.iter().zip(plan) {
            if decision == ApplyDecision::Skip {
                continue;
            }

            let ops_for_this_db: Vec<&Operation> = file
                .operations
                .iter()
                .filter(|op| op_targets_alias(op, alias))
                .collect();
            if ops_for_this_db.is_empty() {
                // File's content all targets some other DB. Don't
                // record it here — re-runs will re-evaluate cleanly
                // once the right DB picks it up. The tracking rows
                // per-DB stay accurate to "what actually ran here."
                continue;
            }

            let snapshot_hash = file.snapshot_after.hash();
            let applied_at = chrono::Utc::now().to_rfc3339();
            // RecordOnly: the squash's replaced set is already applied, so its
            // schema exists — insert the tracking row without running any ops
            // (an empty op slice inserts the row and commits).
            let ops_to_run: &[&Operation] = if decision == ApplyDecision::RecordOnly {
                &[]
            } else {
                &ops_for_this_db
            };
            apply_sqlite_migration_tx(
                pool,
                ops_to_run,
                &file.plugin,
                &file.id,
                &applied_at,
                &snapshot_hash,
            )
            .await?;
            applied_count += 1;
        }
    }
    Ok(applied_count)
}

/// Apply one migration file's SQLite `ops` in a single transaction, then record
/// it in the tracking table.
///
/// When any op is an `AlterColumn` (the table-recreation dance), the
/// transaction is bracketed with `PRAGMA foreign_keys=OFF` … `PRAGMA
/// foreign_key_check` … `PRAGMA foreign_keys=ON` on a **pinned** connection
/// (SQLite's official recipe), so step 3's `DROP TABLE` on a table with inbound
/// FKs doesn't fail with `FOREIGN KEY constraint failed` (error 787, gaps3
/// #13). The pragma MUST be toggled outside the tx (it's a no-op inside one),
/// and enforcement is restored even on failure so the pooled connection never
/// returns with FK checks disabled. `foreign_key_check` before commit keeps the
/// integrity guarantee: a migration that genuinely orphans a row is aborted.
async fn apply_sqlite_migration_tx(
    pool: &sqlx::SqlitePool,
    ops: &[&Operation],
    plugin: &str,
    name: &str,
    applied_at: &str,
    snapshot_hash: &str,
) -> Result<(), MigrateError> {
    use sqlx::Acquire as _;

    let needs_fk_off = ops
        .iter()
        .any(|op| matches!(op, Operation::AlterColumn { .. }));

    let mut conn = pool.acquire().await?;
    if needs_fk_off {
        sqlx::query("PRAGMA foreign_keys=OFF")
            .execute(&mut *conn)
            .await?;
    }

    let result: Result<(), MigrateError> = async {
        let mut tx = conn.begin().await?;
        for op in ops {
            for sql in render_operation_for(op, "sqlite") {
                sqlx::query(&sql).execute(&mut *tx).await?;
            }
        }
        if needs_fk_off {
            // Enforcement was off during the dance; verify the recreation left
            // no dangling references before we commit.
            let violations = sqlx::query("PRAGMA foreign_key_check")
                .fetch_all(&mut *tx)
                .await?;
            if !violations.is_empty() {
                return Err(MigrateError::Sqlx(sqlx::Error::Protocol(format!(
                    "migration `{plugin}/{name}` would leave {} dangling foreign-key \
                     reference(s); aborted",
                    violations.len()
                ))));
            }
        }
        sqlx::query(
            "INSERT INTO umbral_migrations (plugin, name, applied_at, snapshot_hash) \
             VALUES (?, ?, ?, ?)",
        )
        .bind(plugin)
        .bind(name)
        .bind(applied_at)
        .bind(snapshot_hash)
        .execute(&mut *tx)
        .await?;
        tx.commit().await?;
        Ok(())
    }
    .await;

    if needs_fk_off {
        // Restore enforcement before the connection returns to the pool, even
        // on failure — but never mask the primary error with a pragma error.
        let _ = sqlx::query("PRAGMA foreign_keys=ON")
            .execute(&mut *conn)
            .await;
    }
    result
}

/// A stable 64-bit key for the Postgres migration advisory lock, derived from a
/// fixed namespace + a `discriminator` (the pool alias or tenant schema). FNV-1a
/// with fixed constants — deterministic and process-independent, so every
/// migrator computes the SAME key for the same target and they mutually exclude.
/// Different aliases/schemas get different keys, so unrelated logical databases
/// migrate concurrently (audit_2 core-migrate #7).
fn pg_migration_lock_key(discriminator: &str) -> i64 {
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    for b in b"umbral_migrations\0"
        .iter()
        .copied()
        .chain(discriminator.bytes())
    {
        hash ^= b as u64;
        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
    }
    hash as i64
}

/// How long a migrator waits for the advisory lock before giving up. Generous
/// (another replica's migration set can take a while), bounded so a deploy can't
/// hang forever on a wedged migrator. Override with
/// `UMBRAL_MIGRATION_LOCK_TIMEOUT_SECS`.
fn pg_migration_lock_timeout() -> std::time::Duration {
    let secs = std::env::var("UMBRAL_MIGRATION_LOCK_TIMEOUT_SECS")
        .ok()
        .and_then(|v| v.trim().parse::<u64>().ok())
        .filter(|&n| n > 0)
        .unwrap_or(300);
    std::time::Duration::from_secs(secs)
}

/// Acquire the session-level Postgres advisory lock keyed on `discriminator`,
/// holding it on `conn` for the caller to release. Non-blocking polls
/// (`pg_try_advisory_lock`) with a short sleep between attempts, bounded by
/// [`pg_migration_lock_timeout`] — so a stuck migrator surfaces as a clear
/// [`MigrateError::MigrationLockTimeout`] instead of an indefinite hang, and a
/// crashed migrator's lock auto-releases (session locks die with the backend).
async fn acquire_pg_migration_lock(
    conn: &mut sqlx::PgConnection,
    key: i64,
    discriminator: &str,
) -> Result<(), MigrateError> {
    let timeout = pg_migration_lock_timeout();
    let start = std::time::Instant::now();
    let mut warned = false;
    loop {
        let got: bool = sqlx::query_scalar("SELECT pg_try_advisory_lock($1)")
            .bind(key)
            .fetch_one(&mut *conn)
            .await?;
        if got {
            return Ok(());
        }
        let waited = start.elapsed();
        if waited >= timeout {
            return Err(MigrateError::MigrationLockTimeout {
                discriminator: discriminator.to_string(),
                waited_secs: waited.as_secs(),
            });
        }
        if !warned {
            tracing::info!(
                discriminator,
                "umbral migrate: another process holds the migration lock; waiting for it to \
                 finish before applying migrations…"
            );
            warned = true;
        }
        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
    }
}

/// Release the advisory lock acquired by [`acquire_pg_migration_lock`]. Best
/// effort — dropping `conn` also releases a session lock, so a failure here is
/// logged, not propagated (it must never mask the migration's own result).
async fn release_pg_migration_lock(conn: &mut sqlx::PgConnection, key: i64) {
    if let Err(e) = sqlx::query("SELECT pg_advisory_unlock($1)")
        .bind(key)
        .execute(&mut *conn)
        .await
    {
        tracing::warn!("umbral migrate: failed to release the migration advisory lock: {e}");
    }
}

/// Postgres per-alias variant. Mirror of `run_in_sqlite_for_alias`.
///
/// Wraps the apply loop in a session advisory lock (audit_2 core-migrate #7) so
/// two replicas deploying at once can't both read the applied set and race the
/// same DDL (the loser errors "relation already exists" mid-deploy). The lock is
/// held on a dedicated connection for the whole run; the per-migration
/// transactions use their own pooled connections and are unaffected.
async fn run_in_postgres_for_alias(
    dir: &Path,
    alias: &str,
    pool: &sqlx::PgPool,
    shared_only: Option<&std::collections::HashSet<String>>,
) -> Result<u64, MigrateError> {
    let key = pg_migration_lock_key(alias);
    let mut lock_conn = pool.acquire().await?;
    acquire_pg_migration_lock(&mut lock_conn, key, alias).await?;
    let result = run_in_postgres_for_alias_locked(dir, alias, pool, shared_only).await;
    release_pg_migration_lock(&mut lock_conn, key).await;
    result
}

/// Run `f` under the Postgres migration advisory lock keyed on `discriminator`.
/// Shared by the checked-run and schema-per-tenant apply paths so they get the
/// same cross-process serialization as [`run_in_postgres_for_alias`].
async fn with_pg_migration_lock<F, Fut>(
    pool: &sqlx::PgPool,
    discriminator: &str,
    f: F,
) -> Result<u64, MigrateError>
where
    F: FnOnce() -> Fut,
    Fut: std::future::Future<Output = Result<u64, MigrateError>>,
{
    let key = pg_migration_lock_key(discriminator);
    let mut lock_conn = pool.acquire().await?;
    acquire_pg_migration_lock(&mut lock_conn, key, discriminator).await?;
    let result = f().await;
    release_pg_migration_lock(&mut lock_conn, key).await;
    result
}

/// The unlocked body of [`run_in_postgres_for_alias`] — runs while the caller
/// holds the migration advisory lock.
async fn run_in_postgres_for_alias_locked(
    dir: &Path,
    alias: &str,
    pool: &sqlx::PgPool,
    shared_only: Option<&std::collections::HashSet<String>>,
) -> Result<u64, MigrateError> {
    ensure_tracking_table_postgres(pool).await?;
    let applied = applied_names_postgres(pool).await?;

    let mut applied_count: u64 = 0;
    for plugin in plugin_order() {
        // Shared-filtered public migrate (multitenancy): when a shared-app set
        // is given, migrate ONLY those plugins into this pool, so a tenant
        // app's tables (and its M2M junctions) are NOT created in `public` —
        // they belong only in each tenant schema. `None` = migrate everything
        // (the default single-DB behaviour, byte-identical to before).
        if let Some(shared) = shared_only {
            if !shared.contains(&plugin) {
                continue;
            }
        }
        let plugin_dir = dir.join(&plugin);
        let paths = list_migration_files(&plugin_dir)?;

        // Plan squash decisions for the plugin's whole file set (gaps2 #100),
        // identical to the SQLite runner — `squash_plan` is backend-agnostic.
        let files: Vec<MigrationFile> = paths
            .iter()
            .map(|p| read_migration_file(p))
            .collect::<Result<_, _>>()?;
        let plan = squash_plan(&files, &applied)?;

        for (file, decision) in files.iter().zip(plan) {
            if decision == ApplyDecision::Skip {
                continue;
            }

            let ops_for_this_db: Vec<&Operation> = file
                .operations
                .iter()
                .filter(|op| op_targets_alias(op, alias))
                .collect();
            if ops_for_this_db.is_empty() {
                continue;
            }

            let mut tx = pool.begin().await?;
            // RecordOnly (squash whose replaced set is already applied): its
            // schema exists, so run no DDL — just insert the tracking row.
            if decision != ApplyDecision::RecordOnly {
                for op in &ops_for_this_db {
                    for sql in render_operation(op) {
                        sqlx::query(&sql).execute(&mut *tx).await?;
                    }
                }
            }
            let snapshot_hash = file.snapshot_after.hash();
            let applied_at = chrono::Utc::now().to_rfc3339();
            sqlx::query(
                "INSERT INTO umbral_migrations (plugin, name, applied_at, snapshot_hash) \
                 VALUES ($1, $2, $3, $4)",
            )
            .bind(&file.plugin)
            .bind(&file.id)
            .bind(&applied_at)
            .bind(&snapshot_hash)
            .execute(&mut *tx)
            .await?;
            tx.commit().await?;
            applied_count += 1;
        }
    }
    Ok(applied_count)
}

/// Migrate the **tenant** apps into a named Postgres schema (schema-per-tenant
/// style). The migration engine owns all schema DDL; this is the
/// sanctioned `CREATE SCHEMA` / `SET search_path` exception (a plugin calls this
/// rather than writing raw schema SQL itself).
///
/// Steps, all inside one transaction per migration file (mirroring
/// [`run_in_postgres_for_alias`]):
/// 1. `CREATE SCHEMA IF NOT EXISTS "<schema>"` (the `Schema` was already
///    validated to a safe PG identifier, but is still emitted quoted).
/// 2. `SET LOCAL search_path TO "<schema>"` so every unqualified
///    `CREATE TABLE` **and** the `umbral_migrations` ledger land *inside*
///    `<schema>` — per-schema migration tracking falls out for free.
/// 3. Apply pending migrations, **filtered to the tenant apps** — every plugin
///    NOT in `shared_apps` (those tables live in `public` and are migrated by
///    the normal [`run`]). A file with no tenant-app ops for this schema is
///    skipped without a tracking row.
///
/// Idempotent: re-running applies only the migrations the schema's own
/// `umbral_migrations` ledger hasn't recorded. Postgres-only — schemas don't
/// exist on SQLite, so a SQLite pool is a clear error
/// ([`MigrateError::SchemaUnsupportedOnSqlite`]).
pub async fn run_for_schema(
    schema: &crate::db::Schema,
    shared_apps: &std::collections::HashSet<String>,
) -> Result<u64, MigrateError> {
    run_for_schema_in(Path::new(MIGRATIONS_DIR), schema, shared_apps).await
}

/// Same as [`run_for_schema`] but takes an explicit migrations base directory.
/// The entry tests drive.
pub async fn run_for_schema_in(
    dir: &Path,
    schema: &crate::db::Schema,
    shared_apps: &std::collections::HashSet<String>,
) -> Result<u64, MigrateError> {
    match crate::db::pool_dispatched() {
        crate::db::DbPool::Postgres(p) => {
            // audit_2 core-migrate #7: serialize concurrent migrators of THIS
            // tenant schema (keyed by schema name, so different tenants still
            // migrate concurrently). The shared/public run uses a different key
            // (its alias), so a tenant migrate and the public migrate don't
            // block each other.
            with_pg_migration_lock(p, schema.as_str(), || {
                run_tenant_apps_in_postgres_schema(dir, schema, shared_apps, p)
            })
            .await
        }
        crate::db::DbPool::Sqlite(_) => Err(MigrateError::SchemaUnsupportedOnSqlite {
            schema: schema.as_str().to_string(),
        }),
    }
}

/// Postgres schema-scoped variant of [`run_in_postgres_for_alias`]. Creates the
/// schema, pins `search_path` to it for the transaction, and applies only the
/// tenant apps' migrations (plugins not in `shared_apps`). The `umbral_migrations`
/// ledger is read/written *inside* the schema (search_path is set first), so
/// tracking is per-schema with no extra book-keeping.
async fn run_tenant_apps_in_postgres_schema(
    dir: &Path,
    schema: &crate::db::Schema,
    shared_apps: &std::collections::HashSet<String>,
    pool: &sqlx::PgPool,
) -> Result<u64, MigrateError> {
    let quoted = format!("\"{}\"", schema.as_str());

    // Create the schema once, outside the per-file loop. IF NOT EXISTS makes
    // the whole call idempotent.
    sqlx::query(&format!("CREATE SCHEMA IF NOT EXISTS {quoted}"))
        .execute(pool)
        .await?;

    // Ensure + read the ledger INSIDE the schema. Each block runs in its own
    // transaction with `SET LOCAL search_path` so the tracking table is created
    // in (and read from) `<schema>`, not `public` — AND the search_path is
    // transaction-scoped, so the pooled connection is NOT left pinned to this
    // schema when it returns to the pool. A plain session-level `SET` here
    // pollutes the pool: the next unqualified ORM query that reuses the
    // connection would resolve against `<schema>` instead of `public` (e.g. an
    // insert into the public `tenant` registry failing with "relation does not
    // exist") — a real cross-tenant bug, caught only against live Postgres.
    {
        let mut tx = pool.begin().await?;
        sqlx::query(&format!("SET LOCAL search_path TO {quoted}"))
            .execute(&mut *tx)
            .await?;
        ensure_tracking_table_pg_conn(&mut tx).await?;
        tx.commit().await?;
    }
    let applied = {
        let mut tx = pool.begin().await?;
        sqlx::query(&format!("SET LOCAL search_path TO {quoted}"))
            .execute(&mut *tx)
            .await?;
        let rows: Vec<(String, String)> =
            sqlx::query_as("SELECT plugin, name FROM umbral_migrations")
                .fetch_all(&mut *tx)
                .await?;
        tx.commit().await?;
        rows.into_iter().collect::<std::collections::HashSet<_>>()
    };

    let mut applied_count: u64 = 0;
    for plugin in plugin_order() {
        // Tenant apps only — shared apps live in `public`.
        if shared_apps.contains(&plugin) {
            continue;
        }
        let plugin_dir = dir.join(&plugin);
        let paths = list_migration_files(&plugin_dir)?;

        // Squash-aware planning (gaps2 #100), same as every other apply loop.
        let files: Vec<MigrationFile> = paths
            .iter()
            .map(|p| read_migration_file(p))
            .collect::<Result<_, _>>()?;
        let plan = squash_plan(&files, &applied)?;

        for (file, decision) in files.iter().zip(plan) {
            if decision == ApplyDecision::Skip {
                continue;
            }
            // Belt-and-braces: skip a file whose declared plugin is shared.
            if shared_apps.contains(&file.plugin) {
                continue;
            }

            let mut tx = pool.begin().await?;
            // Pin search_path for THIS transaction, tenant schema FIRST with
            // `public` as a fallback. `CREATE TABLE` / `INSERT` still land in
            // the tenant schema (it's first), but an unqualified reference that
            // ISN'T in the tenant schema resolves against `public` — which is
            // what makes a CROSS-BOUNDARY foreign key work: a tenant-owned
            // table (or an M2M junction) with an FK `REFERENCES <shared_child>`
            // resolves the shared child in `public` instead of erroring
            // `relation does not exist`. It also lets a (future) RunSql data
            // migration in a tenant schema read SHARED/`public` lookup tables.
            // The tenant-first ordering means a tenant table still shadows a
            // same-named public table, so no behaviour changes for the common
            // case where tenant and shared table names are distinct.
            sqlx::query(&format!("SET LOCAL search_path TO {quoted}, public"))
                .execute(&mut *tx)
                .await?;
            // RecordOnly: schema already built by the replaced originals — run
            // no DDL, just record the squash.
            if decision != ApplyDecision::RecordOnly {
                for op in &file.operations {
                    for sql in render_operation_for(op, "postgres") {
                        sqlx::query(&sql).execute(&mut *tx).await?;
                    }
                }
            }
            let snapshot_hash = file.snapshot_after.hash();
            let applied_at = chrono::Utc::now().to_rfc3339();
            sqlx::query(
                "INSERT INTO umbral_migrations (plugin, name, applied_at, snapshot_hash) \
                 VALUES ($1, $2, $3, $4)",
            )
            .bind(&file.plugin)
            .bind(&file.id)
            .bind(&applied_at)
            .bind(&snapshot_hash)
            .execute(&mut *tx)
            .await?;
            tx.commit().await?;
            applied_count += 1;
        }
    }
    Ok(applied_count)
}

/// Migrate the **tenant** apps into the pool registered under `alias`
/// (database-per-tenant). The db-per-tenant sibling of [`run_for_schema`]:
/// where the schema variant pins `search_path` inside one shared Postgres
/// database, this targets a *whole separate database/pool* registered at
/// runtime via [`register_tenant_pool`](crate::db::register_tenant_pool) and
/// resolved here through [`pool_for_dispatched`](crate::db::pool_for_dispatched)
/// (which sees dynamic pools). No schema games — per-database migration
/// tracking is just that database's own `umbral_migrations` table.
///
/// Like the schema variant it applies only the **tenant apps**: every plugin
/// NOT in `shared_apps` (the shared registry/auth tables live in the default
/// DB and are migrated there by the normal [`run`]). A migration file whose
/// declared plugin is shared is skipped without a tracking row. Idempotent:
/// re-running applies only what the tenant DB's own ledger hasn't recorded.
///
/// Works on both backends — a tenant pool can be Postgres (the production case)
/// or SQLite (tests). Unlike the alias-routed [`run_in`], this does NOT filter
/// ops by [`table_alias`]: a tenant-owned model's static alias is still
/// `"default"`, so the per-alias filter would wrongly exclude it from the
/// tenant DB. The shared/tenant split is the *only* filter here.
pub async fn migrate_apps_into_pool(
    alias: &str,
    shared_apps: &std::collections::HashSet<String>,
) -> Result<u64, MigrateError> {
    migrate_apps_into_pool_in(Path::new(MIGRATIONS_DIR), alias, shared_apps).await
}

/// Same as [`migrate_apps_into_pool`] but takes an explicit migrations base
/// directory. The entry tests drive.
pub async fn migrate_apps_into_pool_in(
    dir: &Path,
    alias: &str,
    shared_apps: &std::collections::HashSet<String>,
) -> Result<u64, MigrateError> {
    match crate::db::pool_for_dispatched(alias) {
        crate::db::DbPool::Postgres(p) => {
            migrate_tenant_apps_into_pg_pool(dir, shared_apps, p).await
        }
        crate::db::DbPool::Sqlite(p) => {
            migrate_tenant_apps_into_sqlite_pool(dir, shared_apps, p).await
        }
    }
}

/// Postgres tenant-DB apply loop. Mirrors [`run_in_postgres_for_alias`] but the
/// only filter is the shared/tenant split — every plugin not in `shared_apps`
/// is applied in full into this database.
async fn migrate_tenant_apps_into_pg_pool(
    dir: &Path,
    shared_apps: &std::collections::HashSet<String>,
    pool: &sqlx::PgPool,
) -> Result<u64, MigrateError> {
    ensure_tracking_table_postgres(pool).await?;
    let applied = applied_names_postgres(pool).await?;

    let mut applied_count: u64 = 0;
    for plugin in plugin_order() {
        if shared_apps.contains(&plugin) {
            continue;
        }
        let plugin_dir = dir.join(&plugin);
        let files: Vec<MigrationFile> = list_migration_files(&plugin_dir)?
            .iter()
            .map(|p| read_migration_file(p))
            .collect::<Result<_, _>>()?;
        let plan = squash_plan(&files, &applied)?;
        for (file, decision) in files.iter().zip(plan) {
            if decision == ApplyDecision::Skip {
                continue;
            }
            if shared_apps.contains(&file.plugin) {
                continue;
            }
            let mut tx = pool.begin().await?;
            if decision != ApplyDecision::RecordOnly {
                for op in &file.operations {
                    for sql in render_operation_for(op, "postgres") {
                        sqlx::query(&sql).execute(&mut *tx).await?;
                    }
                }
            }
            let snapshot_hash = file.snapshot_after.hash();
            let applied_at = chrono::Utc::now().to_rfc3339();
            sqlx::query(
                "INSERT INTO umbral_migrations (plugin, name, applied_at, snapshot_hash) \
                 VALUES ($1, $2, $3, $4)",
            )
            .bind(&file.plugin)
            .bind(&file.id)
            .bind(&applied_at)
            .bind(&snapshot_hash)
            .execute(&mut *tx)
            .await?;
            tx.commit().await?;
            applied_count += 1;
        }
    }
    Ok(applied_count)
}

/// SQLite tenant-DB apply loop (tests). Same shape as the Postgres variant.
async fn migrate_tenant_apps_into_sqlite_pool(
    dir: &Path,
    shared_apps: &std::collections::HashSet<String>,
    pool: &sqlx::SqlitePool,
) -> Result<u64, MigrateError> {
    ensure_tracking_table_sqlite(pool).await?;
    let applied = applied_names_sqlite(pool).await?;

    let mut applied_count: u64 = 0;
    for plugin in plugin_order() {
        if shared_apps.contains(&plugin) {
            continue;
        }
        let plugin_dir = dir.join(&plugin);
        let files: Vec<MigrationFile> = list_migration_files(&plugin_dir)?
            .iter()
            .map(|p| read_migration_file(p))
            .collect::<Result<_, _>>()?;
        let plan = squash_plan(&files, &applied)?;
        for (file, decision) in files.iter().zip(plan) {
            if decision == ApplyDecision::Skip {
                continue;
            }
            if shared_apps.contains(&file.plugin) {
                continue;
            }
            let snapshot_hash = file.snapshot_after.hash();
            let applied_at = chrono::Utc::now().to_rfc3339();
            // RecordOnly → empty op slice: inserts the tracking row, no DDL.
            let ops: Vec<&Operation> = if decision == ApplyDecision::RecordOnly {
                Vec::new()
            } else {
                file.operations.iter().collect()
            };
            apply_sqlite_migration_tx(
                pool,
                &ops,
                &file.plugin,
                &file.id,
                &applied_at,
                &snapshot_hash,
            )
            .await?;
            applied_count += 1;
        }
    }
    Ok(applied_count)
}

/// `ensure_tracking_table_postgres` against an explicit connection (so the
/// caller can pin `search_path` first and have the table created in the tenant
/// schema rather than `public`).
async fn ensure_tracking_table_pg_conn(conn: &mut sqlx::PgConnection) -> Result<(), MigrateError> {
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS umbral_migrations (
            plugin TEXT NOT NULL,
            name TEXT NOT NULL,
            applied_at TEXT NOT NULL,
            snapshot_hash TEXT NOT NULL,
            PRIMARY KEY (plugin, name)
        )",
    )
    .execute(conn)
    .await?;
    Ok(())
}

/// SQLite drift-checking path for `run_checked_in`.
///
/// Reads the applied set, runs `detect_all_drift`, and either errors
/// (if `allow_drift = false` and critical drift is found) or logs a
/// warning and proceeds (if `allow_drift = true`). Then delegates to
/// `run_in_sqlite` for the actual apply loop.
async fn run_in_sqlite_checked(
    dir: &Path,
    pool: &sqlx::SqlitePool,
    allow_drift: bool,
    alias: &str,
) -> Result<u64, MigrateError> {
    ensure_tracking_table_sqlite(pool).await?;
    let applied = applied_names_sqlite(pool).await?;
    let report = detect_all_drift(&applied, dir)?;

    if report.has_critical_drift() {
        if allow_drift {
            let missing = report.missing_on_disk();
            for entry in &missing {
                eprintln!(
                    "warning: umbral migrate --allow-drift: migration {}/{} is recorded in \
                     the tracking table but the file is missing from disk; proceeding.",
                    entry.plugin, entry.name
                );
            }
        } else {
            let missing: Vec<(String, String)> = report
                .missing_on_disk()
                .iter()
                .map(|e| (e.plugin.clone(), e.name.clone()))
                .collect();
            return Err(MigrateError::DriftDetected { missing });
        }
    }

    // Emit warnings for out-of-order files.
    for entry in report
        .entries
        .iter()
        .filter(|e| e.status == MigrationStatus::OutOfOrder)
    {
        eprintln!(
            "warning: umbral migrate: migration {}/{} is on disk but appears before the \
             last applied migration for this plugin; it looks like a file was restored \
             after a teammate already applied later ones.",
            entry.plugin, entry.name
        );
    }

    run_in_sqlite_for_alias(dir, alias, pool, None).await
}

/// Postgres drift-checking path for `run_checked_in`. Same logic as
/// `run_in_sqlite_checked` but uses the Postgres applied-set reader.
async fn run_in_postgres_checked(
    dir: &Path,
    pool: &sqlx::PgPool,
    allow_drift: bool,
    alias: &str,
) -> Result<u64, MigrateError> {
    ensure_tracking_table_postgres(pool).await?;
    let applied = applied_names_postgres(pool).await?;
    let report = detect_all_drift(&applied, dir)?;

    if report.has_critical_drift() {
        if allow_drift {
            let missing = report.missing_on_disk();
            for entry in &missing {
                eprintln!(
                    "warning: umbral migrate --allow-drift: migration {}/{} is recorded in \
                     the tracking table but the file is missing from disk; proceeding.",
                    entry.plugin, entry.name
                );
            }
        } else {
            let missing: Vec<(String, String)> = report
                .missing_on_disk()
                .iter()
                .map(|e| (e.plugin.clone(), e.name.clone()))
                .collect();
            return Err(MigrateError::DriftDetected { missing });
        }
    }

    for entry in report
        .entries
        .iter()
        .filter(|e| e.status == MigrationStatus::OutOfOrder)
    {
        eprintln!(
            "warning: umbral migrate: migration {}/{} is on disk but appears before the \
             last applied migration for this plugin; it looks like a file was restored \
             after a teammate already applied later ones.",
            entry.plugin, entry.name
        );
    }

    run_in_postgres_for_alias(dir, alias, pool, None).await
}

/// Record a migration as applied in the `umbral_migrations` tracking
/// table without running its operations. The "mark as applied" path
/// `inspectdb --mark-applied` uses to register the introspected
/// `0001_initial` against an already-populated database. Idempotent:
/// if the `(plugin, name)` row already exists, the call is a no-op.
pub async fn record_applied(
    plugin: &str,
    name: &str,
    snapshot_hash: &str,
) -> Result<(), MigrateError> {
    let applied_at = chrono::Utc::now().to_rfc3339();
    match crate::db::pool_dispatched() {
        crate::db::DbPool::Sqlite(pool) => {
            ensure_tracking_table_sqlite(pool).await?;
            sqlx::query(
                "INSERT OR IGNORE INTO umbral_migrations \
                 (plugin, name, applied_at, snapshot_hash) \
                 VALUES (?, ?, ?, ?)",
            )
            .bind(plugin)
            .bind(name)
            .bind(&applied_at)
            .bind(snapshot_hash)
            .execute(pool)
            .await?;
        }
        crate::db::DbPool::Postgres(pool) => {
            ensure_tracking_table_postgres(pool).await?;
            sqlx::query(
                "INSERT INTO umbral_migrations \
                 (plugin, name, applied_at, snapshot_hash) \
                 VALUES ($1, $2, $3, $4) \
                 ON CONFLICT (plugin, name) DO NOTHING",
            )
            .bind(plugin)
            .bind(name)
            .bind(&applied_at)
            .bind(snapshot_hash)
            .execute(pool)
            .await?;
        }
    }
    Ok(())
}

// =========================================================================
// Drift detection — gap 24.
// =========================================================================

/// Compute the drift report for a single plugin directory. Compares the
/// set of `(plugin, name)` pairs recorded in the tracking table against
/// the migration files present on disk and classifies each into one of
/// the four [`MigrationStatus`] states.
///
/// `applied` is the full set of `(plugin, name)` tuples already read
/// from the tracking table (shared across plugins to avoid extra DB
/// round-trips). `plugin_dir` is the on-disk directory for this plugin;
/// an absent directory is treated the same as an empty one.
///
/// # Classification
///
/// - File present + in DB → `Applied`
/// - File absent + in DB → `AppliedButMissing`
/// - File present + not in DB + seq ≤ max_applied_seq → `OutOfOrder`
/// - File present + not in DB + seq > max_applied_seq → `Pending`
///
/// The sequence number is the numeric prefix of the migration name
/// (e.g. `0001` in `0001_create_post`). Absence of any applied
/// migration for this plugin means `max_applied_seq = 0`.
pub fn detect_drift(
    plugin: &str,
    applied: &std::collections::HashSet<(String, String)>,
    plugin_dir: &Path,
) -> Result<Vec<MigrationEntry>, MigrateError> {
    // Collect on-disk migration names (the id, not the full path).
    let paths = list_migration_files(plugin_dir)?;
    let mut on_disk: Vec<String> = Vec::new();
    // Migrations shadowed by an APPLIED squash: an applied `000X_squashed`
    // replaces its originals, which are kept on disk (Django-style, non-
    // destructive) but get no tracking row. Without this they'd be
    // misclassified `Pending` forever and block umbral-health readiness on
    // a freshly-squashed database. Mirrors `squash_plan`'s `shadowed` set.
    let mut shadowed: std::collections::HashSet<String> = std::collections::HashSet::new();
    for path in &paths {
        let file = read_migration_file(path)?;
        if applied.contains(&(plugin.to_string(), file.id.clone())) {
            for m in &file.replaces {
                shadowed.insert(m.migration.clone());
            }
        }
        on_disk.push(file.id.clone());
    }

    // Pull every tracking-table entry for this plugin.
    let plugin_applied: Vec<&str> = applied
        .iter()
        .filter(|(p, _)| p == plugin)
        .map(|(_, n)| n.as_str())
        .collect();

    // Highest sequence number among applied migrations for this plugin.
    let max_applied_seq: u32 = plugin_applied
        .iter()
        .filter_map(|name| name.split('_').next()?.parse::<u32>().ok())
        .max()
        .unwrap_or(0);

    let on_disk_set: std::collections::HashSet<&str> = on_disk.iter().map(|s| s.as_str()).collect();

    let mut entries: Vec<MigrationEntry> = Vec::new();

    // Walk on-disk files in order.
    for name in &on_disk {
        let key = (plugin.to_string(), name.clone());
        let status = if applied.contains(&key) || shadowed.contains(name) {
            // Applied directly, or shadowed by an applied squash (its
            // originals are covered even without their own tracking row).
            MigrationStatus::Applied
        } else {
            // Determine this migration's sequence number.
            let seq: u32 = name
                .split('_')
                .next()
                .and_then(|s| s.parse().ok())
                .unwrap_or(0);
            if seq <= max_applied_seq && max_applied_seq > 0 {
                MigrationStatus::OutOfOrder
            } else {
                MigrationStatus::Pending
            }
        };
        entries.push(MigrationEntry {
            plugin: plugin.to_string(),
            name: name.clone(),
            status,
        });
    }

    // Walk applied entries not present on disk.
    for name in &plugin_applied {
        if !on_disk_set.contains(*name) {
            entries.push(MigrationEntry {
                plugin: plugin.to_string(),
                name: (*name).to_string(),
                status: MigrationStatus::AppliedButMissing,
            });
        }
    }

    // Sort: applied-but-missing entries bubble after their expected
    // position is not determinable; sort all entries by name for a
    // deterministic order. In practice, applied-but-missing names
    // are still prefixed with the numeric sequence so lexical sort
    // yields the right display order.
    entries.sort_by(|a, b| a.name.cmp(&b.name));

    Ok(entries)
}

/// Detect drift across every registered plugin and return a combined
/// [`DriftReport`]. Called by `run_in_checked` before executing SQL
/// and by `show_in` when displaying the four-state list.
///
/// `applied` is already fetched from the DB; `dir` is the migrations
/// root directory.
pub fn detect_all_drift(
    applied: &std::collections::HashSet<(String, String)>,
    dir: &Path,
) -> Result<DriftReport, MigrateError> {
    let mut all_entries: Vec<MigrationEntry> = Vec::new();

    // Also surface any tracking-table entries whose plugin directory
    // doesn't appear in the registered-plugins list — a plugin was
    // removed entirely but its DB rows remain.
    let mut seen_plugins: std::collections::HashSet<String> = std::collections::HashSet::new();

    for plugin in plugin_order() {
        seen_plugins.insert(plugin.clone());
        let plugin_dir = dir.join(&plugin);
        let entries = detect_drift(&plugin, applied, &plugin_dir)?;
        all_entries.extend(entries);
    }

    // Any applied entries whose plugin is not in the registered set at
    // all — treat them as AppliedButMissing (the whole plugin is gone).
    for (plugin, name) in applied {
        if !seen_plugins.contains(plugin.as_str()) {
            all_entries.push(MigrationEntry {
                plugin: plugin.clone(),
                name: name.clone(),
                status: MigrationStatus::AppliedButMissing,
            });
        }
    }

    Ok(DriftReport {
        entries: all_entries,
    })
}

/// Record a migration as applied in the tracking table WITHOUT running
/// its SQL operations. The `--fake` recovery path: the schema already
/// exists (e.g. the migration was run outside umbral, or the DB was
/// bootstrapped from a dump) and the operator wants to bring the
/// tracking table into sync without re-executing the DDL.
///
/// Idempotent: if `(plugin, name)` is already in the table the call
/// is a no-op (same behaviour as `record_applied`).
///
/// The snapshot hash is derived from the migration file on disk.
/// Returns `MigrateError::Io` if the file can't be found (the caller
/// should verify the name before calling this).
pub async fn fake_apply(plugin: &str, name: &str) -> Result<(), MigrateError> {
    fake_apply_in(plugin, name, Path::new(MIGRATIONS_DIR)).await
}

/// Same as [`fake_apply`] but takes an explicit migrations base dir.
/// Used by tests and by the CLI when `--migrations-dir` is passed.
pub async fn fake_apply_in(plugin: &str, name: &str, dir: &Path) -> Result<(), MigrateError> {
    let path = dir.join(plugin).join(format!("{name}.json"));
    let file = read_migration_file(&path)?;
    let snapshot_hash = file.snapshot_after.hash();
    record_applied(plugin, name, &snapshot_hash).await
}

/// For every registered plugin's first migration (`0001_*`), check
/// whether the tables that migration would create already exist in the
/// database. If they do, fake-apply the migration (mark it applied
/// without running its SQL).
///
/// This is the `--fake-initial` path: the operator has a database
/// bootstrapped outside umbral (a dump restore, a manual `CREATE TABLE`,
/// or a previous schema manager) and wants to bring the tracking table
/// into sync so subsequent `migrate` calls apply only the genuine
/// deltas.
///
/// Returns the number of plugins whose `0001_*` migration was
/// fake-applied. Zero means either no `0001_*` file exists or the
/// target tables were absent (in which case normal `migrate` should be
/// run to create them).
pub async fn fake_initial() -> Result<u64, MigrateError> {
    fake_initial_in(Path::new(MIGRATIONS_DIR)).await
}

/// Same as [`fake_initial`] but takes an explicit migrations base dir.
pub async fn fake_initial_in(dir: &Path) -> Result<u64, MigrateError> {
    match crate::db::pool_dispatched() {
        crate::db::DbPool::Sqlite(pool) => fake_initial_sqlite(dir, pool).await,
        crate::db::DbPool::Postgres(pool) => fake_initial_postgres(dir, pool).await,
    }
}

/// SQLite path for [`fake_initial_in`].
async fn fake_initial_sqlite(dir: &Path, pool: &sqlx::SqlitePool) -> Result<u64, MigrateError> {
    ensure_tracking_table_sqlite(pool).await?;
    let applied = applied_names_sqlite(pool).await?;
    let mut count: u64 = 0;

    for plugin in plugin_order() {
        let plugin_dir = dir.join(&plugin);
        let paths = list_migration_files(&plugin_dir)?;

        // Find the first migration file (lowest sequence number).
        let first = paths.first();
        let first = match first {
            Some(p) => p,
            None => continue,
        };
        let file = read_migration_file(first)?;

        // Skip if already applied.
        if applied.contains(&(file.plugin.clone(), file.id.clone())) {
            continue;
        }

        // Check whether the tables the first migration would create
        // already exist in the database.
        let tables_to_create: Vec<&str> = file
            .operations
            .iter()
            .filter_map(|op| match op {
                Operation::CreateTable { table, .. } => Some(table.as_str()),
                _ => None,
            })
            .collect();

        if tables_to_create.is_empty() {
            continue;
        }

        // All tables present → fake-apply.
        let mut all_present = true;
        for table in &tables_to_create {
            let exists: Option<(String,)> =
                sqlx::query_as("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?")
                    .bind(*table)
                    .fetch_optional(pool)
                    .await?;
            if exists.is_none() {
                all_present = false;
                break;
            }
        }

        if all_present {
            let snapshot_hash = file.snapshot_after.hash();
            let applied_at = chrono::Utc::now().to_rfc3339();
            sqlx::query(
                "INSERT OR IGNORE INTO umbral_migrations \
                 (plugin, name, applied_at, snapshot_hash) VALUES (?, ?, ?, ?)",
            )
            .bind(&file.plugin)
            .bind(&file.id)
            .bind(&applied_at)
            .bind(&snapshot_hash)
            .execute(pool)
            .await?;
            count += 1;
        }
    }

    Ok(count)
}

/// Postgres path for [`fake_initial_in`].
async fn fake_initial_postgres(dir: &Path, pool: &sqlx::PgPool) -> Result<u64, MigrateError> {
    ensure_tracking_table_postgres(pool).await?;
    let applied = applied_names_postgres(pool).await?;
    let mut count: u64 = 0;

    for plugin in plugin_order() {
        let plugin_dir = dir.join(&plugin);
        let paths = list_migration_files(&plugin_dir)?;

        let first = paths.first();
        let first = match first {
            Some(p) => p,
            None => continue,
        };
        let file = read_migration_file(first)?;

        if applied.contains(&(file.plugin.clone(), file.id.clone())) {
            continue;
        }

        let tables_to_create: Vec<&str> = file
            .operations
            .iter()
            .filter_map(|op| match op {
                Operation::CreateTable { table, .. } => Some(table.as_str()),
                _ => None,
            })
            .collect();

        if tables_to_create.is_empty() {
            continue;
        }

        let mut all_present = true;
        for table in &tables_to_create {
            let exists: Option<(String,)> = sqlx::query_as(
                "SELECT table_name FROM information_schema.tables \
                 WHERE table_schema = 'public' AND table_name = $1",
            )
            .bind(*table)
            .fetch_optional(pool)
            .await?;
            if exists.is_none() {
                all_present = false;
                break;
            }
        }

        if all_present {
            let snapshot_hash = file.snapshot_after.hash();
            let applied_at = chrono::Utc::now().to_rfc3339();
            sqlx::query(
                "INSERT INTO umbral_migrations \
                 (plugin, name, applied_at, snapshot_hash) VALUES ($1, $2, $3, $4) \
                 ON CONFLICT (plugin, name) DO NOTHING",
            )
            .bind(&file.plugin)
            .bind(&file.id)
            .bind(&applied_at)
            .bind(&snapshot_hash)
            .execute(pool)
            .await?;
            count += 1;
        }
    }

    Ok(count)
}

/// Print the per-migration state, applied or pending. Output goes to
/// stdout; the return value is the count of pending migrations so a
/// CLI can `exit(n)` on need.
pub async fn show() -> Result<u64, MigrateError> {
    show_in(Path::new(MIGRATIONS_DIR)).await
}

/// Read-only migration status for a health / readiness probe (Kikosi #5,
/// gaps3 #38).
///
/// Returns the same [`DriftReport`] `showmigrations` computes — one entry per
/// migration, categorised into the four [`MigrationStatus`] states — but prints
/// nothing, so it is safe to call on every `/readyz` hit. Reads the
/// `umbral_migrations` tracking table (ensuring it exists) and the on-disk
/// `migrations/` tree. Use [`DriftReport::pending`] to gate readiness.
pub async fn drift_report() -> Result<DriftReport, MigrateError> {
    drift_report_in(Path::new(MIGRATIONS_DIR)).await
}

/// [`drift_report`] against an explicit migrations directory. The entry tests
/// drive this so they can point at a temp tree.
pub async fn drift_report_in(dir: &Path) -> Result<DriftReport, MigrateError> {
    let applied = match crate::db::pool_dispatched() {
        crate::db::DbPool::Sqlite(pool) => {
            ensure_tracking_table_sqlite(pool).await?;
            applied_names_sqlite(pool).await?
        }
        crate::db::DbPool::Postgres(pool) => {
            ensure_tracking_table_postgres(pool).await?;
            applied_names_postgres(pool).await?
        }
    };
    detect_all_drift(&applied, dir)
}

/// Same as [`show`] but takes an explicit base directory. Walks every
/// registered plugin in sorted-by-name order, printing one section per
/// plugin that owns at least one migration file; empty plugins are
/// skipped silently rather than emitting a bare header.
///
/// Four-state output (gap 24):
///
/// - `[X]` applied and file present on disk (normal)
/// - `[ ]` pending (on disk, not yet applied, sequence after last applied)
/// - `[!]` applied but missing on disk (drift — tracking table ahead of VCS)
/// - `[?]` on disk but out of order (sequence before last applied, not in DB)
pub async fn show_in(dir: &Path) -> Result<u64, MigrateError> {
    let report = drift_report_in(dir).await?;

    // Group by plugin for display.
    let mut by_plugin: std::collections::BTreeMap<&str, Vec<&MigrationEntry>> =
        std::collections::BTreeMap::new();
    for entry in &report.entries {
        by_plugin
            .entry(entry.plugin.as_str())
            .or_default()
            .push(entry);
    }

    let mut pending: u64 = 0;
    for (plugin, entries) in &by_plugin {
        if entries.is_empty() {
            continue;
        }
        println!("# plugin: {plugin}");
        for entry in entries {
            let marker = match entry.status {
                MigrationStatus::Applied => "[X]",
                MigrationStatus::Pending => {
                    pending += 1;
                    "[ ]"
                }
                MigrationStatus::AppliedButMissing => "[!]",
                MigrationStatus::OutOfOrder => "[?]",
            };
            println!("{marker} {}/{}", entry.plugin, entry.name);
        }
    }
    Ok(pending)
}

/// Safety classification for a single pending migration operation.
///
/// Feature #65 (blue-green / zero-downtime). The `checkmigrations`
/// command walks every pending operation and tags it so an operator
/// deploying without a maintenance window can tell which changes are safe
/// under a rolling deploy (old and new code serving traffic at once) and
/// which need the expand-contract dance. This is advisory triage — the
/// engine still *applies* every op exactly as written; nothing here gates
/// `migrate`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OpSafety {
    /// Additive and backward-compatible — safe while old code still runs.
    Safe,
    /// Applies cleanly but can break still-running old code, lock a large
    /// table, or fail against unexpected production data. Review first.
    Warning(String),
    /// Destroys data or is irreversible; old code referencing the dropped
    /// surface errors immediately.
    Unsafe(String),
}

impl OpSafety {
    /// The advisory reason for a `Warning` / `Unsafe`; empty for `Safe`.
    pub fn reason(&self) -> &str {
        match self {
            OpSafety::Safe => "",
            OpSafety::Warning(r) | OpSafety::Unsafe(r) => r,
        }
    }

    /// True for the destructive / irreversible tier only.
    pub fn is_unsafe(&self) -> bool {
        matches!(self, OpSafety::Unsafe(_))
    }

    /// True for the review-before-deploy tier only.
    pub fn is_warning(&self) -> bool {
        matches!(self, OpSafety::Warning(_))
    }
}

/// One pending operation tagged with its [`OpSafety`] and the migration
/// that introduced it. The unit of output for `checkmigrations`.
#[derive(Debug, Clone)]
pub struct ClassifiedOp {
    pub plugin: String,
    pub migration: String,
    pub op: Operation,
    pub safety: OpSafety,
}

/// Classify one operation for zero-downtime safety. Pure — no DB access,
/// no file reads — so it is trivially unit-testable and reused by both
/// the CLI report and any plugin that wants to gate its own deploys.
pub fn classify_operation(op: &Operation) -> OpSafety {
    match op {
        // Brand-new tables touch no existing rows and no old code reads
        // them yet.
        Operation::CreateTable { .. } | Operation::CreateM2MTable { .. } => OpSafety::Safe,

        // A column comment is metadata: no rows read or written, no lock worth
        // naming, and no code path — old or new — reads it. A docstring edit
        // must never gate a zero-downtime deploy.
        Operation::SetColumnComment { .. } => OpSafety::Safe,

        // Adding a column is additive — unless it's NOT NULL with no
        // default, in which case old code inserting a row without the
        // column fails. (The engine refuses such an add against a
        // populated SQLite table at apply time; this surfaces the same
        // hazard *before* the operator runs it, and for Postgres too.)
        Operation::AddColumn { table, column } => {
            if !column.nullable && column.default.is_empty() {
                OpSafety::Warning(format!(
                    "adds NOT NULL column `{}.{}` with no default — old code inserting without it will fail. Add it nullable (or with a default), backfill, then tighten",
                    table, column.name
                ))
            } else {
                OpSafety::Safe
            }
        }

        // A view holds no rows of its own (a materialized one holds only derived,
        // recomputable rows), so creating one is free and dropping one destroys
        // nothing. What a DropView CAN break is old code still selecting from it —
        // and since every view edit lowers to drop+create, classifying this Unsafe
        // would trip the zero-downtime gate on a routine SQL tweak. Warning is the
        // honest severity: worth reading, not worth blocking.
        Operation::CreateView { .. } => OpSafety::Safe,
        Operation::DropView { name, .. } => OpSafety::Warning(format!(
            "drops view `{name}` — no rows are lost (a view stores none), but old code \
             still selecting from it breaks until the recreate lands in the same migration"
        )),

        // Destructive / irreversible: data loss the moment it runs.
        Operation::DropTable { table } => OpSafety::Unsafe(format!(
            "drops table `{table}` and every row in it — irreversible, and old code still reading it breaks. Stop using it, deploy, then drop in a later migration"
        )),
        Operation::DropM2MTable { junction_table } => OpSafety::Unsafe(format!(
            "drops join table `{junction_table}` and every row in it — irreversible"
        )),
        Operation::DropColumn { table, column } => OpSafety::Unsafe(format!(
            "drops column `{table}.{column}` and its data — old code reading it breaks. Expand-contract: stop writing it, deploy, then drop"
        )),

        // Renames apply atomically in the DB but NOT atomically with a
        // code deploy: between the migration and the rollout, one of the
        // two code versions references the missing name.
        Operation::RenameTable { from, to } => OpSafety::Warning(format!(
            "renames table `{from}` → `{to}` — not atomic with a code deploy; old code references `{from}`. Expand-contract: add `{to}`, dual-write, switch, then drop `{from}`"
        )),
        Operation::RenameColumn {
            table, from, to, ..
        } => OpSafety::Warning(format!(
            "renames column `{table}.{from}` → `{to}` — old code references `{from}`. Expand-contract: add `{to}`, backfill, switch reads, then drop `{from}`"
        )),

        // An alter can rewrite a column (table lock on large data) and a
        // nullable→NOT NULL tightening fails on existing NULLs.
        Operation::AlterColumn { table, column, .. } => OpSafety::Warning(format!(
            "alters column `{table}.{column}` — a type change rewrites the column (locks the table on large data) and a NOT NULL tightening fails on existing NULLs; verify against production data first"
        )),

        // A hand-authored data migration runs arbitrary SQL — the
        // engine can't reason about its row impact, so flag it for
        // human review (it may rewrite or delete data, and re-running
        // the rollout while it's mid-flight can double-apply).
        Operation::RunSql { .. } => OpSafety::Warning(
            "runs a hand-authored data migration (raw SQL) — review its row impact, ensure it's idempotent or guarded, and verify it against production data first".to_string(),
        ),

        // Adding a composite UNIQUE constraint fails at apply time if
        // existing rows already violate it — same hazard as a single-column
        // UNIQUE add. A plain (non-unique) index is purely additive.
        Operation::AddIndex {
            table,
            columns,
            unique: true,
        } => OpSafety::Warning(format!(
            "adds a composite UNIQUE constraint on `{table}` ({}) — fails on existing duplicate rows; de-duplicate first or the migration aborts",
            columns.join(", ")
        )),
        Operation::AddIndex { unique: false, .. } => OpSafety::Safe,

        // Dropping an index / UNIQUE constraint touches no rows. It removes
        // a guarantee (a later duplicate becomes insertable) but that is the
        // intent when a `unique_together` is removed, and no data is lost.
        Operation::DropIndex { .. } => OpSafety::Safe,
    }
}

/// Classify every operation across all pending migrations against the
/// ambient pool. Reads the same applied-set + on-disk diff that
/// `migrate` / `showmigrations` use, then loads each pending migration
/// file and classifies its operations in order. Powers `checkmigrations`.
pub async fn check_pending_safety() -> Result<Vec<ClassifiedOp>, MigrateError> {
    check_pending_safety_in(Path::new(MIGRATIONS_DIR)).await
}

/// [`check_pending_safety`] against an explicit migrations directory.
/// The seam tests use to point at a fixture tree.
pub async fn check_pending_safety_in(dir: &Path) -> Result<Vec<ClassifiedOp>, MigrateError> {
    let applied = match crate::db::pool_dispatched() {
        crate::db::DbPool::Sqlite(pool) => {
            ensure_tracking_table_sqlite(pool).await?;
            applied_names_sqlite(pool).await?
        }
        crate::db::DbPool::Postgres(pool) => {
            ensure_tracking_table_postgres(pool).await?;
            applied_names_postgres(pool).await?
        }
    };

    let report = detect_all_drift(&applied, dir)?;

    let mut out: Vec<ClassifiedOp> = Vec::new();
    for entry in &report.entries {
        if entry.status != MigrationStatus::Pending {
            continue;
        }
        let path = dir.join(&entry.plugin).join(format!("{}.json", entry.name));
        let file = read_migration_file(&path)?;
        for op in &file.operations {
            out.push(ClassifiedOp {
                plugin: entry.plugin.clone(),
                migration: entry.name.clone(),
                op: op.clone(),
                safety: classify_operation(op),
            });
        }
    }
    Ok(out)
}

// =========================================================================
// Internal helpers. Crate-private; the public surface above is the only
// thing the rest of umbral calls into.
// =========================================================================

/// Return every `*.json` migration file in `plugin_dir`, sorted by
/// filename (lexical sort matches numeric order because the prefix is
/// zero-padded). Returns an empty vec if the directory is missing.
fn list_migration_files(plugin_dir: &Path) -> Result<Vec<PathBuf>, MigrateError> {
    if !plugin_dir.exists() {
        return Ok(Vec::new());
    }
    let mut paths: Vec<PathBuf> = Vec::new();
    for entry in std::fs::read_dir(plugin_dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.extension().and_then(|s| s.to_str()) == Some("json") {
            paths.push(path);
        }
    }
    paths.sort();
    Ok(paths)
}

/// Read and parse one migration file.
fn read_migration_file(path: &Path) -> Result<MigrationFile, MigrateError> {
    let text = std::fs::read_to_string(path)?;
    let file: MigrationFile = serde_json::from_str(&text)?;
    Ok(file)
}

/// Diff the previous snapshot against the current one and produce the
/// ordered operation list.
///
/// Emits `CreateTable` / `DropTable` for whole-model changes (M5 v1),
/// and `AddColumn` / `DropColumn` for column-level changes on a model
/// that appears in both snapshots (M8 v1). A column whose name stays
/// the same but whose type or nullable flag changed surfaces as
/// [`MigrateError::UnsafeAlter`]: SQLite can't ALTER COLUMN TYPE in
/// place, and a nullable flip on a populated table is destructive.
///
/// Gap 30 adds two-pass rename detection. `Model::NAME` (the Rust struct
/// name) is the stable identity key across snapshots; the SQL table name
/// in `Model::TABLE` may change (e.g. via the `#[umbral(plugin = "...")]`
/// opt-in). The two passes are:
///
/// - **First pass — struct-name match.** If a model present in `current`
///   but absent from `previous` (by `Model::NAME`) has the same NAME as
///   a model present in `previous` but absent from `current`, the table
///   name changed: emit `RenameTable { from, to }` instead of DropTable +
///   CreateTable. A stdout message names the rename so the developer can
///   audit `makemigrations` output.
/// - **Second pass — column-shape match.** Among unpaired drops and
///   creates, if a drop candidate and a create candidate have bit-identical
///   column shapes (same column names, types, nullable, fk_target), emit
///   `RenameTable` and log a warning so the developer can verify the
///   intent. Struct names differ; the shape heuristic fills in for cases
///   like a wholesale model rename (Foo → Bar, identical fields).
/// - **No-match.** Drop and create as today.
///
/// `pub` (not `pub(crate)`) so integration tests can drive the diff
/// directly with hand-built snapshots. Spec 06 calls the diff the
/// engine's contract; exposing it lets the tests pin every scenario
/// without laundering snapshots through the process-wide registry.
/// audit_2 H23 — how `diff` should treat an ambiguous column-shape rename: an
/// unpaired dropped model and an unpaired created model with *identical* shapes.
/// Driven by `UMBRAL_MIGRATIONS_ASSUME_RENAMES`.
enum RenameIntent {
    /// Auto-pair every shape match into a `RenameTable` (the pre-H23 default).
    Assume,
    /// Treat the pair as unrelated: emit drop + create, no row transfer.
    Independent,
    /// Not configured → `diff` fails closed with `AmbiguousRename`.
    Undecided,
}

fn rename_intent() -> RenameIntent {
    match std::env::var("UMBRAL_MIGRATIONS_ASSUME_RENAMES") {
        Ok(v) => match v.trim().to_ascii_lowercase().as_str() {
            "assume" | "1" | "true" | "yes" | "rename" => RenameIntent::Assume,
            "independent" | "0" | "false" | "no" | "drop" => RenameIntent::Independent,
            _ => RenameIntent::Undecided,
        },
        Err(_) => RenameIntent::Undecided,
    }
}

/// Emit `AddIndex` / `DropIndex` ops for changes to a model's TABLE-level
/// `unique_together` and `indexes` between two snapshots.
///
/// Column-shape changes are handled by [`diff_columns`]; this covers the
/// constraint-only deltas it can't see. Before this existed, adding a
/// `unique_together` group or a multi-column `indexes` entry with no column
/// change produced NO migration at all — `makemigrations` said "no changes"
/// and the constraint was silently never created.
///
/// A group is identified by its ORDERED column list, so re-ordering a group
/// (`[a, b]` → `[b, a]`) reads as drop-old + add-new — correct, since column
/// order changes which queries the index serves. `AddIndex`/`DropIndex`
/// render `IF NOT EXISTS` / `IF EXISTS`, so when a same-table `AlterColumn`
/// in the same migration already rebuilt the table with the new constraint
/// set (the SQLite dance), these ops are harmless no-ops.
fn diff_indexes(previous: &ModelMeta, current: &ModelMeta) -> Vec<Operation> {
    use std::collections::BTreeSet;

    let mut ops: Vec<Operation> = Vec::new();

    let mut emit = |prev_groups: &[Vec<String>], curr_groups: &[Vec<String>], unique: bool| {
        let prev_set: BTreeSet<&Vec<String>> = prev_groups.iter().collect();
        let curr_set: BTreeSet<&Vec<String>> = curr_groups.iter().collect();
        // Added groups → AddIndex (on the current table name).
        for group in curr_set.difference(&prev_set) {
            ops.push(Operation::AddIndex {
                table: current.table.clone(),
                columns: (*group).clone(),
                unique,
            });
        }
        // Removed groups → DropIndex (on the previous table name — a rename
        // in the same diff emits its own RenameTable first, and the index
        // travels with the table, so the drop names the post-rename table;
        // use current.table for that reason).
        for group in prev_set.difference(&curr_set) {
            ops.push(Operation::DropIndex {
                table: current.table.clone(),
                columns: (*group).clone(),
                unique,
            });
        }
    };

    emit(&previous.unique_together, &current.unique_together, true);
    emit(&previous.indexes, &current.indexes, false);

    // Single-column `#[umbral(index)]` flag flips. A column that gains the
    // flag → AddIndex; one that loses it (but still exists) → DropIndex. PK
    // and UNIQUE columns are excluded — they carry their own index, matching
    // `should_emit_btree_index`. A column that was DROPPED entirely takes its
    // index with it (DROP COLUMN cascades on both backends), so we don't emit a
    // redundant DropIndex for it. The `idx_<table>_<col>` name matches the one
    // `create_index_stmt` uses at CreateTable time, so add/drop stay symmetric.
    let indexed = |m: &ModelMeta| -> std::collections::BTreeSet<String> {
        m.fields
            .iter()
            .filter(|c| c.index && !c.primary_key && !c.unique)
            .map(|c| c.name.clone())
            .collect()
    };
    let curr_col_names: std::collections::BTreeSet<&str> =
        current.fields.iter().map(|c| c.name.as_str()).collect();
    let prev_indexed = indexed(previous);
    let curr_indexed = indexed(current);
    for name in curr_indexed.difference(&prev_indexed) {
        ops.push(Operation::AddIndex {
            table: current.table.clone(),
            columns: vec![name.clone()],
            unique: false,
        });
    }
    for name in prev_indexed.difference(&curr_indexed) {
        if curr_col_names.contains(name.as_str()) {
            ops.push(Operation::DropIndex {
                table: current.table.clone(),
                columns: vec![name.clone()],
                unique: false,
            });
        }
    }
    ops
}

pub fn diff(previous: &Snapshot, current: &Snapshot) -> Result<Vec<Operation>, MigrateError> {
    use std::collections::{BTreeMap, HashSet};

    // features #73 — views are diffed on a separate track, for a reason that runs
    // deeper than tidiness: every pass below exists to AVOID destroying data (the
    // rename heuristic, the safe-cast table, the data-preserving ALTER). A view
    // stores nothing, so none of that machinery applies to it, and letting a view
    // through it would be actively wrong — Pass 1 could "detect a rename" between a
    // dropped table and a created view and emit an ALTER against a relation that has
    // no rows to alter.
    //
    // So: hide the views from the table passes entirely, then handle them in Pass 5
    // with the only two operations a view can ever need.
    let view_prev = previous;
    let view_curr = current;
    let prev_tables = Snapshot {
        models: previous
            .models
            .iter()
            .filter(|m| m.view.is_none())
            .cloned()
            .collect(),
    };
    let curr_tables = Snapshot {
        models: current
            .models
            .iter()
            .filter(|m| m.view.is_none())
            .cloned()
            .collect(),
    };
    let previous = &prev_tables;
    let current = &curr_tables;

    let prev_by_name: BTreeMap<&str, &ModelMeta> = previous
        .models
        .iter()
        .map(|m| (m.name.as_str(), m))
        .collect();
    let curr_by_name: BTreeMap<&str, &ModelMeta> = current
        .models
        .iter()
        .map(|m| (m.name.as_str(), m))
        .collect();

    let mut ops: Vec<Operation> = Vec::new();

    // gaps.md #93: every table rename `diff` decides on (old_table → new_table),
    // recorded so Pass 4 can rename the parent's M2M junctions instead of
    // dropping + recreating them (which would destroy every relationship row).
    let mut renamed_tables: BTreeMap<String, String> = BTreeMap::new();

    // ---- Pass 0: Walk models present in both snapshots (same NAME). ----
    // Same-name models with a different table produce a first-pass rename.
    // Same-name models with identical table+columns produce nothing.
    // Same-name models with column changes produce column-level ops.

    let mut drop_candidates: Vec<&ModelMeta> = Vec::new(); // in prev, not curr
    let mut create_candidates: Vec<&ModelMeta> = Vec::new(); // in curr, not prev

    // Creates and column-level diffs, in deterministic name order.
    for (name, curr) in &curr_by_name {
        match prev_by_name.get(name) {
            None => {
                // In current but not previous — might be a create or a first-pass rename.
                create_candidates.push(curr);
            }
            Some(prev) if prev.table != curr.table => {
                // Same struct name, different table name → first-pass rename.
                println!(
                    "umbral makemigrations: rename detected (struct-name match): \
                     table `{}` → `{}`",
                    prev.table, curr.table
                );
                ops.push(Operation::RenameTable {
                    from: prev.table.clone(),
                    to: curr.table.clone(),
                });
                renamed_tables.insert(prev.table.clone(), curr.table.clone());
                // After the rename the columns might also have changed; diff them.
                let col_ops = diff_columns(name, prev, curr)?;
                ops.extend(col_ops);
                // ...and the table-level constraints (unique_together/indexes).
                ops.extend(diff_indexes(prev, curr));
            }
            Some(prev) if prev == curr => {}
            Some(prev) => {
                ops.extend(diff_columns(name, prev, curr)?);
                // Constraint-only deltas (a new/removed unique_together or
                // composite index with no column change) — otherwise silent.
                ops.extend(diff_indexes(prev, curr));
            }
        }
    }

    // Drops — models in prev but not curr (by NAME).
    for (name, prev) in &prev_by_name {
        if !curr_by_name.contains_key(name) {
            drop_candidates.push(prev);
        }
    }

    // ---- Pass 1: Column-shape heuristic for unpaired drops + creates. ----
    // A sorted, canonical serialisation of (name, ty, nullable, fk_target)
    // is the "shape" fingerprint. Bit-identical shapes → likely a model
    // rename where the struct name also changed.

    // audit_2 H23 — a bit-identical column shape between a dropped and a
    // created model is genuinely ambiguous (rename vs. two unrelated models).
    // The pre-H23 code auto-emitted a `RenameTable` with only an `eprintln!`,
    // silently handing one model's rows to another and skipping the intended
    // drop. Now the ambiguity is resolved by explicit operator intent: `assume`
    // restores auto-pairing, `independent` treats the pair as unrelated
    // (drop + create), and the unset default fails closed so no destructive
    // guess is ever applied silently.
    let intent = rename_intent();
    let mut paired_drop_tables: HashSet<&str> = HashSet::new();
    let mut paired_create_tables: HashSet<&str> = HashSet::new();

    'creates: for create in &create_candidates {
        let create_shape = column_shape(&create.fields);
        for drop in &drop_candidates {
            if paired_drop_tables.contains(drop.table.as_str()) {
                continue;
            }
            if column_shape(&drop.fields) != create_shape {
                continue;
            }
            match intent {
                RenameIntent::Assume => {
                    eprintln!(
                        "umbral makemigrations: rename ASSUMED (column-shape match): \
                         `{}` → `{}` — moving the old table's rows to the new name. Set \
                         UMBRAL_MIGRATIONS_ASSUME_RENAMES=independent if these are unrelated \
                         models that merely share a shape.",
                        drop.table, create.table
                    );
                    ops.push(Operation::RenameTable {
                        from: drop.table.clone(),
                        to: create.table.clone(),
                    });
                    renamed_tables.insert(drop.table.clone(), create.table.clone());
                    paired_drop_tables.insert(drop.table.as_str());
                    paired_create_tables.insert(create.table.as_str());
                    continue 'creates;
                }
                RenameIntent::Independent => {
                    eprintln!(
                        "umbral makemigrations: column-shape match `{}` ↔ `{}` treated as \
                         UNRELATED (drop + create) per UMBRAL_MIGRATIONS_ASSUME_RENAMES=\
                         independent. Set it to `assume` (or hand-write a RenameTable) if this \
                         is actually a rename — otherwise `{}`'s rows are dropped.",
                        drop.table, create.table, drop.table
                    );
                    // Leave both unpaired → Pass 2 creates, Pass 3 drops.
                    continue 'creates;
                }
                RenameIntent::Undecided => {
                    return Err(MigrateError::AmbiguousRename {
                        from_table: drop.table.clone(),
                        to_table: create.table.clone(),
                    });
                }
            }
        }
    }

    // ---- Pass 2: Emit plain CreateTable for unpaired creates. ----
    //
    // Sort the create list topologically by FK dependency so that a
    // table referenced by another table in this batch is created first.
    // Without this, Postgres rejects the second CreateTable with
    // `relation "<target>" does not exist`. (SQLite tolerates the wrong
    // order when `foreign_keys=OFF`, the historical default; once
    // we turned foreign_keys ON in connect_sqlite, SQLite agrees with
    // Postgres on the order requirement.)
    //
    // Kahn's algorithm on (table → set of FK-target tables that are
    // ALSO in the create batch). Self-references and FK targets outside
    // the batch are skipped (they're either harmless or already exist
    // by the time this migration runs).
    let creates: Vec<&&ModelMeta> = create_candidates
        .iter()
        .filter(|c| !paired_create_tables.contains(c.table.as_str()))
        .collect();
    let batch_tables: HashSet<&str> = creates.iter().map(|c| c.table.as_str()).collect();
    let mut deps: BTreeMap<&str, HashSet<&str>> = BTreeMap::new();
    for create in &creates {
        let mut in_batch: HashSet<&str> = HashSet::new();
        for col in &create.fields {
            if let Some(target) = col.fk_target.as_deref()
                && target != create.table.as_str()
                && batch_tables.contains(target)
            {
                in_batch.insert(target);
            }
        }
        deps.insert(create.table.as_str(), in_batch);
    }
    // Kahn: repeatedly pop tables with no remaining deps in the batch.
    // BTreeMap iteration is alphabetical → ties break alphabetically,
    // keeping the output stable.
    let mut ordered: Vec<&&ModelMeta> = Vec::with_capacity(creates.len());
    while !deps.is_empty() {
        let ready: Vec<&str> = deps
            .iter()
            .filter(|(_, d)| d.is_empty())
            .map(|(t, _)| *t)
            .collect();
        if ready.is_empty() {
            // Cyclic FK or other unresolvable dep — fall through to
            // the original order rather than dropping models. A cycle
            // here means the user's schema can't be created with
            // plain CreateTable anyway (Postgres needs deferrable
            // constraints), so we surface the user-visible error at
            // apply time instead of silently looping.
            for create in &creates {
                if deps.contains_key(create.table.as_str()) {
                    ordered.push(create);
                }
            }
            break;
        }
        for t in &ready {
            if let Some(create) = creates.iter().find(|c| c.table.as_str() == *t) {
                ordered.push(create);
            }
            deps.remove(t);
        }
        for (_, set) in deps.iter_mut() {
            for t in &ready {
                set.remove(t);
            }
        }
    }
    for create in ordered {
        ops.push(Operation::CreateTable {
            table: create.table.clone(),
            columns: create.fields.clone(),
            unique_together: create.unique_together.clone(),
            indexes: create.indexes.clone(),
        });
    }

    // ---- Pass 3: Emit plain DropTable for unpaired drops. ----
    for drop in &drop_candidates {
        if !paired_drop_tables.contains(drop.table.as_str()) {
            ops.push(Operation::DropTable {
                table: drop.table.clone(),
            });
        }
    }

    // ---- Pass 4: Diff M2M relations. Closes the remaining BUG-16 gap. ----
    //
    // Treat each (parent_table, field_name) pair as a junction-table identity.
    // Compare the flattened set across snapshots and emit CreateM2MTable /
    // DropM2MTable per delta.
    //
    // gaps.md #93: when the PARENT model was renamed (Pass 0/1), its junction's
    // key moves from `(old_table, field)` to `(new_table, field)` — which would
    // otherwise read as one junction dropped and a different one created,
    // destroying every relationship row. Detect that case via `renamed_tables`
    // and emit a plain `RenameTable` on the junction instead. The junction's
    // columns are generic (`parent_id`/`child_id`) and its FK to the parent is
    // auto-updated by the parent's own rename, so a table rename is sufficient.
    let prev_m2m = collect_m2m_pairs(previous);
    let curr_m2m = collect_m2m_pairs(current);

    // Prev junction keys consumed by a junction rename below — skip their drop.
    let mut renamed_prev_junctions: HashSet<(String, String)> = HashSet::new();

    for (key, spec) in &curr_m2m {
        if prev_m2m.contains_key(key) {
            continue;
        }
        let (new_parent, field) = key;
        // Was this junction's parent renamed FROM some old table? If the prior
        // snapshot has the same field on that old parent, targeting the same
        // table, it's a junction rename, not a fresh create.
        let renamed_from = renamed_tables
            .iter()
            .find(|(_, new)| *new == new_parent)
            .and_then(|(old, _)| {
                let old_key = (old.clone(), field.clone());
                prev_m2m.get(&old_key).and_then(|old_spec| {
                    (old_spec.target_table == spec.target_table).then_some(old_key)
                })
            });
        if let Some(old_key) = renamed_from {
            let old_junction = prev_m2m[&old_key].junction_table.clone();
            ops.push(Operation::RenameTable {
                from: old_junction,
                to: spec.junction_table.clone(),
            });
            renamed_prev_junctions.insert(old_key);
            continue;
        }
        // New M2M field on an existing or new model. Resolve the
        // target's PK column from the current snapshot.
        match build_create_m2m_op(spec, current) {
            Ok(op) => ops.push(op),
            Err(e) => return Err(e),
        }
    }
    for (key, spec) in &prev_m2m {
        if curr_m2m.contains_key(key) || renamed_prev_junctions.contains(key) {
            continue;
        }
        // M2M field removed (or its parent was dropped). The junction
        // table goes away.
        ops.push(Operation::DropM2MTable {
            junction_table: spec.junction_table.clone(),
        });
    }

    // ---- Pass 5: views (features #73). ----
    //
    // Ordering is the whole feature. Drops go BEFORE the table ops and creates go
    // AFTER, because Postgres refuses to drop or retype a column that a live view
    // selects from — so a migration that alters `matchday.score` while a view reads
    // it fails unless the view is out of the way first, and is only whole again once
    // the view is back.
    let (view_drops, view_creates) = diff_views(view_prev, view_curr, &ops)?;
    let mut all = view_drops;
    all.extend(ops);
    all.extend(view_creates);
    Ok(all)
}

/// The relations a view's SQL selects from, recovered by scanning its body for the
/// names of relations we know about.
///
/// The SELECT body is an opaque string — nobody is writing a SQL parser here. But
/// the engine already knows every table and view name in the snapshot, so it can ask
/// the cheaper question: *does this view's SQL mention `matchday`?* A whole-word
/// match (so `matchday` does not match `matchday_team`) recovers the dependency edge
/// that ordering needs.
///
/// The failure modes are asymmetric, which is why this is worth doing:
/// - A **false positive** (the name appears in a string literal or a comment) costs
///   one needless `DROP VIEW` + `CREATE VIEW`. A view stores nothing. Nobody notices.
/// - A **false negative** would order a view before the table it reads, and the
///   migration fails at apply time with a clear "relation does not exist".
///
/// Both are safe. Neither can corrupt data. That asymmetry is what makes a heuristic
/// acceptable here and unacceptable in the table passes next door.
fn view_dependencies(sql: &str, known: &[String], self_table: &str) -> Vec<String> {
    let haystack = sql.to_ascii_lowercase();
    let bytes = haystack.as_bytes();
    let is_word = |b: u8| b.is_ascii_alphanumeric() || b == b'_';

    let mut deps = Vec::new();
    for name in known {
        if name == self_table {
            continue;
        }
        let needle = name.to_ascii_lowercase();
        if needle.is_empty() {
            continue;
        }
        let mut from = 0usize;
        while let Some(hit) = haystack[from..].find(&needle) {
            let start = from + hit;
            let end = start + needle.len();
            let before_ok = start == 0 || !is_word(bytes[start - 1]);
            let after_ok = end == bytes.len() || !is_word(bytes[end]);
            if before_ok && after_ok {
                deps.push(name.clone());
                break;
            }
            from = end;
        }
    }
    deps
}

/// Diff the view models of two snapshots into (drops, creates).
///
/// `table_ops` is what the table passes decided; a view that reads from a table
/// those ops touch is recreated even if its own SQL never changed.
fn diff_views(
    previous: &Snapshot,
    current: &Snapshot,
    table_ops: &[Operation],
) -> Result<(Vec<Operation>, Vec<Operation>), MigrateError> {
    use std::collections::{BTreeMap, HashSet};

    let view_models = |snap: &Snapshot| -> Vec<ModelMeta> {
        snap.models
            .iter()
            .filter(|m| m.view.is_some())
            .cloned()
            .collect()
    };
    let prev_views = view_models(previous);
    let curr_views = view_models(current);
    if prev_views.is_empty() && curr_views.is_empty() {
        return Ok((Vec::new(), Vec::new()));
    }

    let touched: HashSet<&str> = table_ops.iter().map(|o| o.table_name()).collect();
    let known: Vec<String> = current.models.iter().map(|m| m.table.clone()).collect();

    let deps: BTreeMap<&str, Vec<String>> = curr_views
        .iter()
        .map(|m| {
            (
                m.name.as_str(),
                view_dependencies(m.view.as_deref().unwrap_or(""), &known, &m.table),
            )
        })
        .collect();

    let prev_by_name: BTreeMap<&str, &ModelMeta> =
        prev_views.iter().map(|m| (m.name.as_str(), m)).collect();

    // Which views are stale? Either their own definition moved, or something they
    // read did.
    let mut recreate: HashSet<&str> = HashSet::new();
    for m in &curr_views {
        let definition_changed = match prev_by_name.get(m.name.as_str()) {
            None => true, // brand new, or was a table until this change
            Some(prev) => {
                prev.view != m.view || prev.materialized != m.materialized || prev.table != m.table
            }
        };
        let reads_a_touched_table = deps[m.name.as_str()]
            .iter()
            .any(|d| touched.contains(d.as_str()));
        if definition_changed || reads_a_touched_table {
            recreate.insert(m.name.as_str());
        }
    }

    // A view built on a view that is being recreated is itself stale. Iterate to a
    // fixpoint rather than assuming one level of nesting.
    loop {
        let mut grew = false;
        for m in &curr_views {
            if recreate.contains(m.name.as_str()) {
                continue;
            }
            let reads_a_stale_view = deps[m.name.as_str()].iter().any(|d| {
                curr_views
                    .iter()
                    .any(|v| &v.table == d && recreate.contains(v.name.as_str()))
            });
            if reads_a_stale_view {
                recreate.insert(m.name.as_str());
                grew = true;
            }
        }
        if !grew {
            break;
        }
    }

    // ---- Creates, in dependency order (a view after the views it reads). ----
    let mut to_create: Vec<&ModelMeta> = curr_views
        .iter()
        .filter(|m| recreate.contains(m.name.as_str()))
        .collect();
    to_create.sort_by(|a, b| a.name.cmp(&b.name)); // deterministic before topo

    let mut creates: Vec<Operation> = Vec::new();
    let mut placed: HashSet<&str> = HashSet::new();
    while placed.len() < to_create.len() {
        let before = placed.len();
        for m in &to_create {
            if placed.contains(m.table.as_str()) {
                continue;
            }
            let blocked = deps[m.name.as_str()].iter().any(|d| {
                to_create
                    .iter()
                    .any(|other| &other.table == d && !placed.contains(other.table.as_str()))
            });
            if blocked {
                continue;
            }
            placed.insert(m.table.as_str());
            creates.push(Operation::CreateView {
                name: m.table.clone(),
                sql: m.view.clone().unwrap_or_default(),
                materialized: m.materialized,
            });
        }
        if placed.len() == before {
            // A cycle. Two views cannot select from each other, so this means the
            // SQL scan found a self-referential edge we cannot honour. Name the
            // views rather than looping forever.
            let stuck: Vec<&str> = to_create
                .iter()
                .filter(|m| !placed.contains(m.table.as_str()))
                .map(|m| m.table.as_str())
                .collect();
            return Err(MigrateError::UnsupportedChange(format!(
                "views {stuck:?} form a dependency cycle — each one's SQL selects from \
                 another in the set, so there is no order in which they can be created. \
                 Break the cycle by inlining one of the definitions."
            )));
        }
    }

    // ---- Drops: every view we are about to recreate, plus every view that is gone
    // (removed, or converted back into a table). Emitted in reverse create order so
    // a dependant view is dropped before the view it reads.
    let mut drops: Vec<Operation> = Vec::new();
    let curr_view_names: HashSet<&str> = curr_views.iter().map(|m| m.name.as_str()).collect();
    let mut to_drop: Vec<&ModelMeta> = prev_views
        .iter()
        .filter(|m| {
            !curr_view_names.contains(m.name.as_str()) || recreate.contains(m.name.as_str())
        })
        .collect();
    // Reverse-topological by the CREATE order we just computed; anything not in it
    // (a removed view) sorts first, since nothing we keep can depend on it.
    let create_pos = |table: &str| -> usize {
        creates
            .iter()
            .position(|op| matches!(op, Operation::CreateView { name, .. } if name == table))
            .map(|i| usize::MAX - i)
            .unwrap_or(0)
    };
    to_drop.sort_by_key(|m| (create_pos(&m.table), m.table.clone()));
    for m in to_drop {
        drops.push(Operation::DropView {
            name: m.table.clone(),
            materialized: m.materialized,
        });
    }

    Ok((drops, creates))
}

/// A flat-resolved M2M descriptor used by [`diff`] to compare snapshots.
/// Owns its strings so it can be keyed in a map without lifetime
/// gymnastics.
#[derive(Debug, Clone)]
struct M2MPair {
    parent_table: String,
    parent_pk: String,
    field_name: String,
    target_table: String,
    junction_table: String,
}

/// Walk a snapshot and produce one [`M2MPair`] per declared M2M field.
/// Keyed on `(parent_table, field_name)` since that uniquely identifies
/// a junction table — two models can't share the same parent_table, and
/// one model can't declare two M2M fields with the same name.
fn collect_m2m_pairs(snap: &Snapshot) -> std::collections::BTreeMap<(String, String), M2MPair> {
    let mut out = std::collections::BTreeMap::new();
    for model in &snap.models {
        let parent_pk = model
            .fields
            .iter()
            .find(|c| c.primary_key)
            .map(|c| c.name.clone())
            .unwrap_or_else(|| "id".to_string());
        for rel in &model.m2m_relations {
            let key = (model.table.clone(), rel.field_name.clone());
            out.insert(
                key,
                M2MPair {
                    parent_table: model.table.clone(),
                    parent_pk: parent_pk.clone(),
                    field_name: rel.field_name.clone(),
                    target_table: rel.target_table.clone(),
                    junction_table: format!("{}_{}", model.table, rel.field_name),
                },
            );
        }
    }
    out
}

/// Lift an [`M2MPair`] into a fully-specified [`Operation::CreateM2MTable`].
/// The target table's PK column name is resolved from `current` (the
/// snapshot the diff is computing toward) — without it the DDL would
/// reference a column the child table doesn't have.
fn build_create_m2m_op(spec: &M2MPair, current: &Snapshot) -> Result<Operation, MigrateError> {
    // Resolve the target's PK from the current snapshot, FALLING BACK to the
    // global model registry. Migrations are generated per-plugin, so a
    // CROSS-PLUGIN M2M (parent owned by app A, target model owned by app B —
    // e.g. a tenant model with an M2M to a SHARED lookup table, or any app's
    // M2M to `umbral-auth`'s `User`) has its target in a *different* plugin's
    // snapshot, absent from `current`. The global registry sees every
    // registered model, so the junction DDL resolves the child PK no matter
    // which plugin owns the target. (Cross-plugin FK ordering already lets the
    // junction migration run after the target table's own migration.)
    let pk_col_and_ty = |m: &ModelMeta| -> (String, crate::orm::SqlType) {
        let pk = m.fields.iter().find(|c| c.primary_key);
        (
            pk.map(|c| c.name.clone())
                .unwrap_or_else(|| "id".to_string()),
            pk.map(|c| c.ty).unwrap_or(crate::orm::SqlType::BigInt),
        )
    };
    let (child_pk_col, child_ty) = current
        .models
        .iter()
        .find(|m| m.table == spec.target_table)
        .map(&pk_col_and_ty)
        .or_else(|| {
            // Non-panicking global lookup. `registered_models()` panics if the
            // registry isn't initialised (unit tests that call `diff` directly,
            // with no `App::build`); a `None` registry simply yields no global
            // fallback, so a TRULY-unregistered target is still rejected below.
            REGISTRY.get().and_then(|reg| {
                reg.iter()
                    .find(|(_, m)| m.table == spec.target_table)
                    .map(|(_, m)| pk_col_and_ty(m))
            })
        })
        .ok_or_else(|| {
            MigrateError::UnsupportedChange(format!(
                "M2M `{}.{}` targets table `{}` which is not registered \
                 anywhere — register the target model via \
                 `AppBuilder::model::<{}>()` or its owning plugin.",
                spec.parent_table, spec.field_name, spec.target_table, spec.target_table,
            ))
        })?;
    let parent_model = current
        .models
        .iter()
        .find(|m| m.table == spec.parent_table)
        .expect("parent model exists in snapshot — collect_m2m_pairs iterated it");
    let parent_ty = parent_model
        .fields
        .iter()
        .find(|c| c.primary_key)
        .map(|c| c.ty)
        .unwrap_or(crate::orm::SqlType::BigInt);
    Ok(Operation::CreateM2MTable {
        junction_table: spec.junction_table.clone(),
        parent_table: spec.parent_table.clone(),
        parent_col: spec.parent_pk.clone(),
        child_table: spec.target_table.clone(),
        child_col: child_pk_col,
        parent_ty,
        child_ty,
    })
}

/// Compute a canonical, sorted column-shape fingerprint for rename
/// heuristic detection in `diff`. Two models whose column fingerprints
/// are identical are candidates for a rename (second-pass detection).
///
/// The fingerprint is a sorted `Vec` of `(name, ty, nullable, fk_target)`
/// tuples. Sorting by name ensures the fingerprint is independent of
/// declaration order.
fn column_shape(fields: &[Column]) -> Vec<(String, SqlType, bool, Option<String>)> {
    let mut shape: Vec<(String, SqlType, bool, Option<String>)> = fields
        .iter()
        .map(|c| (c.name.clone(), c.ty, c.nullable, c.fk_target.clone()))
        .collect();
    shape.sort_by(|a, b| a.0.cmp(&b.0));
    shape
}

/// Type changes the migration engine can apply without user
/// intervention. The contract: every entry in this whitelist must be
/// data-preserving on both backends.
///
/// SQLite handles every entry trivially via the table-recreation
/// dance: its dynamic typing means whatever lives in a column today
/// reads back fine under a new column type affinity. Postgres needs
/// `ALTER COLUMN ... TYPE new_type USING column::new_type`, which the
/// renderer emits when this returns `true`.
///
/// What's *not* here is deliberate:
/// - `Text -> BigInt` / numeric parses can fail at runtime on non-
///   numeric rows. Force the user to write the migration so they own
///   the validation.
/// - Bigger int -> smaller int truncates silently.
/// - `Text -> Date` / `Text -> Uuid` are format-dependent.
/// - Anything -> JSON. Even if existing rows are JSON-shaped, that's
///   the user's invariant to assert.
fn is_safe_cast(from: SqlType, to: SqlType) -> bool {
    use SqlType::*;
    if from == to {
        return true;
    }
    match (from, to) {
        // Stringify: every scalar serialises to text losslessly. Read-
        // path code that wants the typed value parses it back; the
        // cast itself never fails.
        (
            SmallInt | Integer | BigInt | Real | Double | Boolean | Date | Time | Timestamptz
            | Timestamp | Uuid | Inet | Cidr | MacAddr | ForeignKey,
            Text,
        ) => true,
        // A naive/aware timestamp swap keeps the same wall-clock text, so the
        // cast is data-preserving in both directions.
        (Timestamp, Timestamptz) | (Timestamptz, Timestamp) => true,
        // Integer widening — no data loss.
        (SmallInt, Integer | BigInt) => true,
        (Integer, BigInt) => true,
        // Float widening.
        (Real, Double) => true,
        // ForeignKey is stored as BigInt under the hood, so the two
        // directions are storage-identical. The Rust-side type is
        // different but the bytes on disk are not.
        (ForeignKey, BigInt) => true,
        (BigInt, ForeignKey) => true,
        _ => false,
    }
}

/// Postgres type name for an `ALTER COLUMN ... TYPE <name> USING …`
/// clause. Matches what sea-query's `PostgresQueryBuilder` emits for
/// the same `SqlType` inside a `CREATE TABLE`, so the resulting
/// schema after the alter is identical to a freshly created table.
/// The full Postgres type for a column, INCLUDING the varchar bound. A
/// `Text` column with `max_length > 0` is `character varying(n)` — the same
/// mapping the CreateTable path uses — so alters land on the type the table
/// would have been created with, not a bare `text` that silently drops the
/// bound.
fn postgres_type_sql(col: &Column) -> String {
    match col.ty {
        SqlType::Text if col.max_length > 0 => format!("character varying({})", col.max_length),
        // PostGIS spatial types carry their subtype + SRID in the type modifier,
        // e.g. `geometry(Point,4326)`. Reuse the same renderer the CreateTable
        // path uses so an ALTER lands on the identical column type.
        SqlType::Geometry(spec) => crate::backend::pg_spatial_type("geometry", spec),
        SqlType::Geography(spec) => crate::backend::pg_spatial_type("geography", spec),
        // Caller-chosen numeric dimensions, so an ALTER lands on the same
        // `numeric(p,s)` the CreateTable path emits.
        SqlType::DecimalN(spec) => format!("numeric({}, {})", spec.precision, spec.scale),
        _ => postgres_type_name(col.ty).to_string(),
    }
}

fn postgres_type_name(ty: SqlType) -> &'static str {
    use SqlType::*;
    match ty {
        SmallInt => "smallint",
        Integer => "integer",
        BigInt | ForeignKey => "bigint",
        Real => "real",
        Double => "double precision",
        Boolean => "boolean",
        Text => "text",
        Date => "date",
        Time => "time",
        // sea-query's Postgres builder emits `timestamp with time zone`
        // for the equivalent column type; both spellings are accepted
        // by Postgres, but mirroring the builder keeps the surface
        // consistent if a test ever round-trips DDL.
        Timestamptz => "timestamp with time zone",
        Timestamp => "timestamp without time zone",
        Uuid => "uuid",
        Json => "jsonb",
        Inet => "inet",
        Cidr => "cidr",
        MacAddr => "macaddr",
        // gaps2 #70: text-backed Postgres types. `bit varying` mirrors
        // what sea-query's builder emits for the CREATE TABLE path.
        Xml => "xml",
        Ltree => "ltree",
        Bit => "bit varying",
        FullText => "tsvector",
        Bytes => "bytea",
        // BUG-10: NUMERIC(19, 4) — same dimensions as the CREATE TABLE
        // build path. Used by the `ALTER COLUMN ... TYPE ...` render
        // when the safe-cast diff allows transitioning to/from
        // Decimal.
        Decimal => "numeric(19, 4)",
        // Arbitrary-precision `numeric` (no dimensions). Mirrors the
        // unbounded `ColumnType::Decimal(None)` the create path emits.
        BigDecimal => "numeric",
        // Bare fallback; the dimensioned `numeric(p,s)` form is rendered by
        // `postgres_type_sql`, which special-cases DecimalN before reaching here.
        DecimalN(_) => "numeric",
        // Bare spatial base type. The subtype+SRID-aware form is rendered by
        // `postgres_type_sql`, which special-cases these before reaching here;
        // this arm is the unconstrained fallback and keeps the match total.
        Geometry(_) => "geometry",
        Geography(_) => "geography",
        // Arrays render as `<inner>[]` in Postgres. The migration
        // engine doesn't model nested element types deeply enough to
        // emit a precise inner type here at v1; fall back to `text[]`
        // and rely on the column-def renderer for the real shape when
        // recreating the column.
        Array(_) => "text[]",
    }
}

/// Per-model column diff. Same-name columns whose type or nullable
/// flag changed return `UnsafeAlter` (no `AlterColumn` until M8 v1.1
/// covers the table-recreation dance for SQLite plus native ALTER for
/// Postgres). New-named columns emit `AddColumn`; missing-name columns
/// emit `DropColumn`. The ordering is: drops first, then adds, so a
/// rename-as-drop+add doesn't violate a uniqueness constraint mid-
/// migration on a single-row table.
fn diff_columns(
    model: &str,
    previous: &ModelMeta,
    current: &ModelMeta,
) -> Result<Vec<Operation>, MigrateError> {
    use std::collections::BTreeMap;

    let prev_cols: BTreeMap<&str, &Column> = previous
        .fields
        .iter()
        .map(|c| (c.name.as_str(), c))
        .collect();
    let curr_cols: BTreeMap<&str, &Column> = current
        .fields
        .iter()
        .map(|c| (c.name.as_str(), c))
        .collect();

    // Walk the intersection by name. Two questions per shared column:
    //   - did the type change? If so, is the change in the safe-cast
    //     whitelist (e.g. BigInt -> Text, SmallInt -> Integer)? Safe
    //     casts emit AlterColumn; unsafe ones still UnsafeAlter so the
    //     user is forced to write the data-preserving migration by
    //     hand.
    //   - did the nullable flag flip? AlterColumn either way.
    // Primary-key changes still UnsafeAlter (a PK rebuild is its own
    // dance and isn't shipped yet).
    let mut alter_columns: Vec<&str> = Vec::new();
    // Columns whose `#[umbral(help = "...")]` changed (gaps3 #43).
    let mut comment_columns: Vec<&str> = Vec::new();
    for (name, prev_col) in &prev_cols {
        if let Some(curr_col) = curr_cols.get(name) {
            if prev_col.primary_key != curr_col.primary_key {
                return Err(MigrateError::UnsafeAlter {
                    model: model.to_string(),
                    column: (*name).to_string(),
                    reason: "primary-key flips need a manual data-preserving migration".to_string(),
                });
            }
            let type_changed = prev_col.ty != curr_col.ty;
            if type_changed && !is_safe_cast(prev_col.ty, curr_col.ty) {
                return Err(MigrateError::UnsafeAlter {
                    model: model.to_string(),
                    column: (*name).to_string(),
                    reason: format!(
                        "type change {prev_ty:?} -> {curr_ty:?} is not in the safe-cast whitelist — write a data-preserving migration by hand",
                        prev_ty = prev_col.ty,
                        curr_ty = curr_col.ty,
                    ),
                });
            }
            if prev_col.nullable && !curr_col.nullable && curr_col.default.is_empty() {
                return Err(MigrateError::UnsafeAlter {
                    model: model.to_string(),
                    column: (*name).to_string(),
                    reason: "nullable → NOT NULL requires a default/backfill before tightening; otherwise existing NULL rows abort the migration".to_string(),
                });
            }
            if !prev_col.unique && curr_col.unique {
                return Err(MigrateError::UnsafeAlter {
                    model: model.to_string(),
                    column: (*name).to_string(),
                    reason: "adding UNIQUE to an existing column requires a duplicate pre-check/backfill migration; otherwise existing duplicate values abort the migration".to_string(),
                });
            }
            // gaps3 #43: `help` DOES have a DB effect now — it renders as a
            // Postgres `COMMENT ON COLUMN` — but it is not a column rewrite.
            // It gets its own cheap op rather than dragging the column through
            // an `AlterColumn` (a full table-recreation dance on SQLite).
            if prev_col.help != curr_col.help {
                comment_columns.push(*name);
            }

            // `max_length` IS schema-meaningful for Text columns: CreateTable
            // renders `Text + max_length > 0` as `character varying(n)` on
            // Postgres, so treating it as UI-only let models drift from DDL —
            // raising a bound never emitted an ALTER, and every FRESH database
            // enforced the stale one (found live loading TaskFlow's dev dump:
            // four columns rejected rows the app had been writing for weeks;
            // SQLite hid it because its varchar bounds are advisory).
            // WIDENING (n -> bigger, or n -> unbounded) is a lossless in-place
            // alter; NARROWING (smaller, or unbounded -> bounded) can abort on
            // existing rows mid-migration, so it stays a hand-written job.
            let length_changed = !type_changed
                && prev_col.ty == SqlType::Text
                && prev_col.max_length != curr_col.max_length;
            if length_changed
                && curr_col.max_length != 0
                && (prev_col.max_length == 0 || curr_col.max_length < prev_col.max_length)
            {
                return Err(MigrateError::UnsafeAlter {
                    model: model.to_string(),
                    column: (*name).to_string(),
                    reason: format!(
                        "narrowing max_length {prev} -> {curr} can abort on existing oversized rows — write a data-preserving (truncate/validate) migration by hand",
                        prev = if prev_col.max_length == 0 {
                            "unbounded".to_string()
                        } else {
                            prev_col.max_length.to_string()
                        },
                        curr = curr_col.max_length,
                    ),
                });
            }

            // Any schema-meaningful field change triggers AlterColumn.
            // UI-only flags (`noform`, `noedit`,
            // `is_string_repr`, `is_multichoice`) are intentionally
            // excluded — they affect admin / OpenAPI rendering but
            // not the database schema, so emitting an ALTER would do
            // no DB work. The single-column `index` flag is ALSO excluded
            // here: an index add/remove is not a column rewrite. Folding it
            // into `AlterColumn` created no index on Postgres (its native
            // ALTER handles TYPE/nullable/UNIQUE/DEFAULT/FK/CHECK but not
            // indexes) and forced a full table-recreation dance on SQLite.
            // `diff_indexes` now emits a proper `AddIndex`/`DropIndex` for it,
            // which is correct and cheap on both backends.
            if type_changed
                || length_changed
                || prev_col.nullable != curr_col.nullable
                || prev_col.fk_target != curr_col.fk_target
                || prev_col.unique != curr_col.unique
                || prev_col.default != curr_col.default
                || prev_col.choices != curr_col.choices
                || prev_col.choice_labels != curr_col.choice_labels
                || prev_col.on_delete != curr_col.on_delete
                || prev_col.on_update != curr_col.on_update
            {
                alter_columns.push(*name);
            }
        }
    }

    let mut ops: Vec<Operation> = Vec::new();

    // AlterColumn ops first, in name order. One AlterColumn per
    // changed column; each carries the full new schema so the render
    // can rebuild without further context. Multiple nullable flips on
    // one table generate multiple AlterColumns; the apply loop runs
    // them sequentially (each is a table-recreation, so back-to-back
    // alters drop and recreate twice; the cost is acceptable while
    // M5.1 ships the simple case).
    //
    // audit_2 H21: the SQLite recreation dance rebuilds the table by
    // `INSERT INTO tmp (new_columns) SELECT new_columns FROM <old>`, so
    // every name in `new_columns` MUST exist in the old table at alter
    // time. Using `current.fields` here broke any diff that combined an
    // alter with an add or drop on the same table: a newly-ADDED column
    // is in `current` but not the old table (the SELECT hits "no such
    // column"), and a DROPPED column is absent from `current` so the
    // rebuild removed it early — the subsequent `DropColumn` op then
    // failed on the already-gone column. Instead, shape `new_columns`
    // like the PREVIOUS table (exactly the old table's columns), but
    // apply the CURRENT definition to every column that survives so the
    // type/nullable/default change still lands. A to-be-dropped column
    // keeps its old definition and rides through the rebuild; its
    // `DropColumn` op (emitted below, so it runs after) removes it. A
    // to-be-added column is intentionally absent; its `AddColumn` op
    // (also below) adds it after. Ordering alter → drop → add is what
    // the existing op emission already does.
    let new_columns: Vec<Column> = previous
        .fields
        .iter()
        .map(|prev_col| {
            curr_cols
                .get(prev_col.name.as_str())
                .map(|c| (*c).clone())
                .unwrap_or_else(|| prev_col.clone())
        })
        .collect();
    let prev_columns_snapshot: Vec<Column> = previous.fields.clone();
    for name in alter_columns {
        ops.push(Operation::AlterColumn {
            table: current.table.clone(),
            column: name.to_string(),
            new_columns: new_columns.clone(),
            prev_columns: Some(prev_columns_snapshot.clone()),
            // audit_2 core-migrate #10: carry the table-level constraints so the
            // SQLite recreation dance re-creates them instead of dropping them.
            unique_together: current.unique_together.clone(),
            indexes: current.indexes.clone(),
        });
    }

    // gaps3 #43: comment ops, in name order. After any `AlterColumn` on the same
    // column, because SQLite's alter recreates the table and Postgres's rewrites
    // the column — a comment set first would be describing a column that is
    // about to be replaced.
    for name in comment_columns {
        ops.push(Operation::SetColumnComment {
            table: current.table.clone(),
            column: name.to_string(),
            comment: curr_cols
                .get(name)
                .map(|c| c.help.clone())
                .unwrap_or_default(),
        });
    }

    // Collect the dropped + added column names. We need both lists in
    // memory so the rename heuristic can pair them.
    let mut dropped: Vec<&Column> = Vec::new();
    let mut added: Vec<&Column> = Vec::new();
    for (name, prev_col) in &prev_cols {
        if !curr_cols.contains_key(name) {
            dropped.push(prev_col);
        }
    }
    for col in &current.fields {
        if !prev_cols.contains_key(col.name.as_str()) {
            added.push(col);
        }
    }

    // Gap 88 — column rename detection. When the same diff yields
    // exactly one drop and one add whose column shapes (sans name)
    // match bit-for-bit, the most likely interpretation is a rename
    // rather than a coincidental drop+add of two unrelated columns.
    // Emit RenameColumn instead and warn the user so they can
    // verify. Anything more ambiguous (multiple drops or adds, or
    // mismatched shapes) falls back to the drop+add path so the
    // rename is never inferred against the user's actual intent.
    //
    // The heuristic deliberately stays conservative: some tools ask
    // interactively in this case; we don't have
    // a prompt at v1, so the conservative auto-pair is the safest
    // shape. Users can always override by writing the
    // `RenameColumn` op into the migration file by hand.
    let mut paired_drop: Option<&str> = None;
    let mut paired_add: Option<&str> = None;
    if dropped.len() == 1 && added.len() == 1 {
        let d = dropped[0];
        let a = added[0];
        if column_shape_matches(d, a) {
            eprintln!(
                "umbral makemigrations: column rename detected on `{}`: \
                 `{}` → `{}` — verify this is a rename and not a coincidental \
                 shape match; edit the migration file if it's wrong",
                current.table, d.name, a.name,
            );
            ops.push(Operation::RenameColumn {
                table: current.table.clone(),
                from: d.name.clone(),
                to: a.name.clone(),
                column: Some(a.clone()),
            });
            paired_drop = Some(d.name.as_str());
            paired_add = Some(a.name.as_str());
        }
    }

    // Drops first so a same-position add can reuse the column slot.
    for col in &dropped {
        if Some(col.name.as_str()) == paired_drop {
            continue;
        }
        ops.push(Operation::DropColumn {
            table: current.table.clone(),
            column: col.name.clone(),
        });
    }

    // Then adds, in current declaration order so the schema retains
    // the user-written column order even after re-runs.
    for col in &added {
        if Some(col.name.as_str()) == paired_add {
            continue;
        }
        // Gap 97 — refuse to add a NOT NULL column without a default
        // (and without `auto_now_add` / `auto_now`, which fill the
        // column server-side at insert). SQLite + Postgres both
        // reject the ADD on a non-empty table; we surface the same
        // failure at diff time with actionable guidance so the user
        // doesn't ship a migration that bricks every deploy.
        if !col.nullable
            && col.default.is_empty()
            && !col.auto_now_add
            && !col.auto_now
            && !col.primary_key
        {
            return Err(MigrateError::UnsafeAlter {
                model: model.to_string(),
                column: col.name.clone(),
                reason: format!(
                    "adding NOT NULL column `{}` without a default to existing \
                     table `{}` would fail on every populated row. Pick one: \
                     (a) make the field `Option<T>`, (b) add `#[umbral(default = \
                     \"...\")]` so the migration backfills, or (c) add \
                     `#[umbral(auto_now_add)]` for timestamp columns",
                    col.name, current.table,
                ),
            });
        }
        ops.push(Operation::AddColumn {
            table: current.table.clone(),
            column: (*col).clone(),
        });
    }

    Ok(ops)
}

/// Gap 88 helper: compare two column snapshots for shape identity (every
/// schema-meaningful attribute except `name`). Used by the rename-
/// detection heuristic — bit-identical attrs are the signal that a
/// dropped column matches an added column and the diff is actually a
/// rename. Excludes UI-only flags (`noform`, `noedit`, `max_length`,
/// `is_string_repr`, `help`, `example`, `slug_from`) for the same
/// reason the AlterColumn diff excludes them: they have no DB effect.
fn column_shape_matches(a: &Column, b: &Column) -> bool {
    a.ty == b.ty
        && a.primary_key == b.primary_key
        && a.nullable == b.nullable
        && a.fk_target == b.fk_target
        && a.choices == b.choices
        && a.choice_labels == b.choice_labels
        && a.default == b.default
        && a.is_multichoice == b.is_multichoice
        && a.unique == b.unique
        && a.on_delete == b.on_delete
        && a.on_update == b.on_update
        && a.index == b.index
        && a.auto_now_add == b.auto_now_add
        && a.auto_now == b.auto_now
        && a.min == b.min
        && a.max == b.max
        && a.text_format == b.text_format
}

/// Pick the suffix used in a migration filename. Single-op migrations
/// get a descriptive suffix; multi-op migrations fall back to `auto`.
fn suffix_for(ops: &[Operation]) -> String {
    match ops {
        [Operation::CreateTable { table, .. }] => format!("create_{table}"),
        [Operation::DropTable { table }] => format!("drop_{table}"),
        // features #73. The drop+create pair is what an EDIT to a view's SQL looks
        // like — by far the commonest view migration — so name it for what the user
        // did, not for the two statements it lowers to.
        [Operation::CreateView { name, .. }] => format!("create_view_{name}"),
        [Operation::DropView { name, .. }] => format!("drop_view_{name}"),
        [
            Operation::DropView { name: dropped, .. },
            Operation::CreateView { name: created, .. },
        ] if dropped == created => format!("update_view_{created}"),
        [Operation::AddColumn { table, column }] => format!("add_{}_{}", table, column.name),
        [Operation::DropColumn { table, column }] => format!("drop_{table}_{column}"),
        [Operation::AlterColumn { table, column, .. }] => format!("alter_{table}_{column}"),
        [Operation::RenameTable { from, to }] => format!("rename_{from}_to_{to}"),
        [
            Operation::RenameColumn {
                table, from, to, ..
            },
        ] => format!("rename_{table}_{from}_to_{to}"),
        [Operation::SetColumnComment { table, column, .. }] => {
            format!("comment_{table}_{column}")
        }
        [Operation::RunSql { .. }] => "run_sql".to_string(),
        [Operation::AddIndex { table, columns, .. }] => {
            format!("add_index_{table}_{}", columns.join("_"))
        }
        [Operation::DropIndex { table, columns, .. }] => {
            format!("drop_index_{table}_{}", columns.join("_"))
        }
        _ => "auto".to_string(),
    }
}

/// Create the tracking table if it isn't there already. The DDL is
/// dialect-neutral (TEXT + composite PK is valid SQL on both shipped
/// backends), but the executor type isn't — sqlx::query is generic
/// over the database, so each backend gets its own thin wrapper.
///
/// Kept inline because this table is a chicken-and-egg case: every
/// other migration needs the tracking row written, so the table
/// itself can't be a migration.
async fn ensure_tracking_table_sqlite(pool: &sqlx::SqlitePool) -> Result<(), MigrateError> {
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS umbral_migrations (
            plugin TEXT NOT NULL,
            name TEXT NOT NULL,
            applied_at TEXT NOT NULL,
            snapshot_hash TEXT NOT NULL,
            PRIMARY KEY (plugin, name)
        )",
    )
    .execute(pool)
    .await?;
    Ok(())
}

/// Postgres counterpart to [`ensure_tracking_table_sqlite`].
async fn ensure_tracking_table_postgres(pool: &sqlx::PgPool) -> Result<(), MigrateError> {
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS umbral_migrations (
            plugin TEXT NOT NULL,
            name TEXT NOT NULL,
            applied_at TEXT NOT NULL,
            snapshot_hash TEXT NOT NULL,
            PRIMARY KEY (plugin, name)
        )",
    )
    .execute(pool)
    .await?;
    Ok(())
}

/// Pull the set of `(plugin, name)` tuples already recorded in the
/// tracking table (SQLite).
async fn applied_names_sqlite(
    pool: &sqlx::SqlitePool,
) -> Result<std::collections::HashSet<(String, String)>, MigrateError> {
    let rows: Vec<(String, String)> = sqlx::query_as("SELECT plugin, name FROM umbral_migrations")
        .fetch_all(pool)
        .await?;
    Ok(rows.into_iter().collect())
}

/// Postgres counterpart to [`applied_names_sqlite`].
async fn applied_names_postgres(
    pool: &sqlx::PgPool,
) -> Result<std::collections::HashSet<(String, String)>, MigrateError> {
    let rows: Vec<(String, String)> = sqlx::query_as("SELECT plugin, name FROM umbral_migrations")
        .fetch_all(pool)
        .await?;
    Ok(rows.into_iter().collect())
}

/// Render one operation to a list of SQL statements via sea-query.
///
/// Dispatches on the ambient backend's [`crate::backend::active`]
/// name; SQLite and Postgres are the two shipped dialects. Most ops
/// produce one statement; `AlterColumn` produces either the SQLite
/// table-recreation dance (`CREATE _umbral_new` + `INSERT ... SELECT`
/// + `DROP` + `RENAME`) or a single native `ALTER TABLE ... ALTER
/// COLUMN ... SET/DROP NOT NULL` on Postgres.
///
/// The apply loop in `run_in` executes each statement in order inside
/// the same transaction.
///
/// `AddColumn` ignores the `primary_key` flag: neither SQLite nor
/// Postgres lets a primary key be added to an existing table without
/// a table-recreation step, and the autodetector won't route a
/// pk-flagged column through `AddColumn` anyway. A hand-edited
/// migration that sets the flag is taken to mean "the user is taking
/// responsibility".
fn render_operation(op: &Operation) -> Vec<String> {
    render_operation_for(op, crate::backend::active().name())
}

fn should_emit_btree_index(col: &Column) -> bool {
    !col.primary_key
        && !col.unique
        && (col.index || matches!(col.ty, SqlType::ForeignKey) || col.name == "deleted_at")
}

/// A PostGIS spatial column — indexed with GiST rather than B-tree.
fn is_spatial(col: &Column) -> bool {
    matches!(col.ty, SqlType::Geometry(_) | SqlType::Geography(_))
}

/// Render one operation against an explicit backend name. The
/// dispatching seam — the public [`render_operation`] is just
/// `render_operation_for(op, backend::active().name())`. Splitting
/// the two lets tests render Postgres DDL without installing the
/// process-wide ambient backend (the `OnceLock` can only be set once,
/// so `App::build` and tests would otherwise collide).
///
/// Panics on unknown backend names; only `"sqlite"` and `"postgres"`
/// are shipped in Phase 2.
pub fn render_operation_for(op: &Operation, backend_name: &str) -> Vec<String> {
    match backend_name {
        "sqlite" => render_operation_sqlite(op),
        "postgres" => render_operation_postgres(op),
        other => panic!(
            "umbral::migrate: no DDL renderer for backend `{other}`; \
             Phase 2 ships sqlite and postgres only"
        ),
    }
}

/// SQLite-dialect rendering for one operation.
fn render_operation_sqlite(op: &Operation) -> Vec<String> {
    use sea_query::{Alias, SqliteQueryBuilder, Table};

    match op {
        // features #73. A view is DDL the ORM cannot express as a sea-query
        // statement (there is no ViewCreateStatement), and the SELECT body is an
        // opaque string the user wrote. This is exception (1) in CLAUDE.md's raw-SQL
        // rule: schema DDL, owned by the migration engine.
        //
        // A MATERIALIZED view never reaches here — the `model.materialized_view`
        // system check fails the boot on SQLite. Rendering it as a plain view would
        // be the exact "SQLite branch that quietly diverges" the design principles
        // forbid: the same query, silently recomputed on every read.
        Operation::CreateView {
            name,
            sql,
            materialized,
        } => {
            debug_assert!(
                !materialized,
                "materialized views are Postgres-only; the model.materialized_view \
                 system check should have failed the boot before reaching the renderer"
            );
            vec![format!("CREATE VIEW \"{name}\" AS {sql}")]
        }
        Operation::DropView { name, .. } => vec![format!("DROP VIEW IF EXISTS \"{name}\"")],
        Operation::CreateTable {
            table,
            columns,
            unique_together,
            indexes,
        } => {
            // sea-query's TableCreateStatement renders columns inline.
            let mut stmt = Table::create();
            stmt.table(Alias::new(table));
            for col in columns {
                let mut def = build_column_def_sqlite(col);
                stmt.col(&mut def);
            }
            let mut stmts = vec![stmt.build(SqliteQueryBuilder)];
            // `unique_together` groups render as follow-up
            // `CREATE UNIQUE INDEX` statements rather than inline table
            // constraints. A named unique index enforces the SAME
            // constraint, but — unlike an inline `UNIQUE(...)` (which becomes
            // an un-droppable auto-index on SQLite / an implicit constraint
            // on Postgres) — it can be added and DROPPED by name after the
            // table exists. That is what makes `unique_together`
            // autodetection reversible: the exact statement an `AddIndex`
            // would emit, so a later `DropIndex` names the same index.
            for group in unique_together {
                stmts.push(add_index_stmt(table, group, true));
            }
            // Single-column explicit indexes plus ORM-required helper
            // indexes follow the CREATE TABLE. FK columns need indexes
            // for reverse/select-related queries, and soft-delete
            // models read through `deleted_at IS NULL` by default.
            for col in columns {
                if should_emit_btree_index(col) {
                    stmts.push(create_index_stmt(table, &col.name));
                }
            }
            // BUG-7: multi-column indexes follow as plain CREATE INDEX.
            for group in indexes {
                stmts.push(create_multi_index_stmt(table, group));
            }
            stmts
        }
        // gaps3 #60 — `IF EXISTS`, matching `DROP INDEX` and `DROP VIEW`, which have always
        // said it. A migration's job is to make a statement about the DESIRED end state:
        // "this table should not exist". Erroring because the table is already gone is a
        // complaint that the world already agrees with you.
        //
        // It is not masking a bug. Forward application has to be idempotent, or a ledger
        // that drifts even slightly — a table dropped out of band, a rename replayed, an
        // app whose migration history was rewritten — becomes permanently unmigratable,
        // and the only escape the operator can see is deleting the database.
        Operation::DropTable { table } => vec![
            Table::drop()
                .table(Alias::new(table))
                .if_exists()
                .build(SqliteQueryBuilder),
        ],
        Operation::AddColumn { table, column } => {
            // SQLite-specific limitation: `ALTER TABLE ADD COLUMN`
            // requires a CONSTANT default. `CURRENT_TIMESTAMP` is
            // non-constant ("Cannot add a column with non-constant
            // default"). So when we're adding a NOT NULL auto_now /
            // auto_now_add column on top of an existing table, we
            // emit a two-statement sequence:
            //   1. ADD COLUMN as NULLABLE (no default needed).
            //   2. UPDATE every existing row to `datetime('now')`.
            // The column ends up NULL-permitting at the DB level on
            // SQLite — but the Rust type stays `DateTime<Utc>` (not
            // Option), and every INSERT through the ORM supplies a
            // value via the macro-emitted auto_now arm. The DB-side
            // NOT NULL guarantee is lost only for direct-SQL writers,
            // which umbral already discourages (see CLAUDE.md "Plugins
            // use the ORM"). Postgres has no such restriction —
            // `DEFAULT now()` works there in ALTER, no backfill
            // statement needed (see the Postgres render below).
            let needs_backfill = (column.auto_now || column.auto_now_add)
                && !column.nullable
                && matches!(
                    column.ty,
                    SqlType::Timestamptz | SqlType::Timestamp | SqlType::Date | SqlType::Time
                );

            let mut stmts = if needs_backfill {
                let mut nullable_col = column.clone();
                nullable_col.nullable = true;
                let mut stmt = Table::alter();
                stmt.table(Alias::new(table));
                let mut def = build_column_def_sqlite(&nullable_col);
                stmt.add_column(&mut def);
                let add_sql = stmt.build(SqliteQueryBuilder);

                // Manual UPDATE — sea-query's update builder is
                // overkill for a single SET col = datetime('now').
                let table_quoted = table.replace('"', "\"\"");
                let col_quoted = column.name.replace('"', "\"\"");
                let backfill_sql = format!(
                    "UPDATE \"{table_quoted}\" SET \"{col_quoted}\" = datetime('now') \
                     WHERE \"{col_quoted}\" IS NULL"
                );
                vec![add_sql, backfill_sql]
            } else {
                let mut stmt = Table::alter();
                stmt.table(Alias::new(table));
                // SQLite rejects `ADD COLUMN … UNIQUE`. Build the column def
                // WITHOUT the inline UNIQUE and apply uniqueness as a
                // separate `CREATE UNIQUE INDEX` below — semantically
                // identical, and it applies on a populated table.
                let mut col_no_unique = column.clone();
                col_no_unique.unique = false;
                let mut def = build_column_def_sqlite(&col_no_unique);
                stmt.add_column(&mut def);
                vec![stmt.build(SqliteQueryBuilder)]
            };
            if column.unique && !column.primary_key {
                stmts.push(create_unique_index_stmt(table, &column.name));
            }
            if should_emit_btree_index(column) {
                stmts.push(create_index_stmt(table, &column.name));
            }
            stmts
        }
        Operation::DropColumn { table, column } => vec![
            Table::alter()
                .table(Alias::new(table))
                .drop_column(Alias::new(column))
                .build(SqliteQueryBuilder),
        ],
        // gaps3 #43: SQLite has no `COMMENT` statement — no column comments, no
        // table comments, nothing. Rendering zero statements is the whole
        // implementation. This is not a silent divergence of the kind the raw-SQL
        // rule warns about: the columns, types, constraints and rows are
        // identical on both backends. Only the `psql \d+` annotation is absent,
        // because SQLite has nowhere to put it.
        Operation::SetColumnComment { .. } => Vec::new(),
        Operation::AlterColumn {
            table,
            column,
            new_columns,
            prev_columns,
            unique_together,
            indexes,
        } => {
            // gaps3 #24: choices are Rust-enforced on SQLite (build_column_def_sqlite
            // emits no CHECK), so an alter that ONLY changes this column's
            // choices/labels is invisible to the schema. Skip the otherwise
            // byte-identical table-recreation dance. Postgres still swaps its
            // CHECK constraint via the Postgres renderer, so the op is still
            // emitted and recorded — only the SQLite render short-circuits.
            if prev_columns
                .as_ref()
                .is_some_and(|prev| alter_is_choices_only(column, prev, new_columns))
            {
                Vec::new()
            } else {
                render_alter_column_dance_sqlite(table, new_columns, unique_together, indexes)
            }
        }
        Operation::CreateM2MTable {
            junction_table,
            parent_table,
            parent_col,
            child_table,
            child_col,
            parent_ty,
            child_ty,
        } => {
            // Junction table for many-to-many: two FK columns + composite PK.
            // Column types follow the referenced PKs — `BigInt` → `INTEGER`
            // (SQLite affinity), `Text` → `TEXT`, `Uuid` → `TEXT` on SQLite
            // / `UUID` on Postgres. Raw DDL is the simplest expression of
            // the composite-PK + per-side cascade FK shape; sea-query's
            // builder can't express it cleanly in one call.
            vec![format!(
                r#"CREATE TABLE "{jt}" (
    "parent_id" {pty} NOT NULL REFERENCES "{pt}"("{pc}") ON DELETE CASCADE,
    "child_id" {cty} NOT NULL REFERENCES "{ct}"("{cc}") ON DELETE CASCADE,
    PRIMARY KEY ("parent_id", "child_id")
)"#,
                jt = junction_table.replace('"', "\"\""),
                pt = parent_table.replace('"', "\"\""),
                pc = parent_col.replace('"', "\"\""),
                ct = child_table.replace('"', "\"\""),
                cc = child_col.replace('"', "\"\""),
                pty = m2m_pk_sql_type_sqlite(*parent_ty),
                cty = m2m_pk_sql_type_sqlite(*child_ty),
            )]
        }
        // gaps3 #60 — idempotent, same reasoning as `DropTable`.
        Operation::DropM2MTable { junction_table } => vec![
            Table::drop()
                .table(Alias::new(junction_table))
                .if_exists()
                .build(SqliteQueryBuilder),
        ],
        Operation::RenameTable { from, to } => {
            use sea_query::{Alias, SqliteQueryBuilder, Table};
            vec![
                Table::rename()
                    .table(Alias::new(from.as_str()), Alias::new(to.as_str()))
                    .build(SqliteQueryBuilder),
            ]
        }
        Operation::RenameColumn {
            table, from, to, ..
        } => {
            // SQLite 3.25+ supports `ALTER TABLE ... RENAME COLUMN`
            // natively. Quote both sides to allow names that need
            // escaping; sea-query's column-rename builder isn't
            // exposed cleanly so we render the DDL string directly.
            let t = table.replace('"', "\"\"");
            let f = from.replace('"', "\"\"");
            let tn = to.replace('"', "\"\"");
            vec![format!(
                "ALTER TABLE \"{t}\" RENAME COLUMN \"{f}\" TO \"{tn}\""
            )]
        }
        // A data migration renders to its raw forward SQL verbatim —
        // the author owns portability across backends.
        Operation::RunSql { sql, .. } => vec![sql.clone()],
        // Composite index / UNIQUE constraint add + drop. The
        // `CREATE [UNIQUE] INDEX IF NOT EXISTS` / `DROP INDEX IF EXISTS`
        // forms are identical on SQLite and Postgres, so both render arms
        // share the same helpers.
        Operation::AddIndex {
            table,
            columns,
            unique,
        } => vec![add_index_stmt(table, columns, *unique)],
        Operation::DropIndex {
            table,
            columns,
            unique,
        } => vec![drop_index_stmt(&index_name(table, columns, *unique))],
    }
}

/// Postgres-dialect rendering for one operation.
///
/// Postgres has native `ALTER COLUMN` so `AlterColumn` doesn't need
/// the SQLite table-recreation dance; it lowers to a single statement.
/// Integer primary keys use sea-query's `auto_increment()` flag, which
/// the Postgres query builder lowers to `BIGSERIAL` / `SERIAL` rather
/// than SQLite's `INTEGER PRIMARY KEY AUTOINCREMENT` quirk.
fn render_operation_postgres(op: &Operation) -> Vec<String> {
    use sea_query::{Alias, PostgresQueryBuilder, Table};

    match op {
        // features #73 — see the SQLite renderer for why this is raw DDL.
        Operation::CreateView {
            name,
            sql,
            materialized,
        } => {
            let kind = if *materialized {
                "MATERIALIZED VIEW"
            } else {
                "VIEW"
            };
            vec![format!("CREATE {kind} \"{name}\" AS {sql}")]
        }
        Operation::DropView { name, materialized } => {
            let kind = if *materialized {
                "MATERIALIZED VIEW"
            } else {
                "VIEW"
            };
            // No CASCADE. A view another view depends on should fail loudly rather
            // than silently take its dependants down with it — the engine emits the
            // dependants' drops itself, in order, when it knows about them.
            vec![format!("DROP {kind} IF EXISTS \"{name}\"")]
        }
        Operation::CreateTable {
            table,
            columns,
            unique_together,
            indexes,
        } => {
            let mut stmt = Table::create();
            stmt.table(Alias::new(table));
            for col in columns {
                let mut def = build_column_def_postgres(col);
                stmt.col(&mut def);
            }
            let mut stmts = vec![stmt.build(PostgresQueryBuilder)];
            // gaps3 #35: a `#[umbral(case_insensitive)]` text column renders as
            // `citext`, which needs its extension. Emit the (idempotent) create
            // BEFORE the table so the citext type resolves. Requires a role with
            // CREATE privilege on the database — the operator pre-creates it once
            // if the runtime role is restricted.
            if columns
                .iter()
                .any(|c| c.case_insensitive && matches!(c.ty, crate::orm::SqlType::Text))
            {
                stmts.insert(0, "CREATE EXTENSION IF NOT EXISTS citext".to_string());
            }
            // gaps5 #22: a spatial column needs the PostGIS extension. Emit the
            // (idempotent) create BEFORE the table so the `geometry`/`geography`
            // types resolve — the same pattern as citext. A restricted runtime
            // role has the operator pre-install it; `IF NOT EXISTS` no-ops then.
            if columns.iter().any(|c| {
                matches!(
                    c.ty,
                    crate::orm::SqlType::Geometry(_) | crate::orm::SqlType::Geography(_)
                )
            }) {
                stmts.insert(0, "CREATE EXTENSION IF NOT EXISTS postgis".to_string());
            }
            // `unique_together` as follow-up `CREATE UNIQUE INDEX` (not an
            // inline constraint) so it is droppable by name — see the SQLite
            // render arm for the full rationale.
            for group in unique_together {
                stmts.push(add_index_stmt(table, group, true));
            }
            for col in columns {
                if matches!(col.ty, crate::orm::SqlType::FullText) {
                    // tsvector columns get an auto-GIN index (#33) — they're
                    // useless for search without one, so the engine never
                    // makes the caller hand-write it.
                    stmts.push(create_gin_index_stmt(table, &col.name));
                } else if is_spatial(col) && col.index {
                    // A spatial column marked `#[umbral(index)]` gets a GiST
                    // index — the only index type spatial predicates use. A
                    // plain B-tree is meaningless on geometry (gaps5 #22).
                    stmts.push(create_gist_index_stmt(table, &col.name));
                } else if should_emit_btree_index(col) {
                    stmts.push(create_index_stmt(table, &col.name));
                }
            }
            for group in indexes {
                stmts.push(create_multi_index_stmt(table, group));
            }
            // gaps3 #43: `#[umbral(help = "...")]` as a column comment. Postgres
            // has no inline column-comment syntax, so these follow the CREATE —
            // commenting a column that doesn't exist yet is an error.
            for col in columns {
                if !col.help.is_empty() {
                    stmts.push(comment_on_column_stmt(table, &col.name, &col.help));
                }
            }
            stmts
        }
        // gaps3 #60 — see the SQLite renderer.
        Operation::DropTable { table } => vec![
            Table::drop()
                .table(Alias::new(table))
                .if_exists()
                .build(PostgresQueryBuilder),
        ],
        Operation::AddColumn { table, column } => {
            let mut stmt = Table::alter();
            stmt.table(Alias::new(table));
            let mut def = build_column_def_postgres(column);
            stmt.add_column(&mut def);
            let mut stmts = vec![stmt.build(PostgresQueryBuilder)];
            if matches!(column.ty, crate::orm::SqlType::FullText) {
                // Auto-GIN for a tsvector column added later (#33).
                stmts.push(create_gin_index_stmt(table, &column.name));
            } else if is_spatial(column) && column.index {
                // GiST for a spatial column added later (gaps5 #22).
                stmts.push(create_gist_index_stmt(table, &column.name));
            } else if should_emit_btree_index(column) {
                stmts.push(create_index_stmt(table, &column.name));
            }
            if !column.help.is_empty() {
                stmts.push(comment_on_column_stmt(table, &column.name, &column.help));
            }
            stmts
        }
        Operation::SetColumnComment {
            table,
            column,
            comment,
        } => vec![comment_on_column_stmt(table, column, comment)],
        Operation::DropColumn { table, column } => vec![
            Table::alter()
                .table(Alias::new(table))
                .drop_column(Alias::new(column))
                .build(PostgresQueryBuilder),
        ],
        Operation::AlterColumn {
            table,
            column,
            new_columns,
            prev_columns,
            // Postgres alters in place — indexes/UNIQUE survive the ALTER, so
            // it doesn't re-create them (only the SQLite recreation dance does).
            unique_together: _,
            indexes: _,
        } => render_alter_column_postgres(table, column, new_columns, prev_columns.as_deref()),
        Operation::CreateM2MTable {
            junction_table,
            parent_table,
            parent_col,
            child_table,
            child_col,
            parent_ty,
            child_ty,
        } => {
            vec![format!(
                r#"CREATE TABLE "{jt}" (
    "parent_id" {pty} NOT NULL REFERENCES "{pt}"("{pc}") ON DELETE CASCADE DEFERRABLE INITIALLY IMMEDIATE,
    "child_id" {cty} NOT NULL REFERENCES "{ct}"("{cc}") ON DELETE CASCADE DEFERRABLE INITIALLY IMMEDIATE,
    PRIMARY KEY ("parent_id", "child_id")
)"#,
                jt = junction_table.replace('"', "\"\""),
                pt = parent_table.replace('"', "\"\""),
                pc = parent_col.replace('"', "\"\""),
                ct = child_table.replace('"', "\"\""),
                cc = child_col.replace('"', "\"\""),
                pty = m2m_pk_sql_type_postgres(*parent_ty),
                cty = m2m_pk_sql_type_postgres(*child_ty),
            )]
        }
        // gaps3 #60 — idempotent, same reasoning as `DropTable`.
        Operation::DropM2MTable { junction_table } => vec![
            Table::drop()
                .table(Alias::new(junction_table))
                .if_exists()
                .build(PostgresQueryBuilder),
        ],
        Operation::RenameTable { from, to } => {
            // Postgres: ALTER TABLE "<from>" RENAME TO "<to>"
            // sea-query's Table::rename() emits the right form.
            use sea_query::{Alias, PostgresQueryBuilder, Table};
            vec![
                Table::rename()
                    .table(Alias::new(from.as_str()), Alias::new(to.as_str()))
                    .build(PostgresQueryBuilder),
            ]
        }
        Operation::RenameColumn {
            table, from, to, ..
        } => {
            let t = table.replace('"', "\"\"");
            let f = from.replace('"', "\"\"");
            let tn = to.replace('"', "\"\"");
            vec![format!(
                "ALTER TABLE \"{t}\" RENAME COLUMN \"{f}\" TO \"{tn}\""
            )]
        }
        // A data migration renders to its raw forward SQL verbatim —
        // the author owns portability across backends.
        Operation::RunSql { sql, .. } => vec![sql.clone()],
        // Same `CREATE [UNIQUE] INDEX IF NOT EXISTS` / `DROP INDEX IF EXISTS`
        // as SQLite — Postgres accepts the identical form.
        Operation::AddIndex {
            table,
            columns,
            unique,
        } => vec![add_index_stmt(table, columns, *unique)],
        Operation::DropIndex {
            table,
            columns,
            unique,
        } => vec![drop_index_stmt(&index_name(table, columns, *unique))],
    }
}

/// The SQLite table-recreation dance for `AlterColumn`. SQLite has no
/// in-place `ALTER COLUMN`, so the only safe way to flip a column's
/// nullable flag is to rebuild the table:
///
/// 1. `CREATE TABLE _umbral_new_<table>` with the new schema.
/// 2. `INSERT ... SELECT` to copy every row from the old table.
/// 3. `DROP TABLE <table>`.
/// 4. `ALTER TABLE _umbral_new_<table> RENAME TO <table>`.
///
/// Wrapped in a transaction by the caller, which — when the migration contains
/// an `AlterColumn` — brackets that transaction with `PRAGMA foreign_keys=OFF`
/// … `PRAGMA foreign_key_check` … `PRAGMA foreign_keys=ON` (SQLite's official
/// recipe), so step 3's `DROP TABLE` on a table with **inbound** FKs doesn't
/// trip `FOREIGN KEY constraint failed` (gaps3 #13). Indexes, triggers, and FK
/// targets aren't preserved at M5.1 because umbral-core's schema model
/// doesn't yet carry them; once it does, this routine picks them up
/// by rebuilding them at step 1.
///
/// Nullable `TRUE -> FALSE` fails at step 2 if any row holds NULL,
/// which is the correct data-integrity behaviour. Nullable
/// `FALSE -> TRUE` always succeeds.
/// gaps3 #24: true when an `AlterColumn` on `column` changes ONLY the closed-set
/// `choices` / `choice_labels` — every schema-relevant field (type, nullable,
/// unique, default, FK, on_delete/update, pk, length, multichoice) is identical.
/// On SQLite such a delta is a no-op: choices are enforced in Rust there, not by
/// a DB CHECK, so rebuilding the table would produce a byte-identical schema.
fn alter_is_choices_only(column: &str, prev: &[Column], new: &[Column]) -> bool {
    let (Some(p), Some(n)) = (
        prev.iter().find(|c| c.name == column),
        new.iter().find(|c| c.name == column),
    ) else {
        return false;
    };
    let choices_changed = p.choices != n.choices || p.choice_labels != n.choice_labels;
    let schema_same = p.ty == n.ty
        && p.nullable == n.nullable
        && p.unique == n.unique
        && p.default == n.default
        && p.fk_target == n.fk_target
        && p.on_delete == n.on_delete
        && p.on_update == n.on_update
        && p.primary_key == n.primary_key
        && p.max_length == n.max_length
        && p.is_multichoice == n.is_multichoice;
    choices_changed && schema_same
}

fn render_alter_column_dance_sqlite(
    table: &str,
    new_columns: &[Column],
    unique_together: &[Vec<String>],
    indexes: &[Vec<String>],
) -> Vec<String> {
    use sea_query::{Alias, SqliteQueryBuilder, Table};

    let tmp = format!("_umbral_new_{table}");

    // Step 1 — CREATE TABLE _umbral_new_<table>.
    let mut create = Table::create();
    create.table(Alias::new(&tmp));
    for col in new_columns {
        let mut def = build_column_def_sqlite(col);
        create.col(&mut def);
    }

    // Step 2 — INSERT ... SELECT. The INSERT target list is the plain column
    // names; each is double-quoted so SQLite identifier rules don't bite on
    // reserved words. The SELECT side backfills any NOT-NULL-with-default column
    // via `COALESCE(col, <default>)` (audit_2 core-migrate #5) — a
    // nullable→NOT NULL tightening whose existing rows hold NULL would otherwise
    // copy NULL into the new NOT NULL column and abort the rebuild. COALESCE is
    // a harmless no-op for a column that never held NULLs.
    let insert_cols = new_columns
        .iter()
        .map(|c| format!("\"{}\"", c.name.replace('"', "\"\"")))
        .collect::<Vec<_>>()
        .join(", ");
    let select_exprs = new_columns
        .iter()
        .map(|c| {
            let name = format!("\"{}\"", c.name.replace('"', "\"\""));
            if !c.nullable && !c.default.is_empty() {
                format!("COALESCE({name}, {})", default_sql_literal(c, false))
            } else {
                name
            }
        })
        .collect::<Vec<_>>()
        .join(", ");
    let insert_sql =
        format!("INSERT INTO \"{tmp}\" ({insert_cols}) SELECT {select_exprs} FROM \"{table}\"");

    // Step 3 — DROP TABLE <table>.
    let drop_sql = Table::drop()
        .table(Alias::new(table))
        .build(SqliteQueryBuilder);

    // Step 4 — ALTER TABLE _umbral_new_<table> RENAME TO <table>.
    let rename_sql = Table::rename()
        .table(Alias::new(&tmp), Alias::new(table))
        .build(SqliteQueryBuilder);

    let mut stmts = vec![
        create.build(SqliteQueryBuilder),
        insert_sql,
        drop_sql,
        rename_sql,
    ];
    // Step 5 — audit_2 core-migrate #10: re-create the secondary indexes and
    // composite UNIQUE constraints the dropped table carried, or the rebuild
    // silently drops them (duplicates become insertable — integrity loss).
    // Single-column / FK / soft-delete indexes are derived from the columns
    // (same rule as CreateTable); `unique_together` re-emits as a named
    // `CREATE UNIQUE INDEX` and composite `indexes` as plain `CREATE INDEX`.
    // All are `IF NOT EXISTS`, so the step is idempotent.
    for col in new_columns {
        if should_emit_btree_index(col) {
            stmts.push(create_index_stmt(table, &col.name));
        }
    }
    for group in unique_together {
        stmts.push(add_index_stmt(table, group, true));
    }
    for group in indexes {
        stmts.push(create_multi_index_stmt(table, group));
    }
    stmts
}

/// Native Postgres `AlterColumn`. Postgres supports
/// `ALTER TABLE x ALTER COLUMN y SET NOT NULL` and
/// `ALTER TABLE x ALTER COLUMN y DROP NOT NULL` in place, so the
/// SQLite table-recreation dance isn't needed. Lowers to a single
/// statement.
///
/// `SET NOT NULL` fails at the server if any row holds NULL on `y`,
/// matching SQLite's INSERT-time failure on the dance — the
/// data-integrity contract is identical between backends.
///
/// `column` is the field name that triggered the flip; `new_columns`
/// is the post-change schema (carried for parity with the SQLite
/// dance, though Postgres only needs the one column).
fn render_alter_column_postgres(
    table: &str,
    column: &str,
    new_columns: &[Column],
    prev_columns: Option<&[Column]>,
) -> Vec<String> {
    let new = new_columns.iter().find(|c| c.name == column).expect(
        "umbral::migrate: AlterColumn op references a column missing from new_columns; \
             this is a bug in `diff_columns`",
    );
    let prev = prev_columns.and_then(|cols| cols.iter().find(|c| c.name == column));

    let q_table = quote_pg_ident(table);
    let q_column = quote_pg_ident(column);

    let mut stmts: Vec<String> = Vec::new();

    // TYPE change: only when we have a previous snapshot AND it differs
    // AND the change is in the safe-cast whitelist (diff_columns has
    // already gated unsafe ones). Emitted before nullable so a NOT
    // NULL flip against the just-cast column reads the new type.
    //
    // A same-type Text column whose `max_length` changed is ALSO a type
    // change on Postgres — varchar(n) carries the bound in the type — and
    // rendering nothing here is how widened models silently kept their old
    // bound on every fresh database (diff_columns has already refused the
    // narrowing direction). `postgres_type_sql` is length-aware, so a plain
    // safe-cast into a bounded Text lands on varchar(n) too, not bare text.
    if let Some(prev_col) = prev {
        let cast_changed = prev_col.ty != new.ty && is_safe_cast(prev_col.ty, new.ty);
        let length_changed = prev_col.ty == new.ty
            && new.ty == SqlType::Text
            && prev_col.max_length != new.max_length;
        if cast_changed || length_changed {
            let new_ty_sql = postgres_type_sql(new);
            stmts.push(format!(
                "ALTER TABLE {q_table} ALTER COLUMN {q_column} TYPE {new_ty_sql} USING {q_column}::{new_ty_sql}"
            ));
        }
    }

    // NULL-flag change: skipped when prev is None (legacy migrations
    // with no snapshot — preserve the old "emit unconditionally" path
    // because it's idempotent on Postgres). With a snapshot, only emit
    // when the flag actually flipped.
    let nullable_changed = match prev {
        Some(prev_col) => prev_col.nullable != new.nullable,
        None => true,
    };
    if nullable_changed {
        // audit_2 core-migrate #5: backfill existing NULLs before tightening.
        // A nullable→NOT NULL flip whose column carries a default would abort on
        // any pre-existing NULL row (bare `SET NOT NULL` doesn't backfill, and
        // `SET DEFAULT` only affects future inserts). Emit the backfill UPDATE
        // first so the subsequent `SET NOT NULL` succeeds.
        if !new.nullable && !new.default.is_empty() {
            let lit = default_sql_literal(new, true);
            stmts.push(format!(
                "UPDATE {q_table} SET {q_column} = {lit} WHERE {q_column} IS NULL"
            ));
        }
        let clause = if new.nullable {
            "DROP NOT NULL"
        } else {
            "SET NOT NULL"
        };
        stmts.push(format!(
            "ALTER TABLE {q_table} ALTER COLUMN {q_column} {clause}"
        ));
    }

    // From here down — all the gap #65 follow-up changes. Each branch
    // checks if `prev` exists (legacy migrations with no snapshot
    // skip these, matching the historical behaviour) and emits the
    // matching ALTER on real flips.
    if let Some(prev_col) = prev {
        // UNIQUE flag flip. Postgres autogen for column-level UNIQUE
        // at CREATE TABLE is `<table>_<col>_key`; we use the same
        // name when ADDing so a subsequent DROP finds it.
        if prev_col.unique != new.unique {
            let cname = format!("{table}_{column}_key");
            if new.unique {
                stmts.push(format!(
                    "ALTER TABLE {q_table} ADD CONSTRAINT \"{cname}\" UNIQUE ({q_column})"
                ));
            } else {
                stmts.push(format!(
                    "ALTER TABLE {q_table} DROP CONSTRAINT IF EXISTS \"{cname}\""
                ));
            }
        }

        // DEFAULT change. Empty string in either snapshot means "no
        // default"; the canonical SET / DROP pair fully expresses
        // the transition.
        if prev_col.default != new.default {
            if new.default.is_empty() {
                stmts.push(format!(
                    "ALTER TABLE {q_table} ALTER COLUMN {q_column} DROP DEFAULT"
                ));
            } else {
                let escaped = new.default.replace('\'', "''");
                stmts.push(format!(
                    "ALTER TABLE {q_table} ALTER COLUMN {q_column} SET DEFAULT '{escaped}'"
                ));
            }
        }

        // FK target / on_delete / on_update — these are all carried
        // on the same constraint, so any one of them flipping
        // requires a DROP + readd of the whole FK. Autogen name
        // convention `<table>_<col>_fkey` matches Postgres at CREATE
        // TABLE time. Only emitted when the new column is still a
        // FK; if the column stopped being a FK (ty changed away
        // from ForeignKey), the type-change branch above handles
        // it indirectly via the column type rewrite.
        let fk_changed = prev_col.fk_target != new.fk_target
            || prev_col.on_delete != new.on_delete
            || prev_col.on_update != new.on_update;
        if fk_changed && matches!(new.ty, SqlType::ForeignKey) {
            let cname = format!("{table}_{column}_fkey");
            stmts.push(format!(
                "ALTER TABLE {q_table} DROP CONSTRAINT IF EXISTS \"{cname}\""
            ));
            // gaps2 #22: only re-add the physical constraint when the FK
            // still wants one. A `db_constraint = false` FK keeps the
            // DROP (so flipping the flag tears down any prior constraint)
            // but emits no ADD CONSTRAINT.
            if let Some(target) = &new.fk_target
                && new.db_constraint
            {
                let q_target = quote_pg_ident(target);
                // Resolve the referenced PK column from the target model's
                // registered meta instead of hardcoding `"id"`. String/Uuid
                // PKs (e.g. `Permission.codename`) are first-class post-lift;
                // the CreateTable path already resolves via `fk_target_pk`
                // (build_column_def_postgres), so the re-add must match or it
                // aborts the migration ("column id does not exist") / attaches
                // the constraint to the wrong column.
                let (pk_col, _pk_ty) = fk_target_pk(&target.replace('"', "\"\""));
                let q_pk = quote_pg_ident(&pk_col);
                let on_delete_clause = new
                    .on_delete
                    .sql_keyword()
                    .map(|k| format!(" ON DELETE {k}"))
                    .unwrap_or_default();
                let on_update_clause = new
                    .on_update
                    .sql_keyword()
                    .map(|k| format!(" ON UPDATE {k}"))
                    .unwrap_or_default();
                stmts.push(format!(
                    "ALTER TABLE {q_table} ADD CONSTRAINT \"{cname}\" \
                     FOREIGN KEY ({q_column}) REFERENCES {q_target}({q_pk})\
                     {on_delete_clause}{on_update_clause}{PG_FK_DEFERRABLE}"
                ));
            }
        }

        // CHECK constraint (single-valued choices) change. MultiChoice
        // uses CSV storage which can't be expressed as a column-level
        // IN constraint; the runtime sqlx Decode path is the guard.
        if prev_col.choices != new.choices && !new.is_multichoice {
            let cname = format!("{table}_{column}_check");
            stmts.push(format!(
                "ALTER TABLE {q_table} DROP CONSTRAINT IF EXISTS \"{cname}\""
            ));
            if !new.choices.is_empty() {
                let values_sql = new
                    .choices
                    .iter()
                    .map(|v| format!("'{}'", v.replace('\'', "''")))
                    .collect::<Vec<_>>()
                    .join(", ");
                stmts.push(format!(
                    "ALTER TABLE {q_table} ADD CONSTRAINT \"{cname}\" \
                     CHECK ({q_column} IN ({values_sql}))"
                ));
            }
        }
    }

    // Defensive: if we somehow produced no statements (shouldn't
    // happen — diff_columns gates on at least one schema-meaningful
    // flag changing), fall back to a single redundant SET NULL flip
    // to match the legacy contract. Tests cover both branches; this
    // is belt-and-braces.
    if stmts.is_empty() {
        let clause = if new.nullable {
            "DROP NOT NULL"
        } else {
            "SET NOT NULL"
        };
        stmts.push(format!(
            "ALTER TABLE {q_table} ALTER COLUMN {q_column} {clause}"
        ));
    }

    stmts
}

/// Quote a SQL identifier the Postgres way: wrap in double quotes,
/// escape inner double quotes by doubling them. Matches sea-query's
/// `PostgresQueryBuilder` output for identifiers so the rendered
/// statements look uniform.
fn quote_pg_ident(ident: &str) -> String {
    format!("\"{}\"", ident.replace('"', "\"\""))
}

/// Build a SQLite `ColumnDef`. SQLite has one important quirk: its
/// ROWID-alias mechanic (which gives a primary-key column auto-
/// increment behaviour out of the box) only fires when the column's
/// type is the exact text `INTEGER` — case-insensitive but no other
/// variant. `BIGINT PRIMARY KEY`, even on a column the M3 derive
/// declared as `i64`, does NOT auto-increment, so an `INSERT INTO t
/// (other_col) VALUES (...)` without an explicit PK value fails the
/// NOT NULL constraint. Every umbral user with an `id: i64` model
/// would hit this without the override.
///
/// The fix: when a column is a primary key with an integer SqlType
/// (Integer or BigInt), force the rendered type to `Integer` and
/// attach `auto_increment()` so the generated DDL reads `"id" integer
/// NOT NULL PRIMARY KEY AUTOINCREMENT`. SQLite stores both `i32` and
/// `i64` as INTEGER affinity anyway, so the override is a no-op
/// semantically — the rows that round-trip through `sqlx::FromRow`
/// deserialize back into `i64` cleanly.
///
/// For `SqlType::Uuid` PKs: SQLite stores UUIDs as TEXT. No
/// `DEFAULT gen_random_uuid()` is emitted; the application must supply
/// the UUID at create time (or pass `Uuid::nil()` to trigger the
/// omit-on-insert sentinel that leaves the column to a future default).
///
/// For `SqlType::ForeignKey` columns: rendered as `BIGINT` with a
/// `REFERENCES "<target>"("id")` suffix appended via `.extra()`. The
/// target table name comes from `col.fk_target`.
/// Look up the FK target model's primary-key column name and SQL
/// type. Walks the registered ModelMeta set to find the model whose
/// table matches `fk_target_table`, then picks the first column
/// marked `primary_key = true`. Falls back to `("id", BigInteger)`
/// when the target isn't registered (cross-plugin lookup miss, or
/// the FK points outside the framework's model registry).
///
/// Used by both the SQLite and Postgres FK column-def builders so the
/// generated `<col> <type> REFERENCES <tbl>(<pk_col>)` matches the
/// target's actual PK shape — gap #60 made non-`id`, non-i64 PKs
/// (e.g. `Permission.codename: String`) a real case.
fn fk_target_pk(fk_target_table: &str) -> (String, sea_query::ColumnType) {
    use sea_query::ColumnType;
    let unesc = fk_target_table.replace("\"\"", "\"");
    // Non-panicking registry read — `registered_models()` itself
    // panics when called outside an `App::build()` context, but the
    // migration engine's unit tests construct snapshots by hand and
    // call into DDL emit without booting the framework. Fall through
    // to the historical "id"/BigInteger default in that case.
    let Some(metas) = REGISTRY.get() else {
        return ("id".to_string(), ColumnType::BigInteger);
    };
    for meta in metas.iter().map(|(_, m)| m) {
        if meta.table != unesc {
            continue;
        }
        if let Some(pk) = meta.fields.iter().find(|c| c.primary_key) {
            // Map the PK's SqlType to a sea-query ColumnType. We can't
            // route through `SqliteBackend::map_column` because that
            // wants a `Column` and applies max_length / choices
            // metadata which is irrelevant to a FK column. Hand-roll
            // the few cases the framework supports for PKs.
            let ct = match pk.ty {
                SqlType::BigInt | SqlType::Integer => ColumnType::BigInteger,
                SqlType::SmallInt => ColumnType::SmallInteger,
                SqlType::Text => ColumnType::Text,
                SqlType::Uuid => ColumnType::Uuid,
                // Other PK types fall back to BigInteger as the
                // historical default. The compile-time PrimaryKey
                // trait keeps this list closed in practice.
                _ => ColumnType::BigInteger,
            };
            return (pk.name.clone(), ct);
        }
    }
    ("id".to_string(), ColumnType::BigInteger)
}

fn build_column_def_sqlite(col: &Column) -> sea_query::ColumnDef {
    use sea_query::{Alias, ColumnDef, ColumnType};

    // ForeignKey gets a special path: column type + inline REFERENCES
    // clause both derived from the target model's PK column.
    if matches!(col.ty, SqlType::ForeignKey) {
        let fk_target = col
            .fk_target
            .as_deref()
            .unwrap_or("_unknown_")
            .replace('"', "\"\"");
        let (pk_col_name, pk_col_type) = fk_target_pk(&fk_target);
        let mut def = ColumnDef::new_with_type(Alias::new(&col.name), pk_col_type);
        if !col.nullable {
            def.not_null();
        }
        // A FK column that is ALSO the primary key (an identifying relation —
        // Prisma's `@id` on a relation field) must carry the PRIMARY KEY
        // marking. The FK branch returns early, so it wouldn't otherwise reach
        // the general `col.primary_key` handling below. No AUTOINCREMENT: the
        // value is the referenced row's key, not a fresh sequence.
        if col.primary_key {
            def.primary_key();
        }
        // BUG-15: `#[umbral(unique)]` on a FK column is the
        // OneToOne idiom — emit UNIQUE inline so the
        // referencing-row uniqueness is enforced at the DB.
        // The FK branch used to skip this because it returned
        // before the non-FK unique branch ran. A PK column is already
        // unique, so don't double up.
        if col.unique && !col.primary_key {
            def.unique_key();
        }
        // gaps2 #22: `#[umbral(db_constraint = false)]` keeps the logical
        // FK (column type derived from the target PK, above) but emits
        // NO physical `REFERENCES` clause. This is the only valid shape
        // for a cross-database FK. The default (`true`) emits the
        // constraint as before.
        if col.db_constraint {
            def.extra(format!(
                "REFERENCES \"{fk_target}\"(\"{pk_col_name}\"){}",
                fk_action_suffix(col),
            ));
        }
        return def;
    }

    let is_int_pk = col.primary_key && matches!(col.ty, SqlType::Integer | SqlType::BigInt);

    let column_type = if is_int_pk {
        ColumnType::Integer
    } else {
        crate::backend::SqliteBackend.map_column(col)
    };

    let mut def = ColumnDef::new_with_type(Alias::new(&col.name), column_type);
    if !col.nullable {
        def.not_null();
    }
    if col.primary_key {
        def.primary_key();
        if is_int_pk {
            def.auto_increment();
        }
    }
    // gaps3 #35: `#[umbral(case_insensitive)]` on SQLite lifts to a column-level
    // `COLLATE NOCASE`, so `=`, `UNIQUE`, and `ORDER BY` fold case while storage
    // keeps the original casing. Emitted before UNIQUE so the auto-created
    // unique index inherits the column's NOCASE collation. NOCASE folds ASCII
    // A–Z only (a boot check warns about Unicode); Postgres uses `citext`.
    if col.case_insensitive && matches!(col.ty, SqlType::Text) {
        def.extra("COLLATE NOCASE".to_string());
    }
    // `#[umbral(unique)]` lifts to a column-level UNIQUE clause.
    // Skipped on PK columns (already unique) so the DDL stays tidy.
    if col.unique && !col.primary_key {
        def.unique_key();
    }
    // IMP-3: `#[umbral(min = N)]` / `#[umbral(max = N)]` lift to a
    // column-level CHECK clause. Both SQLite and Postgres accept the
    // same syntax. The pre-validation in `insert_json`/`update_json`
    // catches violations earlier with a friendlier error; the CHECK
    // is the DB-side safety net against direct-SQL writers.
    if let Some(check) = check_min_max_sql(col) {
        def.extra(check);
    }
    // User-declared `#[umbral(default = "...")]` lifts to a DDL DEFAULT
    // clause. Required when emitting `ALTER TABLE ADD COLUMN` for a
    // NOT NULL column against a non-empty table (SQLite rejects the
    // ADD otherwise); on CREATE TABLE it sets the column-level default
    // the database uses when an INSERT omits the value.
    //
    // SQLite stores booleans as INTEGER; the literal `'true'` /
    // `'false'` would land as a TEXT default that fails type checks
    // on reads. Translate Boolean defaults to `1` / `0` so the
    // stored representation matches what sqlx expects on hydration
    // (closes IMP-2 in bugs/tests/testBugs.md).
    if !col.default.is_empty() {
        if matches!(col.ty, SqlType::Boolean) {
            // Pass an integer to sea-query so the rendered SQL is
            // `DEFAULT 1` / `DEFAULT 0` instead of the quoted-string
            // `DEFAULT '1'` (which sqlx rejects as TEXT on read of
            // a BOOLEAN column).
            def.default(sqlite_bool_default(&col.default));
        } else {
            def.default(col.default.clone());
        }
    }
    // NOTE: auto_now / auto_now_add deliberately does NOT emit a
    // `DEFAULT CURRENT_TIMESTAMP` here. SQLite rejects non-constant
    // defaults in `ALTER TABLE ADD COLUMN` ("Cannot add a column
    // with non-constant default") and that's the path that matters
    // for evolving an existing table. The SQLite `AddColumn` render
    // path handles the auto_now backfill via a two-statement
    // sequence (nullable ADD + UPDATE backfill). On CREATE TABLE
    // we don't need a default at all because every INSERT goes
    // through the macro-emitted Rust path which always supplies the
    // value. See `Operation::AddColumn` render below.
    def
}

/// Render a column's `#[umbral(default = ...)]` value as a raw SQL literal for
/// a hand-built statement (the NOT-NULL backfill, audit_2 core-migrate #5).
/// sea-query quotes literals itself in the column-def path, but the backfill
/// `UPDATE`/`COALESCE` is a raw `format!`, so it needs the literal here.
/// Numeric and boolean types render unquoted (`0`, `true`); everything else is
/// a single-quoted string with inner quotes doubled. `is_postgres` only affects
/// booleans (`true`/`false` on PG, `1`/`0` on SQLite, matching each backend's
/// boolean storage).
fn default_sql_literal(col: &Column, is_postgres: bool) -> String {
    use crate::orm::SqlType::*;
    match col.ty {
        Boolean => {
            let truthy = matches!(
                col.default.trim().to_ascii_lowercase().as_str(),
                "true" | "1" | "t" | "yes"
            );
            if is_postgres {
                if truthy { "true" } else { "false" }.to_string()
            } else if truthy {
                "1".to_string()
            } else {
                "0".to_string()
            }
        }
        SmallInt | Integer | BigInt | Real | Double | Decimal | ForeignKey => {
            // Numeric literal — validated at derive time; emit unquoted.
            col.default.clone()
        }
        _ => format!("'{}'", col.default.replace('\'', "''")),
    }
}

/// Map a user-supplied boolean default string (`"true"` / `"false"`
/// / `"1"` / `"0"`, case-insensitive) to the SQLite integer literal
/// the column expects. Anything unrecognised falls through to `0`
/// — a developer-visible miss (default is wrong, not stored as
/// text) is friendlier than the runtime decode error the textual
/// path produces.
fn sqlite_bool_default(raw: &str) -> i32 {
    match raw.trim().to_ascii_lowercase().as_str() {
        "true" | "1" | "t" | "yes" => 1,
        _ => 0,
    }
}

/// IMP-3: lower `#[umbral(min = N)]` / `#[umbral(max = N)]` to a
/// DDL CHECK clause. Returns `None` when the column declares
/// neither bound. The rendered SQL works on both SQLite and
/// Postgres (`"<col>" >= N`, `"<col>" <= N`, joined by `AND`).
/// Only applied to numeric columns — applying it to text would
/// compare strings lexicographically and surprise everyone.
fn check_min_max_sql(col: &Column) -> Option<String> {
    if col.min.is_none() && col.max.is_none() {
        return None;
    }
    if !matches!(
        col.ty,
        SqlType::SmallInt | SqlType::Integer | SqlType::BigInt | SqlType::Real | SqlType::Double
    ) {
        return None;
    }
    let name = col.name.replace('"', "\"\"");
    let mut parts = Vec::with_capacity(2);
    if let Some(n) = col.min {
        parts.push(format!("\"{name}\" >= {n}"));
    }
    if let Some(n) = col.max {
        parts.push(format!("\"{name}\" <= {n}"));
    }
    Some(format!("CHECK ({})", parts.join(" AND ")))
}

/// Build a Postgres `ColumnDef`. Integer primary keys use the
/// standard `auto_increment()` flag — sea-query's `PostgresQueryBuilder`
/// lowers that to `BIGSERIAL` for `BigInt` and `SERIAL` for `Integer`.
/// No SQLite-style INTEGER-type override needed; Postgres has proper
/// `BIGSERIAL` / identity columns and respects the declared width.
///
/// For `SqlType::ForeignKey` columns: rendered as `BIGINT` with a
/// `REFERENCES "<target>"("id")` suffix. The target table name comes
/// from `col.fk_target`.
fn build_column_def_postgres(col: &Column) -> sea_query::ColumnDef {
    use sea_query::{Alias, ColumnDef};

    // ForeignKey gets a special path: column type + inline REFERENCES
    // clause both derived from the target model's PK.
    if matches!(col.ty, SqlType::ForeignKey) {
        let fk_target = col
            .fk_target
            .as_deref()
            .unwrap_or("_unknown_")
            .replace('"', "\"\"");
        let (pk_col_name, pk_col_type) = fk_target_pk(&fk_target);
        // sea-query's ColumnType variants are dialect-agnostic; the
        // same value works for both SQLite and Postgres builders here.
        let mut def = ColumnDef::new_with_type(Alias::new(&col.name), pk_col_type);
        if !col.nullable {
            def.not_null();
        }
        // BUG-15: `#[umbral(unique)]` on a FK column is the
        // OneToOne idiom — emit UNIQUE inline so the
        // referencing-row uniqueness is enforced at the DB.
        // The FK branch used to skip this because it returned
        // before the non-FK unique branch ran.
        if col.unique {
            def.unique_key();
        }
        // gaps2 #22: skip the physical `REFERENCES` clause when the FK
        // opted out of the DB constraint (cross-database FK). The
        // logical column + `fk_target` stay intact.
        if col.db_constraint {
            def.extra(format!(
                "REFERENCES \"{fk_target}\"(\"{pk_col_name}\"){}{PG_FK_DEFERRABLE}",
                fk_action_suffix(col),
            ));
        }
        return def;
    }

    let column_type = crate::backend::PostgresBackend.map_column(col);

    let mut def = ColumnDef::new_with_type(Alias::new(&col.name), column_type);
    if !col.nullable {
        def.not_null();
    }
    if col.primary_key {
        def.primary_key();
        if matches!(
            col.ty,
            SqlType::Integer | SqlType::BigInt | SqlType::SmallInt
        ) {
            def.auto_increment();
        }
    }
    // `#[umbral(unique)]` lifts to a column-level UNIQUE clause on
    // Postgres too. Skipped for PK columns (already unique).
    if col.unique && !col.primary_key {
        def.unique_key();
    }
    // IMP-3: numeric bounds CHECK. Mirrors the SQLite branch.
    if let Some(check) = check_min_max_sql(col) {
        def.extra(check);
    }
    // Single-valued Choices: emit a CHECK constraint so a third-party
    // process writing directly to the DB can't insert a value the Rust
    // enum can't model. MultiChoice carries the same choices/labels
    // metadata but the stored value is a CSV — a single-value `IN (...)`
    // constraint would reject every legal CSV. Validating "every CSV
    // piece is a known variant" needs a regex with per-variant
    // escaping, which we leave to the sqlx Decode path at v1.
    if !col.choices.is_empty() && !col.is_multichoice {
        let col_name_escaped = col.name.replace('"', "\"\"");
        let values_sql = col
            .choices
            .iter()
            .map(|v| format!("'{}'", v.replace('\'', "''")))
            .collect::<Vec<_>>()
            .join(", ");
        def.extra(format!("CHECK (\"{col_name_escaped}\" IN ({values_sql}))"));
    }
    // User-declared `#[umbral(default = "...")]` lifts to a DDL DEFAULT
    // clause. Required for `ALTER TABLE ADD COLUMN` of a NOT NULL
    // column against a non-empty table — Postgres needs either a
    // default or a separate backfill.
    if !col.default.is_empty() {
        def.default(col.default.clone());
    } else if (col.auto_now || col.auto_now_add)
        && matches!(
            col.ty,
            SqlType::Timestamptz | SqlType::Timestamp | SqlType::Date | SqlType::Time
        )
    {
        // Mirror of the SQLite branch above. Without a DEFAULT
        // Postgres rejects `ALTER TABLE ADD COLUMN ... NOT NULL`
        // on a populated table. `now()` evaluates per-row during
        // the backfill so every existing row gets a sane value;
        // future INSERTs override via the macro-emitted Rust path.
        def.default(sea_query::Expr::cust("now()"));
    }
    def
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashSet;

    // ---- gaps2 #100: squash_plan (pure squash-vs-originals decision) ----

    /// A minimal migration file for `plugin`/`id`; `replaces` lists the ids it
    /// squashes (all within `plugin`). Empty `replaces` = an ordinary migration.
    fn mf(plugin: &str, id: &str, replaces: &[&str]) -> MigrationFile {
        MigrationFile {
            id: id.to_string(),
            plugin: plugin.to_string(),
            depends_on: Vec::new(),
            operations: Vec::new(),
            snapshot_after: Snapshot::default(),
            replaces: replaces
                .iter()
                .map(|m| MigrationRef {
                    plugin: plugin.to_string(),
                    migration: m.to_string(),
                })
                .collect(),
        }
    }

    fn applied_set(plugin: &str, ids: &[&str]) -> HashSet<(String, String)> {
        ids.iter()
            .map(|id| (plugin.to_string(), id.to_string()))
            .collect()
    }

    #[test]
    fn squash_plan_plain_migrations_apply_when_unrecorded_skip_when_applied() {
        let files = vec![mf("app", "0001", &[]), mf("app", "0002", &[])];
        let applied = applied_set("app", &["0001"]);
        let plan = squash_plan(&files, &applied).unwrap();
        assert_eq!(plan, vec![ApplyDecision::Skip, ApplyDecision::Apply]);
    }

    #[test]
    fn squash_plan_fresh_db_applies_squash_and_shadows_its_originals() {
        // Both the squash and its originals are on disk (Django keeps both).
        // Nothing applied → run the squash once, skip every original.
        let files = vec![
            mf("app", "0001", &[]),
            mf("app", "0002", &[]),
            mf("app", "0001_squashed_0002", &["0001", "0002"]),
        ];
        let applied = applied_set("app", &[]);
        let plan = squash_plan(&files, &applied).unwrap();
        assert_eq!(
            plan,
            vec![
                ApplyDecision::Skip,  // 0001 shadowed by the squash
                ApplyDecision::Skip,  // 0002 shadowed by the squash
                ApplyDecision::Apply  // the squash builds the whole schema
            ]
        );
    }

    #[test]
    fn squash_plan_existing_db_with_full_history_record_only() {
        // Both originals already applied → the squash records itself without
        // running (its schema already exists), originals skipped.
        let files = vec![
            mf("app", "0001", &[]),
            mf("app", "0002", &[]),
            mf("app", "0001_squashed_0002", &["0001", "0002"]),
        ];
        let applied = applied_set("app", &["0001", "0002"]);
        let plan = squash_plan(&files, &applied).unwrap();
        assert_eq!(
            plan,
            vec![
                ApplyDecision::Skip,
                ApplyDecision::Skip,
                ApplyDecision::RecordOnly
            ]
        );
    }

    #[test]
    fn squash_plan_already_recorded_squash_is_skipped() {
        // The squash ran on a previous migrate; it's in the tracking table.
        let files = vec![
            mf("app", "0001", &[]),
            mf("app", "0002", &[]),
            mf("app", "0001_squashed_0002", &["0001", "0002"]),
        ];
        let applied = applied_set("app", &["0001_squashed_0002"]);
        let plan = squash_plan(&files, &applied).unwrap();
        // originals never applied but shadowed by the (already-applied) squash.
        assert_eq!(
            plan,
            vec![
                ApplyDecision::Skip,
                ApplyDecision::Skip,
                ApplyDecision::Skip
            ]
        );
    }

    #[test]
    fn squash_plan_partial_transition_falls_back_to_surviving_originals() {
        // 0001 applied, 0002 not; originals still on disk → ignore the squash,
        // finish 0002 individually.
        let files = vec![
            mf("app", "0001", &[]),
            mf("app", "0002", &[]),
            mf("app", "0001_squashed_0002", &["0001", "0002"]),
        ];
        let applied = applied_set("app", &["0001"]);
        let plan = squash_plan(&files, &applied).unwrap();
        assert_eq!(
            plan,
            vec![
                ApplyDecision::Skip,  // 0001 already applied
                ApplyDecision::Apply, // 0002 finishes individually
                ApplyDecision::Skip   // squash ignored during the transition
            ]
        );
    }

    #[test]
    fn squash_plan_partial_transition_with_missing_original_errors() {
        // 0001 applied, 0002 not, and 0002's file is GONE → can't reconcile.
        let files = vec![
            mf("app", "0001", &[]),
            mf("app", "0001_squashed_0002", &["0001", "0002"]),
        ];
        let applied = applied_set("app", &["0001"]);
        let err = squash_plan(&files, &applied).unwrap_err();
        match err {
            MigrateError::SquashInconsistent {
                plugin,
                squash,
                missing,
            } => {
                assert_eq!(plugin, "app");
                assert_eq!(squash, "0001_squashed_0002");
                assert_eq!(missing, vec!["app/0002".to_string()]);
            }
            other => panic!("expected SquashInconsistent, got {other:?}"),
        }
    }

    /// audit_2 core-migrate #7 — the advisory-lock key must be deterministic
    /// (every process computes the same key for the same target, so they
    /// mutually exclude) and distinct per discriminator (different aliases /
    /// schemas migrate concurrently). Pins the FNV constants so a refactor that
    /// changes the hash — silently breaking cross-process exclusion — fails.
    #[test]
    fn pg_migration_lock_key_is_deterministic_and_distinct() {
        // Deterministic: same input → same key, run to run, process to process.
        assert_eq!(
            pg_migration_lock_key("default"),
            pg_migration_lock_key("default"),
        );
        // Distinct: different aliases/schemas get different keys.
        assert_ne!(
            pg_migration_lock_key("default"),
            pg_migration_lock_key("replica"),
        );
        assert_ne!(
            pg_migration_lock_key("tenant_a"),
            pg_migration_lock_key("tenant_b"),
        );
        // Pin the exact value so the hash can't drift unnoticed (two binaries on
        // different umbral versions must still agree on the key).
        assert_eq!(
            pg_migration_lock_key("default"),
            {
                let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
                for b in b"umbral_migrations\0"
                    .iter()
                    .copied()
                    .chain(b"default".iter().copied())
                {
                    hash ^= b as u64;
                    hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
                }
                hash as i64
            },
            "the lock-key hash changed — this breaks cross-process exclusion \
             between an old and a new migrator; bump deliberately if intended",
        );
    }

    /// M8 — `plugin_order()` falls back to `registered_plugins()` when
    /// no topological order has been published. The fallback keeps the
    /// engine usable from low-level paths that drive `init_plugins`
    /// directly (the M5 / M6 tests that pre-date phase 1.5 of
    /// `App::build()`).
    ///
    /// Runs in the lib's unit-test binary, which is wholly separate
    /// from the integration test binaries and so owns its own copies
    /// of `REGISTRY` and `PLUGIN_ORDER`. This test seeds `REGISTRY` via
    /// `init_plugins`, never touches `init_plugin_order`, and pins the
    /// fallback to the sorted-by-name `registered_plugins()` output.
    /// As the only test that touches either OnceLock in this binary,
    /// it has them to itself.
    #[test]
    fn plugin_order_falls_back_to_registered_plugins_when_unpublished() {
        let mut per_plugin: std::collections::HashMap<String, Vec<ModelMeta>> =
            std::collections::HashMap::new();
        per_plugin.insert(
            "zeta".to_string(),
            vec![ModelMeta {
                view: None,
                materialized: false,
                name: "ZetaModel".to_string(),
                table: "zeta".to_string(),
                fields: Vec::new(),
                display: "ZetaModel".to_string(),
                icon: "database".to_string(),
                database: None,
                singleton: false,
                unique_together: Vec::new(),
                indexes: Vec::new(),
                ordering: Vec::new(),
                m2m_relations: Vec::new(),
                soft_delete: false,
                audited: false,
                app_label: "app".to_string(),
            }],
        );
        per_plugin.insert(
            "alpha".to_string(),
            vec![ModelMeta {
                view: None,
                materialized: false,
                name: "AlphaModel".to_string(),
                table: "alpha".to_string(),
                fields: Vec::new(),
                display: "AlphaModel".to_string(),
                icon: "database".to_string(),
                database: None,
                singleton: false,
                unique_together: Vec::new(),
                indexes: Vec::new(),
                ordering: Vec::new(),
                m2m_relations: Vec::new(),
                soft_delete: false,
                audited: false,
                app_label: "app".to_string(),
            }],
        );
        init_plugins(per_plugin);

        // `init_plugin_order` was never called, so `plugin_order` must
        // return the sorted-by-name fallback.
        let order = plugin_order();
        assert_eq!(
            order,
            vec!["alpha".to_string(), "zeta".to_string()],
            "fallback should sort by name; got {order:?}",
        );
        assert_eq!(
            order,
            registered_plugins(),
            "fallback should exactly equal registered_plugins()",
        );
    }

    /// Gap #65: `#[umbral(unique)]` lifts to a column-level UNIQUE in
    /// CREATE TABLE DDL on both backends. PK columns skip the clause
    /// because they're already unique by virtue of being the PK.
    #[test]
    fn unique_column_emits_unique_keyword_on_both_backends() {
        use sea_query::{Alias, PostgresQueryBuilder, SqliteQueryBuilder, Table};

        let id = Column {
            name: "id".into(),
            ty: SqlType::BigInt,
            primary_key: true,
            nullable: false,
            fk_target: None,
            noform: false,
            privileged: false,
            private: false,
            secret: false,
            db_constraint: true,
            noedit: false,
            auto_user_add: false,
            auto_user: false,
            is_string_repr: false,
            max_length: 0,
            choices: vec![],
            choice_labels: vec![],
            default: String::new(),
            is_multichoice: false,
            // Set even though it's a PK so we can assert below that
            // the emit path drops the redundant clause.
            unique: true,
            on_delete: crate::orm::FkAction::NoAction,
            on_update: crate::orm::FkAction::NoAction,
            index: false,
            auto_now_add: false,
            auto_uuid: false,
            auto_now: false,
            trim: false,
            lowercase: false,
            case_insensitive: false,
            help: String::new(),
            example: String::new(),
            widget: None,
            supported_backends: Vec::new(),
            min: None,
            max: None,
            text_format: ::core::option::Option::None,
            slug_from: ::core::option::Option::None,
        };
        let username = Column {
            name: "username".into(),
            ty: SqlType::Text,
            primary_key: false,
            nullable: false,
            fk_target: None,
            noform: false,
            privileged: false,
            private: false,
            secret: false,
            db_constraint: true,
            noedit: false,
            auto_user_add: false,
            auto_user: false,
            is_string_repr: false,
            max_length: 0,
            choices: vec![],
            choice_labels: vec![],
            default: String::new(),
            is_multichoice: false,
            unique: true,
            on_delete: crate::orm::FkAction::NoAction,
            on_update: crate::orm::FkAction::NoAction,
            index: false,
            auto_now_add: false,
            auto_uuid: false,
            auto_now: false,
            trim: false,
            lowercase: false,
            case_insensitive: false,
            help: String::new(),
            example: String::new(),
            widget: None,
            supported_backends: Vec::new(),
            min: None,
            max: None,
            text_format: ::core::option::Option::None,
            slug_from: ::core::option::Option::None,
        };
        let email = Column {
            name: "email".into(),
            ty: SqlType::Text,
            primary_key: false,
            nullable: false,
            fk_target: None,
            noform: false,
            privileged: false,
            private: false,
            secret: false,
            db_constraint: true,
            noedit: false,
            auto_user_add: false,
            auto_user: false,
            is_string_repr: false,
            max_length: 0,
            choices: vec![],
            choice_labels: vec![],
            default: String::new(),
            is_multichoice: false,
            unique: false,
            on_delete: crate::orm::FkAction::NoAction,
            on_update: crate::orm::FkAction::NoAction,
            index: false,
            auto_now_add: false,
            auto_uuid: false,
            auto_now: false,
            trim: false,
            lowercase: false,
            case_insensitive: false,
            help: String::new(),
            example: String::new(),
            widget: None,
            supported_backends: Vec::new(),
            min: None,
            max: None,
            text_format: ::core::option::Option::None,
            slug_from: ::core::option::Option::None,
        };

        for backend in ["sqlite", "postgres"] {
            let mut stmt = Table::create();
            stmt.table(Alias::new("u"));
            for col in [&id, &username, &email] {
                let mut def = if backend == "sqlite" {
                    build_column_def_sqlite(col)
                } else {
                    build_column_def_postgres(col)
                };
                stmt.col(&mut def);
            }
            let sql = if backend == "sqlite" {
                stmt.to_string(SqliteQueryBuilder)
            } else {
                stmt.to_string(PostgresQueryBuilder)
            };

            // UNIQUE on the explicitly-marked non-PK column.
            assert!(
                sql.contains("\"username\"") && sql.to_uppercase().contains("UNIQUE"),
                "{backend}: expected UNIQUE on username; got: {sql}",
            );
            // No UNIQUE on `email` (flag false).
            let email_clause = sql
                .split("\"email\"")
                .nth(1)
                .unwrap_or_default()
                .split(',')
                .next()
                .unwrap_or_default();
            assert!(
                !email_clause.to_uppercase().contains("UNIQUE"),
                "{backend}: email should not be UNIQUE; clause: {email_clause}",
            );
            // PK still PK; the redundant UNIQUE flag is dropped so we
            // don't double up the constraint.
            let id_clause = sql
                .split("\"id\"")
                .nth(1)
                .unwrap_or_default()
                .split(',')
                .next()
                .unwrap_or_default();
            assert!(
                id_clause.to_uppercase().contains("PRIMARY KEY"),
                "{backend}: id should still be PRIMARY KEY; clause: {id_clause}",
            );
            assert!(
                !id_clause.to_uppercase().contains("UNIQUE"),
                "{backend}: PK column should not also carry UNIQUE; clause: {id_clause}",
            );
        }
    }

    /// Gap #68: `on_delete` / `on_update` lift to the `REFERENCES`
    /// tail in DDL. `NoAction` emits no clause (the SQL default);
    /// any other variant emits `ON DELETE <kw>` / `ON UPDATE <kw>`
    /// on both backends. The clause goes inside the same `extra(...)`
    /// string that already carries `REFERENCES "<target>"("id")` —
    /// the test asserts the full tail shape so a future refactor
    /// that splits the FK rendering won't silently regress.
    #[test]
    fn fk_action_lifts_to_references_clause_on_both_backends() {
        use sea_query::{Alias, PostgresQueryBuilder, SqliteQueryBuilder, Table};

        // Need an FK target table; the DDL renderer looks up the
        // PK column type for `auth_user` via `fk_target_pk`.
        // Using "post" since it's already registered as a real
        // Model in the lib (resolves to BigInt id).
        let plain_fk = Column {
            name: "owner_id".into(),
            ty: SqlType::ForeignKey,
            primary_key: false,
            nullable: false,
            fk_target: Some("post".into()),
            noform: false,
            privileged: false,
            private: false,
            secret: false,
            db_constraint: true,
            noedit: false,
            auto_user_add: false,
            auto_user: false,
            is_string_repr: false,
            max_length: 0,
            choices: vec![],
            choice_labels: vec![],
            default: String::new(),
            is_multichoice: false,
            unique: false,
            on_delete: crate::orm::FkAction::NoAction,
            on_update: crate::orm::FkAction::NoAction,
            index: false,
            auto_now_add: false,
            auto_uuid: false,
            auto_now: false,
            trim: false,
            lowercase: false,
            case_insensitive: false,
            help: String::new(),
            example: String::new(),
            widget: None,
            supported_backends: Vec::new(),
            min: None,
            max: None,
            text_format: ::core::option::Option::None,
            slug_from: ::core::option::Option::None,
        };
        let cascade_fk = Column {
            on_delete: crate::orm::FkAction::Cascade,
            on_update: crate::orm::FkAction::Cascade,
            index: false,
            auto_now_add: false,
            auto_uuid: false,
            auto_now: false,
            trim: false,
            lowercase: false,
            case_insensitive: false,
            help: String::new(),
            example: String::new(),
            widget: None,
            supported_backends: Vec::new(),
            ..plain_fk.clone()
        };
        let restrict_fk = Column {
            on_delete: crate::orm::FkAction::Restrict,
            ..plain_fk.clone()
        };
        let set_null_fk = Column {
            nullable: true,
            on_delete: crate::orm::FkAction::SetNull,
            ..plain_fk.clone()
        };

        for backend in ["sqlite", "postgres"] {
            let render_one = |col: &Column| -> String {
                let mut stmt = Table::create();
                stmt.table(Alias::new("t"));
                let mut def = if backend == "sqlite" {
                    build_column_def_sqlite(col)
                } else {
                    build_column_def_postgres(col)
                };
                stmt.col(&mut def);
                if backend == "sqlite" {
                    stmt.to_string(SqliteQueryBuilder)
                } else {
                    stmt.to_string(PostgresQueryBuilder)
                }
            };

            // NoAction → REFERENCES with no tail clauses.
            let sql = render_one(&plain_fk);
            assert!(
                sql.contains("REFERENCES")
                    && !sql.to_uppercase().contains("ON DELETE")
                    && !sql.to_uppercase().contains("ON UPDATE"),
                "{backend}: NoAction should emit REFERENCES alone; got: {sql}",
            );

            // Cascade on both ON DELETE and ON UPDATE.
            let sql = render_one(&cascade_fk);
            assert!(
                sql.to_uppercase().contains("ON DELETE CASCADE")
                    && sql.to_uppercase().contains("ON UPDATE CASCADE"),
                "{backend}: Cascade should emit both clauses; got: {sql}",
            );

            // Restrict on ON DELETE only; ON UPDATE is NoAction so
            // no clause appears.
            let sql = render_one(&restrict_fk);
            assert!(
                sql.to_uppercase().contains("ON DELETE RESTRICT"),
                "{backend}: Restrict missing; got: {sql}",
            );
            assert!(
                !sql.to_uppercase().contains("ON UPDATE"),
                "{backend}: ON UPDATE shouldn't appear for NoAction; got: {sql}",
            );

            // SET NULL renders verbatim (two-word keyword).
            let sql = render_one(&set_null_fk);
            assert!(
                sql.to_uppercase().contains("ON DELETE SET NULL"),
                "{backend}: SET NULL missing; got: {sql}",
            );
        }
    }

    /// Gap #65 follow-up: the diff engine detects changes to *every*
    /// schema-meaningful field, not just `ty` and `nullable`. Each
    /// branch builds a baseline column, mutates one field, runs
    /// `diff_columns`, and asserts an `AlterColumn` op is produced.
    /// Catches the regression where toggling `unique` or `on_delete`
    /// would silently leave the table unchanged.
    #[test]
    fn diff_detects_all_schema_meaningful_field_changes() {
        fn baseline() -> Column {
            Column {
                name: "x".into(),
                ty: SqlType::Text,
                primary_key: false,
                nullable: false,
                fk_target: None,
                noform: false,
                privileged: false,
                private: false,
                secret: false,
                db_constraint: true,
                noedit: false,
                auto_user_add: false,
                auto_user: false,
                is_string_repr: false,
                max_length: 0,
                choices: vec![],
                choice_labels: vec![],
                default: String::new(),
                is_multichoice: false,
                unique: false,
                on_delete: crate::orm::FkAction::NoAction,
                on_update: crate::orm::FkAction::NoAction,
                index: false,
                auto_now_add: false,
                auto_uuid: false,
                auto_now: false,
                trim: false,
                lowercase: false,
                case_insensitive: false,
                help: String::new(),
                example: String::new(),
                widget: None,
                supported_backends: Vec::new(),
                min: None,
                max: None,
                text_format: ::core::option::Option::None,
                slug_from: ::core::option::Option::None,
            }
        }
        fn meta_with(col: Column) -> ModelMeta {
            ModelMeta {
                view: None,
                materialized: false,
                name: "M".into(),
                table: "m".into(),
                fields: vec![col],
                display: "M".into(),
                icon: "database".into(),
                database: None,
                singleton: false,
                unique_together: Vec::new(),
                indexes: Vec::new(),
                ordering: Vec::new(),
                m2m_relations: Vec::new(),
                soft_delete: false,
                audited: false,
                app_label: "app".into(),
            }
        }
        let prev = meta_with(baseline());
        // Safe-to-alter changes: each must surface as an `AlterColumn`.
        // (`nullable` here is false→true — a *loosening*, which is safe;
        // the tightening direction is guarded separately below.)
        let safe_mutations: Vec<(&str, fn(&mut Column))> = vec![
            ("default", |c| c.default = "hello".into()),
            ("choices", |c| {
                c.choices = vec!["a".into(), "b".into()];
                c.choice_labels = vec!["A".into(), "B".into()];
            }),
            ("nullable", |c| c.nullable = true),
        ];
        for (label, mutate) in safe_mutations {
            let mut col = baseline();
            mutate(&mut col);
            let current = meta_with(col);
            let ops = diff_columns("M", &prev, &current).expect("diff should succeed");
            assert!(
                !ops.is_empty(),
                "{label}: diff should produce at least one op; got none",
            );
            assert!(
                ops.iter()
                    .any(|op| matches!(op, Operation::AlterColumn { column, .. } if column == "x")),
                "{label}: expected AlterColumn on `x`; got: {ops:?}",
            );
        }

        // Adding UNIQUE to an existing column is detected too, but as an
        // `UnsafeAlter` guard rather than a bare `AlterColumn`: dropping a
        // UNIQUE constraint onto a populated column aborts the migration
        // if duplicates already exist, so the engine refuses it with a
        // duplicate-pre-check message instead of silently emitting it.
        let mut col = baseline();
        col.unique = true;
        let current = meta_with(col);
        match diff_columns("M", &prev, &current) {
            Err(MigrateError::UnsafeAlter { column, reason, .. }) => {
                assert_eq!(column, "x");
                assert!(
                    reason.contains("UNIQUE"),
                    "unsafe-alter reason should mention UNIQUE; got: {reason}",
                );
            }
            other => panic!("unique add should be an UnsafeAlter guard; got: {other:?}"),
        }
    }

    /// Gap #65 follow-up: the Postgres `AlterColumn` render handles
    /// the new diff types (unique, default, choices, FK actions)
    /// with native `ALTER TABLE ... ADD/DROP CONSTRAINT` /
    /// `SET/DROP DEFAULT` statements. SQLite is unchanged — the
    /// rebuild dance already swallows any column metadata change.
    #[test]
    fn postgres_alter_column_renders_constraint_changes() {
        let baseline = Column {
            name: "x".into(),
            ty: SqlType::Text,
            primary_key: false,
            nullable: false,
            fk_target: None,
            noform: false,
            privileged: false,
            private: false,
            secret: false,
            db_constraint: true,
            noedit: false,
            auto_user_add: false,
            auto_user: false,
            is_string_repr: false,
            max_length: 0,
            choices: vec![],
            choice_labels: vec![],
            default: String::new(),
            is_multichoice: false,
            unique: false,
            on_delete: crate::orm::FkAction::NoAction,
            on_update: crate::orm::FkAction::NoAction,
            index: false,
            auto_now_add: false,
            auto_uuid: false,
            auto_now: false,
            trim: false,
            lowercase: false,
            case_insensitive: false,
            help: String::new(),
            example: String::new(),
            widget: None,
            supported_backends: Vec::new(),
            min: None,
            max: None,
            text_format: ::core::option::Option::None,
            slug_from: ::core::option::Option::None,
        };

        // unique false → true: emit ADD CONSTRAINT ... UNIQUE
        let mut new = baseline.clone();
        new.unique = true;
        let stmts = render_alter_column_postgres("m", "x", &[new], Some(&[baseline.clone()]));
        let joined = stmts.join("\n");
        assert!(
            joined.contains("ADD CONSTRAINT") && joined.contains("UNIQUE"),
            "unique add: expected ADD CONSTRAINT UNIQUE; got: {joined}",
        );

        // unique true → false: emit DROP CONSTRAINT ... IF EXISTS
        let prev_unique = Column {
            unique: true,
            ..baseline.clone()
        };
        let stmts =
            render_alter_column_postgres("m", "x", &[baseline.clone()], Some(&[prev_unique]));
        let joined = stmts.join("\n");
        assert!(
            joined.contains("DROP CONSTRAINT IF EXISTS"),
            "unique drop: expected DROP CONSTRAINT IF EXISTS; got: {joined}",
        );

        // default empty → "hello": SET DEFAULT 'hello'
        let mut new = baseline.clone();
        new.default = "hello".into();
        let stmts = render_alter_column_postgres("m", "x", &[new], Some(&[baseline.clone()]));
        let joined = stmts.join("\n");
        assert!(
            joined.contains("SET DEFAULT 'hello'"),
            "default set: expected SET DEFAULT; got: {joined}",
        );

        // default "hello" → empty: DROP DEFAULT
        let prev_default = Column {
            default: "hello".into(),
            ..baseline.clone()
        };
        let stmts =
            render_alter_column_postgres("m", "x", &[baseline.clone()], Some(&[prev_default]));
        let joined = stmts.join("\n");
        assert!(
            joined.contains("DROP DEFAULT"),
            "default drop: expected DROP DEFAULT; got: {joined}",
        );

        // FK on_delete change → DROP + readd FK with new clause
        let fk_baseline = Column {
            ty: SqlType::ForeignKey,
            fk_target: Some("other".into()),
            ..baseline.clone()
        };
        let fk_cascade = Column {
            on_delete: crate::orm::FkAction::Cascade,
            ..fk_baseline.clone()
        };
        let stmts = render_alter_column_postgres("m", "x", &[fk_cascade], Some(&[fk_baseline]));
        let joined = stmts.join("\n");
        assert!(
            joined.contains("DROP CONSTRAINT IF EXISTS")
                && joined.contains("FOREIGN KEY")
                && joined.contains("ON DELETE CASCADE"),
            "FK cascade add: expected drop+readd with ON DELETE CASCADE; got: {joined}",
        );
    }

    /// IMP-2 from bugs/tests/testBugs.md: a `#[umbral(default = "true")]`
    /// on a boolean column used to land as `DEFAULT 'true'` on
    /// SQLite, which decode-fails on read (column type is INTEGER,
    /// the stored TEXT can't deserialize as `bool`). The SQLite
    /// renderer now maps the string to `1` / `0`.
    #[test]
    fn sqlite_bool_default_translates_to_integer_literal() {
        use sea_query::{Alias, SqliteQueryBuilder, Table};

        let bool_col = Column {
            name: "is_active".into(),
            ty: SqlType::Boolean,
            primary_key: false,
            nullable: false,
            fk_target: None,
            noform: false,
            privileged: false,
            private: false,
            secret: false,
            db_constraint: true,
            noedit: false,
            auto_user_add: false,
            auto_user: false,
            is_string_repr: false,
            max_length: 0,
            choices: vec![],
            choice_labels: vec![],
            default: "true".into(),
            is_multichoice: false,
            unique: false,
            on_delete: crate::orm::FkAction::NoAction,
            on_update: crate::orm::FkAction::NoAction,
            index: false,
            auto_now_add: false,
            auto_uuid: false,
            auto_now: false,
            trim: false,
            lowercase: false,
            case_insensitive: false,
            help: String::new(),
            example: String::new(),
            widget: None,
            supported_backends: Vec::new(),
            min: None,
            max: None,
            text_format: ::core::option::Option::None,
            slug_from: ::core::option::Option::None,
        };
        let mut stmt = Table::create();
        stmt.table(Alias::new("t"));
        let mut def = build_column_def_sqlite(&bool_col);
        stmt.col(&mut def);
        let sql = stmt.to_string(SqliteQueryBuilder);
        assert!(
            sql.contains("DEFAULT 1") && !sql.contains("DEFAULT 'true'"),
            "bool default 'true' on sqlite should render as DEFAULT 1; got: {sql}",
        );

        // "false" → 0
        let mut bool_col_false = bool_col.clone();
        bool_col_false.default = "false".into();
        let mut stmt = Table::create();
        stmt.table(Alias::new("t"));
        let mut def = build_column_def_sqlite(&bool_col_false);
        stmt.col(&mut def);
        let sql = stmt.to_string(SqliteQueryBuilder);
        assert!(
            sql.contains("DEFAULT 0") && !sql.contains("DEFAULT 'false'"),
            "bool default 'false' on sqlite should render as DEFAULT 0; got: {sql}",
        );

        // Non-bool columns are untouched (text default stays
        // single-quoted literal).
        let text_col = Column {
            name: "label".into(),
            ty: SqlType::Text,
            default: "hello".into(),
            ..bool_col.clone()
        };
        let mut stmt = Table::create();
        stmt.table(Alias::new("t"));
        let mut def = build_column_def_sqlite(&text_col);
        stmt.col(&mut def);
        let sql = stmt.to_string(SqliteQueryBuilder);
        assert!(
            sql.contains("DEFAULT 'hello'"),
            "text default should stay quoted; got: {sql}",
        );
    }

    /// BUG-4 from bugs/tests/testBugs.md: `#[umbral(index)]` lifts
    /// to a `CREATE INDEX IF NOT EXISTS idx_<table>_<col>` statement
    /// alongside the `CREATE TABLE`. The index is skipped on PK
    /// and UNIQUE columns (those are already indexed by the
    /// constraint).
    #[test]
    fn index_attribute_emits_create_index_alongside_create_table() {
        let id = Column {
            name: "id".into(),
            ty: SqlType::BigInt,
            primary_key: true,
            nullable: false,
            fk_target: None,
            noform: false,
            privileged: false,
            private: false,
            secret: false,
            db_constraint: true,
            noedit: false,
            auto_user_add: false,
            auto_user: false,
            is_string_repr: false,
            max_length: 0,
            choices: vec![],
            choice_labels: vec![],
            default: String::new(),
            is_multichoice: false,
            unique: false,
            on_delete: crate::orm::FkAction::NoAction,
            on_update: crate::orm::FkAction::NoAction,
            // PK with index=true; the renderer should skip the
            // extra CREATE INDEX because the PK constraint
            // already covers it.
            index: true,
            auto_now_add: false,
            auto_uuid: false,
            auto_now: false,
            trim: false,
            lowercase: false,
            case_insensitive: false,
            help: String::new(),
            example: String::new(),
            widget: None,
            supported_backends: Vec::new(),
            min: None,
            max: None,
            text_format: ::core::option::Option::None,
            slug_from: ::core::option::Option::None,
        };
        let slug = Column {
            name: "slug".into(),
            ty: SqlType::Text,
            primary_key: false,
            nullable: false,
            index: true,
            auto_now_add: false,
            auto_uuid: false,
            auto_now: false,
            trim: false,
            lowercase: false,
            case_insensitive: false,
            help: String::new(),
            example: String::new(),
            widget: None,
            supported_backends: Vec::new(),
            ..id.clone()
        };
        let title = Column {
            name: "title".into(),
            ty: SqlType::Text,
            primary_key: false,
            nullable: false,
            index: false,
            auto_now_add: false,
            auto_uuid: false,
            auto_now: false,
            trim: false,
            lowercase: false,
            case_insensitive: false,
            help: String::new(),
            example: String::new(),
            widget: None,
            supported_backends: Vec::new(),
            ..id.clone()
        };
        let op = Operation::CreateTable {
            table: "post".into(),
            columns: vec![id, slug, title],
            unique_together: Vec::new(),
            indexes: Vec::new(),
        };

        for backend in ["sqlite", "postgres"] {
            let stmts = render_operation_for(&op, backend);
            assert!(
                stmts
                    .iter()
                    .any(|s| s.to_uppercase().contains("CREATE TABLE")),
                "{backend}: expected a CREATE TABLE; got: {stmts:?}",
            );
            let index_stmts: Vec<_> = stmts
                .iter()
                .filter(|s| s.to_uppercase().contains("CREATE INDEX"))
                .collect();
            assert_eq!(
                index_stmts.len(),
                1,
                "{backend}: expected exactly one CREATE INDEX (on `slug`); got {index_stmts:?}",
            );
            let ix = index_stmts[0];
            assert!(
                ix.contains("\"idx_post_slug\"") && ix.contains("(\"slug\")"),
                "{backend}: index should target post(slug); got: {ix}",
            );
            assert!(
                ix.to_uppercase().contains("IF NOT EXISTS"),
                "{backend}: should be idempotent via IF NOT EXISTS; got: {ix}",
            );
        }
    }

    /// gaps3 #35: a `#[umbral(case_insensitive)]` text column renders
    /// per-backend — SQLite `COLLATE NOCASE`, Postgres `citext` with an
    /// idempotent `CREATE EXTENSION` emitted before the table.
    #[test]
    fn case_insensitive_column_renders_per_backend() {
        let id = Column {
            name: "id".into(),
            ty: SqlType::BigInt,
            primary_key: true,
            nullable: false,
            fk_target: None,
            noform: false,
            privileged: false,
            private: false,
            secret: false,
            db_constraint: true,
            noedit: false,
            auto_user_add: false,
            auto_user: false,
            is_string_repr: false,
            max_length: 0,
            choices: vec![],
            choice_labels: vec![],
            default: String::new(),
            is_multichoice: false,
            unique: false,
            on_delete: crate::orm::FkAction::NoAction,
            on_update: crate::orm::FkAction::NoAction,
            index: false,
            auto_now_add: false,
            auto_uuid: false,
            auto_now: false,
            trim: false,
            lowercase: false,
            case_insensitive: false,
            help: String::new(),
            example: String::new(),
            widget: None,
            supported_backends: Vec::new(),
            min: None,
            max: None,
            text_format: None,
            slug_from: None,
        };
        let name = Column {
            name: "name".into(),
            ty: SqlType::Text,
            primary_key: false,
            unique: true,
            case_insensitive: true,
            ..id.clone()
        };
        let op = Operation::CreateTable {
            table: "handle".into(),
            columns: vec![id, name],
            unique_together: Vec::new(),
            indexes: Vec::new(),
        };

        // SQLite: COLLATE NOCASE on the column; no extension.
        let sqlite = render_operation_for(&op, "sqlite");
        let create = sqlite
            .iter()
            .find(|s| s.to_uppercase().contains("CREATE TABLE"))
            .expect("a CREATE TABLE");
        assert!(
            create.to_uppercase().contains("COLLATE NOCASE"),
            "sqlite case_insensitive column must carry COLLATE NOCASE; got: {create}"
        );
        assert!(
            !sqlite
                .iter()
                .any(|s| s.to_uppercase().contains("EXTENSION")),
            "sqlite must not emit a citext extension; got: {sqlite:?}"
        );

        // Postgres: citext type + CREATE EXTENSION IF NOT EXISTS citext, and the
        // extension statement precedes the CREATE TABLE.
        let pg = render_operation_for(&op, "postgres");
        let ext_idx = pg
            .iter()
            .position(|s| s.to_uppercase().contains("CREATE EXTENSION") && s.contains("citext"))
            .expect("a CREATE EXTENSION citext statement");
        let create_idx = pg
            .iter()
            .position(|s| s.to_uppercase().contains("CREATE TABLE"))
            .expect("a CREATE TABLE");
        assert!(
            ext_idx < create_idx,
            "the citext extension must be created before the table; got: {pg:?}"
        );
        assert!(
            pg[create_idx].to_lowercase().contains("citext"),
            "postgres case_insensitive column must render as citext; got: {}",
            pg[create_idx]
        );
        assert!(
            pg[ext_idx].to_uppercase().contains("IF NOT EXISTS"),
            "the extension create must be idempotent; got: {}",
            pg[ext_idx]
        );
    }

    /// Regression: adding an `auto_now` / `auto_now_add` column to an
    /// existing populated table.
    ///
    ///   - SQLite: a 2-statement sequence (nullable ADD + UPDATE
    ///     backfill) since SQLite refuses non-constant defaults in
    ///     ALTER. The column ends up nullable at the DB level;
    ///     Rust still enforces non-null at the type level.
    ///   - Postgres: a single ALTER with `DEFAULT now()` — Postgres
    ///     allows the non-constant default and backfills inline.
    #[test]
    fn auto_now_add_column_renders_safe_backfill_per_backend() {
        for (label, auto_now, auto_now_add) in
            [("auto_now", true, false), ("auto_now_add", false, true)]
        {
            let col = Column {
                name: "updated_at".to_string(),
                ty: SqlType::Timestamptz,
                primary_key: false,
                nullable: false,
                fk_target: None,
                noform: false,
                privileged: false,
                private: false,
                secret: false,
                db_constraint: true,
                noedit: false,
                auto_user_add: false,
                auto_user: false,
                is_string_repr: false,
                max_length: 0,
                choices: Vec::new(),
                choice_labels: Vec::new(),
                default: String::new(),
                is_multichoice: false,
                unique: false,
                on_delete: crate::orm::FkAction::NoAction,
                on_update: crate::orm::FkAction::NoAction,
                index: false,
                auto_now_add,
                auto_uuid: false,
                auto_now,
                trim: false,
                lowercase: false,
                case_insensitive: false,
                help: String::new(),
                example: String::new(),
                widget: None,
                supported_backends: Vec::new(),
                min: None,
                max: None,
                text_format: None,
                slug_from: None,
            };

            // SQLite: the AddColumn op must produce TWO statements:
            // an ADD COLUMN nullable + an UPDATE backfill. The ADD
            // must NOT carry `NOT NULL` (otherwise SQLite rejects
            // it on the populated rows), and must NOT carry a
            // DEFAULT (otherwise SQLite rejects the non-constant).
            let op = Operation::AddColumn {
                table: "customer".to_string(),
                column: col.clone(),
            };
            let stmts = render_operation_sqlite(&op);
            assert_eq!(
                stmts.len(),
                2,
                "{label} SQLite: must emit ADD + UPDATE, got: {stmts:?}",
            );
            let add_sql = stmts[0].to_uppercase();
            assert!(
                add_sql.contains("ADD COLUMN"),
                "{label} SQLite: first stmt must be ADD COLUMN, got: {}",
                stmts[0],
            );
            assert!(
                !add_sql.contains("NOT NULL"),
                "{label} SQLite: ADD COLUMN must be nullable (NOT NULL = SQLite reject), got: {}",
                stmts[0],
            );
            assert!(
                !add_sql.contains("DEFAULT"),
                "{label} SQLite: ADD COLUMN must omit DEFAULT (non-constant = SQLite reject), got: {}",
                stmts[0],
            );
            let backfill_sql = &stmts[1];
            assert!(
                backfill_sql.contains("UPDATE") && backfill_sql.contains("datetime('now')"),
                "{label} SQLite: second stmt must be backfill UPDATE, got: {backfill_sql}",
            );

            // Postgres: single ALTER with NOT NULL + DEFAULT now().
            let pstmts = render_operation_postgres(&op);
            assert_eq!(
                pstmts.len(),
                1,
                "{label} Postgres: single statement suffices, got: {pstmts:?}",
            );
            let p = &pstmts[0];
            assert!(
                p.to_lowercase().contains("default now()"),
                "{label} Postgres: expected DEFAULT now() in ALTER, got: {p}",
            );
            assert!(
                p.to_uppercase().contains("NOT NULL"),
                "{label} Postgres: keeps NOT NULL (Postgres allows non-constant defaults), got: {p}",
            );
        }
    }

    /// Audit core-migrate #14 — raw DDL that interpolates
    /// developer-supplied identifiers must escape inner double quotes by
    /// doubling them (the quoting idiom used everywhere else), not strip
    /// or pass them through verbatim. A `"` in a table name previously
    /// produced malformed DDL in the multi-column index helper (ON-clause
    /// table was quote-stripped) and the M2M junction DDL (five raw
    /// interpolations).
    #[test]
    fn raw_ddl_escapes_quoted_identifiers() {
        // Multi-column index: the ON-clause table reference must carry
        // the doubled quote, not a stripped one.
        let idx = create_multi_index_stmt("we\"ird", &["a\"b".to_string(), "c".to_string()]);
        assert!(
            idx.contains("ON \"we\"\"ird\""),
            "multi-index ON clause must escape the quote (doubled); got: {idx}",
        );
        assert!(
            idx.contains("\"a\"\"b\""),
            "multi-index column list must escape the quote; got: {idx}",
        );

        // M2M junction DDL: every interpolated identifier escapes its
        // inner quote. Check both backends.
        let op = Operation::CreateM2MTable {
            junction_table: "j\"t".to_string(),
            parent_table: "p\"t".to_string(),
            parent_col: "p\"c".to_string(),
            child_table: "c\"t".to_string(),
            child_col: "c\"c".to_string(),
            parent_ty: SqlType::BigInt,
            child_ty: SqlType::Text,
        };
        for backend in ["sqlite", "postgres"] {
            let sql = render_operation_for(&op, backend).join("\n");
            for (raw, escaped) in [
                ("j\"t", "\"j\"\"t\""),
                ("p\"t", "\"p\"\"t\""),
                ("p\"c", "\"p\"\"c\""),
                ("c\"t", "\"c\"\"t\""),
                ("c\"c", "\"c\"\"c\""),
            ] {
                assert!(
                    sql.contains(escaped),
                    "{backend}: identifier `{raw}` must render escaped as {escaped}; got: {sql}",
                );
            }
        }
    }
}

/// A `#[derive(Model)]` type's self-registration (gaps3 #46).
///
/// The derive submits one of these into a link-time slice, so
/// `AppBuilder::auto_models()` can discover every model the binary links without
/// the app naming each one. It stores a *function* rather than a `ModelMeta`
/// because `ModelMeta::for_::<T>()` isn't const — the meta is built on demand at
/// boot.
pub struct ModelRegistration {
    /// Builds this model's meta.
    pub meta: fn() -> ModelMeta,
    /// `module_path!()` at the derive site (gaps4 #40) — lets
    /// [`models_registered_in`] filter the slice down to one crate's models,
    /// so a plugin's `models()` can be `umbral::discovered_models!()` instead
    /// of a hand-maintained `ModelMeta::for_::<T>()` list.
    pub module_path: &'static str,
}

inventory::collect!(ModelRegistration);

/// Every model that self-registered via `#[derive(Model)]` in the linked binary.
pub fn link_registered_models() -> Vec<ModelMeta> {
    inventory::iter::<ModelRegistration>
        .into_iter()
        .map(|r| (r.meta)())
        .collect()
}

/// The self-registered models whose defining CRATE matches `caller_path`'s
/// crate (gaps4 #40) — the engine behind `umbral::discovered_models!()`.
///
/// Matching is by the first `::` segment of `module_path!()`, i.e. the crate
/// name, so models in submodules (`my_plugin::models::Post`) are found from a
/// `models()` impl at the crate root. Inherits `auto_models()`' documented
/// linker caveat: a model object file nothing references can be dropped and
/// would then be missing here — if a table must NEVER silently go missing,
/// list it explicitly.
pub fn models_registered_in(caller_path: &str) -> Vec<ModelMeta> {
    let crate_root = caller_path.split("::").next().unwrap_or(caller_path);
    inventory::iter::<ModelRegistration>
        .into_iter()
        .filter(|r| r.module_path.split("::").next() == Some(crate_root))
        .map(|r| (r.meta)())
        .collect()
}