rustango-macros 0.27.7

Proc-macros for rustango: #[derive(Model)] and friends.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
//! Proc-macros for rustango.
//!
//! v0.1 ships `#[derive(Model)]`, which emits:
//! * a `Model` impl carrying a static `ModelSchema`,
//! * an `inventory::submit!` so the model is discoverable from the registry,
//! * an inherent `objects()` returning a `QuerySet<Self>`,
//! * a `sqlx::FromRow` impl so query results decode into the struct.

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::{
    parse_macro_input, spanned::Spanned, Data, DeriveInput, Fields, GenericArgument, LitStr,
    PathArguments, Type, TypePath,
};

/// Derive a `Model` impl. See crate docs for the supported attributes.
#[proc_macro_derive(Model, attributes(rustango))]
pub fn derive_model(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand(&input)
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

/// Derive a `router(prefix, pool) -> axum::Router` associated method on a
/// marker struct, wiring the full CRUD ViewSet in one annotation.
///
/// ```ignore
/// #[derive(ViewSet)]
/// #[viewset(
///     model        = Post,
///     fields       = "id, title, body, author_id",
///     filter_fields = "author_id",
///     search_fields = "title, body",
///     ordering     = "-published_at",
///     page_size    = 20,
/// )]
/// pub struct PostViewSet;
///
/// // Mount into your app:
/// let app = Router::new()
///     .merge(PostViewSet::router("/api/posts", pool.clone()));
/// ```
///
/// Attributes:
/// * `model = TypeName` — *required*. The `#[derive(Model)]` struct whose
///   `SCHEMA` constant drives the endpoints.
/// * `fields = "a, b, c"` — scalar fields included in list/retrieve JSON
///   and accepted on create/update (default: all scalar fields).
/// * `filter_fields = "a, b"` — fields filterable via `?a=v` query params.
/// * `search_fields = "a, b"` — fields searched by `?search=...`.
/// * `ordering = "a, -b"` — default list ordering; prefix `-` for DESC.
/// * `page_size = N` — default page size (default: 20, max: 1000).
/// * `read_only` — flag; wires only `list` + `retrieve` (no mutations).
/// * `permissions(list = "...", retrieve = "...", create = "...",
///   update = "...", destroy = "...")` — codenames required per action.
#[proc_macro_derive(ViewSet, attributes(viewset))]
pub fn derive_viewset(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand_viewset(&input)
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

/// Derive `rustango::forms::FormStruct` (slice 8.4B). Generates a
/// `parse(&HashMap<String, String>) -> Result<Self, FormError>` impl
/// that walks every named field and:
///
/// * Parses the string value into the field's Rust type (`String`,
///   `i32`, `i64`, `f32`, `f64`, `bool`, plus `Option<T>` for the
///   nullable case).
/// * Applies any `#[form(min = ..)]` / `#[form(max = ..)]` /
///   `#[form(min_length = ..)]` / `#[form(max_length = ..)]`
///   validators in declaration order, returning `FormError::Parse`
///   on the first failure.
///
/// Example:
///
/// ```ignore
/// #[derive(Form)]
/// pub struct CreateItemForm {
///     #[form(min_length = 1, max_length = 64)]
///     pub name: String,
///     #[form(min = 0, max = 150)]
///     pub age: i32,
///     pub active: bool,
///     pub email: Option<String>,
/// }
///
/// let parsed = CreateItemForm::parse(&form_map)?;
/// ```
#[proc_macro_derive(Form, attributes(form))]
pub fn derive_form(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand_form(&input)
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

/// Derive [`rustango::serializer::ModelSerializer`] for a struct.
///
/// # Container attribute (required)
/// `#[serializer(model = TypeName)]` — the [`Model`] type this serializer maps from.
///
/// # Field attributes
/// - `#[serializer(read_only)]` — mapped from model; included in JSON output; excluded from `writable_fields()`
/// - `#[serializer(write_only)]` — `Default::default()` in `from_model`; excluded from JSON output; included in `writable_fields()`
/// - `#[serializer(source = "field_name")]` — reads from `model.field_name` instead of `model.<field_ident>`
/// - `#[serializer(skip)]` — `Default::default()` in `from_model`; included in JSON output; excluded from `writable_fields()` (user sets manually)
///
/// The macro also emits a custom `impl serde::Serialize` — do **not** also `#[derive(Serialize)]`.
#[proc_macro_derive(Serializer, attributes(serializer))]
pub fn derive_serializer(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand_serializer(&input)
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

/// Bake every `*.json` migration file in a directory into the binary
/// at compile time. Returns a `&'static [(&'static str, &'static str)]`
/// of `(name, json_content)` pairs, lex-sorted by file stem.
///
/// Pair with `rustango::migrate::migrate_embedded` at runtime — same
/// behaviour as `migrate(pool, dir)` but with no filesystem access.
/// The path is interpreted relative to the user's `CARGO_MANIFEST_DIR`
/// (i.e. the crate that invokes the macro). Default is
/// `"./migrations"` if no argument is supplied.
///
/// ```ignore
/// const EMBEDDED: &[(&str, &str)] = rustango::embed_migrations!();
/// // or:
/// const EMBEDDED: &[(&str, &str)] = rustango::embed_migrations!("./migrations");
///
/// rustango::migrate::migrate_embedded(&pool, EMBEDDED).await?;
/// ```
///
/// **Compile-time guarantees** (rustango v0.4+, slice 5): every JSON
/// file's `name` field must equal its file stem, every `prev`
/// reference must point to another migration in the same directory,
/// and the JSON must parse. A broken chain — orphan `prev`, missing
/// predecessor, malformed file — fails at macro-expansion time with
/// a clear `compile_error!`. *No other Django-shape Rust framework
/// validates migration chains at compile time*: Cot's migrations are
/// imperative Rust code (no static chain), Loco's are SeaORM
/// up/down (same), Rwf's are raw SQL (no chain at all).
///
/// Each migration is included via `include_str!` so cargo's rebuild
/// detection picks up file *content* changes. **Caveat:** cargo
/// doesn't watch directory listings, so adding or removing a
/// migration file inside the dir won't auto-trigger a rebuild — run
/// `cargo clean` (or just bump any other source file) when you add
/// new migrations during embedded development.
#[proc_macro]
pub fn embed_migrations(input: TokenStream) -> TokenStream {
    expand_embed_migrations(input.into())
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

/// `#[rustango::main]` — the Django-shape runserver entrypoint. Wraps
/// `#[tokio::main]` and a default `tracing_subscriber` initialisation
/// (env-filter, falling back to `info,sqlx=warn`) so user `main`
/// functions are zero-boilerplate:
///
/// ```ignore
/// #[rustango::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     rustango::server::Builder::from_env().await?
///         .migrate("migrations").await?
///         .api(my_app::urls::api())
///         .seed_with(my_app::seed::run).await?
///         .serve("0.0.0.0:8080").await
/// }
/// ```
///
/// Optional `flavor = "current_thread"` passes through to
/// `#[tokio::main]`; default is the multi-threaded runtime.
///
/// Pulls `tracing-subscriber` into the rustango crate behind the
/// `runtime` sub-feature (implied by `tenancy`), so apps that opt
/// out get plain `#[tokio::main]` ergonomics without the dependency.
#[proc_macro_attribute]
pub fn main(args: TokenStream, item: TokenStream) -> TokenStream {
    expand_main(args.into(), item.into())
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

fn expand_main(args: TokenStream2, item: TokenStream2) -> syn::Result<TokenStream2> {
    let mut input: syn::ItemFn = syn::parse2(item)?;
    if input.sig.asyncness.is_none() {
        return Err(syn::Error::new(
            input.sig.ident.span(),
            "`#[rustango::main]` must wrap an `async fn`",
        ));
    }

    // Parse optional `flavor = "..."` etc. from the attribute args
    // and pass them straight through to `#[tokio::main(...)]`.
    let tokio_attr = if args.is_empty() {
        quote! { #[::tokio::main] }
    } else {
        quote! { #[::tokio::main(#args)] }
    };

    // Re-block the body so the tracing init runs before user code.
    let body = input.block.clone();
    input.block = syn::parse2(quote! {{
        {
            use ::rustango::__private_runtime::tracing_subscriber::{self, EnvFilter};
            // `try_init` so duplicate installers (e.g. tests already
            // holding a subscriber) don't panic.
            let _ = tracing_subscriber::fmt()
                .with_env_filter(
                    EnvFilter::try_from_default_env()
                        .unwrap_or_else(|_| EnvFilter::new("info,sqlx=warn")),
                )
                .try_init();
        }
        #body
    }})?;

    Ok(quote! {
        #tokio_attr
        #input
    })
}

fn expand_embed_migrations(input: TokenStream2) -> syn::Result<TokenStream2> {
    // Default to "./migrations" if invoked without args.
    let path_str = if input.is_empty() {
        "./migrations".to_string()
    } else {
        let lit: LitStr = syn::parse2(input)?;
        lit.value()
    };

    let manifest = std::env::var("CARGO_MANIFEST_DIR").map_err(|_| {
        syn::Error::new(
            proc_macro2::Span::call_site(),
            "embed_migrations! must be invoked during a Cargo build (CARGO_MANIFEST_DIR not set)",
        )
    })?;
    let abs = std::path::Path::new(&manifest).join(&path_str);

    let mut entries: Vec<(String, std::path::PathBuf)> = Vec::new();
    if abs.is_dir() {
        let read = std::fs::read_dir(&abs).map_err(|e| {
            syn::Error::new(
                proc_macro2::Span::call_site(),
                format!("embed_migrations!: cannot read {}: {e}", abs.display()),
            )
        })?;
        for entry in read.flatten() {
            let path = entry.path();
            if !path.is_file() {
                continue;
            }
            if path.extension().and_then(|s| s.to_str()) != Some("json") {
                continue;
            }
            let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
                continue;
            };
            entries.push((stem.to_owned(), path));
        }
    }
    entries.sort_by(|a, b| a.0.cmp(&b.0));

    // Compile-time chain validation: read each migration's JSON,
    // pull `name` and `prev` (file-stem-keyed for the chain check),
    // and verify every `prev` points to another migration in the
    // slice. Mismatches between the file stem and the embedded
    // `name` field — and broken `prev` chains — fail at MACRO
    // EXPANSION time so a misshapen migration set never compiles.
    //
    // This is the v0.4 Slice 5 distinguisher: rustango's JSON
    // migrations + a Rust proc-macro that reads them is the unique
    // combo nothing else in the Django-shape Rust camp can match
    // (Cot's are imperative Rust code, Loco's are SeaORM up/down,
    // Rwf's are raw SQL — none have a static chain to validate).
    let mut chain_names: Vec<String> = Vec::with_capacity(entries.len());
    let mut prev_refs: Vec<(String, Option<String>)> = Vec::with_capacity(entries.len());
    for (stem, path) in &entries {
        let raw = std::fs::read_to_string(path).map_err(|e| {
            syn::Error::new(
                proc_macro2::Span::call_site(),
                format!(
                    "embed_migrations!: cannot read {} for chain validation: {e}",
                    path.display()
                ),
            )
        })?;
        let json: serde_json::Value = serde_json::from_str(&raw).map_err(|e| {
            syn::Error::new(
                proc_macro2::Span::call_site(),
                format!(
                    "embed_migrations!: {} is not valid JSON: {e}",
                    path.display()
                ),
            )
        })?;
        let name = json
            .get("name")
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                syn::Error::new(
                    proc_macro2::Span::call_site(),
                    format!(
                        "embed_migrations!: {} is missing the `name` field",
                        path.display()
                    ),
                )
            })?
            .to_owned();
        if name != *stem {
            return Err(syn::Error::new(
                proc_macro2::Span::call_site(),
                format!(
                    "embed_migrations!: file stem `{stem}` does not match the migration's \
                     `name` field `{name}` — rename the file or fix the JSON",
                ),
            ));
        }
        let prev = json.get("prev").and_then(|v| v.as_str()).map(str::to_owned);
        chain_names.push(name.clone());
        prev_refs.push((name, prev));
    }

    let name_set: std::collections::HashSet<&str> =
        chain_names.iter().map(String::as_str).collect();
    for (name, prev) in &prev_refs {
        if let Some(p) = prev {
            if !name_set.contains(p.as_str()) {
                return Err(syn::Error::new(
                    proc_macro2::Span::call_site(),
                    format!(
                        "embed_migrations!: broken migration chain — `{name}` declares \
                         prev=`{p}` but no migration with that name exists in {}",
                        abs.display()
                    ),
                ));
            }
        }
    }

    let pairs: Vec<TokenStream2> = entries
        .iter()
        .map(|(name, path)| {
            let path_lit = path.display().to_string();
            quote! { (#name, ::core::include_str!(#path_lit)) }
        })
        .collect();

    Ok(quote! {
        {
            const __RUSTANGO_EMBEDDED: &[(&'static str, &'static str)] = &[#(#pairs),*];
            __RUSTANGO_EMBEDDED
        }
    })
}

fn expand(input: &DeriveInput) -> syn::Result<TokenStream2> {
    let struct_name = &input.ident;

    let Data::Struct(data) = &input.data else {
        return Err(syn::Error::new_spanned(
            struct_name,
            "Model can only be derived on structs",
        ));
    };
    let Fields::Named(named) = &data.fields else {
        return Err(syn::Error::new_spanned(
            struct_name,
            "Model requires a struct with named fields",
        ));
    };

    let container = parse_container_attrs(input)?;
    let table = container
        .table
        .unwrap_or_else(|| to_snake_case(&struct_name.to_string()));
    let model_name = struct_name.to_string();

    let collected = collect_fields(named, &table)?;

    // Validate that #[rustango(display = "…")] names a real field.
    if let Some((ref display, span)) = container.display {
        if !collected.field_names.iter().any(|n| n == display) {
            return Err(syn::Error::new(
                span,
                format!("`display = \"{display}\"` does not match any field on this struct"),
            ));
        }
    }
    let display = container.display.map(|(name, _)| name);
    let app_label = container.app.clone();

    // Validate admin field-name lists against declared field names.
    if let Some(admin) = &container.admin {
        for (label, list) in [
            ("list_display", &admin.list_display),
            ("search_fields", &admin.search_fields),
            ("readonly_fields", &admin.readonly_fields),
            ("list_filter", &admin.list_filter),
        ] {
            if let Some((names, span)) = list {
                for name in names {
                    if !collected.field_names.iter().any(|n| n == name) {
                        return Err(syn::Error::new(
                            *span,
                            format!(
                                "`{label} = \"{name}\"`: \"{name}\" is not a declared field on this struct"
                            ),
                        ));
                    }
                }
            }
        }
        if let Some((pairs, span)) = &admin.ordering {
            for (name, _) in pairs {
                if !collected.field_names.iter().any(|n| n == name) {
                    return Err(syn::Error::new(
                        *span,
                        format!(
                            "`ordering = \"{name}\"`: \"{name}\" is not a declared field on this struct"
                        ),
                    ));
                }
            }
        }
        if let Some((groups, span)) = &admin.fieldsets {
            for (_, fields) in groups {
                for name in fields {
                    if !collected.field_names.iter().any(|n| n == name) {
                        return Err(syn::Error::new(
                            *span,
                            format!(
                                "`fieldsets`: \"{name}\" is not a declared field on this struct"
                            ),
                        ));
                    }
                }
            }
        }
    }
    if let Some(audit) = &container.audit {
        if let Some((names, span)) = &audit.track {
            for name in names {
                if !collected.field_names.iter().any(|n| n == name) {
                    return Err(syn::Error::new(
                        *span,
                        format!(
                            "`audit(track = \"{name}\")`: \"{name}\" is not a declared field on this struct"
                        ),
                    ));
                }
            }
        }
    }

    // Build the audit_track list for ModelSchema: None when no audit attr,
    // Some(empty) when audit present without track, Some(names) when explicit.
    let audit_track_names: Option<Vec<String>> = container.audit.as_ref().map(|audit| {
        audit
            .track
            .as_ref()
            .map(|(names, _)| names.clone())
            .unwrap_or_default()
    });

    // Merge field-level indexes into the container's index list.
    let mut all_indexes: Vec<IndexAttr> = container.indexes;
    for field in &named.named {
        let ident = field.ident.as_ref().expect("named");
        let col = to_snake_case(&ident.to_string()); // column name fallback
                                                     // Re-parse field attrs to check for index flag
        if let Ok(fa) = parse_field_attrs(field) {
            if fa.index {
                let col_name = fa.column.clone().unwrap_or_else(|| col.clone());
                let auto_name = if fa.index_unique {
                    format!("{table}_{col_name}_uq_idx")
                } else {
                    format!("{table}_{col_name}_idx")
                };
                all_indexes.push(IndexAttr {
                    name: fa.index_name.or(Some(auto_name)),
                    columns: vec![col_name],
                    unique: fa.index_unique,
                });
            }
        }
    }

    let model_impl = model_impl_tokens(
        struct_name,
        &model_name,
        &table,
        display.as_deref(),
        app_label.as_deref(),
        container.admin.as_ref(),
        &collected.field_schemas,
        collected.soft_delete_column.as_deref(),
        container.permissions,
        audit_track_names.as_deref(),
        &container.m2m,
        &all_indexes,
        &container.checks,
        &container.composite_fks,
        &container.generic_fks,
        container.scope.as_deref(),
    );
    let module_ident = column_module_ident(struct_name);
    let column_consts = column_const_tokens(&module_ident, &collected.column_entries);
    let audited_fields: Option<Vec<&ColumnEntry>> = container.audit.as_ref().map(|audit| {
        let track_set: Option<std::collections::HashSet<&str>> = audit
            .track
            .as_ref()
            .map(|(names, _)| names.iter().map(String::as_str).collect());
        collected
            .column_entries
            .iter()
            .filter(|c| {
                track_set
                    .as_ref()
                    .map_or(true, |s| s.contains(c.name.as_str()))
            })
            .collect()
    });
    let inherent_impl = inherent_impl_tokens(
        struct_name,
        &collected,
        collected.primary_key.as_ref(),
        &column_consts,
        audited_fields.as_deref(),
        &all_indexes,
    );
    let column_module = column_module_tokens(&module_ident, struct_name, &collected.column_entries);
    let from_row_impl = from_row_impl_tokens(struct_name, &collected.from_row_inits);
    let reverse_helpers = reverse_helper_tokens(struct_name, &collected.fk_relations);
    let m2m_accessors = m2m_accessor_tokens(struct_name, &container.m2m);

    Ok(quote! {
        #model_impl
        #inherent_impl
        #from_row_impl
        #column_module
        #reverse_helpers
        #m2m_accessors

        ::rustango::core::inventory::submit! {
            ::rustango::core::ModelEntry {
                schema: <#struct_name as ::rustango::core::Model>::SCHEMA,
                // `module_path!()` evaluates at the registration site,
                // so a Model declared in `crate::blog::models` records
                // `"<crate>::blog::models"` and `resolved_app_label()`
                // can infer "blog" without an explicit attribute.
                module_path: ::core::module_path!(),
            }
        }
    })
}

/// Emit `impl LoadRelated for #StructName` — slice 9.0d. Pattern-
/// matches `field_name` against the model's FK fields and, for a
/// match, decodes the FK target via the parent's macro-generated
/// `__rustango_from_aliased_row`, reads the parent's PK, and stores
/// `ForeignKey::Loaded` on `self`.
///
/// Always emitted (with empty arms for FK-less models, which
/// return `Ok(false)` for any field name) so the `T: LoadRelated`
/// trait bound on `fetch_on` is universally satisfied — users
/// never have to think about implementing it.
fn load_related_impl_tokens(struct_name: &syn::Ident, fk_relations: &[FkRelation]) -> TokenStream2 {
    let arms = fk_relations.iter().map(|rel| {
        let parent_ty = &rel.parent_type;
        let fk_col = rel.fk_column.as_str();
        // FK field's Rust ident matches its SQL column name in v0.8
        // (no `column = "..."` rename ships on FK fields).
        let field_ident = syn::Ident::new(fk_col, proc_macro2::Span::call_site());
        let (variant_ident, default_expr) = rel.pk_kind.sqlvalue_match_arm();
        let assign = if rel.nullable {
            quote! {
                self.#field_ident = ::core::option::Option::Some(
                    ::rustango::sql::ForeignKey::loaded(_pk, _parent),
                );
            }
        } else {
            quote! {
                self.#field_ident = ::rustango::sql::ForeignKey::loaded(_pk, _parent);
            }
        };
        quote! {
            #fk_col => {
                let _parent: #parent_ty = <#parent_ty>::__rustango_from_aliased_row(row, alias)?;
                // Loud-in-debug, default-in-release: a divergence
                // between the FK field's declared `K` (drives the
                // expected `SqlValue::<Variant>`) and the parent's
                // `__rustango_pk_value` output is a macro-internal
                // invariant break — surfacing the panic in dev
                // catches it before users hit silent PK=0 corruption.
                let _pk = match <#parent_ty>::__rustango_pk_value(&_parent) {
                    ::rustango::core::SqlValue::#variant_ident(v) => v,
                    _other => {
                        ::core::debug_assert!(
                            false,
                            "rustango macro bug: load_related on FK `{}` expected \
                             SqlValue::{} from parent's __rustango_pk_value but got \
                             {:?} — file a bug at https://github.com/ujeenet/rustango",
                            #fk_col,
                            ::core::stringify!(#variant_ident),
                            _other,
                        );
                        #default_expr
                    }
                };
                #assign
                ::core::result::Result::Ok(true)
            }
        }
    });
    quote! {
        impl ::rustango::sql::LoadRelated for #struct_name {
            #[allow(unused_variables)]
            fn __rustango_load_related(
                &mut self,
                row: &::rustango::sql::sqlx::postgres::PgRow,
                field_name: &str,
                alias: &str,
            ) -> ::core::result::Result<bool, ::rustango::sql::sqlx::Error> {
                match field_name {
                    #( #arms )*
                    _ => ::core::result::Result::Ok(false),
                }
            }
        }
    }
}

/// MySQL counterpart of [`load_related_impl_tokens`] — v0.23.0-batch8.
/// Emits a call to the cfg-gated `__impl_my_load_related!` macro_rules,
/// which expands to a `LoadRelatedMy` impl when rustango is built with
/// the `mysql` feature, and to nothing otherwise. The decoded parent
/// is read via `__rustango_from_aliased_my_row` (the MySQL aliased
/// decoder, also batch8) so the dual emission is symmetric across
/// backends.
fn load_related_impl_my_tokens(
    struct_name: &syn::Ident,
    fk_relations: &[FkRelation],
) -> TokenStream2 {
    let arms = fk_relations.iter().map(|rel| {
        let parent_ty = &rel.parent_type;
        let fk_col = rel.fk_column.as_str();
        let field_ident = syn::Ident::new(fk_col, proc_macro2::Span::call_site());
        let (variant_ident, default_expr) = rel.pk_kind.sqlvalue_match_arm();
        let assign = if rel.nullable {
            quote! {
                __self.#field_ident = ::core::option::Option::Some(
                    ::rustango::sql::ForeignKey::loaded(_pk, _parent),
                );
            }
        } else {
            quote! {
                __self.#field_ident = ::rustango::sql::ForeignKey::loaded(_pk, _parent);
            }
        };
        // `self` IS hygiene-tracked through macro_rules — emitted from
        // a different context than the `&mut self` parameter inside
        // the macro_rules-expanded fn. Pass it through as `__self`
        // and let the macro_rules rebind it to the receiver.
        quote! {
            #fk_col => {
                let _parent: #parent_ty =
                    <#parent_ty>::__rustango_from_aliased_my_row(row, alias)?;
                // See note in `load_related_impl_tokens` (PG twin) —
                // the same loud-in-debug invariant guard.
                let _pk = match <#parent_ty>::__rustango_pk_value(&_parent) {
                    ::rustango::core::SqlValue::#variant_ident(v) => v,
                    _other => {
                        ::core::debug_assert!(
                            false,
                            "rustango macro bug: load_related on FK `{}` expected \
                             SqlValue::{} from parent's __rustango_pk_value but got \
                             {:?} — file a bug at https://github.com/ujeenet/rustango",
                            #fk_col,
                            ::core::stringify!(#variant_ident),
                            _other,
                        );
                        #default_expr
                    }
                };
                #assign
                ::core::result::Result::Ok(true)
            }
        }
    });
    quote! {
        ::rustango::__impl_my_load_related!(#struct_name, |__self, row, field_name, alias| {
            #( #arms )*
        });
    }
}

/// Same shape as [`load_related_impl_my_tokens`] but for SQLite.
/// Emits a call to `__impl_sqlite_load_related!` which expands to a
/// `LoadRelatedSqlite` impl when the `sqlite` feature is on.
fn load_related_impl_sqlite_tokens(
    struct_name: &syn::Ident,
    fk_relations: &[FkRelation],
) -> TokenStream2 {
    let arms = fk_relations.iter().map(|rel| {
        let parent_ty = &rel.parent_type;
        let fk_col = rel.fk_column.as_str();
        let field_ident = syn::Ident::new(fk_col, proc_macro2::Span::call_site());
        let (variant_ident, default_expr) = rel.pk_kind.sqlvalue_match_arm();
        let assign = if rel.nullable {
            quote! {
                __self.#field_ident = ::core::option::Option::Some(
                    ::rustango::sql::ForeignKey::loaded(_pk, _parent),
                );
            }
        } else {
            quote! {
                __self.#field_ident = ::rustango::sql::ForeignKey::loaded(_pk, _parent);
            }
        };
        quote! {
            #fk_col => {
                let _parent: #parent_ty =
                    <#parent_ty>::__rustango_from_aliased_sqlite_row(row, alias)?;
                let _pk = match <#parent_ty>::__rustango_pk_value(&_parent) {
                    ::rustango::core::SqlValue::#variant_ident(v) => v,
                    _other => {
                        ::core::debug_assert!(
                            false,
                            "rustango macro bug: load_related on FK `{}` expected \
                             SqlValue::{} from parent's __rustango_pk_value but got \
                             {:?} — file a bug at https://github.com/ujeenet/rustango",
                            #fk_col,
                            ::core::stringify!(#variant_ident),
                            _other,
                        );
                        #default_expr
                    }
                };
                #assign
                ::core::result::Result::Ok(true)
            }
        }
    });
    quote! {
        ::rustango::__impl_sqlite_load_related!(#struct_name, |__self, row, field_name, alias| {
            #( #arms )*
        });
    }
}

/// Emit `impl FkPkAccess for #StructName` — slice 9.0e. Pattern-
/// matches `field_name` against the model's FK fields and returns
/// the FK's stored PK as `i64`. Used by `fetch_with_prefetch` to
/// group children by parent PK.
///
/// Always emitted (with `_ => None` for FK-less models) so the
/// trait bound on `fetch_with_prefetch` is universally satisfied.
fn fk_pk_access_impl_tokens(struct_name: &syn::Ident, fk_relations: &[FkRelation]) -> TokenStream2 {
    let arms = fk_relations.iter().map(|rel| {
        let fk_col = rel.fk_column.as_str();
        let field_ident = syn::Ident::new(fk_col, proc_macro2::Span::call_site());
        if rel.pk_kind == DetectedKind::I64 {
            // i64 FK — return the stored PK so prefetch_related can
            // group children by it. Nullable variant unwraps via
            // `as_ref().map(...)`: an unset (NULL) FK column yields
            // `None` and that child sits out of the grouping (correct
            // semantics — it has no parent to attach to).
            if rel.nullable {
                quote! {
                    #fk_col => self.#field_ident
                        .as_ref()
                        .map(|fk| ::rustango::sql::ForeignKey::pk(fk)),
                }
            } else {
                quote! {
                    #fk_col => ::core::option::Option::Some(self.#field_ident.pk()),
                }
            }
        } else {
            // Non-i64 FK PKs (e.g. `ForeignKey<T, String>`,
            // `ForeignKey<T, Uuid>`) opt out of `prefetch_related`'s
            // i64-keyed grouping path — the trait signature is
            // `Option<i64>` and a non-i64 PK can't lower into it.
            // The FK still works for everything else (CRUD, lazy
            // load via `.get()`, select_related JOINs); only the
            // bulk prefetch grouper needs the integer key.
            quote! {
                #fk_col => ::core::option::Option::None,
            }
        }
    });
    // PK-type-agnostic version: every FK arm emits an
    // `Option<SqlValue>` so `fetch_with_prefetch` can group by any
    // PK type (i64, i32, String, Uuid). Models with non-i64 FK PKs
    // opt OUT of the legacy i64 method (it returns None) but opt IN
    // here.
    let value_arms = fk_relations.iter().map(|rel| {
        let fk_col = rel.fk_column.as_str();
        let field_ident = syn::Ident::new(fk_col, proc_macro2::Span::call_site());
        if rel.nullable {
            quote! {
                #fk_col => self.#field_ident
                    .as_ref()
                    .map(|fk| ::core::convert::Into::<::rustango::core::SqlValue>::into(
                        ::rustango::sql::ForeignKey::pk(fk)
                    )),
            }
        } else {
            quote! {
                #fk_col => ::core::option::Option::Some(
                    ::core::convert::Into::<::rustango::core::SqlValue>::into(
                        self.#field_ident.pk()
                    )
                ),
            }
        }
    });
    quote! {
        impl ::rustango::sql::FkPkAccess for #struct_name {
            #[allow(unused_variables)]
            fn __rustango_fk_pk(&self, field_name: &str) -> ::core::option::Option<i64> {
                match field_name {
                    #( #arms )*
                    _ => ::core::option::Option::None,
                }
            }
            #[allow(unused_variables)]
            fn __rustango_fk_pk_value(
                &self,
                field_name: &str,
            ) -> ::core::option::Option<::rustango::core::SqlValue> {
                match field_name {
                    #( #value_arms )*
                    _ => ::core::option::Option::None,
                }
            }
        }
    }
}

/// For every `ForeignKey<Parent>` field on `Child`, emit
/// `impl Parent { pub async fn <child_table>_set(&self, executor) -> Vec<Child> }`.
/// Reads the parent's PK via the macro-generated `__rustango_pk_value`
/// and runs a single `SELECT … FROM <child_table> WHERE <fk_column> = $1`
/// — the canonical reverse-FK fetch. One round trip, no N+1.
fn reverse_helper_tokens(child_ident: &syn::Ident, fk_relations: &[FkRelation]) -> TokenStream2 {
    if fk_relations.is_empty() {
        return TokenStream2::new();
    }
    // Snake-case the child struct name to derive the method suffix —
    // `Post` → `post_set`, `BlogComment` → `blog_comment_set`. Avoids
    // English-plural edge cases (Django's `<child>_set` convention).
    let suffix = format!("{}_set", to_snake_case(&child_ident.to_string()));
    let method_ident = syn::Ident::new(&suffix, child_ident.span());
    let impls = fk_relations.iter().map(|rel| {
        let parent_ty = &rel.parent_type;
        let fk_col = rel.fk_column.as_str();
        let doc = format!(
            "Fetch every `{child_ident}` whose `{fk_col}` foreign key points at this row. \
             Single SQL query — `SELECT … FROM <{child_ident} table> WHERE {fk_col} = $1` — \
             generated from the FK declaration on `{child_ident}::{fk_col}`. Composes with \
             further `{child_ident}::objects()` filters via direct queryset use."
        );
        quote! {
            impl #parent_ty {
                #[doc = #doc]
                ///
                /// # Errors
                /// Returns [`::rustango::sql::ExecError`] for SQL-writing
                /// or driver failures.
                pub async fn #method_ident<'_c, _E>(
                    &self,
                    _executor: _E,
                ) -> ::core::result::Result<
                    ::std::vec::Vec<#child_ident>,
                    ::rustango::sql::ExecError,
                >
                where
                    _E: ::rustango::sql::sqlx::Executor<
                        '_c,
                        Database = ::rustango::sql::sqlx::Postgres,
                    >,
                {
                    let _pk: ::rustango::core::SqlValue = self.__rustango_pk_value();
                    ::rustango::query::QuerySet::<#child_ident>::new()
                        .filter(#fk_col, ::rustango::core::Op::Eq, _pk)
                        .fetch_on(_executor)
                        .await
                }
            }
        }
    });
    quote! { #( #impls )* }
}

/// Emit `<name>_m2m(&self) -> M2MManager` inherent methods for every M2M
/// relation declared on the model.
fn m2m_accessor_tokens(struct_name: &syn::Ident, m2m_relations: &[M2MAttr]) -> TokenStream2 {
    if m2m_relations.is_empty() {
        return TokenStream2::new();
    }
    let methods = m2m_relations.iter().map(|rel| {
        let method_name = format!("{}_m2m", rel.name);
        let method_ident = syn::Ident::new(&method_name, struct_name.span());
        let through = rel.through.as_str();
        let src_col = rel.src.as_str();
        let dst_col = rel.dst.as_str();
        quote! {
            pub fn #method_ident(&self) -> ::rustango::sql::M2MManager {
                ::rustango::sql::M2MManager {
                    src_pk: self.__rustango_pk_value(),
                    through: #through,
                    src_col: #src_col,
                    dst_col: #dst_col,
                }
            }
        }
    });
    quote! {
        impl #struct_name {
            #( #methods )*
        }
    }
}

struct ColumnEntry {
    /// The struct field ident, used both for the inherent const name on
    /// the model and for the inner column type's name.
    ident: syn::Ident,
    /// The struct's field type, used as `Column::Value`.
    value_ty: Type,
    /// Rust-side field name (e.g. `"id"`).
    name: String,
    /// SQL-side column name (e.g. `"user_id"`).
    column: String,
    /// `::rustango::core::FieldType::I64` etc.
    field_type_tokens: TokenStream2,
}

struct CollectedFields {
    field_schemas: Vec<TokenStream2>,
    from_row_inits: Vec<TokenStream2>,
    /// Aliased counterparts of `from_row_inits` — read columns via
    /// `format!("{prefix}__{col}")` aliases so a Model can be
    /// decoded from a JOINed row's projected target columns.
    from_aliased_row_inits: Vec<TokenStream2>,
    /// Static column-name list — used by the simple insert path
    /// (no `Auto<T>` fields). Aligned with `insert_values`.
    insert_columns: Vec<TokenStream2>,
    /// Static `Into<SqlValue>` expressions, one per field. Aligned
    /// with `insert_columns`. Used by the simple insert path only.
    insert_values: Vec<TokenStream2>,
    /// Per-field push expressions for the dynamic (Auto-aware)
    /// insert path. Each statement either unconditionally pushes
    /// `(column, value)` or, for an `Auto<T>` field, conditionally
    /// pushes only when `Auto::Set(_)`. Built only when `has_auto`.
    insert_pushes: Vec<TokenStream2>,
    /// SQL columns for `RETURNING` — one per `Auto<T>` field. Empty
    /// when `has_auto == false`.
    returning_cols: Vec<TokenStream2>,
    /// `self.<field> = Row::try_get(&row, "<col>")?;` for each Auto
    /// field. Run after `insert_returning` to populate the model.
    auto_assigns: Vec<TokenStream2>,
    /// `(ident, column_literal)` pairs for every Auto field. Used by
    /// the bulk_insert codegen to rebuild assigns against `_row_mut`
    /// instead of `self`.
    auto_field_idents: Vec<(syn::Ident, String)>,
    /// Inner `T` of the first `Auto<T>` field, for the MySQL
    /// `LAST_INSERT_ID()` assignment in `AssignAutoPkPool`.
    first_auto_value_ty: Option<Type>,
    /// Bulk-insert per-row pushes for **non-Auto fields only**. Used
    /// by the all-Auto-Unset bulk path (Auto cols dropped from
    /// `columns`).
    bulk_pushes_no_auto: Vec<TokenStream2>,
    /// Bulk-insert per-row pushes for **all fields including Auto**.
    /// Used by the all-Auto-Set bulk path (Auto col included with the
    /// caller-supplied value).
    bulk_pushes_all: Vec<TokenStream2>,
    /// Column-name literals for non-Auto fields only (paired with
    /// `bulk_pushes_no_auto`).
    bulk_columns_no_auto: Vec<TokenStream2>,
    /// Column-name literals for every field including Auto (paired
    /// with `bulk_pushes_all`).
    bulk_columns_all: Vec<TokenStream2>,
    /// `let _i_unset_<n> = matches!(rows[0].<auto_field>, Auto::Unset);`
    /// + the loop that asserts every row matches. One pair per Auto
    /// field. Empty when `has_auto == false`.
    bulk_auto_uniformity: Vec<TokenStream2>,
    /// Identifier of the first Auto field, used as the witness for
    /// "all rows agree on Set vs Unset". Set only when `has_auto`.
    first_auto_ident: Option<syn::Ident>,
    /// `true` if any field on the struct is `Auto<T>`.
    has_auto: bool,
    /// `true` when the primary-key field's Rust type is `Auto<T>`.
    /// Gates `save()` codegen — only Auto PKs let us infer
    /// insert-vs-update from the in-memory value.
    pk_is_auto: bool,
    /// `Assignment` constructors for every non-PK column. Drives the
    /// UPDATE branch of `save()`.
    update_assignments: Vec<TokenStream2>,
    /// Column name literals (`"col"`) for every non-PK, non-auto_now_add column.
    /// Drives the `ON CONFLICT ... DO UPDATE SET` clause in `upsert_on`.
    upsert_update_columns: Vec<TokenStream2>,
    primary_key: Option<(syn::Ident, String)>,
    column_entries: Vec<ColumnEntry>,
    /// Rust-side field names, in declaration order. Used to validate
    /// container attributes like `display = "…"`.
    field_names: Vec<String>,
    /// FK fields on this child model. Drives the reverse-relation
    /// helper emit — for each FK, the macro adds an inherent
    /// `<parent>::<child_table>_set(&self, executor) -> Vec<Self>`
    /// method on the parent type.
    fk_relations: Vec<FkRelation>,
    /// SQL column name of the `#[rustango(soft_delete)]` field, if
    /// the model has one. Drives emission of the `soft_delete_on` /
    /// `restore_on` inherent methods. At most one such column per
    /// model is allowed; collect_fields rejects duplicates.
    soft_delete_column: Option<String>,
}

#[derive(Clone)]
struct FkRelation {
    /// Inner type of `ForeignKey<T, K>` — the parent model. The reverse
    /// helper is emitted as `impl <ParentType> { … }`.
    parent_type: Type,
    /// SQL column name on the child table for this FK (e.g. `"author"`).
    /// Used in the generated `WHERE <fk_column> = $1` clause.
    fk_column: String,
    /// `K`'s underlying scalar kind — drives the `match SqlValue { … }`
    /// arm emitted by [`load_related_impl_tokens`]. `I64` for the
    /// default `ForeignKey<T>` (no explicit K); other kinds when the
    /// user wrote `ForeignKey<T, String>`, `ForeignKey<T, Uuid>`, etc.
    pk_kind: DetectedKind,
    /// `true` when the field is `Option<ForeignKey<T, K>>` (nullable
    /// FK column). Drives the `Some(...)` wrapping in load_related
    /// assignment and `.as_ref().map(...)` in the FK PK accessor so
    /// the codegen matches the field's declared shape.
    nullable: bool,
}

fn collect_fields(named: &syn::FieldsNamed, table: &str) -> syn::Result<CollectedFields> {
    let cap = named.named.len();
    let mut out = CollectedFields {
        field_schemas: Vec::with_capacity(cap),
        from_row_inits: Vec::with_capacity(cap),
        from_aliased_row_inits: Vec::with_capacity(cap),
        insert_columns: Vec::with_capacity(cap),
        insert_values: Vec::with_capacity(cap),
        insert_pushes: Vec::with_capacity(cap),
        returning_cols: Vec::new(),
        auto_assigns: Vec::new(),
        auto_field_idents: Vec::new(),
        first_auto_value_ty: None,
        bulk_pushes_no_auto: Vec::with_capacity(cap),
        bulk_pushes_all: Vec::with_capacity(cap),
        bulk_columns_no_auto: Vec::with_capacity(cap),
        bulk_columns_all: Vec::with_capacity(cap),
        bulk_auto_uniformity: Vec::new(),
        first_auto_ident: None,
        has_auto: false,
        pk_is_auto: false,
        update_assignments: Vec::with_capacity(cap),
        upsert_update_columns: Vec::with_capacity(cap),
        primary_key: None,
        column_entries: Vec::with_capacity(cap),
        field_names: Vec::with_capacity(cap),
        fk_relations: Vec::new(),
        soft_delete_column: None,
    };

    for field in &named.named {
        let info = process_field(field, table)?;
        out.field_names.push(info.ident.to_string());
        out.field_schemas.push(info.schema);
        out.from_row_inits.push(info.from_row_init);
        out.from_aliased_row_inits.push(info.from_aliased_row_init);
        if let Some(parent_ty) = info.fk_inner.clone() {
            out.fk_relations.push(FkRelation {
                parent_type: parent_ty,
                fk_column: info.column.clone(),
                pk_kind: info.fk_pk_kind,
                nullable: info.nullable,
            });
        }
        if info.soft_delete {
            if out.soft_delete_column.is_some() {
                return Err(syn::Error::new_spanned(
                    field,
                    "only one field may be marked `#[rustango(soft_delete)]`",
                ));
            }
            out.soft_delete_column = Some(info.column.clone());
        }
        let column = info.column.as_str();
        let ident = info.ident;
        // Generated columns (`#[rustango(generated_as = "EXPR")]`)
        // skip every write path — Postgres recomputes the value
        // from EXPR. Push only the column-entry record (so typed
        // column constants still exist for filtering / projection)
        // and the schema literal (already pushed above) and move
        // on. No insert_columns/values, no insert_pushes, no
        // bulk_*, no update_assignments, no upsert_update_columns,
        // no returning_cols.
        if info.generated_as.is_some() {
            out.column_entries.push(ColumnEntry {
                ident: ident.clone(),
                value_ty: info.value_ty.clone(),
                name: ident.to_string(),
                column: info.column.clone(),
                field_type_tokens: info.field_type_tokens,
            });
            continue;
        }
        out.insert_columns.push(quote!(#column));
        out.insert_values.push(quote! {
            ::core::convert::Into::<::rustango::core::SqlValue>::into(
                ::core::clone::Clone::clone(&self.#ident)
            )
        });
        if info.auto {
            out.has_auto = true;
            if out.first_auto_ident.is_none() {
                out.first_auto_ident = Some(ident.clone());
                out.first_auto_value_ty = auto_inner_type(info.value_ty).cloned();
            }
            out.returning_cols.push(quote!(#column));
            out.auto_field_idents
                .push((ident.clone(), info.column.clone()));
            out.auto_assigns.push(quote! {
                self.#ident = ::rustango::sql::try_get_returning(_returning_row, #column)?;
            });
            out.insert_pushes.push(quote! {
                if let ::rustango::sql::Auto::Set(_v) = &self.#ident {
                    _columns.push(#column);
                    _values.push(::core::convert::Into::<::rustango::core::SqlValue>::into(
                        ::core::clone::Clone::clone(_v)
                    ));
                }
            });
            // Bulk: Auto fields appear only in the all-Set path,
            // never in the Unset path (we drop them from `columns`).
            out.bulk_columns_all.push(quote!(#column));
            out.bulk_pushes_all.push(quote! {
                _row_vals.push(::core::convert::Into::<::rustango::core::SqlValue>::into(
                    ::core::clone::Clone::clone(&_row.#ident)
                ));
            });
            // Uniformity check: every row's Auto state must match the
            // first row's. Mixed Set/Unset within one bulk_insert is
            // rejected here so the column list stays consistent.
            let ident_clone = ident.clone();
            out.bulk_auto_uniformity.push(quote! {
                for _r in rows.iter().skip(1) {
                    if matches!(_r.#ident_clone, ::rustango::sql::Auto::Unset) != _first_unset {
                        return ::core::result::Result::Err(
                            ::rustango::sql::ExecError::Sql(
                                ::rustango::sql::SqlError::BulkAutoMixed
                            )
                        );
                    }
                }
            });
        } else {
            out.insert_pushes.push(quote! {
                _columns.push(#column);
                _values.push(::core::convert::Into::<::rustango::core::SqlValue>::into(
                    ::core::clone::Clone::clone(&self.#ident)
                ));
            });
            // Bulk: non-Auto fields appear in BOTH paths.
            out.bulk_columns_no_auto.push(quote!(#column));
            out.bulk_columns_all.push(quote!(#column));
            let push_expr = quote! {
                _row_vals.push(::core::convert::Into::<::rustango::core::SqlValue>::into(
                    ::core::clone::Clone::clone(&_row.#ident)
                ));
            };
            out.bulk_pushes_no_auto.push(push_expr.clone());
            out.bulk_pushes_all.push(push_expr);
        }
        if info.primary_key {
            if out.primary_key.is_some() {
                return Err(syn::Error::new_spanned(
                    field,
                    "only one field may be marked `#[rustango(primary_key)]`",
                ));
            }
            out.primary_key = Some((ident.clone(), info.column.clone()));
            if info.auto {
                out.pk_is_auto = true;
            }
        } else if info.auto_now_add {
            // Immutable post-insert: skip from UPDATE entirely.
        } else if info.auto_now {
            // `auto_now` columns: bind `chrono::Utc::now()` on every
            // UPDATE so the column is always overridden with the
            // wall-clock at write time, regardless of what value the
            // user left in the struct field.
            out.update_assignments.push(quote! {
                ::rustango::core::Assignment {
                    column: #column,
                    value: ::core::convert::Into::<::rustango::core::SqlValue>::into(
                        ::chrono::Utc::now()
                    ),
                }
            });
            out.upsert_update_columns.push(quote!(#column));
        } else {
            out.update_assignments.push(quote! {
                ::rustango::core::Assignment {
                    column: #column,
                    value: ::core::convert::Into::<::rustango::core::SqlValue>::into(
                        ::core::clone::Clone::clone(&self.#ident)
                    ),
                }
            });
            out.upsert_update_columns.push(quote!(#column));
        }
        out.column_entries.push(ColumnEntry {
            ident: ident.clone(),
            value_ty: info.value_ty.clone(),
            name: ident.to_string(),
            column: info.column.clone(),
            field_type_tokens: info.field_type_tokens,
        });
    }
    Ok(out)
}

fn model_impl_tokens(
    struct_name: &syn::Ident,
    model_name: &str,
    table: &str,
    display: Option<&str>,
    app_label: Option<&str>,
    admin: Option<&AdminAttrs>,
    field_schemas: &[TokenStream2],
    soft_delete_column: Option<&str>,
    permissions: bool,
    audit_track: Option<&[String]>,
    m2m_relations: &[M2MAttr],
    indexes: &[IndexAttr],
    checks: &[CheckAttr],
    composite_fks: &[CompositeFkAttr],
    generic_fks: &[GenericFkAttr],
    scope: Option<&str>,
) -> TokenStream2 {
    let display_tokens = if let Some(name) = display {
        quote!(::core::option::Option::Some(#name))
    } else {
        quote!(::core::option::Option::None)
    };
    let app_label_tokens = if let Some(name) = app_label {
        quote!(::core::option::Option::Some(#name))
    } else {
        quote!(::core::option::Option::None)
    };
    let soft_delete_tokens = if let Some(col) = soft_delete_column {
        quote!(::core::option::Option::Some(#col))
    } else {
        quote!(::core::option::Option::None)
    };
    let audit_track_tokens = match audit_track {
        None => quote!(::core::option::Option::None),
        Some(names) => {
            let lits = names.iter().map(|n| n.as_str());
            quote!(::core::option::Option::Some(&[ #(#lits),* ]))
        }
    };
    let admin_tokens = admin_config_tokens(admin);
    // Default `tenant` so single-tenant projects (no `scope` attr
    // anywhere) keep the v0.24.x behavior. Container-attr parser
    // already validated the value is "registry" or "tenant".
    let scope_tokens = match scope.map(|s| s.to_ascii_lowercase()).as_deref() {
        Some("registry") => quote!(::rustango::core::ModelScope::Registry),
        _ => quote!(::rustango::core::ModelScope::Tenant),
    };
    let indexes_tokens = indexes.iter().map(|idx| {
        let name = idx.name.as_deref().unwrap_or("unnamed_index");
        let cols: Vec<&str> = idx.columns.iter().map(String::as_str).collect();
        let unique = idx.unique;
        quote! {
            ::rustango::core::IndexSchema {
                name: #name,
                columns: &[ #(#cols),* ],
                unique: #unique,
            }
        }
    });
    let checks_tokens = checks.iter().map(|c| {
        let name = c.name.as_str();
        let expr = c.expr.as_str();
        quote! {
            ::rustango::core::CheckConstraint {
                name: #name,
                expr: #expr,
            }
        }
    });
    let composite_fk_tokens = composite_fks.iter().map(|rel| {
        let name = rel.name.as_str();
        let to = rel.to.as_str();
        let from_cols: Vec<&str> = rel.from.iter().map(String::as_str).collect();
        let on_cols: Vec<&str> = rel.on.iter().map(String::as_str).collect();
        quote! {
            ::rustango::core::CompositeFkRelation {
                name: #name,
                to: #to,
                from: &[ #(#from_cols),* ],
                on: &[ #(#on_cols),* ],
            }
        }
    });
    let generic_fk_tokens = generic_fks.iter().map(|rel| {
        let name = rel.name.as_str();
        let ct_col = rel.ct_column.as_str();
        let pk_col = rel.pk_column.as_str();
        quote! {
            ::rustango::core::GenericRelation {
                name: #name,
                ct_column: #ct_col,
                pk_column: #pk_col,
            }
        }
    });
    let m2m_tokens = m2m_relations.iter().map(|rel| {
        let name = rel.name.as_str();
        let to = rel.to.as_str();
        let through = rel.through.as_str();
        let src = rel.src.as_str();
        let dst = rel.dst.as_str();
        quote! {
            ::rustango::core::M2MRelation {
                name: #name,
                to: #to,
                through: #through,
                src_col: #src,
                dst_col: #dst,
            }
        }
    });
    quote! {
        impl ::rustango::core::Model for #struct_name {
            const SCHEMA: &'static ::rustango::core::ModelSchema = &::rustango::core::ModelSchema {
                name: #model_name,
                table: #table,
                fields: &[ #(#field_schemas),* ],
                display: #display_tokens,
                app_label: #app_label_tokens,
                admin: #admin_tokens,
                soft_delete_column: #soft_delete_tokens,
                permissions: #permissions,
                audit_track: #audit_track_tokens,
                m2m: &[ #(#m2m_tokens),* ],
                indexes: &[ #(#indexes_tokens),* ],
                check_constraints: &[ #(#checks_tokens),* ],
                composite_relations: &[ #(#composite_fk_tokens),* ],
                generic_relations: &[ #(#generic_fk_tokens),* ],
                scope: #scope_tokens,
            };
        }
    }
}

/// Emit the `admin: Option<&'static AdminConfig>` field for the model
/// schema. `None` when the user wrote no `#[rustango(admin(...))]`;
/// otherwise a static reference to a populated `AdminConfig`.
fn admin_config_tokens(admin: Option<&AdminAttrs>) -> TokenStream2 {
    let Some(admin) = admin else {
        return quote!(::core::option::Option::None);
    };

    let list_display = admin
        .list_display
        .as_ref()
        .map(|(v, _)| v.as_slice())
        .unwrap_or(&[]);
    let list_display_lits = list_display.iter().map(|s| s.as_str());

    let search_fields = admin
        .search_fields
        .as_ref()
        .map(|(v, _)| v.as_slice())
        .unwrap_or(&[]);
    let search_fields_lits = search_fields.iter().map(|s| s.as_str());

    let readonly_fields = admin
        .readonly_fields
        .as_ref()
        .map(|(v, _)| v.as_slice())
        .unwrap_or(&[]);
    let readonly_fields_lits = readonly_fields.iter().map(|s| s.as_str());

    let list_filter = admin
        .list_filter
        .as_ref()
        .map(|(v, _)| v.as_slice())
        .unwrap_or(&[]);
    let list_filter_lits = list_filter.iter().map(|s| s.as_str());

    let actions = admin
        .actions
        .as_ref()
        .map(|(v, _)| v.as_slice())
        .unwrap_or(&[]);
    let actions_lits = actions.iter().map(|s| s.as_str());

    let fieldsets = admin
        .fieldsets
        .as_ref()
        .map(|(v, _)| v.as_slice())
        .unwrap_or(&[]);
    let fieldset_tokens = fieldsets.iter().map(|(title, fields)| {
        let title = title.as_str();
        let field_lits = fields.iter().map(|s| s.as_str());
        quote!(::rustango::core::Fieldset {
            title: #title,
            fields: &[ #( #field_lits ),* ],
        })
    });

    let list_per_page = admin.list_per_page.unwrap_or(0);

    let ordering_pairs = admin
        .ordering
        .as_ref()
        .map(|(v, _)| v.as_slice())
        .unwrap_or(&[]);
    let ordering_tokens = ordering_pairs.iter().map(|(name, desc)| {
        let name = name.as_str();
        let desc = *desc;
        quote!((#name, #desc))
    });

    quote! {
        ::core::option::Option::Some(&::rustango::core::AdminConfig {
            list_display: &[ #( #list_display_lits ),* ],
            search_fields: &[ #( #search_fields_lits ),* ],
            list_per_page: #list_per_page,
            ordering: &[ #( #ordering_tokens ),* ],
            readonly_fields: &[ #( #readonly_fields_lits ),* ],
            list_filter: &[ #( #list_filter_lits ),* ],
            actions: &[ #( #actions_lits ),* ],
            fieldsets: &[ #( #fieldset_tokens ),* ],
        })
    }
}

fn inherent_impl_tokens(
    struct_name: &syn::Ident,
    fields: &CollectedFields,
    primary_key: Option<&(syn::Ident, String)>,
    column_consts: &TokenStream2,
    audited_fields: Option<&[&ColumnEntry]>,
    indexes: &[IndexAttr],
) -> TokenStream2 {
    // Audit-emit fragments threaded into write paths. Non-empty only
    // when the model carries `#[rustango(audit(...))]`. They reborrow
    // `_executor` (a `&mut PgConnection` for audited models — the
    // macro switches the signature below) so the data write and the
    // audit INSERT both run on the same caller-supplied connection.
    let executor_passes_to_data_write = if audited_fields.is_some() {
        quote!(&mut *_executor)
    } else {
        quote!(_executor)
    };
    let executor_param = if audited_fields.is_some() {
        quote!(_executor: &mut ::rustango::sql::sqlx::PgConnection)
    } else {
        quote!(_executor: _E)
    };
    let executor_generics = if audited_fields.is_some() {
        quote!()
    } else {
        quote!(<'_c, _E>)
    };
    let executor_where = if audited_fields.is_some() {
        quote!()
    } else {
        quote! {
            where
                _E: ::rustango::sql::sqlx::Executor<'_c, Database = ::rustango::sql::sqlx::Postgres>,
        }
    };
    // For audited models the `_on` methods take `&mut PgConnection`, so
    // the &PgPool convenience wrappers (`save`, `insert`, `delete`)
    // must acquire a connection first. Non-audited models keep the
    // direct delegation since `&PgPool` IS an Executor.
    let pool_to_save_on = if audited_fields.is_some() {
        quote! {
            let mut _conn = pool.acquire().await?;
            self.save_on(&mut *_conn).await
        }
    } else {
        quote!(self.save_on(pool).await)
    };
    let pool_to_insert_on = if audited_fields.is_some() {
        quote! {
            let mut _conn = pool.acquire().await?;
            self.insert_on(&mut *_conn).await
        }
    } else {
        quote!(self.insert_on(pool).await)
    };
    let pool_to_delete_on = if audited_fields.is_some() {
        quote! {
            let mut _conn = pool.acquire().await?;
            self.delete_on(&mut *_conn).await
        }
    } else {
        quote!(self.delete_on(pool).await)
    };
    let pool_to_bulk_insert_on = if audited_fields.is_some() {
        quote! {
            let mut _conn = pool.acquire().await?;
            Self::bulk_insert_on(rows, &mut *_conn).await
        }
    } else {
        quote!(Self::bulk_insert_on(rows, pool).await)
    };
    // Pre-existing bug surfaced by batch 22's first audited Auto<T>
    // PK test model: `upsert(&PgPool)` body called `self.upsert_on(pool)`
    // directly, but `upsert_on` for audited models takes
    // `&mut PgConnection` (the audit emit needs a real connection).
    // Add the missing acquire shim to keep audited Auto-PK upsert
    // compiling.
    let pool_to_upsert_on = if audited_fields.is_some() {
        quote! {
            let mut _conn = pool.acquire().await?;
            self.upsert_on(&mut *_conn).await
        }
    } else {
        quote!(self.upsert_on(pool).await)
    };

    // `insert_pool(&Pool)` — v0.23.0-batch9. Non-audited models only
    // (audit-on-connection over &Pool needs a bi-dialect transaction
    // helper, deferred). Two body shapes:
    // - has_auto: build InsertQuery skipping Auto::Unset columns,
    //   request Auto cols in `returning`, dispatch via
    //   `insert_returning_pool`, then on the returned `PgRow` /
    //   `MySqlAutoId(id)` enum — pull each Auto field from the PG
    //   row OR drop the single i64 into the first Auto field on MySQL
    //   (multi-Auto models on MySQL error at runtime since
    //   `LAST_INSERT_ID()` only reports one)
    // - non-Auto: build InsertQuery with explicit columns/values and
    //   call `insert_pool` (no returning needed)
    // pool_insert_method body for the audited Auto-PK case is moved
    // to after audit_pair_tokens / audit_pk_to_string (they live
    // ~150 lines below). This block keeps the non-audited and
    // non-Auto branches in place — the audited Auto-PK arm is
    // computed below and merged via the dispatch helper variable.
    let pool_insert_method = if audited_fields.is_some() && !fields.has_auto {
        // Audited models with explicit (non-Auto) PKs go through
        // the non-Auto insert path below — the audit emit is one
        // round-trip after the INSERT inside the same tx via
        // audit::save_one_with_audit_pool? No, INSERT semantics
        // differ. For non-Auto PK + audited, route through a
        // dedicated insert + audit emit on the same tx, but defer
        // the macro emission to the audit-bundle-aware block below
        // — this `quote!()` placeholder gets overwritten there.
        quote!()
    } else if audited_fields.is_some() && fields.has_auto {
        // Audited Auto-PK insert_pool — assembled after the audit
        // bundles. Placeholder; real emission below.
        quote!()
    } else if fields.has_auto {
        let pushes = &fields.insert_pushes;
        let returning_cols = &fields.returning_cols;
        quote! {
            /// Insert this row against either backend, populating any
            /// `Auto<T>` PK from the auto-assigned value.
            ///
            /// # Errors
            /// As [`Self::insert`].
            pub async fn insert_pool(
                &mut self,
                pool: &::rustango::sql::Pool,
            ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
                let mut _columns: ::std::vec::Vec<&'static str> =
                    ::std::vec::Vec::new();
                let mut _values: ::std::vec::Vec<::rustango::core::SqlValue> =
                    ::std::vec::Vec::new();
                #( #pushes )*
                let _query = ::rustango::core::InsertQuery {
                    model: <Self as ::rustango::core::Model>::SCHEMA,
                    columns: _columns,
                    values: _values,
                    returning: ::std::vec![ #( #returning_cols ),* ],
                    on_conflict: ::core::option::Option::None,
                };
                let _result = ::rustango::sql::insert_returning_pool(
                    pool, &_query,
                ).await?;
                ::rustango::sql::apply_auto_pk_pool(_result, self)
            }
        }
    } else {
        let insert_columns = &fields.insert_columns;
        let insert_values = &fields.insert_values;
        quote! {
            /// Insert this row into its table against either backend.
            /// Equivalent to [`Self::insert`] but takes
            /// [`::rustango::sql::Pool`].
            ///
            /// # Errors
            /// As [`Self::insert`].
            pub async fn insert_pool(
                &self,
                pool: &::rustango::sql::Pool,
            ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
                let _query = ::rustango::core::InsertQuery {
                    model: <Self as ::rustango::core::Model>::SCHEMA,
                    columns: ::std::vec![ #( #insert_columns ),* ],
                    values: ::std::vec![ #( #insert_values ),* ],
                    returning: ::std::vec::Vec::new(),
                    on_conflict: ::core::option::Option::None,
                };
                ::rustango::sql::insert_pool(pool, &_query).await
            }
        }
    };

    // pool_save_method moved to after audit_pair_tokens /
    // audit_pk_to_string (they live ~70 lines below) — needed for
    // the audited branch which builds an UpdateQuery + PendingEntry
    // and dispatches via audit::save_one_with_audit_pool.

    // pool_delete_method moved to after audit_pair_tokens / audit_pk_to_string
    // are computed (they live ~80 lines below).

    // Build the (column, JSON value) pair list used by every
    // snapshot-style audit emission. Reused across delete_on,
    // soft_delete_on, restore_on, and (later) bulk paths. Empty
    // when the model isn't audited.
    let audit_pair_tokens: Vec<TokenStream2> = audited_fields
        .map(|tracked| {
            tracked
                .iter()
                .map(|c| {
                    let column_lit = c.column.as_str();
                    let ident = &c.ident;
                    quote! {
                        (
                            #column_lit,
                            ::serde_json::to_value(&self.#ident)
                                .unwrap_or(::serde_json::Value::Null),
                        )
                    }
                })
                .collect()
        })
        .unwrap_or_default();
    let audit_pk_to_string = if let Some((pk_ident, _)) = primary_key {
        if fields.pk_is_auto {
            quote!(self.#pk_ident.get().map(|v| ::std::format!("{}", v)).unwrap_or_default())
        } else {
            quote!(::std::format!("{}", &self.#pk_ident))
        }
    } else {
        quote!(::std::string::String::new())
    };
    let make_op_emit = |op_path: TokenStream2| -> TokenStream2 {
        if audited_fields.is_some() {
            let pairs = audit_pair_tokens.iter();
            let pk_str = audit_pk_to_string.clone();
            quote! {
                let _audit_entry = ::rustango::audit::PendingEntry {
                    entity_table: <Self as ::rustango::core::Model>::SCHEMA.table,
                    entity_pk: #pk_str,
                    operation: #op_path,
                    source: ::rustango::audit::current_source(),
                    changes: ::rustango::audit::snapshot_changes(&[
                        #( #pairs ),*
                    ]),
                };
                ::rustango::audit::emit_one(&mut *_executor, &_audit_entry).await?;
            }
        } else {
            quote!()
        }
    };
    let audit_insert_emit = make_op_emit(quote!(::rustango::audit::AuditOp::Create));
    let audit_delete_emit = make_op_emit(quote!(::rustango::audit::AuditOp::Delete));
    let audit_softdelete_emit = make_op_emit(quote!(::rustango::audit::AuditOp::SoftDelete));
    let audit_restore_emit = make_op_emit(quote!(::rustango::audit::AuditOp::Restore));

    // `save_pool(&Pool)` — emitted for every model with a PK.
    // Audited Auto-PK models are deferred (the Auto::Unset →
    // insert_pool path needs the audited-insert flow from a future
    // batch). Three body shapes:
    // - non-audited, plain PK: build UpdateQuery + dispatch through
    //   sql::update_pool
    // - non-audited, Auto-PK: same, but Auto::Unset routes to
    //   self.insert_pool which already handles RETURNING / LAST_INSERT_ID
    // - audited, plain PK: build UpdateQuery + PendingEntry, dispatch
    //   through audit::save_one_with_audit_pool (per-backend tx wraps
    //   UPDATE + audit emit atomically). Snapshot-style audit (post-
    //   write field values) — diff-style audit (with pre-UPDATE
    //   SELECT for `before` values) needs per-tracked-column codegen
    //   that doesn't fit the runtime-helper pattern; legacy &PgPool
    //   `save` keeps the diff for now.
    let pool_save_method = if let Some((pk_ident, pk_col)) = primary_key {
        let pk_column_lit = pk_col.as_str();
        let assignments = &fields.update_assignments;
        if audited_fields.is_some() {
            if fields.pk_is_auto {
                // Auto-PK + audited: defer. The Auto::Unset insert
                // path needs a transactional INSERT + LAST_INSERT_ID
                // + audit emit flow — that's a follow-up batch.
                quote!()
            } else {
                let pairs = audit_pair_tokens.iter();
                let pk_str = audit_pk_to_string.clone();
                quote! {
                    /// Save (UPDATE) this row against either backend
                    /// with audit emission inside the same transaction.
                    /// Bi-dialect counterpart of [`Self::save`] for
                    /// audited models with non-`Auto<T>` PKs.
                    ///
                    /// Captures **post-write** field state (snapshot
                    /// audit). The legacy &PgPool [`Self::save`]
                    /// captures BEFORE+AFTER for true diff audit;
                    /// porting that to the &Pool path needs runtime
                    /// per-tracked-column decoding and is deferred.
                    ///
                    /// # Errors
                    /// As [`Self::save`].
                    pub async fn save_pool(
                        &mut self,
                        pool: &::rustango::sql::Pool,
                    ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
                        let _query = ::rustango::core::UpdateQuery {
                            model: <Self as ::rustango::core::Model>::SCHEMA,
                            set: ::std::vec![ #( #assignments ),* ],
                            where_clause: ::rustango::core::WhereExpr::Predicate(
                                ::rustango::core::Filter {
                                    column: #pk_column_lit,
                                    op: ::rustango::core::Op::Eq,
                                    value: ::core::convert::Into::<::rustango::core::SqlValue>::into(
                                        ::core::clone::Clone::clone(&self.#pk_ident)
                                    ),
                                }
                            ),
                        };
                        let _audit_entry = ::rustango::audit::PendingEntry {
                            entity_table: <Self as ::rustango::core::Model>::SCHEMA.table,
                            entity_pk: #pk_str,
                            operation: ::rustango::audit::AuditOp::Update,
                            source: ::rustango::audit::current_source(),
                            changes: ::rustango::audit::snapshot_changes(&[
                                #( #pairs ),*
                            ]),
                        };
                        let _ = ::rustango::audit::save_one_with_audit_pool(
                            pool, &_query, &_audit_entry,
                        ).await?;
                        ::core::result::Result::Ok(())
                    }
                }
            }
        } else {
            let dispatch_unset = if fields.pk_is_auto {
                quote! {
                    if matches!(self.#pk_ident, ::rustango::sql::Auto::Unset) {
                        return self.insert_pool(pool).await;
                    }
                }
            } else {
                quote!()
            };
            quote! {
                /// Save this row to its table against either backend.
                /// `INSERT` when the `Auto<T>` PK is `Unset`, else
                /// `UPDATE` keyed on the PK.
                ///
                /// # Errors
                /// As [`Self::save`].
                pub async fn save_pool(
                    &mut self,
                    pool: &::rustango::sql::Pool,
                ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
                    #dispatch_unset
                    let _query = ::rustango::core::UpdateQuery {
                        model: <Self as ::rustango::core::Model>::SCHEMA,
                        set: ::std::vec![ #( #assignments ),* ],
                        where_clause: ::rustango::core::WhereExpr::Predicate(
                            ::rustango::core::Filter {
                                column: #pk_column_lit,
                                op: ::rustango::core::Op::Eq,
                                value: ::core::convert::Into::<::rustango::core::SqlValue>::into(
                                    ::core::clone::Clone::clone(&self.#pk_ident)
                                ),
                            }
                        ),
                    };
                    let _ = ::rustango::sql::update_pool(pool, &_query).await?;
                    ::core::result::Result::Ok(())
                }
            }
        }
    } else {
        quote!()
    };

    // Audited `insert_pool` (overrides the placeholder set higher up
    // in the function). v0.23.0-batch22 — both Auto-PK and non-Auto-PK
    // audited models get insert_pool routing through
    // audit::insert_one_with_audit_pool (per-backend tx wraps INSERT
    // + auto-PK readback + audit emit). Snapshot-style audit (the
    // PendingEntry's `changes` carries post-write field values).
    let pool_insert_method = if audited_fields.is_some() {
        if let Some(_) = primary_key {
            let pushes = if fields.has_auto {
                fields.insert_pushes.clone()
            } else {
                // For non-Auto-PK models, the macro normally builds
                // {columns, values} from fields.insert_columns +
                // fields.insert_values rather than insert_pushes.
                // Map those into the pushes shape.
                fields
                    .insert_columns
                    .iter()
                    .zip(&fields.insert_values)
                    .map(|(col, val)| {
                        quote! {
                            _columns.push(#col);
                            _values.push(#val);
                        }
                    })
                    .collect()
            };
            let returning_cols: Vec<proc_macro2::TokenStream> = if fields.has_auto {
                fields.returning_cols.clone()
            } else {
                // Non-Auto-PK: still need RETURNING something for the
                // audit helper's contract (it errors on empty
                // returning). Return the PK column so the audit row
                // can carry the assigned PK back. Some non-Auto PKs
                // are server-side-default (e.g. UUIDv4 default), so
                // RETURNING is genuinely useful.
                primary_key
                    .map(|(_, col)| {
                        let lit = col.as_str();
                        vec![quote!(#lit)]
                    })
                    .unwrap_or_default()
            };
            let pairs = audit_pair_tokens.iter();
            let pk_str = audit_pk_to_string.clone();
            quote! {
                /// Insert this row against either backend with audit
                /// emission inside the same transaction. Bi-dialect
                /// counterpart of [`Self::insert`] for audited models.
                ///
                /// Snapshot-style audit (post-write field values).
                ///
                /// # Errors
                /// As [`Self::insert`].
                pub async fn insert_pool(
                    &mut self,
                    pool: &::rustango::sql::Pool,
                ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
                    let mut _columns: ::std::vec::Vec<&'static str> =
                        ::std::vec::Vec::new();
                    let mut _values: ::std::vec::Vec<::rustango::core::SqlValue> =
                        ::std::vec::Vec::new();
                    #( #pushes )*
                    let _query = ::rustango::core::InsertQuery {
                        model: <Self as ::rustango::core::Model>::SCHEMA,
                        columns: _columns,
                        values: _values,
                        returning: ::std::vec![ #( #returning_cols ),* ],
                        on_conflict: ::core::option::Option::None,
                    };
                    let _audit_entry = ::rustango::audit::PendingEntry {
                        entity_table: <Self as ::rustango::core::Model>::SCHEMA.table,
                        entity_pk: #pk_str,
                        operation: ::rustango::audit::AuditOp::Create,
                        source: ::rustango::audit::current_source(),
                        changes: ::rustango::audit::snapshot_changes(&[
                            #( #pairs ),*
                        ]),
                    };
                    let _result = ::rustango::audit::insert_one_with_audit_pool(
                        pool, &_query, &_audit_entry,
                    ).await?;
                    ::rustango::sql::apply_auto_pk_pool(_result, self)
                }
            }
        } else {
            quote!()
        }
    } else {
        // Keep the non-audited pool_insert_method we built earlier.
        pool_insert_method
    };

    // Update audited save_pool: now that insert_pool is wired for
    // audited Auto-PK models, save_pool can dispatch Auto::Unset →
    // insert_pool. Non-audited save_pool already does this.
    // v0.23.0-batch25 — diff-style audit on the audited save_pool path.
    // Replaces the snapshot-only emission with a per-backend transaction
    // body that:
    //  1. SELECTs the tracked columns by PK (typed Row::try_get per
    //     column), capturing BEFORE values
    //  2. compiles the UPDATE via pool.dialect() and runs it on the tx
    //  3. builds AFTER pairs from &self
    //  4. diffs BEFORE/AFTER, emits one PendingEntry with
    //     AuditOp::Update + diff_changes(...) on the same tx connection
    //  5. commits
    //
    // Per-backend arms inline the SQL string + placeholder shape, then
    // share the `audit_before_pair_tokens` decoder block (Row::try_get
    // is polymorphic over Row type — the same tokens work against
    // PgRow and MySqlRow as long as the field's Rust type implements
    // both Decode<Postgres> and Decode<MySql>, which Auto<T> +
    // primitives + chrono/uuid/serde_json::Value all do).
    let pool_save_method = if let Some(tracked) = audited_fields {
        if let Some((pk_ident, pk_col)) = primary_key {
            let pk_column_lit = pk_col.as_str();
            // Two iterators — quote!'s `#(#var)*` consumes the
            // iterator, and we need to splice the same after-pairs
            // sequence into both per-backend arms.
            let after_pairs_pg = audit_pair_tokens.iter().collect::<Vec<_>>();
            let pk_str = audit_pk_to_string.clone();
            // Per-tracked-column BEFORE-pair token list. Each entry
            // is `(col_lit, try_get_returning<value_ty>(row, col_lit) → Json)`.
            // The Row alias resolves to PgRow / MySqlRow per call site,
            // so the same template generates both the PG and MySQL bodies.
            let mk_before_pairs =
                |getter: proc_macro2::TokenStream| -> Vec<proc_macro2::TokenStream> {
                    tracked
                        .iter()
                        .map(|c| {
                            let column_lit = c.column.as_str();
                            let value_ty = &c.value_ty;
                            quote! {
                                (
                                    #column_lit,
                                    match #getter::<#value_ty>(
                                        _audit_before_row, #column_lit,
                                    ) {
                                        ::core::result::Result::Ok(v) => {
                                            ::serde_json::to_value(&v)
                                                .unwrap_or(::serde_json::Value::Null)
                                        }
                                        ::core::result::Result::Err(_) => ::serde_json::Value::Null,
                                    },
                                )
                            }
                        })
                        .collect()
                };
            let before_pairs_pg: Vec<proc_macro2::TokenStream> =
                mk_before_pairs(quote!(::rustango::sql::try_get_returning));
            let before_pairs_my: Vec<proc_macro2::TokenStream> =
                mk_before_pairs(quote!(::rustango::sql::try_get_returning_my));
            let before_pairs_sqlite: Vec<proc_macro2::TokenStream> =
                mk_before_pairs(quote!(::rustango::sql::try_get_returning_sqlite));
            let pg_select_cols: String = tracked
                .iter()
                .map(|c| format!("\"{}\"", c.column.replace('"', "\"\"")))
                .collect::<Vec<_>>()
                .join(", ");
            let my_select_cols: String = tracked
                .iter()
                .map(|c| format!("`{}`", c.column.replace('`', "``")))
                .collect::<Vec<_>>()
                .join(", ");
            // SQLite uses double-quote identifier quoting (same as
            // Postgres in default config), so the column-list shape
            // matches PG.
            let sqlite_select_cols: String = pg_select_cols.clone();
            let pk_value_for_bind = if fields.pk_is_auto {
                quote!(self.#pk_ident.get().copied().unwrap_or_default())
            } else {
                quote!(::core::clone::Clone::clone(&self.#pk_ident))
            };
            let assignments = &fields.update_assignments;
            let unset_dispatch = if fields.has_auto {
                quote! {
                    if matches!(self.#pk_ident, ::rustango::sql::Auto::Unset) {
                        return self.insert_pool(pool).await;
                    }
                }
            } else {
                quote!()
            };
            quote! {
                /// Save this row against either backend with audit
                /// emission (diff-style: BEFORE+AFTER) inside the
                /// same transaction. Auto::Unset PK routes to
                /// insert_pool. Bi-dialect counterpart of
                /// [`Self::save`] for audited models.
                ///
                /// The audit row's `changes` JSON contains one
                /// `{ "field": { "before": …, "after": … } }` entry
                /// per tracked column whose value actually changed
                /// — same shape as the existing &PgPool save() emits.
                ///
                /// # Errors
                /// As [`Self::save`].
                pub async fn save_pool(
                    &mut self,
                    pool: &::rustango::sql::Pool,
                ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
                    #unset_dispatch
                    let _query = ::rustango::core::UpdateQuery {
                        model: <Self as ::rustango::core::Model>::SCHEMA,
                        set: ::std::vec![ #( #assignments ),* ],
                        where_clause: ::rustango::core::WhereExpr::Predicate(
                            ::rustango::core::Filter {
                                column: #pk_column_lit,
                                op: ::rustango::core::Op::Eq,
                                value: ::core::convert::Into::<::rustango::core::SqlValue>::into(
                                    ::core::clone::Clone::clone(&self.#pk_ident)
                                ),
                            }
                        ),
                    };
                    let _after_pairs: ::std::vec::Vec<(&'static str, ::serde_json::Value)> =
                        ::std::vec![ #( #after_pairs_pg ),* ];
                    ::rustango::audit::save_one_with_diff_pool(
                        pool,
                        &_query,
                        #pk_column_lit,
                        ::core::convert::Into::<::rustango::core::SqlValue>::into(
                            #pk_value_for_bind,
                        ),
                        <Self as ::rustango::core::Model>::SCHEMA.table,
                        #pk_str,
                        _after_pairs,
                        #pg_select_cols,
                        #my_select_cols,
                        #sqlite_select_cols,
                        |_audit_before_row| ::std::vec![ #( #before_pairs_pg ),* ],
                        |_audit_before_row| ::std::vec![ #( #before_pairs_my ),* ],
                        |_audit_before_row| ::std::vec![ #( #before_pairs_sqlite ),* ],
                    ).await
                }
            }
        } else {
            quote!()
        }
    } else {
        pool_save_method
    };

    // `delete_pool(&Pool)` — emitted for every model with a PK. Two
    // body shapes:
    // - non-audited: simple dispatch through `sql::delete_pool`
    // - audited: routes through `audit::delete_one_with_audit_pool`,
    //   which opens a per-backend transaction wrapping DELETE +
    //   audit emit so the data write and audit row commit atomically.
    let pool_delete_method = {
        let pk_column_lit = primary_key.map(|(_, col)| col.as_str()).unwrap_or("id");
        let pk_ident_for_pool = primary_key.map(|(ident, _)| ident);
        if let Some(pk_ident) = pk_ident_for_pool {
            if audited_fields.is_some() {
                let pairs = audit_pair_tokens.iter();
                let pk_str = audit_pk_to_string.clone();
                quote! {
                    /// Delete this row against either backend with audit
                    /// emission inside the same transaction. Bi-dialect
                    /// counterpart of [`Self::delete`] for audited models.
                    ///
                    /// # Errors
                    /// As [`Self::delete`].
                    pub async fn delete_pool(
                        &self,
                        pool: &::rustango::sql::Pool,
                    ) -> ::core::result::Result<u64, ::rustango::sql::ExecError> {
                        let _query = ::rustango::core::DeleteQuery {
                            model: <Self as ::rustango::core::Model>::SCHEMA,
                            where_clause: ::rustango::core::WhereExpr::Predicate(
                                ::rustango::core::Filter {
                                    column: #pk_column_lit,
                                    op: ::rustango::core::Op::Eq,
                                    value: ::core::convert::Into::<::rustango::core::SqlValue>::into(
                                        ::core::clone::Clone::clone(&self.#pk_ident)
                                    ),
                                }
                            ),
                        };
                        let _audit_entry = ::rustango::audit::PendingEntry {
                            entity_table: <Self as ::rustango::core::Model>::SCHEMA.table,
                            entity_pk: #pk_str,
                            operation: ::rustango::audit::AuditOp::Delete,
                            source: ::rustango::audit::current_source(),
                            changes: ::rustango::audit::snapshot_changes(&[
                                #( #pairs ),*
                            ]),
                        };
                        ::rustango::audit::delete_one_with_audit_pool(
                            pool, &_query, &_audit_entry,
                        ).await
                    }
                }
            } else {
                quote! {
                    /// Delete the row identified by this instance's primary key
                    /// against either backend. Equivalent to [`Self::delete`] but
                    /// takes [`::rustango::sql::Pool`] and dispatches per backend.
                    ///
                    /// # Errors
                    /// As [`Self::delete`].
                    pub async fn delete_pool(
                        &self,
                        pool: &::rustango::sql::Pool,
                    ) -> ::core::result::Result<u64, ::rustango::sql::ExecError> {
                        let _query = ::rustango::core::DeleteQuery {
                            model: <Self as ::rustango::core::Model>::SCHEMA,
                            where_clause: ::rustango::core::WhereExpr::Predicate(
                                ::rustango::core::Filter {
                                    column: #pk_column_lit,
                                    op: ::rustango::core::Op::Eq,
                                    value: ::core::convert::Into::<::rustango::core::SqlValue>::into(
                                        ::core::clone::Clone::clone(&self.#pk_ident)
                                    ),
                                }
                            ),
                        };
                        ::rustango::sql::delete_pool(pool, &_query).await
                    }
                }
            }
        } else {
            quote!()
        }
    };

    // Update emission captures both BEFORE and AFTER state — runs an
    // extra SELECT against `_executor` BEFORE the UPDATE, captures
    // each tracked field's prior value, then after the UPDATE diffs
    // against the in-memory `&self`. `diff_changes` drops unchanged
    // columns so the JSON only contains the actual delta.
    //
    // Two-fragment shape: `audit_update_pre` runs before the UPDATE
    // and binds `_audit_before_pairs`; `audit_update_post` runs
    // after the UPDATE and emits the PendingEntry.
    let (audit_update_pre, audit_update_post): (TokenStream2, TokenStream2) = if let Some(tracked) =
        audited_fields
    {
        if tracked.is_empty() {
            (quote!(), quote!())
        } else {
            let select_cols: String = tracked
                .iter()
                .map(|c| format!("\"{}\"", c.column.replace('"', "\"\"")))
                .collect::<Vec<_>>()
                .join(", ");
            let pk_column_for_select = primary_key.map(|(_, col)| col.clone()).unwrap_or_default();
            let select_cols_lit = select_cols;
            let pk_column_lit_for_select = pk_column_for_select;
            let pk_value_for_bind = if let Some((pk_ident, _)) = primary_key {
                if fields.pk_is_auto {
                    quote!(self.#pk_ident.get().copied().unwrap_or_default())
                } else {
                    quote!(::core::clone::Clone::clone(&self.#pk_ident))
                }
            } else {
                quote!(0_i64)
            };
            let before_pairs = tracked.iter().map(|c| {
                let column_lit = c.column.as_str();
                let value_ty = &c.value_ty;
                quote! {
                    (
                        #column_lit,
                        match ::rustango::sql::sqlx::Row::try_get::<#value_ty, _>(
                            &_audit_before_row, #column_lit,
                        ) {
                            ::core::result::Result::Ok(v) => {
                                ::serde_json::to_value(&v)
                                    .unwrap_or(::serde_json::Value::Null)
                            }
                            ::core::result::Result::Err(_) => ::serde_json::Value::Null,
                        },
                    )
                }
            });
            let after_pairs = tracked.iter().map(|c| {
                let column_lit = c.column.as_str();
                let ident = &c.ident;
                quote! {
                    (
                        #column_lit,
                        ::serde_json::to_value(&self.#ident)
                            .unwrap_or(::serde_json::Value::Null),
                    )
                }
            });
            let pk_str = audit_pk_to_string.clone();
            let pre = quote! {
                let _audit_select_sql = ::std::format!(
                    r#"SELECT {} FROM "{}" WHERE "{}" = $1"#,
                    #select_cols_lit,
                    <Self as ::rustango::core::Model>::SCHEMA.table,
                    #pk_column_lit_for_select,
                );
                let _audit_before_pairs:
                    ::std::option::Option<::std::vec::Vec<(&'static str, ::serde_json::Value)>> =
                    match ::rustango::sql::sqlx::query(&_audit_select_sql)
                        .bind(#pk_value_for_bind)
                        .fetch_optional(&mut *_executor)
                        .await
                    {
                        ::core::result::Result::Ok(::core::option::Option::Some(_audit_before_row)) => {
                            ::core::option::Option::Some(::std::vec![ #( #before_pairs ),* ])
                        }
                        _ => ::core::option::Option::None,
                    };
            };
            let post = quote! {
                if let ::core::option::Option::Some(_audit_before) = _audit_before_pairs {
                    let _audit_after:
                        ::std::vec::Vec<(&'static str, ::serde_json::Value)> =
                        ::std::vec![ #( #after_pairs ),* ];
                    let _audit_entry = ::rustango::audit::PendingEntry {
                        entity_table: <Self as ::rustango::core::Model>::SCHEMA.table,
                        entity_pk: #pk_str,
                        operation: ::rustango::audit::AuditOp::Update,
                        source: ::rustango::audit::current_source(),
                        changes: ::rustango::audit::diff_changes(
                            &_audit_before,
                            &_audit_after,
                        ),
                    };
                    ::rustango::audit::emit_one(&mut *_executor, &_audit_entry).await?;
                }
            };
            (pre, post)
        }
    } else {
        (quote!(), quote!())
    };

    // Bulk-insert audit: capture every row's tracked fields after the
    // RETURNING populates each PK, then push one batched INSERT INTO
    // audit_log via `emit_many`. One round-trip regardless of N rows.
    let audit_bulk_insert_emit: TokenStream2 = if audited_fields.is_some() {
        let row_pk_str = if let Some((pk_ident, _)) = primary_key {
            if fields.pk_is_auto {
                quote!(_row.#pk_ident.get().map(|v| ::std::format!("{}", v)).unwrap_or_default())
            } else {
                quote!(::std::format!("{}", &_row.#pk_ident))
            }
        } else {
            quote!(::std::string::String::new())
        };
        let row_pairs = audited_fields.unwrap_or(&[]).iter().map(|c| {
            let column_lit = c.column.as_str();
            let ident = &c.ident;
            quote! {
                (
                    #column_lit,
                    ::serde_json::to_value(&_row.#ident)
                        .unwrap_or(::serde_json::Value::Null),
                )
            }
        });
        quote! {
            let _audit_source = ::rustango::audit::current_source();
            let mut _audit_entries:
                ::std::vec::Vec<::rustango::audit::PendingEntry> =
                    ::std::vec::Vec::with_capacity(rows.len());
            for _row in rows.iter() {
                _audit_entries.push(::rustango::audit::PendingEntry {
                    entity_table: <Self as ::rustango::core::Model>::SCHEMA.table,
                    entity_pk: #row_pk_str,
                    operation: ::rustango::audit::AuditOp::Create,
                    source: _audit_source.clone(),
                    changes: ::rustango::audit::snapshot_changes(&[
                        #( #row_pairs ),*
                    ]),
                });
            }
            ::rustango::audit::emit_many(&mut *_executor, &_audit_entries).await?;
        }
    } else {
        quote!()
    };

    let save_method = if fields.pk_is_auto {
        let (pk_ident, pk_column) = primary_key.expect("pk_is_auto implies primary_key is Some");
        let pk_column_lit = pk_column.as_str();
        let assignments = &fields.update_assignments;
        let upsert_cols = &fields.upsert_update_columns;
        let upsert_pushes = &fields.insert_pushes;
        let upsert_returning = &fields.returning_cols;
        let upsert_auto_assigns = &fields.auto_assigns;
        // Conflict target: prefer the first declared `unique_together`
        // when it exists. Plain `Auto<T>` PKs are server-assigned via
        // `BIGSERIAL` and never collide on insert, so a PK-only target
        // would silently turn `upsert()` into "always-insert" for
        // surrogate-PK models with composite UNIQUE constraints — see
        // `RolePermission` / `UserRole` / `UserPermission` in the
        // tenancy permission engine. When no `unique_together` is
        // declared we keep the PK target (the original behaviour).
        let upsert_target_columns: Vec<String> = indexes
            .iter()
            .find(|i| i.unique && !i.columns.is_empty())
            .map(|i| i.columns.clone())
            .unwrap_or_else(|| vec![pk_column.clone()]);
        let upsert_target_lits = upsert_target_columns
            .iter()
            .map(String::as_str)
            .collect::<Vec<_>>();
        let conflict_clause = if fields.upsert_update_columns.is_empty() {
            quote!(::rustango::core::ConflictClause::DoNothing)
        } else {
            quote!(::rustango::core::ConflictClause::DoUpdate {
                target: ::std::vec![ #( #upsert_target_lits ),* ],
                update_columns: ::std::vec![ #( #upsert_cols ),* ],
            })
        };
        Some(quote! {
            /// Insert this row if its `Auto<T>` primary key is
            /// `Unset`, otherwise update the existing row matching the
            /// PK. Mirrors Django's `save()` — caller doesn't need to
            /// pick `insert` vs the bulk-update path manually.
            ///
            /// On the insert branch, populates the PK from `RETURNING`
            /// (same behavior as `insert`). On the update branch,
            /// writes every non-PK column back; if no row matches the
            /// PK, returns `Ok(())` silently.
            ///
            /// Only generated when the primary key is declared as
            /// `Auto<T>`. Models with a manually-managed PK must use
            /// `insert` or the QuerySet update builder.
            ///
            /// # Errors
            /// Returns [`::rustango::sql::ExecError`] for SQL-writing
            /// or driver failures.
            pub async fn save(
                &mut self,
                pool: &::rustango::sql::sqlx::PgPool,
            ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
                #pool_to_save_on
            }

            /// Like [`Self::save`] but accepts any sqlx executor —
            /// `&PgPool`, `&mut PgConnection`, or a transaction. The
            /// escape hatch for tenant-scoped writes: schema-mode
            /// tenants share the registry pool but rely on a per-
            /// checkout `SET search_path`, so passing `&PgPool` would
            /// silently hit the wrong schema. Acquire a connection
            /// via `TenantPools::acquire(&org)` and pass `&mut *conn`.
            ///
            /// # Errors
            /// As [`Self::save`].
            pub async fn save_on #executor_generics (
                &mut self,
                #executor_param,
            ) -> ::core::result::Result<(), ::rustango::sql::ExecError>
            #executor_where
            {
                if matches!(self.#pk_ident, ::rustango::sql::Auto::Unset) {
                    return self.insert_on(#executor_passes_to_data_write).await;
                }
                #audit_update_pre
                let _query = ::rustango::core::UpdateQuery {
                    model: <Self as ::rustango::core::Model>::SCHEMA,
                    set: ::std::vec![ #( #assignments ),* ],
                    where_clause: ::rustango::core::WhereExpr::Predicate(
                        ::rustango::core::Filter {
                            column: #pk_column_lit,
                            op: ::rustango::core::Op::Eq,
                            value: ::core::convert::Into::<::rustango::core::SqlValue>::into(
                                ::core::clone::Clone::clone(&self.#pk_ident)
                            ),
                        }
                    ),
                };
                let _ = ::rustango::sql::update_on(
                    #executor_passes_to_data_write,
                    &_query,
                ).await?;
                #audit_update_post
                ::core::result::Result::Ok(())
            }

            /// Per-call override for the audit source. Runs
            /// [`Self::save_on`] inside an [`::rustango::audit::with_source`]
            /// scope so the resulting audit entry records `source`
            /// instead of the task-local default. Useful for seed
            /// scripts and one-off CLI tools that don't sit inside an
            /// admin handler. The override applies only to this call;
            /// no global state changes.
            ///
            /// # Errors
            /// As [`Self::save_on`].
            pub async fn save_on_with #executor_generics (
                &mut self,
                #executor_param,
                source: ::rustango::audit::AuditSource,
            ) -> ::core::result::Result<(), ::rustango::sql::ExecError>
            #executor_where
            {
                ::rustango::audit::with_source(source, self.save_on(_executor)).await
            }

            /// Insert this row or update it in-place if the primary key already
            /// exists — single round-trip via `INSERT … ON CONFLICT (pk) DO UPDATE`.
            ///
            /// With `Auto::Unset` PK the server assigns a new key and no conflict
            /// can occur (equivalent to `insert`). With `Auto::Set` PK the row is
            /// inserted if absent or all non-PK columns are overwritten if present.
            ///
            /// # Errors
            /// As [`Self::insert_on`].
            pub async fn upsert(
                &mut self,
                pool: &::rustango::sql::sqlx::PgPool,
            ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
                #pool_to_upsert_on
            }

            /// Like [`Self::upsert`] but accepts any sqlx executor.
            /// See [`Self::save_on`] for tenancy-scoped rationale.
            ///
            /// # Errors
            /// As [`Self::upsert`].
            pub async fn upsert_on #executor_generics (
                &mut self,
                #executor_param,
            ) -> ::core::result::Result<(), ::rustango::sql::ExecError>
            #executor_where
            {
                let mut _columns: ::std::vec::Vec<&'static str> =
                    ::std::vec::Vec::new();
                let mut _values: ::std::vec::Vec<::rustango::core::SqlValue> =
                    ::std::vec::Vec::new();
                #( #upsert_pushes )*
                let query = ::rustango::core::InsertQuery {
                    model: <Self as ::rustango::core::Model>::SCHEMA,
                    columns: _columns,
                    values: _values,
                    returning: ::std::vec![ #( #upsert_returning ),* ],
                    on_conflict: ::core::option::Option::Some(#conflict_clause),
                };
                let _returning_row_v = ::rustango::sql::insert_returning_on(
                    #executor_passes_to_data_write,
                    &query,
                ).await?;
                let _returning_row = &_returning_row_v;
                #( #upsert_auto_assigns )*
                ::core::result::Result::Ok(())
            }
        })
    } else {
        None
    };

    let pk_methods = primary_key.map(|(pk_ident, pk_column)| {
        let pk_column_lit = pk_column.as_str();
        // Optional `soft_delete_on` / `restore_on` companions when the
        // model has a `#[rustango(soft_delete)]` column. They land
        // alongside the regular `delete_on` so callers have both
        // options — a hard delete (audit-tracked as a real DELETE) and
        // a logical delete (audit-tracked as an UPDATE setting the
        // deleted_at column to NOW()).
        let soft_delete_methods = if let Some(col) = fields.soft_delete_column.as_deref() {
            let col_lit = col;
            quote! {
                /// Soft-delete this row by setting its
                /// `#[rustango(soft_delete)]` column to `NOW()`.
                /// Mirrors Django's `SoftDeleteModel.delete()` shape:
                /// the row stays in the table; query helpers can
                /// filter it out by checking the column for `IS NOT
                /// NULL`.
                ///
                /// # Errors
                /// As [`Self::delete`].
                pub async fn soft_delete_on #executor_generics (
                    &self,
                    #executor_param,
                ) -> ::core::result::Result<u64, ::rustango::sql::ExecError>
                #executor_where
                {
                    let _query = ::rustango::core::UpdateQuery {
                        model: <Self as ::rustango::core::Model>::SCHEMA,
                        set: ::std::vec![
                            ::rustango::core::Assignment {
                                column: #col_lit,
                                value: ::core::convert::Into::<::rustango::core::SqlValue>::into(
                                    ::chrono::Utc::now()
                                ),
                            },
                        ],
                        where_clause: ::rustango::core::WhereExpr::Predicate(
                            ::rustango::core::Filter {
                                column: #pk_column_lit,
                                op: ::rustango::core::Op::Eq,
                                value: ::core::convert::Into::<::rustango::core::SqlValue>::into(
                                    ::core::clone::Clone::clone(&self.#pk_ident)
                                ),
                            }
                        ),
                    };
                    let _affected = ::rustango::sql::update_on(
                        #executor_passes_to_data_write,
                        &_query,
                    ).await?;
                    #audit_softdelete_emit
                    ::core::result::Result::Ok(_affected)
                }

                /// Inverse of [`Self::soft_delete_on`] — clears the
                /// soft-delete column back to NULL so the row is
                /// considered live again.
                ///
                /// # Errors
                /// As [`Self::delete`].
                pub async fn restore_on #executor_generics (
                    &self,
                    #executor_param,
                ) -> ::core::result::Result<u64, ::rustango::sql::ExecError>
                #executor_where
                {
                    let _query = ::rustango::core::UpdateQuery {
                        model: <Self as ::rustango::core::Model>::SCHEMA,
                        set: ::std::vec![
                            ::rustango::core::Assignment {
                                column: #col_lit,
                                value: ::rustango::core::SqlValue::Null,
                            },
                        ],
                        where_clause: ::rustango::core::WhereExpr::Predicate(
                            ::rustango::core::Filter {
                                column: #pk_column_lit,
                                op: ::rustango::core::Op::Eq,
                                value: ::core::convert::Into::<::rustango::core::SqlValue>::into(
                                    ::core::clone::Clone::clone(&self.#pk_ident)
                                ),
                            }
                        ),
                    };
                    let _affected = ::rustango::sql::update_on(
                        #executor_passes_to_data_write,
                        &_query,
                    ).await?;
                    #audit_restore_emit
                    ::core::result::Result::Ok(_affected)
                }
            }
        } else {
            quote!()
        };
        quote! {
            /// Delete the row identified by this instance's primary key.
            ///
            /// Returns the number of rows affected (0 or 1).
            ///
            /// # Errors
            /// Returns [`::rustango::sql::ExecError`] for SQL-writing or
            /// driver failures.
            pub async fn delete(
                &self,
                pool: &::rustango::sql::sqlx::PgPool,
            ) -> ::core::result::Result<u64, ::rustango::sql::ExecError> {
                #pool_to_delete_on
            }

            /// Like [`Self::delete`] but accepts any sqlx executor —
            /// for tenant-scoped deletes against an explicitly-acquired
            /// connection. See [`Self::save_on`] for the rationale.
            ///
            /// # Errors
            /// As [`Self::delete`].
            pub async fn delete_on #executor_generics (
                &self,
                #executor_param,
            ) -> ::core::result::Result<u64, ::rustango::sql::ExecError>
            #executor_where
            {
                let query = ::rustango::core::DeleteQuery {
                    model: <Self as ::rustango::core::Model>::SCHEMA,
                    where_clause: ::rustango::core::WhereExpr::Predicate(
                        ::rustango::core::Filter {
                            column: #pk_column_lit,
                            op: ::rustango::core::Op::Eq,
                            value: ::core::convert::Into::<::rustango::core::SqlValue>::into(
                                ::core::clone::Clone::clone(&self.#pk_ident)
                            ),
                        }
                    ),
                };
                let _affected = ::rustango::sql::delete_on(
                    #executor_passes_to_data_write,
                    &query,
                ).await?;
                #audit_delete_emit
                ::core::result::Result::Ok(_affected)
            }

            /// Per-call audit-source override for [`Self::delete_on`].
            /// See [`Self::save_on_with`] for shape rationale.
            ///
            /// # Errors
            /// As [`Self::delete_on`].
            pub async fn delete_on_with #executor_generics (
                &self,
                #executor_param,
                source: ::rustango::audit::AuditSource,
            ) -> ::core::result::Result<u64, ::rustango::sql::ExecError>
            #executor_where
            {
                ::rustango::audit::with_source(source, self.delete_on(_executor)).await
            }
            #pool_delete_method
            #pool_insert_method
            #pool_save_method
            #soft_delete_methods
        }
    });

    let insert_method = if fields.has_auto {
        let pushes = &fields.insert_pushes;
        let returning_cols = &fields.returning_cols;
        let auto_assigns = &fields.auto_assigns;
        quote! {
            /// Insert this row into its table. Skips columns whose
            /// `Auto<T>` value is `Unset` so Postgres' SERIAL/BIGSERIAL
            /// sequence fills them in, then reads each `Auto` column
            /// back via `RETURNING` and stores it on `self`.
            ///
            /// # Errors
            /// Returns [`::rustango::sql::ExecError`] for SQL-writing or
            /// driver failures.
            pub async fn insert(
                &mut self,
                pool: &::rustango::sql::sqlx::PgPool,
            ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
                #pool_to_insert_on
            }

            /// Like [`Self::insert`] but accepts any sqlx executor.
            /// See [`Self::save_on`] for tenancy-scoped rationale.
            ///
            /// # Errors
            /// As [`Self::insert`].
            pub async fn insert_on #executor_generics (
                &mut self,
                #executor_param,
            ) -> ::core::result::Result<(), ::rustango::sql::ExecError>
            #executor_where
            {
                let mut _columns: ::std::vec::Vec<&'static str> =
                    ::std::vec::Vec::new();
                let mut _values: ::std::vec::Vec<::rustango::core::SqlValue> =
                    ::std::vec::Vec::new();
                #( #pushes )*
                let query = ::rustango::core::InsertQuery {
                    model: <Self as ::rustango::core::Model>::SCHEMA,
                    columns: _columns,
                    values: _values,
                    returning: ::std::vec![ #( #returning_cols ),* ],
                    on_conflict: ::core::option::Option::None,
                };
                let _returning_row_v = ::rustango::sql::insert_returning_on(
                    #executor_passes_to_data_write,
                    &query,
                ).await?;
                let _returning_row = &_returning_row_v;
                #( #auto_assigns )*
                #audit_insert_emit
                ::core::result::Result::Ok(())
            }

            /// Per-call audit-source override for [`Self::insert_on`].
            /// See [`Self::save_on_with`] for shape rationale.
            ///
            /// # Errors
            /// As [`Self::insert_on`].
            pub async fn insert_on_with #executor_generics (
                &mut self,
                #executor_param,
                source: ::rustango::audit::AuditSource,
            ) -> ::core::result::Result<(), ::rustango::sql::ExecError>
            #executor_where
            {
                ::rustango::audit::with_source(source, self.insert_on(_executor)).await
            }
        }
    } else {
        let insert_columns = &fields.insert_columns;
        let insert_values = &fields.insert_values;
        quote! {
            /// Insert this row into its table.
            ///
            /// # Errors
            /// Returns [`::rustango::sql::ExecError`] for SQL-writing or
            /// driver failures.
            pub async fn insert(
                &self,
                pool: &::rustango::sql::sqlx::PgPool,
            ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
                self.insert_on(pool).await
            }

            /// Like [`Self::insert`] but accepts any sqlx executor.
            /// See [`Self::save_on`] for tenancy-scoped rationale.
            ///
            /// # Errors
            /// As [`Self::insert`].
            pub async fn insert_on<'_c, _E>(
                &self,
                _executor: _E,
            ) -> ::core::result::Result<(), ::rustango::sql::ExecError>
            where
                _E: ::rustango::sql::sqlx::Executor<'_c, Database = ::rustango::sql::sqlx::Postgres>,
            {
                let query = ::rustango::core::InsertQuery {
                    model: <Self as ::rustango::core::Model>::SCHEMA,
                    columns: ::std::vec![ #( #insert_columns ),* ],
                    values: ::std::vec![ #( #insert_values ),* ],
                    returning: ::std::vec::Vec::new(),
                    on_conflict: ::core::option::Option::None,
                };
                ::rustango::sql::insert_on(_executor, &query).await
            }
        }
    };

    let bulk_insert_method = if fields.has_auto {
        let cols_no_auto = &fields.bulk_columns_no_auto;
        let cols_all = &fields.bulk_columns_all;
        let pushes_no_auto = &fields.bulk_pushes_no_auto;
        let pushes_all = &fields.bulk_pushes_all;
        let returning_cols = &fields.returning_cols;
        let auto_assigns_for_row = bulk_auto_assigns_for_row(fields);
        let uniformity = &fields.bulk_auto_uniformity;
        let first_auto_ident = fields
            .first_auto_ident
            .as_ref()
            .expect("has_auto implies first_auto_ident is Some");
        quote! {
            /// Bulk-insert `rows` in a single round-trip. Every row's
            /// `Auto<T>` PK fields must uniformly be `Auto::Unset`
            /// (sequence fills them in) or uniformly `Auto::Set(_)`
            /// (caller-supplied values). Mixed Set/Unset is rejected
            /// — call `insert` per row for that case.
            ///
            /// Empty slice is a no-op. Each row's `Auto` fields are
            /// populated from the `RETURNING` clause in input order
            /// before this returns.
            ///
            /// # Errors
            /// Returns [`::rustango::sql::ExecError`] for validation,
            /// SQL-writing, mixed-Auto rejection, or driver failures.
            pub async fn bulk_insert(
                rows: &mut [Self],
                pool: &::rustango::sql::sqlx::PgPool,
            ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
                #pool_to_bulk_insert_on
            }

            /// Like [`Self::bulk_insert`] but accepts any sqlx executor.
            /// See [`Self::save_on`] for tenancy-scoped rationale.
            ///
            /// # Errors
            /// As [`Self::bulk_insert`].
            pub async fn bulk_insert_on #executor_generics (
                rows: &mut [Self],
                #executor_param,
            ) -> ::core::result::Result<(), ::rustango::sql::ExecError>
            #executor_where
            {
                if rows.is_empty() {
                    return ::core::result::Result::Ok(());
                }
                let _first_unset = matches!(
                    rows[0].#first_auto_ident,
                    ::rustango::sql::Auto::Unset
                );
                #( #uniformity )*

                let mut _all_rows: ::std::vec::Vec<
                    ::std::vec::Vec<::rustango::core::SqlValue>,
                > = ::std::vec::Vec::with_capacity(rows.len());
                let _columns: ::std::vec::Vec<&'static str> = if _first_unset {
                    for _row in rows.iter() {
                        let mut _row_vals: ::std::vec::Vec<::rustango::core::SqlValue> =
                            ::std::vec::Vec::new();
                        #( #pushes_no_auto )*
                        _all_rows.push(_row_vals);
                    }
                    ::std::vec![ #( #cols_no_auto ),* ]
                } else {
                    for _row in rows.iter() {
                        let mut _row_vals: ::std::vec::Vec<::rustango::core::SqlValue> =
                            ::std::vec::Vec::new();
                        #( #pushes_all )*
                        _all_rows.push(_row_vals);
                    }
                    ::std::vec![ #( #cols_all ),* ]
                };

                let _query = ::rustango::core::BulkInsertQuery {
                    model: <Self as ::rustango::core::Model>::SCHEMA,
                    columns: _columns,
                    rows: _all_rows,
                    returning: ::std::vec![ #( #returning_cols ),* ],
                    on_conflict: ::core::option::Option::None,
                };
                let _returned = ::rustango::sql::bulk_insert_on(
                    #executor_passes_to_data_write,
                    &_query,
                ).await?;
                if _returned.len() != rows.len() {
                    return ::core::result::Result::Err(
                        ::rustango::sql::ExecError::Sql(
                            ::rustango::sql::SqlError::BulkInsertReturningMismatch {
                                expected: rows.len(),
                                actual: _returned.len(),
                            }
                        )
                    );
                }
                for (_returning_row, _row_mut) in _returned.iter().zip(rows.iter_mut()) {
                    #auto_assigns_for_row
                }
                #audit_bulk_insert_emit
                ::core::result::Result::Ok(())
            }
        }
    } else {
        let cols_all = &fields.bulk_columns_all;
        let pushes_all = &fields.bulk_pushes_all;
        quote! {
            /// Bulk-insert `rows` in a single round-trip. Every row's
            /// fields are written verbatim — there are no `Auto<T>`
            /// fields on this model.
            ///
            /// Empty slice is a no-op.
            ///
            /// # Errors
            /// Returns [`::rustango::sql::ExecError`] for validation,
            /// SQL-writing, or driver failures.
            pub async fn bulk_insert(
                rows: &[Self],
                pool: &::rustango::sql::sqlx::PgPool,
            ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
                Self::bulk_insert_on(rows, pool).await
            }

            /// Like [`Self::bulk_insert`] but accepts any sqlx executor.
            /// See [`Self::save_on`] for tenancy-scoped rationale.
            ///
            /// # Errors
            /// As [`Self::bulk_insert`].
            pub async fn bulk_insert_on<'_c, _E>(
                rows: &[Self],
                _executor: _E,
            ) -> ::core::result::Result<(), ::rustango::sql::ExecError>
            where
                _E: ::rustango::sql::sqlx::Executor<'_c, Database = ::rustango::sql::sqlx::Postgres>,
            {
                if rows.is_empty() {
                    return ::core::result::Result::Ok(());
                }
                let mut _all_rows: ::std::vec::Vec<
                    ::std::vec::Vec<::rustango::core::SqlValue>,
                > = ::std::vec::Vec::with_capacity(rows.len());
                for _row in rows.iter() {
                    let mut _row_vals: ::std::vec::Vec<::rustango::core::SqlValue> =
                        ::std::vec::Vec::new();
                    #( #pushes_all )*
                    _all_rows.push(_row_vals);
                }
                let _query = ::rustango::core::BulkInsertQuery {
                    model: <Self as ::rustango::core::Model>::SCHEMA,
                    columns: ::std::vec![ #( #cols_all ),* ],
                    rows: _all_rows,
                    returning: ::std::vec::Vec::new(),
                    on_conflict: ::core::option::Option::None,
                };
                let _ = ::rustango::sql::bulk_insert_on(_executor, &_query).await?;
                ::core::result::Result::Ok(())
            }
        }
    };

    let pk_value_helper = primary_key.map(|(pk_ident, _)| {
        quote! {
            /// Hidden runtime accessor for the primary-key value as a
            /// [`SqlValue`]. Used by reverse-relation helpers
            /// (`<parent>::<child>_set`) emitted from sibling models'
            /// FK fields. Not part of the public API.
            #[doc(hidden)]
            pub fn __rustango_pk_value(&self) -> ::rustango::core::SqlValue {
                ::core::convert::Into::<::rustango::core::SqlValue>::into(
                    ::core::clone::Clone::clone(&self.#pk_ident)
                )
            }
        }
    });

    let has_pk_value_impl = primary_key.map(|(pk_ident, _)| {
        quote! {
            impl ::rustango::sql::HasPkValue for #struct_name {
                fn __rustango_pk_value_impl(&self) -> ::rustango::core::SqlValue {
                    ::core::convert::Into::<::rustango::core::SqlValue>::into(
                        ::core::clone::Clone::clone(&self.#pk_ident)
                    )
                }
            }
        }
    });

    let fk_pk_access_impl = fk_pk_access_impl_tokens(struct_name, &fields.fk_relations);

    // Slice 17.1 — `AssignAutoPkPool` impl lets `apply_auto_pk_pool`
    // dispatch to the right per-backend body without the macro emitting
    // any `#[cfg(feature = …)]` arm into consumer code. Always emitted
    // so audited models with non-Auto PKs (which still go through
    // `insert_one_with_audit_pool` → `apply_auto_pk_pool`) link.
    let assign_auto_pk_pool_impl = {
        let auto_assigns = &fields.auto_assigns;
        // SQLite ≥ 3.35 supports the same RETURNING shape as Postgres,
        // so the body is structurally identical to `auto_assigns` —
        // only the helper name swaps from `try_get_returning` to
        // `try_get_returning_sqlite` so the closure typechecks against
        // a `SqliteRow` instead of a `PgRow`.
        let auto_assigns_sqlite: Vec<TokenStream2> = fields
            .auto_field_idents
            .iter()
            .map(|(ident, column)| {
                quote! {
                    self.#ident = ::rustango::sql::try_get_returning_sqlite(
                        _returning_row, #column
                    )?;
                }
            })
            .collect();
        let mysql_body = if let Some(first) = fields.first_auto_ident.as_ref() {
            // The MySQL `LAST_INSERT_ID()` is always i64. Route through
            // `MysqlAutoIdSet` so Auto<i32> narrows safely and
            // Auto<Uuid>/etc. fail to link against MySQL (intended —
            // those models can't use AUTO_INCREMENT). The trait is only
            // touched on the MySQL arm at runtime, so PG-only consumers
            // never see the bound failure.
            //
            // Pre-v0.20: models with multiple `Auto<T>` fields (e.g.
            // Auto<i64> PK + auto_now_add timestamp) errored hard at
            // runtime with "multi-column RETURNING". MySQL has no
            // multi-column RETURNING semantic and a follow-up SELECT
            // would need cross-trait plumbing. Pragmatic shape: succeed
            // with the FIRST Auto field populated from LAST_INSERT_ID();
            // any other Auto fields stay `Auto::Unset`. Callers that
            // need the DB-defaulted timestamp / UUID can re-fetch the
            // row by PK after `save_pool`. Fixes the cookbook chapter
            // 12 dialect divergence.
            let value_ty = fields
                .first_auto_value_ty
                .as_ref()
                .expect("first_auto_value_ty set whenever first_auto_ident is");
            quote! {
                let _converted = <#value_ty as ::rustango::sql::MysqlAutoIdSet>
                    ::rustango_from_mysql_auto_id(_id)?;
                self.#first = ::rustango::sql::Auto::Set(_converted);
                ::core::result::Result::Ok(())
            }
        } else {
            quote! {
                let _ = _id;
                ::core::result::Result::Ok(())
            }
        };
        quote! {
            impl ::rustango::sql::AssignAutoPkPool for #struct_name {
                fn __rustango_assign_from_pg_row(
                    &mut self,
                    _returning_row: &::rustango::sql::PgReturningRow,
                ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
                    #( #auto_assigns )*
                    ::core::result::Result::Ok(())
                }
                fn __rustango_assign_from_mysql_id(
                    &mut self,
                    _id: i64,
                ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
                    #mysql_body
                }
                fn __rustango_assign_from_sqlite_row(
                    &mut self,
                    _returning_row: &::rustango::sql::SqliteReturningRow,
                ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
                    #( #auto_assigns_sqlite )*
                    ::core::result::Result::Ok(())
                }
            }
        }
    };

    let from_aliased_row_inits = &fields.from_aliased_row_inits;
    let aliased_row_helper = quote! {
        /// Decode a row's aliased target columns (produced by
        /// `select_related`'s LEFT JOIN) into a fresh instance of
        /// this model. Reads each column via
        /// `format!("{prefix}__{col}")`, matching the alias the
        /// SELECT writer emitted. Slice 9.0d.
        #[doc(hidden)]
        pub fn __rustango_from_aliased_row(
            row: &::rustango::sql::sqlx::postgres::PgRow,
            prefix: &str,
        ) -> ::core::result::Result<Self, ::rustango::sql::sqlx::Error> {
            ::core::result::Result::Ok(Self {
                #( #from_aliased_row_inits ),*
            })
        }
    };
    // v0.23.0-batch8 — MySQL counterpart, gated through the
    // cfg-aware macro_rules so PG-only builds expand to nothing.
    let aliased_row_helper_my = quote! {
        ::rustango::__impl_my_aliased_row_decoder!(#struct_name, |row, prefix| {
            #( #from_aliased_row_inits ),*
        });
    };

    // v0.27 Phase 3 — SQLite counterpart, same hygiene-aware closure
    // pattern + cfg gate on the `sqlite` feature.
    let aliased_row_helper_sqlite = quote! {
        ::rustango::__impl_sqlite_aliased_row_decoder!(#struct_name, |row, prefix| {
            #( #from_aliased_row_inits ),*
        });
    };

    let load_related_impl = load_related_impl_tokens(struct_name, &fields.fk_relations);
    let load_related_impl_my = load_related_impl_my_tokens(struct_name, &fields.fk_relations);
    let load_related_impl_sqlite =
        load_related_impl_sqlite_tokens(struct_name, &fields.fk_relations);

    quote! {
        impl #struct_name {
            /// Start a new `QuerySet` over this model.
            #[must_use]
            pub fn objects() -> ::rustango::query::QuerySet<#struct_name> {
                ::rustango::query::QuerySet::new()
            }

            #insert_method

            #bulk_insert_method

            #save_method

            #pk_methods

            #pk_value_helper

            #aliased_row_helper

            #column_consts
        }

        #aliased_row_helper_my

        #aliased_row_helper_sqlite

        #load_related_impl

        #load_related_impl_my

        #load_related_impl_sqlite

        #has_pk_value_impl

        #fk_pk_access_impl

        #assign_auto_pk_pool_impl
    }
}

/// Per-row Auto-field assigns for `bulk_insert` — equivalent to
/// `auto_assigns` but reading from `_returning_row` and writing to
/// `_row_mut` instead of `self`.
fn bulk_auto_assigns_for_row(fields: &CollectedFields) -> TokenStream2 {
    let lines = fields.auto_field_idents.iter().map(|(ident, column)| {
        let col_lit = column.as_str();
        quote! {
            _row_mut.#ident = ::rustango::sql::sqlx::Row::try_get(
                _returning_row,
                #col_lit,
            )?;
        }
    });
    quote! { #( #lines )* }
}

/// Emit `pub const id: …Id = …Id;` per field, inside the inherent impl.
fn column_const_tokens(module_ident: &syn::Ident, entries: &[ColumnEntry]) -> TokenStream2 {
    let lines = entries.iter().map(|e| {
        let ident = &e.ident;
        let col_ty = column_type_ident(ident);
        quote! {
            #[allow(non_upper_case_globals)]
            pub const #ident: #module_ident::#col_ty = #module_ident::#col_ty;
        }
    });
    quote! { #(#lines)* }
}

/// Emit a hidden per-model module carrying one zero-sized type per field,
/// each with a `Column` impl pointing back at the model.
fn column_module_tokens(
    module_ident: &syn::Ident,
    struct_name: &syn::Ident,
    entries: &[ColumnEntry],
) -> TokenStream2 {
    let items = entries.iter().map(|e| {
        let col_ty = column_type_ident(&e.ident);
        let value_ty = &e.value_ty;
        let name = &e.name;
        let column = &e.column;
        let field_type_tokens = &e.field_type_tokens;
        quote! {
            #[derive(::core::clone::Clone, ::core::marker::Copy)]
            pub struct #col_ty;

            impl ::rustango::core::Column for #col_ty {
                type Model = super::#struct_name;
                type Value = #value_ty;
                const NAME: &'static str = #name;
                const COLUMN: &'static str = #column;
                const FIELD_TYPE: ::rustango::core::FieldType = #field_type_tokens;
            }
        }
    });
    quote! {
        #[doc(hidden)]
        #[allow(non_camel_case_types, non_snake_case)]
        pub mod #module_ident {
            // Re-import the parent scope so field types referencing
            // sibling models (e.g. `ForeignKey<Author>`) resolve
            // inside this submodule. Without this we'd hit
            // `proc_macro_derive_resolution_fallback` warnings.
            #[allow(unused_imports)]
            use super::*;
            #(#items)*
        }
    }
}

fn column_type_ident(field_ident: &syn::Ident) -> syn::Ident {
    syn::Ident::new(&format!("{field_ident}_col"), field_ident.span())
}

fn column_module_ident(struct_name: &syn::Ident) -> syn::Ident {
    syn::Ident::new(
        &format!("__rustango_cols_{struct_name}"),
        struct_name.span(),
    )
}

fn from_row_impl_tokens(struct_name: &syn::Ident, from_row_inits: &[TokenStream2]) -> TokenStream2 {
    // The Postgres impl is always emitted — every rustango build pulls in
    // sqlx-postgres via the default `postgres` feature. The MySQL impl is
    // routed through `::rustango::__impl_my_from_row!`, a cfg-gated
    // macro_rules whose body collapses to nothing when rustango is built
    // without the `mysql` feature. No user-facing feature shim required.
    //
    // The macro_rules pattern expects `[ field: expr, … ]` — we need to
    // re-shape `from_row_inits` (each token is `field: row.try_get(...)`)
    // back into a comma-separated list inside square brackets. Since each
    // entry is already in `field: expr` shape, the existing tokens slot in.
    quote! {
        impl<'r> ::rustango::sql::sqlx::FromRow<'r, ::rustango::sql::sqlx::postgres::PgRow>
            for #struct_name
        {
            fn from_row(
                row: &'r ::rustango::sql::sqlx::postgres::PgRow,
            ) -> ::core::result::Result<Self, ::rustango::sql::sqlx::Error> {
                ::core::result::Result::Ok(Self {
                    #( #from_row_inits ),*
                })
            }
        }

        ::rustango::__impl_my_from_row!(#struct_name, |row| {
            #( #from_row_inits ),*
        });

        ::rustango::__impl_sqlite_from_row!(#struct_name, |row| {
            #( #from_row_inits ),*
        });
    }
}

struct ContainerAttrs {
    table: Option<String>,
    display: Option<(String, proc_macro2::Span)>,
    /// Explicit Django-style app label from `#[rustango(app = "blog")]`.
    /// Recorded on the emitted `ModelSchema.app_label`. When unset,
    /// `ModelEntry::resolved_app_label()` infers from `module_path!()`
    /// at runtime — this attribute is the override for cases where
    /// the inference is wrong (e.g. a model that conceptually belongs
    /// to one app but is physically in another module).
    app: Option<String>,
    /// Django ModelAdmin-shape per-model knobs from
    /// `#[rustango(admin(...))]`. `None` when the user didn't write the
    /// attribute — the emitted `ModelSchema.admin` becomes `None` and
    /// admin code falls back to `AdminConfig::DEFAULT`.
    admin: Option<AdminAttrs>,
    /// Per-model audit configuration from `#[rustango(audit(...))]`.
    /// `None` when the model isn't audited — write paths emit no
    /// audit entries. When present, single-row writes capture
    /// before/after for the listed fields and bulk writes batch
    /// snapshots into one INSERT into `rustango_audit_log`.
    audit: Option<AuditAttrs>,
    /// `true` when `#[rustango(permissions)]` is present. Signals that
    /// `auto_create_permissions` should seed the four CRUD codenames for
    /// this model.
    permissions: bool,
    /// Many-to-many relations declared via
    /// `#[rustango(m2m(name = "tags", to = "app_tags", through = "post_tags",
    ///                 src = "post_id", dst = "tag_id"))]`.
    m2m: Vec<M2MAttr>,
    /// Composite indexes declared via
    /// `#[rustango(index("col1, col2"))]` or
    /// `#[rustango(index("col1, col2", unique, name = "my_idx"))]`.
    /// Single-column indexes from `#[rustango(index)]` on fields are
    /// accumulated here during field collection.
    indexes: Vec<IndexAttr>,
    /// Table-level CHECK constraints declared via
    /// `#[rustango(check(name = "…", expr = "…"))]`.
    checks: Vec<CheckAttr>,
    /// Composite (multi-column) FKs declared via
    /// `#[rustango(fk_composite(name = "…", to = "…", on = (…), from = (…)))]`.
    /// Sub-slice F.2 of the v0.15.0 ContentType plan.
    composite_fks: Vec<CompositeFkAttr>,
    /// Generic ("any model") FKs declared via
    /// `#[rustango(generic_fk(name = "…", ct_column = "…", pk_column = "…"))]`.
    /// Sub-slice F.4 of the v0.15.0 ContentType plan.
    generic_fks: Vec<GenericFkAttr>,
    /// Where this model lives in a tenancy deployment, declared via
    /// `#[rustango(scope = "registry")]` or `#[rustango(scope = "tenant")]`.
    /// Defaults to `"tenant"` when unset; `makemigrations` uses this
    /// to partition diff output between registry-scoped and
    /// tenant-scoped migration files.
    scope: Option<String>,
}

/// Parsed form of one index declaration (field-level or container-level).
struct IndexAttr {
    /// Index name; auto-derived when `None` at parse time.
    name: Option<String>,
    /// Column names in the index.
    columns: Vec<String>,
    /// `true` for `CREATE UNIQUE INDEX`.
    unique: bool,
}

/// Parsed form of one `#[rustango(check(name = "…", expr = "…"))]` declaration.
struct CheckAttr {
    name: String,
    expr: String,
}

/// Parsed form of one `#[rustango(fk_composite(name = "audit_target",
/// to = "rustango_audit_log", on = ("entity_table", "entity_pk"),
/// from = ("table_name", "row_pk")))]` declaration. Sub-slice F.2 of
/// the v0.15.0 ContentType plan — multi-column foreign keys live on
/// the model, not the field.
struct CompositeFkAttr {
    /// Logical relation name (free-form Rust identifier).
    name: String,
    /// SQL table name of the target.
    to: String,
    /// Source-side column names, in declaration order.
    from: Vec<String>,
    /// Target-side column names, same length / order as `from`.
    on: Vec<String>,
}

/// Parsed form of one `#[rustango(generic_fk(name = "target",
/// ct_column = "content_type_id", pk_column = "object_pk"))]`
/// declaration. Sub-slice F.4 of the v0.15.0 ContentType plan —
/// generic ("any model") FKs live on the model, not the field.
struct GenericFkAttr {
    /// Logical relation name (free-form Rust identifier).
    name: String,
    /// Source-side column carrying the `content_type_id` value.
    ct_column: String,
    /// Source-side column carrying the target row's primary key.
    pk_column: String,
}

/// Parsed form of one `#[rustango(m2m(...))]` declaration.
struct M2MAttr {
    /// Accessor suffix: `tags` → generates `tags_m2m()`.
    name: String,
    /// Target table (e.g. `"app_tags"`).
    to: String,
    /// Junction table (e.g. `"post_tags"`).
    through: String,
    /// Source FK column in the junction table (e.g. `"post_id"`).
    src: String,
    /// Destination FK column in the junction table (e.g. `"tag_id"`).
    dst: String,
}

/// Parsed shape of `#[rustango(audit(track = "name, body", source =
/// "user"))]`. `track` is a comma-separated list of field names whose
/// before/after values land in the JSONB `changes` column. `source`
/// is informational only — it pins a default source when the model
/// is written outside any `audit::with_source(...)` scope (rare).
#[derive(Default)]
struct AuditAttrs {
    /// Field names to capture in the `changes` JSONB. Validated
    /// against declared scalar fields at compile time. Empty means
    /// "track every scalar field" — Django's audit-everything default.
    track: Option<(Vec<String>, proc_macro2::Span)>,
}

/// Parsed shape of `#[rustango(admin(list_display = "…", search_fields =
/// "…", list_per_page = N, ordering = "…"))]`. Field-name lists are
/// comma-separated strings; we validate each ident against the model's
/// declared fields at compile time.
#[derive(Default)]
struct AdminAttrs {
    list_display: Option<(Vec<String>, proc_macro2::Span)>,
    search_fields: Option<(Vec<String>, proc_macro2::Span)>,
    list_per_page: Option<usize>,
    ordering: Option<(Vec<(String, bool)>, proc_macro2::Span)>,
    readonly_fields: Option<(Vec<String>, proc_macro2::Span)>,
    list_filter: Option<(Vec<String>, proc_macro2::Span)>,
    /// Bulk action names. No field-validation against model fields —
    /// these are action handlers, not column references.
    actions: Option<(Vec<String>, proc_macro2::Span)>,
    /// Form fieldsets — `Vec<(title, [field_names])>`. Pipe-separated
    /// sections, comma-separated fields per section, optional
    /// `Title:` prefix. Empty title omits the `<legend>`.
    fieldsets: Option<(Vec<(String, Vec<String>)>, proc_macro2::Span)>,
}

fn parse_container_attrs(input: &DeriveInput) -> syn::Result<ContainerAttrs> {
    let mut out = ContainerAttrs {
        table: None,
        display: None,
        app: None,
        admin: None,
        audit: None,
        // Default `permissions = true` so every `#[derive(Model)]`
        // gets the four CRUD codenames seeded by `auto_create_permissions`
        // and is visible to non-superusers in the tenant admin without
        // manual per-model annotation. Models that intentionally don't
        // want permission rows (registry-internal types, framework
        // tables operators shouldn't manage directly) opt out via
        // `#[rustango(permissions = false)]`. v0.27.2 — fixes the
        // out-of-the-box admin invisibility regression (#62).
        permissions: true,
        m2m: Vec::new(),
        indexes: Vec::new(),
        checks: Vec::new(),
        composite_fks: Vec::new(),
        generic_fks: Vec::new(),
        scope: None,
    };
    for attr in &input.attrs {
        if !attr.path().is_ident("rustango") {
            continue;
        }
        attr.parse_nested_meta(|meta| {
            if meta.path.is_ident("table") {
                let s: LitStr = meta.value()?.parse()?;
                let name = s.value();
                // v0.27.3 (#65) — macro-time guard against table names
                // that compile but break SQL downstream. Hyphens are
                // the common footgun: PostgreSQL accepts a quoted
                // `"intermediate-region"` in CREATE TABLE, but the
                // FK / index name derivation in `migrate::ddl`
                // emits `intermediate-region_field_fkey` unquoted,
                // which then fails the SQL parser. Same shape rule
                // as Postgres regular identifiers so the safe path
                // is the only path.
                validate_table_name(&name, s.span())?;
                out.table = Some(name);
                return Ok(());
            }
            if meta.path.is_ident("display") {
                let s: LitStr = meta.value()?.parse()?;
                out.display = Some((s.value(), s.span()));
                return Ok(());
            }
            if meta.path.is_ident("app") {
                let s: LitStr = meta.value()?.parse()?;
                out.app = Some(s.value());
                return Ok(());
            }
            if meta.path.is_ident("scope") {
                let s: LitStr = meta.value()?.parse()?;
                let val = s.value();
                if !matches!(val.to_ascii_lowercase().as_str(), "registry" | "tenant") {
                    return Err(meta.error(format!(
                        "`scope` must be \"registry\" or \"tenant\", got {val:?}"
                    )));
                }
                out.scope = Some(val);
                return Ok(());
            }
            if meta.path.is_ident("admin") {
                let mut admin = AdminAttrs::default();
                meta.parse_nested_meta(|inner| {
                    if inner.path.is_ident("list_display") {
                        let s: LitStr = inner.value()?.parse()?;
                        admin.list_display =
                            Some((split_field_list(&s.value()), s.span()));
                        return Ok(());
                    }
                    if inner.path.is_ident("search_fields") {
                        let s: LitStr = inner.value()?.parse()?;
                        admin.search_fields =
                            Some((split_field_list(&s.value()), s.span()));
                        return Ok(());
                    }
                    if inner.path.is_ident("readonly_fields") {
                        let s: LitStr = inner.value()?.parse()?;
                        admin.readonly_fields =
                            Some((split_field_list(&s.value()), s.span()));
                        return Ok(());
                    }
                    if inner.path.is_ident("list_per_page") {
                        let lit: syn::LitInt = inner.value()?.parse()?;
                        admin.list_per_page = Some(lit.base10_parse::<usize>()?);
                        return Ok(());
                    }
                    if inner.path.is_ident("ordering") {
                        let s: LitStr = inner.value()?.parse()?;
                        admin.ordering = Some((
                            parse_ordering_list(&s.value()),
                            s.span(),
                        ));
                        return Ok(());
                    }
                    if inner.path.is_ident("list_filter") {
                        let s: LitStr = inner.value()?.parse()?;
                        admin.list_filter =
                            Some((split_field_list(&s.value()), s.span()));
                        return Ok(());
                    }
                    if inner.path.is_ident("actions") {
                        let s: LitStr = inner.value()?.parse()?;
                        admin.actions =
                            Some((split_field_list(&s.value()), s.span()));
                        return Ok(());
                    }
                    if inner.path.is_ident("fieldsets") {
                        let s: LitStr = inner.value()?.parse()?;
                        admin.fieldsets =
                            Some((parse_fieldset_list(&s.value()), s.span()));
                        return Ok(());
                    }
                    Err(inner.error(
                        "unknown admin attribute (supported: \
                         `list_display`, `search_fields`, `readonly_fields`, \
                         `list_filter`, `list_per_page`, `ordering`, `actions`, \
                         `fieldsets`)",
                    ))
                })?;
                out.admin = Some(admin);
                return Ok(());
            }
            if meta.path.is_ident("audit") {
                let mut audit = AuditAttrs::default();
                meta.parse_nested_meta(|inner| {
                    if inner.path.is_ident("track") {
                        let s: LitStr = inner.value()?.parse()?;
                        audit.track =
                            Some((split_field_list(&s.value()), s.span()));
                        return Ok(());
                    }
                    Err(inner.error(
                        "unknown audit attribute (supported: `track`)",
                    ))
                })?;
                out.audit = Some(audit);
                return Ok(());
            }
            if meta.path.is_ident("permissions") {
                // Two forms accepted:
                //   #[rustango(permissions)]          — flag form, true
                //   #[rustango(permissions = false)]  — explicit opt-out
                //   #[rustango(permissions = true)]   — explicit opt-in
                if let Ok(v) = meta.value() {
                    let lit: syn::LitBool = v.parse()?;
                    out.permissions = lit.value;
                } else {
                    out.permissions = true;
                }
                return Ok(());
            }
            if meta.path.is_ident("unique_together") {
                // Django-shape composite UNIQUE index. Two syntaxes:
                //
                //   #[rustango(unique_together = "org_id, user_id")]                       — auto-derived name
                //   #[rustango(unique_together(columns = "org_id, user_id", name = "x"))]  — explicit name
                //
                // Both produce `CREATE UNIQUE INDEX <name> ON <table>
                // (col1, col2)`, where <name> defaults to
                // `<table>_<col1>_<col2>_uq` when not supplied.
                let (columns, name) = parse_together_attr(&meta, "unique_together")?;
                out.indexes.push(IndexAttr { name, columns, unique: true });
                return Ok(());
            }
            if meta.path.is_ident("index_together") {
                // Django-shape composite (non-unique) index. Two syntaxes
                // mirroring `unique_together`.
                //
                //   #[rustango(index_together = "created_at, status")]
                //   #[rustango(index_together(columns = "created_at, status", name = "x"))]
                let (columns, name) = parse_together_attr(&meta, "index_together")?;
                out.indexes.push(IndexAttr { name, columns, unique: false });
                return Ok(());
            }
            if meta.path.is_ident("index") {
                // Container-level composite index — legacy entry that
                // was advertised with a trailing `, unique, name = ...`
                // flag block which doesn't actually compose under
                // `parse_nested_meta`. Prefer `unique_together` /
                // `index_together` (above) for new code. The bare
                // `index = "..."` form is kept for back-compat: it
                // emits a non-unique composite index.
                let cols_lit: LitStr = meta.value()?.parse()?;
                let columns = split_field_list(&cols_lit.value());
                out.indexes.push(IndexAttr { name: None, columns, unique: false });
                return Ok(());
            }
            if meta.path.is_ident("check") {
                // #[rustango(check(name = "…", expr = "…"))]
                let mut name: Option<String> = None;
                let mut expr: Option<String> = None;
                meta.parse_nested_meta(|inner| {
                    if inner.path.is_ident("name") {
                        let s: LitStr = inner.value()?.parse()?;
                        name = Some(s.value());
                        return Ok(());
                    }
                    if inner.path.is_ident("expr") {
                        let s: LitStr = inner.value()?.parse()?;
                        expr = Some(s.value());
                        return Ok(());
                    }
                    Err(inner.error("unknown check attribute (supported: `name`, `expr`)"))
                })?;
                let name = name.ok_or_else(|| meta.error("check requires `name = \"...\"`"))?;
                let expr = expr.ok_or_else(|| meta.error("check requires `expr = \"...\"`"))?;
                out.checks.push(CheckAttr { name, expr });
                return Ok(());
            }
            if meta.path.is_ident("generic_fk") {
                let mut gfk = GenericFkAttr {
                    name: String::new(),
                    ct_column: String::new(),
                    pk_column: String::new(),
                };
                meta.parse_nested_meta(|inner| {
                    if inner.path.is_ident("name") {
                        let s: LitStr = inner.value()?.parse()?;
                        gfk.name = s.value();
                        return Ok(());
                    }
                    if inner.path.is_ident("ct_column") {
                        let s: LitStr = inner.value()?.parse()?;
                        gfk.ct_column = s.value();
                        return Ok(());
                    }
                    if inner.path.is_ident("pk_column") {
                        let s: LitStr = inner.value()?.parse()?;
                        gfk.pk_column = s.value();
                        return Ok(());
                    }
                    Err(inner.error(
                        "unknown generic_fk attribute (supported: `name`, `ct_column`, `pk_column`)",
                    ))
                })?;
                if gfk.name.is_empty() {
                    return Err(meta.error("generic_fk requires `name = \"...\"`"));
                }
                if gfk.ct_column.is_empty() {
                    return Err(meta.error("generic_fk requires `ct_column = \"...\"`"));
                }
                if gfk.pk_column.is_empty() {
                    return Err(meta.error("generic_fk requires `pk_column = \"...\"`"));
                }
                out.generic_fks.push(gfk);
                return Ok(());
            }
            if meta.path.is_ident("fk_composite") {
                let mut fk = CompositeFkAttr {
                    name: String::new(),
                    to: String::new(),
                    from: Vec::new(),
                    on: Vec::new(),
                };
                meta.parse_nested_meta(|inner| {
                    if inner.path.is_ident("name") {
                        let s: LitStr = inner.value()?.parse()?;
                        fk.name = s.value();
                        return Ok(());
                    }
                    if inner.path.is_ident("to") {
                        let s: LitStr = inner.value()?.parse()?;
                        fk.to = s.value();
                        return Ok(());
                    }
                    // `on = ("col1", "col2", ...)` — parse a parenthesised
                    // comma-list of string literals.
                    if inner.path.is_ident("on") || inner.path.is_ident("from") {
                        let value = inner.value()?;
                        let content;
                        syn::parenthesized!(content in value);
                        let lits: syn::punctuated::Punctuated<syn::LitStr, syn::Token![,]> =
                            content.parse_terminated(
                                |p| p.parse::<syn::LitStr>(),
                                syn::Token![,],
                            )?;
                        let cols: Vec<String> = lits.iter().map(syn::LitStr::value).collect();
                        if inner.path.is_ident("on") {
                            fk.on = cols;
                        } else {
                            fk.from = cols;
                        }
                        return Ok(());
                    }
                    Err(inner.error(
                        "unknown fk_composite attribute (supported: `name`, `to`, `on`, `from`)",
                    ))
                })?;
                if fk.name.is_empty() {
                    return Err(meta.error("fk_composite requires `name = \"...\"`"));
                }
                if fk.to.is_empty() {
                    return Err(meta.error("fk_composite requires `to = \"...\"`"));
                }
                if fk.from.is_empty() || fk.on.is_empty() {
                    return Err(meta.error(
                        "fk_composite requires non-empty `from = (...)` and `on = (...)` tuples",
                    ));
                }
                if fk.from.len() != fk.on.len() {
                    return Err(meta.error(format!(
                        "fk_composite `from` ({} cols) and `on` ({} cols) must be the same length",
                        fk.from.len(),
                        fk.on.len(),
                    )));
                }
                out.composite_fks.push(fk);
                return Ok(());
            }
            if meta.path.is_ident("m2m") {
                let mut m2m = M2MAttr {
                    name: String::new(),
                    to: String::new(),
                    through: String::new(),
                    src: String::new(),
                    dst: String::new(),
                };
                meta.parse_nested_meta(|inner| {
                    if inner.path.is_ident("name") {
                        let s: LitStr = inner.value()?.parse()?;
                        m2m.name = s.value();
                        return Ok(());
                    }
                    if inner.path.is_ident("to") {
                        let s: LitStr = inner.value()?.parse()?;
                        m2m.to = s.value();
                        return Ok(());
                    }
                    if inner.path.is_ident("through") {
                        let s: LitStr = inner.value()?.parse()?;
                        m2m.through = s.value();
                        return Ok(());
                    }
                    if inner.path.is_ident("src") {
                        let s: LitStr = inner.value()?.parse()?;
                        m2m.src = s.value();
                        return Ok(());
                    }
                    if inner.path.is_ident("dst") {
                        let s: LitStr = inner.value()?.parse()?;
                        m2m.dst = s.value();
                        return Ok(());
                    }
                    Err(inner.error("unknown m2m attribute (supported: `name`, `to`, `through`, `src`, `dst`)"))
                })?;
                if m2m.name.is_empty() {
                    return Err(meta.error("m2m requires `name = \"...\"`"));
                }
                if m2m.to.is_empty() {
                    return Err(meta.error("m2m requires `to = \"...\"`"));
                }
                if m2m.through.is_empty() {
                    return Err(meta.error("m2m requires `through = \"...\"`"));
                }
                if m2m.src.is_empty() {
                    return Err(meta.error("m2m requires `src = \"...\"`"));
                }
                if m2m.dst.is_empty() {
                    return Err(meta.error("m2m requires `dst = \"...\"`"));
                }
                out.m2m.push(m2m);
                return Ok(());
            }
            Err(meta.error("unknown rustango container attribute"))
        })?;
    }
    Ok(out)
}

/// Split a comma-separated field-name list (e.g. `"name, office"`) into
/// owned field names, trimming whitespace and skipping empty entries.
/// Field-name validation against the model is done by the caller.
fn split_field_list(raw: &str) -> Vec<String> {
    raw.split(',')
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_owned)
        .collect()
}

/// Shared parser for `unique_together` and `index_together` container
/// attrs. Accepts both shapes:
///
///   * `attr = "col1, col2"`              — auto-derived index name.
///   * `attr(columns = "col1, col2", name = "...")` — explicit name.
///
/// Returns `(columns, name)`.
fn parse_together_attr(
    meta: &syn::meta::ParseNestedMeta<'_>,
    attr: &str,
) -> syn::Result<(Vec<String>, Option<String>)> {
    // Disambiguate by whether the next token is `=` (key-value) or
    // `(` (parenthesized).
    if meta.input.peek(syn::Token![=]) {
        let cols_lit: LitStr = meta.value()?.parse()?;
        let columns = split_field_list(&cols_lit.value());
        check_together_columns(meta, attr, &columns)?;
        return Ok((columns, None));
    }
    let mut columns: Option<Vec<String>> = None;
    let mut name: Option<String> = None;
    meta.parse_nested_meta(|inner| {
        if inner.path.is_ident("columns") {
            let s: LitStr = inner.value()?.parse()?;
            columns = Some(split_field_list(&s.value()));
            return Ok(());
        }
        if inner.path.is_ident("name") {
            let s: LitStr = inner.value()?.parse()?;
            name = Some(s.value());
            return Ok(());
        }
        Err(inner.error("unknown sub-attribute (supported: `columns`, `name`)"))
    })?;
    let columns = columns.ok_or_else(|| {
        meta.error(format!(
            "{attr}(...) requires a `columns = \"col1, col2\"` argument",
        ))
    })?;
    check_together_columns(meta, attr, &columns)?;
    Ok((columns, name))
}

fn check_together_columns(
    meta: &syn::meta::ParseNestedMeta<'_>,
    attr: &str,
    columns: &[String],
) -> syn::Result<()> {
    if columns.len() < 2 {
        let single = if attr == "unique_together" {
            "#[rustango(unique)] on the field"
        } else {
            "#[rustango(index)] on the field"
        };
        return Err(meta.error(format!(
            "{attr} expects two or more columns; for a single-column equivalent use {single}",
        )));
    }
    Ok(())
}

/// Parse the fieldsets DSL: pipe-separated sections, optional
/// `"Title:"` prefix on each, comma-separated field names after.
/// Examples:
/// * `"name, office"` → one untitled section with two fields
/// * `"Identity: name, office | Metadata: created_at"` → two titled
///   sections
///
/// Returns `(title, fields)` pairs. Title is `""` when no prefix.
fn parse_fieldset_list(raw: &str) -> Vec<(String, Vec<String>)> {
    raw.split('|')
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(|section| {
            // Split off an optional `Title:` prefix (first colon).
            let (title, rest) = match section.split_once(':') {
                Some((title, rest)) if !title.contains(',') => (title.trim().to_owned(), rest),
                _ => (String::new(), section),
            };
            let fields = split_field_list(rest);
            (title, fields)
        })
        .collect()
}

/// Parse Django-shape ordering — `"name"` is ASC, `"-name"` is DESC.
/// Returns `(field_name, desc)` pairs in the same order as the input.
fn parse_ordering_list(raw: &str) -> Vec<(String, bool)> {
    raw.split(',')
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(|spec| {
            spec.strip_prefix('-')
                .map_or((spec.to_owned(), false), |rest| {
                    (rest.trim().to_owned(), true)
                })
        })
        .collect()
}

struct FieldAttrs {
    column: Option<String>,
    primary_key: bool,
    fk: Option<String>,
    o2o: Option<String>,
    on: Option<String>,
    max_length: Option<u32>,
    min: Option<i64>,
    max: Option<i64>,
    default: Option<String>,
    /// `#[rustango(auto_uuid)]` — UUID PK generated by Postgres
    /// `gen_random_uuid()`. Implies `auto + primary_key + default =
    /// "gen_random_uuid()"`. The Rust field type must be
    /// `uuid::Uuid` (or `Auto<Uuid>`); the column is excluded from
    /// INSERTs so the DB DEFAULT fires.
    auto_uuid: bool,
    /// `#[rustango(auto_now_add)]` — `created_at`-shape column.
    /// Server-set on insert, immutable from app code afterwards.
    /// Implies `auto + default = "now()"`. Field type must be
    /// `DateTime<Utc>`.
    auto_now_add: bool,
    /// `#[rustango(auto_now)]` — `updated_at`-shape column. Set on
    /// every insert AND every update. Implies `auto + default =
    /// "now()"`; the macro additionally rewrites `update_on` /
    /// `save_on` to bind `chrono::Utc::now()` instead of the user's
    /// field value.
    auto_now: bool,
    /// `#[rustango(soft_delete)]` — `deleted_at`-shape column. Type
    /// must be `Option<DateTime<Utc>>`. Triggers macro emission of
    /// `soft_delete_on(executor)` and `restore_on(executor)`
    /// methods on the model.
    soft_delete: bool,
    /// `#[rustango(unique)]` — adds a `UNIQUE` constraint inline on
    /// the column in the generated DDL.
    unique: bool,
    /// `#[rustango(index)]` or `#[rustango(index(name = "…", unique))]` —
    /// generates a `CREATE INDEX` for this column. `unique` here means
    /// `CREATE UNIQUE INDEX` (distinct from the `unique` constraint above).
    index: bool,
    index_unique: bool,
    index_name: Option<String>,
    /// `#[rustango(generated_as = "EXPR")]` — emit `GENERATED ALWAYS
    /// AS (EXPR) STORED` in the column DDL. Read-only from app code:
    /// the macro skips this column from every INSERT and UPDATE
    /// path, so the database always recomputes the value from
    /// `EXPR`. Backlog item #35.
    generated_as: Option<String>,
}

fn parse_field_attrs(field: &syn::Field) -> syn::Result<FieldAttrs> {
    let mut out = FieldAttrs {
        column: None,
        primary_key: false,
        fk: None,
        o2o: None,
        on: None,
        max_length: None,
        min: None,
        max: None,
        default: None,
        auto_uuid: false,
        auto_now_add: false,
        auto_now: false,
        soft_delete: false,
        unique: false,
        index: false,
        index_unique: false,
        index_name: None,
        generated_as: None,
    };
    for attr in &field.attrs {
        if !attr.path().is_ident("rustango") {
            continue;
        }
        attr.parse_nested_meta(|meta| {
            if meta.path.is_ident("column") {
                let s: LitStr = meta.value()?.parse()?;
                out.column = Some(s.value());
                return Ok(());
            }
            if meta.path.is_ident("primary_key") {
                out.primary_key = true;
                return Ok(());
            }
            if meta.path.is_ident("fk") {
                let s: LitStr = meta.value()?.parse()?;
                out.fk = Some(s.value());
                return Ok(());
            }
            if meta.path.is_ident("o2o") {
                let s: LitStr = meta.value()?.parse()?;
                out.o2o = Some(s.value());
                return Ok(());
            }
            if meta.path.is_ident("on") {
                let s: LitStr = meta.value()?.parse()?;
                out.on = Some(s.value());
                return Ok(());
            }
            if meta.path.is_ident("max_length") {
                let lit: syn::LitInt = meta.value()?.parse()?;
                out.max_length = Some(lit.base10_parse::<u32>()?);
                return Ok(());
            }
            if meta.path.is_ident("min") {
                out.min = Some(parse_signed_i64(&meta)?);
                return Ok(());
            }
            if meta.path.is_ident("max") {
                out.max = Some(parse_signed_i64(&meta)?);
                return Ok(());
            }
            if meta.path.is_ident("default") {
                let s: LitStr = meta.value()?.parse()?;
                out.default = Some(s.value());
                return Ok(());
            }
            if meta.path.is_ident("generated_as") {
                let s: LitStr = meta.value()?.parse()?;
                out.generated_as = Some(s.value());
                return Ok(());
            }
            if meta.path.is_ident("auto_uuid") {
                out.auto_uuid = true;
                // Implied: PK + auto + DEFAULT gen_random_uuid().
                // Each is also explicitly settable; the explicit
                // value wins if conflicting.
                out.primary_key = true;
                if out.default.is_none() {
                    out.default = Some("gen_random_uuid()".into());
                }
                return Ok(());
            }
            if meta.path.is_ident("auto_now_add") {
                out.auto_now_add = true;
                if out.default.is_none() {
                    out.default = Some("now()".into());
                }
                return Ok(());
            }
            if meta.path.is_ident("auto_now") {
                out.auto_now = true;
                if out.default.is_none() {
                    out.default = Some("now()".into());
                }
                return Ok(());
            }
            if meta.path.is_ident("soft_delete") {
                out.soft_delete = true;
                return Ok(());
            }
            if meta.path.is_ident("unique") {
                out.unique = true;
                return Ok(());
            }
            if meta.path.is_ident("index") {
                out.index = true;
                // Optional sub-attrs: #[rustango(index(unique, name = "…"))]
                if meta.input.peek(syn::token::Paren) {
                    meta.parse_nested_meta(|inner| {
                        if inner.path.is_ident("unique") {
                            out.index_unique = true;
                            return Ok(());
                        }
                        if inner.path.is_ident("name") {
                            let s: LitStr = inner.value()?.parse()?;
                            out.index_name = Some(s.value());
                            return Ok(());
                        }
                        Err(inner
                            .error("unknown index sub-attribute (supported: `unique`, `name`)"))
                    })?;
                }
                return Ok(());
            }
            Err(meta.error("unknown rustango field attribute"))
        })?;
    }
    Ok(out)
}

/// Parse a signed integer literal, accepting optional leading `-`.
fn parse_signed_i64(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<i64> {
    let expr: syn::Expr = meta.value()?.parse()?;
    match expr {
        syn::Expr::Lit(syn::ExprLit {
            lit: syn::Lit::Int(lit),
            ..
        }) => lit.base10_parse::<i64>(),
        syn::Expr::Unary(syn::ExprUnary {
            op: syn::UnOp::Neg(_),
            expr,
            ..
        }) => {
            if let syn::Expr::Lit(syn::ExprLit {
                lit: syn::Lit::Int(lit),
                ..
            }) = *expr
            {
                let v: i64 = lit.base10_parse()?;
                Ok(-v)
            } else {
                Err(syn::Error::new_spanned(expr, "expected integer literal"))
            }
        }
        other => Err(syn::Error::new_spanned(
            other,
            "expected integer literal (signed)",
        )),
    }
}

struct FieldInfo<'a> {
    ident: &'a syn::Ident,
    column: String,
    primary_key: bool,
    /// `true` when the Rust type was `Auto<T>` — the INSERT path will
    /// skip this column when `Auto::Unset` and emit it under
    /// `RETURNING` so Postgres' sequence DEFAULT fills in the value.
    auto: bool,
    /// The original field type, e.g. `i64` or `Option<String>`. Emitted as
    /// the `Column::Value` associated type for typed-column tokens.
    value_ty: &'a Type,
    /// `FieldType` variant tokens (`::rustango::core::FieldType::I64`).
    field_type_tokens: TokenStream2,
    schema: TokenStream2,
    from_row_init: TokenStream2,
    /// Variant of [`Self::from_row_init`] that reads the column via
    /// `format!("{prefix}__{col}")` so a model can be decoded out of
    /// the aliased columns of a JOINed row. Drives slice 9.0d's
    /// `Self::__rustango_from_aliased_row(row, prefix)` per-Model
    /// helper that `select_related` calls when stitching loaded FKs.
    from_aliased_row_init: TokenStream2,
    /// Inner type from a `ForeignKey<T, K>` field, if any. The reverse-
    /// relation helper emit (`Author::<child>_set`) needs to know `T`
    /// to point the generated method at the right child model.
    fk_inner: Option<Type>,
    /// `K`'s scalar kind for a `ForeignKey<T, K>` field. Mirrors
    /// `kind` (since ForeignKey detection sets `kind` to K's
    /// underlying type) but stored separately for clarity at the
    /// `FkRelation` construction site, which only sees the FK's
    /// surface fields.
    fk_pk_kind: DetectedKind,
    /// `true` when the field is `Option<ForeignKey<T, K>>` rather than
    /// the bare `ForeignKey<T, K>`. Routes the load_related and
    /// fk_pk_access emitters to wrap assignments / accessors in
    /// `Some(...)` / `as_ref().map(...)` respectively, so a nullable
    /// FK column compiles end-to-end. The DDL writer reads this off
    /// the field schema (`nullable` flag); the macro just needs to
    /// keep the Rust-side codegen consistent.
    nullable: bool,
    /// `true` when this column was marked `#[rustango(auto_now)]` —
    /// `update_on` / `save_on` bind `chrono::Utc::now()` for this
    /// column instead of the user-supplied value, so `updated_at`
    /// always reflects the latest write without the caller having
    /// to remember to set it.
    auto_now: bool,
    /// `true` when this column was marked `#[rustango(auto_now_add)]`
    /// — the column is server-set on INSERT (DB DEFAULT) and
    /// **immutable** afterwards. `update_on` / `save_on` skip the
    /// column entirely so a stale `created_at` value in memory never
    /// rewrites the persisted timestamp.
    auto_now_add: bool,
    /// `true` when this column was marked `#[rustango(soft_delete)]`.
    /// Triggers emission of `soft_delete_on(executor)` and
    /// `restore_on(executor)` on the model's inherent impl. There is
    /// at most one such column per model — emission asserts this.
    soft_delete: bool,
    /// `Some` when this column was marked
    /// `#[rustango(generated_as = "EXPR")]`. The macro skips it from
    /// every INSERT and UPDATE path; the database recomputes the
    /// value from `EXPR`. Backlog item #35.
    generated_as: Option<String>,
}

/// Reject table names that won't survive SQL identifier
/// derivation downstream. Postgres' regular-identifier rule
/// (`[a-zA-Z_][a-zA-Z0-9_]*`) is the safe shape: it round-trips
/// through the framework's unquoted FK / index / constraint name
/// emission without surprises. We also disallow leading-digit and
/// the empty string for clarity.
///
/// Reserved-word collisions (`select`, `from`, …) aren't flagged
/// here — those produce a runtime error from the SQL parser,
/// which is loud enough; statically enumerating reserved words
/// across the three supported dialects is more friction than help.
///
/// Backlog item #65.
fn validate_table_name(name: &str, span: proc_macro2::Span) -> syn::Result<()> {
    if name.is_empty() {
        return Err(syn::Error::new(
            span,
            "`table = \"\"` is not a valid SQL identifier",
        ));
    }
    let mut chars = name.chars();
    let first = chars.next().unwrap();
    if !(first.is_ascii_alphabetic() || first == '_') {
        return Err(syn::Error::new(
            span,
            format!("table name `{name}` must start with a letter or underscore (got {first:?})",),
        ));
    }
    for c in chars {
        if !(c.is_ascii_alphanumeric() || c == '_') {
            return Err(syn::Error::new(
                span,
                format!(
                    "table name `{name}` contains invalid character {c:?} — \
                     SQL identifiers must match `[a-zA-Z_][a-zA-Z0-9_]*`. \
                     Hyphens in particular break FK / index name derivation \
                     downstream; use underscores instead (e.g. `{}`)",
                    name.replace(|x: char| !x.is_ascii_alphanumeric() && x != '_', "_"),
                ),
            ));
        }
    }
    Ok(())
}

fn process_field<'a>(field: &'a syn::Field, table: &str) -> syn::Result<FieldInfo<'a>> {
    let attrs = parse_field_attrs(field)?;
    let ident = field
        .ident
        .as_ref()
        .ok_or_else(|| syn::Error::new(field.span(), "tuple structs are not supported"))?;
    let name = ident.to_string();
    let column = attrs.column.clone().unwrap_or_else(|| name.clone());
    let primary_key = attrs.primary_key;
    let DetectedType {
        kind,
        nullable,
        auto: detected_auto,
        fk_inner,
    } = detect_type(&field.ty)?;
    check_bound_compatibility(field, &attrs, kind)?;
    let auto = detected_auto;
    // Mixin attributes piggyback on the existing `Auto<T>` skip-on-
    // INSERT path: the user must wrap the field in `Auto<T>`, which
    // marks the column as DB-default-supplied. The mixin attrs then
    // layer in the SQL default (`now()` / `gen_random_uuid()`) and,
    // for `auto_now`, force the value on UPDATE too.
    if attrs.auto_uuid {
        if kind != DetectedKind::Uuid {
            return Err(syn::Error::new_spanned(
                field,
                "`#[rustango(auto_uuid)]` requires the field type to be \
                 `Auto<uuid::Uuid>`",
            ));
        }
        if !detected_auto {
            return Err(syn::Error::new_spanned(
                field,
                "`#[rustango(auto_uuid)]` requires the field type to be \
                 wrapped in `Auto<...>` so the macro skips the column on \
                 INSERT and the DB DEFAULT (`gen_random_uuid()`) fires",
            ));
        }
    }
    if attrs.auto_now_add || attrs.auto_now {
        if kind != DetectedKind::DateTime {
            return Err(syn::Error::new_spanned(
                field,
                "`#[rustango(auto_now_add)]` / `#[rustango(auto_now)]` require \
                 the field type to be `Auto<chrono::DateTime<chrono::Utc>>`",
            ));
        }
        if !detected_auto {
            return Err(syn::Error::new_spanned(
                field,
                "`#[rustango(auto_now_add)]` / `#[rustango(auto_now)]` require \
                 the field type to be wrapped in `Auto<...>` so the macro skips \
                 the column on INSERT and the DB DEFAULT (`now()`) fires",
            ));
        }
    }
    if attrs.soft_delete && !(kind == DetectedKind::DateTime && nullable) {
        return Err(syn::Error::new_spanned(
            field,
            "`#[rustango(soft_delete)]` requires the field type to be \
             `Option<chrono::DateTime<chrono::Utc>>`",
        ));
    }
    let is_mixin_auto = attrs.auto_uuid || attrs.auto_now_add || attrs.auto_now;
    if detected_auto && !primary_key && !is_mixin_auto {
        return Err(syn::Error::new_spanned(
            field,
            "`Auto<T>` is only valid on a `#[rustango(primary_key)]` field, \
             or on a field carrying one of `auto_uuid`, `auto_now_add`, or \
             `auto_now`",
        ));
    }
    if detected_auto && attrs.default.is_some() && !is_mixin_auto {
        return Err(syn::Error::new_spanned(
            field,
            "`#[rustango(default = \"…\")]` is redundant on an `Auto<T>` field — \
             SERIAL / BIGSERIAL already supplies a default sequence.",
        ));
    }
    if fk_inner.is_some() && primary_key {
        return Err(syn::Error::new_spanned(
            field,
            "`ForeignKey<T>` is not allowed on a primary-key field — \
             a row's PK is its own identity, not a reference to a parent.",
        ));
    }
    if attrs.generated_as.is_some() {
        if primary_key {
            return Err(syn::Error::new_spanned(
                field,
                "`#[rustango(generated_as = \"…\")]` is not allowed on a \
                 primary-key field — a PK must be writable so the row \
                 has an identity at INSERT time.",
            ));
        }
        if attrs.default.is_some() {
            return Err(syn::Error::new_spanned(
                field,
                "`#[rustango(generated_as = \"…\")]` cannot combine with \
                 `default = \"…\"` — Postgres rejects DEFAULT on \
                 generated columns. The expression IS the default.",
            ));
        }
        if detected_auto {
            return Err(syn::Error::new_spanned(
                field,
                "`#[rustango(generated_as = \"…\")]` is not allowed on \
                 an `Auto<T>` field — generated columns are computed \
                 by the DB, not server-assigned via a sequence. Use a \
                 plain Rust type (e.g. `f64`).",
            ));
        }
        if fk_inner.is_some() {
            return Err(syn::Error::new_spanned(
                field,
                "`#[rustango(generated_as = \"…\")]` is not allowed on a \
                 ForeignKey field.",
            ));
        }
    }
    let relation = relation_tokens(field, &attrs, fk_inner, table)?;
    let column_lit = column.as_str();
    let field_type_tokens = kind.variant_tokens();
    let max_length = optional_u32(attrs.max_length);
    let min = optional_i64(attrs.min);
    let max = optional_i64(attrs.max);
    let default = optional_str(attrs.default.as_deref());

    let unique = attrs.unique;
    let generated_as = optional_str(attrs.generated_as.as_deref());
    let schema = quote! {
        ::rustango::core::FieldSchema {
            name: #name,
            column: #column_lit,
            ty: #field_type_tokens,
            nullable: #nullable,
            primary_key: #primary_key,
            relation: #relation,
            max_length: #max_length,
            min: #min,
            max: #max,
            default: #default,
            auto: #auto,
            unique: #unique,
            generated_as: #generated_as,
        }
    };

    let from_row_init = quote! {
        #ident: ::rustango::sql::sqlx::Row::try_get(row, #column_lit)?
    };
    let from_aliased_row_init = quote! {
        #ident: ::rustango::sql::sqlx::Row::try_get(
            row,
            ::std::format!("{}__{}", prefix, #column_lit).as_str(),
        )?
    };

    Ok(FieldInfo {
        ident,
        column,
        primary_key,
        auto,
        value_ty: &field.ty,
        field_type_tokens,
        schema,
        from_row_init,
        from_aliased_row_init,
        fk_inner: fk_inner.cloned(),
        fk_pk_kind: kind,
        nullable,
        auto_now: attrs.auto_now,
        auto_now_add: attrs.auto_now_add,
        soft_delete: attrs.soft_delete,
        generated_as: attrs.generated_as.clone(),
    })
}

fn check_bound_compatibility(
    field: &syn::Field,
    attrs: &FieldAttrs,
    kind: DetectedKind,
) -> syn::Result<()> {
    if attrs.max_length.is_some() && kind != DetectedKind::String {
        return Err(syn::Error::new_spanned(
            field,
            "`max_length` is only valid on `String` fields (or `Option<String>`)",
        ));
    }
    if (attrs.min.is_some() || attrs.max.is_some()) && !kind.is_integer() {
        return Err(syn::Error::new_spanned(
            field,
            "`min` / `max` are only valid on integer fields (`i32`, `i64`, optionally Option-wrapped)",
        ));
    }
    if let (Some(min), Some(max)) = (attrs.min, attrs.max) {
        if min > max {
            return Err(syn::Error::new_spanned(
                field,
                format!("`min` ({min}) is greater than `max` ({max})"),
            ));
        }
    }
    Ok(())
}

fn optional_u32(value: Option<u32>) -> TokenStream2 {
    if let Some(v) = value {
        quote!(::core::option::Option::Some(#v))
    } else {
        quote!(::core::option::Option::None)
    }
}

fn optional_i64(value: Option<i64>) -> TokenStream2 {
    if let Some(v) = value {
        quote!(::core::option::Option::Some(#v))
    } else {
        quote!(::core::option::Option::None)
    }
}

fn optional_str(value: Option<&str>) -> TokenStream2 {
    if let Some(v) = value {
        quote!(::core::option::Option::Some(#v))
    } else {
        quote!(::core::option::Option::None)
    }
}

fn relation_tokens(
    field: &syn::Field,
    attrs: &FieldAttrs,
    fk_inner: Option<&syn::Type>,
    table: &str,
) -> syn::Result<TokenStream2> {
    if let Some(inner) = fk_inner {
        if attrs.fk.is_some() || attrs.o2o.is_some() {
            return Err(syn::Error::new_spanned(
                field,
                "`ForeignKey<T>` already declares the FK target via the type parameter — \
                 remove the `fk = \"…\"` / `o2o = \"…\"` attribute.",
            ));
        }
        let on = attrs.on.as_deref().unwrap_or("id");
        return Ok(quote! {
            ::core::option::Option::Some(::rustango::core::Relation::Fk {
                to: <#inner as ::rustango::core::Model>::SCHEMA.table,
                on: #on,
            })
        });
    }
    match (&attrs.fk, &attrs.o2o) {
        (Some(_), Some(_)) => Err(syn::Error::new_spanned(
            field,
            "`fk` and `o2o` are mutually exclusive",
        )),
        (Some(to), None) => {
            let on = attrs.on.as_deref().unwrap_or("id");
            // Self-FK sentinel — `#[rustango(fk = "self")]` resolves to
            // the model's own table. Threaded as a literal string at
            // macro-expansion time to sidestep the const-eval cycle
            // that `Self::SCHEMA.table` would create when referenced
            // inside Self::SCHEMA's own initializer.
            let resolved = if to == "self" { table } else { to };
            Ok(quote! {
                ::core::option::Option::Some(::rustango::core::Relation::Fk { to: #resolved, on: #on })
            })
        }
        (None, Some(to)) => {
            let on = attrs.on.as_deref().unwrap_or("id");
            let resolved = if to == "self" { table } else { to };
            Ok(quote! {
                ::core::option::Option::Some(::rustango::core::Relation::O2O { to: #resolved, on: #on })
            })
        }
        (None, None) => {
            if attrs.on.is_some() {
                return Err(syn::Error::new_spanned(
                    field,
                    "`on` requires `fk` or `o2o`",
                ));
            }
            Ok(quote!(::core::option::Option::None))
        }
    }
}

/// Mirrors `rustango_core::FieldType`. Local copy so the macro can reason
/// about kinds without depending on `rustango-core` (which would require a
/// proc-macro/normal split it doesn't have today).
#[derive(Clone, Copy, PartialEq, Eq)]
enum DetectedKind {
    I16,
    I32,
    I64,
    F32,
    F64,
    Bool,
    String,
    DateTime,
    Date,
    Uuid,
    Json,
}

impl DetectedKind {
    fn variant_tokens(self) -> TokenStream2 {
        match self {
            Self::I16 => quote!(::rustango::core::FieldType::I16),
            Self::I32 => quote!(::rustango::core::FieldType::I32),
            Self::I64 => quote!(::rustango::core::FieldType::I64),
            Self::F32 => quote!(::rustango::core::FieldType::F32),
            Self::F64 => quote!(::rustango::core::FieldType::F64),
            Self::Bool => quote!(::rustango::core::FieldType::Bool),
            Self::String => quote!(::rustango::core::FieldType::String),
            Self::DateTime => quote!(::rustango::core::FieldType::DateTime),
            Self::Date => quote!(::rustango::core::FieldType::Date),
            Self::Uuid => quote!(::rustango::core::FieldType::Uuid),
            Self::Json => quote!(::rustango::core::FieldType::Json),
        }
    }

    fn is_integer(self) -> bool {
        matches!(self, Self::I16 | Self::I32 | Self::I64)
    }

    /// `(SqlValue::<Variant>, default expr)` for emitting the
    /// `match SqlValue { … }` arm in `LoadRelated::__rustango_load_related`
    /// for a `ForeignKey<T, K>` FK whose K maps to `self`. The default
    /// fires only when the parent's `__rustango_pk_value` returns a
    /// different variant than expected, which is a compile-time bug —
    /// but we still need a value-typed fallback to keep the match
    /// total.
    fn sqlvalue_match_arm(self) -> (TokenStream2, TokenStream2) {
        match self {
            Self::I16 => (quote!(I16), quote!(0i16)),
            Self::I32 => (quote!(I32), quote!(0i32)),
            Self::I64 => (quote!(I64), quote!(0i64)),
            Self::F32 => (quote!(F32), quote!(0f32)),
            Self::F64 => (quote!(F64), quote!(0f64)),
            Self::Bool => (quote!(Bool), quote!(false)),
            Self::String => (quote!(String), quote!(::std::string::String::new())),
            Self::DateTime => (
                quote!(DateTime),
                quote!(<::chrono::DateTime<::chrono::Utc> as ::std::default::Default>::default()),
            ),
            Self::Date => (
                quote!(Date),
                quote!(<::chrono::NaiveDate as ::std::default::Default>::default()),
            ),
            Self::Uuid => (quote!(Uuid), quote!(::uuid::Uuid::nil())),
            Self::Json => (quote!(Json), quote!(::serde_json::Value::Null)),
        }
    }
}

/// Result of walking a field's Rust type. `kind` is the underlying
/// `FieldType`; `nullable` is set by an outer `Option<T>`; `auto` is
/// set by an outer `Auto<T>` (server-assigned PK); `fk_inner` is
/// `Some(<T>)` when the field was `ForeignKey<T>` (or
/// `Option<ForeignKey<T>>`), letting the codegen reach `T::SCHEMA`.
#[derive(Clone, Copy)]
struct DetectedType<'a> {
    kind: DetectedKind,
    nullable: bool,
    auto: bool,
    fk_inner: Option<&'a syn::Type>,
}

/// Extract the `T` from a `…::Auto<T>` field type. Returns `None` for
/// non-`Auto` types — the caller should already have routed Auto-only
/// codegen through this helper, so a `None` indicates a macro-internal
/// invariant break.
fn auto_inner_type(ty: &syn::Type) -> Option<&syn::Type> {
    let Type::Path(TypePath { path, qself: None }) = ty else {
        return None;
    };
    let last = path.segments.last()?;
    if last.ident != "Auto" {
        return None;
    }
    let syn::PathArguments::AngleBracketed(args) = &last.arguments else {
        return None;
    };
    args.args.iter().find_map(|a| match a {
        syn::GenericArgument::Type(t) => Some(t),
        _ => None,
    })
}

fn detect_type(ty: &syn::Type) -> syn::Result<DetectedType<'_>> {
    let Type::Path(TypePath { path, qself: None }) = ty else {
        return Err(syn::Error::new_spanned(ty, "unsupported field type"));
    };
    let last = path
        .segments
        .last()
        .ok_or_else(|| syn::Error::new_spanned(ty, "empty type path"))?;

    if last.ident == "Option" {
        let inner = generic_inner(ty, &last.arguments, "Option")?;
        let inner_det = detect_type(inner)?;
        if inner_det.nullable {
            return Err(syn::Error::new_spanned(
                ty,
                "nested Option is not supported",
            ));
        }
        if inner_det.auto {
            return Err(syn::Error::new_spanned(
                ty,
                "`Option<Auto<T>>` is not supported — Auto fields are server-assigned and cannot be NULL",
            ));
        }
        return Ok(DetectedType {
            nullable: true,
            ..inner_det
        });
    }

    if last.ident == "Auto" {
        let inner = generic_inner(ty, &last.arguments, "Auto")?;
        let inner_det = detect_type(inner)?;
        if inner_det.auto {
            return Err(syn::Error::new_spanned(ty, "nested Auto is not supported"));
        }
        if inner_det.nullable {
            return Err(syn::Error::new_spanned(
                ty,
                "`Auto<Option<T>>` is not supported — Auto fields are server-assigned and cannot be NULL",
            ));
        }
        if inner_det.fk_inner.is_some() {
            return Err(syn::Error::new_spanned(
                ty,
                "`Auto<ForeignKey<T>>` is not supported — Auto is for server-assigned PKs, ForeignKey is for parent references",
            ));
        }
        if !matches!(
            inner_det.kind,
            DetectedKind::I32 | DetectedKind::I64 | DetectedKind::Uuid | DetectedKind::DateTime
        ) {
            return Err(syn::Error::new_spanned(
                ty,
                "`Auto<T>` only supports integers (`i32` → SERIAL, `i64` → BIGSERIAL), \
                 `uuid::Uuid` (DEFAULT gen_random_uuid()), or `chrono::DateTime<chrono::Utc>` \
                 (DEFAULT now())",
            ));
        }
        return Ok(DetectedType {
            auto: true,
            ..inner_det
        });
    }

    if last.ident == "ForeignKey" {
        let (inner, key_ty) = generic_pair(ty, &last.arguments, "ForeignKey")?;
        // Resolve the FK column's underlying SQL type from `K`. When the
        // user wrote `ForeignKey<T>` without a key parameter, the type
        // alias defaults to `i64` and we keep the v0.7 BIGINT shape.
        // When the user wrote `ForeignKey<T, K>` with an explicit `K`,
        // recurse into K so the column DDL emits the right SQL type
        // (VARCHAR for String, UUID for Uuid, …) and the load_related
        // emitter knows which `SqlValue` variant to match.
        let kind = match key_ty {
            Some(k) => detect_type(k)?.kind,
            None => DetectedKind::I64,
        };
        return Ok(DetectedType {
            kind,
            nullable: false,
            auto: false,
            fk_inner: Some(inner),
        });
    }

    let kind = match last.ident.to_string().as_str() {
        "i16" => DetectedKind::I16,
        "i32" => DetectedKind::I32,
        "i64" => DetectedKind::I64,
        "f32" => DetectedKind::F32,
        "f64" => DetectedKind::F64,
        "bool" => DetectedKind::Bool,
        "String" => DetectedKind::String,
        "DateTime" => DetectedKind::DateTime,
        "NaiveDate" => DetectedKind::Date,
        "Uuid" => DetectedKind::Uuid,
        "Value" => DetectedKind::Json,
        other => {
            return Err(syn::Error::new_spanned(
                ty,
                format!("unsupported field type `{other}`; v0.1 supports i32/i64/f32/f64/bool/String/DateTime/NaiveDate/Uuid/serde_json::Value, optionally wrapped in Option or Auto (Auto only on integers)"),
            ));
        }
    };
    Ok(DetectedType {
        kind,
        nullable: false,
        auto: false,
        fk_inner: None,
    })
}

fn generic_inner<'a>(
    ty: &'a Type,
    arguments: &'a PathArguments,
    wrapper: &str,
) -> syn::Result<&'a Type> {
    let PathArguments::AngleBracketed(args) = arguments else {
        return Err(syn::Error::new_spanned(
            ty,
            format!("{wrapper} requires a generic argument"),
        ));
    };
    args.args
        .iter()
        .find_map(|a| match a {
            GenericArgument::Type(t) => Some(t),
            _ => None,
        })
        .ok_or_else(|| {
            syn::Error::new_spanned(ty, format!("{wrapper}<T> requires a type argument"))
        })
}

/// Like [`generic_inner`] but pulls *two* type args — the first is
/// required, the second is optional. Used by the `ForeignKey<T, K>`
/// detection where K defaults to `i64` when omitted.
fn generic_pair<'a>(
    ty: &'a Type,
    arguments: &'a PathArguments,
    wrapper: &str,
) -> syn::Result<(&'a Type, Option<&'a Type>)> {
    let PathArguments::AngleBracketed(args) = arguments else {
        return Err(syn::Error::new_spanned(
            ty,
            format!("{wrapper} requires a generic argument"),
        ));
    };
    let mut types = args.args.iter().filter_map(|a| match a {
        GenericArgument::Type(t) => Some(t),
        _ => None,
    });
    let first = types.next().ok_or_else(|| {
        syn::Error::new_spanned(ty, format!("{wrapper}<T> requires a type argument"))
    })?;
    let second = types.next();
    Ok((first, second))
}

fn to_snake_case(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 4);
    for (i, ch) in s.chars().enumerate() {
        if ch.is_ascii_uppercase() {
            if i > 0 {
                out.push('_');
            }
            out.push(ch.to_ascii_lowercase());
        } else {
            out.push(ch);
        }
    }
    out
}

// ============================================================
//  #[derive(Form)]  —  slice 8.4B
// ============================================================

/// Per-field `#[form(...)]` attributes recognised by the derive.
#[derive(Default)]
struct FormFieldAttrs {
    min: Option<i64>,
    max: Option<i64>,
    min_length: Option<u32>,
    max_length: Option<u32>,
}

/// Detected shape of a form field's Rust type.
#[derive(Clone, Copy)]
enum FormFieldKind {
    String,
    I16,
    I32,
    I64,
    F32,
    F64,
    Bool,
}

impl FormFieldKind {
    fn parse_method(self) -> &'static str {
        match self {
            Self::I16 => "i16",
            Self::I32 => "i32",
            Self::I64 => "i64",
            Self::F32 => "f32",
            Self::F64 => "f64",
            // String + Bool don't go through `str::parse`; the codegen
            // handles them inline.
            Self::String | Self::Bool => "",
        }
    }
}

fn expand_form(input: &DeriveInput) -> syn::Result<TokenStream2> {
    let struct_name = &input.ident;

    let Data::Struct(data) = &input.data else {
        return Err(syn::Error::new_spanned(
            struct_name,
            "Form can only be derived on structs",
        ));
    };
    let Fields::Named(named) = &data.fields else {
        return Err(syn::Error::new_spanned(
            struct_name,
            "Form requires a struct with named fields",
        ));
    };

    let mut field_blocks: Vec<TokenStream2> = Vec::with_capacity(named.named.len());
    let mut field_idents: Vec<&syn::Ident> = Vec::with_capacity(named.named.len());

    for field in &named.named {
        let ident = field
            .ident
            .as_ref()
            .ok_or_else(|| syn::Error::new(field.span(), "tuple structs are not supported"))?;
        let attrs = parse_form_field_attrs(field)?;
        let (kind, nullable) = detect_form_field(&field.ty, field.span())?;

        let name_lit = ident.to_string();
        let parse_block = render_form_field_parse(ident, &name_lit, kind, nullable, &attrs);
        field_blocks.push(parse_block);
        field_idents.push(ident);
    }

    Ok(quote! {
        impl ::rustango::forms::Form for #struct_name {
            fn parse(
                data: &::std::collections::HashMap<::std::string::String, ::std::string::String>,
            ) -> ::core::result::Result<Self, ::rustango::forms::FormErrors> {
                let mut __errors = ::rustango::forms::FormErrors::default();
                #( #field_blocks )*
                if !__errors.is_empty() {
                    return ::core::result::Result::Err(__errors);
                }
                ::core::result::Result::Ok(Self {
                    #( #field_idents ),*
                })
            }
        }
    })
}

fn parse_form_field_attrs(field: &syn::Field) -> syn::Result<FormFieldAttrs> {
    let mut out = FormFieldAttrs::default();
    for attr in &field.attrs {
        if !attr.path().is_ident("form") {
            continue;
        }
        attr.parse_nested_meta(|meta| {
            if meta.path.is_ident("min") {
                let lit: syn::LitInt = meta.value()?.parse()?;
                out.min = Some(lit.base10_parse::<i64>()?);
                return Ok(());
            }
            if meta.path.is_ident("max") {
                let lit: syn::LitInt = meta.value()?.parse()?;
                out.max = Some(lit.base10_parse::<i64>()?);
                return Ok(());
            }
            if meta.path.is_ident("min_length") {
                let lit: syn::LitInt = meta.value()?.parse()?;
                out.min_length = Some(lit.base10_parse::<u32>()?);
                return Ok(());
            }
            if meta.path.is_ident("max_length") {
                let lit: syn::LitInt = meta.value()?.parse()?;
                out.max_length = Some(lit.base10_parse::<u32>()?);
                return Ok(());
            }
            Err(meta.error(
                "unknown form attribute (supported: `min`, `max`, `min_length`, `max_length`)",
            ))
        })?;
    }
    Ok(out)
}

fn detect_form_field(ty: &Type, span: proc_macro2::Span) -> syn::Result<(FormFieldKind, bool)> {
    let Type::Path(TypePath { path, qself: None }) = ty else {
        return Err(syn::Error::new(
            span,
            "Form field must be a simple typed path (e.g. `String`, `i32`, `Option<String>`)",
        ));
    };
    let last = path
        .segments
        .last()
        .ok_or_else(|| syn::Error::new(span, "empty type path"))?;

    if last.ident == "Option" {
        let inner = generic_inner(ty, &last.arguments, "Option")?;
        let (kind, nested) = detect_form_field(inner, span)?;
        if nested {
            return Err(syn::Error::new(
                span,
                "nested Option in Form fields is not supported",
            ));
        }
        return Ok((kind, true));
    }

    let kind = match last.ident.to_string().as_str() {
        "String" => FormFieldKind::String,
        "i16" => FormFieldKind::I16,
        "i32" => FormFieldKind::I32,
        "i64" => FormFieldKind::I64,
        "f32" => FormFieldKind::F32,
        "f64" => FormFieldKind::F64,
        "bool" => FormFieldKind::Bool,
        other => {
            return Err(syn::Error::new(
                span,
                format!(
                    "Form field type `{other}` is not supported in v0.8 — use String / \
                     i16 / i32 / i64 / f32 / f64 / bool, optionally wrapped in Option<…>"
                ),
            ));
        }
    };
    Ok((kind, false))
}

#[allow(clippy::too_many_lines)]
fn render_form_field_parse(
    ident: &syn::Ident,
    name_lit: &str,
    kind: FormFieldKind,
    nullable: bool,
    attrs: &FormFieldAttrs,
) -> TokenStream2 {
    // Pull the raw &str from the payload. Uses variable name `data` to
    // match the new `Form::parse(data: &HashMap<…>)` signature.
    let lookup = quote! {
        let __raw: ::core::option::Option<&::std::string::String> = data.get(#name_lit);
    };

    let parsed_value = match kind {
        FormFieldKind::Bool => quote! {
            let __v: bool = match __raw {
                ::core::option::Option::None => false,
                ::core::option::Option::Some(__s) => !matches!(
                    __s.to_ascii_lowercase().as_str(),
                    "" | "false" | "0" | "off" | "no"
                ),
            };
        },
        FormFieldKind::String => {
            if nullable {
                quote! {
                    let __v: ::core::option::Option<::std::string::String> = match __raw {
                        ::core::option::Option::None => ::core::option::Option::None,
                        ::core::option::Option::Some(__s) if __s.is_empty() => {
                            ::core::option::Option::None
                        }
                        ::core::option::Option::Some(__s) => {
                            ::core::option::Option::Some(::core::clone::Clone::clone(__s))
                        }
                    };
                }
            } else {
                quote! {
                    let __v: ::std::string::String = match __raw {
                        ::core::option::Option::Some(__s) if !__s.is_empty() => {
                            ::core::clone::Clone::clone(__s)
                        }
                        _ => {
                            __errors.add(#name_lit, "This field is required.");
                            ::std::string::String::new()
                        }
                    };
                }
            }
        }
        FormFieldKind::I16
        | FormFieldKind::I32
        | FormFieldKind::I64
        | FormFieldKind::F32
        | FormFieldKind::F64 => {
            let parse_ty = syn::Ident::new(kind.parse_method(), proc_macro2::Span::call_site());
            let ty_lit = kind.parse_method();
            let default_val = match kind {
                FormFieldKind::I16 => quote! { 0i16 },
                FormFieldKind::I32 => quote! { 0i32 },
                FormFieldKind::I64 => quote! { 0i64 },
                FormFieldKind::F32 => quote! { 0f32 },
                FormFieldKind::F64 => quote! { 0f64 },
                _ => quote! { Default::default() },
            };
            if nullable {
                quote! {
                    let __v: ::core::option::Option<#parse_ty> = match __raw {
                        ::core::option::Option::None => ::core::option::Option::None,
                        ::core::option::Option::Some(__s) if __s.is_empty() => {
                            ::core::option::Option::None
                        }
                        ::core::option::Option::Some(__s) => {
                            match __s.parse::<#parse_ty>() {
                                ::core::result::Result::Ok(__n) => {
                                    ::core::option::Option::Some(__n)
                                }
                                ::core::result::Result::Err(__e) => {
                                    __errors.add(
                                        #name_lit,
                                        ::std::format!("Enter a valid {} value: {}", #ty_lit, __e),
                                    );
                                    ::core::option::Option::None
                                }
                            }
                        }
                    };
                }
            } else {
                quote! {
                    let __v: #parse_ty = match __raw {
                        ::core::option::Option::Some(__s) if !__s.is_empty() => {
                            match __s.parse::<#parse_ty>() {
                                ::core::result::Result::Ok(__n) => __n,
                                ::core::result::Result::Err(__e) => {
                                    __errors.add(
                                        #name_lit,
                                        ::std::format!("Enter a valid {} value: {}", #ty_lit, __e),
                                    );
                                    #default_val
                                }
                            }
                        }
                        _ => {
                            __errors.add(#name_lit, "This field is required.");
                            #default_val
                        }
                    };
                }
            }
        }
    };

    let validators = render_form_validators(name_lit, kind, nullable, attrs);

    quote! {
        let #ident = {
            #lookup
            #parsed_value
            #validators
            __v
        };
    }
}

fn render_form_validators(
    name_lit: &str,
    kind: FormFieldKind,
    nullable: bool,
    attrs: &FormFieldAttrs,
) -> TokenStream2 {
    let mut checks: Vec<TokenStream2> = Vec::new();

    let val_ref = if nullable {
        quote! { __v.as_ref() }
    } else {
        quote! { ::core::option::Option::Some(&__v) }
    };

    let is_string = matches!(kind, FormFieldKind::String);
    let is_numeric = matches!(
        kind,
        FormFieldKind::I16
            | FormFieldKind::I32
            | FormFieldKind::I64
            | FormFieldKind::F32
            | FormFieldKind::F64
    );

    if is_string {
        if let Some(min_len) = attrs.min_length {
            let min_len_usize = min_len as usize;
            checks.push(quote! {
                if let ::core::option::Option::Some(__s) = #val_ref {
                    if __s.len() < #min_len_usize {
                        __errors.add(
                            #name_lit,
                            ::std::format!("Ensure this value has at least {} characters.", #min_len_usize),
                        );
                    }
                }
            });
        }
        if let Some(max_len) = attrs.max_length {
            let max_len_usize = max_len as usize;
            checks.push(quote! {
                if let ::core::option::Option::Some(__s) = #val_ref {
                    if __s.len() > #max_len_usize {
                        __errors.add(
                            #name_lit,
                            ::std::format!("Ensure this value has at most {} characters.", #max_len_usize),
                        );
                    }
                }
            });
        }
    }

    if is_numeric {
        if let Some(min) = attrs.min {
            checks.push(quote! {
                if let ::core::option::Option::Some(__n) = #val_ref {
                    if (*__n as f64) < (#min as f64) {
                        __errors.add(
                            #name_lit,
                            ::std::format!("Ensure this value is greater than or equal to {}.", #min),
                        );
                    }
                }
            });
        }
        if let Some(max) = attrs.max {
            checks.push(quote! {
                if let ::core::option::Option::Some(__n) = #val_ref {
                    if (*__n as f64) > (#max as f64) {
                        __errors.add(
                            #name_lit,
                            ::std::format!("Ensure this value is less than or equal to {}.", #max),
                        );
                    }
                }
            });
        }
    }

    quote! { #( #checks )* }
}

// ============================================================
//  #[derive(ViewSet)]
// ============================================================

struct ViewSetAttrs {
    model: syn::Path,
    fields: Option<Vec<String>>,
    filter_fields: Vec<String>,
    search_fields: Vec<String>,
    /// (field_name, desc)
    ordering: Vec<(String, bool)>,
    page_size: Option<usize>,
    read_only: bool,
    perms: ViewSetPermsAttrs,
}

#[derive(Default)]
struct ViewSetPermsAttrs {
    list: Vec<String>,
    retrieve: Vec<String>,
    create: Vec<String>,
    update: Vec<String>,
    destroy: Vec<String>,
}

fn expand_viewset(input: &DeriveInput) -> syn::Result<TokenStream2> {
    let struct_name = &input.ident;

    // Must be a unit struct or an empty named struct.
    match &input.data {
        Data::Struct(s) => match &s.fields {
            Fields::Unit | Fields::Named(_) => {}
            Fields::Unnamed(_) => {
                return Err(syn::Error::new_spanned(
                    struct_name,
                    "ViewSet can only be derived on a unit struct or an empty named struct",
                ));
            }
        },
        _ => {
            return Err(syn::Error::new_spanned(
                struct_name,
                "ViewSet can only be derived on a struct",
            ));
        }
    }

    let attrs = parse_viewset_attrs(input)?;
    let model_path = &attrs.model;

    // `.fields(&[...])` call — None means skip (use all scalar fields).
    let fields_call = if let Some(ref fields) = attrs.fields {
        let lits = fields.iter().map(|f| f.as_str());
        quote!(.fields(&[ #(#lits),* ]))
    } else {
        quote!()
    };

    let filter_fields_call = if attrs.filter_fields.is_empty() {
        quote!()
    } else {
        let lits = attrs.filter_fields.iter().map(|f| f.as_str());
        quote!(.filter_fields(&[ #(#lits),* ]))
    };

    let search_fields_call = if attrs.search_fields.is_empty() {
        quote!()
    } else {
        let lits = attrs.search_fields.iter().map(|f| f.as_str());
        quote!(.search_fields(&[ #(#lits),* ]))
    };

    let ordering_call = if attrs.ordering.is_empty() {
        quote!()
    } else {
        let pairs = attrs.ordering.iter().map(|(f, desc)| {
            let f = f.as_str();
            quote!((#f, #desc))
        });
        quote!(.ordering(&[ #(#pairs),* ]))
    };

    let page_size_call = if let Some(n) = attrs.page_size {
        quote!(.page_size(#n))
    } else {
        quote!()
    };

    let read_only_call = if attrs.read_only {
        quote!(.read_only())
    } else {
        quote!()
    };

    let perms = &attrs.perms;
    let perms_call = if perms.list.is_empty()
        && perms.retrieve.is_empty()
        && perms.create.is_empty()
        && perms.update.is_empty()
        && perms.destroy.is_empty()
    {
        quote!()
    } else {
        let list_lits = perms.list.iter().map(|s| s.as_str());
        let retrieve_lits = perms.retrieve.iter().map(|s| s.as_str());
        let create_lits = perms.create.iter().map(|s| s.as_str());
        let update_lits = perms.update.iter().map(|s| s.as_str());
        let destroy_lits = perms.destroy.iter().map(|s| s.as_str());
        quote! {
            .permissions(::rustango::viewset::ViewSetPerms {
                list:     ::std::vec![ #(#list_lits.to_owned()),* ],
                retrieve: ::std::vec![ #(#retrieve_lits.to_owned()),* ],
                create:   ::std::vec![ #(#create_lits.to_owned()),* ],
                update:   ::std::vec![ #(#update_lits.to_owned()),* ],
                destroy:  ::std::vec![ #(#destroy_lits.to_owned()),* ],
            })
        }
    };

    Ok(quote! {
        impl #struct_name {
            /// Build an `axum::Router` with the six standard REST endpoints
            /// for this ViewSet, mounted at `prefix`.
            pub fn router(prefix: &str, pool: ::rustango::sql::sqlx::PgPool) -> ::axum::Router {
                ::rustango::viewset::ViewSet::for_model(
                    <#model_path as ::rustango::core::Model>::SCHEMA
                )
                    #fields_call
                    #filter_fields_call
                    #search_fields_call
                    #ordering_call
                    #page_size_call
                    #perms_call
                    #read_only_call
                    .router(prefix, pool)
            }
        }
    })
}

fn parse_viewset_attrs(input: &DeriveInput) -> syn::Result<ViewSetAttrs> {
    let mut model: Option<syn::Path> = None;
    let mut fields: Option<Vec<String>> = None;
    let mut filter_fields: Vec<String> = Vec::new();
    let mut search_fields: Vec<String> = Vec::new();
    let mut ordering: Vec<(String, bool)> = Vec::new();
    let mut page_size: Option<usize> = None;
    let mut read_only = false;
    let mut perms = ViewSetPermsAttrs::default();

    for attr in &input.attrs {
        if !attr.path().is_ident("viewset") {
            continue;
        }
        attr.parse_nested_meta(|meta| {
            if meta.path.is_ident("model") {
                let path: syn::Path = meta.value()?.parse()?;
                model = Some(path);
                return Ok(());
            }
            if meta.path.is_ident("fields") {
                let s: LitStr = meta.value()?.parse()?;
                fields = Some(split_field_list(&s.value()));
                return Ok(());
            }
            if meta.path.is_ident("filter_fields") {
                let s: LitStr = meta.value()?.parse()?;
                filter_fields = split_field_list(&s.value());
                return Ok(());
            }
            if meta.path.is_ident("search_fields") {
                let s: LitStr = meta.value()?.parse()?;
                search_fields = split_field_list(&s.value());
                return Ok(());
            }
            if meta.path.is_ident("ordering") {
                let s: LitStr = meta.value()?.parse()?;
                ordering = parse_ordering_list(&s.value());
                return Ok(());
            }
            if meta.path.is_ident("page_size") {
                let lit: syn::LitInt = meta.value()?.parse()?;
                page_size = Some(lit.base10_parse::<usize>()?);
                return Ok(());
            }
            if meta.path.is_ident("read_only") {
                read_only = true;
                return Ok(());
            }
            if meta.path.is_ident("permissions") {
                meta.parse_nested_meta(|inner| {
                    let parse_codenames = |inner: &syn::meta::ParseNestedMeta| -> syn::Result<Vec<String>> {
                        let s: LitStr = inner.value()?.parse()?;
                        Ok(split_field_list(&s.value()))
                    };
                    if inner.path.is_ident("list") {
                        perms.list = parse_codenames(&inner)?;
                    } else if inner.path.is_ident("retrieve") {
                        perms.retrieve = parse_codenames(&inner)?;
                    } else if inner.path.is_ident("create") {
                        perms.create = parse_codenames(&inner)?;
                    } else if inner.path.is_ident("update") {
                        perms.update = parse_codenames(&inner)?;
                    } else if inner.path.is_ident("destroy") {
                        perms.destroy = parse_codenames(&inner)?;
                    } else {
                        return Err(inner.error(
                            "unknown permissions key (supported: list, retrieve, create, update, destroy)",
                        ));
                    }
                    Ok(())
                })?;
                return Ok(());
            }
            Err(meta.error(
                "unknown viewset attribute (supported: model, fields, filter_fields, \
                 search_fields, ordering, page_size, read_only, permissions(...))",
            ))
        })?;
    }

    let model = model.ok_or_else(|| {
        syn::Error::new_spanned(&input.ident, "`#[viewset(model = SomeModel)]` is required")
    })?;

    Ok(ViewSetAttrs {
        model,
        fields,
        filter_fields,
        search_fields,
        ordering,
        page_size,
        read_only,
        perms,
    })
}

// ============================================================ #[derive(Serializer)]

struct SerializerContainerAttrs {
    model: syn::Path,
}

#[derive(Default)]
struct SerializerFieldAttrs {
    read_only: bool,
    write_only: bool,
    source: Option<String>,
    skip: bool,
    /// `#[serializer(method = "fn_name")]` — DRF SerializerMethodField
    /// analog. The macro emits `from_model` initializer that calls
    /// `Self::fn_name(&model)` and stores the return value.
    method: Option<String>,
    /// `#[serializer(validate = "fn_name")]` — per-field validator
    /// callable run by `Self::validate(&self)`. Must return
    /// `Result<(), String>`. Errors land in `FormErrors` keyed by
    /// the field name.
    validate: Option<String>,
    /// `#[serializer(nested)]` on a field whose type is another
    /// `Serializer` — the macro emits `from_model` initializer that
    /// reads the parent via `model.<source>.value()` then calls the
    /// child serializer's `from_model(parent)`. When the FK is
    /// unloaded the field falls back to `Default::default()` (does
    /// NOT panic) so a missing prefetch in prod degrades gracefully.
    /// Source field on the model defaults to the field name; override
    /// with `source = "..."`. Combine with `strict` to keep the v0.18.1
    /// panic-on-unloaded behavior for tests.
    nested: bool,
    /// `#[serializer(nested, strict)]` — opt back into the v0.18.1
    /// strict behavior: panic when the FK isn't loaded. Useful in
    /// test code where forgetting select_related must trip a hard
    /// failure rather than render a blank nested object.
    nested_strict: bool,
    /// `#[serializer(many = TagSerializer)]` — declare the field as
    /// a list of nested serializers. Field type must be `Vec<S>`
    /// where `S` is the inner serializer. The macro initializes the
    /// field to `Vec::new()` in `from_model` and emits a typed
    /// `set_<field>(&mut self, models: &[<S::Model>])` helper that
    /// maps each model row through `S::from_model`. Auto-load isn't
    /// possible (the M2M / one-to-many accessor is async); callers
    /// fetch the children + call the setter post-from_model.
    many: Option<syn::Type>,
}

fn parse_serializer_container_attrs(input: &DeriveInput) -> syn::Result<SerializerContainerAttrs> {
    let mut model: Option<syn::Path> = None;
    for attr in &input.attrs {
        if !attr.path().is_ident("serializer") {
            continue;
        }
        attr.parse_nested_meta(|meta| {
            if meta.path.is_ident("model") {
                let _eq: syn::Token![=] = meta.input.parse()?;
                model = Some(meta.input.parse()?);
                return Ok(());
            }
            Err(meta.error("unknown serializer container attribute (supported: `model`)"))
        })?;
    }
    let model = model.ok_or_else(|| {
        syn::Error::new_spanned(
            &input.ident,
            "`#[serializer(model = SomeModel)]` is required",
        )
    })?;
    Ok(SerializerContainerAttrs { model })
}

fn parse_serializer_field_attrs(field: &syn::Field) -> syn::Result<SerializerFieldAttrs> {
    let mut out = SerializerFieldAttrs::default();
    for attr in &field.attrs {
        if !attr.path().is_ident("serializer") {
            continue;
        }
        attr.parse_nested_meta(|meta| {
            if meta.path.is_ident("read_only") {
                out.read_only = true;
                return Ok(());
            }
            if meta.path.is_ident("write_only") {
                out.write_only = true;
                return Ok(());
            }
            if meta.path.is_ident("skip") {
                out.skip = true;
                return Ok(());
            }
            if meta.path.is_ident("source") {
                let s: LitStr = meta.value()?.parse()?;
                out.source = Some(s.value());
                return Ok(());
            }
            if meta.path.is_ident("method") {
                let s: LitStr = meta.value()?.parse()?;
                out.method = Some(s.value());
                return Ok(());
            }
            if meta.path.is_ident("validate") {
                let s: LitStr = meta.value()?.parse()?;
                out.validate = Some(s.value());
                return Ok(());
            }
            if meta.path.is_ident("many") {
                let _eq: syn::Token![=] = meta.input.parse()?;
                out.many = Some(meta.input.parse()?);
                return Ok(());
            }
            if meta.path.is_ident("nested") {
                out.nested = true;
                // Optional strict flag inside parentheses:
                //   #[serializer(nested(strict))]
                if meta.input.peek(syn::token::Paren) {
                    meta.parse_nested_meta(|inner| {
                        if inner.path.is_ident("strict") {
                            out.nested_strict = true;
                            return Ok(());
                        }
                        Err(inner.error("unknown nested sub-attribute (supported: `strict`)"))
                    })?;
                }
                return Ok(());
            }
            Err(meta.error(
                "unknown serializer field attribute (supported: \
                 `read_only`, `write_only`, `source`, `skip`, `method`, `validate`, `nested`)",
            ))
        })?;
    }
    // Validate: read_only + write_only is nonsensical
    if out.read_only && out.write_only {
        return Err(syn::Error::new_spanned(
            field,
            "a field cannot be both `read_only` and `write_only`",
        ));
    }
    if out.method.is_some() && out.source.is_some() {
        return Err(syn::Error::new_spanned(
            field,
            "`method` and `source` are mutually exclusive — `method` computes \
             the value from a method, `source` reads it from a different model field",
        ));
    }
    Ok(out)
}

fn expand_serializer(input: &DeriveInput) -> syn::Result<TokenStream2> {
    let struct_name = &input.ident;
    let struct_name_lit = struct_name.to_string();

    let Data::Struct(data) = &input.data else {
        return Err(syn::Error::new_spanned(
            struct_name,
            "Serializer can only be derived on structs",
        ));
    };
    let Fields::Named(named) = &data.fields else {
        return Err(syn::Error::new_spanned(
            struct_name,
            "Serializer requires a struct with named fields",
        ));
    };

    let container = parse_serializer_container_attrs(input)?;
    let model_path = &container.model;

    // Classify each field. `ty` is only consumed by the
    // `#[cfg(feature = "openapi")]` block below, but we always
    // capture it to keep the field-info build a single pass.
    #[allow(dead_code)]
    struct FieldInfo {
        ident: syn::Ident,
        ty: syn::Type,
        attrs: SerializerFieldAttrs,
    }
    let mut fields_info: Vec<FieldInfo> = Vec::new();
    for field in &named.named {
        let ident = field.ident.clone().expect("named field has ident");
        let attrs = parse_serializer_field_attrs(field)?;
        fields_info.push(FieldInfo {
            ident,
            ty: field.ty.clone(),
            attrs,
        });
    }

    // Generate from_model body: struct literal with each field assigned.
    let from_model_fields = fields_info.iter().map(|fi| {
        let ident = &fi.ident;
        let ty = &fi.ty;
        if let Some(_inner) = &fi.attrs.many {
            // Many — collection field. Initialize empty; caller
            // populates via the macro-emitted set_<field> helper
            // after fetching the M2M children.
            quote! { #ident: ::std::vec::Vec::new() }
        } else if let Some(method) = &fi.attrs.method {
            // SerializerMethodField: call Self::<method>(&model) to
            // compute the value. Method signature must be
            // `fn <method>(model: &T) -> <field type>`.
            let method_ident = syn::Ident::new(method, ident.span());
            quote! { #ident: Self::#method_ident(model) }
        } else if fi.attrs.nested {
            // Nested serializer. Source defaults to the field name on
            // this struct; override via `source = "..."`. The source
            // field on the model is expected to be a `ForeignKey<T>`
            // whose `.value()` returns `Option<&T>` after lazy-load.
            //
            // Behavior matrix (tweakable per-field):
            //   * FK loaded   → nested object materializes via
            //                   ChildSerializer::from_model(parent).
            //   * FK unloaded → fall back to ChildSerializer::default()
            //                   (so prod doesn't crash on a missing
            //                   prefetch — just renders a blank nested
            //                   object). Add `#[serializer(nested,
            //                   strict)]` to keep the v0.18.1
            //                   panic-on-unloaded behavior for tests
            //                   that want hard guardrails.
            let src_name = fi.attrs.source.as_deref().unwrap_or(&fi.ident.to_string()).to_owned();
            let src_ident = syn::Ident::new(&src_name, ident.span());
            if fi.attrs.nested_strict {
                let panic_msg = format!(
                    "nested(strict) serializer for `{ident}` requires `model.{src_name}` to be loaded — \
                     call .get(&pool).await? or .select_related(\"{src_name}\") on the model first",
                );
                quote! {
                    #ident: <#ty as ::rustango::serializer::ModelSerializer>::from_model(
                        model.#src_ident.value().expect(#panic_msg),
                    )
                }
            } else {
                quote! {
                    #ident: match model.#src_ident.value() {
                        ::core::option::Option::Some(__loaded) =>
                            <#ty as ::rustango::serializer::ModelSerializer>::from_model(__loaded),
                        ::core::option::Option::None =>
                            ::core::default::Default::default(),
                    }
                }
            }
        } else if fi.attrs.write_only || fi.attrs.skip {
            // Not read from model — use default
            quote! { #ident: ::core::default::Default::default() }
        } else if let Some(src) = &fi.attrs.source {
            let src_ident = syn::Ident::new(src, ident.span());
            quote! { #ident: ::core::clone::Clone::clone(&model.#src_ident) }
        } else {
            quote! { #ident: ::core::clone::Clone::clone(&model.#ident) }
        }
    });

    // Per-field validators (DRF-shape `validators=[...]`). Emit a
    // `validate(&self)` method that runs each user-defined validator
    // and aggregates errors into `FormErrors`.
    let validator_calls: Vec<_> = fields_info
        .iter()
        .filter_map(|fi| {
            let ident = &fi.ident;
            let name_lit = ident.to_string();
            let method = fi.attrs.validate.as_ref()?;
            let method_ident = syn::Ident::new(method, ident.span());
            Some(quote! {
                if let ::core::result::Result::Err(__e) = Self::#method_ident(&self.#ident) {
                    __errors.add(#name_lit.to_owned(), __e);
                }
            })
        })
        .collect();
    let validate_method = if validator_calls.is_empty() {
        quote! {}
    } else {
        quote! {
            impl #struct_name {
                /// Run every `#[serializer(validate = "...")]` per-field
                /// validator. Aggregates errors into `FormErrors` keyed
                /// by the field name. Returns `Ok(())` when all pass.
                pub fn validate(&self) -> ::core::result::Result<(), ::rustango::forms::FormErrors> {
                    let mut __errors = ::rustango::forms::FormErrors::default();
                    #( #validator_calls )*
                    if __errors.is_empty() {
                        ::core::result::Result::Ok(())
                    } else {
                        ::core::result::Result::Err(__errors)
                    }
                }
            }
        }
    };

    // For every `#[serializer(many = S)]` field, emit a
    // `pub fn set_<field>(&mut self, models: &[<S::Model>]) -> &mut Self`
    // helper that maps the parents through `S::from_model`.
    let many_setters: Vec<_> = fields_info
        .iter()
        .filter_map(|fi| {
            let many_ty = fi.attrs.many.as_ref()?;
            let ident = &fi.ident;
            let setter = syn::Ident::new(&format!("set_{ident}"), ident.span());
            Some(quote! {
                /// Populate this `many` field by mapping each parent model
                /// through the inner serializer's `from_model`. Call after
                /// fetching the M2M / one-to-many children since
                /// `from_model` itself can't await an SQL query.
                pub fn #setter(
                    &mut self,
                    models: &[<#many_ty as ::rustango::serializer::ModelSerializer>::Model],
                ) -> &mut Self {
                    self.#ident = models.iter()
                        .map(<#many_ty as ::rustango::serializer::ModelSerializer>::from_model)
                        .collect();
                    self
                }
            })
        })
        .collect();
    let many_setters_impl = if many_setters.is_empty() {
        quote! {}
    } else {
        quote! {
            impl #struct_name {
                #( #many_setters )*
            }
        }
    };

    // Generate custom Serialize: skip write_only fields
    let output_fields: Vec<_> = fields_info
        .iter()
        .filter(|fi| !fi.attrs.write_only)
        .collect();
    let output_field_count = output_fields.len();
    let serialize_fields = output_fields.iter().map(|fi| {
        let ident = &fi.ident;
        let name_lit = ident.to_string();
        quote! { __state.serialize_field(#name_lit, &self.#ident)?; }
    });

    // writable_fields: normal + write_only (not read_only, not skip)
    let writable_lits: Vec<_> = fields_info
        .iter()
        .filter(|fi| !fi.attrs.read_only && !fi.attrs.skip)
        .map(|fi| fi.ident.to_string())
        .collect();

    // OpenAPI: emit `impl OpenApiSchema` when our `openapi` feature is on.
    // Only includes fields shown in JSON output (skips write_only). For each
    // `Option<T>` field, omit from `required` and add `.nullable()`.
    let openapi_impl = {
        #[cfg(feature = "openapi")]
        {
            let property_calls = output_fields.iter().map(|fi| {
                let ident = &fi.ident;
                let name_lit = ident.to_string();
                let ty = &fi.ty;
                let nullable_call = if is_option(ty) {
                    quote! { .nullable() }
                } else {
                    quote! {}
                };
                quote! {
                    .property(
                        #name_lit,
                        <#ty as ::rustango::openapi::OpenApiSchema>::openapi_schema()
                            #nullable_call,
                    )
                }
            });
            let required_lits: Vec<_> = output_fields
                .iter()
                .filter(|fi| !is_option(&fi.ty))
                .map(|fi| fi.ident.to_string())
                .collect();
            quote! {
                impl ::rustango::openapi::OpenApiSchema for #struct_name {
                    fn openapi_schema() -> ::rustango::openapi::Schema {
                        ::rustango::openapi::Schema::object()
                            #( #property_calls )*
                            .required([ #( #required_lits ),* ])
                    }
                }
            }
        }
        #[cfg(not(feature = "openapi"))]
        {
            quote! {}
        }
    };

    Ok(quote! {
        impl ::rustango::serializer::ModelSerializer for #struct_name {
            type Model = #model_path;

            fn from_model(model: &Self::Model) -> Self {
                Self {
                    #( #from_model_fields ),*
                }
            }

            fn writable_fields() -> &'static [&'static str] {
                &[ #( #writable_lits ),* ]
            }
        }

        impl ::serde::Serialize for #struct_name {
            fn serialize<S>(&self, serializer: S)
                -> ::core::result::Result<S::Ok, S::Error>
            where
                S: ::serde::Serializer,
            {
                use ::serde::ser::SerializeStruct;
                let mut __state = serializer.serialize_struct(
                    #struct_name_lit,
                    #output_field_count,
                )?;
                #( #serialize_fields )*
                __state.end()
            }
        }

        #openapi_impl

        #validate_method

        #many_setters_impl
    })
}

/// Returns true if `ty` looks like `Option<T>` (any path ending in `Option`).
/// Only used by the `openapi`-gated emission of `OpenApiSchema`; muted
/// when the feature is off.
#[cfg_attr(not(feature = "openapi"), allow(dead_code))]
fn is_option(ty: &syn::Type) -> bool {
    if let syn::Type::Path(p) = ty {
        if let Some(last) = p.path.segments.last() {
            return last.ident == "Option";
        }
    }
    false
}