umbral-core 0.0.4

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
//! 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> {
    REGISTRY
        .get()
        .expect("umbral: model registry not initialised — did you call App::build()?")
        .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,
    /// 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,
            app_label: default_app_label(),
        }
    }
}

/// 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,
            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.
///
/// M5 v1 shipped table-level ops; M8 v1 adds `AddColumn` and
/// `DropColumn`. `AlterColumn`, index / constraint ops, and
/// `RunSql` / `RunCode` are deferred (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 },
    /// 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>,
        /// 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>,
    },
    /// 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>,
    },
}

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::CreateTable { table, .. }
            | Operation::DropTable { table }
            | Operation::AddColumn { table, .. }
            | Operation::DropColumn { table, .. }
            | Operation::AlterColumn { table, .. }
            | Operation::RenameColumn { 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,
    /// 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_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::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)
}

/// 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('"', ""),
    )
}

/// 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('"', ""),
    )
}

/// 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 {
    if columns.is_empty() {
        return String::new();
    }
    let t = table.replace('"', "");
    let name_suffix = columns
        .iter()
        .map(|c| c.replace('"', ""))
        .collect::<Vec<_>>()
        .join("_");
    let col_list = columns
        .iter()
        .map(|c| format!("\"{}\"", c.replace('"', "\"\"")))
        .collect::<Vec<_>>()
        .join(", ");
    format!(
        "CREATE INDEX IF NOT EXISTS \"idx_{t}_{name_suffix}\" ON \"{t}\" ({col_list})",
        t = t.replace('"', "\"\""),
    )
}

/// 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",
        SqlType::Text | SqlType::Uuid => "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
}

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,
            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_now: f.auto_now,
            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,
}

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

/// 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()
    }
}

/// 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> },
}

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(", ")
            ),
        }
    }
}

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,
        };

        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,
    };

    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)
}

/// 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)?;

        for path in paths {
            let file = read_migration_file(&path)?;
            if applied.contains(&(file.plugin.clone(), file.id.clone())) {
                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 mut tx = pool.begin().await?;
            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 (?, ?, ?, ?)",
            )
            .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)
}

/// Postgres per-alias variant. Mirror of `run_in_sqlite_for_alias`.
async fn run_in_postgres_for_alias(
    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)?;

        for path in paths {
            let file = read_migration_file(&path)?;
            if applied.contains(&(file.plugin.clone(), file.id.clone())) {
                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?;
            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) => {
            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)?;

        for path in paths {
            let file = read_migration_file(&path)?;
            if applied.contains(&(file.plugin.clone(), file.id.clone())) {
                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?;
            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);
        for path in list_migration_files(&plugin_dir)? {
            let file = read_migration_file(&path)?;
            if applied.contains(&(file.plugin.clone(), file.id.clone())) {
                continue;
            }
            if shared_apps.contains(&file.plugin) {
                continue;
            }
            let mut tx = pool.begin().await?;
            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);
        for path in list_migration_files(&plugin_dir)? {
            let file = read_migration_file(&path)?;
            if applied.contains(&(file.plugin.clone(), file.id.clone())) {
                continue;
            }
            if shared_apps.contains(&file.plugin) {
                continue;
            }
            let mut tx = pool.begin().await?;
            for op in &file.operations {
                for sql in render_operation_for(op, "sqlite") {
                    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 (?, ?, ?, ?)",
            )
            .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)
}

/// `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();
    for path in &paths {
        let file = read_migration_file(path)?;
        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) {
            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
}

/// 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 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)?;

    // 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,

        // 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
            }
        }

        // 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(),
        ),
    }
}

/// 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.
pub fn diff(previous: &Snapshot, current: &Snapshot) -> Result<Vec<Operation>, MigrateError> {
    use std::collections::{BTreeMap, HashSet};

    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();

    // ---- 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(),
                });
                // After the rename the columns might also have changed; diff them.
                let col_ops = diff_columns(name, prev, curr)?;
                ops.extend(col_ops);
            }
            Some(prev) if prev == curr => {}
            Some(prev) => {
                ops.extend(diff_columns(name, 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.

    let mut paired_drop_tables: HashSet<&str> = HashSet::new();
    let mut paired_create_tables: HashSet<&str> = HashSet::new();

    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;
            }
            let drop_shape = column_shape(&drop.fields);
            if create_shape == drop_shape {
                eprintln!(
                    "umbral makemigrations: rename detected (column-shape match): \
                     `{}` → `{}` — please verify this is a rename and not a coincidental \
                     column-shape match between two unrelated models",
                    drop.table, create.table
                );
                ops.push(Operation::RenameTable {
                    from: drop.table.clone(),
                    to: create.table.clone(),
                });
                paired_drop_tables.insert(drop.table.as_str());
                paired_create_tables.insert(create.table.as_str());
                break;
            }
        }
    }

    // ---- 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. Renames of the parent
    // model trip a Drop + Create on the junction; the rename-tracking
    // we'd need to do better is ambitious enough to defer.
    let prev_m2m = collect_m2m_pairs(previous);
    let curr_m2m = collect_m2m_pairs(current);
    for (key, spec) in &curr_m2m {
        if prev_m2m.contains_key(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) {
            continue;
        }
        // M2M field removed (or its parent was dropped). The junction
        // table goes away.
        ops.push(Operation::DropM2MTable {
            junction_table: spec.junction_table.clone(),
        });
    }

    Ok(ops)
}

/// 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(|m| pk_col_and_ty(m))
        .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
            | Uuid | Inet | Cidr | MacAddr | ForeignKey,
            Text,
        ) => 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.
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",
        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)",
        // 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();
    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(),
                });
            }
            // Any schema-meaningful field change triggers AlterColumn.
            // UI-only flags (`noform`, `noedit`, `max_length`,
            // `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 snapshot still updates because the next
            // CreateTable in the migration stream carries the flag.
            if type_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
                || prev_col.index != curr_col.index
            {
                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).
    let new_columns: Vec<Column> = current.fields.clone();
    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()),
        });
    }

    // 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}"),
        [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::RunSql { .. }] => "run_sql".to_string(),
        _ => "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")
}

/// 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 {
        Operation::CreateTable {
            table,
            columns,
            unique_together,
            indexes,
        } => {
            // sea-query's TableCreateStatement renders columns inline.
            // For composite UNIQUE constraints, we append them via
            // `stmt.index(Index::create().unique().col(...))` — works on
            // both backends and uses sea-query's quoting.
            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);
            }
            for group in unique_together {
                let mut idx = sea_query::Index::create().unique().to_owned();
                for col in group {
                    idx.col(Alias::new(col));
                }
                stmt.index(&mut idx);
            }
            let mut stmts = vec![stmt.build(SqliteQueryBuilder)];
            // 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
        }
        Operation::DropTable { table } => vec![
            Table::drop()
                .table(Alias::new(table))
                .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::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));
                let mut def = build_column_def_sqlite(column);
                stmt.add_column(&mut def);
                vec![stmt.build(SqliteQueryBuilder)]
            };
            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),
        ],
        Operation::AlterColumn {
            table,
            column: _,
            new_columns,
            prev_columns: _,
        } => render_alter_column_dance_sqlite(table, new_columns),
        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,
                pt = parent_table,
                pc = parent_col,
                ct = child_table,
                cc = child_col,
                pty = m2m_pk_sql_type_sqlite(*parent_ty),
                cty = m2m_pk_sql_type_sqlite(*child_ty),
            )]
        }
        Operation::DropM2MTable { junction_table } => vec![
            Table::drop()
                .table(Alias::new(junction_table))
                .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()],
    }
}

/// 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 {
        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);
            }
            for group in unique_together {
                let mut idx = sea_query::Index::create().unique().to_owned();
                for col in group {
                    idx.col(Alias::new(col));
                }
                stmt.index(&mut idx);
            }
            let mut stmts = vec![stmt.build(PostgresQueryBuilder)];
            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 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));
            }
            stmts
        }
        Operation::DropTable { table } => vec![
            Table::drop()
                .table(Alias::new(table))
                .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 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(PostgresQueryBuilder),
        ],
        Operation::AlterColumn {
            table,
            column,
            new_columns,
            prev_columns,
        } => 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,
    "child_id" {cty} NOT NULL REFERENCES "{ct}"("{cc}") ON DELETE CASCADE,
    PRIMARY KEY ("parent_id", "child_id")
)"#,
                jt = junction_table,
                pt = parent_table,
                pc = parent_col,
                ct = child_table,
                cc = child_col,
                pty = m2m_pk_sql_type_postgres(*parent_ty),
                cty = m2m_pk_sql_type_postgres(*child_ty),
            )]
        }
        Operation::DropM2MTable { junction_table } => vec![
            Table::drop()
                .table(Alias::new(junction_table))
                .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()],
    }
}

/// 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. 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.
fn render_alter_column_dance_sqlite(table: &str, new_columns: &[Column]) -> 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. Same column list both sides; the
    // dance only handles nullable flips (columns are otherwise
    // identical). Each name is double-quoted so SQLite identifier
    // rules don't bite on reserved words.
    let column_list = new_columns
        .iter()
        .map(|c| format!("\"{}\"", c.name.replace('"', "\"\"")))
        .collect::<Vec<_>>()
        .join(", ");
    let insert_sql =
        format!("INSERT INTO \"{tmp}\" ({column_list}) SELECT {column_list} 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);

    vec![
        create.build(SqliteQueryBuilder),
        insert_sql,
        drop_sql,
        rename_sql,
    ]
}

/// 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.
    if let Some(prev_col) = prev {
        if prev_col.ty != new.ty && is_safe_cast(prev_col.ty, new.ty) {
            let new_ty_sql = postgres_type_name(new.ty);
            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 {
        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);
                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}(\"id\")\
                     {on_delete_clause}{on_update_clause}"
                ));
            }
        }

        // 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();
        }
        // 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: `#[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();
        }
    }
    // `#[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
}

/// 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}\"){}",
                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::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::*;

    /// 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 {
                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,
                app_label: "app".to_string(),
            }],
        );
        per_plugin.insert(
            "alpha".to_string(),
            vec![ModelMeta {
                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,
                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,
            db_constraint: true,
            noedit: 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_now: 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,
            db_constraint: true,
            noedit: 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_now: 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,
            db_constraint: true,
            noedit: 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_now: 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,
            db_constraint: true,
            noedit: 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_now: 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_now: 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,
                db_constraint: true,
                noedit: 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_now: 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 {
                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,
                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,
            db_constraint: true,
            noedit: 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_now: 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,
            db_constraint: true,
            noedit: 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_now: 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,
            db_constraint: true,
            noedit: 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_now: 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_now: 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_now: 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}",
            );
        }
    }

    /// 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,
                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,
                auto_now,
                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}",
            );
        }
    }
}