rustango 0.60.0

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
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
//! Query layer for rustango.
//!
//! `QuerySet<T>` is a typed builder for `SELECT`. It joins filters with
//! `AND` and compiles to the dialect-neutral `SelectQuery` IR in
//! `rustango-core`. `UpdateBuilder<T>` does the same for `UPDATE`, and
//! `QuerySet<T>` is also the input to bulk delete.

use std::marker::PhantomData;

use crate::core::{
    AggregateExpr, AggregateQuery, Assignment, DeleteQuery, Expr, Filter, Model, ModelSchema, Op,
    QueryError, ScalarFn, SelectQuery, SqlValue, TypedAssignment, TypedExpr, UpdateQuery,
    WhereExpr,
};

mod q;
pub use q::Q;

/// A lazy builder for a `SELECT` over `T`.
///
/// Filters are kept in the order you add them. Nothing touches the schema
/// until `compile` is called, so the builder never panics on bad input.
///
/// You can mix two filter shapes freely:
/// * [`Self::filter`] / [`Self::eq`] — string keys, checked at `compile`
///   time.
/// * [`Self::where_`] — typed (`User::id.gt(10)`); the column is already
///   resolved, so `compile` skips the schema lookup.
///
/// `Clone` is written by hand so a half-built queryset can be the base for
/// two different branches. The derive would add a spurious `T: Clone`
/// bound, and `T` is only a compile-time schema reference.
pub struct QuerySet<T: Model> {
    pending: Vec<PendingFilter>,
    limit: Option<i64>,
    offset: Option<i64>,
    /// DISTINCT mode. `None` emits no DISTINCT clause.
    /// See [`crate::core::DistinctMode`] for what each mode means.
    distinct: Option<crate::core::DistinctMode>,
    /// FK field names registered by [`Self::select_related`]. Each one
    /// becomes a `Join` against the FK target at `compile()` time, so
    /// parents and children come back in one round trip.
    select_related: Vec<String>,
    /// Joins added by [`Self::join`]. Stored pre-built, not as field
    /// names, because the predicate is arbitrary. Appended after the
    /// `select_related` joins.
    ad_hoc_joins: Vec<crate::core::Join>,
    /// Derived-table joins from [`Self::join_sub`] /
    /// [`Self::join_lateral`]. Copied straight onto the compiled
    /// [`SelectQuery::subquery_joins`].
    subquery_joins: Vec<crate::core::SubqueryJoin>,
    /// Pending `ORDER BY` list. Holds `Field` entries from
    /// `.order_by(...)` / `.order_by_with_nulls(...)` and `Expr` entries
    /// from `.order_by_expr(...)`. Lowered in registration order, so
    /// chain order survives mixed builder calls.
    order_by: Vec<PendingOrderItem>,
    /// Row-lock mode for `SELECT … FOR UPDATE`. `None` emits no lock
    /// clause.
    lock_mode: Option<crate::core::LockMode>,
    /// Set-algebra branches from `.union()` / `.intersection()` /
    /// `.difference()`. Each entry is a compiled
    /// [`crate::core::CompoundBranch`]. Empty emits a plain SELECT.
    compound: Vec<crate::core::CompoundBranch>,
    /// Head-branch `ORDER BY`, frozen at the first set-op call.
    /// `order_by` / `limit` / `offset` set BEFORE the first set-op belong
    /// to the first queryset only.
    /// Freezing them here lets anything chained after the set-op apply
    /// to the combined result. Empty until the first set-op call.
    head_order_by: Vec<PendingOrderItem>,
    /// Head-branch `LIMIT`, frozen at the first set-op call.
    /// See [`Self::head_order_by`].
    head_limit: Option<i64>,
    /// Head-branch `OFFSET`, frozen at the first set-op call.
    /// See [`Self::head_order_by`].
    head_offset: Option<i64>,
    /// `.none()` short-circuit. When `true`, every terminal op
    /// compiles to a statement that matches nothing: SELECT gets
    /// `LIMIT 0`; UPDATE / DELETE get an `IS NULL` test against the
    /// NOT NULL primary key. Later calls still accumulate filters and
    /// orderings; the queryset stays empty.
    is_none: bool,
    /// Scope names from `T::SCHEMA.global_scopes` to skip on this
    /// queryset (Eloquent `withoutGlobalScope($name)`). Empty keeps every
    /// scope active. Populated by [`Self::without_global_scope`], and
    /// ignored when [`Self::disable_all_global_scopes`] is set.
    disabled_global_scopes: Vec<&'static str>,
    /// When `true`, skip every scope on `T::SCHEMA.global_scopes`
    /// (Eloquent `withoutGlobalScopes()`). Set by
    /// [`Self::without_global_scopes`]. The
    /// [`Self::disabled_global_scopes`] list is then unused, but stays
    /// intact so adding a name afterwards is not surprising.
    disable_all_global_scopes: bool,
    _model: PhantomData<fn() -> T>,
}

/// One entry in the QuerySet's pending `ORDER BY` list. `Field` holds a
/// field name resolved against the schema at `compile()` time; `Expr`
/// holds an already-built expression. The list keeps registration order,
/// so mixed builder chains compose predictably.
#[derive(Debug, Clone)]
enum PendingOrderItem {
    Field {
        name: String,
        desc: bool,
        nulls: crate::core::NullsOrder,
    },
    Expr {
        expr: crate::core::Expr,
        desc: bool,
        nulls: crate::core::NullsOrder,
    },
    /// `ORDER BY RANDOM()` / `RAND()`. The writer picks the dialect
    /// token at emit time.
    Random,
}

/// Filter accumulator entry. Keeps insertion order across string-keyed and
/// typed filter calls. Each entry adds one node to the final
/// `WhereExpr::And` clause.
#[derive(Clone)]
enum PendingFilter {
    /// String-keyed; resolved against the schema at `compile` time.
    Raw(RawFilter),
    /// Date-part transform lookup, such as `created__year__gte`. At
    /// resolve time the column is wrapped in the named scalar fn
    /// (`ExtractYear`, `TruncDate`, …) and compared with `value` using
    /// `op`.
    DateTransform(DateTransformFilter),
    /// Already resolved by a typed [`Column`](crate::core::Column).
    Resolved(Filter),
    /// Typed sub-expression built with `.and()` / `.or()` on the
    /// typed-column API. Already validated; adds a whole sub-tree to the
    /// WHERE clause.
    Expr(WhereExpr),
    /// Negated predicate, `NOT (<inner>)`. Backs [`QuerySet::exclude`].
    /// The inner entry resolves first, then gets wrapped in
    /// [`WhereExpr::Not`], so `exclude` supports the full lookup grammar
    /// (`__gt`, `__icontains`, …).
    Negated(Box<PendingFilter>),
    /// Relation-spanning lookup deferred from [`parse_lookup`], such as
    /// `author__profile__bio__icontains`. A pre-pass in
    /// [`QuerySet::compile`] turns it into a [`PendingFilter::Expr`] and
    /// registers the FK-chain JOINs. If one still reaches
    /// [`resolve_one_pending`], the caller is on an update, delete or
    /// aggregate path, where it is not supported, so it errors.
    RelationSpan { raw_key: String, value: SqlValue },
    /// Error held back until `compile()`. [`QuerySet::filter`] uses it
    /// when the lookup-suffix parser fails, so the builder API stays
    /// non-`Result` and the cause still surfaces.
    Error(QueryError),
}

#[derive(Debug, Clone)]
struct RawFilter {
    field: String,
    op: Op,
    value: SqlValue,
}

#[derive(Debug, Clone)]
struct DateTransformFilter {
    field: String,
    transform: ScalarFn,
    op: Op,
    value: SqlValue,
}

#[derive(Debug, Clone)]
struct RawAssignment {
    field: String,
    value: SqlValue,
}

/// Staged `field = <expression>` assignment for the [`F()`] SET path.
/// `field` is the Rust-side name, resolved against the schema at
/// `compile()` time. `value` is an [`crate::core::Expr`] tree that may
/// hold column refs and arithmetic. Resolves to
/// [`crate::core::Assignment`].
///
/// [`F()`]: crate::core::F
#[derive(Debug, Clone)]
struct RawExprAssignment {
    field: String,
    value: crate::core::Expr,
}

impl<T: Model> Default for QuerySet<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Model> Clone for QuerySet<T> {
    fn clone(&self) -> Self {
        Self {
            pending: self.pending.clone(),
            limit: self.limit,
            offset: self.offset,
            distinct: self.distinct.clone(),
            select_related: self.select_related.clone(),
            ad_hoc_joins: self.ad_hoc_joins.clone(),
            subquery_joins: self.subquery_joins.clone(),
            order_by: self.order_by.clone(),
            lock_mode: self.lock_mode.clone(),
            compound: self.compound.clone(),
            head_order_by: self.head_order_by.clone(),
            head_limit: self.head_limit,
            head_offset: self.head_offset,
            is_none: self.is_none,
            disabled_global_scopes: self.disabled_global_scopes.clone(),
            disable_all_global_scopes: self.disable_all_global_scopes,
            _model: std::marker::PhantomData,
        }
    }
}

impl<T: Model> QuerySet<T> {
    #[must_use]
    pub fn new() -> Self {
        Self {
            pending: Vec::new(),
            limit: None,
            offset: None,
            distinct: None,
            select_related: Vec::new(),
            ad_hoc_joins: Vec::new(),
            subquery_joins: Vec::new(),
            order_by: Vec::new(),
            lock_mode: None,
            compound: Vec::new(),
            head_order_by: Vec::new(),
            head_limit: None,
            head_offset: None,
            is_none: false,
            disabled_global_scopes: Vec::new(),
            disable_all_global_scopes: false,
            _model: PhantomData,
        }
    }

    /// Eloquent `withoutGlobalScope($name)`. Skip one named entry from
    /// [`crate::core::ModelSchema::global_scopes`] on this queryset.
    /// Repeated calls add up.
    ///
    /// Unknown names are ignored, like Eloquent, so a call site can opt
    /// out of a scope that does not exist yet.
    #[must_use]
    pub fn without_global_scope(mut self, name: &'static str) -> Self {
        if !self.disabled_global_scopes.contains(&name) {
            self.disabled_global_scopes.push(name);
        }
        self
    }

    /// Eloquent `withoutGlobalScopes()`. Skip *every* scope from
    /// [`crate::core::ModelSchema::global_scopes`]. Useful for admin or
    /// migration code that must see soft-deleted, unpublished or
    /// cross-tenant rows the app normally hides.
    ///
    /// Once set, later [`Self::without_global_scope`] calls change
    /// nothing: everything stays disabled on this queryset.
    #[must_use]
    pub fn without_global_scopes(mut self) -> Self {
        self.disable_all_global_scopes = true;
        self
    }

    /// Fold the schema's global scopes into the pending filter list,
    /// honouring the per-queryset opt-outs. Called at the top of every
    /// `compile*` entry point, so scope expressions go through the same
    /// resolver as any other typed filter.
    ///
    /// Scope filters are **prepended** in declared order, so the WHERE
    /// reads `scope_a AND scope_b AND <user filters>`. `AND` is
    /// commutative, so this only affects how an `EXPLAIN` trace reads.
    fn apply_global_scopes(&mut self) {
        if self.disable_all_global_scopes {
            return;
        }
        let mut prefixed: Vec<PendingFilter> = T::SCHEMA
            .global_scope_exprs(&self.disabled_global_scopes)
            .into_iter()
            .map(PendingFilter::Expr)
            .collect();
        if !prefixed.is_empty() {
            prefixed.append(&mut self.pending);
            self.pending = prefixed;
        }
    }

    /// A queryset that matches zero rows. Handy as a
    /// safe base for conditional filters, such as
    /// `if !user.has_perm { qs = qs.none() }`.
    ///
    /// SELECT compiles to `LIMIT 0`. UPDATE / DELETE add an `IS NULL`
    /// test against the NOT NULL primary key, so no row matches.
    #[must_use]
    pub fn none(mut self) -> Self {
        self.is_none = true;
        self
    }

    /// Emit `SELECT DISTINCT ...`. Behaves the
    /// same on every dialect. Add `.order_by(...)` to decide which row
    /// of a duplicate group survives; without it the order is undefined.
    ///
    /// For "first row per group", use [`Self::distinct_on`].
    #[must_use]
    pub fn distinct(mut self) -> Self {
        self.distinct = Some(crate::core::DistinctMode::All);
        self
    }

    /// Distinct on named columns. Emits `DISTINCT ON (col1, col2)` on
    /// Postgres. On MySQL / SQLite it lowers to a `ROW_NUMBER() OVER
    /// (PARTITION BY cols ORDER BY <order_by>)` subquery. All three give
    /// "first row per group", and the queryset's `ORDER BY` decides
    /// which row is first.
    ///
    /// The columns must come first in `.order_by(...)`.
    /// Otherwise `.compile()` returns
    /// [`QueryError::DistinctOnOrderByMismatch`]. Empty `fields`
    /// returns [`QueryError::DistinctOnEmpty`]; use
    /// [`Self::distinct`] for that instead.
    #[must_use]
    pub fn distinct_on(mut self, fields: &[&'static str]) -> Self {
        self.distinct = Some(crate::core::DistinctMode::On(fields.to_vec()));
        self
    }

    /// Take a row lock. Emits `SELECT … FOR UPDATE` on
    /// Postgres and MySQL 8+. SQLite has no row-lock syntax, so it is a
    /// no-op there; a SQLite transaction locks the whole database.
    ///
    /// Run it inside a transaction. `FOR UPDATE` outside one does
    /// nothing on Postgres and errors on MySQL. Open one with
    /// [`crate::sql::transaction_pool`], then call
    /// `.fetch_on(&mut *tx)`.
    ///
    /// The defaults ([`crate::core::LockMode::default`]) emit plain
    /// `FOR UPDATE`. Use the methods below to set individual flags.
    #[must_use]
    pub fn select_for_update(mut self) -> Self {
        self.lock_mode = Some(crate::core::LockMode::default());
        self
    }

    /// Eloquent `Builder::lockForUpdate()`. Alias of
    /// [`Self::select_for_update`], with the same rules.
    #[must_use]
    pub fn lock_for_update(self) -> Self {
        self.select_for_update()
    }

    /// PG / MySQL 8+: add `SKIP LOCKED` — the "claim the next free row"
    /// pattern. Rows another transaction holds are skipped instead of
    /// blocking. No effect on SQLite. Implies
    /// [`Self::select_for_update`].
    #[must_use]
    pub fn skip_locked(mut self) -> Self {
        let mut lock = self.lock_mode.take().unwrap_or_default();
        lock.skip_locked = true;
        self.lock_mode = Some(lock);
        self
    }

    /// PG / MySQL 8+: add `NOWAIT` — return a driver error at once if
    /// any matching row is locked. The database forbids it together
    /// with `SKIP LOCKED`, so if both are set the writer emits
    /// `SKIP LOCKED`. Implies [`Self::select_for_update`].
    #[must_use]
    pub fn nowait(mut self) -> Self {
        let mut lock = self.lock_mode.take().unwrap_or_default();
        lock.nowait = true;
        self.lock_mode = Some(lock);
        self
    }

    /// PG 9.3+: `FOR NO KEY UPDATE` instead of `FOR UPDATE`. A weaker
    /// lock that does not block writers leaving the row's PK and unique
    /// columns alone. Good for busy update paths that never change
    /// indexed columns. MySQL has no equivalent, so the writer falls
    /// back to `FOR UPDATE`.
    #[must_use]
    pub fn no_key(mut self) -> Self {
        let mut lock = self.lock_mode.take().unwrap_or_default();
        lock.no_key = true;
        self.lock_mode = Some(lock);
        self
    }

    /// PG 9.3+ / MySQL 8.0.1+: `FOR UPDATE OF table1, table2, …` — lock
    /// only the named tables when the query joins. Without `OF` the
    /// lock covers every joined table the result touches. No-op on
    /// SQLite.
    ///
    /// Each call appends. Pass base table names or join aliases.
    #[must_use]
    pub fn of(mut self, tables: &[&'static str]) -> Self {
        let mut lock = self.lock_mode.take().unwrap_or_default();
        lock.of.extend_from_slice(tables);
        self.lock_mode = Some(lock);
        self
    }

    /// Stop the writer from warning that SQLite has no row locks.
    ///
    /// SQLite has no `FOR UPDATE` syntax, so the lock modifiers are
    /// dropped. The writer logs a `tracing::warn!` by default, so nobody
    /// chases a phantom concurrency bug on a SQLite fixture. Call this
    /// when SQLite's single global write lock is enough for you.
    ///
    /// No effect on PG / MySQL; locks emit normally there.
    #[must_use]
    pub fn silent_on_sqlite(mut self) -> Self {
        let mut lock = self.lock_mode.take().unwrap_or_default();
        lock.silent_on_sqlite = true;
        self.lock_mode = Some(lock);
        self
    }

    /// Combines this queryset with `other`
    /// using SQL `UNION`, which removes duplicates. Both target model
    /// `T`, so the column shape always matches.
    ///
    /// Every `.union()` / `.union_all()` call appends another branch.
    /// Mixing in `intersection` or `difference` is allowed; SQL
    /// evaluates the chain left to right.
    ///
    /// `.order_by()` / `.limit()` / `.offset()` called AFTER `.union()`
    /// apply to the combined result. The same calls BEFORE it apply to
    /// the first queryset only. Each
    /// branch keeps its own clauses, because every component is wrapped
    /// in an aliased derived table (`SELECT * FROM (…) AS
    /// __rustango_bN`) on all three backends.
    ///
    /// Works on every supported backend.
    ///
    /// # Panics
    /// If `other.compile()` fails, for example on a typo'd column in
    /// the branch. A malformed branch is a programmer error. To get a
    /// `Result` instead, pre-compile the branch and pass it to
    /// [`Self::with_compound`].
    #[must_use]
    pub fn union(self, other: QuerySet<T>) -> Self {
        self.add_compound(crate::core::SetOp::Union, other)
    }

    /// `UNION ALL` — combine without removing duplicates. Cheaper than
    /// [`Self::union`] because the database skips the DISTINCT pass.
    /// Use it when you know the branches do not overlap.
    ///
    /// # Panics
    /// As [`Self::union`].
    #[must_use]
    pub fn union_all(self, other: QuerySet<T>) -> Self {
        self.add_compound(crate::core::SetOp::UnionAll, other)
    }

    /// Rows present in BOTH
    /// querysets. Postgres, SQLite and MySQL 8.0.31+.
    ///
    /// # Panics
    /// As [`Self::union`].
    #[must_use]
    pub fn intersection(self, other: QuerySet<T>) -> Self {
        self.add_compound(crate::core::SetOp::Intersection, other)
    }

    /// Emits `EXCEPT`: rows in this
    /// queryset but not in `other`. Postgres, SQLite and MySQL 8.0.31+.
    ///
    /// # Panics
    /// As [`Self::union`].
    #[must_use]
    pub fn difference(self, other: QuerySet<T>) -> Self {
        self.add_compound(crate::core::SetOp::Difference, other)
    }

    /// Set-algebra entry point that takes an already-compiled
    /// `SelectQuery` branch. Use it when building the branch may fail
    /// and you want to handle that error yourself. The operator
    /// argument covers union, union_all, intersection and difference.
    ///
    /// ```ignore
    /// // Caller wants to handle the branch's compile error explicitly:
    /// let branch = Post::objects()
    ///     .filter("typo_field__lt", 100_i64)  // may fail
    ///     .compile()?;                         // → Result
    /// let qs = Post::objects()
    ///     .where_(Post::active.eq(true))
    ///     .with_compound(SetOp::Union, branch);
    /// ```
    #[must_use]
    pub fn with_compound(self, op: crate::core::SetOp, branch: crate::core::SelectQuery) -> Self {
        self.add_compound_compiled(op, branch)
    }

    /// Shared lowering for [`Self::union`], [`Self::union_all`],
    /// [`Self::intersection`] and [`Self::difference`]. Compiles the
    /// branch and appends a `CompoundBranch`. Panics if the branch
    /// fails to compile; use [`Self::with_compound`] for the fallible
    /// form.
    fn add_compound(self, op: crate::core::SetOp, other: QuerySet<T>) -> Self {
        match other.compile() {
            Ok(branch) => self.add_compound_compiled(op, branch),
            Err(e) => panic!(
                "rustango: set-algebra branch failed to compile: {e}. \
                 Pre-compile the branch and pass via .with_compound(op, \
                 branch) to surface this error as a Result."
            ),
        }
    }

    fn add_compound_compiled(
        mut self,
        op: crate::core::SetOp,
        branch: crate::core::SelectQuery,
    ) -> Self {
        // The first set-op call freezes the pre-union ORDER BY / LIMIT /
        // OFFSET into the head slots: those clauses belong to the first
        // queryset. Clearing the live slots means anything chained after
        // this point applies to the combined result. Later set-op calls
        // leave the frozen head alone.
        if self.compound.is_empty() {
            self.head_order_by = std::mem::take(&mut self.order_by);
            self.head_limit = self.limit.take();
            self.head_offset = self.offset.take();
        }
        self.compound.push(crate::core::CompoundBranch {
            op,
            query: Box::new(branch),
        });
        self
    }

    /// Append `ORDER BY` columns.
    ///
    /// Each entry is a `(field_name, desc)` pair naming a Rust-side
    /// field on the model. The schema check runs at `compile()` time.
    /// Calls compose: later ones append after earlier ones.
    ///
    /// ```ignore
    /// let posts = Post::objects()
    ///     .order_by(&[("published_at", true)])  // newest first
    ///     .fetch_on(conn).await?;
    /// ```
    ///
    /// To sort by multiple columns:
    ///
    /// ```ignore
    /// .order_by(&[("category", false), ("published_at", true)])
    /// ```
    #[must_use]
    pub fn order_by(mut self, items: &[(&str, bool)]) -> Self {
        for (field, desc) in items {
            self.order_by.push(PendingOrderItem::Field {
                name: (*field).to_owned(),
                desc: *desc,
                nulls: crate::core::NullsOrder::Default,
            });
        }
        self
    }

    /// Eloquent `Builder::reorder([col, asc?])` — **replace** the
    /// accumulated `ORDER BY` list instead of appending to it like
    /// [`Self::order_by`]. Use it to override a default ordering that
    /// came from a base queryset or manager:
    ///
    /// ```ignore
    /// let qs = Post::objects()
    ///     .with_default_order()                          // model's default
    ///     .reorder(&[("created_at", true)]);             // wipes default
    /// ```
    ///
    /// Pass an empty slice, `.reorder(&[])`, to clear every sort key,
    /// like Eloquent's `reorder()` with no arguments.
    #[must_use]
    pub fn reorder(mut self, items: &[(&str, bool)]) -> Self {
        self.order_by.clear();
        for (field, desc) in items {
            self.order_by.push(PendingOrderItem::Field {
                name: (*field).to_owned(),
                desc: *desc,
                nulls: crate::core::NullsOrder::Default,
            });
        }
        self
    }

    /// Shortcut for `ORDER BY <col> DESC`. Appends to the existing
    /// list; call [`Self::reorder`] first to replace it.
    ///
    /// Eloquent calls this `Builder::latest($column)`, but rustango's
    /// [`Self::latest`] is the async fetcher, so the chainable form
    /// uses this name.
    ///
    /// ```ignore
    /// Post::objects().order_by_desc("created_at").fetch(&pool).await?;
    /// // SELECT ... FROM post ORDER BY created_at DESC
    /// ```
    #[must_use]
    pub fn order_by_desc(self, column: &str) -> Self {
        self.order_by(&[(column, true)])
    }

    /// Single-column shortcut for `ORDER BY <col> ASC`. Appends to the
    /// existing ORDER BY list.
    ///
    /// Counterpart of [`Self::order_by_desc`]; mirrors Eloquent's
    /// `Builder::oldest($column)`.
    ///
    /// ```ignore
    /// Post::objects().order_by_asc("created_at").fetch(&pool).await?;
    /// // SELECT ... FROM post ORDER BY created_at ASC
    /// ```
    #[must_use]
    pub fn order_by_asc(self, column: &str) -> Self {
        self.order_by(&[(column, false)])
    }

    /// Apply the schema's `default_order` for `T`. Each entry from
    /// `#[rustango(default_order = "...")]` is prepended to the pending
    /// ORDER BY list, so a later `.order_by(...)` adds secondary keys.
    ///
    /// **You must opt in per query.** A model's default order is not
    /// applied on its own; every queryset starts unsorted. This keeps
    /// `.count()`, `.exists()` and
    /// `.delete()` from paying for a sort they do not need.
    ///
    /// A no-op when the model has no `default_order`, and calling it
    /// twice does not duplicate the entries.
    #[must_use]
    pub fn with_default_order(mut self) -> Self {
        let model = T::SCHEMA;
        // Build the new entries first so we can pre-pend them.
        let new_entries: Vec<PendingOrderItem> = model
            .default_order
            .iter()
            .map(|(name, desc)| PendingOrderItem::Field {
                name: (*name).to_owned(),
                desc: *desc,
                nulls: crate::core::NullsOrder::Default,
            })
            .collect();
        if new_entries.is_empty() {
            return self;
        }
        // Idempotency check: if the head of `order_by` already matches
        // the model's default sequence, skip re-prepending.
        let already_applied = self.order_by.len() >= new_entries.len()
            && self
                .order_by
                .iter()
                .zip(new_entries.iter())
                .all(|(a, b)| match (a, b) {
                    (
                        PendingOrderItem::Field {
                            name: an, desc: ad, ..
                        },
                        PendingOrderItem::Field {
                            name: bn, desc: bd, ..
                        },
                    ) => an == bn && ad == bd,
                    _ => false,
                });
        if already_applied {
            return self;
        }
        // Pre-pend.
        let mut combined = new_entries;
        combined.extend(self.order_by.drain(..));
        self.order_by = combined;
        self
    }

    /// Order by the PK when nothing else orders the rows, so LIMIT and
    /// OFFSET page through a stable sequence.
    #[must_use]
    pub(crate) fn ordered_or_by_pk(self) -> Self {
        match T::SCHEMA.primary_key() {
            Some(pk) if self.order_by.is_empty() => self.order_by(&[(pk.name, false)]),
            _ => self,
        }
    }

    /// Clear every accumulated `ORDER BY` entry, whatever added it
    /// (`.order_by(...)`, `.order_by_expr(...)`,
    /// `.with_default_order()`). Use it to drop the default order of a
    /// queryset you got from a builder helper.
    #[must_use]
    pub fn unordered(mut self) -> Self {
        self.order_by.clear();
        self
    }

    /// Append `ORDER BY` columns and say where NULLs go. PG and SQLite
    /// emit the `NULLS …` keyword. MySQL has no such syntax, so it
    /// sorts by `<col> IS NULL` first instead.
    ///
    /// ```ignore
    /// use rustango::core::NullsOrder;
    /// Post::objects()
    ///     .order_by_with_nulls(&[("published_at", true, NullsOrder::Last)])
    ///     .fetch(&pool).await?;
    /// ```
    ///
    /// Composes with `.order_by(...)`: entries from both methods appear
    /// in the `ORDER BY` clause in **registration order**.
    #[must_use]
    pub fn order_by_with_nulls(
        mut self,
        items: &[(&'static str, bool, crate::core::NullsOrder)],
    ) -> Self {
        for (field, desc, nulls) in items {
            self.order_by.push(PendingOrderItem::Field {
                name: (*field).to_owned(),
                desc: *desc,
                nulls: *nulls,
            });
        }
        self
    }

    /// Append an `ORDER BY` item over any [`Expr`], such as
    /// `lower(F("title"))`, `case(...)` or `F("a") + F("b")`.
    ///
    /// `desc = true` gives `DESC`. NULL placement follows the dialect
    /// default; use [`Self::order_by_expr_with_nulls`] to pin it.
    ///
    /// [`Expr`]: crate::core::Expr
    #[must_use]
    pub fn order_by_expr(mut self, expr: impl Into<crate::core::Expr>, desc: bool) -> Self {
        self.order_by.push(PendingOrderItem::Expr {
            expr: expr.into(),
            desc,
            nulls: crate::core::NullsOrder::Default,
        });
        self
    }

    /// Order rows by pgvector distance from `query` to the `column`
    /// vector. Distance ascends, so the **nearest** rows come first for
    /// every metric.
    ///
    /// Emits `ORDER BY <column> <op> $vec`, where `<op>` is the pgvector
    /// operator for `metric` (`<->`, `<=>`, `<#>`). **PG only**: the
    /// writer raises `OpNotSupportedInDialect` on MySQL / SQLite. Add
    /// `.limit(k)`, or use [`Self::k_nearest`], for a k-NN query. The
    /// column should be a [`crate::sql::Vector`] field.
    ///
    /// ```ignore
    /// use rustango::core::VectorMetric;
    /// // 5 nearest documents to `query_embedding` by cosine distance.
    /// let hits = Doc::objects()
    ///     .order_by_distance("embedding", query_embedding, VectorMetric::Cosine)
    ///     .limit(5)
    ///     .fetch(&pool).await?;
    /// ```
    #[must_use]
    pub fn order_by_distance(
        self,
        column: &'static str,
        query: Vec<f32>,
        metric: crate::core::VectorMetric,
    ) -> Self {
        let expr = crate::core::Expr::BinOp {
            left: Box::new(crate::core::Expr::Column(column)),
            op: metric.to_binop(),
            right: Box::new(crate::core::Expr::Literal(SqlValue::Vector(query))),
        };
        self.order_by_expr(expr, /*desc=*/ false)
    }

    /// k-nearest-neighbour shortcut: [`Self::order_by_distance`] plus
    /// `.limit(k)`. Returns the `k` rows closest to `query` under
    /// `metric`. **PG only.**
    ///
    /// ```ignore
    /// use rustango::core::VectorMetric;
    /// let top3 = Doc::objects()
    ///     .k_nearest("embedding", query_embedding, 3, VectorMetric::L2)
    ///     .fetch(&pool).await?;
    /// ```
    #[must_use]
    pub fn k_nearest(
        self,
        column: &'static str,
        query: Vec<f32>,
        k: i64,
        metric: crate::core::VectorMetric,
    ) -> Self {
        self.order_by_distance(column, query, metric).limit(k)
    }

    /// PostGIS nearest-first ordering: `ORDER BY ST_Distance(<column>,
    /// <point>)` ascending. Add `.limit(k)` for a k-nearest query.
    /// `column` should be a `#[rustango(geometry(...))]` field.
    /// **PG / PostGIS only**: MySQL and SQLite raise
    /// `OpNotSupportedInDialect` at compile time.
    ///
    /// ```ignore
    /// // The 5 places nearest to `here`.
    /// let near = Place::objects()
    ///     .order_by_distance_to("location", here)
    ///     .limit(5)
    ///     .fetch(&pool).await?;
    /// ```
    #[must_use]
    pub fn order_by_distance_to(self, column: &'static str, point: crate::sql::Point) -> Self {
        let expr = crate::core::funcs::st_distance(crate::core::Expr::Column(column), point);
        self.order_by_expr(expr, /*desc=*/ false)
    }

    /// PostGIS "within radius" filter: `WHERE ST_DWithin(<column>,
    /// <point>, <distance>)`. `distance` uses the column's SRID units,
    /// which is degrees for SRID 4326. For metres, cast to
    /// `::geography` in raw SQL. **PG / PostGIS only.**
    ///
    /// ```ignore
    /// // Places within ~1km (in degrees) of `here`.
    /// let nearby = Place::objects()
    ///     .filter_dwithin("location", here, 0.01)
    ///     .fetch(&pool).await?;
    /// ```
    #[must_use]
    pub fn filter_dwithin(
        self,
        column: &'static str,
        point: crate::sql::Point,
        distance: f64,
    ) -> Self {
        let pred = WhereExpr::ExprCompare {
            lhs: crate::core::funcs::st_dwithin(
                crate::core::Expr::Column(column),
                point,
                crate::core::Expr::Literal(SqlValue::F64(distance)),
            ),
            op: Op::Eq,
            rhs: crate::core::Expr::Literal(SqlValue::Bool(true)),
        };
        self.where_raw(pred)
    }

    /// Same as [`Self::order_by_expr`], but with an explicit
    /// `NullsOrder`.
    #[must_use]
    pub fn order_by_expr_with_nulls(
        mut self,
        expr: impl Into<crate::core::Expr>,
        desc: bool,
        nulls: crate::core::NullsOrder,
    ) -> Self {
        self.order_by.push(PendingOrderItem::Expr {
            expr: expr.into(),
            desc,
            nulls,
        });
        self
    }

    /// `ORDER BY RANDOM()` (PG / SQLite) or `ORDER BY RAND()` (MySQL).
    /// Good for "random N rows" needs
    /// such as banner rotation or sampling.
    ///
    /// ```ignore
    /// // Three random posts.
    /// Post::objects()
    ///     .order_random()
    ///     .limit(3)
    ///     .fetch(&pool).await?;
    /// ```
    ///
    /// **Cost**: this forces a full table scan and an in-memory sort on
    /// a random key per row. No index can help. On tables much larger
    /// than memory, use `WHERE pk >= <random_offset> LIMIT N` instead,
    /// which can range-scan an index, and accept that the rows come out
    /// next to each other by primary key.
    ///
    /// It composes with other `.order_by*` calls: the random key only
    /// breaks ties. Most callers want [`Self::replace_order_by`] first.
    #[must_use]
    pub fn order_random(mut self) -> Self {
        self.order_by.push(PendingOrderItem::Random);
        self
    }

    /// Eloquent `Builder::inRandomOrder()`. Alias of
    /// [`Self::order_random`], with the same cost.
    ///
    /// ```ignore
    /// // Eloquent: Post::query()->inRandomOrder()->take(5)->get();
    /// let five = Post::objects()
    ///     .in_random_order()
    ///     .take(5)
    ///     .fetch(&pool).await?;
    /// ```
    #[must_use]
    pub fn in_random_order(self) -> Self {
        self.order_random()
    }

    /// Drop every pending `ORDER BY` item and use `items` instead.
    /// Used by `earliest` and `latest`, which set their own sort.
    #[must_use]
    pub fn replace_order_by(mut self, items: &[(&str, bool)]) -> Self {
        self.order_by.clear();
        self.order_by(items)
    }

    /// Flips the direction of every pending `ORDER BY` entry.
    /// `Random` has no direction, so it stays as it is.
    ///
    /// No-op when no ordering is set.
    ///
    /// ```ignore
    /// // newest first
    /// let q = Post::objects()
    ///     .order_by(&[("published_at", true)]);
    /// // oldest first — same predicate set, flipped sort
    /// let r = q.reverse();
    /// ```
    #[must_use]
    pub fn reverse(mut self) -> Self {
        for item in &mut self.order_by {
            match item {
                PendingOrderItem::Field { desc, .. } | PendingOrderItem::Expr { desc, .. } => {
                    *desc = !*desc
                }
                PendingOrderItem::Random => {}
            }
        }
        self
    }

    /// Flip every ordering direction in place. `last` uses it to take
    /// the first row of the reversed sort, which avoids `OFFSET` plus
    /// `COUNT(*)` and works on every dialect. It also swaps
    /// `NullsOrder::First` and `NullsOrder::Last`, so NULLs stay at the
    /// same logical end.
    #[must_use]
    pub fn flip_order_by(mut self) -> Self {
        for entry in &mut self.order_by {
            match entry {
                PendingOrderItem::Field { desc, nulls, .. }
                | PendingOrderItem::Expr { desc, nulls, .. } => {
                    *desc = !*desc;
                    *nulls = match *nulls {
                        crate::core::NullsOrder::First => crate::core::NullsOrder::Last,
                        crate::core::NullsOrder::Last => crate::core::NullsOrder::First,
                        crate::core::NullsOrder::Default => crate::core::NullsOrder::Default,
                    };
                }
                // Random has no direction or NULLS clause to flip.
                PendingOrderItem::Random => {}
            }
        }
        self
    }

    /// Whether any `ORDER BY` item is registered. The executor's
    /// `ensure_pk_ordering` uses it to spot "no ordering set" without
    /// looking at the entry variants.
    #[must_use]
    pub fn has_order_by(&self) -> bool {
        !self.order_by.is_empty()
    }

    /// Load a `ForeignKey<Parent>` field with a `LEFT JOIN`, in the
    /// same query. Pass the field name on `T`, not the
    /// FK column or the parent table. `fetch_on` then returns rows
    /// whose `ForeignKey<Parent>` is already `Loaded`, from a single
    /// query, with no N+1.
    ///
    /// ```ignore
    /// let posts: Vec<Post> = Post::objects()
    ///     .select_related("author")
    ///     .fetch_on(conn).await?;
    /// // post.author is ForeignKey::Loaded { pk, value }
    /// ```
    ///
    /// Calls compose: each adds another `LEFT JOIN` to the same SELECT.
    /// The schema check — field exists, is an FK, target has a primary
    /// key — runs at `compile()` time.
    #[must_use]
    pub fn select_related(mut self, field: impl Into<String>) -> Self {
        self.select_related.push(field.into());
        self
    }

    /// Append a fully specified [`crate::core::Join`]. Unlike
    /// [`select_related`], which builds joins from FK metadata, you
    /// choose the join kind, alias, predicate and projected columns.
    /// The predicate is any [`WhereExpr`]; its columns qualify against
    /// the joined alias by default, or against another alias via
    /// [`crate::core::Expr::AliasedColumn`].
    ///
    /// Calls compose; each JOIN lands after the `select_related` ones.
    /// Aliases must be unique within the queryset.
    ///
    /// ```ignore
    /// use rustango::core::joins::aliased;
    /// use rustango::core::{Join, JoinKind, Op, WhereExpr};
    ///
    /// Post::objects()
    ///     .join(Join {
    ///         target: Comment::SCHEMA,
    ///         alias: "c",
    ///         kind: JoinKind::Inner,
    ///         on: WhereExpr::And(vec![
    ///             WhereExpr::ExprCompare {
    ///                 lhs: aliased("c", "post_id"),
    ///                 op: Op::Eq,
    ///                 rhs: aliased("post", "id"),
    ///             },
    ///             // Filter columns inside `on` qualify to the joined
    ///             // alias (`c`) by default — no need to `aliased()` here.
    ///             Comment::is_approved.eq(true).into(),
    ///         ]),
    ///         project: vec![],
    ///     })
    ///     .fetch(&pool).await?;
    /// ```
    ///
    /// [`select_related`]: Self::select_related
    /// [`WhereExpr`]: crate::core::WhereExpr
    #[must_use]
    pub fn join(mut self, join: crate::core::Join) -> Self {
        self.ad_hoc_joins.push(join);
        self
    }

    /// `INNER JOIN (<subquery>) AS <alias> ON <on>` — join a **derived
    /// table**, like Eloquent's `joinSub`.
    ///
    /// `sub` is a compiled `SelectQuery`. In `on`, name the derived
    /// table's columns and the outer table's columns with
    /// [`crate::core::joins::aliased`]. The derived table adds no
    /// columns to the SELECT, so a typed fetch still returns the base
    /// model. Works on PG, MySQL and SQLite.
    ///
    /// ```ignore
    /// use rustango::core::joins::aliased;
    /// use rustango::core::{Op, WhereExpr};
    ///
    /// // Customers who have placed at least one order.
    /// let recent = Order::objects()
    ///     .values(&["customer_id"])      // derived table: distinct customer ids
    ///     .compile()?;
    /// let with_orders = Customer::objects()
    ///     .join_sub(recent, "o", WhereExpr::ExprCompare {
    ///         lhs: aliased("o", "customer_id"),
    ///         op: Op::Eq,
    ///         rhs: aliased("customer", "id"),
    ///     })
    ///     .fetch(&pool).await?;
    /// ```
    #[must_use]
    pub fn join_sub(
        self,
        sub: impl Into<crate::core::DerivedSource>,
        alias: &'static str,
        on: WhereExpr,
    ) -> Self {
        self.push_subquery_join(
            sub,
            alias,
            crate::core::JoinKind::Inner,
            on,
            /*lateral=*/ false,
        )
    }

    /// `LEFT JOIN (<subquery>) AS <alias> ON <on>` — the left-join form
    /// of [`Self::join_sub`] (Eloquent `leftJoinSub`).
    #[must_use]
    pub fn left_join_sub(
        self,
        sub: impl Into<crate::core::DerivedSource>,
        alias: &'static str,
        on: WhereExpr,
    ) -> Self {
        self.push_subquery_join(
            sub,
            alias,
            crate::core::JoinKind::Left,
            on,
            /*lateral=*/ false,
        )
    }

    /// `INNER JOIN LATERAL (<subquery>) AS <alias> ON <on>` — Eloquent
    /// `joinLateral`. The subquery may read columns from the outer
    /// query, which is how you get "top-N rows per group". Put that
    /// correlation in the subquery's own `WHERE`, using
    /// [`crate::core::joins::aliased`] against the outer table, and
    /// pass `WhereExpr::And(vec![])` as `on` to emit `ON true`.
    ///
    /// **PostgreSQL and MySQL 8.0.14+ only.** SQLite has no `LATERAL`,
    /// so the writer raises
    /// [`crate::sql::SqlError::LateralJoinNotSupported`].
    #[must_use]
    pub fn join_lateral(
        self,
        sub: impl Into<crate::core::DerivedSource>,
        alias: &'static str,
        on: WhereExpr,
    ) -> Self {
        self.push_subquery_join(
            sub,
            alias,
            crate::core::JoinKind::Inner,
            on,
            /*lateral=*/ true,
        )
    }

    /// `LEFT JOIN LATERAL (<subquery>) AS <alias> ON <on>` — the
    /// left-join form of [`Self::join_lateral`] (Eloquent
    /// `leftJoinLateral`). Keeps every outer row even when the lateral
    /// subquery returns none, as in "latest order per customer,
    /// including customers with no orders". **PG / MySQL only.**
    #[must_use]
    pub fn left_join_lateral(
        self,
        sub: impl Into<crate::core::DerivedSource>,
        alias: &'static str,
        on: WhereExpr,
    ) -> Self {
        self.push_subquery_join(
            sub,
            alias,
            crate::core::JoinKind::Left,
            on,
            /*lateral=*/ true,
        )
    }

    /// Shared builder for the four derived-table join methods.
    #[must_use]
    fn push_subquery_join(
        mut self,
        sub: impl Into<crate::core::DerivedSource>,
        alias: &'static str,
        kind: crate::core::JoinKind,
        on: WhereExpr,
        lateral: bool,
    ) -> Self {
        self.subquery_joins.push(crate::core::SubqueryJoin {
            subquery: sub.into(),
            alias,
            kind,
            on,
            lateral,
        });
        self
    }

    /// Cap the number of returned rows. A later call replaces the cap.
    #[must_use]
    pub fn limit(mut self, n: i64) -> Self {
        self.limit = Some(n);
        self
    }

    /// Skip the first `n` rows. Pair with [`limit`](Self::limit) for paging.
    #[must_use]
    pub fn offset(mut self, n: i64) -> Self {
        self.offset = Some(n);
        self
    }

    /// Eloquent `Builder::take($n)` — alias of [`Self::limit`].
    /// Cap the result to at most `n` rows.
    #[must_use]
    pub fn take(self, n: i64) -> Self {
        self.limit(n)
    }

    /// Eloquent `Builder::skip($n)` — alias of [`Self::offset`].
    #[must_use]
    pub fn skip(self, n: i64) -> Self {
        self.offset(n)
    }

    /// Append a `WHERE field <op> value` predicate with an explicit
    /// `Op`. Use it when you already know the operator; for the
    /// `filter("field__lookup", value)` shape see [`Self::filter`].
    ///
    /// `field` is the Rust-side field name. The column is looked up in
    /// the schema at compile time.
    #[must_use]
    pub fn filter_op(
        mut self,
        field: impl Into<String>,
        op: Op,
        value: impl Into<SqlValue>,
    ) -> Self {
        self.pending.push(PendingFilter::Raw(RawFilter {
            field: field.into(),
            op,
            value: value.into(),
        }));
        self
    }

    /// Append a `WHERE` predicate. Parses a `"field"` or
    /// `"field__lookup"` key and picks the matching `Op`.
    ///
    /// | Suffix | SQL | Value treatment |
    /// |---|---|---|
    /// | (none) / `__exact` | `<col> = ?` | as-is |
    /// | `__iexact` | `<col> ILIKE ?` | as-is (no wildcards) |
    /// | `__contains` | `<col> LIKE ?` | wrap `%value%` |
    /// | `__icontains` | `<col> ILIKE ?` | wrap `%value%` |
    /// | `__startswith` | `<col> LIKE ?` | wrap `value%` |
    /// | `__istartswith` | `<col> ILIKE ?` | wrap `value%` |
    /// | `__endswith` | `<col> LIKE ?` | wrap `%value` |
    /// | `__iendswith` | `<col> ILIKE ?` | wrap `%value` |
    /// | `__like` / `__ilike` / `__not_like` / `__not_ilike` | `<col> [NOT] (I)LIKE ?` | value bound verbatim — caller controls `%` / `_` placement. Eloquent `whereLike` / `whereNotLike` parity. |
    /// | `__gt` / `__gte` / `__lt` / `__lte` | direct map | as-is |
    /// | `__ne` | `<col> <> ?` | as-is |
    /// | `__in` | `<col> IN (...)` | value must be `SqlValue::List` |
    /// | `__not_in` | `<col> NOT IN (...)` | value must be `SqlValue::List`. Eloquent `whereNotIn` parity. |
    /// | `__isnull` | `<col> IS NULL` / `IS NOT NULL` | value must be `bool` |
    /// | `__between` / `__range` | `<col> BETWEEN ? AND ?` | value must be 2-element `SqlValue::List` |
    /// | `__not_between` / `__not_range` | `<col> NOT BETWEEN ? AND ?` | value must be 2-element `SqlValue::List`. Eloquent `whereNotBetween` parity. |
    /// | `__year` / `__month` / `__day` / `__hour` / `__minute` / `__second` / `__quarter` / `__week` / `__week_day` | `EXTRACT(<part> FROM <col>) = ?` | scalar value matches the date part. Composes with a trailing `__gte` / `__lt` / etc. `__quarter` works on every dialect; SQLite derives it from the month. `__week` numbering differs per backend. |
    /// | `__date` | `DATE(<col>) = ?` | value is a `chrono::NaiveDate`; strips the time component before comparison. |
    ///
    /// ```ignore
    /// Post::objects()
    ///     .filter("title__icontains", "rust")
    ///     .filter("views__gt", 100_i64)
    ///     .filter("author_id__in", rustango::core::SqlValue::List(vec![
    ///         1_i64.into(), 2_i64.into(), 3_i64.into(),
    ///     ]))
    ///     .fetch(&pool).await?;
    /// ```
    ///
    /// Unknown suffixes surface as [`QueryError::UnknownLookup`] at
    /// `compile()`. A wrong value shape, such as `__in` with a non-list
    /// value, surfaces as [`QueryError::InvalidLookupValue`].
    ///
    /// Relation-spanning keys such as `author__name__icontains` work on
    /// the SELECT path: `compile()` adds the FK-chain JOINs for you.
    /// They are not supported on update, delete or aggregate paths,
    /// which error instead.
    #[must_use]
    pub fn filter(mut self, key: &str, value: impl Into<SqlValue>) -> Self {
        self.pending.push(parse_to_pending(key, value.into()));
        self
    }

    /// The negation of [`Self::filter`]. Each call wraps **its own**
    /// predicate in `NOT (…)`, and chained excludes AND together. The
    /// full `__lookup` grammar works here too.
    ///
    /// ```ignore
    /// Post::objects().exclude("status", "draft").fetch(&pool).await?;
    /// // with a lookup suffix:
    /// Post::objects().exclude("views__lt", 100_i64)
    /// ```
    ///
    /// **NULLs:** `NOT (col = v)` also drops rows where `col IS NULL`,
    /// because of SQL three-valued logic. To put one `NOT` over a
    /// whole group of conditions, use `where_raw(!Q(...))`.
    #[must_use]
    pub fn exclude(mut self, key: &str, value: impl Into<SqlValue>) -> Self {
        self.pending
            .push(PendingFilter::Negated(Box::new(parse_to_pending(
                key,
                value.into(),
            ))));
        self
    }

    /// Stash a builder-time error to surface at `compile()` time.
    /// Used by [`Self::filter`] when the lookup-suffix parser fails.
    fn with_pending_error(mut self, e: QueryError) -> Self {
        // `compile()`'s `resolve_pending` walk surfaces the error.
        self.pending.push(PendingFilter::Error(e));
        self
    }

    /// Shorthand for `filter_op(field, Op::Eq, value)`.
    #[must_use]
    pub fn eq(self, field: impl Into<String>, value: impl Into<SqlValue>) -> Self {
        self.filter_op(field, Op::Eq, value)
    }

    /// Eloquent `Builder::whereKey($pk)`. Filter on the model's
    /// primary key without naming the column; it comes from
    /// `T::SCHEMA.primary_key()`.
    ///
    /// ```ignore
    /// // Eloquent: Post::query()->whereKey(42)->first();
    /// // rustango:
    /// let post = Post::objects()
    ///     .where_key(42_i64)
    ///     .first(&pool).await?;
    /// ```
    ///
    /// Models without `#[rustango(primary_key)]` surface as
    /// [`QueryError::UnknownField`] (field `"<pk>"`) at compile time.
    #[must_use]
    pub fn where_key(self, pk: impl Into<SqlValue>) -> Self {
        match T::SCHEMA.primary_key() {
            Some(f) => self.filter_op(f.name, Op::Eq, pk),
            None => self.with_pending_error(QueryError::UnknownField {
                model: T::SCHEMA.name,
                field: "<pk>".to_string(),
            }),
        }
    }

    /// Eloquent `Builder::whereKeyNot($pk)`. The opposite of
    /// [`Self::where_key`]: matches every row whose PK is not `pk`.
    ///
    /// ```ignore
    /// // Eloquent: Post::query()->whereKeyNot(1)->get();
    /// let others = Post::objects()
    ///     .where_key_not(1_i64)
    ///     .fetch(&pool).await?;
    /// ```
    ///
    /// Errors as [`Self::where_key`] when the model carries no PK.
    #[must_use]
    pub fn where_key_not(self, pk: impl Into<SqlValue>) -> Self {
        match T::SCHEMA.primary_key() {
            Some(f) => self.filter_op(f.name, Op::Ne, pk),
            None => self.with_pending_error(QueryError::UnknownField {
                model: T::SCHEMA.name,
                field: "<pk>".to_string(),
            }),
        }
    }

    /// Eloquent `Builder::whereExists($closure)`. ANDs an
    /// `EXISTS (subquery)` predicate onto this queryset's WHERE.
    ///
    /// `subquery` is an already-compiled [`SelectQuery`]. Build it from
    /// the inner model's `objects()` chain and call `.compile()`, so a
    /// column typo surfaces there. Use
    /// [`crate::core::subquery::outer_ref`] to refer to columns of the
    /// outer model.
    ///
    /// ```ignore
    /// use rustango::core::Column as _;
    /// use rustango::core::subquery::outer_ref;
    ///
    /// // Authors who have at least one book.
    /// let with_books = Book::objects()
    ///     .where_(Book::author_id.eq_expr(outer_ref("id")))
    ///     .compile()?;
    /// let authors = Author::objects()
    ///     .where_exists(with_books)
    ///     .fetch(&pool).await?;
    /// ```
    ///
    /// Sugar over `self.where_raw(subquery::exists(subquery))`.
    #[must_use]
    pub fn where_exists(self, subquery: SelectQuery) -> Self {
        self.where_raw(crate::core::subquery::exists(subquery))
    }

    /// Eloquent `Builder::whereNotExists($closure)`. ANDs a
    /// `NOT EXISTS (subquery)` predicate. The inverse of
    /// [`Self::where_exists`], and the usual way to find rows in A with
    /// no related row in B.
    ///
    /// ```ignore
    /// let no_books = Book::objects()
    ///     .where_(Book::author_id.eq_expr(outer_ref("id")))
    ///     .compile()?;
    /// let empty = Author::objects()
    ///     .where_not_exists(no_books)
    ///     .fetch(&pool).await?;
    /// ```
    #[must_use]
    pub fn where_not_exists(self, subquery: SelectQuery) -> Self {
        self.where_raw(crate::core::subquery::not_exists(subquery))
    }

    /// Eloquent `Builder::whereIn($column, $closure)` with a subquery
    /// instead of a value list. Emits `<column> IN (subquery)`.
    ///
    /// `subquery` is an already-compiled [`SelectQuery`] that should
    /// project one column, matched against `column` on the outer model.
    ///
    /// ```ignore
    /// let public_cat_ids = Category::objects()
    ///     .filter("is_public", true)
    ///     .values_list_flat("id")
    ///     .compile()?;
    /// let visible = Post::objects()
    ///     .where_in_subquery("category_id", public_cat_ids)
    ///     .fetch(&pool).await?;
    /// ```
    #[must_use]
    pub fn where_in_subquery(self, column: &'static str, subquery: SelectQuery) -> Self {
        self.where_raw(crate::core::subquery::in_subquery(column, subquery))
    }

    /// Eloquent `Builder::whereNotIn($column, $closure)`. The inverse
    /// of [`Self::where_in_subquery`]; emits
    /// `<column> NOT IN (subquery)`.
    #[must_use]
    pub fn where_not_in_subquery(self, column: &'static str, subquery: SelectQuery) -> Self {
        self.where_raw(crate::core::subquery::not_in_subquery(column, subquery))
    }

    /// Keep rows that have at least one related row through the
    /// relation named `name`.
    ///
    /// `name` is looked up in three relation kinds, in this order, so
    /// the same call works however the relation is declared on `T`:
    /// - **reverse-FK** — `EXISTS (SELECT 1 FROM <child> WHERE
    ///   <child_fk> = <outer>.<pk>)`.
    /// - **many-to-many** — the same `EXISTS` over the junction table.
    /// - **generic-FK** — the same `EXISTS` over the polymorphic child,
    ///   AND-ed with a content-type check so only children pointing at
    ///   *this* model match.
    ///
    /// All three emit the same way on PG, MySQL and SQLite. An unknown
    /// relation name surfaces as [`QueryError::UnknownField`] at
    /// `compile()` time.
    ///
    /// ```ignore
    /// // Authors with at least one book (reverse-FK relation "books").
    /// let with_books = Author::objects()
    ///     .where_has("books")
    ///     .fetch(&pool).await?;
    /// ```
    #[must_use]
    pub fn where_has(self, name: &str) -> Self {
        match Self::resolve_rel_exists(name, /*negated=*/ false) {
            Some(expr) => self.where_raw(expr),
            None => self.with_pending_error(QueryError::UnknownField {
                model: T::SCHEMA.name,
                field: name.to_string(),
            }),
        }
    }

    /// This model's primary-key column name (defaults to `"id"`). Used
    /// to correlate M2M relation subqueries back to the parent row.
    fn self_pk_column() -> &'static str {
        T::SCHEMA.primary_key().map_or("id", |f| f.column)
    }

    /// Turn a relation `name` (reverse-FK, many-to-many or generic-FK)
    /// into a correlated `[NOT ]EXISTS` predicate. Returns `None` when
    /// no relation matches, so callers can raise
    /// [`QueryError::UnknownField`]. Lookup order is reverse-FK, M2M,
    /// then GFK; names should be unique across the three.
    fn resolve_rel_exists(name: &str, negated: bool) -> Option<WhereExpr> {
        use crate::core::subquery;
        if let Some(rel) = T::reverse_relations().iter().find(|r| r.name == name) {
            return Some(if negated {
                subquery::reverse_has_not_exists(rel)
            } else {
                subquery::reverse_has_exists(rel)
            });
        }
        if let Some(m2m) = T::SCHEMA.m2m.iter().find(|m| m.name == name) {
            return Some(subquery::m2m_has_exists(
                m2m,
                Self::self_pk_column(),
                negated,
            ));
        }
        if let Some(g) = T::generic_reverse_relations()
            .iter()
            .find(|g| g.name == name)
        {
            return Some(subquery::generic_has_exists(g, T::SCHEMA.table, negated));
        }
        None
    }

    /// Turn a relation `name` into a correlated scalar `COUNT` [`Expr`],
    /// the left side of a `has($rel, op, n)` comparison. Covers
    /// reverse-FK, M2M and GFK. `None` if the name is unknown.
    fn resolve_rel_count(name: &str) -> Option<Expr> {
        use crate::core::{subquery, RelAggKind};
        if let Some(rel) = T::reverse_relations().iter().find(|r| r.name == name) {
            return Some(subquery::reverse_has_count(rel));
        }
        if let Some(m2m) = T::SCHEMA.m2m.iter().find(|m| m.name == name) {
            return Some(subquery::m2m_has_aggregate(
                m2m,
                Self::self_pk_column(),
                RelAggKind::Count,
                None,
            ));
        }
        if let Some(g) = T::generic_reverse_relations()
            .iter()
            .find(|g| g.name == name)
        {
            return Some(subquery::generic_has_aggregate(
                g,
                T::SCHEMA.table,
                RelAggKind::Count,
                None,
            ));
        }
        None
    }

    /// The opposite of [`Self::where_has`]: keep rows that have **no**
    /// related row. Emits `NOT EXISTS (subquery)`. Same relation lookup
    /// and same errors.
    ///
    /// ```ignore
    /// // Authors with zero books.
    /// let empty = Author::objects()
    ///     .where_doesnt_have("books")
    ///     .fetch(&pool).await?;
    /// ```
    #[must_use]
    pub fn where_doesnt_have(self, name: &str) -> Self {
        match Self::resolve_rel_exists(name, /*negated=*/ true) {
            Some(expr) => self.where_raw(expr),
            None => self.with_pending_error(QueryError::UnknownField {
                model: T::SCHEMA.name,
                field: name.to_string(),
            }),
        }
    }

    /// Keep rows with at least one related row through the named
    /// reverse-FK relation **and** matching your inner predicate.
    /// Eloquent `Builder::whereHas($rel, fn ($q) => …)`.
    ///
    /// `inner` is a compiled `SelectQuery` on the child model, usually
    /// `Child::objects().filter(...).compile()?`. Its `WHERE` is ANDed
    /// with the correlation `<child_fk_column> = <outer>.<self_pk>`,
    /// and the result is wrapped in `EXISTS (…)`.
    ///
    /// `inner.model` must be the relation's child model. A mismatch
    /// surfaces as [`QueryError::UnknownField`] at compile time.
    ///
    /// ```ignore
    /// // Eloquent: Author::whereHas('books', fn ($q) => $q->where('published', true))->get();
    /// let inner = Book::objects().filter("published", true).compile()?;
    /// let authors = Author::objects()
    ///     .where_has_filter("books", inner)
    ///     .fetch(&pool).await?;
    /// ```
    #[must_use]
    pub fn where_has_filter(self, name: &str, inner: SelectQuery) -> Self {
        self.where_has_filter_impl(name, inner, /*negated=*/ false)
    }

    /// `whereDoesntHave($rel, fn ($q) => …)`, the counterpart of
    /// [`Self::where_has_filter`]. Keeps rows with **no** related row
    /// matching the inner predicate, using `NOT EXISTS (…)`.
    #[must_use]
    pub fn where_doesnt_have_filter(self, name: &str, inner: SelectQuery) -> Self {
        self.where_has_filter_impl(name, inner, /*negated=*/ true)
    }

    /// Internal worker shared by [`Self::where_has_filter`] and
    /// [`Self::where_doesnt_have_filter`]. `negated = true` wraps the
    /// merged inner SELECT in `NOT EXISTS` instead of `EXISTS`.
    fn where_has_filter_impl(self, name: &str, mut inner: SelectQuery, negated: bool) -> Self {
        let rel = match T::reverse_relations().iter().find(|r| r.name == name) {
            Some(r) => r,
            None => {
                return self.with_pending_error(QueryError::UnknownField {
                    model: T::SCHEMA.name,
                    field: name.to_string(),
                });
            }
        };
        // Guard against an inner queryset built on the wrong child
        // model, which would silently produce wrong SQL. `Model::SCHEMA`
        // is a `const`, so each use site may get its own address and
        // pointer equality is unreliable. Compare by model name, which
        // is unique within the crate.
        if inner.model.name != rel.child_schema.name {
            return self.with_pending_error(QueryError::UnknownField {
                model: T::SCHEMA.name,
                field: format!(
                    "where_has_filter({name}): inner queryset model mismatch — \
                     expected `{}`, got `{}`",
                    rel.child_schema.name, inner.model.name
                ),
            });
        }
        let correlated = WhereExpr::ExprCompare {
            lhs: crate::core::Expr::Column(rel.child_fk_column),
            op: Op::Eq,
            rhs: crate::core::Expr::OuterRef(rel.self_pk_column),
        };
        // AND the correlation onto whatever is already on the inner
        // SelectQuery. Flatten a nested `And` to keep the tree shallow.
        inner.where_clause =
            match std::mem::replace(&mut inner.where_clause, WhereExpr::And(Vec::new())) {
                WhereExpr::And(mut v) => {
                    v.push(correlated);
                    WhereExpr::And(v)
                }
                other => WhereExpr::And(vec![other, correlated]),
            };
        let wrapped = if negated {
            WhereExpr::NotExists(Box::new(inner))
        } else {
            WhereExpr::Exists(Box::new(inner))
        };
        self.where_raw(wrapped)
    }

    /// Keep rows whose **count** of related rows satisfies
    /// `<count> <op> n`.
    ///
    /// Emits a correlated aggregate subquery in the WHERE clause:
    /// `(SELECT COUNT(*) FROM <child> WHERE <child_fk> =
    /// <outer>.<self_pk>) <op> n`. It runs the same on PG, MySQL and
    /// SQLite.
    ///
    /// `op` must be a comparison: [`Op::Eq`], [`Op::Ne`], [`Op::Lt`],
    /// [`Op::Lte`], [`Op::Gt`] or [`Op::Gte`]. Anything else errors at
    /// compile time. For "has at least one" or "has none", prefer
    /// [`Self::where_has`] / [`Self::where_doesnt_have`], which emit a
    /// cheaper `EXISTS`.
    ///
    /// An unknown relation name surfaces as
    /// [`QueryError::UnknownField`], as in [`Self::where_has`].
    ///
    /// ```ignore
    /// // Eloquent: Author::has('books', '>', 3)->get();
    /// let prolific = Author::objects()
    ///     .where_has_count("books", Op::Gt, 3)
    ///     .fetch(&pool).await?;
    /// ```
    #[must_use]
    pub fn where_has_count(self, name: &str, op: Op, n: i64) -> Self {
        match Self::resolve_rel_count(name) {
            Some(lhs) => self.where_raw(WhereExpr::ExprCompare {
                lhs,
                op,
                rhs: Expr::Literal(SqlValue::I64(n)),
            }),
            None => self.with_pending_error(QueryError::UnknownField {
                model: T::SCHEMA.name,
                field: name.to_string(),
            }),
        }
    }

    /// Add the **count** of related rows as a `<name>_count` column.
    ///
    /// This turns the queryset into an [`AggregateBuilder`], whose rows
    /// are `Vec<HashMap<String, SqlValue>>`, like every other
    /// [`QuerySet::annotate`] path: a typed `T` has no field for the
    /// derived column. Each row carries every scalar column of `T` plus
    /// the `<name>_count` key.
    ///
    /// The count comes from a correlated subquery, not a `JOIN`, so it
    /// never double-counts and causes no N+1.
    ///
    /// An unknown relation name surfaces as
    /// [`QueryError::UnknownField`] at `compile()` time.
    ///
    /// ```ignore
    /// // Eloquent: Author::withCount('books')->get();
    /// let rows = Author::objects()
    ///     .annotate_count("books")
    ///     .fetch(&pool).await?;
    /// // rows[0]["books_count"] => SqlValue::I64(n)
    /// ```
    #[must_use]
    pub fn annotate_count(self, name: &str) -> AggregateBuilder<T> {
        self.annotate_relation_aggregate(name, None, AggregateExpr::Count(None), "count")
    }

    /// Add `SUM(<column>)` over related rows as `<name>_sum_<column>`.
    /// Eloquent `withSum('orders', 'total')`. `column` belongs to the
    /// **child** model and is checked at `compile()` time. See
    /// [`Self::annotate_count`] for the return shape.
    #[must_use]
    pub fn annotate_sum(self, name: &str, column: &'static str) -> AggregateBuilder<T> {
        self.annotate_relation_aggregate(name, Some(column), AggregateExpr::Sum(column), "sum")
    }

    /// Add `AVG(<column>)` over related rows as `<name>_avg_<column>`.
    /// Eloquent `withAvg('orders', 'total')`. See
    /// [`Self::annotate_sum`].
    #[must_use]
    pub fn annotate_avg(self, name: &str, column: &'static str) -> AggregateBuilder<T> {
        self.annotate_relation_aggregate(name, Some(column), AggregateExpr::Avg(column), "avg")
    }

    /// Add `MAX(<column>)` over related rows as `<name>_max_<column>`.
    /// Eloquent `withMax('orders', 'total')`. See
    /// [`Self::annotate_sum`].
    #[must_use]
    pub fn annotate_max(self, name: &str, column: &'static str) -> AggregateBuilder<T> {
        self.annotate_relation_aggregate(name, Some(column), AggregateExpr::Max(column), "max")
    }

    /// Add `MIN(<column>)` over related rows as `<name>_min_<column>`.
    /// Eloquent `withMin('orders', 'total')`. See
    /// [`Self::annotate_sum`].
    #[must_use]
    pub fn annotate_min(self, name: &str, column: &'static str) -> AggregateBuilder<T> {
        self.annotate_relation_aggregate(name, Some(column), AggregateExpr::Min(column), "min")
    }

    /// Add a `<name>_exists` column saying whether **any** related row
    /// exists.
    ///
    /// Emits `CASE WHEN EXISTS (…) THEN 1 ELSE 0 END`, which is cheaper
    /// than [`Self::annotate_count`] when you only need presence,
    /// because `EXISTS` stops at the first matching child row. The
    /// column decodes as `SqlValue::I64(1)` or `I64(0)` on all three
    /// backends; integer literals keep the value the same everywhere.
    /// See [`Self::annotate_count`] for the return shape.
    ///
    /// An unknown relation name surfaces as
    /// [`QueryError::UnknownField`] at `compile()` time.
    #[must_use]
    pub fn annotate_exists(self, name: &str) -> AggregateBuilder<T> {
        let mut builder = self.aggregate();
        builder.push_relation_exists(name);
        builder
    }

    /// Shared worker for the `annotate_{count,sum,avg,max,min}` family.
    /// Resolves the reverse relation, names the projected column
    /// (`<name>_count` or `<name>_<suffix>_<column>`), wraps the
    /// correlated subquery in an [`AggregateExpr::RelatedAggregate`],
    /// and stages it on a fresh [`AggregateBuilder`].
    ///
    /// Errors are held on the builder and surface from `compile()`: an
    /// unknown relation name gives [`QueryError::UnknownField`] on `T`,
    /// and a `column` that is not a child field gives the same error
    /// keyed on the child schema.
    fn annotate_relation_aggregate(
        self,
        name: &str,
        column: Option<&'static str>,
        agg: AggregateExpr,
        suffix: &str,
    ) -> AggregateBuilder<T> {
        // The resolve-and-push worker lives on `AggregateBuilder` so a
        // query can chain more than one relation aggregate. Here we
        // just open a builder and delegate.
        let mut builder = self.aggregate();
        builder.push_relation_aggregate(name, column, agg, suffix);
        builder
    }

    /// Eloquent `Builder::whereColumn($col1, $col2)`. Emits
    /// `<col1> = <col2>`, comparing two columns instead of a column
    /// and a literal. For any other operator, see
    /// [`Self::where_column_op`].
    ///
    /// Both column names are checked against the schema at
    /// `compile()` time, through
    /// [`WhereExpr::ExprCompare`](crate::core::WhereExpr::ExprCompare).
    ///
    /// ```ignore
    /// // Eloquent: User::whereColumn('first_name', 'last_name');
    /// User::objects()
    ///     .where_column("first_name", "last_name")
    ///     .fetch(&pool).await?;
    /// ```
    #[must_use]
    pub fn where_column(self, col1: &'static str, col2: &'static str) -> Self {
        self.where_column_op(col1, Op::Eq, col2)
    }

    /// Eloquent `Builder::whereColumn($col1, $op, $col2)`. Compares
    /// two columns with an explicit operator. Use the shorter
    /// [`Self::where_column`] when the operator is `Eq`.
    ///
    /// ```ignore
    /// use rustango::core::Op;
    /// // start_date < end_date — Eloquent: whereColumn('start_date', '<', 'end_date')
    /// Reservation::objects()
    ///     .where_column_op("start_date", Op::Lt, "end_date")
    ///     .fetch(&pool).await?;
    /// ```
    #[must_use]
    pub fn where_column_op(self, col1: &'static str, op: Op, col2: &'static str) -> Self {
        use crate::core::F;
        self.where_raw(WhereExpr::ExprCompare {
            lhs: F(col1).into(),
            op,
            rhs: F(col2).into(),
        })
    }

    /// AND a raw [`WhereExpr`] into the accumulated WHERE clause. Use
    /// it when the model has no derived typed columns, so
    /// [`Self::where_`] is unavailable, and you need OR / NOT / nested
    /// predicates that the string-keyed [`Self::filter`] cannot reach.
    ///
    /// The expression is checked against `T::SCHEMA` at `compile()`
    /// time. An unknown column or a wrong-typed value returns
    /// [`QueryError::UnknownField`] or [`QueryError::TypeMismatch`],
    /// as on the typed paths.
    #[must_use]
    pub fn where_raw(mut self, expr: WhereExpr) -> Self {
        self.pending.push(PendingFilter::Expr(expr));
        self
    }

    /// Eloquent `Builder::when($condition, $callback)`. Applies `f` to
    /// `self` only when `condition` is `true`, and otherwise returns
    /// `self` unchanged. It keeps a conditional filter inside the
    /// chain:
    ///
    /// ```ignore
    /// let qs = Post::objects()
    ///     .when(only_active, |qs| qs.filter("active", true))
    ///     .when(category_id.is_some(), |qs| {
    ///         qs.filter("category_id", category_id.unwrap())
    ///     });
    /// ```
    ///
    /// Equivalent to:
    ///
    /// ```ignore
    /// let mut qs = Post::objects();
    /// if only_active { qs = qs.filter("active", true); }
    /// if let Some(id) = category_id { qs = qs.filter("category_id", id); }
    /// ```
    ///
    /// The closure form keeps the chain readable when the condition is
    /// an inline expression rather than a plain `bool`.
    #[must_use]
    pub fn when<F>(self, condition: bool, f: F) -> Self
    where
        F: FnOnce(Self) -> Self,
    {
        if condition {
            f(self)
        } else {
            self
        }
    }

    /// Eloquent `Builder::unless($condition, $callback)`. The inverse
    /// of [`Self::when`]: applies `f` only when `condition` is `false`.
    /// Use it when the guard reads better stated negatively, such as
    /// `qs.unless(is_admin, |q| q.filter("public", true))`.
    #[must_use]
    pub fn unless<F>(self, condition: bool, f: F) -> Self
    where
        F: FnOnce(Self) -> Self,
    {
        if condition {
            self
        } else {
            f(self)
        }
    }

    /// Eloquent `Builder::tap($callback)`. Runs a callback against the
    /// queryset and returns it unchanged, so you can add logging,
    /// metrics or a debug print without breaking the chain:
    ///
    /// ```ignore
    /// let rows = Post::objects()
    ///     .filter("active", true)
    ///     .tap(|qs| tracing::debug!(?qs, "about to fetch"))
    ///     .fetch(&pool).await?;
    /// ```
    #[must_use]
    pub fn tap<F>(self, f: F) -> Self
    where
        F: FnOnce(&Self),
    {
        f(&self);
        self
    }

    /// Keep only rows that are NOT soft-deleted.
    ///
    /// When `T` has `#[rustango(soft_delete)]` on a nullable
    /// `DateTime<Utc>` column, this ANDs `<col> IS NULL` into the WHERE
    /// clause. Models without a soft-delete column get a no-op, so
    /// generic code can call `.active()` on any model. See
    /// [`crate::soft_delete::active_filter`].
    #[must_use]
    pub fn active(self) -> Self {
        match crate::soft_delete::active_filter(T::SCHEMA) {
            Some(expr) => self.where_raw(expr),
            None => self,
        }
    }

    /// Keep ONLY soft-deleted rows — the mirror of [`Self::active`],
    /// for trash pages and restore flows. A no-op when the model has
    /// no soft-delete column. Eloquent `onlyTrashed`.
    #[must_use]
    pub fn only_trashed(self) -> Self {
        match crate::soft_delete::trashed_filter(T::SCHEMA) {
            Some(expr) => self.where_raw(expr),
            None => self,
        }
    }

    /// Eloquent `withTrashed`. A no-op marker that states intent: a
    /// `QuerySet` already includes trashed rows unless you call
    /// [`Self::active`] or the model declares a global scope that
    /// filters them out.
    #[must_use]
    pub fn with_trashed(self) -> Self {
        self
    }

    /// Append a typed predicate or boolean expression built with the
    /// [`Column`](crate::core::Column) API. Takes a single
    /// [`TypedFilter`](crate::core::TypedFilter) (`User::id.gt(10)`) or
    /// a composed [`TypedExpr`] (`User::id.eq(1).or(User::id.eq(2))`).
    /// Every call ANDs its argument into the WHERE clause.
    #[must_use]
    pub fn where_<E: Into<TypedExpr<T>>>(mut self, predicate: E) -> Self {
        let expr = predicate.into().into_expr();
        // Put a bare predicate in the `Resolved` slot so a simple chain
        // stays a flat AND-of-predicates, which `as_flat_and()` needs.
        match expr {
            WhereExpr::Predicate(filter) => {
                self.pending.push(PendingFilter::Resolved(filter));
            }
            other => {
                self.pending.push(PendingFilter::Expr(other));
            }
        }
        self
    }

    /// [`Self::compile`], or `None` after [`Self::none`], so counts and
    /// aggregates answer without a round trip.
    pub(crate) fn compile_unless_none(self) -> Result<Option<SelectQuery>, QueryError> {
        let none = self.is_none;
        let select = self.compile()?;
        Ok((!none).then_some(select))
    }

    /// Validate the accumulated filters against `T::SCHEMA` and lower to
    /// the dialect-neutral `SelectQuery` IR.
    ///
    /// # Errors
    /// Returns [`QueryError::UnknownField`] if a filter names a field not
    /// present on the model, and [`QueryError::TypeMismatch`] if the bound
    /// value's type does not match the field's declared type.
    pub fn compile(mut self) -> Result<SelectQuery, QueryError> {
        // Fold the schema's global scopes into the pending list, minus
        // any opt-outs, before the resolver sees it. After this the
        // resolver cannot tell a scope filter from a user filter.
        self.apply_global_scopes();
        let model: &'static ModelSchema = T::SCHEMA;
        // Lower relation-spanning lookups (`author__name`) into aliased
        // predicates plus their FK-chain JOINs before resolving the
        // WHERE. Those JOINs merge into the select_related set below.
        let (pending, span_joins) = lower_relation_spans(model, self.pending)?;
        let where_clause = resolve_pending(model, pending)?;
        let mut joins = lower_select_related(model, &self.select_related)?;
        // Ad-hoc joins come after the FK-driven select_related ones, so
        // column order stays stable and user joins sit next to the user
        // WHERE.
        joins.extend(self.ad_hoc_joins);
        // Skip a span JOIN whose alias is already here, so a span over
        // the same path as a select_related emits only once.
        for j in span_joins {
            if !joins.iter().any(|e| e.alias == j.alias) {
                joins.push(j);
            }
        }
        // Split head-branch clauses from combined-result clauses. With
        // a compound, `head_*` holds what was frozen at the first
        // set-op call and the live slots apply to the merged result.
        // Without one, the live slots are the query's own.
        let has_compound = !self.compound.is_empty();
        let (head_pending, head_limit, head_offset, comb_pending, comb_limit, comb_offset) =
            if has_compound {
                (
                    std::mem::take(&mut self.head_order_by),
                    self.head_limit,
                    self.head_offset,
                    std::mem::take(&mut self.order_by),
                    self.limit,
                    self.offset,
                )
            } else {
                (
                    std::mem::take(&mut self.order_by),
                    self.limit,
                    self.offset,
                    Vec::new(),
                    None,
                    None,
                )
            };
        // Lower the pending list to OrderItems, keeping insertion order
        // across all the `.order_by*` variants so a mixed chain emits
        // as written. `order_by` is the head (or only) ordering; the
        // combined-result ordering lowers on the next line.
        let (order_by, order_joins) = lower_order_items(model, head_pending)?;
        let (compound_order_by, comb_order_joins) = lower_order_items(model, comb_pending)?;
        // Merge relation-span `order_by` JOINs into the join set,
        // skipping aliases already added above.
        for j in order_joins.into_iter().chain(comb_order_joins) {
            if !joins.iter().any(|e| e.alias == j.alias) {
                joins.push(j);
            }
        }
        // `.distinct_on(&[...])` needs its columns at the head of the
        // ORDER BY, so catch a mismatch at compile time.
        // An empty list is rejected: it would just mean `.distinct()`.
        if let Some(crate::core::DistinctMode::On(cols)) = &self.distinct {
            if cols.is_empty() {
                return Err(QueryError::DistinctOnEmpty);
            }
            for col in cols {
                if model.field_by_column(col).is_none() {
                    return Err(QueryError::UnknownField {
                        model: model.name,
                        field: (*col).to_owned(),
                    });
                }
            }
            // The first `cols.len()` order_by items must be those
            // columns, in order. Only bare `OrderItem::Column` counts;
            // an expression or random cannot be a DISTINCT ON key.
            if order_by.len() < cols.len() {
                return Err(QueryError::DistinctOnOrderByMismatch {
                    distinct_on: cols.iter().map(|s| (*s).to_owned()).collect(),
                    order_by: order_by_column_names(&order_by),
                });
            }
            for (i, col) in cols.iter().enumerate() {
                let head = match &order_by[i] {
                    crate::core::OrderItem::Column { column, .. } => *column,
                    _ => {
                        return Err(QueryError::DistinctOnOrderByMismatch {
                            distinct_on: cols.iter().map(|s| (*s).to_owned()).collect(),
                            order_by: order_by_column_names(&order_by),
                        });
                    }
                };
                if head != *col {
                    return Err(QueryError::DistinctOnOrderByMismatch {
                        distinct_on: cols.iter().map(|s| (*s).to_owned()).collect(),
                        order_by: order_by_column_names(&order_by),
                    });
                }
            }
        }
        // `.none()` forces an empty result with `LIMIT 0`; counts and
        // aggregates skip the query via `compile_unless_none`. The `LIMIT 0` goes
        // on the outermost slot: the combined result when a compound is
        // present, otherwise the single query.
        let (limit, compound_limit) = if self.is_none {
            if has_compound {
                (head_limit, Some(0))
            } else {
                (Some(0), comb_limit)
            }
        } else {
            (head_limit, comb_limit)
        };
        Ok(SelectQuery {
            model,
            where_clause,
            search: None,
            joins,
            subquery_joins: self.subquery_joins,
            order_by,
            limit,
            offset: head_offset,
            lock_mode: self.lock_mode,
            compound: self.compound,
            projection: None,
            distinct: self.distinct,
            compound_order_by,
            compound_limit,
            compound_offset: comb_offset,
        })
    }

    /// Project to `Vec<HashMap<String, SqlValue>>` — named columns
    /// only, no typed model. Returns a [`ValuesQuerySet`] whose
    /// `.fetch(&pool)` decodes rows into a `HashMap` keyed by column
    /// name.
    ///
    /// It skips the typed `Model` decode. Use it for a few fields off
    /// a wide table, or when the result feeds code that wants dynamic
    /// column access, such as templates, JSON or CSV export. For
    /// GROUP BY, use [`QuerySet::values`] instead, which promotes to
    /// [`AggregateBuilder`].
    ///
    /// Columns are checked against the schema at `.compile()` time. A
    /// typo gives [`QueryError::UnknownField`], and empty `cols` gives
    /// [`QueryError::EmptyValuesProjection`].
    #[must_use]
    pub fn values_dict(self, cols: &[&'static str]) -> ValuesQuerySet<T> {
        ValuesQuerySet {
            qs: self,
            cols: cols.to_vec(),
        }
    }

    /// Project to `Vec<Vec<SqlValue>>`. Same as [`Self::values_dict`],
    /// but each row is an ordered `Vec<SqlValue>` matching the `cols`
    /// order instead of a `HashMap`.
    #[must_use]
    pub fn values_list(self, cols: &[&'static str]) -> ValuesListQuerySet<T> {
        ValuesListQuerySet {
            qs: self,
            cols: cols.to_vec(),
        }
    }

    /// Single-column projection, flattened. Returns a
    /// [`ValuesFlatQuerySet`] whose `.fetch::<U>(&pool)` decodes the
    /// column into `Vec<U>` through sqlx's `query_scalar`.
    ///
    /// `U` must decode from the column's SQL type on every dialect the
    /// binary targets. Usually `i64`, `i32`, `String`, `bool` or `f64`.
    #[must_use]
    pub fn values_list_flat(self, col: &'static str) -> ValuesFlatQuerySet<T> {
        ValuesFlatQuerySet { qs: self, col }
    }

    /// Project only the listed columns.
    /// Same behaviour as [`Self::values_dict`]:
    /// the SQL is `SELECT cols FROM …` and each row is a
    /// `HashMap<String, SqlValue>` keyed by column name. The separate
    /// name just reads better at the call site.
    ///
    /// Columns are checked at `.compile()` time. A typo gives
    /// [`QueryError::UnknownField`], and an empty list gives
    /// [`QueryError::EmptyValuesProjection`].
    ///
    /// You get a `HashMap` rather than a partly filled `Model`: there
    /// are no lazy-loading field descriptors, so a half-built struct
    /// would silently read as zeroed.
    #[must_use]
    pub fn only(self, cols: &[&'static str]) -> ValuesQuerySet<T> {
        self.values_dict(cols)
    }

    /// Project every scalar column EXCEPT the listed ones — the
    /// inverse of [`Self::only`]. The SELECT leaves
    /// out the named columns, which saves IO on wide tables.
    ///
    /// Same return shape as [`Self::only`].
    ///
    /// A column that does not exist on the model gives
    /// [`QueryError::UnknownField`] at `.compile()` time, as it would
    /// in `.only(...)`. An empty list returns every scalar column.
    #[must_use]
    pub fn defer(self, cols: &[&'static str]) -> ValuesQuerySet<T> {
        let model = T::SCHEMA;
        let exclude: std::collections::HashSet<&'static str> = cols.iter().copied().collect();
        let mut projection: Vec<&'static str> = model
            .scalar_fields()
            .filter(|f| !exclude.contains(f.column))
            .map(|f| f.column)
            .collect();
        // Pass unknown defer columns into the projection so
        // `values_dict`'s `UnknownField` check rejects them.
        for &col in cols {
            if model.field_by_column(col).is_none() {
                projection.push(col);
            }
        }
        self.values_dict(&projection)
    }

    /// Lower this queryset to a `DeleteQuery` — same WHERE clause, no projection.
    /// `limit` / `offset` / `order_by` bound it by primary key.
    ///
    /// # Errors
    /// As [`QuerySet::compile`], plus [`QueryError::BoundedDmlUnsupported`]
    /// when a limit or offset cannot be bounded.
    pub fn compile_delete(mut self) -> Result<DeleteQuery, QueryError> {
        // Fold global scopes into the WHERE, so a bulk delete honours
        // the same filters as a fetch. A `published_only` scope means
        // a wholesale delete still cannot reach unpublished rows.
        self.apply_global_scopes();
        let model: &'static ModelSchema = T::SCHEMA;
        let where_clause = resolve_pending(model, self.pending)?;
        // `.none().delete()` must delete nothing. An `IS NULL` test on
        // the NOT NULL primary key makes sure no row matches.
        let where_clause = if self.is_none {
            never_match_clause(model, where_clause)?
        } else {
            where_clause
        };
        let where_clause = bound_dml_where(
            model,
            where_clause,
            self.order_by,
            self.limit,
            self.offset,
            !self.compound.is_empty(),
        )?;
        Ok(DeleteQuery {
            model,
            where_clause,
        })
    }

    /// Start an `UpdateBuilder` carrying this queryset's filters as the WHERE clause.
    #[must_use]
    pub fn update(self) -> UpdateBuilder<T> {
        UpdateBuilder {
            qs: self,
            set: Vec::new(),
        }
    }

    /// Start an [`AggregateBuilder`] carrying this queryset's filters as the
    /// WHERE clause. Chain `.group_by`, `.annotate`, `.having`, `.order_by`,
    /// `.limit`, `.offset` then call `.compile()` to get an [`AggregateQuery`].
    #[must_use]
    pub fn aggregate(self) -> AggregateBuilder<T> {
        AggregateBuilder {
            qs: self,
            group_by: Vec::new(),
            aggregates: Vec::new(),
            aliases: Vec::new(),
            having: None,
            order_by: Vec::new(),
            limit: None,
            offset: None,
            deferred_error: None,
            values: None,
        }
    }

    /// Group by the named columns.
    ///
    /// Switches the queryset into aggregate mode and records the
    /// projection columns. Followed by `.annotate("alias", aggregate)`,
    /// it emits `SELECT cols, AGGR(...) FROM t GROUP BY cols`; the
    /// GROUP BY comes from the values list.
    ///
    /// This is **shape 2** in the cheat-sheet on [`Self::annotate`].
    /// The same IR gives equivalent SQL on Postgres, MySQL and SQLite.
    ///
    /// ```ignore
    /// // "Posts per author".
    /// Post::objects()
    ///     .values(&["author_id"])
    ///     .annotate("n", count_all().into())
    ///     .compile()?;
    /// // → SELECT "author_id", COUNT(*) AS "n" FROM "post" GROUP BY "author_id"
    /// ```
    ///
    /// Filtering by an `.annotate()` alias routes to `HAVING`; filtering
    /// by a model column routes to `WHERE`:
    ///
    /// ```ignore
    /// // Authors with > 5 published posts.
    /// Post::objects()
    ///     .values(&["author_id"])
    ///     .annotate("n", count_all().into())
    ///     .filter("status", Op::Eq, "published") // → WHERE
    ///     .filter("n", Op::Gt, 5_i64)            // → HAVING
    ///     .compile()?;
    /// ```
    ///
    /// Calling `.values()` without a subsequent aggregating `.annotate(...)`
    /// is **shape 1** — a pure projection, with no GROUP BY emitted.
    #[must_use]
    pub fn values(self, columns: &[&'static str]) -> AggregateBuilder<T> {
        AggregateBuilder {
            qs: self,
            group_by: Vec::new(),
            aggregates: Vec::new(),
            aliases: Vec::new(),
            having: None,
            order_by: Vec::new(),
            limit: None,
            offset: None,
            deferred_error: None,
            values: Some(columns.to_vec()),
        }
    }

    /// Add a derived column without calling `.aggregate()`.
    ///
    /// Promotes to an [`AggregateBuilder`]. If the annotation
    /// aggregates rows (`Count`, `Sum`, `Avg`, …) and you did not call
    /// `.values()`, `compile()` fills GROUP BY with every
    /// non-aggregate scalar column. This is **shape 3**: each row plus
    /// a derived aggregate over its children.
    ///
    /// ```ignore
    /// // "Each author + their post count" — every column of `Author`
    /// // ends up in the SELECT list AND in GROUP BY.
    /// Author::objects()
    ///     .annotate("post_count", count_all().into())
    ///     .compile()?;
    /// ```
    ///
    /// # Projection cheat-sheet
    ///
    /// | Shape | Call site                                | GROUP BY        |
    /// |-------|------------------------------------------|-----------------|
    /// | 1     | `.values_dict(&[cols])`                  | (none)          |
    /// | 2     | `.values(&[cols]).annotate(alias, agg)`  | the values cols |
    /// | 3     | `.annotate(alias, agg)` (alone)          | every scalar    |
    #[must_use]
    pub fn annotate(self, alias: &'static str, expr: AggregateExpr) -> AggregateBuilder<T> {
        self.aggregate().annotate(alias, expr)
    }

    /// Project a correlated scalar subquery under `alias`, promoting to
    /// an [`AggregateBuilder`].
    /// Shorthand for [`Self::annotate`] with
    /// [`crate::core::subquery::scalar_subquery`]. `inner` must return
    /// one column and at most one row. Correlate it with
    /// [`crate::core::subquery::outer_ref`].
    #[must_use]
    pub fn annotate_subquery(
        self,
        alias: &'static str,
        inner: crate::core::SelectQuery,
    ) -> AggregateBuilder<T> {
        self.aggregate()
            .annotate(alias, crate::core::subquery::scalar_subquery(inner))
    }
}

/// Accumulates `SET column = value` assignments, then compiles to an `UpdateQuery`.
///
/// Constructed via [`QuerySet::update`]. The queryset's filters become the
/// WHERE clause; an empty queryset produces an unfiltered update affecting
/// every row.
pub struct UpdateBuilder<T: Model> {
    qs: QuerySet<T>,
    set: Vec<PendingAssignment>,
}

enum PendingAssignment {
    Raw(RawAssignment),
    /// `field = <Expr>` — staging for the `F()` SET path. Resolved at
    /// `compile()` time so the field name validates against the schema.
    RawExpr(RawExprAssignment),
    Resolved(Assignment),
}

impl<T: Model> UpdateBuilder<T> {
    /// Append a `SET field = value` assignment. Last write wins for repeated fields.
    #[must_use]
    pub fn set(mut self, field: impl Into<String>, value: impl Into<SqlValue>) -> Self {
        self.set.push(PendingAssignment::Raw(RawAssignment {
            field: field.into(),
            value: value.into(),
        }));
        self
    }

    /// Append a typed `SET column = value` from a [`Column`](crate::core::Column).
    #[must_use]
    pub fn set_typed(mut self, assignment: TypedAssignment<T>) -> Self {
        self.set
            .push(PendingAssignment::Resolved(assignment.into_assignment()));
        self
    }

    /// Append a `SET field = <expression>` — the [`Expr`]-shaped form
    /// that powers `F()` column references and arithmetic:
    ///
    /// ```ignore
    /// // Atomic counter increment, no read-modify-write race:
    /// Post::objects()
    ///     .where_(Post::id.eq(7))
    ///     .update()
    ///     .set_expr("views", F("views") + 1)
    ///     .execute_pool(&pool).await?;
    /// ```
    ///
    /// Accepts a bare [`F`](crate::core::F), a literal (anything that
    /// `Into<SqlValue>`), or a full arithmetic tree.
    #[must_use]
    pub fn set_expr(
        mut self,
        field: impl Into<String>,
        expr: impl Into<crate::core::Expr>,
    ) -> Self {
        self.set.push(PendingAssignment::RawExpr(RawExprAssignment {
            field: field.into(),
            value: expr.into(),
        }));
        self
    }

    /// Validate against `T::SCHEMA` and lower to an `UpdateQuery`.
    ///
    /// # Errors
    /// Returns [`QueryError::UnknownField`] if any `set` or filter names an
    /// unknown field, [`QueryError::TypeMismatch`] if any bound value's
    /// type doesn't match the field's declared type, and
    /// [`QueryError::BoundedDmlUnsupported`] if the queryset's limit or
    /// offset cannot be bounded by primary key.
    pub fn compile(mut self) -> Result<UpdateQuery, QueryError> {
        // As on the SELECT and DELETE paths: an `.update().set(...)`
        // must not escape the model's global scopes.
        self.qs.apply_global_scopes();
        let model: &'static ModelSchema = T::SCHEMA;

        let assignments = self
            .set
            .into_iter()
            .map(|p| match p {
                PendingAssignment::Raw(raw) => resolve_assignment(model, raw),
                PendingAssignment::RawExpr(raw) => resolve_assignment_expr(model, raw),
                PendingAssignment::Resolved(assignment) => Ok(assignment),
            })
            .collect::<Result<Vec<_>, _>>()?;

        let where_clause = resolve_pending(model, self.qs.pending)?;
        // `.none().update().set(...)` affects nothing, for the same
        // reason `.none().delete()` does.
        let where_clause = if self.qs.is_none {
            never_match_clause(model, where_clause)?
        } else {
            where_clause
        };
        let where_clause = bound_dml_where(
            model,
            where_clause,
            self.qs.order_by,
            self.qs.limit,
            self.qs.offset,
            !self.qs.compound.is_empty(),
        )?;

        Ok(UpdateQuery {
            model,
            set: assignments,
            where_clause,
        })
    }
}

/// Render the column-only view of an `order_by` list for the
/// `DistinctOnOrderByMismatch` error. `Expr` and `Random` entries
/// render as `<expr>` and `RANDOM`, so the message still shows where
/// the mismatch starts.
fn order_by_column_names(order_by: &[crate::core::OrderItem]) -> Vec<String> {
    order_by
        .iter()
        .map(|item| match item {
            crate::core::OrderItem::Column { column, .. } => (*column).to_owned(),
            crate::core::OrderItem::Expr { .. } => "<expr>".to_owned(),
            crate::core::OrderItem::Random => "RANDOM".to_owned(),
        })
        .collect()
}

/// Lower the pending order-by list to `Vec<OrderItem>` at `compile()`
/// time. `Field` entries resolve their name against the model schema.
/// `Expr` entries pass through as they are, so a typo inside an
/// expression surfaces as a database error, like `set_expr`.
fn lower_order_items(
    model: &'static ModelSchema,
    items: Vec<PendingOrderItem>,
) -> Result<(Vec<crate::core::OrderItem>, Vec<crate::core::Join>), QueryError> {
    let mut out = Vec::with_capacity(items.len());
    let mut joins: Vec<crate::core::Join> = Vec::new();
    for item in items {
        match item {
            PendingOrderItem::Field { name, desc, nulls } => match model.field(&name) {
                Some(field) => {
                    out.push(crate::core::OrderItem::column_with_nulls(
                        field.column,
                        desc,
                        nulls,
                    ));
                }
                // Relation span, such as `order_by("author__name")`:
                // resolve the FK chain into LEFT JOINs plus an aliased
                // ORDER BY term, reusing the `filter()` walk. `order_by`
                // has no lookup suffixes, so anything after the terminal
                // column makes the key invalid.
                None if name.contains("__") => {
                    let segs: Vec<&str> = name.split("__").collect();
                    let (jns, prev_alias, current, term_i) = resolve_span_chain(model, &name)?;
                    if term_i + 1 < segs.len() {
                        return Err(QueryError::UnknownField {
                            model: current.name,
                            field: name.clone(),
                        });
                    }
                    let term_field =
                        current
                            .field(segs[term_i])
                            .ok_or_else(|| QueryError::UnknownField {
                                model: current.name,
                                field: segs[term_i].to_owned(),
                            })?;
                    // Dedupe by alias, so a path already joined by
                    // `select_related` or a filter span emits once.
                    // `compile()` dedupes again against the full set.
                    for j in jns {
                        if !joins.iter().any(|e| e.alias == j.alias) {
                            joins.push(j);
                        }
                    }
                    out.push(crate::core::OrderItem::expr_with_nulls(
                        crate::core::Expr::AliasedColumn {
                            alias: prev_alias,
                            column: term_field.column,
                        },
                        desc,
                        nulls,
                    ));
                }
                None => {
                    return Err(QueryError::UnknownField {
                        model: model.name,
                        field: name,
                    })
                }
            },
            PendingOrderItem::Expr { expr, desc, nulls } => {
                out.push(crate::core::OrderItem::expr_with_nulls(expr, desc, nulls));
            }
            PendingOrderItem::Random => {
                out.push(crate::core::OrderItem::random());
            }
        }
    }
    Ok((out, joins))
}

/// Convert `select_related` field names into `Join`s.
///
/// **Single hop**, such as `"author"`: look up the field on `model`,
/// check it is a `Relation::Fk` or `Relation::O2O`, find the target
/// schema in inventory, and build a LEFT `Join` projecting all the
/// target's columns.
///
/// **Multi-hop**, such as `"author__profile__country"`: split on `__`
/// and resolve each hop against the previous hop's target schema. Each
/// hop uses the previous join's alias on the left of its `ON`
/// predicate, so the FK chain stitches together in SQL. The join alias
/// is the full dotted path, which stays unique even when two roots
/// share a tail name.
///
/// Any hop that does not resolve returns `SelectRelatedInvalid` naming
/// its position in the chain.
fn lower_select_related(
    model: &'static ModelSchema,
    names: &[String],
) -> Result<Vec<crate::core::Join>, QueryError> {
    use crate::core::{Expr, Join, JoinKind, ModelEntry, Op, Relation, WhereExpr};
    let mut out: Vec<Join> = Vec::with_capacity(names.len());
    for name in names {
        // Walk each `__`-separated hop. `current` tracks the schema
        // we look up the next hop's FK on; `prev_alias` tracks the
        // alias the next hop's ON predicate joins against on the
        // LHS. For the first hop, that LHS is the main table.
        let hops: Vec<&str> = name.split("__").collect();
        if hops.iter().any(|h| h.is_empty()) {
            return Err(QueryError::SelectRelatedInvalid {
                model: model.name,
                field: name.clone(),
                reason: format!(
                    "empty hop in chain `{name}` (use `field` or `field__nested`, not `field____nested`)"
                ),
            });
        }
        let mut current: &'static ModelSchema = model;
        let mut prev_alias: &'static str = model.table;
        let mut prev_alias_owned: String = String::new();
        for (depth, hop) in hops.iter().enumerate() {
            let field = current
                .field(hop)
                .ok_or_else(|| QueryError::SelectRelatedInvalid {
                    model: current.name,
                    field: name.clone(),
                    reason: format!(
                        "no field `{hop}` on `{}` (hop {} of chain `{name}`)",
                        current.name,
                        depth + 1
                    ),
                })?;
            let (to, on) = match field.relation {
                Some(Relation::Fk { to, on }) | Some(Relation::O2O { to, on }) => (to, on),
                _ => {
                    return Err(QueryError::SelectRelatedInvalid {
                        model: current.name,
                        field: name.clone(),
                        reason: format!(
                            "`{hop}` on `{}` is not a `ForeignKey<T>` field (hop {} of chain `{name}`)",
                            current.name,
                            depth + 1
                        ),
                    });
                }
            };
            let target = ModelEntry::for_table(to)
                .map(|e| e.schema)
                .ok_or_else(|| QueryError::SelectRelatedInvalid {
                    model: current.name,
                    field: name.clone(),
                    reason: format!(
                        "target table `{to}` is not registered (hop {} of chain `{name}` — is `{}`'s `#[derive(Model)]` linked into the binary?)",
                        depth + 1,
                        current.name
                    ),
                })?;
            // Per-hop alias: the dotted path up to this hop. A single
            // hop is just `field.name`; a chain accumulates `author`,
            // `author__profile`, `author__profile__country`.
            //
            // The writer needs `&'static str`: the first hop has the
            // schema's field name, deeper ones are interned.
            let alias: &'static str = if depth == 0 {
                prev_alias_owned.push_str(hop);
                field.name
            } else {
                prev_alias_owned = format!("{prev_alias_owned}__{hop}");
                intern_join_alias(&prev_alias_owned)?
            };
            let project: Vec<&'static str> = target.scalar_fields().map(|f| f.column).collect();
            out.push(Join {
                target,
                alias,
                kind: JoinKind::Left,
                on: WhereExpr::ExprCompare {
                    lhs: Expr::AliasedColumn {
                        alias: prev_alias,
                        column: field.column,
                    },
                    op: Op::Eq,
                    rhs: Expr::AliasedColumn { alias, column: on },
                },
                project,
            });
            // Advance the chain for the next hop.
            current = target;
            prev_alias = alias;
        }
    }
    Ok(out)
}

/// Result of [`parse_lookup`]: a plain field/op/value triple, a
/// date-transform wrapper the resolver re-renders as
/// `EXTRACT(…) <op> ?`, or a relation span for the resolver to walk.
enum ParsedLookup {
    Raw {
        field: String,
        op: Op,
        value: SqlValue,
    },
    DateTransform {
        field: String,
        transform: ScalarFn,
        op: Op,
        value: SqlValue,
    },
    /// Relation-spanning lookup such as `author__name` or
    /// `author__profile__bio__icontains`: one or more FK hops before
    /// the terminal column, with an optional lookup suffix.
    /// `parse_lookup` cannot tell an FK hop from a scalar field, so it
    /// defers the whole key here. `resolve_span` walks it against the
    /// schema and builds the JOINs and the aliased predicate, or
    /// reports the original `UnknownLookup` if no FK chain matches.
    RelationSpan { raw_key: String, value: SqlValue },
}

/// Map a date-transform suffix token to its scalar fn. `None` means
/// the token is not a date transform, so the caller falls through to
/// the comparison-suffix table.
fn date_transform_fn(token: &str) -> Option<ScalarFn> {
    match token {
        "year" => Some(ScalarFn::ExtractYear),
        "month" => Some(ScalarFn::ExtractMonth),
        "day" => Some(ScalarFn::ExtractDay),
        "hour" => Some(ScalarFn::ExtractHour),
        "minute" => Some(ScalarFn::ExtractMinute),
        "second" => Some(ScalarFn::ExtractSecond),
        "quarter" => Some(ScalarFn::ExtractQuarter),
        "week" => Some(ScalarFn::ExtractWeek),
        "week_day" => Some(ScalarFn::ExtractWeekDay),
        "date" => Some(ScalarFn::TruncDate),
        _ => None,
    }
}

/// Map a trailing comparison suffix (`gte`, `lt`, …) to an `Op` for
/// date-transform lookups. This is a small subset of the full lookup
/// grammar on purpose: LIKE, IN, IS NULL and regex make no sense on an
/// extracted integer or date.
fn date_compare_op(suffix: &str) -> Option<Op> {
    match suffix {
        "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,
    }
}

/// Parse a `"field"` or `"field__suffix"` key and its
/// value into a [`ParsedLookup`]. The suffix table lives on
/// [`QuerySet::filter`].
///
/// An unknown `__suffix` gives [`QueryError::UnknownLookup`]. A wrong
/// value shape for `__in`, `__isnull`, `__between` or `__range` gives
/// [`QueryError::InvalidLookupValue`].
fn parse_lookup(key: &str, value: SqlValue) -> Result<ParsedLookup, QueryError> {
    // Bare field (no `__`) → exact match.
    let Some(split_at) = key.find("__") else {
        return Ok(ParsedLookup::Raw {
            field: key.to_owned(),
            op: Op::Eq,
            value,
        });
    };
    let field = key[..split_at].to_owned();
    let suffix = &key[split_at + 2..];

    // Date-transform suffixes: `__year`, `__year__gte`, `__date` and
    // so on. Split the suffix into a transform token and an optional
    // trailing comparison. If the token is not a date transform, fall
    // through to the comparison-suffix table.
    let (transform_token, trailing) = match suffix.find("__") {
        Some(at) => (&suffix[..at], Some(&suffix[at + 2..])),
        None => (suffix, None),
    };
    if let Some(transform) = date_transform_fn(transform_token) {
        let op = match trailing {
            None => Op::Eq,
            Some(t) => date_compare_op(t).ok_or_else(|| QueryError::UnknownLookup {
                field: field.clone(),
                suffix: suffix.to_owned(),
            })?,
        };
        return Ok(ParsedLookup::DateTransform {
            field,
            transform,
            op,
            value,
        });
    }

    let pair = |field: String, op: Op, value: SqlValue| ParsedLookup::Raw { field, op, value };
    match suffix {
        "exact" => Ok(pair(field, Op::Eq, value)),
        "ne" => Ok(pair(field, Op::Ne, value)),
        "gt" => Ok(pair(field, Op::Gt, value)),
        "gte" => Ok(pair(field, Op::Gte, value)),
        "lt" => Ok(pair(field, Op::Lt, value)),
        "lte" => Ok(pair(field, Op::Lte, value)),
        "iexact" => {
            // Case-insensitive equality, not a pattern. Escape the
            // value so `%` and `_` match themselves; otherwise
            // `email__iexact` with a `%` would match every row.
            let v = wrap_like(&value, "", "", &field, suffix)?;
            Ok(pair(field, Op::ILikeEscaped, v))
        }
        "contains" => {
            let v = wrap_like(&value, "%", "%", &field, suffix)?;
            Ok(pair(field, Op::LikeEscaped, v))
        }
        "icontains" => {
            let v = wrap_like(&value, "%", "%", &field, suffix)?;
            Ok(pair(field, Op::ILikeEscaped, v))
        }
        "startswith" => {
            let v = wrap_like(&value, "", "%", &field, suffix)?;
            Ok(pair(field, Op::LikeEscaped, v))
        }
        "istartswith" => {
            let v = wrap_like(&value, "", "%", &field, suffix)?;
            Ok(pair(field, Op::ILikeEscaped, v))
        }
        "endswith" => {
            let v = wrap_like(&value, "%", "", &field, suffix)?;
            Ok(pair(field, Op::LikeEscaped, v))
        }
        "iendswith" => {
            let v = wrap_like(&value, "%", "", &field, suffix)?;
            Ok(pair(field, Op::ILikeEscaped, v))
        }
        // Raw LIKE / ILIKE / NOT LIKE / NOT ILIKE. Unlike
        // `__contains` and friends, the value is bound as given, so
        // the caller places `%` and `_`. Use it for patterns the
        // auto-wrapping suffixes cannot express, like `'%foo%bar%'`.
        "like" | "ilike" | "not_like" | "not_ilike" => {
            if !matches!(value, SqlValue::String(_)) {
                return Err(QueryError::InvalidLookupValue {
                    field,
                    suffix: suffix.to_owned(),
                    expected: "SqlValue::String(<LIKE pattern>)",
                    actual: sql_value_shape_name(&value),
                });
            }
            let op = match suffix {
                "like" => Op::Like,
                "ilike" => Op::ILike,
                "not_like" => Op::NotLike,
                "not_ilike" => Op::NotILike,
                _ => unreachable!(),
            };
            Ok(pair(field, op, value))
        }
        "in" | "not_in" => {
            if !matches!(value, SqlValue::List(_)) {
                return Err(QueryError::InvalidLookupValue {
                    field,
                    suffix: suffix.to_owned(),
                    expected: "SqlValue::List(...)",
                    actual: sql_value_shape_name(&value),
                });
            }
            let op = if suffix == "not_in" {
                Op::NotIn
            } else {
                Op::In
            };
            Ok(pair(field, op, value))
        }
        "isnull" => {
            if !matches!(value, SqlValue::Bool(_)) {
                return Err(QueryError::InvalidLookupValue {
                    field,
                    suffix: suffix.to_owned(),
                    expected: "SqlValue::Bool(true|false)",
                    actual: sql_value_shape_name(&value),
                });
            }
            Ok(pair(field, Op::IsNull, value))
        }
        "between" | "range" | "not_between" | "not_range" => {
            match &value {
                SqlValue::List(items) if items.len() == 2 => {}
                SqlValue::List(_) => {
                    return Err(QueryError::InvalidLookupValue {
                        field,
                        suffix: suffix.to_owned(),
                        expected: "SqlValue::List with exactly 2 elements [lo, hi]",
                        actual: "SqlValue::List with wrong arity",
                    });
                }
                other => {
                    return Err(QueryError::InvalidLookupValue {
                        field,
                        suffix: suffix.to_owned(),
                        expected: "SqlValue::List([lo, hi])",
                        actual: sql_value_shape_name(other),
                    });
                }
            }
            // `__not_between` / `__not_range` flip it to `NOT BETWEEN`.
            let op = if matches!(suffix, "not_between" | "not_range") {
                Op::NotBetween
            } else {
                Op::Between
            };
            Ok(pair(field, op, value))
        }
        "regex" | "iregex" => {
            if !matches!(value, SqlValue::String(_)) {
                return Err(QueryError::InvalidLookupValue {
                    field,
                    suffix: suffix.to_owned(),
                    expected: "SqlValue::String(<regex pattern>)",
                    actual: sql_value_shape_name(&value),
                });
            }
            let op = if suffix == "regex" {
                Op::Regex
            } else {
                Op::IRegex
            };
            Ok(pair(field, op, value))
        }
        "trigram_similar" | "trigram_word_similar" => {
            if !matches!(value, SqlValue::String(_)) {
                return Err(QueryError::InvalidLookupValue {
                    field,
                    suffix: suffix.to_owned(),
                    expected: "SqlValue::String(<trigram pattern>)",
                    actual: sql_value_shape_name(&value),
                });
            }
            let op = if suffix == "trigram_similar" {
                Op::TrigramSimilar
            } else {
                Op::TrigramWordSimilar
            };
            Ok(pair(field, op, value))
        }
        "search" => {
            if !matches!(value, SqlValue::String(_)) {
                return Err(QueryError::InvalidLookupValue {
                    field,
                    suffix: suffix.to_owned(),
                    expected: "SqlValue::String(<search query>)",
                    actual: sql_value_shape_name(&value),
                });
            }
            Ok(pair(field, Op::Search, value))
        }
        // The array operators get explicit `__array_*` suffixes: the
        // parser has no field type to dispatch on, so a bare
        // `__contains` would collide with the text one. Prefer
        // the typed `Column::array_*` methods where you can.
        "range_contains"
        | "range_contained_by"
        | "range_overlap"
        | "range_strictly_left"
        | "range_strictly_right"
        | "range_adjacent" => {
            // PG range operators. The value is a range literal string
            // such as `"[1, 10)"`, which PG casts to the column's
            // range type. A plain `SqlValue::String` is wrapped into a
            // `RangeLiteral`; a `RangeLiteral` from the typed helpers
            // is taken as is. Both emit the same SQL.
            let literal = match value {
                SqlValue::String(s) => s,
                SqlValue::RangeLiteral(s) => s,
                other => {
                    return Err(QueryError::InvalidLookupValue {
                        field,
                        suffix: suffix.to_owned(),
                        expected: "SqlValue::String(<PG range literal>) — e.g. \"[1, 10)\"",
                        actual: sql_value_shape_name(&other),
                    });
                }
            };
            let op = match suffix {
                "range_contains" => Op::RangeContains,
                "range_contained_by" => Op::RangeContainedBy,
                "range_overlap" => Op::RangeOverlap,
                "range_strictly_left" => Op::RangeStrictlyLeft,
                "range_strictly_right" => Op::RangeStrictlyRight,
                "range_adjacent" => Op::RangeAdjacent,
                _ => unreachable!(),
            };
            Ok(pair(field, op, SqlValue::RangeLiteral(literal)))
        }
        "array_contains" | "array_contained_by" | "array_overlap" => {
            // The value must be a list of elements. Promote
            // `SqlValue::List` to `SqlValue::Array` so the writer
            // binds it as one PG array parameter.
            let SqlValue::List(elems) = value else {
                return Err(QueryError::InvalidLookupValue {
                    field,
                    suffix: suffix.to_owned(),
                    expected: "SqlValue::List(<elements>) — typed homogeneous array",
                    actual: sql_value_shape_name(&value),
                });
            };
            let op = match suffix {
                "array_contains" => Op::ArrayContains,
                "array_contained_by" => Op::ArrayContainedBy,
                "array_overlap" => Op::ArrayOverlap,
                _ => unreachable!(),
            };
            Ok(pair(field, op, SqlValue::Array(elems)))
        }
        // Unknown suffix — but the key may be a relation span such as
        // `author__name__icontains`. There is no schema here to tell,
        // so defer the whole key to the resolver. It walks the FK
        // chain, and if the first segment is not an FK (a real typo
        // like `pages__bogus`) it raises `UnknownLookup`.
        _ => Ok(ParsedLookup::RelationSpan {
            raw_key: key.to_owned(),
            value,
        }),
    }
}

/// Wrap a `SqlValue::String` with leading and trailing wildcards for
/// `__contains` / `__startswith` / `__endswith` and their `i*` forms.
///
/// A non-string value is rejected with
/// [`QueryError::InvalidLookupValue`]: LIKE needs text.
fn wrap_like(
    value: &SqlValue,
    prefix: &str,
    suffix_char: &str,
    field: &str,
    suffix: &str,
) -> Result<SqlValue, QueryError> {
    let s = match value {
        SqlValue::String(s) => s,
        other => {
            return Err(QueryError::InvalidLookupValue {
                field: field.to_owned(),
                suffix: suffix.to_owned(),
                expected: "SqlValue::String(...)",
                actual: sql_value_shape_name(other),
            });
        }
    };
    // Escape LIKE metacharacters in the user value so `%` and `_`
    // match literally. The wrapping wildcards go on after escaping, so
    // they keep their pattern meaning. The result is only correct
    // under `ESCAPE '!'`, so every caller pairs it with
    // `Op::LikeEscaped` or `Op::ILikeEscaped`.
    let escaped = crate::core::escape_like(s);
    Ok(SqlValue::String(format!("{prefix}{escaped}{suffix_char}")))
}

/// Readable shape name for an `SqlValue`, used in
/// [`QueryError::InvalidLookupValue`] messages.
fn sql_value_shape_name(v: &SqlValue) -> &'static str {
    match v {
        SqlValue::Null => "SqlValue::Null",
        SqlValue::I16(_) => "SqlValue::I16",
        SqlValue::I32(_) => "SqlValue::I32",
        SqlValue::I64(_) => "SqlValue::I64",
        SqlValue::F32(_) => "SqlValue::F32",
        SqlValue::F64(_) => "SqlValue::F64",
        SqlValue::Bool(_) => "SqlValue::Bool",
        SqlValue::String(_) => "SqlValue::String",
        SqlValue::List(_) => "SqlValue::List",
        _ => "SqlValue::<other>",
    }
}

/// Add an always-false predicate to `base` so the surrounding UPDATE
/// or DELETE matches no row.
///
/// It uses `<primary_key> IS NULL`. Every model declares a NOT NULL
/// primary key, so that can never be true, on any backend. A `1 = 0`
/// literal would need a raw-SQL escape hatch the IR does not expose,
/// while `IS NULL` reuses the existing `Op::IsNull` path.
fn never_match_clause(
    model: &'static ModelSchema,
    base: WhereExpr,
) -> Result<WhereExpr, QueryError> {
    let pk = model
        .primary_key()
        .ok_or_else(|| QueryError::UnknownField {
            model: model.name,
            field: "<primary_key>".to_owned(),
        })?;
    let never = WhereExpr::Predicate(crate::core::Filter {
        column: pk.column,
        op: Op::IsNull,
        value: SqlValue::Bool(true),
    });
    Ok(match base {
        // An empty `And` collapses to the never-match predicate alone,
        // which keeps the emitted WHERE to a single column reference.
        WhereExpr::And(nodes) if nodes.is_empty() => never,
        WhereExpr::And(mut nodes) => {
            nodes.push(never);
            WhereExpr::And(nodes)
        }
        other => WhereExpr::And(vec![other, never]),
    })
}

/// Bound an UPDATE/DELETE: `<where> AND pk IN (SELECT pk … ORDER BY …, pk LIMIT … OFFSET …)`.
/// The outer `<where>` stays so a row changed by a concurrent writer is not claimed.
/// Without a limit or offset the order cannot change the row set, so it is left out.
fn bound_dml_where(
    model: &'static ModelSchema,
    where_clause: WhereExpr,
    order_by: Vec<PendingOrderItem>,
    limit: Option<i64>,
    offset: Option<i64>,
    has_compound: bool,
) -> Result<WhereExpr, QueryError> {
    use crate::core::BoundedDmlReason as Why;
    if limit.is_none() && offset.is_none() {
        return Ok(where_clause);
    }
    let refuse = |reason| {
        Err(QueryError::BoundedDmlUnsupported {
            model: model.name,
            reason,
        })
    };
    // SQLite reads `LIMIT -1` as no limit at all.
    if limit.is_some_and(|n| n < 0) || offset.is_some_and(|n| n < 0) {
        return refuse(Why::Negative);
    }
    if has_compound {
        return refuse(Why::SetOperation);
    }
    let mut pks = model.fields.iter().filter(|f| f.primary_key);
    let pk = match (pks.next(), pks.next()) {
        (Some(pk), None) => pk,
        _ => return refuse(Why::NoSinglePrimaryKey),
    };
    let (mut order_by, joins) = lower_order_items(model, order_by)?;
    if !joins.is_empty() {
        return refuse(Why::RelationOrderBy);
    }
    // PK tiebreaker: ties must not pick a different row set each run.
    let has_pk = order_by.iter().any(
        |o| matches!(o, crate::core::OrderItem::Column { column, .. } if *column == pk.column),
    );
    if !has_pk {
        order_by.push(crate::core::OrderItem::column(pk.column, false));
    }
    let mut inner = SelectQuery::new(model);
    inner.where_clause = where_clause.clone();
    inner.order_by = order_by;
    inner.limit = limit;
    inner.offset = offset;
    inner.projection = Some(vec![pk.column]);
    let bound = WhereExpr::InSubquery {
        column: pk.column,
        negated: false,
        subquery: Box::new(inner),
    };
    Ok(if where_clause.is_empty() {
        bound
    } else {
        WhereExpr::And(vec![where_clause, bound])
    })
}

/// Parse a `key`/`value` pair through the lookup grammar into one
/// [`PendingFilter`]. Shared by [`QuerySet::filter`] and
/// [`QuerySet::exclude`], so the `__lookup` grammar cannot drift
/// between them.
fn parse_to_pending(key: &str, value: SqlValue) -> PendingFilter {
    match parse_lookup(key, value) {
        Ok(ParsedLookup::Raw { field, op, value }) => {
            PendingFilter::Raw(RawFilter { field, op, value })
        }
        Ok(ParsedLookup::DateTransform {
            field,
            transform,
            op,
            value,
        }) => PendingFilter::DateTransform(DateTransformFilter {
            field,
            transform,
            op,
            value,
        }),
        Ok(ParsedLookup::RelationSpan { raw_key, value }) => {
            PendingFilter::RelationSpan { raw_key, value }
        }
        Err(e) => PendingFilter::Error(e),
    }
}

fn resolve_pending(
    model: &'static ModelSchema,
    pending: Vec<PendingFilter>,
) -> Result<WhereExpr, QueryError> {
    let mut nodes: Vec<WhereExpr> = Vec::with_capacity(pending.len());
    for entry in pending {
        nodes.push(resolve_one_pending(model, entry)?);
    }
    Ok(WhereExpr::And(nodes))
}

/// Lower a single [`PendingFilter`] to a [`WhereExpr`]. Split out of
/// [`resolve_pending`]'s loop so [`PendingFilter::Negated`] can
/// resolve its inner entry recursively.
fn resolve_one_pending(
    model: &'static ModelSchema,
    entry: PendingFilter,
) -> Result<WhereExpr, QueryError> {
    Ok(match entry {
        PendingFilter::Raw(raw) => WhereExpr::Predicate(resolve_filter(model, raw)?),
        PendingFilter::DateTransform(dt) => resolve_date_transform(model, dt)?,
        PendingFilter::Resolved(filter) => WhereExpr::Predicate(filter),
        PendingFilter::Expr(expr) => expr,
        PendingFilter::Negated(inner) => {
            WhereExpr::Not(Box::new(resolve_one_pending(model, *inner)?))
        }
        // `lower_relation_spans` turns spans into `Expr` plus JOINs on
        // the SELECT path. One arriving here means update / delete /
        // aggregate, which cannot carry a JOIN. Resolve it first to
        // tell a real span (resolves, so report "unsupported here")
        // from a bad suffix like `status__bogus` (whose first segment
        // is not an FK, so keep the original `UnknownLookup`).
        PendingFilter::RelationSpan { raw_key, value } => {
            return match resolve_span(model, &raw_key, value) {
                Ok(_) => Err(QueryError::RelationSpanUnsupportedHere { key: raw_key }),
                Err(e) => Err(e),
            }
        }
        // Surface the deferred lookup-parse error at `compile()`.
        PendingFilter::Error(e) => return Err(e),
    })
}

fn resolve_filter(model: &'static ModelSchema, raw: RawFilter) -> Result<Filter, QueryError> {
    let field = model
        .field(&raw.field)
        .ok_or_else(|| QueryError::UnknownField {
            model: model.name,
            field: raw.field.clone(),
        })?;

    // `IsNull` carries a Bool flag, not a value to compare with the
    // field, so skip the type check. `In` carries a List, whose
    // elements are not checked one by one.
    let skip_type_check = matches!(raw.op, Op::IsNull | Op::In);

    if !skip_type_check {
        if let Some(value_ty) = raw.value.field_type() {
            if value_ty != field.ty {
                return Err(QueryError::TypeMismatch {
                    model: model.name,
                    field: raw.field,
                    expected: field.ty,
                    actual: value_ty,
                });
            }
        }
    }

    Ok(Filter {
        column: field.column,
        op: raw.op,
        value: raw.value,
    })
}

/// Resolve a relation-spanning lookup key into its FK-chain LEFT JOINs
/// plus an aliased `ExprCompare` predicate.
///
/// A key such as `author__profile__bio__icontains` splits into three
/// parts. Leading segments naming an FK or O2O field are JOIN hops.
/// The first non-FK segment, or the last one, is the terminal column.
/// Anything after that is a lookup suffix, re-parsed through
/// [`parse_lookup`] and applied to the aliased column.
///
/// If the first segment is not an FK, the key is not a span at all,
/// for example `pages__bogus`. The original
/// [`QueryError::UnknownLookup`] is returned so the error stays the
/// same as before.
fn resolve_span(
    model: &'static ModelSchema,
    raw_key: &str,
    value: SqlValue,
) -> Result<(Vec<crate::core::Join>, WhereExpr), QueryError> {
    use crate::core::Expr;
    let segs: Vec<&str> = raw_key.split("__").collect();
    // The FK-chain walk is shared with the `order_by` path.
    let (joins, prev_alias, current, term_i) = resolve_span_chain(model, raw_key)?;

    let term_field = current
        .field(segs[term_i])
        .ok_or_else(|| QueryError::UnknownField {
            model: current.name,
            field: segs[term_i].to_owned(),
        })?;
    let suffix_segs = &segs[term_i + 1..];

    // Re-parse any trailing suffix through the normal grammar; bare
    // span (no suffix) is an exact match.
    let (op, value, transform) = if suffix_segs.is_empty() {
        (Op::Eq, value, None)
    } else {
        let synth = format!("{}__{}", term_field.name, suffix_segs.join("__"));
        match parse_lookup(&synth, value) {
            Ok(ParsedLookup::Raw { op, value, .. }) => (op, value, None),
            Ok(ParsedLookup::DateTransform {
                transform,
                op,
                value,
                ..
            }) => (op, value, Some(transform)),
            // A trailing suffix still unknown here is a real typo on
            // the terminal field.
            Ok(ParsedLookup::RelationSpan { .. }) => {
                return Err(QueryError::UnknownLookup {
                    field: term_field.name.to_owned(),
                    suffix: suffix_segs.join("__"),
                })
            }
            Err(e) => return Err(e),
        }
    };
    let column = Expr::AliasedColumn {
        alias: prev_alias,
        column: term_field.column,
    };
    let lhs = match transform {
        None => column,
        Some(kind) => Expr::Function {
            kind,
            args: vec![column],
        },
    };
    let predicate = WhereExpr::ExprCompare {
        lhs,
        op,
        rhs: Expr::Literal(value),
    };
    Ok((joins, predicate))
}

/// Deepest relation path a span or `select_related` may walk. It bounds the
/// interned aliases by the schema's FK paths, so user-built lookups
/// (`parent__parent__…`) cannot grow the set without limit.
const MAX_RELATION_HOPS: usize = 6;

/// A `&'static` join alias for a multi-hop path (`author__profile`),
/// leaked once per distinct path rather than once per `compile()`.
fn intern_join_alias(path: &str) -> Result<&'static str, QueryError> {
    use std::collections::HashSet;
    use std::sync::{OnceLock, PoisonError, RwLock};
    static ALIASES: OnceLock<RwLock<HashSet<&'static str>>> = OnceLock::new();
    if path.split("__").count() > MAX_RELATION_HOPS {
        return Err(QueryError::RelationPathTooDeep {
            path: path.to_owned(),
            max: MAX_RELATION_HOPS,
        });
    }
    let set = ALIASES.get_or_init(RwLock::default);
    // Read first: after warm-up every lookup is a hit and runs in parallel.
    if let Some(alias) = set.read().unwrap_or_else(PoisonError::into_inner).get(path) {
        return Ok(alias);
    }
    let mut set = set.write().unwrap_or_else(PoisonError::into_inner);
    if let Some(alias) = set.get(path) {
        return Ok(alias);
    }
    let alias: &'static str = Box::leak(path.into());
    set.insert(alias);
    Ok(alias)
}

/// Walk a relation-span path's FK / O2O hops into LEFT JOINs. Shared
/// by [`resolve_span`] (the `filter()` path) and [`lower_order_items`]
/// (the `order_by()` path), so the two cannot drift.
///
/// Returns the JOINs, the alias of the table holding the terminal
/// column, that table's schema, and the index of the terminal segment
/// in the `__`-split key. The terminal column is
/// `current.field(segs[term_i])`; callers turn it into a predicate or
/// an `OrderItem`.
///
/// Returns the original [`QueryError::UnknownLookup`] when the first
/// segment is not an FK, so non-span keys keep their existing error.
fn resolve_span_chain(
    model: &'static ModelSchema,
    raw_key: &str,
) -> Result<
    (
        Vec<crate::core::Join>,
        &'static str,
        &'static ModelSchema,
        usize,
    ),
    QueryError,
> {
    use crate::core::{Expr, Join, JoinKind, ModelEntry, Relation};
    let segs: Vec<&str> = raw_key.split("__").collect();
    let mut joins: Vec<Join> = Vec::new();
    let mut current: &'static ModelSchema = model;
    let mut prev_alias: &'static str = model.table;
    let mut alias_path = String::new();
    let mut term_i = segs.len() - 1;
    for (i, seg) in segs.iter().enumerate() {
        let is_last = i + 1 == segs.len();
        let field = current.field(seg);
        let fk = field.and_then(|f| match f.relation {
            Some(Relation::Fk { to, on }) | Some(Relation::O2O { to, on }) => Some((f, to, on)),
            _ => None,
        });
        match fk {
            // An FK that isn't the final segment is a JOIN hop.
            Some((field, to, on)) if !is_last => {
                let target = ModelEntry::for_table(to).map(|e| e.schema).ok_or_else(|| {
                    QueryError::UnknownField {
                        model: current.name,
                        field: format!("{seg} (target table `{to}` not registered)"),
                    }
                })?;
                // The first hop's alias is the schema's field name; deeper
                // ones are interned. Same scheme as `lower_select_related`,
                // so a span and a `select_related` over one path dedupe.
                let alias: &'static str = if alias_path.is_empty() {
                    alias_path.push_str(seg);
                    field.name
                } else {
                    alias_path = format!("{alias_path}__{seg}");
                    intern_join_alias(&alias_path)?
                };
                let project: Vec<&'static str> = target.scalar_fields().map(|f| f.column).collect();
                joins.push(Join {
                    target,
                    alias,
                    kind: JoinKind::Left,
                    on: WhereExpr::ExprCompare {
                        lhs: Expr::AliasedColumn {
                            alias: prev_alias,
                            column: field.column,
                        },
                        op: Op::Eq,
                        rhs: Expr::AliasedColumn { alias, column: on },
                    },
                    project,
                });
                current = target;
                prev_alias = alias;
            }
            _ => {
                term_i = i;
                break;
            }
        }
    }

    // No hop consumed means the first segment is not an FK, so this is
    // an unknown suffix on a scalar field. Return the original error:
    // `pages__bogus` gives `UnknownLookup { pages, bogus }`.
    if joins.is_empty() {
        let suffix = raw_key.splitn(2, "__").nth(1).unwrap_or("").to_owned();
        return Err(QueryError::UnknownLookup {
            field: segs.first().map_or_else(String::new, |s| (*s).to_owned()),
            suffix,
        });
    }

    Ok((joins, prev_alias, current, term_i))
}

/// Pre-pass over the pending filters. Lowers every
/// [`PendingFilter::RelationSpan`], including ones nested in a
/// [`PendingFilter::Negated`] from `exclude`, into a resolved `Expr`
/// predicate and collects the FK-chain JOINs. Returns the rewritten
/// pending list and the JOINs for the SELECT path to merge by alias.
fn lower_relation_spans(
    model: &'static ModelSchema,
    pending: Vec<PendingFilter>,
) -> Result<(Vec<PendingFilter>, Vec<crate::core::Join>), QueryError> {
    let mut joins: Vec<crate::core::Join> = Vec::new();
    let mut out = Vec::with_capacity(pending.len());
    for pf in pending {
        out.push(convert_relation_span(model, pf, &mut joins)?);
    }
    Ok((out, joins))
}

fn convert_relation_span(
    model: &'static ModelSchema,
    pf: PendingFilter,
    joins: &mut Vec<crate::core::Join>,
) -> Result<PendingFilter, QueryError> {
    Ok(match pf {
        PendingFilter::RelationSpan { raw_key, value } => {
            let (jns, predicate) = resolve_span(model, &raw_key, value)?;
            for j in jns {
                if !joins.iter().any(|e| e.alias == j.alias) {
                    joins.push(j);
                }
            }
            PendingFilter::Expr(predicate)
        }
        PendingFilter::Negated(inner) => {
            PendingFilter::Negated(Box::new(convert_relation_span(model, *inner, joins)?))
        }
        other => other,
    })
}

/// Resolve a [`DateTransformFilter`] into a `WhereExpr::ExprCompare`.
/// The field is looked up in the schema and wrapped in its
/// [`ScalarFn`], such as `EXTRACT(YEAR FROM …)`, on the left. The
/// bound value becomes a literal on the right.
///
/// This skips the type check [`resolve_filter`] does: the extracted
/// value is an integer or date, not the column's own type.
fn resolve_date_transform(
    model: &'static ModelSchema,
    dt: DateTransformFilter,
) -> Result<WhereExpr, QueryError> {
    let field = model
        .field(&dt.field)
        .ok_or_else(|| QueryError::UnknownField {
            model: model.name,
            field: dt.field.clone(),
        })?;
    Ok(WhereExpr::ExprCompare {
        lhs: Expr::Function {
            kind: dt.transform,
            args: vec![Expr::Column(field.column)],
        },
        op: dt.op,
        rhs: Expr::Literal(dt.value),
    })
}

fn resolve_assignment(
    model: &'static ModelSchema,
    raw: RawAssignment,
) -> Result<Assignment, QueryError> {
    let field = model
        .field(&raw.field)
        .ok_or_else(|| QueryError::UnknownField {
            model: model.name,
            field: raw.field.clone(),
        })?;

    if let Some(value_ty) = raw.value.field_type() {
        if value_ty != field.ty {
            return Err(QueryError::TypeMismatch {
                model: model.name,
                field: raw.field,
                expected: field.ty,
                actual: value_ty,
            });
        }
    }

    Ok(Assignment {
        column: field.column,
        value: raw.value.into(),
    })
}

/// Resolve a [`RawExprAssignment`] (the `F()` SET path) against the
/// schema. The field name and every column reference in the
/// expression tree are checked. The literal type check that
/// [`resolve_assignment`] does for [`SqlValue`] is skipped: the right
/// side may be a column reference or arithmetic, whose type is only
/// known per row.
fn resolve_assignment_expr(
    model: &'static ModelSchema,
    raw: RawExprAssignment,
) -> Result<Assignment, QueryError> {
    let field = model
        .field(&raw.field)
        .ok_or_else(|| QueryError::UnknownField {
            model: model.name,
            field: raw.field.clone(),
        })?;
    validate_expr_columns_in_model(model, &raw.value)?;
    Ok(Assignment {
        column: field.column,
        value: raw.value,
    })
}

/// Walk an [`crate::core::Expr`] and check every `Column` reference
/// resolves on `model`. Same check `core::query::WhereExpr::validate`
/// does for `ColumnCompare`, repeated here so the `UpdateBuilder` path
/// catches a typo at `compile()` time instead of at the database.
fn validate_expr_columns_in_model(
    model: &'static ModelSchema,
    expr: &crate::core::Expr,
) -> Result<(), QueryError> {
    use crate::core::Expr;
    match expr {
        Expr::Literal(_) => Ok(()),
        Expr::Column(name) => {
            if model.field_by_column(name).is_none() {
                Err(QueryError::UnknownField {
                    model: model.name,
                    field: (*name).to_owned(),
                })
            } else {
                Ok(())
            }
        }
        Expr::BinOp { left, right, .. } => {
            validate_expr_columns_in_model(model, left)?;
            validate_expr_columns_in_model(model, right)
        }
        Expr::Function { args, .. } => {
            for a in args {
                validate_expr_columns_in_model(model, a)?;
            }
            Ok(())
        }
        Expr::Cast { expr: inner, .. } => validate_expr_columns_in_model(model, inner),
        Expr::Case { branches, default } => {
            for b in branches {
                b.condition.validate(model)?;
                validate_expr_columns_in_model(model, &b.then)?;
            }
            if let Some(d) = default {
                validate_expr_columns_in_model(model, d)?;
            }
            Ok(())
        }
        // None of these resolve against this model. A subquery was
        // already checked by its own `compile()`. An `OuterRef` was
        // checked by the outer queryset. An `AliasedColumn` belongs to
        // a joined alias and is checked by the JOIN writer.
        // `AggregateSubquery` and `RelAggregate` resolve against the
        // child model or relation table.
        Expr::Subquery(_)
        | Expr::AggregateSubquery(_)
        | Expr::OuterRef(_)
        | Expr::RelAggregate { .. }
        | Expr::AliasedColumn { .. } => Ok(()),
        // A window's partition_by, order_by and arg columns do belong
        // to this model, so walk them.
        Expr::Window(w) => {
            for col in &w.partition_by {
                if model.field_by_column(col).is_none() {
                    return Err(QueryError::UnknownField {
                        model: model.name,
                        field: (*col).to_owned(),
                    });
                }
            }
            for o in &w.order_by {
                if model.field_by_column(o.column).is_none() {
                    return Err(QueryError::UnknownField {
                        model: model.name,
                        field: o.column.to_owned(),
                    });
                }
            }
            for arg in &w.args {
                validate_expr_columns_in_model(model, arg)?;
            }
            Ok(())
        }
        // The flat aggregate variants hold raw column names this
        // walker does not visit — a known gap. Window-shaped
        // aggregates go through `validate_aggregate_expr_columns`.
        Expr::Aggregate(_) => Ok(()),
        // Only a JSON path's `source` is a column expression; the
        // steps are keys and indices, not model columns.
        Expr::JsonPath { source, .. } => validate_expr_columns_in_model(model, source),
    }
}

// ------------------------------------------------------------------ AggregateBuilder

/// Fluent builder for [`AggregateQuery`]. Constructed via [`QuerySet::aggregate`].
pub struct AggregateBuilder<T: Model> {
    qs: QuerySet<T>,
    group_by: Vec<&'static str>,
    aggregates: Vec<(std::borrow::Cow<'static, str>, AggregateExpr)>,
    /// Aliases: annotations you can use in
    /// `.filter(name, …)` and `.order_by([(name, …)])`, but that never
    /// appear in the SELECT list. `compile()` lifts the expression
    /// into the predicate or ORDER item.
    aliases: Vec<(std::borrow::Cow<'static, str>, AggregateExpr)>,
    having: Option<WhereExpr>,
    order_by: Vec<(&'static str, bool)>,
    limit: Option<i64>,
    offset: Option<i64>,
    /// First builder-time validation error, surfaced from `compile()`.
    /// An example is `.filter(alias, Op::JsonContains, …)` on an
    /// annotation alias: the JSON ops need dialect-specific writers
    /// that do not work against an aggregate on the left. Only the
    /// first error is kept, so later calls cannot mask the cause.
    deferred_error: Option<crate::core::QueryError>,
    /// Projection columns from [`Self::values`] or [`QuerySet::values`].
    /// With `Some(cols)` and no explicit `.group_by(...)`, `compile()`
    /// derives `GROUP BY cols`. With `None` and an aggregating
    /// annotation, it groups by every non-aggregate scalar column
    /// (shape 3).
    values: Option<Vec<&'static str>>,
}

impl<T: Model> AggregateBuilder<T> {
    /// Add a `GROUP BY` column. Call multiple times to group by multiple columns.
    ///
    /// An explicit `.group_by(...)` always wins. Paired with
    /// [`Self::values`], the explicit list reaches the writer while
    /// the values list still drives the SELECT projection.
    #[must_use]
    pub fn group_by(mut self, column: &'static str) -> Self {
        self.group_by.push(column);
        self
    }

    /// Set the projection column list. Same as [`QuerySet::values`],
    /// but usable mid-chain when you started from `.aggregate()`.
    #[must_use]
    pub fn values(mut self, columns: &[&'static str]) -> Self {
        self.values = Some(columns.to_vec());
        self
    }

    /// Add an aggregate expression under `alias` (e.g. `"post_count"`).
    #[must_use]
    pub fn annotate(mut self, alias: &'static str, expr: AggregateExpr) -> Self {
        self.aggregates
            .push((std::borrow::Cow::Borrowed(alias), expr));
        self
    }

    /// Project a correlated scalar subquery under `alias`.
    /// Shorthand for [`Self::annotate`]
    /// with [`crate::core::subquery::scalar_subquery`]. `inner` must
    /// return one column and at most one row.
    #[must_use]
    pub fn annotate_subquery(self, alias: &'static str, inner: crate::core::SelectQuery) -> Self {
        self.annotate(alias, crate::core::subquery::scalar_subquery(inner))
    }

    /// Resolve a relation `name` (reverse-FK, M2M or generic-FK) into
    /// a correlated `RelatedAggregate` and stage it on this builder.
    /// Shared with [`QuerySet::annotate_count`] and friends, so a
    /// query can chain several relation aggregates. Errors go to
    /// `self.deferred_error` and surface from `compile()`.
    fn push_relation_aggregate(
        &mut self,
        name: &str,
        column: Option<&'static str>,
        agg: AggregateExpr,
        suffix: &str,
    ) {
        use crate::core::{subquery, RelAggKind};
        // `<name>_count` (no column) or `<name>_<suffix>_<column>`.
        let alias = || match column {
            Some(col) => std::borrow::Cow::Owned(format!("{name}_{suffix}_{col}")),
            None => std::borrow::Cow::Owned(format!("{name}_{suffix}")),
        };
        let rel_kind = |a: &AggregateExpr| match a {
            AggregateExpr::Sum(_) => RelAggKind::Sum,
            AggregateExpr::Avg(_) => RelAggKind::Avg,
            AggregateExpr::Max(_) => RelAggKind::Max,
            AggregateExpr::Min(_) => RelAggKind::Min,
            _ => RelAggKind::Count,
        };

        // Reverse-FK relation — aggregate over the child table directly.
        if let Some(rel) = T::reverse_relations().iter().find(|r| r.name == name) {
            if let Some(col) = column {
                if rel.child_schema.field_by_column(col).is_none() {
                    self.deferred_error.get_or_insert(QueryError::UnknownField {
                        model: rel.child_schema.name,
                        field: col.to_owned(),
                    });
                    return;
                }
            }
            let expr = AggregateExpr::RelatedAggregate(Box::new(subquery::reverse_has_aggregate(
                rel, agg,
            )));
            self.aggregates.push((alias(), expr));
            return;
        }

        // Many-to-many: `Count` over the junction table, and the other
        // aggregates over a target column reached through it. The
        // target table has no `ModelSchema` here, so a bad `column`
        // only surfaces at the database.
        if let Some(m2m) = T::SCHEMA.m2m.iter().find(|m| m.name == name) {
            let pk = T::SCHEMA.primary_key().map_or("id", |f| f.column);
            let expr = AggregateExpr::RelatedAggregate(Box::new(subquery::m2m_has_aggregate(
                m2m,
                pk,
                rel_kind(&agg),
                column,
            )));
            self.aggregates.push((alias(), expr));
            return;
        }

        // Generic-FK — aggregate over the polymorphic child table,
        // discriminated by content type.
        if let Some(g) = T::generic_reverse_relations()
            .iter()
            .find(|g| g.name == name)
        {
            if let Some(col) = column {
                if g.child_schema.field_by_column(col).is_none() {
                    self.deferred_error.get_or_insert(QueryError::UnknownField {
                        model: g.child_schema.name,
                        field: col.to_owned(),
                    });
                    return;
                }
            }
            let expr = AggregateExpr::RelatedAggregate(Box::new(subquery::generic_has_aggregate(
                g,
                T::SCHEMA.table,
                rel_kind(&agg),
                column,
            )));
            self.aggregates.push((alias(), expr));
            return;
        }

        self.deferred_error.get_or_insert(QueryError::UnknownField {
            model: T::SCHEMA.name,
            field: name.to_owned(),
        });
    }

    /// The `<name>_exists` companion of
    /// [`Self::push_relation_aggregate`], projecting
    /// `CASE WHEN EXISTS(...) THEN 1 ELSE 0`. It reuses the `QuerySet`
    /// resolver, so the reverse-FK / M2M / GFK logic lives in one
    /// place.
    fn push_relation_exists(&mut self, name: &str) {
        match QuerySet::<T>::resolve_rel_exists(name, /*negated=*/ false) {
            Some(exists) => {
                let expr = AggregateExpr::RelatedAggregate(Box::new(
                    crate::core::subquery::exists_as_int(exists),
                ));
                self.aggregates
                    .push((std::borrow::Cow::Owned(format!("{name}_exists")), expr));
            }
            None => {
                self.deferred_error.get_or_insert(QueryError::UnknownField {
                    model: T::SCHEMA.name,
                    field: name.to_owned(),
                });
            }
        }
    }

    /// Chain a relation `COUNT` onto an existing aggregate builder,
    /// like [`QuerySet::annotate_count`], so two relation counts fit in
    /// one query:
    /// `Post::objects().annotate_count("comments").annotate_count("likes")`.
    #[must_use]
    pub fn annotate_count(mut self, name: &str) -> Self {
        self.push_relation_aggregate(name, None, AggregateExpr::Count(None), "count");
        self
    }

    /// Chain a relation `SUM(<column>)`. See [`QuerySet::annotate_sum`].
    #[must_use]
    pub fn annotate_sum(mut self, name: &str, column: &'static str) -> Self {
        self.push_relation_aggregate(name, Some(column), AggregateExpr::Sum(column), "sum");
        self
    }

    /// Chain a relation `AVG(<column>)`. See [`QuerySet::annotate_avg`].
    #[must_use]
    pub fn annotate_avg(mut self, name: &str, column: &'static str) -> Self {
        self.push_relation_aggregate(name, Some(column), AggregateExpr::Avg(column), "avg");
        self
    }

    /// Chain a relation `MAX(<column>)`. See [`QuerySet::annotate_max`].
    #[must_use]
    pub fn annotate_max(mut self, name: &str, column: &'static str) -> Self {
        self.push_relation_aggregate(name, Some(column), AggregateExpr::Max(column), "max");
        self
    }

    /// Chain a relation `MIN(<column>)`. See [`QuerySet::annotate_min`].
    #[must_use]
    pub fn annotate_min(mut self, name: &str, column: &'static str) -> Self {
        self.push_relation_aggregate(name, Some(column), AggregateExpr::Min(column), "min");
        self
    }

    /// Chain a relation `<name>_exists` projection. See
    /// [`QuerySet::annotate_exists`].
    #[must_use]
    pub fn annotate_exists(mut self, name: &str) -> Self {
        self.push_relation_exists(name);
        self
    }

    /// Annotate without projecting. The
    /// expression is registered under `name` and usable in
    /// [`Self::filter`] and [`Self::order_by`], but the writer
    /// **leaves it out of the SELECT list**.
    ///
    /// Use it to filter or order by a derived aggregate without
    /// decoding that column on every row:
    ///
    /// ```ignore
    /// // Authors with > 5 posts, ordered by post count desc — but no post
    /// // count column in the result row.
    /// Author::objects()
    ///     .aggregate()
    ///     .group_by("id")
    ///     .alias("c", count_all().into())
    ///     .filter("c", Op::Gt, 5_i64)
    ///     .order_by(&[("c", true)])
    ///     .compile()?;
    /// // SELECT "id" FROM "author"
    /// // GROUP BY "id"
    /// // HAVING COUNT(*) > $1
    /// // ORDER BY COUNT(*) DESC
    /// ```
    ///
    /// **Order matters**, as with [`Self::annotate`]: call
    /// `.alias(name, ...)` BEFORE the matching `.filter(name, ...)` or
    /// `.order_by([(name, ...)])`, so the lookup can find it.
    ///
    /// If `name` clashes with an annotate alias, the annotate wins.
    #[must_use]
    pub fn alias(mut self, name: &'static str, expr: AggregateExpr) -> Self {
        self.aliases.push((std::borrow::Cow::Borrowed(name), expr));
        self
    }

    /// Add a `HAVING` predicate. Multiple calls AND-join.
    #[must_use]
    pub fn having<E: Into<crate::core::TypedExpr<T>>>(mut self, predicate: E) -> Self {
        let expr = predicate.into().into_expr();
        match self.having {
            None => self.having = Some(expr),
            Some(ref mut existing) => existing.push_and(expr),
        }
        self
    }

    /// String-keyed filter that routes itself to WHERE or HAVING.
    /// If `field`
    /// matches an annotation alias from [`Self::annotate`], the
    /// predicate joins `HAVING`. Otherwise it goes to the WHERE path
    /// on the underlying `QuerySet`.
    ///
    /// ```ignore
    /// // Authors with > 10 published posts:
    /// Author::objects()
    ///     .aggregate()
    ///     .group_by("id")
    ///     .annotate("post_count", count_all().filter(Post::status.eq("published")).into())
    ///     .filter("post_count", Op::Gt, 10_i64)   // → HAVING (annotation alias)
    ///     .filter("active", Op::Eq, true)         // → WHERE  (model column)
    ///     .compile()?;
    /// ```
    ///
    /// **Order matters**: `.annotate(alias, ...)` must come BEFORE the
    /// matching `.filter(alias, ...)`, because the alias is resolved
    /// at call time, not when the query compiles.
    ///
    /// **Gap**: an alias-routed HAVING predicate skips the schema
    /// column check, because the alias is not a real column, so a
    /// typo surfaces at the database rather than at `compile()`.
    /// WHERE-routed predicates are still checked.
    #[must_use]
    pub fn filter(
        mut self,
        field: &'static str,
        op: crate::core::Op,
        value: impl Into<crate::core::SqlValue>,
    ) -> Self {
        // Once an error is recorded, ignore later builder calls so the
        // original cause is not masked.
        if self.deferred_error.is_some() {
            return self;
        }
        // Find the AggregateExpr behind the alias. PG forbids
        // SELECT-list aliases in HAVING, so lift the whole expression
        // into the predicate instead of naming the alias:
        // `HAVING COUNT(*) > $1` works on every backend.
        // `.alias()` entries are lift-able too; annotate wins a clash
        // because it comes first.
        let agg = self
            .aggregates
            .iter()
            .chain(self.aliases.iter())
            .find(|(alias, _)| *alias == field)
            .map(|(_, expr)| expr.clone());
        if let Some(agg) = agg {
            // `write_expr_compare` handles the comparison operators
            // plus IN, BETWEEN, IS NULL, LIKE and ILIKE against an
            // aggregate on the left. JSON ops and null-safe equality
            // still need dialect-specific writers that take a `&str`
            // left side, so they are rejected here.
            if matches!(
                op,
                crate::core::Op::JsonContains
                    | crate::core::Op::JsonContainedBy
                    | crate::core::Op::JsonHasKey
                    | crate::core::Op::JsonHasAnyKey
                    | crate::core::Op::JsonHasAllKeys
                    | crate::core::Op::IsDistinctFrom
                    | crate::core::Op::IsNotDistinctFrom
            ) {
                self.deferred_error = Some(crate::core::QueryError::HavingOpNotSupported {
                    alias: field.to_owned(),
                    op,
                });
                return self;
            }
            let pred = WhereExpr::ExprCompare {
                lhs: crate::core::Expr::Aggregate(Box::new(agg)),
                op,
                rhs: crate::core::Expr::Literal(value.into()),
            };
            match self.having {
                None => self.having = Some(pred),
                Some(ref mut existing) => existing.push_and(pred),
            }
        } else {
            // Forward to the QuerySet's WHERE path, where
            // `resolve_pending` catches a typo'd column at compile().
            self.qs = self.qs.filter_op(field, op, value);
        }
        self
    }

    /// Add `ORDER BY` columns. `desc = true` → DESC.
    #[must_use]
    pub fn order_by(mut self, items: &[(&'static str, bool)]) -> Self {
        self.order_by.extend_from_slice(items);
        self
    }

    /// Set `LIMIT`.
    #[must_use]
    pub fn limit(mut self, n: i64) -> Self {
        self.limit = Some(n);
        self
    }

    /// Set `OFFSET`.
    #[must_use]
    pub fn offset(mut self, n: i64) -> Self {
        self.offset = Some(n);
        self
    }

    /// Compile to an [`AggregateQuery`] IR.
    ///
    /// # Errors
    /// Returns [`QueryError`] if any filter or having clause names an
    /// unknown field, or if `.values()` was called without a
    /// subsequent aggregating `.annotate(...)`.
    ///
    /// # GROUP BY inference
    ///
    /// Without an explicit `.group_by(...)`, the builder fills it in:
    ///
    /// * `.values(cols).annotate(agg)` → `GROUP BY cols` (shape 2).
    /// * `.annotate(agg)` (no values) → `GROUP BY` every non-aggregate
    ///   scalar column on the model (shape 3).
    /// * `.annotate(window)` only → no GROUP BY (window functions are
    ///   per-row).
    ///
    /// Explicit `.group_by(...)` always wins.
    pub fn compile(mut self) -> Result<AggregateQuery, QueryError> {
        // Report any deferred builder error first, so the user sees
        // the real cause and not a later compile failure.
        if let Some(e) = self.deferred_error {
            return Err(e);
        }
        let model = T::SCHEMA;
        let is_none = self.qs.is_none;
        // DISTINCT, a set operation, a derived join or a limit shape the
        // rows, so group the compiled queryset (joins included) as a derived table.
        let (where_clause, mut source, joins) = if self.qs.distinct.is_some()
            || !self.qs.compound.is_empty()
            || !self.qs.subquery_joins.is_empty()
            || self.qs.limit.is_some()
            || self.qs.offset.is_some()
        {
            let select = self.qs.compile()?;
            (WhereExpr::And(Vec::new()), Some(select), Vec::new())
        } else {
            // Fold global scopes into the WHERE so aggregates honour them
            // too: `.count()` on a `published_only` model counts published
            // rows, not the whole table.
            self.qs.apply_global_scopes();
            // Carry the ad-hoc JOINs over so the aggregate can group by a
            // related column, as in `group_by("author.name")`.
            let joins = std::mem::take(&mut self.qs.ad_hoc_joins);
            (resolve_pending(model, self.qs.pending)?, None, joins)
        };
        // Check each AggregateExpr for column typos. This covers the
        // partition_by, order_by and args of a window aggregate. The
        // flat `Sum("col")` / `Count(Some("col"))` shapes are a known
        // gap and are not checked.
        for (_alias, expr) in self.aggregates.iter().chain(self.aliases.iter()) {
            validate_aggregate_expr_columns(model, expr)?;
        }
        // `.order_by((name, desc))` uses the same alias registry as
        // `.filter(name, ...)`. On a match, lift the whole aggregate
        // expression into the `ORDER BY`. That is required for an
        // `.alias()` name, which is not in the SELECT, and harmless
        // for an `.annotate()` one.
        let alias_for = |name: &str| -> Option<crate::core::AggregateExpr> {
            self.aggregates
                .iter()
                .chain(self.aliases.iter())
                .find(|(a, _)| a.as_ref() == name)
                .map(|(_, e)| e.clone())
        };
        // Dotted order columns, which a derived table must also project.
        let order_join_cols: Vec<&'static str> = self
            .order_by
            .iter()
            .map(|(c, _)| *c)
            .filter(|c| c.contains('.'))
            .collect();
        let order_by = self
            .order_by
            .into_iter()
            .map(|(col, desc)| match (alias_for(col), col.split_once('.')) {
                (Some(agg), _) => {
                    crate::core::OrderItem::expr(crate::core::Expr::Aggregate(Box::new(agg)), desc)
                }
                // A dotted `alias.col` names a joined column.
                (None, Some((alias, column))) => crate::core::OrderItem::expr(
                    crate::core::Expr::AliasedColumn { alias, column },
                    desc,
                ),
                (None, None) => crate::core::OrderItem::column(col, desc),
            })
            .collect();

        // GROUP BY inference. `.alias()` entries count here too: an
        // `.alias("c", Count(...))` still needs a GROUP BY even
        // though nothing is projected.
        let has_aggregating = self
            .aggregates
            .iter()
            .chain(self.aliases.iter())
            .any(|(_, e)| e.is_aggregating());
        let group_by = if !self.group_by.is_empty() {
            // An explicit `.group_by(...)` always wins. Check the
            // columns now, or a typo would only surface at the DB.
            for col in &self.group_by {
                // A dotted `alias.col` names a joined table, so the
                // JOIN validates it, not the base model.
                if !col.contains('.') && model.field_by_column(col).is_none() {
                    return Err(QueryError::UnknownField {
                        model: model.name,
                        field: (*col).to_owned(),
                    });
                }
            }
            self.group_by
        } else if let Some(cols) = self.values.as_ref() {
            // `.values(cols)` set. Without an aggregating annotation
            // we'd produce a degenerate `SELECT cols GROUP BY cols`
            // (distinct-projection) — refuse and point the user at
            // the right path for pure projection.
            if !has_aggregating {
                return Err(QueryError::ValuesRequiresAggregate { cols: cols.clone() });
            }
            for col in cols {
                if !col.contains('.') && model.field_by_column(col).is_none() {
                    return Err(QueryError::UnknownField {
                        model: model.name,
                        field: (*col).to_owned(),
                    });
                }
            }
            cols.clone()
        } else if has_aggregating {
            // Shape 3: an implicit GROUP BY over every non-aggregate
            // scalar column.
            model.scalar_fields().map(|f| f.column).collect()
        } else {
            // No aggregating annotation and no values: a pure window
            // annotation or an empty builder. No GROUP BY.
            Vec::new()
        };

        // `.none().count()` must return zero without scanning a row.
        // Use the same never-match guard as UPDATE / DELETE, and add
        // `LIMIT 0` so the executor stops early even when a GROUP BY
        // could otherwise produce rows.
        let (where_clause, limit) = if is_none {
            (never_match_clause(model, where_clause)?, Some(0))
        } else {
            (where_clause, self.limit)
        };
        if let Some(select) = source.as_mut() {
            project_group_cols(model, select, &group_by)?;
            project_group_cols(model, select, &order_join_cols)?;
        }

        Ok(AggregateQuery {
            model,
            joins,
            where_clause,
            group_by,
            aggregates: self.aggregates,
            aliases: self.aliases,
            having: self.having,
            order_by,
            limit,
            offset: self.offset,
            source: source.map(SelectQuery::into_derived),
        })
    }
}

/// Project each dotted `alias.col` group column out of the derived
/// `select`, where the outer aggregate reads it back as `alias__col`.
fn project_group_cols(
    model: &'static ModelSchema,
    select: &mut SelectQuery,
    group_by: &[&'static str],
) -> Result<(), QueryError> {
    for col in group_by {
        let Some((alias, c)) = col.split_once('.').filter(|(a, _)| *a != model.table) else {
            continue;
        };
        let join = select.joins.iter_mut().find(|j| j.alias == alias);
        // Every UNION branch must project the same columns, so only a
        // plain derived select can grow one.
        match join {
            Some(j) if select.compound.is_empty() => {
                if !j.project.contains(&c) {
                    j.project.push(c);
                }
            }
            _ => {
                return Err(QueryError::GroupByJoinUnreachable {
                    model: model.name,
                    column: (*col).to_owned(),
                })
            }
        }
    }
    Ok(())
}

/// Walk an [`AggregateExpr`] for column references that must resolve
/// against `model`. Only `AggregateExpr::Window` carries columns this
/// can check: its `partition_by`, `order_by` and any `Expr::Column`
/// argument. The flat variants such as `Sum("col")` hold a bare
/// `&'static str` that no validator visits — a known gap.
///
/// [`AggregateExpr`]: crate::core::AggregateExpr
fn validate_aggregate_expr_columns(
    model: &'static ModelSchema,
    expr: &crate::core::AggregateExpr,
) -> Result<(), QueryError> {
    use crate::core::AggregateExpr;
    match expr {
        AggregateExpr::Filtered { inner, filter } => {
            filter.validate(model)?;
            validate_aggregate_expr_columns(model, inner)
        }
        AggregateExpr::Coalesced { inner, .. } => validate_aggregate_expr_columns(model, inner),
        AggregateExpr::Window(w) => {
            for col in &w.partition_by {
                if model.field_by_column(col).is_none() {
                    return Err(QueryError::UnknownField {
                        model: model.name,
                        field: (*col).to_owned(),
                    });
                }
            }
            for o in &w.order_by {
                if model.field_by_column(o.column).is_none() {
                    return Err(QueryError::UnknownField {
                        model: model.name,
                        field: o.column.to_owned(),
                    });
                }
            }
            for arg in &w.args {
                validate_expr_columns_in_model(model, arg)?;
            }
            Ok(())
        }
        // The flat variants (Count, Sum, Avg, Max, Min, CountDistinct,
        // StdDev*, Variance*) name their column with a bare
        // `&'static str` that nothing here checks, so a typo only
        // surfaces at execution. Known gap.
        _ => Ok(()),
    }
}

// ====================================================================
// Pure projection — `.values_dict()` / `.values_list()`
// ====================================================================

/// Pure-projection queryset returned by [`QuerySet::values_dict`].
/// Compiles to a `SELECT <cols> FROM …` with the WHERE / ORDER BY /
/// LIMIT / OFFSET / set-algebra branches of the underlying queryset
/// preserved. The terminal is [`Self::fetch`], added by the executor.
pub struct ValuesQuerySet<T: Model> {
    pub(crate) qs: QuerySet<T>,
    pub(crate) cols: Vec<&'static str>,
}

/// Pure-projection queryset returned by [`QuerySet::values_list`].
/// Like [`ValuesQuerySet`], but the fetch yields `Vec<Vec<SqlValue>>`
/// with cells in `cols` order instead of a `HashMap`.
pub struct ValuesListQuerySet<T: Model> {
    pub(crate) qs: QuerySet<T>,
    pub(crate) cols: Vec<&'static str>,
}

/// Single-column projection queryset returned by
/// [`QuerySet::values_list_flat`]. The fetch decodes the column into
/// `Vec<U>` through sqlx's typed scalar path.
pub struct ValuesFlatQuerySet<T: Model> {
    pub(crate) qs: QuerySet<T>,
    pub(crate) col: &'static str,
}

impl<T: Model> ValuesQuerySet<T> {
    /// Compile to a [`SelectQuery`] with `projection` set to the
    /// validated column list.
    ///
    /// # Errors
    /// - [`QueryError::EmptyValuesProjection`] if `cols` is empty.
    /// - [`QueryError::UnknownField`] if any column doesn't exist on
    ///   the model.
    /// - Anything [`QuerySet::compile`] surfaces.
    pub fn compile(self) -> Result<SelectQuery, QueryError> {
        compile_values_select(self.qs, self.cols)
    }

    /// The validated column list, so the fetch in [`crate::sql`] can
    /// pass it to the row decoder.
    #[must_use]
    pub fn columns(&self) -> &[&'static str] {
        &self.cols
    }
}

impl<T: Model> ValuesListQuerySet<T> {
    /// See [`ValuesQuerySet::compile`].
    ///
    /// # Errors
    /// As [`ValuesQuerySet::compile`].
    pub fn compile(self) -> Result<SelectQuery, QueryError> {
        compile_values_select(self.qs, self.cols)
    }

    /// The validated column list, for the terminal fetch.
    #[must_use]
    pub fn columns(&self) -> &[&'static str] {
        &self.cols
    }
}

impl<T: Model> ValuesFlatQuerySet<T> {
    /// Compile to a [`SelectQuery`] with `projection` set to the
    /// single column.
    ///
    /// # Errors
    /// - [`QueryError::UnknownField`] if `col` doesn't exist on the
    ///   model.
    /// - Anything [`QuerySet::compile`] surfaces.
    pub fn compile(self) -> Result<SelectQuery, QueryError> {
        compile_values_select(self.qs, vec![self.col])
    }
}

// ====================================================================
// `.dates(field, kind)` — distinct truncated dates
// ====================================================================

/// Truncation granularity for [`QuerySet::dates`] / [`QuerySet::datetimes`].
/// One of year, month or day.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DateKind {
    Year,
    Month,
    Day,
}

/// Builder returned by [`QuerySet::dates`]. Run it with
/// [`crate::sql::fetch_dates_pool`], which emits
/// `SELECT DISTINCT <trunc(col)> AS d FROM (<inner-query>) sub ORDER BY d`.
/// The wrapper keeps the queryset's WHERE, JOINs, LIMIT and ORDER BY,
/// so filters set before `.dates()` still apply.
pub struct DatesQuerySet<T: Model> {
    pub(crate) qs: QuerySet<T>,
    pub(crate) field: &'static str,
    pub(crate) kind: DateKind,
    pub(crate) descending: bool,
}

impl<T: Model> DatesQuerySet<T> {
    /// Reverse the ORDER BY direction. The default is ascending,
    /// oldest first.
    #[must_use]
    pub fn order_desc(mut self, desc: bool) -> Self {
        self.descending = desc;
        self
    }

    /// Check the field and return its column name from the schema.
    ///
    /// # Errors
    /// [`QueryError::UnknownField`] when the model has no such field,
    /// and [`QueryError::TypeMismatch`] when it is not a date or
    /// datetime column.
    pub fn resolve_column(&self) -> Result<&'static str, QueryError> {
        let model: &'static ModelSchema = T::SCHEMA;
        let field = model
            .field(self.field)
            .ok_or_else(|| QueryError::UnknownField {
                model: model.name,
                field: self.field.to_owned(),
            })?;
        // The field must be a Date or DateTime, or the truncation
        // means nothing. Other types would quietly produce garbage on
        // some backends.
        if !matches!(
            field.ty,
            crate::core::FieldType::Date | crate::core::FieldType::DateTime
        ) {
            return Err(QueryError::TypeMismatch {
                model: model.name,
                field: self.field.to_owned(),
                // Either Date or DateTime is fine; report DateTime as
                // the representative, since truncation always yields
                // a Date whatever the input.
                expected: crate::core::FieldType::DateTime,
                actual: field.ty,
            });
        }
        Ok(field.column)
    }
}

impl<T: Model> QuerySet<T> {
    /// The distinct date values of `field`, truncated to `kind`.
    ///
    /// Output is ascending by default, oldest first. Chain
    /// [`DatesQuerySet::order_desc`] for newest first.
    ///
    /// Filters, joins and limits on the queryset still apply, so
    /// `.filter(...).dates(...)` only sees matching rows.
    #[must_use]
    pub fn dates(self, field: &'static str, kind: DateKind) -> DatesQuerySet<T> {
        DatesQuerySet {
            qs: self,
            field,
            kind,
            descending: false,
        }
    }

    /// The distinct datetime values of `field`, truncated to `kind`.
    ///
    /// Finer than [`Self::dates`]: as well as `Year`, `Month` and
    /// `Day`, it takes `Hour`, `Minute` and `Second`. Each value is a
    /// `DateTime<Utc>` at the truncated instant.
    #[must_use]
    pub fn datetimes(self, field: &'static str, kind: DateTimeKind) -> DateTimesQuerySet<T> {
        DateTimesQuerySet {
            qs: self,
            field,
            kind,
            descending: false,
        }
    }
}

/// Truncation granularity for [`QuerySet::datetimes`]: year, month,
/// day, hour, minute or second.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DateTimeKind {
    Year,
    Month,
    Day,
    Hour,
    Minute,
    Second,
}

/// Builder returned by [`QuerySet::datetimes`]. Like
/// [`DatesQuerySet`], but with finer granularity and a
/// `DateTime<Utc>` return type.
pub struct DateTimesQuerySet<T: Model> {
    pub(crate) qs: QuerySet<T>,
    pub(crate) field: &'static str,
    pub(crate) kind: DateTimeKind,
    pub(crate) descending: bool,
}

impl<T: Model> DateTimesQuerySet<T> {
    #[must_use]
    pub fn order_desc(mut self, desc: bool) -> Self {
        self.descending = desc;
        self
    }

    pub fn resolve_column(&self) -> Result<&'static str, QueryError> {
        let model: &'static ModelSchema = T::SCHEMA;
        let field = model
            .field(self.field)
            .ok_or_else(|| QueryError::UnknownField {
                model: model.name,
                field: self.field.to_owned(),
            })?;
        if !matches!(
            field.ty,
            crate::core::FieldType::Date | crate::core::FieldType::DateTime
        ) {
            return Err(QueryError::TypeMismatch {
                model: model.name,
                field: self.field.to_owned(),
                expected: crate::core::FieldType::DateTime,
                actual: field.ty,
            });
        }
        Ok(field.column)
    }
}

/// Shared compile path for the three values builders. Validates the
/// column list, then delegates to `QuerySet::compile` and stamps the
/// projection onto the resulting [`SelectQuery`].
fn compile_values_select<T: Model>(
    qs: QuerySet<T>,
    cols: Vec<&'static str>,
) -> Result<SelectQuery, QueryError> {
    if cols.is_empty() {
        return Err(QueryError::EmptyValuesProjection);
    }
    let model: &'static ModelSchema = T::SCHEMA;
    for col in &cols {
        if model.field_by_column(col).is_none() {
            return Err(QueryError::UnknownField {
                model: model.name,
                field: (*col).to_owned(),
            });
        }
    }
    let mut q = qs.compile()?;
    project_every_branch(&mut q, &cols);
    Ok(q)
}

/// Set `cols` on `q` and on each set-op branch that projects nothing,
/// so every branch of a union returns the same columns.
fn project_every_branch(q: &mut SelectQuery, cols: &[&'static str]) {
    q.projection = Some(cols.to_vec());
    for branch in &mut q.compound {
        if branch.query.projection.is_none() {
            project_every_branch(&mut branch.query, cols);
        }
    }
}

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

    #[test]
    fn too_deep_paths_fail_alone_and_are_not_kept() {
        let deep = "t1__a__a__a__a__a__a";
        assert!(matches!(
            intern_join_alias(deep),
            Err(QueryError::RelationPathTooDeep { max: 6, .. })
        ));
        let a = intern_join_alias("t1__b").unwrap();
        assert!(std::ptr::eq(a, intern_join_alias("t1__b").unwrap()));
        intern_join_alias("t1__a__a__a__a__a").expect("six hops still intern");
    }
}