rustango 0.57.8

Django-shaped batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
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
//! Django REST Framework–style router viewsets.
//!
//! A [`ViewSet`] wires five standard REST endpoints for any [`Model`]
//! table in ~5 lines. No hand-written handlers, no SQL, no repetition.
//!
//! ## Quick start
//!
//! ```ignore
//! use rustango::viewset::ViewSet;
//!
//! // In your router setup:
//! let posts_router = ViewSet::for_model(Post::SCHEMA)
//!     .fields(&["id", "title", "body", "author_id", "published_at"])
//!     .filter_fields(&["author_id"])
//!     .search_fields(&["title", "body"])
//!     .ordering(&[("published_at", true)])  // DESC by default
//!     .page_size(20)
//!     .router("/api/posts", pool.clone());
//!
//! // Merge into your app router:
//! let app = Router::new().merge(posts_router);
//! ```
//!
//! ## Endpoints
//!
//! | Method | Path | Action |
//! |---|---|---|
//! | `GET` | `/api/posts` | List — `{"count": N, "results": [...]}` |
//! | `POST` | `/api/posts` | Create — returns the new object |
//! | `GET` | `/api/posts/{pk}` | Retrieve — single object |
//! | `PUT` | `/api/posts/{pk}` | Update — full replace |
//! | `PATCH` | `/api/posts/{pk}` | Partial update — only supplied fields |
//! | `DELETE` | `/api/posts/{pk}` | Delete — `204 No Content` |
//!
//! ## Query parameters (list endpoint)
//!
//! ### Page-number pagination (default)
//!
//! | Parameter | Default | Description |
//! |---|---|---|
//! | `page` | 1 | 1-based page number |
//! | `page_size` | configured default | Items per page (capped at `max_page_size`, default 100) |
//! | `ordering` | configured default | Comma-separated field names, prefix `-` for DESC |
//! | `search` | — | Full-text search across `search_fields` |
//! | `{field}` | — | Exact filter for any `filter_fields` |
//! | `{field}__{lookup}` | — | Django-style lookup (gt/gte/lt/lte/ne/in/not_in/contains/icontains/startswith/istartswith/endswith/iendswith/isnull) |
//!
//! Response: `{"count": N, "page": P, "page_size": S, "last_page": L, "results": [...]}`
//!
//! ### Cursor pagination (opt-in)
//!
//! Enable via `.cursor_pagination("id")` or `.cursor_pagination_desc("id")`.
//! Skips the `COUNT(*)` query so it scales to billion-row tables.
//!
//! | Parameter | Default | Description |
//! |---|---|---|
//! | `cursor` | — | Opaque token from a previous response's `next` field |
//! | `page_size` | configured default | Items per page (capped at `max_page_size`, default 100) |
//! | `{field}` | — | Exact filter for any `filter_fields` |
//!
//! Response: `{"page_size": S, "next": "<token>" \| null, "results": [...]}`
//!
//! ### Limit/offset pagination (opt-in)
//!
//! Enable via `.limit_offset_pagination()`. DRF-shape `?limit=&offset=`
//! windowing — handy for tables/grids that page by row offset rather
//! than page number. Runs `COUNT(*)` per request (same cost as
//! page-number).
//!
//! | Parameter | Default | Description |
//! |---|---|---|
//! | `limit` | configured default | Items to return (capped at `max_page_size`, default 100) |
//! | `offset` | 0 | Rows to skip before the window |
//! | `ordering` | configured default | Comma-separated field names, prefix `-` for DESC |
//! | `search` | — | Full-text search across `search_fields` |
//! | `{field}` | — | Exact filter for any `filter_fields` |
//!
//! Response: `{"count": N, "limit": L, "offset": O, "results": [...]}`
//!
//! ## Permissions
//!
//! Pair with [`RouterAuthExt`](crate::tenancy::middleware::RouterAuthExt)
//! on the outer router to require auth, then pass codenames to `.permissions()`:
//!
//! ```ignore
//! ViewSet::for_model(Post::SCHEMA)
//!     .permissions(ViewSetPerms {
//!         list:     vec!["post.view"],
//!         retrieve: vec!["post.view"],
//!         create:   vec!["post.add"],
//!         update:   vec!["post.change"],
//!         destroy:  vec!["post.delete"],
//!     })
//!     .router("/api/posts", pool.clone())
//! ```

#[cfg(feature = "openapi")]
mod openapi;

use std::collections::HashMap;
use std::future::Future;
#[cfg(feature = "serializer")]
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::time::Instant;

use axum::body::Body;
use axum::extract::{Path, Query, State};
use axum::http::{header, StatusCode};
use axum::response::Response;
use axum::routing::get;
use axum::Router;
use serde_json::{json, Value};

use crate::core::{
    Assignment, CountQuery, DeleteQuery, FieldType, Filter, InsertQuery, ModelSchema, Op,
    SearchClause, SelectQuery, SqlValue, UpdateQuery, WhereExpr,
};
use crate::forms::{collect_values, parse_form_value, parse_pk_string, FormError};
use crate::sql::Pool;

// ------------------------------------------------------------------ Permissions config

/// Permission codenames required for each ViewSet action.
///
/// Any field left as an empty vec means "no permission check" for that action.
#[derive(Clone, Default)]
pub struct ViewSetPerms {
    /// Codenames required to call `GET /` (list).
    pub list: Vec<String>,
    /// Codenames required to call `GET /{pk}` (retrieve).
    pub retrieve: Vec<String>,
    /// Codenames required to call `POST /` (create).
    pub create: Vec<String>,
    /// Codenames required to call `PUT /{pk}` or `PATCH /{pk}` (update).
    pub update: Vec<String>,
    /// Codenames required to call `DELETE /{pk}` (destroy).
    pub destroy: Vec<String>,
}

/// A fixed-window throttle limit — at most `max` requests per
/// `window_secs` (DRF `ScopedRateThrottle` shape, #1010).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ThrottleRule {
    /// Max requests allowed within the window.
    pub max: u32,
    /// Window length in seconds.
    pub window_secs: u64,
}

impl ThrottleRule {
    /// `max` requests per `window_secs` seconds.
    #[must_use]
    pub const fn new(max: u32, window_secs: u64) -> Self {
        Self { max, window_secs }
    }
}

/// Per-action request throttles for a ViewSet (DRF `throttle_classes`
/// parity, #1010). Any action left `None` is unthrottled.
///
/// Counters are **process-local** (per server instance) — same model as
/// [`crate::rate_limit`]. Behind N replicas the effective limit is N×;
/// for a shared limit, front the service with a gateway throttle.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ViewSetThrottle {
    /// Throttle for `GET /` (list).
    pub list: Option<ThrottleRule>,
    /// Throttle for `GET /{pk}` (retrieve).
    pub retrieve: Option<ThrottleRule>,
    /// Throttle for `POST /` (create).
    pub create: Option<ThrottleRule>,
    /// Throttle for `PUT`/`PATCH /{pk}` (update).
    pub update: Option<ThrottleRule>,
    /// Throttle for `DELETE /{pk}` (destroy).
    pub destroy: Option<ThrottleRule>,
}

impl ViewSetThrottle {
    /// Apply the same rule to every action.
    #[must_use]
    pub const fn all(max: u32, window_secs: u64) -> Self {
        let r = Some(ThrottleRule::new(max, window_secs));
        Self {
            list: r,
            retrieve: r,
            create: r,
            update: r,
            destroy: r,
        }
    }

    /// The rule for an action name (`"list"` / `"retrieve"` / `"create"`
    /// / `"update"` / `"destroy"`), if any.
    #[must_use]
    pub fn for_action(&self, action: &str) -> Option<ThrottleRule> {
        match action {
            "list" => self.list,
            "retrieve" => self.retrieve,
            "create" => self.create,
            "update" => self.update,
            "destroy" => self.destroy,
            _ => None,
        }
    }
}

// ------------------------------------------------------------------ ViewSet builder

/// Pagination strategy for ViewSet list endpoints.
#[derive(Clone, Debug)]
pub enum PaginationStyle {
    /// 1-based page numbering — `?page=1&page_size=20`. Returns
    /// `count` + `page` + `last_page` in the response. Cheap when
    /// the table is small; runs `COUNT(*)` per request.
    PageNumber,
    /// Cursor-based pagination — `?cursor=<encoded>&page_size=20`.
    /// `field` must be a stable, monotonically-ordered column
    /// (typically the primary key). Skips the COUNT query, so it
    /// scales to billion-row tables.
    Cursor {
        /// SQL field name used as the cursor (e.g. `"id"`).
        field: &'static str,
        /// `true` for descending order. Cursors compare with `<` instead
        /// of `>`. Default ordering is set automatically to match.
        desc: bool,
    },
    /// DRF-shape limit/offset windowing — `?limit=20&offset=40`. Returns
    /// `count` + `limit` + `offset` in the response. Runs `COUNT(*)` per
    /// request (same cost as [`PaginationStyle::PageNumber`]); pick it
    /// when callers think in row offsets rather than page numbers.
    LimitOffset,
}

impl PaginationStyle {
    /// Default — 1-based page numbering.
    #[must_use]
    pub const fn page_number() -> Self {
        Self::PageNumber
    }

    /// Cursor pagination on the named field, ascending.
    #[must_use]
    pub const fn cursor(field: &'static str) -> Self {
        Self::Cursor { field, desc: false }
    }

    /// Cursor pagination on the named field, descending.
    #[must_use]
    pub const fn cursor_desc(field: &'static str) -> Self {
        Self::Cursor { field, desc: true }
    }

    /// DRF-shape limit/offset pagination.
    #[must_use]
    pub const fn limit_offset() -> Self {
        Self::LimitOffset
    }
}

/// Type-erased bridge that lets a `dyn`-routed [`ViewSet`] render rows
/// through a concrete [`crate::serializer::ModelSerializer`].
///
/// `ViewSet` is stored without its model/serializer type (so a router
/// can hold many of them), so it can't name `S` directly. Instead
/// [`ViewSet::serializer`] boxes a [`Bridge<S>`] behind this trait.
/// When set, list / retrieve / create responses route through the
/// bridge instead of the default field-level `select_rows_as_json`
/// projection, so `method` / `read_only` / `source` / `write_only`
/// overrides all shape the JSON output.
///
/// Tri-dialect (v0.45): the bridge fetches typed `Vec<S::Model>` via
/// [`crate::sql::select_rows_pool_with_related`] — which decodes `T`
/// on Postgres, MySQL **and** SQLite — then maps each model through
/// `S::from_model` + `to_value`. The pre-v0.45 implementation was a
/// `Fn(&PgRow) -> Value` closure, which pinned the feature to Postgres.
trait SerializerBridge: Send + Sync {
    /// Fetch every row matching `q` and render it through the
    /// serializer (replaces the default field-level projection).
    fn render_rows<'a>(
        &'a self,
        acq: &'a mut AcquiredConn,
        q: &'a SelectQuery,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<Value>, crate::sql::ExecError>> + Send + 'a>>;

    /// Fetch the first row matching `q` and render it, or `None`.
    fn render_one<'a>(
        &'a self,
        acq: &'a mut AcquiredConn,
        q: &'a SelectQuery,
    ) -> Pin<Box<dyn Future<Output = Result<Option<Value>, crate::sql::ExecError>> + Send + 'a>>;

    /// Run the serializer's input validation against a JSON request body:
    /// parse the writable fields (DRF read shape) then call the
    /// serializer's `validate()` hook. `Err` carries DRF-shape field
    /// errors for a 400 response.
    fn validate_body(&self, body: &Value) -> Result<(), crate::forms::FormErrors>;

    /// The **model** field names the serializer accepts on write
    /// (`source`-resolved). The write path skips every other model column
    /// so `read_only` / computed fields can't be set by a client.
    fn writable_model_fields(&self) -> &'static [&'static str];

    /// The **serializer** field names of the writable fields — the JSON
    /// keys a client sends (DRF read/write shape). Parallel to
    /// [`Self::writable_model_fields`]; the two differ only where a field
    /// declares `#[serializer(source = "…")]`, which the write path uses
    /// to translate the inbound key to its model column.
    fn writable_field_names(&self) -> &'static [&'static str];
}

/// Zero-sized carrier that pins a concrete serializer type `S` so the
/// type-erased [`SerializerBridge`] trait object can call back into
/// `S::from_model` / `S::Model`'s tri-dialect row decode.
#[cfg(feature = "serializer")]
struct Bridge<S>(PhantomData<S>);

#[cfg(feature = "serializer")]
impl<S> SerializerBridge for Bridge<S>
where
    S: crate::serializer::ModelSerializer + Send + Sync + 'static,
    S::Model: crate::sql::MaybePgFromRow
        + crate::sql::MaybeMyFromRow
        + crate::sql::MaybeSqliteFromRow
        + crate::sql::LoadRelated
        + crate::sql::MaybeMyLoadRelated
        + crate::sql::MaybeSqliteLoadRelated
        + Send
        + Unpin,
{
    fn render_rows<'a>(
        &'a self,
        acq: &'a mut AcquiredConn,
        q: &'a SelectQuery,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<Value>, crate::sql::ExecError>> + Send + 'a>> {
        Box::pin(async move {
            let models = acq.select_rows_typed::<S::Model>(q).await?;
            Ok(models.iter().map(|m| S::from_model(m).to_value()).collect())
        })
    }

    fn render_one<'a>(
        &'a self,
        acq: &'a mut AcquiredConn,
        q: &'a SelectQuery,
    ) -> Pin<Box<dyn Future<Output = Result<Option<Value>, crate::sql::ExecError>> + Send + 'a>>
    {
        Box::pin(async move {
            let models = acq.select_rows_typed::<S::Model>(q).await?;
            Ok(models.first().map(|m| S::from_model(m).to_value()))
        })
    }

    fn validate_body(&self, body: &Value) -> Result<(), crate::forms::FormErrors> {
        // Parse the writable fields into a partial serializer instance
        // (surfacing per-field type errors), then run its validation hook.
        let s = S::from_writable_json(body)?;
        s.validate()
    }

    fn writable_model_fields(&self) -> &'static [&'static str] {
        S::writable_source_fields()
    }

    fn writable_field_names(&self) -> &'static [&'static str] {
        S::writable_fields()
    }
}

/// A pluggable filter backend (DRF `BaseFilterBackend` parity, #1010).
///
/// Registered on a [`ViewSet`] via [`ViewSet::filter_backend`], a backend
/// contributes extra `WHERE` predicates from the list request's query
/// params. Its predicates are `AND`-ed with the built-in exact / lookup
/// filters — use it for what the `filter_fields` surface can't express
/// (a geo-radius, a custom `?q=` DSL, request-scoped row visibility, …).
///
/// Any `Fn(&HashMap<String, String>, &'static ModelSchema) -> Vec<WhereExpr>`
/// is a backend via the blanket impl below, so a closure works directly:
///
/// ```ignore
/// use rustango::core::{Filter, Op, SqlValue, WhereExpr};
/// ViewSet::for_model(Post::SCHEMA)
///     .filter_backend(|params: &HashMap<String, String>, schema| {
///         // hide drafts unless ?include_drafts=1
///         if params.get("include_drafts").map(String::as_str) == Some("1") {
///             return Vec::new();
///         }
///         schema.field("status").map_or_else(Vec::new, |f| {
///             vec![WhereExpr::Predicate(Filter {
///                 column: f.column,
///                 op: Op::Eq,
///                 value: SqlValue::from("published"),
///             })]
///         })
///     })
///     .router_pool("/posts", pool);
/// ```
///
/// Backends run on **every** action: they narrow the list query, and they
/// scope `retrieve` / `update` / `destroy` so a row the backend excludes is a
/// 404 rather than someone else's data. That is DRF's `get_queryset()`
/// contract, and without it an ownership backend would guard the collection
/// while leaving every row reachable by id.
pub trait ViewSetFilter: Send + Sync + 'static {
    /// Return `WHERE` predicates to AND into the query for this request.
    fn filter(
        &self,
        params: &HashMap<String, String>,
        schema: &'static ModelSchema,
    ) -> Vec<WhereExpr>;

    /// As [`Self::filter`], with the request's [`Parts`] in hand.
    ///
    /// The authenticated principal lives in the request extensions, not in the
    /// query string, so "only this user's rows" cannot be written against
    /// `filter` alone. Defaults to [`Self::filter`], so every existing backend
    /// — including the plain closure form — keeps compiling and behaving
    /// exactly as before.
    ///
    /// [`Parts`]: axum::http::request::Parts
    fn filter_with(
        &self,
        _parts: &axum::http::request::Parts,
        params: &HashMap<String, String>,
        schema: &'static ModelSchema,
    ) -> Vec<WhereExpr> {
        self.filter(params, schema)
    }
}

/// Scope every row to the principal that owns it.
///
/// The reusable half of ownership: name the column that holds the owner and
/// mount it. It works on any model with such a column — `owner_id`,
/// `member_id`, `user_id`, `created_by` — and applies to every action, so the
/// collection and the item routes cannot disagree.
///
/// ```no_run
/// # use rustango::viewset::{OwnedBy, ViewSet};
/// # use rustango::core::Model as _;
/// # #[derive(rustango::Model)] #[rustango(table = "note")]
/// # pub struct Note { #[rustango(primary_key)] pub id: rustango::sql::Auto<i64>, pub owner_id: i64 }
/// # fn main() {
/// ViewSet::for_model(Note::SCHEMA)
///     .filter_backend(OwnedBy::column("owner_id"))
///     .tenant_router("/api/notes");
/// # }
/// ```
///
/// The owner comes from [`Principal`], which every auth path populates, so the
/// same backend covers a cookie session, a Bearer token and an agent token
/// without knowing which one ran. It is **never** read from the query string:
/// a client that could name its own `owner_id` is not being authorized.
///
/// Fails closed. No principal ⇒ a contradiction, matching nothing — an
/// unauthenticated request sees an empty list rather than the whole table.
/// Pair it with an auth layer that rejects those requests outright; this is
/// the second line, not the first.
///
/// [`Principal`]: crate::tenancy::Principal
#[cfg(feature = "tenancy")]
#[derive(Clone, Copy, Debug)]
pub struct OwnedBy {
    column: &'static str,
    superuser_sees_all: bool,
}

#[cfg(feature = "tenancy")]
impl OwnedBy {
    /// Scope to `column = <principal's user id>`.
    #[must_use]
    pub const fn column(column: &'static str) -> Self {
        Self {
            column,
            superuser_sees_all: false,
        }
    }

    /// Let superusers read and write every row.
    ///
    /// Off by default: "admins see everything" is a product decision. A
    /// support tool wants it; a gym app where the owner is also a member
    /// emphatically does not.
    #[must_use]
    pub const fn superuser_sees_all(self) -> Self {
        Self {
            superuser_sees_all: true,
            ..self
        }
    }
}

#[cfg(feature = "tenancy")]
impl ViewSetFilter for OwnedBy {
    fn filter(
        &self,
        _params: &HashMap<String, String>,
        schema: &'static ModelSchema,
    ) -> Vec<WhereExpr> {
        // Reached only when something calls the params-only path — no request
        // in hand means no principal, and no principal means no rows.
        vec![match_nothing(schema)]
    }

    fn filter_with(
        &self,
        parts: &axum::http::request::Parts,
        _params: &HashMap<String, String>,
        schema: &'static ModelSchema,
    ) -> Vec<WhereExpr> {
        let Some(principal) = crate::tenancy::Principal::from_parts(parts) else {
            return vec![match_nothing(schema)];
        };
        if self.superuser_sees_all && principal.is_superuser {
            return Vec::new();
        }
        let Some(field) = schema.field(self.column) else {
            // The column named at mount time is not on this model. Denying is
            // the only safe reading of "scope to an owner I cannot find".
            tracing::error!(
                model = schema.table,
                column = self.column,
                "OwnedBy names a column this model does not have — denying every row"
            );
            return vec![match_nothing(schema)];
        };
        vec![WhereExpr::Predicate(Filter {
            column: field.column,
            op: Op::Eq,
            value: SqlValue::from(principal.user_id),
        })]
    }
}

/// A predicate no row satisfies: `col IS NULL AND col IS NOT NULL`.
///
/// A contradiction rather than `1 = 0` because it binds no parameters and
/// every dialect writes it the same way. Used wherever a scoping backend
/// cannot determine the principal — returning *no* predicates there would
/// widen the query to the whole table, which is the failure this exists to
/// prevent.
///
/// This is the fail-closed branch of a [`ViewSetFilter`], so it is public:
/// writing one means having somewhere to go when the principal is absent,
/// and the obvious guess is an empty `Vec`, which is not "match nothing"
/// but "no filter at all" (#1411).
///
/// ```ignore
/// fn filter(&self, _p: &HashMap<String, String>, schema: &'static ModelSchema)
///     -> Vec<WhereExpr>
/// {
///     vec![match_nothing(schema)]   // not `vec![]`
/// }
/// ```
///
/// Returns one `WhereExpr`, so wrap it in `vec![]` where the trait wants a
/// list. Not gated on `tenancy`: `ViewSetFilter` is not either, and a
/// soft-delete or date-window backend needs to fail closed just as much as
/// an ownership one.
pub fn match_nothing(schema: &'static ModelSchema) -> WhereExpr {
    let column = schema
        .primary_key()
        .or_else(|| schema.scalar_fields().next())
        .map_or("id", |f| f.column);
    WhereExpr::And(vec![
        WhereExpr::Predicate(Filter {
            column,
            op: Op::IsNull,
            value: SqlValue::Bool(true),
        }),
        WhereExpr::Predicate(Filter {
            column,
            op: Op::IsNull,
            value: SqlValue::Bool(false),
        }),
    ])
}

impl<F> ViewSetFilter for F
where
    F: Fn(&HashMap<String, String>, &'static ModelSchema) -> Vec<WhereExpr> + Send + Sync + 'static,
{
    fn filter(
        &self,
        params: &HashMap<String, String>,
        schema: &'static ModelSchema,
    ) -> Vec<WhereExpr> {
        self(params, schema)
    }
}

/// Builder for a set of REST CRUD endpoints over a single [`Model`] table.
///
/// Call `.router(prefix, pool)` when done to get an `axum::Router`.
#[derive(Clone)]
pub struct ViewSet {
    schema: &'static ModelSchema,
    fields: Option<Vec<String>>,
    filter_fields: Vec<String>,
    search_fields: Vec<String>,
    /// DRF `ordering_fields` whitelist — when non-empty, only the
    /// listed fields are honored via `?ordering=`. Unknown names get
    /// silently dropped. When empty (the default), any field on the
    /// schema is sortable — the v0.30 behavior. Issue #439.
    ordering_fields: Vec<String>,
    default_page_size: usize,
    default_ordering: Vec<(String, bool)>,
    perms: ViewSetPerms,
    read_only: bool,
    pagination: PaginationStyle,
    /// Pluggable filter backends (#1010) — each contributes extra `WHERE`
    /// predicates on the list action, ANDed with the built-in filters.
    filter_backends: Vec<std::sync::Arc<dyn ViewSetFilter>>,
    /// Per-action request throttles (#1010). Default: unthrottled.
    throttle: ViewSetThrottle,
    /// When set, list / retrieve / create responses render each row
    /// through this serializer bridge instead of the default
    /// field-level projection. Tri-dialect. Wired via
    /// [`Self::serializer`].
    serializer: Option<Arc<dyn SerializerBridge>>,
    /// Largest page a client may request via `?page_size=` / `?limit=`.
    /// Defaults to 100. See [`ViewSet::max_page_size`].
    max_page_size: usize,
    /// Name of the path capture for the detail routes — `pk` by default,
    /// giving `/{pk}`. See [`ViewSet::pk_param`].
    pk_param: String,
}

impl ViewSet {
    /// Start a ViewSet for the given model schema.
    pub fn for_model(schema: &'static ModelSchema) -> Self {
        Self {
            schema,
            fields: None,
            filter_fields: Vec::new(),
            search_fields: Vec::new(),
            ordering_fields: Vec::new(),
            default_page_size: 20,
            default_ordering: Vec::new(),
            perms: ViewSetPerms::default(),
            read_only: false,
            pagination: PaginationStyle::PageNumber,
            filter_backends: Vec::new(),
            throttle: ViewSetThrottle::default(),
            serializer: None,
            max_page_size: 100,
            pk_param: "pk".to_owned(),
        }
    }

    /// Render list / retrieve / create responses through `S` (a
    /// serializer derived via `#[derive(Serializer)]
    /// #[serializer(model = T)]`) instead of the default field-level
    /// projection.
    ///
    /// Apply when you want the ViewSet's JSON shape to match a typed
    /// serializer's `read_only` / `source` / `method` / `nested` /
    /// `many` overrides. The serializer's `Model` associated type must
    /// be the same model the ViewSet is built over.
    ///
    /// Internally boxes a [`Bridge<S>`] behind a [`SerializerBridge`]
    /// trait object so the `ViewSet` itself stays type-erased — a
    /// non-breaking add-on.
    ///
    /// Tri-dialect (v0.45): works on Postgres, MySQL and SQLite. The
    /// render path fetches typed `Vec<S::Model>` via the tri-dialect
    /// `select_rows_pool_with_related` rather than a PG-only
    /// `FromRow<PgRow>` closure.
    ///
    /// Note: `nested` / `many` fields need the related rows a flat
    /// fetch doesn't load unless the ViewSet's query populated them via
    /// `select_related`; those fields render as their `Default` value
    /// otherwise. `method` / `read_only` / `source` / `write_only`
    /// always apply because a real typed model is in hand.
    #[cfg(feature = "serializer")]
    #[must_use]
    pub fn serializer<S>(mut self) -> Self
    where
        S: crate::serializer::ModelSerializer + Send + Sync + 'static,
        S::Model: crate::sql::MaybePgFromRow
            + crate::sql::MaybeMyFromRow
            + crate::sql::MaybeSqliteFromRow
            + crate::sql::LoadRelated
            + crate::sql::MaybeMyLoadRelated
            + crate::sql::MaybeSqliteLoadRelated
            + Send
            + Unpin,
    {
        self.serializer = Some(Arc::new(Bridge::<S>(PhantomData)));
        self
    }

    /// Switch to cursor-based pagination on `field`. This skips the
    /// `COUNT(*)` query that page-number pagination runs, so it scales
    /// well for large tables.
    ///
    /// The field must be a **totally ordered** column: an integer,
    /// timestamp, date, uuid or string. `"id"` is the usual choice; a
    /// `created_at` timestamp is the other common one, and is what you
    /// want on an append-only table.
    ///
    /// # Panics
    ///
    /// If `field` is not on the model, or is of a type that cannot be a
    /// cursor (a float, bool, json or blob). This is a programming
    /// error and it is caught here rather than per request: until
    /// #1459 an unusable field was accepted silently and then returned
    /// **500 on every request**, so a misconfigured ViewSet built fine,
    /// started fine, passed its health check, and served nothing.
    #[must_use]
    pub fn cursor_pagination(mut self, field: &'static str) -> Self {
        self.assert_cursor_field(field);
        self.assert_cursor_is_projected(field);
        self.pagination = PaginationStyle::Cursor { field, desc: false };
        self
    }

    /// Cursor pagination, descending order. Same constraints and same
    /// panics as [`Self::cursor_pagination`].
    #[must_use]
    pub fn cursor_pagination_desc(mut self, field: &'static str) -> Self {
        self.assert_cursor_field(field);
        self.assert_cursor_is_projected(field);
        self.pagination = PaginationStyle::Cursor { field, desc: true };
        self
    }

    /// Fail where the mistake is, not once per request (#1459).
    fn assert_cursor_field(&self, field: &'static str) {
        let table = self.schema.table;
        let Some(f) = self.schema.field(field) else {
            let known: Vec<&str> = self
                .schema
                .fields
                .iter()
                .filter(|f| cursor_field_supported(f.ty))
                .map(|f| f.name)
                .collect();
            panic!(
                "cursor_pagination(\"{field}\"): `{table}` has no field `{field}`. \
                 Usable cursor fields on this model: {known:?}"
            );
        };
        assert!(
            cursor_field_supported(f.ty),
            "cursor_pagination(\"{field}\"): `{table}.{field}` is {:?}, which cannot \
             be a cursor — the value has to round-trip through a token and order \
             totally. Use an integer, timestamp, date, uuid or string column.",
            f.ty
        );
    }

    /// A `.fields([..])` projection must include the cursor column and
    /// the primary key.
    ///
    /// The `next` token is built from the *rendered* row, so a
    /// projection that drops either leaves nothing to encode — and
    /// that is a static fact about the builder, knowable here rather
    /// than once per request. Checked in both directions: from
    /// `fields()` when a cursor is already set, and from
    /// `cursor_pagination()` when the projection is.
    ///
    /// Only `.fields([..])` is covered. A serializer can project the
    /// same column away and `ModelSerializer` exposes no field list to
    /// check against, so that case is still caught at request time —
    /// which is how the commerce soak found `OrderSerializer` omitting
    /// `placed_at` and 500ing on all six instances.
    fn assert_cursor_is_projected(&self, field: &str) {
        let Some(projection) = self.fields.as_ref() else {
            return; // no projection: every column is rendered
        };
        let table = self.schema.table;
        assert!(
            projection.iter().any(|f| f == field),
            "cursor_pagination(\"{field}\") with .fields({projection:?}): the cursor \
             column is projected away, so no `next` token can be built from a rendered \
             row and pagination would stop after one page. Add `{field}` to the field \
             list, or paginate on a field that is in it."
        );
        if let Some(pk) = self.schema.fields.iter().find(|f| f.primary_key) {
            assert!(
                pk.name == field || projection.iter().any(|f| f == pk.name),
                "cursor_pagination(\"{field}\") with .fields({projection:?}): the primary \
                 key `{table}.{}` is projected away. It breaks ties between rows sharing \
                 a `{field}`, and without it a page boundary inside a run of equal values \
                 skips the rest of the run. Add `{}` to the field list.",
                pk.name,
                pk.name
            );
        }
    }

    /// Switch to DRF-shape limit/offset pagination — `?limit=&offset=`.
    /// Like page-number it runs `COUNT(*)` per request, but callers
    /// window by row offset instead of page index.
    #[must_use]
    pub fn limit_offset_pagination(mut self) -> Self {
        self.pagination = PaginationStyle::LimitOffset;
        self
    }

    /// Set the pagination strategy explicitly.
    #[must_use]
    pub fn pagination(mut self, style: PaginationStyle) -> Self {
        self.pagination = style;
        self
    }

    /// Register a pluggable filter backend (DRF `filter_backends` parity,
    /// #1010). Each backend contributes extra `WHERE` predicates on the
    /// list action, ANDed with the built-in `filter_fields`. Call
    /// repeatedly to stack backends; any matching closure works (see
    /// [`ViewSetFilter`]).
    #[must_use]
    pub fn filter_backend(mut self, backend: impl ViewSetFilter) -> Self {
        self.filter_backends.push(std::sync::Arc::new(backend));
        self
    }

    /// Set per-action request throttles (DRF `throttle_classes` parity,
    /// #1010). Counters are process-local — see [`ViewSetThrottle`].
    #[must_use]
    pub fn throttle(mut self, throttle: ViewSetThrottle) -> Self {
        self.throttle = throttle;
        self
    }

    /// Throttle every action to `max` requests per `window_secs`.
    /// Shorthand for `.throttle(ViewSetThrottle::all(max, window_secs))`.
    #[must_use]
    pub fn throttle_all(mut self, max: u32, window_secs: u64) -> Self {
        self.throttle = ViewSetThrottle::all(max, window_secs);
        self
    }

    /// Restrict which fields appear in list/retrieve responses and are
    /// accepted on create/update. Default: all scalar fields.
    pub fn fields(mut self, fields: &[&str]) -> Self {
        self.fields = Some(fields.iter().map(|&s| s.to_owned()).collect());
        // Order-independent: the projection can be narrowed after the
        // cursor is chosen just as easily as before it.
        if let PaginationStyle::Cursor { field, .. } = self.pagination {
            self.assert_cursor_is_projected(field);
        }
        self
    }

    /// Fields that can be filtered via query params (`?field=value`).
    pub fn filter_fields(mut self, fields: &[&str]) -> Self {
        self.filter_fields = fields.iter().map(|&s| s.to_owned()).collect();
        self
    }

    /// Fields searched by the `?search=` query param.
    pub fn search_fields(mut self, fields: &[&str]) -> Self {
        self.search_fields = fields.iter().map(|&s| s.to_owned()).collect();
        self
    }

    /// DRF `ordering_fields` whitelist — when set, only the listed
    /// field names are honored via `?ordering=`. Unknown names are
    /// silently dropped so a hostile client can't sort on a sensitive
    /// column. When unset (the default), any schema field is sortable.
    /// Issue #439.
    pub fn ordering_fields(mut self, fields: &[&str]) -> Self {
        self.ordering_fields = fields.iter().map(|&s| s.to_owned()).collect();
        self
    }

    /// Default page size for list responses (default: 20).
    ///
    /// This is the size used when the client asks for none. What a client may
    /// *request* is bounded separately by [`ViewSet::max_page_size`], and the
    /// effective size is clamped to that bound at request time — so the order
    /// of these two builder calls doesn't matter.
    pub fn page_size(mut self, n: usize) -> Self {
        self.default_page_size = n.max(1);
        self
    }

    /// Largest page a client may request via `?page_size=` / `?limit=`
    /// (default: 100).
    ///
    /// The ceiling used to be a hard-coded 1000 with no way to lower it, so an
    /// app that sized its serializer, joins and response budget around
    /// `page_size(20)` could still be asked for 1000 rows by any client — a
    /// 50× amplification. If the serializer does per-row work that touches the
    /// database, that is an N+1 turning into a thousand queries in a single
    /// request (#1196).
    ///
    /// The default matches `template_views`' ceiling, so the framework's two
    /// pagination surfaces now agree. Raise it deliberately when a consumer
    /// genuinely needs bigger pages:
    ///
    /// ```ignore
    /// ViewSet::for_model(Post::SCHEMA).page_size(20).max_page_size(500)
    /// ```
    #[must_use]
    pub fn max_page_size(mut self, n: usize) -> Self {
        self.max_page_size = n.max(1);
        self
    }

    /// Default ordering for list responses. `(field, true)` = descending.
    pub fn ordering(mut self, ordering: &[(&str, bool)]) -> Self {
        self.default_ordering = ordering.iter().map(|&(f, d)| (f.to_owned(), d)).collect();
        self
    }

    /// Permission codenames required per action. Empty vec = allow all.
    pub fn permissions(mut self, perms: ViewSetPerms) -> Self {
        self.perms = perms;
        self
    }

    /// Auto-fill `ViewSetPerms` with the four standard CRUD codenames
    /// for `T` (`<table>.view` / `<table>.add` / `<table>.change` /
    /// `<table>.delete`), routed through the v0.16.0 typed
    /// permissions facade ([`crate::permissions::codename_for`]).
    ///
    /// `list` + `retrieve` get `view`; `create` gets `add`; `update`
    /// gets `change`; `destroy` gets `delete`. Mirrors Django's
    /// `DjangoModelPermissions` shape — the convention every Django
    /// app starts with.
    ///
    /// Use [`Self::permissions`] for fully-custom codenames or
    /// non-CRUD actions. Requires the `tenancy` feature (the
    /// underlying `has_perm` engine lives there).
    #[cfg(feature = "tenancy")]
    pub fn permissions_for_model<T: crate::core::Model>(mut self) -> Self {
        let cn = |action: &str| crate::permissions::codename_for::<T>(action);
        self.perms = ViewSetPerms {
            list: vec![cn("view")],
            retrieve: vec![cn("view")],
            create: vec![cn("add")],
            update: vec![cn("change")],
            destroy: vec![cn("delete")],
        };
        self
    }

    /// Rename the detail routes' path capture. Defaults to `pk`, i.e.
    /// `/{pk}`.
    ///
    /// axum allows only **one** capture name per path position across a
    /// router, so a hand-written route mounted beside a ViewSet that spells
    /// the same position differently — `/{id}`, `/{token}` — panics at
    /// startup, and the panic points at axum rather than at the ViewSet.
    /// Rather than forcing every neighbouring route to adopt `pk`, match the
    /// ViewSet to them:
    ///
    /// ```ignore
    /// ViewSet::for_model(Post::SCHEMA).pk_param("id").router("/api/posts", pool)
    /// // detail routes become /api/posts/{id}
    /// ```
    ///
    /// The handlers read the capture positionally, so only the route string
    /// and the generated OpenAPI parameter change.
    ///
    /// Note that a capture cannot share a segment with a literal, so an
    /// AIP-style `/{token}:accept` is not expressible; use `/{token}/accept`.
    #[must_use]
    pub fn pk_param(mut self, name: impl Into<String>) -> Self {
        self.pk_param = name.into();
        self
    }

    /// The configured detail-route capture name (`pk` unless
    /// [`ViewSet::pk_param`] changed it).
    #[must_use]
    pub fn pk_param_name(&self) -> &str {
        &self.pk_param
    }

    /// Allow GET only — wires list + retrieve, skips create/update/destroy.
    pub fn read_only(mut self) -> Self {
        self.read_only = true;
        self
    }

    /// Build and return an `axum::Router` mounted at `prefix`. The
    /// pool is baked at mount time — every request uses the same
    /// `&PgPool`. For tenancy projects use [`Self::tenant_router`]
    /// instead so each request resolves its own tenant connection.
    ///
    /// The prefix may or may not end with `/` — both `/api/posts` and
    /// `/api/posts/` work identically.
    #[cfg(feature = "postgres")]
    pub fn router(self, prefix: &str, pool: crate::sql::sqlx::PgPool) -> Router {
        Self::router_with_source(self, prefix, PoolSource::Static(pool))
    }

    /// v0.38 — tri-dialect counterpart of [`Self::router`] that
    /// accepts the backend-erasing [`crate::sql::Pool`] enum. Sqlite/
    /// MySQL projects use this; PG projects can still use either.
    pub fn router_pool(self, prefix: &str, pool: crate::sql::Pool) -> Router {
        Self::router_with_source(self, prefix, PoolSource::StaticPool(pool))
    }

    /// Build a router that resolves the database connection per
    /// request via the [`crate::extractors::Tenant`] extractor —
    /// the right shape for multi-tenant projects (subdomain / schema /
    /// per-tenant database). Each handler runs against the connection
    /// for whichever tenant the request resolves to.
    ///
    /// Mount on the API router that the `Server::Builder` (or
    /// `Cli::tenancy()`) wires up; both inject the
    /// [`TenantContext`](crate::extractors::TenantContext) extension
    /// the extractor reads from.
    ///
    /// ```ignore
    /// use rustango::viewset::ViewSet;
    ///
    /// let posts_router = ViewSet::for_model(Post::SCHEMA)
    ///     .filter_fields(&["author_id"])
    ///     .search_fields(&["title", "body"])
    ///     .ordering(&[("published_at", true)])
    ///     .tenant_router("/api/posts");
    ///
    /// // In `urls::api()`:
    /// axum::Router::new().merge(posts_router)
    /// ```
    ///
    /// Permission checks (when configured via [`Self::permissions`] /
    /// [`Self::permissions_for_model`]) run against the same per-request
    /// connection — no second pool acquire.
    ///
    /// **Note on list-endpoint parallelism (v0.30 behavior change)**:
    /// pre-v0.30 the static-pool list endpoint ran SELECT + COUNT in
    /// parallel via `tokio::join!`. v0.30 unified both pool-source
    /// paths on the same handler, which serializes the two queries —
    /// tenant mode can't `join!` because `Tenant::conn()` hands out
    /// an exclusive `&mut PgConnection`, and unifying the code path
    /// keeps the handler simple. In practice two short queries on
    /// one connection are usually faster than two pool round-trips
    /// anyway, so the regression is bounded; latency-sensitive
    /// callers can opt out of the page-number COUNT entirely with
    /// [`Self::cursor_pagination`].
    #[cfg(feature = "tenancy")]
    #[must_use]
    pub fn tenant_router(self, prefix: &str) -> Router {
        Self::router_with_source(self, prefix, PoolSource::Tenant)
    }

    fn router_with_source(self, prefix: &str, pool_source: PoolSource) -> Router {
        let state = Arc::new(ViewSetState {
            pool_source,
            vs: self.clone(),
            throttle_store: Arc::new(Mutex::new(HashMap::new())),
        });
        let prefix = prefix.trim_end_matches('/').to_owned();
        let collection = prefix.clone();
        let item = format!("{prefix}/{{{}}}", self.pk_param);

        let collection_route = if self.read_only {
            get(handle_list)
        } else {
            get(handle_list).post(handle_create)
        };
        // RFC 10008 QUERY collection action (#1112) — same filtered list as
        // GET, criteria in the body. Gated on `admin` since the QUERY
        // routing shim lives in the `admin`-gated `http_query` module; a
        // `tenancy`-only ViewSet build keeps GET/POST without QUERY.
        #[cfg(feature = "admin")]
        let collection_route = {
            use crate::http_query::QueryRouterExt as _;
            collection_route.query(handle_query)
        };

        let item_route = if self.read_only {
            axum::routing::MethodRouter::new().get(handle_retrieve)
        } else {
            axum::routing::MethodRouter::new()
                .get(handle_retrieve)
                .put(handle_update)
                .patch(handle_partial_update)
                .delete(handle_destroy)
        };

        Router::new()
            .route(&collection, collection_route)
            .route(&item, item_route)
            .with_state(state)
    }
}

// ------------------------------------------------------------------ Internal state

/// Source of the database pool for a [`ViewSet`]. `Static` carries an
/// owned [`PgPool`] (the legacy `router(prefix, pool)` path); `Tenant`
/// is a marker that defers resolution to per-request [`Tenant`]
/// extraction (the v0.30 [`ViewSet::tenant_router`] path).
#[derive(Clone)]
enum PoolSource {
    /// PG-typed static pool (back-compat for the `router(prefix, &PgPool)` path).
    #[cfg(feature = "postgres")]
    Static(crate::sql::sqlx::PgPool),
    /// Backend-erasing static pool — accepts any dialect; used by
    /// `router_pool(prefix, &Pool)`.
    StaticPool(crate::sql::Pool),
    /// Tenant mode — each handler resolves a connection via the
    /// [`crate::extractors::Tenant`] extractor at request time. We
    /// can't bake a `&PgPool` because schema-mode tenants need
    /// per-connection `SET search_path` setup, which only the
    /// `TenantPools::acquire` path provides.
    #[cfg(feature = "tenancy")]
    Tenant,
}

#[derive(Clone)]
struct ViewSetState {
    pool_source: PoolSource,
    vs: ViewSet,
    /// Process-local fixed-window throttle counters, keyed by
    /// `{table}:{action}:{client}`. Shared across requests via the
    /// `Arc<ViewSetState>` the router holds. `#1010`.
    throttle_store: Arc<Mutex<HashMap<String, (u32, Instant)>>>,
}

/// A per-request connection handle that abstracts over static-pool
/// and per-request-tenant modes. Constructed by
/// [`ViewSetState::acquire`] near the top of each handler; the
/// returned wrapper exposes `select_rows` / `count_rows` /
/// `insert_returning` / `update` / `delete` / `has_perm` facade
/// methods so handler bodies stay free of pool-source branching.
/// v0.38 — `Pool` enum wraps either the static-mode pool or the
/// tenant-scoped pool yielded by `Tenant<DB>::pool()`. Schema-mode
/// PG tenants go through the search-path-bound pool that
/// `TenantPools::scoped_pool_dyn` builds; database-mode tenants
/// (any backend) clone the cached pool.
struct AcquiredConn {
    pool: Pool,
    /// Kept alive so PG schema-mode connections aren't released
    /// before the handler is done.
    #[cfg(feature = "tenancy")]
    #[allow(dead_code)]
    _tenant: Option<Box<crate::extractors::Tenant>>,
}

impl AcquiredConn {
    async fn select_rows_as_json(
        &mut self,
        q: &SelectQuery,
        fields: &[&'static crate::core::FieldSchema],
    ) -> Result<Vec<Value>, crate::sql::ExecError> {
        crate::sql::select_rows_as_json(&self.pool, q, fields).await
    }

    async fn count_rows(&mut self, q: &CountQuery) -> Result<i64, crate::sql::ExecError> {
        crate::sql::count_rows_pool(&self.pool, q).await
    }

    async fn select_one_as_json(
        &mut self,
        q: &SelectQuery,
        fields: &[&'static crate::core::FieldSchema],
    ) -> Result<Option<Value>, crate::sql::ExecError> {
        let mut rows = crate::sql::select_rows_as_json(&self.pool, q, fields).await?;
        Ok(rows.pop())
    }

    /// Tri-dialect typed fetch — decode every row matching `q` into
    /// `T` (the model struct) on Postgres, MySQL **or** SQLite. Used by
    /// the serializer render path ([`SerializerBridge`]); mirrors
    /// [`Self::select_rows_as_json`] but yields typed models instead of
    /// the field-level JSON projection. Goes through `&self.pool`, so
    /// it inherits the same tenant-scoping the JSON projection has.
    #[cfg(feature = "serializer")]
    async fn select_rows_typed<T>(
        &mut self,
        q: &SelectQuery,
    ) -> Result<Vec<T>, crate::sql::ExecError>
    where
        T: crate::sql::MaybePgFromRow
            + crate::sql::MaybeMyFromRow
            + crate::sql::MaybeSqliteFromRow
            + crate::sql::LoadRelated
            + crate::sql::MaybeMyLoadRelated
            + crate::sql::MaybeSqliteLoadRelated
            + Send
            + Unpin,
    {
        crate::sql::select_rows_pool_with_related::<T>(&self.pool, q).await
    }

    /// Insert a row and return the primary-key value of the new row
    /// (per-backend: PG/SQLite use RETURNING, MySQL uses
    /// LAST_INSERT_ID()).
    async fn insert_returning_pk(
        &mut self,
        q: &InsertQuery,
        pk_field: &crate::core::FieldSchema,
    ) -> Result<SqlValue, crate::sql::ExecError> {
        let returning = crate::sql::insert_returning_pool(&self.pool, q).await?;
        Ok(pk_from_returning(returning, pk_field))
    }
}

/// Decode the primary key out of an INSERT's RETURNING (or MySQL's
/// `LAST_INSERT_ID()`). Shared by the single-row path and the
/// transactional bulk path, which get the same enum from
/// `insert_returning_pool` / `insert_returning_tx`.
fn pk_from_returning(
    returning: crate::sql::InsertReturningPool,
    pk_field: &crate::core::FieldSchema,
) -> SqlValue {
    #[allow(unused_variables)]
    {
        match returning {
            #[cfg(feature = "postgres")]
            crate::sql::InsertReturningPool::PgRow(row) => {
                use crate::sql::sqlx::Row as _;
                match pk_field.ty {
                    FieldType::I64 => SqlValue::I64(row.try_get(pk_field.column).unwrap_or(0)),
                    FieldType::I32 => SqlValue::I32(row.try_get(pk_field.column).unwrap_or(0)),
                    FieldType::I16 => SqlValue::I16(row.try_get(pk_field.column).unwrap_or(0)),
                    FieldType::String => {
                        SqlValue::String(row.try_get(pk_field.column).unwrap_or_default())
                    }
                    _ => SqlValue::Null,
                }
            }
            #[cfg(feature = "mysql")]
            crate::sql::InsertReturningPool::MySqlAutoId(id) => match pk_field.ty {
                FieldType::I64 => SqlValue::I64(id),
                FieldType::I32 => SqlValue::I32(id as i32),
                FieldType::I16 => SqlValue::I16(id as i16),
                _ => SqlValue::I64(id),
            },
            #[cfg(feature = "sqlite")]
            crate::sql::InsertReturningPool::SqliteRow(row) => {
                use crate::sql::sqlx::Row as _;
                match pk_field.ty {
                    FieldType::I64 => SqlValue::I64(row.try_get(pk_field.column).unwrap_or(0)),
                    FieldType::I32 => SqlValue::I32(row.try_get(pk_field.column).unwrap_or(0)),
                    FieldType::I16 => SqlValue::I16(row.try_get(pk_field.column).unwrap_or(0)),
                    FieldType::String => {
                        SqlValue::String(row.try_get(pk_field.column).unwrap_or_default())
                    }
                    _ => SqlValue::Null,
                }
            }
        }
    }
}

impl AcquiredConn {
    async fn update(&mut self, q: &UpdateQuery) -> Result<u64, crate::sql::ExecError> {
        crate::sql::update_pool(&self.pool, q).await
    }

    async fn delete(&mut self, q: &DeleteQuery) -> Result<u64, crate::sql::ExecError> {
        crate::sql::delete_pool(&self.pool, q).await
    }

    #[cfg(feature = "tenancy")]
    async fn has_perm(&mut self, uid: i64, codename: &str) -> bool {
        crate::tenancy::permissions::has_perm_pool(uid, codename, &self.pool)
            .await
            .unwrap_or(false)
    }
}

impl ViewSetState {
    fn effective_fields(&self) -> Vec<&'static crate::core::FieldSchema> {
        let schema = self.vs.schema;
        match &self.vs.fields {
            Some(names) => names.iter().filter_map(|n| schema.field(n)).collect(),
            None => schema.scalar_fields().collect(),
        }
    }

    /// Acquire a per-request connection / pool handle. For static-pool
    /// mode this is a cheap clone; for tenant mode this runs the
    /// resolver chain + acquires a connection from the right tenant
    /// pool. Errors return a fully-formed [`Response`] (with the
    /// appropriate status code) rather than a typed error so handlers
    /// can `?`-bubble straight to the client.
    // Only the `PoolSource::Tenant` arm reads `parts` (it runs the tenant
    // resolver chain), and that arm is `tenancy`-gated — so an admin-only
    // build has an unused parameter it cannot rename (#1208).
    #[cfg_attr(not(feature = "tenancy"), allow(unused_variables))]
    async fn acquire(
        &self,
        parts: &mut axum::http::request::Parts,
    ) -> Result<AcquiredConn, Response> {
        match &self.pool_source {
            #[cfg(feature = "postgres")]
            PoolSource::Static(pool) => Ok(AcquiredConn {
                pool: Pool::from(pool.clone()),
                #[cfg(feature = "tenancy")]
                _tenant: None,
            }),
            PoolSource::StaticPool(pool) => Ok(AcquiredConn {
                pool: pool.clone(),
                #[cfg(feature = "tenancy")]
                _tenant: None,
            }),
            #[cfg(feature = "tenancy")]
            PoolSource::Tenant => {
                use axum::response::IntoResponse as _;
                // v0.38 — annotate the generic param so multi-backend
                // builds (e.g. `--features postgres,sqlite`) infer
                // `Tenant<DefaultTenantDb>` instead of erroring on
                // ambiguous type inference.
                let t = <crate::extractors::Tenant<
                    crate::tenancy::DefaultTenantDb,
                > as axum::extract::FromRequestParts<()>>::from_request_parts(parts, &())
                    .await
                    .map_err(|e| e.into_response())?;
                let pool = t.pool().clone();
                Ok(AcquiredConn {
                    pool,
                    _tenant: Some(Box::new(t)),
                })
            }
        }
    }

    /// Permission gate. Skips the check when `codenames` is empty.
    /// Reads the request's `AuthenticatedUser` extension; superusers
    /// short-circuit to allow. Falls through to the
    /// `tenancy::permissions::has_perm_on` engine.
    async fn check_perm(
        &self,
        codenames: &[String],
        parts: &axum::http::request::Parts,
        conn: &mut AcquiredConn,
    ) -> PermOutcome {
        if codenames.is_empty() {
            return PermOutcome::Allow;
        }
        #[cfg(feature = "tenancy")]
        {
            let Some(auth) = parts
                .extensions
                .get::<crate::tenancy::middleware::AuthenticatedUser>()
            else {
                // No principal at all — the client needs to authenticate,
                // which is 401, not 403 (#1193).
                return PermOutcome::Unauthenticated;
            };
            if auth.is_superuser {
                return PermOutcome::Allow;
            }
            for cn in codenames {
                if conn.has_perm(auth.id, cn).await {
                    return PermOutcome::Allow;
                }
            }
            PermOutcome::Forbidden
        }
        #[cfg(not(feature = "tenancy"))]
        {
            // Without tenancy there's no AuthenticatedUser extension and no
            // has_perm engine, so codenames present + no engine means we
            // conservatively deny. Deliberately 403, NOT 401: no amount of
            // authenticating can satisfy a check with no engine behind it,
            // and answering 401 would send a token client into exactly the
            // futile refresh loop this issue set out to remove (#1193).
            let _ = (parts, conn);
            PermOutcome::Forbidden
        }
    }

    fn pk_field(&self) -> Option<&'static crate::core::FieldSchema> {
        self.vs.schema.primary_key()
    }
}

// ------------------------------------------------------------------ Serialization

/// Build a JSON response with `status` and `body`. The 3-line
/// `Response::builder()` chain repeated verbatim in [`json_response`]
/// / [`json_created`] / [`json_error`] now lives here (#808 part 7).
fn json_with_status(status: StatusCode, body: Value) -> Response {
    Response::builder()
        .status(status)
        .header(header::CONTENT_TYPE, "application/json")
        .body(Body::from(body.to_string()))
        .unwrap()
}

/// Re-export of the shared row-to-JSON helper. Lives in
fn json_response(body: Value) -> Response {
    json_with_status(StatusCode::OK, body)
}

fn json_error(status: StatusCode, msg: &str) -> Response {
    json_with_status(status, json!({ "error": msg }))
}

/// `400` from serializer validation, DRF shape:
/// `{"<field>": ["msg", …], …, "non_field_errors": [ … ]}`.
fn json_form_errors(errs: &crate::forms::FormErrors) -> Response {
    let mut map = serde_json::Map::new();
    for (field, msgs) in errs.fields() {
        map.insert(field.clone(), json!(msgs));
    }
    if !errs.non_field().is_empty() {
        map.insert("non_field_errors".to_owned(), json!(errs.non_field()));
    }
    json_with_status(StatusCode::BAD_REQUEST, Value::Object(map))
}

/// When a serializer is registered, validate the JSON request body (if
/// present) through it and compute the extra model fields to skip on
/// write — every column the serializer doesn't accept (`read_only` /
/// computed). Returns the 400 response on a validation failure so the
/// caller can short-circuit. No-op (`Ok(vec![])`) without a serializer.
/// Translate inbound form keys from serializer field names to model
/// columns for any `#[serializer(source = "…")]`-renamed **writable**
/// field, so a client POSTs the serializer field name (DRF shape) — e.g.
/// `content` for a field declared `#[serializer(source = "body")]` — and
/// the persist step (which reads model columns) still finds the value.
///
/// Returns `None` when nothing needs renaming (no serializer, or no
/// renamed writable key present in the body) — the common case, so no
/// allocation. Otherwise returns a remapped clone of the form.
fn serializer_input_renamed_form(
    state: &ViewSetState,
    form: &HashMap<String, String>,
) -> Option<HashMap<String, String>> {
    let bridge = state.vs.serializer.as_ref()?;
    // `writable_field_names()` (JSON keys) and `writable_model_fields()`
    // (model columns) are parallel; they differ only at `source` renames.
    let renames: Vec<(&'static str, &'static str)> = bridge
        .writable_field_names()
        .iter()
        .zip(bridge.writable_model_fields().iter())
        .filter(|(name, col)| name != col && form.contains_key(**name))
        .map(|(name, col)| (*name, *col))
        .collect();
    if renames.is_empty() {
        return None;
    }
    let mut out = form.clone();
    for (name, col) in renames {
        if let Some(v) = out.remove(name) {
            // Don't clobber an explicit model-column key if a client sent both.
            out.entry(col.to_owned()).or_insert(v);
        }
    }
    Some(out)
}

/// The name the API publishes for a model field, when a `source` rename
/// gave it a different one.
///
/// The inverse of [`serializer_input_renamed_form`]. Parse errors are
/// raised against model fields, because that is what the write loop
/// walks — so without this a `source = "body"` rename tells the client to
/// supply `body`, a column their schema never mentions (#1386).
fn serializer_public_field_name(state: &ViewSetState, model_field: &str) -> Option<&'static str> {
    let bridge = state.vs.serializer.as_ref()?;
    bridge
        .writable_field_names()
        .iter()
        .zip(bridge.writable_model_fields().iter())
        .find(|(name, col)| **col == model_field && *name != *col)
        .map(|(name, _)| *name)
}

/// Re-render a form error against the names the API publishes.
///
/// Only the field name moves; the wording is untouched, so a client that
/// was matching on the message still matches.
fn public_form_error(state: &ViewSetState, e: FormError) -> FormError {
    match e {
        FormError::Missing { field } => FormError::Missing {
            field: serializer_public_field_name(state, &field).map_or(field, ToOwned::to_owned),
        },
        FormError::Parse {
            field,
            ty,
            value,
            detail,
        } => FormError::Parse {
            field: serializer_public_field_name(state, &field).map_or(field, ToOwned::to_owned),
            ty,
            value,
            detail,
        },
        // Names a primary key, which no serializer renames. Matched by
        // name rather than `_` so a new variant has to be considered
        // here instead of silently leaking a model column.
        other @ FormError::UnsupportedPk { .. } => other,
    }
}

fn serializer_write_prep(
    state: &ViewSetState,
    json: Option<&Value>,
) -> Result<Vec<&'static str>, Response> {
    match &state.vs.serializer {
        Some(bridge) => {
            if let Some(body) = json {
                if let Err(errs) = bridge.validate_body(body) {
                    return Err(json_form_errors(&errs));
                }
            }
            let writable = bridge.writable_model_fields();
            let extra_skip = state
                .vs
                .schema
                .scalar_fields()
                .map(|f| f.name)
                .filter(|n| !writable.contains(n))
                .collect();
            Ok(extra_skip)
        }
        None => Ok(Vec::new()),
    }
}

/// Unwrap-or-return-500. Collapses the `match expr { Ok(v) => v,
/// Err(e) => return json_error(INTERNAL_SERVER_ERROR, &e.to_string()) }`
/// shape that recurred ~5× in handler bodies. Issue #808 (item 4).
///
/// `$expr` must yield `Result<_, E>` where `E: ::std::fmt::Display`
/// — covers every error type used in the viewset (`ExecError`,
/// `String`, `QueryError`, etc.).
macro_rules! or_500 {
    ($expr:expr) => {
        match $expr {
            ::core::result::Result::Ok(v) => v,
            ::core::result::Result::Err(e) => {
                return json_error(
                    ::axum::http::StatusCode::INTERNAL_SERVER_ERROR,
                    &::std::string::ToString::to_string(&e),
                );
            }
        }
    };
}

/// Unwrap-or-return-400. Sibling of [`or_500`]; collapses the
/// `match expr { Ok(v) => v, Err(e) => return json_error(BAD_REQUEST,
/// &e.to_string()) }` shape. Issue #808 (item 4).
macro_rules! or_400 {
    ($expr:expr) => {
        match $expr {
            ::core::result::Result::Ok(v) => v,
            ::core::result::Result::Err(e) => {
                return json_error(
                    ::axum::http::StatusCode::BAD_REQUEST,
                    &::std::string::ToString::to_string(&e),
                );
            }
        }
    };
}

/// Common entry preamble shared by every REST handler — closes
/// item 1 of #808. Splits the inbound `Request` into `(parts, body)`,
/// resolves a connection via the [`PoolSource`] chain (per-tenant or
/// static), then enforces the per-action permission codenames. On
/// failure returns a fully-formed [`Response`] (401 / 403 / 5xx)
/// ready for the handler to `?`-bubble.
///
/// Handlers that don't need the body bind it as `_body` and ignore
/// it; the helper still returns the body so write paths
/// (`handle_create`, `update_inner`) can consume it after the
/// permission gate.
/// Predicates every backend contributes for this request, ANDed into
/// whatever query the action is about to run.
fn scope_filters(
    state: &ViewSetState,
    parts: &axum::http::request::Parts,
    params: &HashMap<String, String>,
) -> Vec<WhereExpr> {
    state
        .vs
        .filter_backends
        .iter()
        .flat_map(|b| b.filter_with(parts, params, state.vs.schema))
        .collect()
}

/// `expr` narrowed by `extra`. An empty `extra` returns `expr` untouched, so
/// a ViewSet with no backends builds the same SQL it always did.
fn narrow(expr: WhereExpr, extra: Vec<WhereExpr>) -> WhereExpr {
    if extra.is_empty() {
        return expr;
    }
    let mut all = vec![expr];
    all.extend(extra);
    WhereExpr::And(all)
}

/// Outcome of a per-action permission check.
///
/// Three-valued on purpose: "no principal" and "principal without the
/// permission" are different answers to the client. Collapsing them to a
/// single bool is what produced a 403 for anonymous requests (#1193).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PermOutcome {
    /// Authorised — proceed.
    Allow,
    /// No authenticated principal → `401`.
    ///
    /// Only the permission engine constructs this, and that lives behind
    /// `tenancy`; without it every denial is a `Forbidden` by design, so the
    /// variant is legitimately unconstructed rather than dead (#1208).
    #[cfg_attr(not(feature = "tenancy"), allow(dead_code))]
    Unauthenticated,
    /// Authenticated, but lacks every required codename → `403`.
    Forbidden,
}

async fn enter(
    state: &Arc<ViewSetState>,
    req: axum::extract::Request,
    codenames: &[String],
    action: &'static str,
) -> Result<(axum::http::request::Parts, Body, AcquiredConn), Response> {
    let (mut parts, body) = req.into_parts();
    // #1010 — per-action throttle is checked before acquiring a
    // connection, so throttled requests shed load early.
    if let Some(resp) = check_throttle(state, action, &parts) {
        return Err(resp);
    }
    let mut acq = state.acquire(&mut parts).await?;
    match state.check_perm(codenames, &parts, &mut acq).await {
        PermOutcome::Allow => {}
        // 401 means "authenticate", 403 means "you cannot do this". A token
        // client treats 401 as its cue to refresh; answering 403 to an
        // anonymous request means the refresh never fires and the member is
        // silently logged out (#1193).
        PermOutcome::Unauthenticated => {
            return Err(json_error(
                StatusCode::UNAUTHORIZED,
                "authentication required",
            ))
        }
        PermOutcome::Forbidden => {
            return Err(json_error(StatusCode::FORBIDDEN, "permission denied"))
        }
    }
    Ok((parts, body, acq))
}

/// Per-action fixed-window throttle (#1010). Returns `Some(429)` when the
/// client has exceeded the action's [`ThrottleRule`] within its window,
/// else `None`. Counters are process-local (see [`ViewSetThrottle`]).
fn check_throttle(
    state: &ViewSetState,
    action: &str,
    parts: &axum::http::request::Parts,
) -> Option<Response> {
    let rule = state.vs.throttle.for_action(action)?;
    let client = client_key(parts);
    let key = format!("{}:{}:{}", state.vs.schema.table, action, client);
    let now = Instant::now();
    let window = std::time::Duration::from_secs(rule.window_secs);

    // A poisoned mutex means a prior panic mid-update; fail open rather
    // than reject every subsequent request.
    let mut store = match state.throttle_store.lock() {
        Ok(g) => g,
        Err(_) => return None,
    };
    let entry = store.entry(key).or_insert((0, now));
    if now.duration_since(entry.1) >= window {
        *entry = (0, now); // window elapsed → reset
    }
    entry.0 += 1;
    if entry.0 > rule.max {
        let retry = window
            .checked_sub(now.duration_since(entry.1))
            .map_or(1, |d| d.as_secs().max(1));
        return Some(throttled_response(retry));
    }
    None
}

/// Best-effort client identity for throttle keying: the peer IP from
/// `ConnectInfo` when the server installed it, else the first
/// `X-Forwarded-For` / `X-Real-IP` hop, else a shared `"global"` bucket
/// (coarse but safe). #1010.
fn client_key(parts: &axum::http::request::Parts) -> String {
    if let Some(ci) = parts
        .extensions
        .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
    {
        return ci.0.ip().to_string();
    }
    for h in ["x-forwarded-for", "x-real-ip"] {
        if let Some(first) = parts
            .headers
            .get(h)
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.split(',').next())
            .map(str::trim)
            .filter(|s| !s.is_empty())
        {
            return first.to_owned();
        }
    }
    "global".to_owned()
}

/// A `429 Too Many Requests` with a `Retry-After` header (#1010).
fn throttled_response(retry_after_secs: u64) -> Response {
    Response::builder()
        .status(StatusCode::TOO_MANY_REQUESTS)
        .header(header::CONTENT_TYPE, "application/json")
        .header(header::RETRY_AFTER, retry_after_secs.to_string())
        .body(Body::from(
            json!({ "error": "request throttled" }).to_string(),
        ))
        .unwrap()
}

/// #808 — was repeated verbatim in `handle_retrieve` / `update_inner`
/// / `handle_destroy` (the three item-route handlers). Each spelled
/// out the same `match parse_pk_string(field, raw) { Ok(v) => v, Err(e)
/// => return json_error(400, &e.to_string()) }` pattern. Factored
/// out so the handler bodies focus on what they're doing.
fn parse_pk_or_400(
    field: &'static crate::core::FieldSchema,
    raw: &str,
) -> Result<crate::core::SqlValue, Response> {
    parse_pk_string(field, raw).map_err(|e| json_error(StatusCode::BAD_REQUEST, &e.to_string()))
}

/// #808 — was repeated verbatim ×4: `handle_retrieve`, `handle_create`,
/// `update_inner`, `handle_destroy` all do the same
/// `let Some(pk_field) = state.pk_field() else { return json_error(500,
/// "model has no primary key") }`. Factored so the calling handlers
/// shrink to the `?` form.
fn pk_field_or_500(state: &ViewSetState) -> Result<&'static crate::core::FieldSchema, Response> {
    state.pk_field().ok_or_else(|| {
        json_error(
            StatusCode::INTERNAL_SERVER_ERROR,
            "model has no primary key",
        )
    })
}

fn json_created(body: Value) -> Response {
    json_with_status(StatusCode::CREATED, body)
}

fn no_content() -> Response {
    Response::builder()
        .status(StatusCode::NO_CONTENT)
        .body(Body::empty())
        .unwrap()
}

/// Build a `WhereExpr` from one query-param `field[__lookup]=value` entry.
///
/// Supported Django-style lookups:
/// - (none) / `exact` — `Op::Eq`
/// - `gt`, `gte`, `lt`, `lte`, `ne`
/// - `in` / `not_in` — comma-separated values
/// - `contains` (LIKE %v%) / `icontains` (ILIKE %v%)
/// - `startswith` (LIKE v%) / `istartswith` (ILIKE v%)
/// - `endswith` (LIKE %v) / `iendswith` (ILIKE %v)
/// - `isnull` — value `"true"` / `"false"`
fn build_lookup_filter(
    field: &'static crate::core::FieldSchema,
    lookup: Option<&str>,
    raw: &str,
) -> Option<WhereExpr> {
    let column = field.column;
    let predicate =
        |op: Op, value: SqlValue| Some(WhereExpr::Predicate(Filter { column, op, value }));
    // The escaped-LIKE builder: escapes the user value and pairs it with
    // the matching `*Escaped` op in one place (#1257), so no arm can
    // combine an escaped value with a plain `Op::Like` (or vice versa).
    let escaped_like = |prefix: &str, suffix: &str, raw: &str, case_insensitive: bool| {
        let escaped = crate::core::escape_like(raw);
        let op = if case_insensitive {
            Op::ILikeEscaped
        } else {
            Op::LikeEscaped
        };
        predicate(op, SqlValue::String(format!("{prefix}{escaped}{suffix}")))
    };
    // #808 part 6 — six binary-comparison arms had byte-identical
    // bodies modulo the `Op` constant. Map the lookup token to its
    // `Op`, parse once, branch once.
    let binary_op = match lookup.unwrap_or("exact") {
        "exact" => Some(Op::Eq),
        "ne" => Some(Op::Ne),
        "gt" => Some(Op::Gt),
        "gte" => Some(Op::Gte),
        "lt" => Some(Op::Lt),
        "lte" => Some(Op::Lte),
        _ => None,
    };
    if let Some(op) = binary_op {
        return parse_form_value(field, Some(raw))
            .ok()
            .and_then(|v| predicate(op, v));
    }
    match lookup.unwrap_or("exact") {
        "in" | "not_in" => {
            let parts: Vec<SqlValue> = raw
                .split(',')
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .filter_map(|s| parse_form_value(field, Some(s)).ok())
                .collect();
            if parts.is_empty() {
                return None;
            }
            let op = if lookup == Some("not_in") {
                Op::NotIn
            } else {
                Op::In
            };
            predicate(op, SqlValue::List(parts))
        }
        // Escape LIKE metacharacters in `raw` (URL-supplied) so `%`/`_`
        // match literally, and pair with the *Escaped ops so the ESCAPE
        // clause is emitted — required for correctness on SQLite
        // (#1257). One helper owns the escape⟷op pairing so a future
        // arm cannot mismatch them.
        "contains" => escaped_like("%", "%", raw, false),
        "icontains" => escaped_like("%", "%", raw, true),
        "startswith" => escaped_like("", "%", raw, false),
        "istartswith" => escaped_like("", "%", raw, true),
        "endswith" => escaped_like("%", "", raw, false),
        "iendswith" => escaped_like("%", "", raw, true),
        "isnull" => {
            let is_null = matches!(raw.to_ascii_lowercase().as_str(), "true" | "1" | "yes");
            predicate(Op::IsNull, SqlValue::Bool(is_null))
        }
        _ => None, // unknown lookup → silently ignore
    }
}

// ------------------------------------------------------------------ Handlers

async fn handle_list(
    State(state): State<Arc<ViewSetState>>,
    Query(params): Query<HashMap<String, String>>,
    req: axum::extract::Request,
) -> Response {
    let (parts, _body, acq) = match enter(&state, req, &state.vs.perms.list, "list").await {
        Ok(x) => x,
        Err(resp) => return resp,
    };
    run_list(state, params, acq, &parts).await
}

/// Core `list` logic shared by the GET `list` action and the RFC 10008
/// QUERY action (#1112): builds filters / search / ordering / pagination
/// from `params` and renders the paginated envelope. `params` arrive from
/// the querystring on GET and from the request body on QUERY, so the two
/// transports return byte-identical results for equivalent criteria.
async fn run_list(
    state: Arc<ViewSetState>,
    params: HashMap<String, String>,
    mut acq: AcquiredConn,
    parts: &axum::http::request::Parts,
) -> Response {
    // Clamp to the ViewSet's own ceiling, not a hard-coded 1000 (#1196). The
    // default page size is clamped too, so a `page_size` larger than
    // `max_page_size` can't smuggle a bigger page through the default path.
    let page_size: i64 = params
        .get("page_size")
        .and_then(|p| p.parse().ok())
        .unwrap_or(state.vs.default_page_size as i64)
        .min(state.vs.max_page_size as i64)
        .max(1);

    // Build WHERE from filter_fields in query params.
    //
    // Supports both:
    //   ?author_id=42                — exact match (Op::Eq)
    //   ?author_id__gt=10            — Django-style lookup
    //   ?status__in=draft,published  — comma-separated for IN/NOT_IN
    //   ?title__icontains=hello      — pattern lookups
    //   ?published_at__isnull=true   — IS NULL / IS NOT NULL
    let mut filters: Vec<WhereExpr> = Vec::new();
    for (param_key, raw_val) in &params {
        // #809 — was a hand-spelled `matches!` reserved-key check
        // that had drifted from template_views's copy. Route through
        // `list_params::is_reserved_list_key` (single source of truth).
        if crate::list_params::is_reserved_list_key(param_key) {
            continue;
        }
        let (field_name, lookup) = match param_key.split_once("__") {
            Some((name, lk)) => (name, Some(lk)),
            None => (param_key.as_str(), None),
        };
        if !state.vs.filter_fields.iter().any(|f| f == field_name) {
            continue;
        }
        let Some(field) = state.vs.schema.field(field_name) else {
            continue;
        };
        if let Some(predicate) = build_lookup_filter(field, lookup, raw_val) {
            filters.push(predicate);
        }
    }

    // #1010 — pluggable filter backends contribute extra predicates,
    // ANDed with the built-in filter_fields parsed above.
    filters.extend(scope_filters(&state, parts, &params));

    let where_clause = if filters.len() == 1 {
        filters.remove(0)
    } else if filters.is_empty() {
        WhereExpr::And(vec![])
    } else {
        WhereExpr::And(filters)
    };

    // Search
    let search = params.get("search").filter(|s| !s.is_empty()).cloned();
    let search_clause = search.map(|q| SearchClause {
        query: q,
        columns: state
            .vs
            .search_fields
            .iter()
            .filter_map(|n| state.vs.schema.field(n).map(|f| f.column))
            .collect(),
    });

    // Ordering — #439 honors the DRF `ordering_fields` whitelist when
    // set: only listed field names are sortable via `?ordering=`. An
    // empty whitelist (the default) keeps the v0.30 behavior of
    // allowing any schema field. Unknown / off-whitelist names are
    // silently dropped (mirrors DRF's defensive default — a hostile
    // client can't sort on `password_hash` just because it's a column).
    // #809 — was a hand-rolled `-`-prefix split + allowlist filter +
    // schema-field lookup. Route through `list_params::parse_ordering`
    // (single source of truth shared with template_views::ListView).
    // #1282 — with no explicit `ordering_fields`, fall back to the fields
    // this ViewSet actually *exposes* rather than every column on the
    // model. The comment above described this protection, but an empty
    // allowlist skipped the check entirely, so a ViewSet declaring
    // `fields = "id, title"` still honoured `?ordering=password_hash` —
    // a sort oracle over a column the API never returns. DRF defaults to
    // the serializer's readable fields for the same reason. When `fields`
    // is unset, `effective_fields` is every scalar column, so the
    // permissive behaviour is retained exactly where it is harmless.
    let ordering_allowlist: Vec<String> = if state.vs.ordering_fields.is_empty() {
        state
            .effective_fields()
            .iter()
            .map(|f| f.name.to_owned())
            .collect()
    } else {
        state.vs.ordering_fields.clone()
    };
    let order_by: Vec<crate::core::OrderItem> = params
        .get("ordering")
        .map(|raw| crate::list_params::parse_ordering(raw, &ordering_allowlist, state.vs.schema))
        .filter(|v| !v.is_empty())
        .unwrap_or_else(|| {
            state
                .vs
                .default_ordering
                .iter()
                .filter_map(|(name, desc)| {
                    state
                        .vs
                        .schema
                        .field(name)
                        .map(|f| crate::core::OrderItem::column(f.column, *desc))
                })
                .collect()
        });

    let fields = state.effective_fields();

    match &state.vs.pagination {
        PaginationStyle::PageNumber => {
            let page: i64 = params
                .get("page")
                .and_then(|p| p.parse().ok())
                .unwrap_or(1)
                .max(1);
            let offset = (page - 1) * page_size;

            // #562 — struct-update over SelectQuery::new for the
            // paginated list query.
            let select_q = SelectQuery {
                where_clause: where_clause.clone(),
                search: search_clause.clone(),
                order_by: order_by.clone(),
                limit: Some(page_size),
                offset: Some(offset),
                ..SelectQuery::new(state.vs.schema)
            };
            let count_q = CountQuery {
                model: state.vs.schema,
                where_clause,
                search: search_clause.clone(),
            };

            // Tenant mode holds a single per-request connection, so
            // the two queries serialize. Static mode could parallelize
            // via `tokio::join!`, but unifying on the sequential path
            // keeps the handler simple — two short queries on the
            // same connection are typically faster than two pool
            // round-trips anyway.
            // `render_list` renders through the registered serializer
            // (typed tri-dialect fetch) when one is set, else falls
            // back to the default field-level `select_rows_as_json`
            // projection — both dialect-agnostic.
            let results = or_500!(render_list(&state, &mut acq, &select_q, &fields).await);
            let count = or_500!(acq.count_rows(&count_q).await);
            let last_page = ((count - 1).max(0) / page_size) + 1;
            json_response(json!({
                "count": count,
                "page": page,
                "page_size": page_size,
                "last_page": last_page,
                "results": results,
            }))
        }
        PaginationStyle::Cursor {
            field: cursor_field,
            desc,
        } => {
            handle_list_cursor(
                state.as_ref(),
                &mut acq,
                params,
                where_clause,
                search_clause,
                fields,
                page_size,
                cursor_field,
                *desc,
            )
            .await
        }
        PaginationStyle::LimitOffset => {
            // `?limit=` overrides the default page size; `?offset=` skips
            // rows. Same `COUNT(*)` cost as page-number pagination.
            // Same ceiling as `?page_size=` — otherwise limit/offset would be
            // an unbounded way around it (#1196).
            let limit: i64 = params
                .get("limit")
                .and_then(|p| p.parse().ok())
                .unwrap_or(page_size)
                .min(state.vs.max_page_size as i64)
                .max(1);
            let offset: i64 = params
                .get("offset")
                .and_then(|p| p.parse().ok())
                .unwrap_or(0)
                .max(0);

            let select_q = SelectQuery {
                where_clause: where_clause.clone(),
                search: search_clause.clone(),
                order_by,
                limit: Some(limit),
                offset: Some(offset),
                ..SelectQuery::new(state.vs.schema)
            };
            let count_q = CountQuery {
                model: state.vs.schema,
                where_clause,
                search: search_clause,
            };
            let results = or_500!(render_list(&state, &mut acq, &select_q, &fields).await);
            let count = or_500!(acq.count_rows(&count_q).await);
            json_response(json!({
                "count": count,
                "limit": limit,
                "offset": offset,
                "results": results,
            }))
        }
    }
}

/// RFC 10008 QUERY action on the collection (#1112) — the same filtered,
/// paginated `list`, but with the criteria in the request body instead of
/// the querystring. A ViewSet gets this for free (no trait method to
/// implement); `QUERY /things` with body `status=draft&ordering=-created`
/// returns exactly what `GET /things?status=draft&ordering=-created`
/// would. Permissions / throttles reuse the `list` codenames via `enter`.
#[cfg(feature = "admin")]
async fn handle_query(
    State(state): State<Arc<ViewSetState>>,
    req: axum::extract::Request,
) -> Response {
    // `enter` returns the body unconsumed (it only reads `parts` for
    // throttle + permission checks), so we can parse params from it here.
    let (parts, body, acq) = match enter(&state, req, &state.vs.perms.list, "query").await {
        Ok(x) => x,
        Err(resp) => return resp,
    };
    let params = match parse_query_body_params(&parts, body).await {
        Ok(p) => p,
        Err(resp) => return resp,
    };
    run_list(state, params, acq, &parts).await
}

/// Parse a QUERY request body into the same `HashMap<String, String>`
/// param shape `run_list` consumes for GET. Dispatches on `Content-Type`:
/// urlencoded (or none) via the querystring codepath, JSON objects flattened
/// to string values (scalars stringified, arrays comma-joined so
/// `{"status__in":["a","b"]}` matches `status__in=a,b`), anything else 415.
#[cfg(feature = "admin")]
async fn parse_query_body_params(
    parts: &axum::http::request::Parts,
    body: Body,
) -> Result<HashMap<String, String>, Response> {
    const CAP: usize = 1 << 20;
    let essence = parts
        .headers
        .get(axum::http::header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("")
        .split(';')
        .next()
        .unwrap_or("")
        .trim()
        .to_ascii_lowercase();
    let bytes = match axum::body::to_bytes(body, CAP).await {
        Ok(b) => b,
        Err(_) => {
            return Err(json_error(
                StatusCode::PAYLOAD_TOO_LARGE,
                "QUERY body too large",
            ))
        }
    };

    if essence == "application/json" || essence.ends_with("+json") {
        let value: Value = serde_json::from_slice(&bytes).map_err(|e| {
            json_error(
                StatusCode::UNPROCESSABLE_ENTITY,
                &format!("invalid JSON QUERY body: {e}"),
            )
        })?;
        let Value::Object(obj) = value else {
            return Err(json_error(
                StatusCode::UNPROCESSABLE_ENTITY,
                "QUERY JSON body must be an object of criteria",
            ));
        };
        Ok(obj
            .iter()
            .map(|(k, v)| (k.clone(), json_value_to_param(v)))
            .collect())
    } else if essence.is_empty() || essence == "application/x-www-form-urlencoded" {
        serde_urlencoded::from_bytes::<HashMap<String, String>>(&bytes)
            .map_err(|e| json_error(StatusCode::BAD_REQUEST, &format!("invalid QUERY body: {e}")))
    } else {
        Err(json_error(
            StatusCode::UNSUPPORTED_MEDIA_TYPE,
            "QUERY body must be application/x-www-form-urlencoded or application/json",
        ))
    }
}

/// Flatten a JSON value to the string form `run_list`'s filter parser
/// expects: strings verbatim, arrays comma-joined (for `__in` lookups),
/// null → empty, numbers / bools via their JSON text.
#[cfg(feature = "admin")]
fn json_value_to_param(v: &Value) -> String {
    match v {
        Value::String(s) => s.clone(),
        Value::Array(items) => items
            .iter()
            .map(json_value_to_param)
            .collect::<Vec<_>>()
            .join(","),
        Value::Null => String::new(),
        other => other.to_string(),
    }
}

async fn handle_list_cursor(
    state: &ViewSetState,
    acq: &mut AcquiredConn,
    params: HashMap<String, String>,
    where_clause: WhereExpr,
    search_clause: Option<SearchClause>,
    fields: Vec<&'static crate::core::FieldSchema>,
    page_size: i64,
    cursor_field: &str,
    desc: bool,
) -> Response {
    // Resolve cursor field schema
    let Some(cursor_schema) = state.vs.schema.field(cursor_field) else {
        return json_error(
            StatusCode::INTERNAL_SERVER_ERROR,
            &format!("cursor field `{cursor_field}` not found on model"),
        );
    };
    if !cursor_field_supported(cursor_schema.ty) {
        // Still a 500, because it is a server-side misconfiguration
        // rather than anything the caller did — but the set of usable
        // types is much wider now, and `cursor_pagination()` panics at
        // build time on an unusable one, so reaching this at request
        // time takes a `pagination(PaginationStyle::Cursor { .. })`
        // constructed by hand (#1459).
        return json_error(
            StatusCode::INTERNAL_SERVER_ERROR,
            &format!(
                "cursor pagination needs a totally-ordered column; `{cursor_field}` is \
                 {:?}, which does not round-trip through a cursor token. Use an \
                 integer, timestamp, date, uuid or string column.",
                cursor_schema.ty
            ),
        );
    }

    // The primary key breaks ties. A cursor column that is *not* unique
    // — any timestamp, and #1459 made those legal — puts equal values on
    // both sides of a page boundary, and a strict `>` on the column
    // alone then skips every tied row after the first. Ordering by
    // `(col, pk)` and comparing the pair makes the position total.
    //
    // Skipped when the cursor *is* the primary key, which is the
    // pre-#1459 case and already unique.
    let pk_schema = state.vs.schema.fields.iter().find(|f| f.primary_key);
    let tiebreak = pk_schema.filter(|pk| pk.column != cursor_schema.column);

    // Decode the incoming cursor (if any)
    let cursor_pos: Option<(SqlValue, Option<SqlValue>)> = match params.get("cursor") {
        Some(c) if !c.is_empty() => {
            let pk_ty = tiebreak.map_or(cursor_schema.ty, |pk| pk.ty);
            match decode_cursor(c, cursor_schema.ty, pk_ty) {
                Some(v) => Some(v),
                None => return json_error(StatusCode::BAD_REQUEST, "invalid cursor"),
            }
        }
        _ => None,
    };

    // Build WHERE = filters AND (cursor predicate, if any)
    let final_where = match cursor_pos {
        Some((v, pk_v)) => {
            let op = if desc { Op::Lt } else { Op::Gt };
            let cursor_pred = match (tiebreak, pk_v) {
                // `col > v OR (col = v AND pk > pk_v)` — strictly after
                // the last row of the previous page, ties included.
                (Some(pk), Some(pk_v)) => WhereExpr::Or(vec![
                    WhereExpr::Predicate(Filter {
                        column: cursor_schema.column,
                        op,
                        value: v.clone(),
                    }),
                    WhereExpr::And(vec![
                        WhereExpr::Predicate(Filter {
                            column: cursor_schema.column,
                            op: Op::Eq,
                            value: v,
                        }),
                        WhereExpr::Predicate(Filter {
                            column: pk.column,
                            op,
                            value: pk_v,
                        }),
                    ]),
                ]),
                // No tiebreak: the cursor is the PK, or the token is a
                // pre-#1459 one that carries no pk component.
                _ => WhereExpr::Predicate(Filter {
                    column: cursor_schema.column,
                    op,
                    value: v,
                }),
            };
            match where_clause {
                WhereExpr::And(v) if v.is_empty() => cursor_pred,
                WhereExpr::And(mut v) => {
                    v.push(cursor_pred);
                    WhereExpr::And(v)
                }
                other => WhereExpr::And(vec![other, cursor_pred]),
            }
        }
        None => where_clause,
    };

    // Order by the cursor field, then the tiebreaker — the ORDER BY has
    // to match the comparison above or the "strictly after" is a lie.
    let mut order_by = vec![crate::core::OrderItem::column(cursor_schema.column, desc)];
    if let Some(pk) = tiebreak {
        order_by.push(crate::core::OrderItem::column(pk.column, desc));
    }

    // #562 — struct-update over SelectQuery::new for the cursor-
    // paginated SELECT. Fetch page_size+1 to detect if a next page
    // exists.
    let select_q = SelectQuery {
        where_clause: final_where,
        search: search_clause,
        order_by,
        limit: Some(page_size + 1),
        ..SelectQuery::new(state.vs.schema)
    };
    let rows = or_500!(render_list(state, acq, &select_q, &fields).await);

    let has_more = rows.len() as i64 > page_size;
    let page_rows: &[Value] = if has_more {
        &rows[..page_size as usize]
    } else {
        &rows[..]
    };

    let next_cursor = if has_more {
        // Read the cursor field value from the last JSON row.
        let last = page_rows.last().expect("non-empty page");
        // The tiebreaker travels in the token. If the PK is projected
        // away the position cannot be made total, and issuing a
        // value-only token would quietly reintroduce the row-skipping
        // this exists to prevent — so it is reported, like a missing
        // cursor column.
        let pk_part = match tiebreak {
            Some(pk) => match cursor_value_of(last, pk.name) {
                Some(v) => Some(v),
                None => {
                    return json_error(
                        StatusCode::INTERNAL_SERVER_ERROR,
                        &format!(
                            "cursor pagination on `{}` needs the primary key `{}` in the \
                             rendered rows to break ties, and it is not projected. Two rows \
                             sharing a `{}` would otherwise be split across a page boundary \
                             and all but one skipped. Include `{}` in `.fields([..])` / the \
                             serializer.",
                            cursor_schema.name, pk.name, cursor_schema.name, pk.name,
                        ),
                    );
                }
            },
            None => None,
        };
        match cursor_value_of(last, cursor_schema.name) {
            Some(v) => Some(encode_cursor(&v, pk_part.as_deref())),
            // The cursor column is not in the rendered row — almost
            // always `.fields([...])` (or a serializer) projecting it
            // away. Answering `next: null` here would be **silent
            // truncation**: `has_more` is true, the caller sees a page
            // with no continuation token, and pagination stops at page
            // one with nothing reporting an error. Say so instead.
            None => {
                return json_error(
                    StatusCode::INTERNAL_SERVER_ERROR,
                    &format!(
                        "cursor field `{}` is not present in the rendered rows, so no \
                         `next` token can be issued and pagination would silently stop \
                         after one page. Include it in `.fields([..])` / the \
                         serializer, or paginate on a field that is projected.",
                        cursor_schema.name
                    ),
                );
            }
        }
    } else {
        None
    };

    let results: Vec<Value> = page_rows.to_vec();
    json_response(json!({
        "page_size": page_size,
        "next": next_cursor,
        "results": results,
    }))
}

/// Can this column be a cursor?
///
/// Cursor pagination needs a **totally ordered** column whose value
/// round-trips through a string. Integers qualify, and so do timestamps,
/// dates, UUIDs and strings — the last two because monotonic ids
/// (`UUIDv7`, ULID) are a common cursor and sort correctly in SQL.
///
/// What is excluded is excluded for a reason: floats do not round-trip
/// exactly, `Json` / `Binary` / `Array` have no useful total order, and
/// `Bool` has too few values to page by.
///
/// Before #1459 this list was `I16 | I32 | I64` only, and a
/// non-integer field was not rejected where it was *configured* — it
/// was accepted by `cursor_pagination()` and then returned 500 on every
/// request, forever, while the docs described "a stable,
/// monotonically-ordered column (typically `id`)". A `TIMESTAMPTZ
/// created_at` is exactly that, and is the canonical cursor in the DRF
/// API this one is shaped after.
pub(crate) fn cursor_field_supported(ty: FieldType) -> bool {
    matches!(
        ty,
        FieldType::I16
            | FieldType::I32
            | FieldType::I64
            | FieldType::DateTime
            | FieldType::Date
            | FieldType::Uuid
            | FieldType::String
    )
}

/// Encode a cursor position as URL-safe base64.
///
/// `tiebreak` is the row's primary key, carried alongside the cursor
/// value whenever the cursor column is not itself the primary key.
/// Without it a page boundary that lands on a run of equal values drops
/// every row in that run but one: the next page asks for `col > v`, and
/// the rest of the tied rows are `= v`. That was latent while cursors
/// had to be integers (in practice the unique PK); #1459 widened them to
/// timestamps and strings, where ties are ordinary — a `bulk_insert`, or
/// Postgres' per-transaction `now()`.
///
/// Composite tokens are a two-element JSON array; a bare value is the
/// pre-#1459 form. [`decode_cursor`] reads both, so a client paginating
/// across an upgrade keeps working.
fn encode_cursor(value: &str, tiebreak: Option<&str>) -> String {
    use base64::Engine;
    let payload = match tiebreak {
        Some(pk) => serde_json::json!([value, pk]).to_string(),
        None => value.to_owned(),
    };
    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(payload.as_bytes())
}

/// Decode a cursor token into a bind value of the cursor column's type.
///
/// Returns `None` for malformed input, which the caller turns into a
/// 400 — a bad cursor is the client's, unlike the 500 a misconfigured
/// cursor *field* used to produce.
fn decode_cursor(
    token: &str,
    ty: FieldType,
    pk_ty: FieldType,
) -> Option<(SqlValue, Option<SqlValue>)> {
    use base64::Engine;
    let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
        .decode(token.as_bytes())
        .ok()?;
    let s = std::str::from_utf8(&bytes).ok()?;

    // Composite form first: `["<value>", "<pk>"]`. A pre-#1459 token is
    // a bare value, and a bare value that happens to parse as JSON (an
    // integer cursor does) is not a two-element array of strings, so
    // the two forms cannot be confused.
    if let Some([a, b]) = serde_json::from_str::<Vec<String>>(s)
        .ok()
        .filter(|v| v.len() == 2)
        .as_deref()
    {
        return Some((
            parse_cursor_scalar(a, ty)?,
            Some(parse_cursor_scalar(b, pk_ty)?),
        ));
    }
    Some((parse_cursor_scalar(s, ty)?, None))
}

/// One cursor component, parsed per the column's type.
fn parse_cursor_scalar(s: &str, ty: FieldType) -> Option<SqlValue> {
    match ty {
        FieldType::I16 | FieldType::I32 | FieldType::I64 => {
            s.parse::<i64>().ok().map(SqlValue::I64)
        }
        FieldType::DateTime => chrono::DateTime::parse_from_rfc3339(s)
            .ok()
            .map(|dt| SqlValue::DateTime(dt.with_timezone(&chrono::Utc))),
        FieldType::Date => chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d")
            .ok()
            .map(SqlValue::Date),
        FieldType::Uuid => s.parse::<uuid::Uuid>().ok().map(SqlValue::Uuid),
        FieldType::String => Some(SqlValue::String(s.to_owned())),
        _ => None,
    }
}

/// The string form of a rendered row's cursor column, for the `next`
/// token.
///
/// Reads the JSON the list endpoint already produced rather than
/// re-querying: an integer arrives as a number, everything else as a
/// string, and the two cases are the whole of it.
fn cursor_value_of(row: &Value, field_name: &str) -> Option<String> {
    let v = row.get(field_name)?;
    v.as_i64()
        .map(|n| n.to_string())
        .or_else(|| v.as_str().map(std::borrow::ToOwned::to_owned))
}

async fn handle_retrieve(
    State(state): State<Arc<ViewSetState>>,
    Path(pk_raw): Path<String>,
    req: axum::extract::Request,
) -> Response {
    let (parts, _body, mut acq) =
        match enter(&state, req, &state.vs.perms.retrieve, "retrieve").await {
            Ok(x) => x,
            Err(resp) => return resp,
        };

    let pk_field = match pk_field_or_500(&state) {
        Ok(f) => f,
        Err(resp) => return resp,
    };
    let pk_val = match parse_pk_or_400(pk_field, &pk_raw) {
        Ok(v) => v,
        Err(resp) => return resp,
    };

    // #562 — was 11-field struct literal; SelectQuery::by_pk constructs
    // the single-PK-lookup shape directly.
    let mut select_q = SelectQuery::by_pk(state.vs.schema, pk_field.column, pk_val);
    // …narrowed by the filter backends, so a row this principal may not see
    // reads as absent rather than forbidden — a 403 would confirm the id.
    let scope = scope_filters(&state, &parts, &HashMap::new());
    select_q.where_clause = narrow(select_q.where_clause, scope);

    let fields = state.effective_fields();
    match render_single(&state, &mut acq, &select_q, &fields).await {
        Ok(Some(row)) => json_response(row),
        Ok(None) => json_error(StatusCode::NOT_FOUND, "not found"),
        Err(e) => json_error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
    }
}

async fn handle_create(
    State(state): State<Arc<ViewSetState>>,
    req: axum::extract::Request,
) -> Response {
    let (parts, body, mut acq) = match enter(&state, req, &state.vs.perms.create, "create").await {
        Ok(x) => x,
        Err(resp) => return resp,
    };

    // #435 — sniff for bulk shape (JSON array body) and dispatch.
    let create_body = or_400!(extract_create_body(parts, body).await);

    let skip: Vec<&str> = state
        .vs
        .schema
        .scalar_fields()
        .filter(|f| f.primary_key || f.auto)
        .map(|f| f.name)
        .collect();

    let pk_field = match pk_field_or_500(&state) {
        Ok(f) => f,
        Err(resp) => return resp,
    };

    match create_body {
        CreateBody::Single(form, json) => {
            create_one(&state, &mut acq, &form, json.as_ref(), &skip, pk_field).await
        }
        CreateBody::Bulk(rows) => create_many(&state, &mut acq, &rows, &skip, pk_field).await,
    }
}

/// Build the `InsertQuery`, run `INSERT … RETURNING <pk>`, then
/// re-fetch the row by its PK as a JSON object — the
/// `create_one` ↔ `create_many` shared insert→fetch tail. Issue #808
/// (item 5).
///
/// Returns `(StatusCode, message)` on the two distinct failure modes
/// so both callers can re-emit the right HTTP code:
/// * `BAD_REQUEST` when the INSERT itself fails (constraint violation,
///   bad value, etc. — likely client fault).
/// * `INTERNAL_SERVER_ERROR` when the INSERT succeeds but the re-fetch
///   misses (a row vanishing between INSERT and SELECT is a server-
///   side anomaly).
///
/// `columns` / `values` come from a prior `collect_values` step so
/// the caller has already validated the inbound form / JSON shape.
async fn insert_and_fetch_one(
    state: &Arc<ViewSetState>,
    acq: &mut AcquiredConn,
    columns: Vec<&'static str>,
    values: Vec<SqlValue>,
    pk_field: &'static crate::core::FieldSchema,
    fields: &[&'static crate::core::FieldSchema],
) -> Result<Value, (StatusCode, String)> {
    let query = InsertQuery {
        model: state.vs.schema,
        columns,
        values,
        returning: vec![pk_field.column],
        on_conflict: None,
    };
    let pk_val = acq
        .insert_returning_pk(&query, pk_field)
        .await
        .map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;
    fetch_by_pk(state, acq, pk_field, pk_val, fields)
        .await
        .ok_or_else(|| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                "created but could not retrieve".to_owned(),
            )
        })
}

/// Single-row create — used by both the form-urlencoded codepath
/// and the JSON-object body codepath. Returns 201 + the row JSON.
async fn create_one(
    state: &Arc<ViewSetState>,
    acq: &mut AcquiredConn,
    form: &HashMap<String, String>,
    json: Option<&Value>,
    skip: &[&str],
    pk_field: &'static crate::core::FieldSchema,
) -> Response {
    // When a serializer is registered: run its input validation and
    // skip every model column it doesn't accept (read_only / computed).
    let extra_skip = match serializer_write_prep(state, json) {
        Ok(s) => s,
        Err(resp) => return resp,
    };
    let mut all_skip: Vec<&str> = skip.to_vec();
    all_skip.extend(extra_skip);
    // Translate `source`-renamed writable keys (serializer field name →
    // model column) so the client can POST the serializer field name.
    let renamed = serializer_input_renamed_form(state, form);
    let form = renamed.as_ref().unwrap_or(form);
    let collected = match collect_values(state.vs.schema, form, &all_skip) {
        Ok(v) => v,
        Err(e) => {
            return json_error(
                StatusCode::BAD_REQUEST,
                &public_form_error(state, e).to_string(),
            )
        }
    };
    let (columns, values): (Vec<_>, Vec<_>) = collected.into_iter().unzip();
    let fields = state.effective_fields();
    match insert_and_fetch_one(state, acq, columns, values, pk_field, &fields).await {
        Ok(obj) => json_created(obj),
        Err((code, msg)) => json_error(code, &msg),
    }
}

/// Bulk create — Django DRF `ListSerializer(many=True)` shape.
/// Validates every entry first; on first failure, the WHOLE bulk
/// is rejected with the index + message (atomic-validate, not
/// atomic-insert — partial-insert recovery is a separate concern).
/// On success, inserts each row sequentially and returns 201 + the
/// JSON array of created rows in submission order.
///
/// Issue #435.
async fn create_many(
    state: &Arc<ViewSetState>,
    acq: &mut AcquiredConn,
    rows: &[(HashMap<String, String>, Option<Value>)],
    skip: &[&str],
    pk_field: &'static crate::core::FieldSchema,
) -> Response {
    if rows.is_empty() {
        return json_created(Value::Array(Vec::new()));
    }

    // Atomic validation: collect every (columns, values) up front
    // so a bad row near the end of the list doesn't leave half the
    // INSERTs committed. DRF's default ListSerializer.create has
    // the same shape — validate the whole list before any save.
    let mut prepared: Vec<(Vec<&'static str>, Vec<SqlValue>)> = Vec::with_capacity(rows.len());
    for (i, (row, json)) in rows.iter().enumerate() {
        // Serializer validation + non-writable skip, per entry.
        let extra_skip = match serializer_write_prep(state, json.as_ref()) {
            Ok(s) => s,
            Err(resp) => return resp,
        };
        let mut all_skip: Vec<&str> = skip.to_vec();
        all_skip.extend(extra_skip);
        let renamed = serializer_input_renamed_form(state, row);
        let row = renamed.as_ref().unwrap_or(row);
        let collected = match collect_values(state.vs.schema, row, &all_skip) {
            Ok(v) => v,
            Err(e) => {
                let e = public_form_error(state, e);
                return json_error(StatusCode::BAD_REQUEST, &format!("bulk entry {i}: {e}"));
            }
        };
        prepared.push(collected.into_iter().unzip());
    }

    // Insert sequentially. We loop INSERT-RETURNING rather than
    // emitting one multi-row INSERT because:
    //
    // 1. Per-row PK extraction stays straightforward (one returning
    //    row per call, no fan-out parsing).
    // 2. The framework's `bulk_insert_pool` path is typed-model-
    //    shaped; this dynamic-JSON codepath doesn't have a typed
    //    handle to feed it.
    // 3. Most ListSerializer.create callers are submitting tens of
    //    rows, not millions. A real high-volume bulk endpoint
    //    should mount its own custom handler with bulk_insert_pool.
    //
    // The trade-off: N round-trips per request. We document
    // accordingly in the issue + viewset docs.
    //
    // All N inside one transaction (#1403). Validation was atomic and
    // the writes were not, which is worse than plainly non-atomic: a
    // unique or foreign-key violation on entry 5 committed entries 0-4,
    // returned `400 bulk entry 5`, and listed none of them — so the
    // caller is told the batch failed, five rows exist, and nothing in
    // the response says which. Those constraints are exactly the class
    // validation cannot decide up front.
    let fields = state.effective_fields();
    let mut tx = match crate::sql::transaction_pool(&acq.pool).await {
        Ok(tx) => tx,
        Err(e) => return json_error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
    };

    let mut pks: Vec<SqlValue> = Vec::with_capacity(prepared.len());
    for (i, (columns, values)) in prepared.into_iter().enumerate() {
        let query = InsertQuery {
            model: state.vs.schema,
            columns,
            values,
            returning: vec![pk_field.column],
            on_conflict: None,
        };
        match crate::sql::insert_returning_tx(&mut tx, &query).await {
            Ok(returning) => pks.push(pk_from_returning(returning, pk_field)),
            Err(e) => {
                // Drop every row this request wrote, including the ones
                // that succeeded before entry `i`.
                let _ = tx.rollback().await;
                return json_error(StatusCode::BAD_REQUEST, &format!("bulk entry {i}: {e}"));
            }
        }
    }
    if let Err(e) = tx.commit().await {
        return json_error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
    }

    // Read the rows back after the commit. They have to be committed to
    // be visible here — `acq` is the pool, not the transaction — and
    // atomicity is a property of the writes, which is the part that was
    // missing.
    let mut created: Vec<Value> = Vec::with_capacity(pks.len());
    for (i, pk_val) in pks.into_iter().enumerate() {
        match fetch_by_pk(state, acq, pk_field, pk_val, &fields).await {
            Some(obj) => created.push(obj),
            None => {
                return json_error(
                    StatusCode::INTERNAL_SERVER_ERROR,
                    &format!("bulk entry {i}: created but could not retrieve"),
                );
            }
        }
    }

    json_created(Value::Array(created))
}

async fn handle_update(
    State(state): State<Arc<ViewSetState>>,
    Path(pk_raw): Path<String>,
    req: axum::extract::Request,
) -> Response {
    update_inner(state, pk_raw, req, false).await
}

async fn handle_partial_update(
    State(state): State<Arc<ViewSetState>>,
    Path(pk_raw): Path<String>,
    req: axum::extract::Request,
) -> Response {
    update_inner(state, pk_raw, req, true).await
}

async fn update_inner(
    state: Arc<ViewSetState>,
    pk_raw: String,
    req: axum::extract::Request,
    partial: bool,
) -> Response {
    let (parts, body, mut acq) = match enter(&state, req, &state.vs.perms.update, "update").await {
        Ok(x) => x,
        Err(resp) => return resp,
    };
    // Scope first: an update must not reach a row this principal cannot see.
    let scope = scope_filters(&state, &parts, &HashMap::new());

    let pk_field = match pk_field_or_500(&state) {
        Ok(f) => f,
        Err(resp) => return resp,
    };
    let pk_val = match parse_pk_or_400(pk_field, &pk_raw) {
        Ok(v) => v,
        Err(resp) => return resp,
    };

    let (form, json) = or_400!(extract_form_body(parts, body).await);

    // Serializer (when set): validate the body + the set of model
    // columns it doesn't accept (read_only / computed), which we skip.
    let non_writable = match serializer_write_prep(&state, json.as_ref()) {
        Ok(s) => s,
        Err(resp) => return resp,
    };

    // Translate `source`-renamed writable keys (serializer field name →
    // model column) before the per-column update loop reads the form.
    let renamed = serializer_input_renamed_form(&state, &form);
    let form = renamed.as_ref().unwrap_or(&form);

    let mut assignments: Vec<Assignment> = Vec::new();
    for field in state.vs.schema.scalar_fields() {
        if field.primary_key || field.auto {
            continue;
        }
        if non_writable.contains(&field.name) {
            continue;
        }
        if partial && !form.contains_key(field.name) {
            continue;
        }
        let raw = form.get(field.name).map(String::as_str);
        match parse_form_value(field, raw) {
            Ok(v) => assignments.push(Assignment {
                column: field.column,
                value: v.into(),
            }),
            Err(FormError::Missing { .. }) if partial => continue,
            Err(e) => {
                return json_error(
                    StatusCode::BAD_REQUEST,
                    &public_form_error(&state, e).to_string(),
                )
            }
        }
    }

    if assignments.is_empty() {
        return json_error(StatusCode::BAD_REQUEST, "no fields to update");
    }

    let query = UpdateQuery {
        model: state.vs.schema,
        set: assignments,
        where_clause: narrow(
            WhereExpr::Predicate(Filter {
                column: pk_field.column,
                op: Op::Eq,
                value: pk_val.clone(),
            }),
            scope.clone(),
        ),
    };

    match acq.update(&query).await {
        // Nothing matched: either no such row, or one this principal is
        // scoped out of. Both are a 404 — see `handle_retrieve`.
        Ok(0) => return json_error(StatusCode::NOT_FOUND, "not found"),
        Ok(_) => {}
        Err(e) => return json_error(StatusCode::BAD_REQUEST, &e.to_string()),
    }

    let fields = state.effective_fields();
    match fetch_by_pk_scoped(&state, &mut acq, pk_field, pk_val, &fields, scope).await {
        Some(obj) => json_response(obj),
        None => json_error(StatusCode::NOT_FOUND, "not found after update"),
    }
}

async fn handle_destroy(
    State(state): State<Arc<ViewSetState>>,
    Path(pk_raw): Path<String>,
    req: axum::extract::Request,
) -> Response {
    let (parts, _body, mut acq) = match enter(&state, req, &state.vs.perms.destroy, "destroy").await
    {
        Ok(x) => x,
        Err(resp) => return resp,
    };
    let scope = scope_filters(&state, &parts, &HashMap::new());

    let pk_field = match pk_field_or_500(&state) {
        Ok(f) => f,
        Err(resp) => return resp,
    };
    let pk_val = match parse_pk_or_400(pk_field, &pk_raw) {
        Ok(v) => v,
        Err(resp) => return resp,
    };

    let query = DeleteQuery {
        model: state.vs.schema,
        where_clause: narrow(
            WhereExpr::Predicate(Filter {
                column: pk_field.column,
                op: Op::Eq,
                value: pk_val,
            }),
            scope,
        ),
    };

    match acq.delete(&query).await {
        Ok(0) => json_error(StatusCode::NOT_FOUND, "not found"),
        Ok(_) => no_content(),
        Err(e) => json_error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
    }
}

// ------------------------------------------------------------------ helpers

/// [`fetch_by_pk`] narrowed by the filter backends — the read-back after an
/// update, which must not return a row the principal is scoped out of.
async fn fetch_by_pk_scoped(
    state: &ViewSetState,
    acq: &mut AcquiredConn,
    pk_field: &'static crate::core::FieldSchema,
    pk_val: SqlValue,
    fields: &[&'static crate::core::FieldSchema],
    scope: Vec<WhereExpr>,
) -> Option<Value> {
    let mut select_q = SelectQuery::by_pk(state.vs.schema, pk_field.column, pk_val);
    select_q.where_clause = narrow(select_q.where_clause, scope);
    render_single(state, acq, &select_q, fields)
        .await
        .ok()
        .flatten()
}

async fn fetch_by_pk(
    state: &ViewSetState,
    acq: &mut AcquiredConn,
    pk_field: &'static crate::core::FieldSchema,
    pk_val: SqlValue,
    fields: &[&'static crate::core::FieldSchema],
) -> Option<Value> {
    // #562 — SelectQuery::by_pk replaces the 11-field literal.
    let select_q = SelectQuery::by_pk(state.vs.schema, pk_field.column, pk_val);
    render_single(state, acq, &select_q, fields)
        .await
        .ok()
        .flatten()
}

/// Render the rows matching `select_q` for a list response: through
/// the registered [`SerializerBridge`] when one is set
/// ([`ViewSet::serializer`]), else the default field-level JSON
/// projection. Single source of truth for the three list shapes.
async fn render_list(
    state: &ViewSetState,
    acq: &mut AcquiredConn,
    select_q: &SelectQuery,
    fields: &[&'static crate::core::FieldSchema],
) -> Result<Vec<Value>, crate::sql::ExecError> {
    match &state.vs.serializer {
        Some(bridge) => bridge.render_rows(acq, select_q).await,
        None => acq.select_rows_as_json(select_q, fields).await,
    }
}

/// Render the single row matching `select_q` for a retrieve / create /
/// update response: through the registered serializer when set, else
/// the default field-level JSON projection.
async fn render_single(
    state: &ViewSetState,
    acq: &mut AcquiredConn,
    select_q: &SelectQuery,
    fields: &[&'static crate::core::FieldSchema],
) -> Result<Option<Value>, crate::sql::ExecError> {
    match &state.vs.serializer {
        Some(bridge) => bridge.render_one(acq, select_q).await,
        None => acq.select_one_as_json(select_q, fields).await,
    }
}

/// Extract form data from both `application/x-www-form-urlencoded` and
/// `application/json` request bodies.
async fn extract_form_body(
    parts: axum::http::request::Parts,
    body: Body,
) -> Result<(HashMap<String, String>, Option<Value>), String> {
    match extract_create_body(parts, body).await? {
        CreateBody::Single(form, json) => Ok((form, json)),
        CreateBody::Bulk(_) => Err("expected a JSON object; got an array".into()),
    }
}

/// Sniff a POST body and return either a single record (object body
/// or form-urlencoded body) or a bulk list (JSON array body — DRF's
/// `ListSerializer(many=True)` shape). Issue #435.
///
/// Bulk shape is only recognized for `application/json` content-type
/// + a JSON array body — form-urlencoded payloads always parse as
/// single records (multi-row form encoding doesn't have a portable
/// shape).
pub(crate) enum CreateBody {
    /// `(stringified form, raw JSON value)`. The JSON value is `Some`
    /// for `application/json` bodies (used for typed serializer
    /// validation) and `None` for form-urlencoded.
    Single(HashMap<String, String>, Option<Value>),
    Bulk(Vec<(HashMap<String, String>, Option<Value>)>),
}

pub(crate) async fn extract_create_body(
    parts: axum::http::request::Parts,
    body: Body,
) -> Result<CreateBody, String> {
    use axum::body::to_bytes;

    let content_type = parts
        .headers
        .get(header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");

    let bytes = to_bytes(body, 4 * 1024 * 1024)
        .await
        .map_err(|e| e.to_string())?;

    if content_type.contains("application/json") {
        let value: serde_json::Value = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?;
        if let Some(array) = value.as_array() {
            // Bulk shape: each element must be an object. Keep the raw
            // JSON entry alongside the stringified form for serializer
            // validation.
            let mut bulk: Vec<(HashMap<String, String>, Option<Value>)> =
                Vec::with_capacity(array.len());
            for (i, entry) in array.iter().enumerate() {
                let obj = entry
                    .as_object()
                    .ok_or_else(|| format!("bulk entry {i} is not a JSON object"))?;
                bulk.push((json_object_to_form(obj), Some(entry.clone())));
            }
            return Ok(CreateBody::Bulk(bulk));
        }
        let obj = value
            .as_object()
            .ok_or("expected a JSON object or array of objects")?;
        Ok(CreateBody::Single(json_object_to_form(obj), Some(value)))
    } else {
        // form-urlencoded (default) — single only, no typed JSON value.
        let form = serde_urlencoded::from_bytes::<HashMap<String, String>>(&bytes)
            .map_err(|e| e.to_string())?;
        Ok(CreateBody::Single(form, None))
    }
}

/// Flatten a JSON object's top-level values into the
/// `HashMap<String, String>` shape every existing collector expects.
/// Numeric / boolean / null primitives stringify; nested objects /
/// arrays serialize back to JSON text (caller can re-parse if it
/// needs typed access). Extracted from the inlined `extract_form_body`
/// path so both single and bulk codepaths share it.
fn json_object_to_form(obj: &serde_json::Map<String, Value>) -> HashMap<String, String> {
    let mut form = HashMap::with_capacity(obj.len());
    for (k, v) in obj {
        let s = match v {
            Value::String(s) => s.clone(),
            Value::Number(n) => n.to_string(),
            Value::Bool(b) => b.to_string(),
            Value::Null => String::new(),
            other => other.to_string(),
        };
        form.insert(k.clone(), s);
    }
    form
}

#[cfg(test)]
mod cursor_tests {
    use super::{cursor_field_supported, decode_cursor, encode_cursor, FieldType, SqlValue};

    fn int_token(v: i64) -> String {
        encode_cursor(&v.to_string(), None)
    }

    /// Decode a value-only token. Most cases below predate the
    /// tiebreaker and only care about the cursor component.
    fn decode_value(token: &str, ty: FieldType) -> Option<SqlValue> {
        decode_cursor(token, ty, FieldType::I64).map(|(v, _)| v)
    }

    #[test]
    fn cursor_roundtrip_positive() {
        let token = int_token(12345);
        assert_eq!(
            decode_value(&token, FieldType::I64),
            Some(SqlValue::I64(12345))
        );
    }

    #[test]
    fn cursor_roundtrip_zero() {
        let token = int_token(0);
        assert_eq!(decode_value(&token, FieldType::I64), Some(SqlValue::I64(0)));
    }

    #[test]
    fn cursor_roundtrip_max() {
        let token = int_token(i64::MAX);
        assert_eq!(
            decode_value(&token, FieldType::I64),
            Some(SqlValue::I64(i64::MAX))
        );
    }

    #[test]
    fn cursor_decode_invalid_base64_returns_none() {
        assert!(decode_value("not!valid!base64@@", FieldType::I64).is_none());
    }

    #[test]
    fn cursor_decode_non_numeric_payload_returns_none() {
        use base64::Engine;
        let token = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode("not_a_number");
        assert!(decode_value(&token, FieldType::I64).is_none());
    }

    /// Tokens issued before #1459 must still decode. An integer cursor
    /// is base64 of its decimal string in both the old and the new
    /// encoder, so a client paginating across an upgrade keeps working.
    #[test]
    fn integer_tokens_are_unchanged_by_the_generalisation() {
        use base64::Engine;
        let legacy = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(b"4242");
        assert_eq!(int_token(4242), legacy);
        assert_eq!(
            decode_value(&legacy, FieldType::I64),
            Some(SqlValue::I64(4242))
        );
    }

    /// A composite token carries the tiebreaker and comes back intact.
    ///
    /// The tiebreaker is what stops a page boundary inside a run of
    /// equal cursor values from skipping the rest of the run — see
    /// `tests/cursor_pagination_on_a_timestamp.rs` for the end-to-end
    /// version.
    #[test]
    fn composite_tokens_round_trip_both_components() {
        let iso = "2026-09-14T22:41:59Z";
        let token = encode_cursor(iso, Some("4242"));
        let (value, tie) =
            decode_cursor(&token, FieldType::DateTime, FieldType::I64).expect("decodes");
        assert!(matches!(value, SqlValue::DateTime(_)), "got {value:?}");
        assert_eq!(tie, Some(SqlValue::I64(4242)));
    }

    /// A bare value and a composite must never be confused. An integer
    /// cursor's payload (`4242`) is valid JSON, so the discriminator has
    /// to be "a two-element array of strings", not "parses as JSON".
    #[test]
    fn a_bare_integer_token_is_not_read_as_composite() {
        let (value, tie) =
            decode_cursor(&int_token(4242), FieldType::I64, FieldType::I64).expect("decodes");
        assert_eq!(value, SqlValue::I64(4242));
        assert_eq!(
            tie, None,
            "a pre-tiebreaker token carries no second component"
        );
    }

    /// The case that 500'd on every request before #1459.
    #[test]
    fn timestamp_cursors_round_trip() {
        let iso = "2026-09-14T22:41:59Z";
        let token = encode_cursor(iso, None);
        let decoded = decode_value(&token, FieldType::DateTime);
        match decoded {
            Some(SqlValue::DateTime(dt)) => {
                assert_eq!(dt.to_rfc3339_opts(chrono::SecondsFormat::Secs, true), iso);
            }
            other => panic!("expected a DateTime cursor, got {other:?}"),
        }
    }

    #[test]
    fn uuid_and_string_cursors_round_trip() {
        let u = "0199c1f4-0000-7000-8000-000000000000";
        assert!(matches!(
            decode_value(&encode_cursor(u, None), FieldType::Uuid),
            Some(SqlValue::Uuid(_))
        ));
        assert_eq!(
            decode_value(&encode_cursor("01J8Z", None), FieldType::String),
            Some(SqlValue::String("01J8Z".into()))
        );
    }

    /// The supported set is a decision, not an accident — floats do not
    /// round-trip exactly and JSON/binary have no total order, so they
    /// stay out.
    #[test]
    fn only_totally_ordered_types_are_accepted() {
        for ok in [
            FieldType::I16,
            FieldType::I32,
            FieldType::I64,
            FieldType::DateTime,
            FieldType::Date,
            FieldType::Uuid,
            FieldType::String,
        ] {
            assert!(cursor_field_supported(ok), "{ok:?} should be usable");
        }
        for bad in [
            FieldType::F32,
            FieldType::F64,
            FieldType::Bool,
            FieldType::Json,
            FieldType::Binary,
        ] {
            assert!(!cursor_field_supported(bad), "{bad:?} must not be usable");
        }
    }
}

#[cfg(all(test, feature = "tenancy"))]
mod tenant_router_tests {
    use super::*;

    /// Smoke: building a tenant_router shouldn't panic and must
    /// produce a usable `Router` value. The full CRUD round-trip
    /// is exercised via integration tests against a real Postgres
    /// + tenant pool. Mirrors the v1 `viewset/tenant.rs` smoke
    /// test from before the v0.30 unification.
    #[test]
    fn tenant_router_builds_for_a_basic_model() {
        use crate::core::Model as _;
        // Use the framework's own User schema as a stand-in —
        // it's always available and has a PK.
        let _r = ViewSet::for_model(crate::tenancy::auth::User::SCHEMA)
            .read_only()
            .tenant_router("/api/users");
    }

    /// `tenant_router` with the full filter/search/ordering/perm
    /// builder chain compiles + builds — proves the v0.30
    /// unification keeps every static-router knob available in
    /// tenant mode (the v1 had none of these).
    #[test]
    fn tenant_router_carries_over_full_builder_chain() {
        use crate::core::Model as _;
        let _r = ViewSet::for_model(crate::tenancy::auth::User::SCHEMA)
            .filter_fields(&["username"])
            .search_fields(&["username"])
            .ordering(&[("id", true)])
            .page_size(50)
            .tenant_router("/api/users");
    }

    /// Mode flag round-trips. Pure unit assertion that the two
    /// public router builders set distinct internal pool sources.
    #[test]
    fn router_and_tenant_router_set_distinct_pool_sources() {
        use crate::core::Model as _;
        // We can't compare PoolSource directly (no PartialEq), but we
        // can assert the discriminant via matches!.
        let static_state = ViewSet::for_model(crate::tenancy::auth::User::SCHEMA);
        // Static can't be tested without a real PgPool; just confirm
        // the tenant variant exists and matches what we expect.
        let vs = static_state.read_only();
        let _r = vs.clone().tenant_router("/api/users");
        // If this compiles, the variant + builder are wired.
    }
}

#[cfg(test)]
mod lookup_tests {
    use super::*;
    use crate::core::{FieldSchema, FieldType};

    fn int_field() -> &'static FieldSchema {
        &FieldSchema {
            name: "author_id",
            column: "author_id",
            ty: FieldType::I64,
            nullable: false,
            primary_key: false,
            relation: None,
            max_length: None,
            min: None,
            max: None,
            default: None,
            auto: false,
            unique: false,
            generated_as: None,
            help_text: None,
            choices: None,
            db_comment: None,
            verbose_name: None,
            editable: true,
            blank: false,
            case_insensitive: false,
            fk_on_delete: None,
            validators: &[],
        }
    }

    fn string_field() -> &'static FieldSchema {
        &FieldSchema {
            name: "title",
            column: "title",
            ty: FieldType::String,
            nullable: true,
            primary_key: false,
            relation: None,
            max_length: None,
            min: None,
            max: None,
            default: None,
            auto: false,
            unique: false,
            generated_as: None,
            help_text: None,
            choices: None,
            db_comment: None,
            verbose_name: None,
            editable: true,
            blank: false,
            case_insensitive: false,
            fk_on_delete: None,
            validators: &[],
        }
    }

    fn extract_pred(expr: WhereExpr) -> Filter {
        match expr {
            WhereExpr::Predicate(f) => f,
            _ => panic!("expected Predicate"),
        }
    }

    #[test]
    fn no_lookup_means_eq() {
        let f = extract_pred(build_lookup_filter(int_field(), None, "42").unwrap());
        assert_eq!(f.op, Op::Eq);
        assert!(matches!(f.value, SqlValue::I64(42)));
    }

    #[test]
    fn explicit_exact_means_eq() {
        let f = extract_pred(build_lookup_filter(int_field(), Some("exact"), "42").unwrap());
        assert_eq!(f.op, Op::Eq);
    }

    #[test]
    fn comparison_lookups() {
        for (lk, expected) in [
            ("gt", Op::Gt),
            ("gte", Op::Gte),
            ("lt", Op::Lt),
            ("lte", Op::Lte),
            ("ne", Op::Ne),
        ] {
            let f = extract_pred(build_lookup_filter(int_field(), Some(lk), "10").unwrap());
            assert_eq!(f.op, expected, "lookup {lk}");
        }
    }

    #[test]
    fn in_lookup_parses_csv() {
        let f = extract_pred(build_lookup_filter(int_field(), Some("in"), "1,2,3").unwrap());
        assert_eq!(f.op, Op::In);
        match f.value {
            SqlValue::List(v) => assert_eq!(v.len(), 3),
            _ => panic!("expected List"),
        }
    }

    #[test]
    fn not_in_lookup_parses_csv() {
        let f = extract_pred(build_lookup_filter(int_field(), Some("not_in"), "1,2").unwrap());
        assert_eq!(f.op, Op::NotIn);
    }

    #[test]
    fn in_lookup_drops_empty_entries() {
        let f = extract_pred(build_lookup_filter(int_field(), Some("in"), "1,,2,").unwrap());
        match f.value {
            SqlValue::List(v) => assert_eq!(v.len(), 2),
            _ => panic!("expected List"),
        }
    }

    #[test]
    fn contains_wraps_with_percents_and_uses_like() {
        let f =
            extract_pred(build_lookup_filter(string_field(), Some("contains"), "hello").unwrap());
        assert_eq!(f.op, Op::LikeEscaped);
        assert!(matches!(f.value, SqlValue::String(ref s) if s == "%hello%"));
    }

    #[test]
    fn icontains_uses_ilike() {
        let f = extract_pred(build_lookup_filter(string_field(), Some("icontains"), "hi").unwrap());
        assert_eq!(f.op, Op::ILikeEscaped);
        assert!(matches!(f.value, SqlValue::String(ref s) if s == "%hi%"));
    }

    #[test]
    fn startswith_only_trailing_percent() {
        let f =
            extract_pred(build_lookup_filter(string_field(), Some("startswith"), "pre").unwrap());
        assert!(matches!(f.value, SqlValue::String(ref s) if s == "pre%"));
    }

    #[test]
    fn endswith_only_leading_percent() {
        let f = extract_pred(build_lookup_filter(string_field(), Some("endswith"), "fix").unwrap());
        assert!(matches!(f.value, SqlValue::String(ref s) if s == "%fix"));
    }

    #[test]
    fn isnull_true() {
        let f = extract_pred(build_lookup_filter(string_field(), Some("isnull"), "true").unwrap());
        assert_eq!(f.op, Op::IsNull);
        assert!(matches!(f.value, SqlValue::Bool(true)));
    }

    #[test]
    fn isnull_false() {
        let f = extract_pred(build_lookup_filter(string_field(), Some("isnull"), "false").unwrap());
        assert!(matches!(f.value, SqlValue::Bool(false)));
    }

    #[test]
    fn unknown_lookup_returns_none() {
        let r = build_lookup_filter(int_field(), Some("frobulate"), "x");
        assert!(r.is_none());
    }

    #[test]
    fn parse_failure_returns_none() {
        let r = build_lookup_filter(int_field(), Some("gt"), "not-a-number");
        assert!(r.is_none());
    }
}

#[cfg(all(test, feature = "tenancy"))]
mod typed_perms_tests {
    use super::*;
    use crate::sql::Auto;

    #[derive(crate::Model)]
    #[rustango(table = "vs_typed_perm_post")]
    #[allow(dead_code)]
    pub struct PermPost {
        #[rustango(primary_key)]
        pub id: Auto<i64>,
        #[rustango(max_length = 200)]
        pub title: String,
    }

    #[test]
    fn permissions_for_model_fills_all_four_crud_codenames() {
        use crate::core::Model;
        let vs =
            ViewSet::for_model(<PermPost as Model>::SCHEMA).permissions_for_model::<PermPost>();
        assert_eq!(vs.perms.list, vec!["vs_typed_perm_post.view"]);
        assert_eq!(vs.perms.retrieve, vec!["vs_typed_perm_post.view"]);
        assert_eq!(vs.perms.create, vec!["vs_typed_perm_post.add"]);
        assert_eq!(vs.perms.update, vec!["vs_typed_perm_post.change"]);
        assert_eq!(vs.perms.destroy, vec!["vs_typed_perm_post.delete"]);
    }
}