ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
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
//! The wire face: one output object per declared backend, and the filter beside it — plus the
//! record's ORDER-BY, which is not one of them and lives here only because its neighbours do.
//!
//! Only the OUTPUT object needs a per-field declaration. The tree fixes the rest — `GraphqlOutput`'s
//! `Key` and `KeyInput` are mechanical projections of the key's columns, and the search envelopes
//! derive from `Key` alone — so nothing here asks a declaration for them.
//!
//! **The filter takes every STORED column, not every exposed one.** A field carrying `persist` is
//! filterable and orderable *because it is stored*; a field that is not stored has nothing to
//! query. So there is no `filterable` marker to write and none to forget, and the two lists differ
//! on purpose: a column may be filtered on without being returned.
//!
//! **The ORDER-BY is emitted here and is not a wire type**, which is the one thing to know before
//! reading the two halves together: [`RecordModel::ordering`] writes it, a record with no
//! `graphql(…)` gets it, and the wire face declares three types rather than four. It sits in this
//! file because its variants, its per-database resolvers and its lowering are the same walks the
//! filter's are, and a second file would put one walk in two places.
//!
//! **Both faces project the DOMAIN type**, with per-backend `input_type`/`output_type` overrides. A
//! database-generic input is refused: it would push storage encoding — a big-endian blob — onto the
//! wire, and two declared databases would render two SDL types for one logical filter. The bridge
//! from domain values to storage values is the comparison layer's, and it crosses exactly once.
//!
//! **SDL names are the external face, Rust identifiers the safe one.** The external name is what a
//! client sees and must not be rewritten by a mangling rule it cannot know about; the Rust one is
//! normalised to snake_case, because a generated field a consumer cannot edit must not carry a
//! `non_snake_case` warning. The two are two faces of ONE declared name, and both live on the model.
//!
//! **No backend derive is emitted here — structures and enums only.** `InputObject` and
//! `OneofObject` are the BACKEND's traits, and implementing a backend's traits is the
//! trait-implementation work the era rule holds back. The external names are carried on the
//! model for exactly that round to consume: [`crate::model::Face::name`] and
//! [`crate::model::GraphqlKind::output_object`] name what to emit and what to emit it with, so
//! nothing about the shapes has to be rediscovered.
//!
//! The OUTPUT object's face is not a derive at all, and the model says so: it is an `#[Object]`
//! attribute over the ACCESSORS this file already writes, because the accessor law puts the public
//! face there and leaves the members a `pub(crate)` substrate no rename word may move.
//!
//! The ORDER-BY's face is no longer held: [`wire`](super::wire) writes it out, `InputType` and the
//! two markers, rather than attaching the derive named above — a derive belongs to a type's own
//! declaration, and this file writes those OUTSIDE the binding gate. What that file's note carries
//! is why the other three faces are still held, which is a fact about the framework's own filter
//! registrations rather than about the era rule.
//!
//! What the held-back round cannot change is the SHAPE, which is why the order-by's is measured
//! here rather than left to it: `OneofObject` takes an enum of single-value tuple variants and
//! nothing else, so a face built any other way could not carry the derive when it arrives.
//!
//! The FRAMEWORK's own trait layer is a separate question, and two items of it are emitted:
//! [`DatabaseBackend::comparison_traits`] binds the filter to each database's comparison, and
//! [`DatabaseBackend::lowering`] is the promise that map makes — its associated type carries
//! `ComplexComparison<Db>` as an item bound, so writing the map without the lowering is not a
//! smaller emission but an ill-formed one. What the era rule still holds back is stated at the
//! first, with what was measured.
//!
//! **Descriptions come from `attrs(desc = …)` and nowhere else.** A source `///` comment is
//! deliberately not published: what reaches a schema is what a declaration says reaches it.

use quote::{format_ident, quote};

use crate::{
  method::Member,
  model::{
    Crossing, DatabaseBackend, FrameworkMarker, Graphql, GraphqlBackend, Label, Marker,
    PersistColumn, RecordModel, Reference,
  },
  name::RustSafeName,
};

/// The filter that guards a column of this DOMAIN type: the interpretation the type carries, and
/// that interpretation's filter.
///
/// Two projections rather than one, and the split is the whole of what the marker layer bought. The
/// first asks what the type MEANS — `Vec<u8>` is a blob, `Vec<Label>` a list — and the second what
/// guards that meaning. Keyed on the type alone, the first question had one answer per type and a
/// declaration could not say otherwise; `ingraph`'s `marker` module is where it is answered now.
///
/// The emitter picks NO marker of its own, and must not: it sees a field's SPELLING, where
/// `type Labels = Vec<String>` is indistinguishable from a scalar, so a marker chosen here would
/// read an alias as the wrong interpretation. Naming the type and letting the type answer is what
/// keeps an alias transparent — the same reason `flatten` is a marker the declaration writes rather
/// than a fact this emitter could detect.
///
/// # A DECLARED marker replaces the first projection rather than feeding it
///
/// ```text
/// declared none:  <<T as DefaultMarker>::Marker as ToGraphqlFilter>::Filter
/// declared one:   <TheirMarker<T> as ToGraphqlFilter>::Filter
/// ```
///
/// TWO shapes, and they cannot be unified: a trait impl cannot be overridden per field, so an
/// override has to BYPASS the inference. That is honest rather than a hole — the default IS an
/// indirection, and what an override says is *do not ask the type, I have answered*. A `T` with no
/// `DefaultMarker` row at all is filterable under the second shape and not under the first, which is
/// the same fact seen from the other side.
///
/// The FIELD's type is applied here rather than written into the declaration, so an author names
/// `their::RollMarker` where the field is `Roll<Tag>` instead of spelling the type twice. Every one
/// of the framework's own markers is that shape; the price is that a declared marker must be
/// generic over the field type, and `ingraph-derive`'s grammar says so.
///
/// # The `Option` at the COLUMN position is structural, and a WORD penetrates it
///
/// Presence is not a family, so a written `Option<…>` is taken off before a family word is applied
/// and the word's own family says what an `Option` of its reading is:
///
/// - A COLLECTION has no null state, and [`Label::collection`](crate::model::Label::collection)
///   carries the ruling: the column resolves as if the `Option` had not been written, so the
///   `Nullable<F>` wrapper is never built for it. Taking the `Option` off is also structural for
///   the element, whose type is `<C as State<Extracted<Inner>>>::Output` — asked of the `Option`
///   that projection answers with the collection rather than with what it holds.
/// - Every other word answers `Marker::UnderOption`, which is the FAMILY's own statement of the
///   same question, and for the six value families that is the null test.
///
/// The custom escape is the one marker no `Option` is taken off for, and that is the shape the
/// escape already promises: the FIELD's type is what a declared marker is applied to, and the field's
/// type is what was written. Penetrating the `Option` would ask its author for a `Marker` impl to
/// answer a question they were never asked, on a marker whose family this crate cannot see.
///
/// A field naming no word takes the inference, and the same ruling is settled there by the TYPE —
/// `ingraph`'s blanket over `Option<T>` asks the inferred marker's `UnderOption` too. The two paths
/// agree by construction, which is why the labelled emission of a word that agrees with a type's
/// own row resolves to the very type the inference resolves to.
///
/// # The FACE is the node's KIND, and this is the seat where the two host worlds part
///
/// *Each face tells its own truth* — the 2026-08-22 ruling. A composite column's predicate is the
/// STORED subset where the node holds rows and the whole declared field set where it does not, and
/// [`NodeKind::holds_rows`](crate::model::NodeKind::holds_rows) is the fact that already answers
/// which. ONE fork, read here rather than at each of the five call sites, because a record's FILTER
/// and its COMPARISON are the same list seen twice: a door taking one face for the slot and the
/// other for the crossing would emit a struct whose members no `ToDatabaseComparison` reaches.
///
/// It decides nothing for any reading but the composite one, and nothing at all for a declaration
/// holding no fragment activated for both host kinds — which is every declaration written before the
/// ruling.
///
/// # The rowless arm is WIRED and not yet exercised, and that is measured rather than assumed
///
/// A rowless node's filter is built from [`queried_columns`](Self::queried_columns), which walks
/// `stored_columns` — and an entity has no stored columns, so `<Entity>Filter` is a struct with no
/// member, no input face and therefore no composite slot for this fork to decide. The fork is stated
/// here anyway because it is the seat the question is asked AT: the alternative is a call taking the
/// stored face unconditionally, which would be silently wrong the day the entity tier's filter grows
/// a field. What proves the same routing on live types today is the FRAGMENT's own nested walk,
/// where both faces exist and each reads its components at its own — see
/// [`crate::fields::FieldsModel::predicate`].
fn filter_of(
  model: &RecordModel,
  ty: &syn::Type,
  marker: Option<&Marker>,
) -> proc_macro2::TokenStream {
  let face = if model.kind.holds_rows() {
    super::FilterFace::Column
  } else {
    super::FilterFace::Full
  };
  super::filter_of(&model.krate, ty, marker, face)
}

/// The type a label's word is applied to when an `Option<…>` was WRITTEN around it, and `None`
/// when none was.
///
/// # The only place this emitter reads a type's SPELLING, and what makes it admissible
///
/// Everywhere else the rule is absolute: the emitter names the declared type and the compiler
/// answers, because `type Ids = Vec<Uuid7>` and a scalar are the same tokens. Nothing here
/// contradicts it, because nothing here is a GUESS about what the type is — the declaration already
/// said, in the word that named the field's family. What is left is to find the type that word is
/// ABOUT, and presence is not a family: `Option` is a wrapper the word penetrates, chosen by the
/// SHAPE `Option<…>` and by nothing else, so the shape is what has to go.
///
/// It cannot be asked of the type instead. The projection that would answer it — *this type with its
/// nullability removed* — is not on the shelf: `State<Extracted<Inner>>` strips ONE layer from any
/// container it knows, so it takes a `Vec<T>` down to `T` as readily as an `Option<Vec<T>>` down to
/// `Vec<T>`, and a peel that over-strips a bare collection is not the peel this needs.
///
/// # An ALIAS is a refusal, never a wrong answer
///
/// `type MaybeTags = Option<Vec<String>>` hides the shape, so nothing is taken off and the marker
/// lands on `MaybeTags` — where `MaybeTags: ListFilterMarker` is unsatisfied and rustc names the
/// type at the declaration. That is the whole difference from the syntactic reading this crate
/// refuses for the PROJECTIONS: that one ANSWERS, handing an aliased collection back as a scalar's
/// borrow with no diagnostic anywhere; this one stops. A rule that cannot be silently wrong is a
/// rule a reader can keep.
///
/// The last segment is what is matched, so `core::option::Option<T>` and `::std::option::Option<T>`
/// are the same shape a bare `Option<T>` is. A qualified self type (`<A as B>::C`) is left alone: it
/// is a projection rather than a written wrapper, and its head is not a name this can read.
fn written_option(ty: &syn::Type) -> Option<&syn::Type> {
  let syn::Type::Path(path) = ty else {
    return None;
  };
  let segment = path.path.segments.last()?;
  if path.qself.is_some() || segment.ident != "Option" {
    return None;
  }
  let syn::PathArguments::AngleBracketed(arguments) = &segment.arguments else {
    return None;
  };
  let mut arguments = arguments.args.iter();
  match (arguments.next(), arguments.next()) {
    (Some(syn::GenericArgument::Type(inner)), None) => Some(inner),
    _ => None,
  }
}

impl Marker {
  /// The MARKER a declared label resolves to at a column of this type — the marker TREE, built from
  /// the label tree.
  ///
  /// # Every element TYPE is a projection, never a token
  ///
  /// `list(string)` on a `Vec<Tag>` resolves to `ListMarker<Vec<Tag>, StringMarker<Tag>>`, and the
  /// `Tag` in it is written `<Vec<Tag> as State<Extracted<Inner>>>::Output` — the projection layer's
  /// answer to *what does this collection hold*. Reading the element out of the declaration's tokens
  /// would resolve `type Tags = Vec<Tag>` as a collection of nothing; asking the type keeps an alias
  /// as transparent one level in as it is at the field.
  ///
  /// # A word DECIDES, where the inference only offers
  ///
  /// The element marker is the second parameter both collection markers already carry, whose
  /// default is the element's own `DefaultMarker` row. Naming it is what makes a word that
  /// DISAGREES with that row win: `list(enum)` over an element whose own row says text resolves to
  /// the enumeration filter, and the row is never consulted.
  ///
  /// The family trait is what audits the word either way, at the element exactly as at the field:
  /// `ListMarker`'s own bound requires the inner marker to resolve to a filter, so `list(duration)`
  /// over a `Vec<i64>` is `E0277` naming `DurationFilterMarker` at the `#[ingraph::record(…)]`.
  ///
  /// # The optional reading is ASKED for, not spelled
  ///
  /// `<W<T> as Marker>::UnderOption` rather than `NullableMarker<Option<T>, W<T>>`, and the two
  /// reasons are measured rather than stylistic:
  ///
  /// - **It emits no `Option` token.** An expansion lands in the DECLARER's namespace, where
  ///   `Option` may name something the declaring module wrote — `ingraph-derive`'s `Shadowed`
  ///   fixture is exactly that module, and it carries an optional column under a word.
  /// - **The family ruling stays in ONE place.** Which wrapper an `Option` of a reading is, is a
  ///   fact about the family, and the family already states it. Naming the wrapper here would be
  ///   that ruling written a second time, in a layer that would then have to be kept in step.
  ///
  /// # It takes a CRATE ROOT and not a model, because both declarations write words
  ///
  /// A record's field and an interface's PIN read one vocabulary through one front-end door, and
  /// the only thing this needs off either model is where the framework's own names live.
  pub(crate) fn resolved(&self, krate: &syn::Path, ty: &syn::Type) -> proc_macro2::TokenStream {
    let shelved = |module: &[&str], name: &str| super::framework(krate, module, name);
    // The FIELD-INTENT half is deliberately unread here: `sortable` decides what the STORAGE does
    // with a collection and nothing about the filter its label resolves to, so the marker a
    // declaration with the word resolves to is the marker it resolved to without one.
    let Self::Framework(FrameworkMarker { label, element, .. }) = self else {
      let Self::Path(path) = self else {
        unreachable!("a marker is one of the framework's words or a declared path")
      };
      return quote!(#path<#ty>);
    };
    let subject = written_option(ty);
    let core = subject.unwrap_or(ty);
    let marker = shelved(&["marker"], label.item());
    let applied = match element {
      None => quote!(#marker<#core>),
      Some(element) => {
        let element = shelved(&["marker"], element.item());
        let state = shelved(&["state"], "State");
        let extracted = shelved(&["state"], "Extracted");
        let inner = shelved(&["state"], "Inner");
        quote!(#marker<#core, #element<<#core as #state<#extracted<#inner>>>::Output>>)
      }
    };
    // A collection reads a written `Option` transparently and every other word asks its family what
    // an `Option` of its reading is — see [`filter_of`], where the split is stated.
    if subject.is_none() || label.collection() {
      return applied;
    }
    let marker = shelved(&["marker"], "Marker");
    quote!(<#applied as #marker>::UnderOption)
  }
}

impl RecordModel {
  /// Whether the FRAMEWORK writes the output object's `id` member, or the face already carries one.
  ///
  /// Every output object has an address member; the question is WHOSE it is. A face that EXPOSES the
  /// id column has already published it — under `id`, which is the ordinary shape a GraphQL object
  /// takes, or under a name of its own — and a framework member beside that one would publish the
  /// same column twice, move it twice out of one record, and collide outright at the commoner of the
  /// two spellings.
  ///
  /// So the framework writes the member exactly where nothing else does. A field landing on the name
  /// `id` WITHOUT being the id column is a different mistake and stays a collision: the framework's
  /// member is there, and `emitted_methods` refuses the pair at the declaration.
  ///
  /// # WHERE ITS LIVE ANSWER MOVED TO, measured
  ///
  /// The inversion made publishing the DEFAULT: a declaration naming a wire backend publishes every
  /// column it has, and the one word that would take the id off the face is refused by name at both
  /// axes, identity being unskippable. So no DECLARATION reaches the `true` branch any more — the
  /// derive cannot build a wire face without its id column, and if it could, the whole corpus would
  /// be a duplicate-`id_ref` refusal instead of compiling.
  ///
  /// It is NOT dead, and the difference is which front end is asking. [`RecordModel`] is a plain
  /// model with public fields and two front ends — the derive today and a manifest compiler later —
  /// and a face assembled without the id column is a model the second one can hand over. Measured by
  /// forcing this to `false`: the output object then carries `key` and no `id` at all, an address a
  /// client cannot ask a row back by, which is the very shape the unskippable-identity law exists to
  /// prevent. So the seat's live domain moved from *a declaration that did not expose its id* to *a
  /// front end that did not*, and deleting it would trade an unreachable branch for a silent hole.
  ///
  /// The participation masks give it nothing either way: participation is a STORAGE axis and this is
  /// a WIRE one.
  pub(crate) fn wire_writes_id(&self) -> bool {
    let id = &self.key.id.source;
    !self
      .graphql
      .as_ref()
      .and_then(|graphql| graphql.backends.first())
      .is_some_and(|backend| backend.fields().iter().any(|field| field.source == *id))
  }

  /// The databases whose ROW can become the wire OUTPUT object — the ones that can SUPPLY every
  /// member the object is built from.
  ///
  /// Two conditions, and each is a member the object could not otherwise fill: the whole ADDRESS,
  /// which the `id` and `key` members are, and every EXPOSED field. A database missing either gets
  /// no crossing at all and a call site naming one fails to resolve — the same answer
  /// [`queryable`](Self::queryable) gives a database whose row cannot become the record.
  ///
  /// # SUPPLY, not carry — publishing and storing are two axes
  ///
  /// The second condition used to demand a COLUMN, which contradicted the participation model's own
  /// law: *the value exists in memory whatever supplied it*. A narrowed column is supplied by this
  /// database's own fill, so its row raises the whole record and its output object is complete — and
  /// a database excluded for want of a column it fills would silently hand the wire to whichever
  /// dialect still had one, which is the deployment deciding the schema by the back door.
  ///
  /// So the question asked is the RAISE's, and `carries_every_field` is the one that answers it. The
  /// consequence is what the declaration-truth ruling needs: a deployment really may serve its wire
  /// face from the database that narrowed a published column, and a predicate over that column is
  /// then refused at the crossing BY NAME rather than being unreachable.
  pub(crate) fn wire_rows(&self) -> Vec<&DatabaseBackend> {
    let exposed: &[crate::model::GraphqlField] = self
      .graphql
      .as_ref()
      .and_then(|graphql| graphql.backends.first())
      .map_or(&[], GraphqlBackend::fields);
    self
      .persist
      .iter()
      .flat_map(|persist| &persist.backends)
      .filter(|database| {
        self.key_columns_stored(database).is_some()
          && exposed.iter().all(|field| database.supplies(&field.source))
      })
      .collect()
  }

  /// Where each of the KEY's columns sits among a database's stored ones, in KEY order — and `None`
  /// where any of them is stored nowhere.
  ///
  /// Matched on the record FIELD rather than on a name, because a `key(rename = "…")` moves a
  /// column's name inside the key type and a `<db>(rename)` moves it inside the row: two
  /// scopes, two names, one field. The field is what neither can move.
  pub(crate) fn key_columns_stored(&self, database: &DatabaseBackend) -> Option<Vec<usize>> {
    self
      .key
      .columns()
      .map(|column| {
        database
          .columns()
          .iter()
          .position(|stored| stored.source == column.source)
      })
      .collect()
  }

  /// The interpretation the field behind this column declared, or `None` where the type answers for
  /// itself.
  ///
  /// Read off the RECORD's fields rather than off a face, because a label is the field's own: a
  /// column stored and not exposed reaches this through the comparison it crosses into, and a field
  /// bearing identity reaches it carrying no label at all.
  pub(super) fn marker_of(&self, source: &syn::Ident) -> Option<&Marker> {
    self
      .fields
      .iter()
      .find(|field| field.column.source == *source)?
      .marker
      .as_ref()
  }

  /// The `ref(…)` the field behind this column declared, or `None` where the column points at
  /// nothing.
  ///
  /// [`Self::marker_of`]'s twin, off the same list and for the same reason: a reference is the
  /// FIELD's fact, and a column reaches it by naming the field it projects. It is what turns a stored
  /// column into a widened one — see [`Graphql::filter_rows`].
  pub(super) fn reference_of(&self, source: &syn::Ident) -> Option<&Reference> {
    self
      .fields
      .iter()
      .find(|field| field.column.source == *source)?
      .reference
      .as_ref()
  }
}

impl RecordModel {
  /// The record's ORDER-BY: one term as a type, and everything that reads one.
  ///
  /// # It rides the STORAGE and not the wire, which is where it used to sit
  ///
  /// Its content is mechanical from the stored columns and its lowering is pure SQL — no part of it
  /// is a wire fact — so it was only ever inside the `graphql(…)` block's emission because that is
  /// where the type happened to be declared. A record with no wire face therefore had no term type
  /// to name and could not implement `SqlOrdering`, which cost it `.order(…)` and every page: it
  /// kept `get`, the unordered lanes and the ceiling, and that was the whole of the gap. Emitted
  /// beside the comparison, the gap closes — a PERSIST-ONLY record pages.
  ///
  /// Nothing about the wire changes with it. No backend derive was ever written on this type — the
  /// `OneofObject` derive is the backend's and is added where a schema is assembled — so what moved
  /// is a plain Rust enum and its inherent methods.
  ///
  /// # What each half is gated on
  ///
  /// The TYPE and the per-database resolvers exist wherever a record is stored at all. The PAGE
  /// vocabulary — the identity, the per-database term and the id tail — and the lowering below ride
  /// one further law: a written order can be COMPLETED only where the id is stored, and only the SQL
  /// family has a clause machine to render it. A record missing either keeps the resolver and the
  /// direction and gets nothing else, because there is nothing a page could do with them.
  pub(super) fn ordering(&self) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
    if self.persist.is_none() {
      return Default::default();
    }
    let vis = &self.vis;
    let record = &self.record;
    let stored = self.stored_columns();
    // ---- the order-by, ONE TERM: a column and the direction it runs in ------------------------
    // A variant per orderable field — that is, per `persist` field — each CARRYING the direction,
    // so one value is one whole ordering term. A query orders by a LIST of these, and the list is
    // ordered by the GraphQL specification where an input object's fields are not: `ORDER BY a, b`
    // is not `ORDER BY b, a`, so the sequence has to be carried by the one structure the spec calls
    // ordered.
    //
    // Two parallel lists — `orderBy: [a, b], orderDirection: [desc]` — is the shape this replaces,
    // and the pairing is why: nothing in a type system makes two lists the same length, so a
    // mismatch is silently completed rather than refused. Here a column and its direction are ONE
    // value and there is no index to line up.
    //
    // The SHAPE IS async-graphql's `OneofObject`, measured rather than assumed: that derive takes
    // an ENUM of single-value tuple variants and renders `input <E>OrderBy @oneOf { … }` with one
    // nullable field per variant, and its "exactly one field" is enforced by the
    // `arguments_of_correct_type` VALIDATION rule — a request setting two fields, or none, is
    // refused before any resolver runs, through a literal and through a variable alike. The derive
    // itself is the backend's, so it is not emitted here (see the module note); what is emitted is
    // the shape it takes, which is what makes the ruled SDL reachable at all. A struct with one
    // `Option<OrderDirection>` field per column — the obvious reading of that SDL — is NOT that
    // shape: the derive refuses it outright with `InputObject can only be applied to an enum.`
    let order_by = self.order_by.safe();
    let direction_ty = self.framework(&["graphql"], "OrderDirection");
    let ordered_columns = self.ordered_columns();
    let order_rows: ::std::vec::Vec<crate::unit::OrderColumn> = ordered_columns
      .iter()
      .map(|(_, column)| {
        crate::unit::OrderColumn::of(&column.source, format!("`{}` column", column.name))
          .with_gate(self.gate(&column.source))
      })
      .collect();
    let order_header = crate::unit::UnitHeader {
      vis,
      name: order_by.clone(),
      subject: format!("[`{record}`]"),
      note: None,
    };
    let (declaration, direction) = crate::unit::order_by(&order_header, &direction_ty, &order_rows);
    // An order-by variant RESOLVES to a column name per database, because `<db>(rename)` may
    // make them differ. One method per declared database, so the resolution is total and typed.
    //
    // `FieldName` and not `&'static str`, because what comes back is an IDENTIFIER and the builder's
    // ordering seam quotes what it is handed. `&str` on that same builder is the EXPRESSION slot,
    // which legitimately takes `*` and `count(*)` — so the two spellings are the two roles, and a
    // resolver answering in the wrong one hands a name to a position that will not quote it.
    let order_column = self.framework(&["field"], "FieldName");
    let not_stored = self.framework(&["query"], "ColumnNotStored");
    let term_name = self.framework(&["cursor"], "TermName");
    let resolvers = self.persist.iter().flat_map(|persist| &persist.backends).map(|database: &DatabaseBackend| {
      let method = database.kind().order_resolver();
      // The VARIANT is the RECORD FIELD's and the NAME is this database's, looked up by SOURCE:
      // `<db>(rename)` is what moves the name, and taking it from another database's list would
      // answer with that database's rename.
      //
      // The variant used to come off the FIRST declared database's column list, which was consistent
      // across backends and still wrong: it made the vocabulary a storage fact, and the `OneofObject`
      // derive renders a variant as a schema key, so the rename reached a client's document.
      //
      // A variant this database has NO COLUMN for is a real state now, because the vocabulary is the
      // DECLARATION's: the schema publishes every declared column's word wherever the service runs,
      // and which of them this deployment's database stores is a runtime fact. So the answer is
      // fallible, and the refusal names the column and the dialect rather than handing back a name
      // that would render into a statement the engine answers with `no such column`.
      let kind = database.kind().as_str();
      let arms = ordered_columns.iter().map(|(_, column)| {
        let variant = column.order_variant();
        let gate = self.gate(&column.source);
        let answer = match database.stores(&column.source) {
          Some(mine) => {
            let name = mine.name.to_string();
            quote!(::core::result::Result::Ok(#order_column::new(#name)))
          }
          None => {
            let identity = RustSafeName::from_ident(&column.source).external().to_owned();
            quote! {
              ::core::result::Result::Err(#not_stored::new(#term_name::new(#identity), #kind))
            }
          }
        };
        quote!(#gate Self::#variant(_) => #answer,)
      });
      let doc = super::leading(&format!(
        "The column this orders by IN {kind} — a plain name, quoted by the backend that renders it, which `persist({kind}(rename))` may make differ from another database's.\n\n# Errors\n\n`ColumnNotStored` where the declaration narrowed this term's column out of `{kind}`: the word is in the schema because the schema states the declaration's truth, and this deployment's database is what has not got the column."
      ));
      quote! {
        #[doc = #doc]
        #[inline]
        #vis const fn #method(
          self,
        ) -> ::core::result::Result<&'static #order_column, #not_stored> {
          match self {
            #(#arms)*
          }
        }
      }
    });
    // The other half of a term, and the half that is the SAME at every database: a direction is not
    // a storage fact, so there is one method rather than one per backend. Which is also why it is
    // separate from the resolvers above — pairing them into a per-database tuple would write the
    // per-database match twice, or the direction's arms N times, to say something no database
    // refines.
    //
    // The lowering asks BOTH of one value. That is what keeps the pairing structural on this side
    // of the wire too: `self` is one term, so its column and its direction cannot come from
    // different entries of the list unless a caller writes two receivers to make it so.
    //
    // An or-pattern rather than an arm per variant, because every arm's body is the binding and
    // nothing else. The empty case is the record that stores no column at all: the enum is
    // uninhabited there and the empty `match` is what a value of it can be taken apart into.
    // The SEMANTIC IDENTITY, and the one input a cursor's SIGNATURE takes from a term. It is the
    // RECORD FIELD's own name — the name `<db>(rename)` renames FROM — so a cursor minted
    // against one deployment's dialect is the same order's on the next: a rendered name would SPLIT
    // one order apart the moment either database renamed a column, and could ALIAS two orders
    // together where two renames crossed.
    //
    // It is no longer the ONLY name a rename cannot move — the variant is one too, now that it is
    // built from the same field — and that is a strengthening rather than a redundancy. What this
    // still answers is what a variant cannot: a VALUE a decoder generic over the term type can ask
    // for, fold into a signature and compare, where a variant is a type-level thing each record
    // spells for itself.
    //
    // One method rather than one per database, for the reason `direction` is one: an identity is
    // what storage cannot move, so no database refines it.
    // The page vocabulary rides the SAME law the ordering lowering does: it exists where a written
    // order can be COMPLETED, which needs the id stored, and where the clause machine that renders
    // it exists, which is the SQL family's. A record neither of those holds for keeps the resolver
    // and the direction and gets no term, no identity and no tail — there is nothing a page could
    // do with them.
    //
    // The stored half of that gate cannot fire on the MANDATED path — a framework-emitted table
    // stores its id by construction, which is what makes it the primary key — so what it guards is
    // the CAPABILITY: a user-declared physical layout whose id no `persist(…)` block names.
    let paged = self.id_column_stored().is_some()
      && self
        .persist
        .iter()
        .flat_map(|persist| &persist.backends)
        .any(|backend| backend.kind().is_sql());
    let identity = paged.then(|| crate::unit::order_identity(vis, &term_name, &order_rows));
    // THE SAME identity, as the wire's decode reads it: a PATH rather than one name, and answered
    // through a trait so a decoder generic over the term type can ask.
    //
    // The arms are built from the same `RustSafeName` expression the identities above are, in the
    // same walk, so the two cannot drift into naming different columns. What differs is the SHAPE
    // and the GATE. The shape is a path because `cover.title` and `title` are two subjects and so
    // are `cover.title` and `cover.duration` — every emitted term is one segment today, and the
    // path is what keeps the day a term reaches through a relation from being a change to the
    // uniqueness rule. The gate is none: `identity` is the PAGE's, which needs the id stored and a
    // SQL clause machine to render, where a wire order is every order-capable record's — a
    // mongo-only declaration has a decode to serve too.
    //
    // A `const` ITEM per arm, and not an inline `const { … }` block: the block does not make the
    // borrow inside it `'static` either, so both spellings without an item are `E0716`. Measured
    // both ways before this was written.
    let to_subject_path = self.framework(&["graphql"], "ToSubjectPath");
    let subject_path = self.framework(&["graphql"], "SubjectPath");
    // `match *self` rather than `match self`, and the EMPTY case is what forces it: the trait takes
    // `&self`, a reference is always considered INHABITED, and an empty match on one is `E0004`
    // even where the enum has no variant to write an arm for. Dereferencing puts the match back on
    // the uninhabited place, where the empty one is exactly right. The populated arm follows the
    // same spelling rather than the reverse, so a record storing one column and a record storing
    // none read alike; no arm binds, so nothing moves out of the borrow.
    let subject = crate::unit::order_subject_path(
      order_by,
      &to_subject_path,
      &subject_path,
      &term_name,
      &order_rows,
    );
    // The whole of a term as the page machinery reads one: the identity above, the column THIS
    // database spells, the direction the client wrote, and whether the column can hold `NULL`.
    //
    // Nullability is DECLARED here rather than inferred from a cursor's value, and the difference is
    // a wrong page: a nullable column whose boundary value happens to be present still needs the
    // null-admitting arm of its comparison, because the rows on the other side of the boundary may
    // hold `NULL` where the cursor's row did not.
    //
    // The WIDTH of each term's column and the SEQUENCE those columns mean, both the type's own
    // answer and neither the emitter's: a composite column contributes one `ORDER BY` entry per
    // column and one row-value comparison in the keyset, and `at: Timestamp` and `title: String` are
    // the same tokens here. So every term over a value is written `spanning` with
    // `<T as ColumnKind>::SEGMENTS` and `::ORDER`, and a scalar lands back on the one-column answer
    // in the declaration order, which is `shape()`'s arrangement carried to the ordering seam.
    //
    // What the SEQUENCE buys downstream is `OrderTerm::levels`: a term whose type states one is
    // expanded by the framework into one ordinary term per level. That expansion is deliberately not
    // written here — an emission states a column's facts, and how many terms an order runs as is one
    // fact of the framework's, held in one place rather than in every emitted lowering.
    let column_kind = self.framework(&["column"], "ColumnKind");
    let order_term = self.framework(&["cursor"], "OrderTerm");
    let terms = self
      .persist
      .iter()
      .filter(|_| paged)
      .flat_map(|persist| &persist.backends)
      .filter(|backend| backend.kind().is_sql())
      .map(|backend: &DatabaseBackend| {
        let method = backend.kind().order_term();
        let kind = backend.kind().as_str();
        let arms = ordered_columns.iter().map(|(_, column)| {
          let variant = column.order_variant();
          let identity = RustSafeName::from_ident(&column.source).external().to_owned();
          let gate = self.gate(&column.source);
          // THIS DATABASE's entry, looked up by SOURCE — and a column this database has not got is
          // now a real state, the vocabulary being the DECLARATION's rather than the intersection.
          // Such a term carries the ABSENT subject, which is the storage fact a per-database term
          // exists to carry: `SqlOrder::new` and `MongoOrder::new` refuse an order holding one BY
          // NAME, before a row is read, rather than the statement naming a column no table has.
          //
          // The rendered name is the one the databases that DO store it use, there being no other:
          // it reaches no statement, and what a client is told names the term rather than a column.
          let Some(per_db) = backend.stores(&column.source) else {
            let name = column.name.to_string();
            return quote! {
              #gate
              Self::#variant(direction) => #order_term::absent(
                #term_name::new(#identity),
                #order_column::new(#name),
                direction,
                #kind,
              ),
            };
          };
          let name = per_db.name.to_string();
          // WHICH constructor is the term's SUBJECT in this database, and the fork is the storage
          // form rather than the type: a collection kept in a column of the row is an array a
          // backend may or may not order the framework's way, and one kept in a table of its own is
          // no column of this row at all. `edge_stored` is the single authority on which — the same
          // one the read plan, the write plan and the DDL each read — so an order-by term and the
          // table a write fills cannot disagree about where a collection lives.
          //
          // A collection has no NULL state, so the nullable arm is a scalar's alone and there is no
          // pair to reconcile. It has no WIDTH to state either, which is why the subject fork sits
          // OUTSIDE the width one rather than beside it: `impl<T> ColumnKind for Vec<T>` is one
          // column whatever it holds, so the collection constructors take no segments and the two
          // axes never both leave their default on a single term.
          let build = if self.collects(&column.source) {
            // THREE subjects, and the third is the `sortable` word's: a collection this database
            // keeps in a table of its own AND mirrors into an order-preserving companion column
            // beside the row. It is the ONE term whose rendered name is not the column's — the
            // statement orders by the companion — while the identity stays the field's, so a client's
            // written order fingerprints alike whichever storage form answered it.
            let mirrored = backend.mirrors(self, per_db);
            let subject = match (backend.edge_stored(self, per_db), mirrored) {
              (true, true) => quote!(#order_term::shadow),
              (true, false) => quote!(#order_term::edge),
              (false, _) => quote!(#order_term::array),
            };
            let rendered = if mirrored {
              backend.sort_column(self, per_db)
            } else {
              name.clone()
            };
            quote! {
              #subject(
                #term_name::new(#identity),
                #order_column::new(#rendered),
                direction,
              )
            }
          } else {
            let ty = per_db.ty();
            let width = if per_db.nullable {
              quote!(#order_term::spanning_nullable)
            } else {
              quote!(#order_term::spanning)
            };
            // The SEQUENCE beside the segments, written at every term for the segments' own reason:
            // `at: MediaTimestamp` and `title: String` are the same tokens, so a macro asked which
            // types mean their columns in a different order would be guessing. It writes one
            // spelling and the compiler selects — a scalar and a composite that means its columns as
            // declared both answer `&[]`, and a term over either is what it always was.
            quote! {
              #width(
                #term_name::new(#identity),
                #order_column::new(#name),
                <#ty as #column_kind>::SEGMENTS,
                <#ty as #column_kind>::ORDER,
                direction,
              )
            }
          };
          quote! {
            #gate
            Self::#variant(direction) => #build,
          }
        });
        let body = if ordered_columns.is_empty() {
          quote!(match self {})
        } else {
          quote! {
            match self {
              #(#arms)*
            }
          }
        };
        let doc = super::leading(&format!(
          "This term as a page renders it IN {} — its rename-proof identity, this database's column \
           name, the direction it runs in, and whether that column can hold `NULL`.",
          backend.kind().as_str()
        ));
        quote! {
          #[doc = #doc]
          #[inline]
          #vis const fn #method(self) -> #order_term {
            #body
          }
        }
      });
    // The id TAIL, as a value rather than as a rendering — which is what lets a PAGE spend the same
    // law the ordering lowering does. `<db>_order_by` pushes the tail straight into a builder, which
    // is right for an ordered query that is not paged and useless to one that is: a page needs the
    // completed order as VALUES, because the `ORDER BY`, the keyset `WHERE` and the cursor are three
    // readings of it.
    //
    // ONE term, because one column is what an order needs to be total: the id is UNIQUE, so no two
    // rows tie on it and nothing after it could reorder anything. No database refines it — which
    // column is the id is the RECORD's — and the dedupe matches on the VARIANT, which is the record
    // field's own name, so no rename can fool it. That is true by construction now rather than
    // through the identity beside it.
    let complete = self.id_column_stored().filter(|_| paged).map(|at| {
      let variant = stored[at].order_variant();
      let tail = quote! {
        if !::core::iter::Iterator::any(&mut written.iter(), |__ingraph_term| {
          ::core::matches!(__ingraph_term, Self::#variant(_))
        }) {
          ::std::vec::Vec::push(&mut order, Self::#variant(#direction_ty::Asc));
        }
      };
      let doc = super::leading(
        "This order completed into a TOTAL one: the written terms, then the id ascending where none \
         of them named it. A term that already named the id moves it rather than repeating it, and \
         the tail is what a keyset cursor pages without skipping or repeating a row.",
      );
      quote! {
        #[doc = #doc]
        #[must_use]
        #vis fn complete(written: &[Self]) -> ::std::vec::Vec<Self> {
          let mut order = ::std::vec::Vec::from(written);
          #tail
          order
        }
      }
    });
    let lowerings = self.orderings(&order_column);
    let methods = quote! {
      impl #order_by {
        #(#resolvers)*
        #direction
        #identity
        #(#terms)*
        #complete
        #(#lowerings)*
      }

      #subject
    };
    (declaration, methods)
  }

  /// The ordering LOWERING, one per SQL database: the terms a query wrote, and then the id.
  ///
  /// # A WRITTEN order ends with the id
  ///
  /// It is load-bearing rather than tidy. A keyset cursor is `(sort values…, id)`, because sort
  /// values REPEAT — a cursor that cannot break the tie skips or repeats rows at the page boundary,
  /// which is a wrong answer with no error anywhere. So the tail is not an option a caller passes
  /// and can leave out: it is written into the walk, and the requested terms are the only part a
  /// client decides. Completing a client's OWN order into a total one is what makes that client's
  /// page correct.
  ///
  /// ONE column ends it, and the id is the one that can: a framework-emitted table's id is UNIQUE,
  /// so no two rows tie on it and an order ending there is total. The lineage columns are stored
  /// beside it and a client may still write a term over one — they are ordinary columns now, not a
  /// tail the walk appends.
  ///
  /// # There is no default order, and no way to ask this for one
  ///
  /// A query that writes no term gets no `ORDER BY` at all: SQL's own unordered semantics is the
  /// answer, and a sort nobody asked for is work every row pays for. The SIGNATURE is where that
  /// is said — the first term is a parameter of its own and the rest are a slice, so "ordered by
  /// nothing" has no spelling here, and a caller holding no term never calls this and leaves the
  /// statement in its un-ordered state. `FROM → ORDER BY` is the edge such a query simply does not
  /// take.
  ///
  /// That is also the whole of why no `#[orderby(default)]` attribute exists to write or to forget.
  /// polarsync requires exactly one such variant and errors when a declaration omits it; here there
  /// is no default for a declaration to name.
  ///
  /// A PAGE is what then requires a written order — a cursor over an unordered set compares nothing
  /// — and that enforcement belongs to the query layer that owns paging, not to this lowering.
  ///
  /// # A requested term naming the id DEDUPES it, and that was measured
  ///
  /// The tail drops the column a requested term already named. Both halves of the choice were
  /// checked rather than argued:
  ///
  /// - **It changes no result set.** Within a tie group of an earlier term the repeated column is
  ///   CONSTANT, so a later term over it can reorder nothing — whichever direction either runs in.
  ///   Measured on SQLite: `ORDER BY "id" DESC, "media_id" ASC, "id" ASC` and the same order without
  ///   the third term return the identical row sequence.
  /// - **It is not free to leave in.** SQLite folds no duplicate: `EXPLAIN` shows the sorter key
  ///   widen from `k(2,-B,B)` to `k(3,-B,B,B)`, one extra `Column` opcode per row, and a sorter
  ///   record one field wider. An adjacent exact duplicate is not folded either. So the redundant
  ///   term costs per-row work in the one dialect that could most cheaply have optimised it away.
  ///
  /// TOTALITY survives the dedupe, which is the property that had to: the id leaves the tail only
  /// when the order already contains it, so it appears exactly once either way and the order is
  /// still unique. The DIRECTION it appears in does not enter that argument — a permutation of a
  /// unique tuple is still unique.
  ///
  /// The test is the VARIANT rather than the rendered name: a variant is the RECORD FIELD's name,
  /// where the rendered one is what `<db>(rename)` moves, so matching on the variant cannot
  /// be fooled by a rename and needs no string comparison. The variant used to be built from a
  /// column name too — consistently, from the first declared database — so this held by arithmetic
  /// rather than by meaning; it holds by meaning now.
  ///
  /// # The tail runs ASCENDING whatever the terms do
  ///
  /// The design rules the wire face and the law, and says nothing about the tail's direction. It is
  /// fixed rather than following the last term because the tail is the CURSOR's spine and not a user
  /// preference: a client asked for an ordering over the columns it named, and the id is what makes
  /// that ordering pageable. Following the last term would make the cursor's own comparison depend
  /// on a term the client may not send twice running.
  ///
  /// # Why here, and why not on the comparison
  ///
  /// An associated function on the order-by, beside the two accessors it consumes. Not a method on
  /// the `*Comparison`: ordering is not a predicate, and `FROM → ORDER BY` is an edge in the clause
  /// machine precisely so that a statement can be ordered without being filtered — a lowering
  /// reached through a comparison would need one to exist before a query could be ordered at all.
  ///
  /// SQL only. The clause machine is the SQL family's, and how a mongo `find` takes a sort is
  /// unsettled in the design — an ordered BSON document rather than a clause — so a database whose
  /// kind is not SQL gets the resolver it already had and no walk.
  ///
  /// # The dialect stays a parameter
  ///
  /// The method NAME picks which column names are rendered; the dialect that brackets them is a
  /// type parameter, exactly as it is on an emitted `<Row>Comparison<DB>`. That keeps a declaration
  /// storing one dialect from needing that dialect's feature to COMPILE, and it is what lets a test
  /// render one database's names through another's driver.
  fn orderings(&self, order_column: &proc_macro2::TokenStream) -> Vec<proc_macro2::TokenStream> {
    // Cannot fire on the MANDATED path — a framework-emitted table stores its id by construction,
    // which is what makes it the primary key — so this is the refusal a user-declared physical
    // layout gets when the column its rows are addressed by is in no `persist(…)` block.
    let Some(id_at) = self.id_column_stored() else {
      return Vec::new();
    };
    let stored = self.stored_columns();
    let vis = &self.vis;
    let builder = self.framework(&["comparison", "sql"], "QueryBuilder");
    let ordered = self.framework(&["comparison", "sql"], "OrderByClause");
    let transition = self.framework(&["comparison", "sql"], "ClauseTransition");
    let quoting = self.framework(&["comparison", "sql"], "QuoteIdent");
    let database = self.framework(&["sqlx"], "Database");
    let held = self.framework(&["sqlx"], "QueryBuilder");
    let not_stored = self.framework(&["query"], "ColumnNotStored");
    let clause = super::parameter("CLAUSE");
    let db = super::parameter("DB");
    let holder = super::parameter("HOLDER");
    let address = &stored[id_at].source;

    self
      .persist
      .iter()
      .flat_map(|persist| &persist.backends)
      .filter(|backend| backend.kind().is_sql())
      .map(|backend: &DatabaseBackend| {
        let method = backend.kind().order_lowering();
        let resolver = backend.kind().order_resolver();
        // By SOURCE, and the `expect` is a LAW rather than a hope: an address step may not be
        // narrowed out of any database — identity is unskippable, and a store that narrowed one
        // addresses nothing — so `ingraph-derive` refuses both narrowing spellings on it at the
        // word. That is what keeps the declaration-truth vocabulary from ever putting a runtime
        // refusal on a PAGE's own tail.
        let column = backend
          .stores(address)
          .expect("an address step is a column of every database the record declares")
          .name
          .to_string();
        let variant = stored[id_at].order_variant();

        // Both halves of the split are searched, because either can be the term that named the id:
        // the first is one value rather than a slice, so the dedupe asks it separately and then
        // asks the rest.
        let tail = quote! {
          if !::core::iter::once(__ingraph_first)
            .chain(__ingraph_rest)
            .any(|__ingraph_term| ::core::matches!(__ingraph_term, Self::#variant(_)))
          {
            __ingraph_builder =
              __ingraph_builder.order_by(#order_column::new(#column), false);
          }
        };

        let doc = super::leading(&format!(
          "Order a statement by this term and the ones after it IN {kind}, and then by the id — \
           the requested columns followed by `{column}` ascending, which is what a keyset cursor \
           pages without skipping or repeating a row. A term naming the id moves it rather than \
           repeating it. A query that wrote no term does not call this at all: it gets no \
           `ORDER BY`, which is the answer SQL already has for an unordered query.\n\n# Errors\n\n\
           `ColumnNotStored` where a term names a column the declaration narrowed out of `{kind}`. \
           The word is in the schema because the schema states the declaration's truth; this \
           deployment's database is what has not got the column, and the refusal names both. \
           *A refusal leaves the accumulator exactly as it was found* does NOT hold here — the \
           builder is taken by value and a refused order returns none of it.",
          kind = backend.kind().as_str(),
        ));
        quote! {
          #[doc = #doc]
          #vis fn #method<#clause, #db, #holder>(
            __ingraph_first: &Self,
            __ingraph_rest: &[Self],
            __ingraph_builder: #builder<#clause, #db, #holder>,
          ) -> ::core::result::Result<#builder<#ordered, #db, #holder>, #not_stored>
          where
            #clause: #transition<#ordered>,
            #db: #database + #quoting,
            #holder: ::core::borrow::BorrowMut<#held<#db>>,
          {
            let mut __ingraph_builder = __ingraph_builder.order_by(
              __ingraph_first.#resolver()?,
              __ingraph_first.direction().is_descending(),
            );
            for __ingraph_term in __ingraph_rest {
              __ingraph_builder = __ingraph_builder.order_by(
                __ingraph_term.#resolver()?,
                __ingraph_term.direction().is_descending(),
              );
            }
            #tail
            ::core::result::Result::Ok(__ingraph_builder)
          }
        }
      })
      .collect()
  }
}

/// ONE stored column, as everything downstream of `<E>Filter` reads it.
///
/// Three readers and one walk, which is the whole reason the row exists: the FILTER STRUCT takes the
/// member and the filter, its WIRE FACE takes the member, the declared name and the filter, the
/// CROSSING takes the member and the filter, and the LINEAGE leg takes the member, the declared name
/// and the type the filter's operands are held at. A filter asked for twice is a filter two answers
/// can disagree about, and between those two there is no conversion — the same argument
/// [`super::filter_of`] is one function for.
pub(super) struct FilterRow {
  /// The Rust member — layer 1, the field's own name, which no word moves.
  pub(super) member: syn::Ident,
  /// What a doc sentence calls this column — the name the FIRST database renders it under.
  pub(super) column: String,
  /// The name a client writes this field under, as DECLARED — before [`super::wire::wire_field`]
  /// applies the fallback, which is a wire fact and belongs at the face.
  pub(super) declared: String,
  /// The type this column's OPERANDS are held at — the wire type where a field has one, the domain
  /// type where none was declared, and the same tokens [`filter`](Self::filter) was projected from.
  ///
  /// Read by the one leg that BUILDS a predicate rather than receiving one: an emitted lineage walk
  /// takes its operand as an argument and equates it, so it needs the type the filter's parameter is
  /// spelled at. The other three readers project it away and never name it.
  pub(super) wire: syn::Type,
  /// The filter this column is guarded by, already projected through the marker layer — WIDENED
  /// where the column is a `ref`, which is what the `<E>Filter`'s member and its wire face carry.
  pub(super) filter: proc_macro2::TokenStream,
  /// The column's OWN filter, before any widening: what a CROSSING converts, since the nested half
  /// of a widened one crosses through the target's row instead.
  ///
  /// Equal to [`filter`](Self::filter) for every column that references nothing, and carried beside
  /// it rather than re-derived at the crossing — one derivation, so the member's type and the type
  /// its operands cross from cannot come to disagree.
  pub(super) operators: proc_macro2::TokenStream,
}

/// ONE REVERSE relation position, as the two readers of `<E>Filter` see it.
///
/// A second row beside [`FilterRow`] rather than an eighth field on it, and the reason is that
/// nothing else about the two is alike: a stored column has a COLUMN name, a wire type its operands
/// are held at and a CROSSING, where a position has none of the three — it is not stored, it names
/// no column of this row, and its crossing is the reverse lowering rather than a column's.
///
/// Two readers, which is why the row exists at all: the FILTER STRUCT takes the member and the held
/// type, and its WIRE FACE takes the member, the name a client writes and the same held type. The
/// crossing does NOT read it — a relation member changes no emitted crossing, only a positional
/// constructor's arity, which is the measurement `emit::query`'s own note records.
pub(super) struct RelationRow {
  /// The Rust member — the position's own declared name, which is layer 1 here exactly as a field's
  /// name is for a column. `derived(clips = "…")` writes it, and no word moves it.
  pub(super) member: syn::Ident,
  /// The SOURCE as the declaration spelled it, for the doc sentence alone.
  pub(super) source: String,
  /// The SOURCE as a PATH — what the comparison names to reach the far side's row, comparison and
  /// referring columns. Beside the spelling rather than parsed back out of it: a path is what the
  /// declaration handed over, and re-parsing a string would be this emitter guessing at tokens it
  /// already has.
  pub(super) path: syn::Path,
  /// The DECLARED name of the referring field, as a `const` expression yielding a `&'static str`.
  ///
  /// Two shapes, one type. The full form's is the literal a declaration wrote; the SHORTHAND's is
  /// `<Source as Related<Me>>::COLUMNS[0].as_str()`, which is a `const` because every part of it is
  /// — the evidence const, the index, and the name's own `as_str`. Both are then the KEY
  /// `stored_column` is asked with, so the two forms reach the stored spelling by one road.
  ///
  /// The shorthand's index is sound because the shorthand's own audit is a `OneReference` bound: a
  /// source pointing back through two fields is refused before this is evaluated.
  pub(super) declared: proc_macro2::TokenStream,
  /// The quantifier vocabulary over the far side's filter, UNBOXED —
  /// `RelatedFilter<<Source as GraphqlInput>::Filter>`.
  ///
  /// Unboxed here and boxed at the STRUCT, because the box is the holder's: a record whose reverse
  /// position names its own kind would contain itself (`E0072`), and the wire face parses the
  /// unboxed type because a `Box` has no `InputType` row — the box is a Rust fact and not a schema
  /// one.
  pub(super) held: proc_macro2::TokenStream,
}

/// ONE FORWARD relation position — a `ref` column's nested half, as the COMPARISON and the CROSSING
/// see it.
///
/// A row of its own beside [`RelationRow`] rather than a variant of it, because the two are
/// different facts about different declarations: a reverse position is DECLARED and stored nowhere,
/// where this one is a stored COLUMN that happens to carry another row's id. What they share is
/// exactly the projection into the far side's predicate, and each spells its own.
///
/// It never reaches the WIRE face. A widened column publishes ONE field carrying [`RefFilter`]'s own
/// flat object, so the nested arm is inside a type the face already registers — which is the whole of
/// what *widens in place* means.
pub(super) struct ForwardRow {
  /// The comparison's member for the NESTED half — the column's own member with `_related` after it.
  ///
  /// A second member rather than a wider one, because the two halves lower at different arities: the
  /// column half is an ordinary predicate on the foreign key and the nested half is a semi-join
  /// through it, and a record's lowering conjoins them exactly as it conjoins two columns.
  ///
  /// The suffix can collide with a real column called `<name>_related`, and that collision is a
  /// duplicate field inside the expansion rather than a refusal by name. It is the class
  /// `emit::relate`'s own note records for its artifacts: this crate takes a rule when something live
  /// wants one.
  pub(super) position: syn::Ident,
  /// The COLUMN's member — what the wire field is read off, and the name the nested half is framed
  /// under, since a semi-join renders at the FOREIGN KEY's address.
  pub(super) column: syn::Ident,
  /// The target as a PATH — what the comparison names to reach the far side's row and predicate.
  pub(super) target: syn::Path,
  /// The target as the declaration spelled it, for a doc sentence alone.
  pub(super) spelling: String,
  /// The widened filter this position's half is read out of — `RefFilter<…, …>`, the same tokens the
  /// `<E>Filter`'s member carries, so the crossing lands on the type the struct really holds.
  pub(super) held: proc_macro2::TokenStream,
}

/// The predicate a client sends against `target` — `<<T as Graphql>::Input as GraphqlInput>::Filter`.
///
/// THROUGH the face rather than off the record: `GraphqlInput` is implemented by the ARGUMENT OBJECT
/// and the record binds it as `Graphql::Input`, so a neighbour's filter is two projections away. One
/// function because both directions take the same chain — a reverse position to its SOURCE's filter,
/// a forward one to its TARGET's — and two spellings of one chain are two that could drift.
fn target_filter(model: &RecordModel, target: &syn::Path) -> proc_macro2::TokenStream {
  let face = model.framework(&["transform"], "Graphql");
  let input = model.framework(&["transform"], "GraphqlInput");
  quote!(<<#target as #face>::Input as #input>::Filter)
}

impl Graphql {
  /// Every REVERSE relation position this record declares, as the `<E>Filter` and its wire face read
  /// them.
  ///
  /// # Only the REVERSE half, and the forward one is not an omission
  ///
  /// A `ref` field is already a filterable column — `coverId: { eq: 3 }` asks the foreign key — and
  /// the NESTED position beside it would be a second field of the same face asking the target's own
  /// predicate. What that field is CALLED is the open end: `ref(type = "…")` is the whole of the
  /// forward grammar, so a declaration writes no name for the position, and deriving one off the
  /// column (`cover_id` → `cover`) would be this emitter guessing a client-visible word — the move
  /// it refuses everywhere else, and the one `default_row_name` exists to say is unavailable.
  ///
  /// A reverse position has no such gap: `derived(<name> = "…")` IS a name, and
  /// [`Derived::name`](crate::model::Derived::name)'s own doc says it is the one a wire face exposes
  /// the position under.
  pub(super) fn relation_rows(&self, model: &RecordModel) -> Vec<RelationRow> {
    let related = model.framework(&["graphql"], "RelatedFilter");
    let related_evidence = model.framework(&["transform"], "Related");
    let record = &model.record;
    model
      .derived
      .iter()
      .map(|entry| {
        let source = &entry.source;
        // The full form NAMES the field and the shorthand asks the evidence which one it is. Both
        // answer a `&'static str` in a `const`, which is what `stored_column`'s key has to be.
        let declared = entry.field.as_ref().map_or_else(
          || quote!(<#source as #related_evidence<#record>>::COLUMNS[0].as_str()),
          |field| quote!(#field),
        );
        let filter = target_filter(model, source);
        RelationRow {
          member: entry.name.clone(),
          source: quote!(#source).to_string().replace(' ', ""),
          path: source.clone(),
          declared,
          held: quote!(#related<#filter>),
        }
      })
      .collect()
  }

  /// The same positions as [`crate::unit::FilterColumn`]s — what the filter unit splices, with the
  /// box the struct owes put on.
  ///
  /// Here rather than at the caller so that the STRUCT's member type and the wire face's parse are
  /// one derivation apart rather than two spellings: the face unboxes exactly what this boxes.
  pub(super) fn relation_columns(&self, model: &RecordModel) -> Vec<crate::unit::FilterColumn> {
    self
      .relation_rows(model)
      .into_iter()
      .map(|row| {
        let held = &row.held;
        crate::unit::FilterColumn {
          name: format!("`{}` reverse position (`{}`)", row.member, row.source),
          filter: quote!(::std::boxed::Box<#held>),
          member: row.member,
          // A REVERSE POSITION is no field of this declaration, so there is no condition to carry:
          // what a `#[cfg]` on the CHILD's own field removes is a column of the child's face.
          gate: proc_macro2::TokenStream::new(),
        }
      })
      .collect()
  }

  /// Every stored column as a [`FilterRow`] — the ONE walk `<E>Filter`, its wire face and its
  /// crossing all read.
  ///
  /// Empty where the record stores nothing, which is the state the two faces and the crossing each
  /// refuse for their own reason: an input object with no fields is not a GraphQL type, and a
  /// predicate over no columns is a predicate nothing can narrow.
  pub(super) fn filter_rows(&self, model: &RecordModel) -> Vec<FilterRow> {
    let Some(backend) = self.backends.first() else {
      return Vec::new();
    };
    model
      .queried_columns()
      .into_iter()
      .map(|(_, column)| {
        let (member, declared, ty) = backend.filter_field(column);
        let column_filter = filter_of(model, &ty, model.marker_of(&column.source));
        FilterRow {
          member,
          column: column.name.to_string(),
          declared,
          filter: match model.reference_of(&column.source) {
            Some(reference) => self.widened(model, &column_filter, reference),
            None => column_filter.clone(),
          },
          operators: column_filter,
          wire: ty,
        }
      })
      .collect()
  }

  /// A `ref` column's filter, WIDENED: the column's own operators and the predicate over the row it
  /// points at, in one flat input object.
  ///
  /// ```text
  /// RefFilter<<column's filter>, <<Target as Graphql>::Input as GraphqlInput>::Filter>
  /// ```
  ///
  /// # The nested half is named by PROJECTION, never by a string
  ///
  /// The declaration wrote a TYPE — `ref = "media::Keyframe"` — and the chain finds that type's own
  /// published filter, which is the same chain a REVERSE position takes to the source's. So a target
  /// that renames its wire face moves both ends at once, and a target with no `graphql(…)` block has
  /// no `Graphql` impl at all: `E0277` at the `ref` that named it, which is the tooth every other
  /// projection here has.
  ///
  /// # It WIDENS in place rather than standing beside the column
  ///
  /// `coverId` keeps its name and its object grows one arm, so every spelling a client already sends
  /// keeps working and no second wire field is minted. The arm is ADDITIVE — `{ in: […], related: {…}
  /// }` is a real question — and the shorthand laws are untouched beside it: a bare value is still
  /// the column's `eq`, and an explicit null is still the null test one wrapper out.
  ///
  /// The BOX is inside [`RefFilter`], not written here: a wrapper every `ref` column shares is where
  /// the recursion is cut once rather than per target.
  fn widened(
    &self,
    model: &RecordModel,
    column: &proc_macro2::TokenStream,
    reference: &Reference,
  ) -> proc_macro2::TokenStream {
    let widened = model.framework(&["graphql"], "RefFilter");
    let nested = target_filter(model, &reference.target);
    quote!(#widened<#column, #nested>)
  }

  /// Every `ref` COLUMN as a FORWARD relation position — the second half of a widened filter, as the
  /// comparison and the crossing read it.
  ///
  /// # It rides the STORED columns, because a reference IS one
  ///
  /// A reverse position is declared (`derived(<name> = "…")`) and stored nowhere; a forward one is a
  /// column of this row that happens to carry another row's id. So the walk is the stored list rather
  /// than the `derived` list, and the row it yields carries the column's own member beside the
  /// position's — one wire field, two predicates.
  ///
  /// # Only where this record has a wire FACE
  ///
  /// The member exists to receive the `related` arm a client wrote, and a record with no `<E>Filter`
  /// has no arm to receive. This walk is [`Graphql`]'s own, so the condition is the placement rather
  /// than a check — the same one [`Self::relation_rows`] takes.
  pub(super) fn forward_rows(&self, model: &RecordModel) -> Vec<ForwardRow> {
    let Some(backend) = self.backends.first() else {
      return Vec::new();
    };
    model
      .queried_columns()
      .into_iter()
      .filter_map(|(_, column)| {
        let reference = model.reference_of(&column.source)?;
        let (member, _, ty) = backend.filter_field(column);
        let held = self.widened(
          model,
          &filter_of(model, &ty, model.marker_of(&column.source)),
          reference,
        );
        let target = &reference.target;
        Some(ForwardRow {
          position: format_ident!("{member}_related"),
          column: member,
          spelling: quote!(#target).to_string().replace(' ', ""),
          target: target.clone(),
          held,
        })
      })
      .collect()
  }

  /// The whole wire face: four types, one of each per RECORD.
  ///
  /// | type | authored | why it exists |
  /// |---|---|---|
  /// | `<E>GraphqlInput` | MECHANICAL from the engine's find surface | what a client SENDS: the filter, the order, the page |
  /// | `<E>GraphqlOutput` | the address MECHANICALLY, the rest per field | what a client RECEIVES |
  /// | `<E>KeyOutput` | MECHANICAL from the key's columns | a hit IS a `Scored` over `K`, and the search envelopes derive their wire shape from it |
  /// | `<E>Filter` | mechanical from the STORED columns | a field is filterable because it is stored |
  ///
  /// A fifth rides beside them CONDITIONALLY — the refusal a fallible crossing answers with, named
  /// after the output object so a rename moves both. See [`Self::refusal`].
  ///
  /// `<E>OrderBy` is not a wire type: its variants are the STORED columns and its lowering is pure
  /// SQL, so it is emitted beside the comparison — see [`RecordModel::ordering`] for what the
  /// placement cost while it stood here. Its NAME is still written inside the `graphql(…)` block,
  /// which is a fact about the grammar rather than about the type.
  ///
  /// One of each per record rather than per database: a client must never see a schema that varies
  /// with a deployment's storage choice. Their RESOLUTION is per database — the filter crosses into
  /// each `*Comparison`, and the output object is minted out of each row — and that crossing is the
  /// single place storage enters.
  ///
  /// # The two halves are the FACE's own types now, not carriers beside them
  ///
  /// `Graphql::Input` and `Graphql::Output` used to bind a `struct …(())` apiece, minted inside the
  /// record's anonymous const with the members named on them and nothing in them. Both have content
  /// now, so both are API and both are written here — see
  /// [`wire_binding`](RecordModel::wire_binding), which is what still binds them.
  pub(crate) fn faces(
    &self,
    model: &RecordModel,
  ) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
    let mut types = proc_macro2::TokenStream::new();
    let mut impls = proc_macro2::TokenStream::new();
    let Some(backend) = self.backends.first() else {
      return (types, impls);
    };
    let vis = &model.vis;
    let record = &model.record;

    // ---- the argument object, mechanical from the ENGINE's find surface -----------------------
    // First, because the input half is the face's first member and the emission's order is what
    // `RecordModel::emitted_types` enumerates.
    let (input_type, input_impl) = self.arguments(model);
    types.extend(input_type);

    // ---- the object -------------------------------------------------------------------------
    // The ADDRESS first and the declared fields after it. The id is what a client addresses a row
    // by — `get` takes it, it is `UNIQUE`, and it is the one member every output object has whatever
    // the declaration exposes — and the key is the whole ancestry the row is handed back UNDER, so a
    // hit reads its parents off the hit instead of paying a round trip for them. A field landing on
    // either Rust name is a refusal at the front end, where the field that collided can be named.
    //
    // The id's type is the DECLARATION's, carried through verbatim as every other emitted spelling
    // is: a declaration whose id is a `TypedId<Uuid, Video>` gets that on the wire, and one whose id
    // is a bare `u64` gets the `u64`. Wrapping it here would be the emitter inventing a type the
    // declaration did not write — and would break the `refers_to` equation every `ref` at this
    // record instantiates.
    //
    // A `ref` field needs nothing of its own. It already CARRIES the target's id, which is what
    // `refers_to` holds it to, so exposing one gives a member of the target's id type by
    // construction. A nested OBJECT is a resolver's answer and not a column's, so nothing here mints
    // one.
    let output_ty = self.output.safe();
    let key_output = self.key_output.safe();
    let id_ty = &model.key.id.ty;
    let writes_id = model.wire_writes_id();
    let substrate = super::substrate();
    let id_member = writes_id.then(|| quote!(#substrate id: #id_ty,));
    // LAYER 1: the member is the field's DOMAIN name, and no word reaches it — see
    // [`GraphqlField::accessor`], where the three layers are tabled. The declaration's own words
    // land one layer out, on the accessor below and on the schema name the derive round will spend.
    let members = backend.fields().iter().map(|field| {
      let name = &field.source;
      let ty = field.wire_ty();
      let gate = model.gate(name);
      quote!(#gate #substrate #name: #ty,)
    });
    let doc = super::leading(&format!(
      "The wire face of a [`{record}`] — its id, its whole address, and every field the declaration \
       exposes."
    ));
    types.extend(quote! {
      #[doc = #doc]
      #[derive(::core::fmt::Debug, ::core::clone::Clone)]
      #vis struct #output_ty {
        #id_member
        #substrate key: #key_output,
        #(#members)*
      }
    });

    // ---- the key object, mechanical from the key's columns -----------------------------------
    let key_members = model.key.columns().map(|column| {
      let name = &column.name;
      let ty = &column.ty;
      quote!(#substrate #name: #ty,)
    });
    let doc = super::leading(&format!(
      "A [`{record}`]'s address, on the wire — what a search or knn hit renders into."
    ));
    types.extend(quote! {
      #[doc = #doc]
      #[derive(::core::fmt::Debug, ::core::clone::Clone)]
      #vis struct #key_output {
        #(#key_members)*
      }
    });

    // ---- the key ARGUMENT, over a compound key alone -----------------------------------------
    // See [`Self::key_input`]: a root's address crosses inward as its id and mints nothing, and
    // this is the type the other case needs. The `ToGraphqlInput` row that spends it is written in
    // the same call, so the two cannot be emitted apart.
    let (key_input_ty, key_input_impl) = self.key_input(model);
    types.extend(key_input_ty);

    // ---- the filter, mechanical from the STORED columns --------------------------------------
    let filter = self.filter.safe();
    // Each field carries its type's FILTER, never its value. `Option<value>` expresses equality
    // ALONE, and on a nullable column it collapses three states — no predicate, `IS NULL`, `= v` —
    // into two, making a null match inexpressible. The framework carries the null test on a
    // `Nullable<F>` wrapper and registers `Option<T>` to it, where a bare `T` gets the plain filter
    // (`ingraph`'s `graphql::filter::nullable`), so nullability needs no detection here — and must
    // get NONE: the domain type is written verbatim, and normalising an `Option` away would hand a
    // nullable column the filter of a `NOT NULL` one, where `IS NULL` does not exist. Which is what
    // lets the macro stay type-blind, as it must.
    //
    // A field whose filter can name THIS record's filter needs `Option<Box<…::Filter>>`: unboxed,
    // the struct contains itself and is infinitely sized (E0072). Every column here is a scalar-ish
    // domain type, so the unboxed form is correct — the box is owed the moment a field's filter can
    // reach back.
    //
    // The REVERSE relation positions ride at the END of the same list. They are not stored columns
    // and the walk that finds them is a different one — see [`Self::relation_rows`] — but what the
    // filter unit takes is ROWS, so a position joins the face by being one rather than by the unit
    // learning a second shape. Their order is the declaration's, after every column, which is the
    // order the wire face registers them in too.
    let mut filter_rows: ::std::vec::Vec<crate::unit::FilterColumn> = self
      .filter_rows(model)
      .into_iter()
      .map(|row| crate::unit::FilterColumn {
        name: format!("`{}` column", row.column),
        filter: row.filter,
        gate: model.gate(&row.member),
        member: row.member,
      })
      .collect();
    filter_rows.extend(self.relation_columns(model));
    let filter_header = crate::unit::UnitHeader {
      vis,
      name: filter.clone(),
      subject: format!("[`{record}`]"),
      note: None,
    };
    let (filter_type, filter_builders) = crate::unit::filter(&filter_header, &filter_rows);
    types.extend(filter_type);

    // ---- the impls ---------------------------------------------------------------------------
    // A borrow per member and NO constructor, which is the whole of the sealing: the members are
    // `pub(crate)`, so the conversions below are the only way a DOWNSTREAM crate mints a value of
    // this type and a client never receives one this record did not produce. The key's own `new` is
    // the counter-example that shows the line — every combination of ids is a valid ADDRESS, where
    // an output object built from nothing would be a hit that never happened.
    //
    // The declaring crate can still write the literal, and that is the substrate rather than a hole:
    // a neighbouring expansion reads these members, and a rule that let it read without letting it
    // write would be two visibilities for one fact. What the sealing is ABOUT is the party that
    // receives the object, which is downstream of the crate that declared it.
    let id_borrow = Member::Borrow.name(&format_ident!("id"));
    let key_borrow = Member::Borrow.name(&format_ident!("key"));
    let id_doc = super::leading("The row's own id, by reference.");
    let key_doc = super::leading("The row's whole address, by reference.");
    let id_accessor = writes_id.then(|| {
      quote! {
        #[doc = #id_doc]
        #[inline]
        #vis const fn #id_borrow(&self) -> &#id_ty {
          &self.id
        }
      }
    });
    let address_accessors = quote! {
      #id_accessor

      #[doc = #key_doc]
      #[inline]
      #vis const fn #key_borrow(&self) -> &#key_output {
        &self.key
      }
    };
    // LAYER 2: the Rust FACE, and the one layer a declaration's `output(field = "…")` moves. The
    // member it borrows is layer 1 and stays the domain name, so a renamed accessor and the
    // substrate under it are two names on purpose — see [`GraphqlField::accessor`].
    let accessors = backend.fields().iter().map(|field| {
      let name = &field.source;
      let borrow = Member::Borrow.name(field.accessor());
      let ty = field.wire_ty();
      let gate = model.gate(name);
      // Named for the COLUMN it answers about rather than for the member it reads, because the two
      // may differ now and the sentence a caller reads should be about the field they declared.
      let doc = super::leading(&format!("The `{name}` field, by reference."));
      quote! {
        #gate
        #[doc = #doc]
        #[inline]
        #vis const fn #borrow(&self) -> &#ty {
          &self.#name
        }
      }
    });
    // LAYER 2 ON THE ADDRESS OBJECT — the Rust READ ROAD, and the one thing this face never had.
    //
    // `<E>KeyOutput` is a wire face and was nothing else, so a caller OUTSIDE the declaring crate
    // could not read a key's members in Rust at all: the members are `pub(crate)` substrate and the
    // `#[Object]` methods are the wire's. That measurement is what this closes — the house accessor
    // projection, one per key member, under the member's own domain name.
    //
    // The COLUMN's own family rather than a borrow spelled here, because the projection law is the
    // column's: a `copy` key column gets its value accessor beside the borrow exactly as it does on
    // the key type itself. `mutable` is FALSE — an address a client received is a value read, not one
    // being built, and the key type keeps the mutators for the party that builds one.
    //
    // The wire face is UNCHANGED: its methods are layer 1 under the `__async_graphql_` prefix, so
    // `__async_graphql_media_id` sits beside `media_id_ref` and neither can reach the other's name.
    let key_accessors = model.key.columns().map(|column| {
      // NO gate, for the key type's own reason: identity is not conditional.
      column.methods(
        vis,
        &model.krate,
        &format!("`{}` step of the address", column.name),
        false,
        &proc_macro2::TokenStream::new(),
      )
    });
    let key_name = &model.key.name;
    // Unconditional because this projection applies no conversion — every column is a move, which
    // cannot fail. `GraphqlOutput::Key` documents this type as the key's `COLUMNS` projected
    // through a scalar lowering (`Text→String` / `I64→Int` / `Uuid→UUID`), and a lowering that
    // could fail would be a different type.
    let key_reads = model.key.columns().map(|column| {
      let name = &column.name;
      quote!(#name: key.#name,)
    });
    let key_doc = super::leading(&format!("Project a [`{key_name}`] onto the wire."));
    let rows = self.row_crossings(model);
    impls.extend(quote! {
      impl #output_ty {
        #address_accessors
        #(#accessors)*
      }

      #input_impl

      #filter_builders

      impl #key_output {
        #(#key_accessors)*
      }

      #rows

      #[automatically_derived]
      impl ::core::convert::From<#key_name> for #key_output {
        #[doc = #key_doc]
        #[inline]
        fn from(key: #key_name) -> Self {
          Self { #(#key_reads)* }
        }
      }

      #key_input_impl
    });
    (types, impls)
  }

  /// **THE ADDRESS, CROSSING INWARD** — the `*Key`'s [`ToGraphqlInput`] row, and the argument object
  /// a COMPOUND key needs to have one.
  ///
  /// ```text
  /// root      reelsSimilarByClipKeys(key: Int!)               ← the id's own wire form, nothing minted
  /// compound  shotsSimilarByClipKeys(key: KeyframeKeyInput!)  ← { mediaId: Int!, id: Int! }
  /// ```
  ///
  /// # Why the ROOT case mints NOTHING
  ///
  /// A root record's key IS its id — `Key::columns` is `path ⊕ id` and a root's path is empty — and
  /// an id already spends [`ToGraphqlInput`] inward at every position that takes one: the record's
  /// own single-leg query field is `id: <IdTy as ToGraphqlInput>::Input`, crossed in the body, and
  /// the filter faces ask the same map of every operand. So the row written here for a root
  /// FORWARDS to that one and publishes no type: an id wrapped in a single-field object would be a
  /// second shape for an address the schema already carries a form for.
  ///
  /// # Why the COMPOUND case is a PRODUCT INPUT OBJECT and never a scalar
  ///
  /// Ruled 2026-08-16, and the ground is the house law against magic strings at an API floor: a
  /// two-column address encoded into one scalar is a format a client has to be told about out of
  /// band, and a schema that publishes it has published nothing machine-readable. One honest field
  /// per key column is the shape a client can introspect, and each field crosses through the same
  /// [`ToGraphqlInput`] map every other operand does — so a `u128` step arrives as the carrier its
  /// own row names rather than as a type no library gives an `InputType`.
  ///
  /// Every field is REQUIRED. An address with a step missing is not a narrower address; it is not
  /// one at all, so there is no nullable member here and no `oneof` flag — the `@oneOf` question
  /// input beside it is a CHOICE and this is a PRODUCT.
  ///
  /// # The CROSSING happens at `parse`, which is what makes the refusal name the field
  ///
  /// The argument object holds the DECLARATION's own column types, not their wire forms, and the
  /// per-column [`ToGraphqlInput::cross`] runs inside `InputType::parse`. So a step a client wrote
  /// wrong is `InputValueError` at that member's own position — async-graphql names the argument and
  /// the path — where a crossing deferred to `ToGraphqlInput::cross` on the whole key could only
  /// report one sentence about the address as a whole. What that buys the outer row is
  /// [`Infallible`]: a compound key's `cross` is a move of columns already crossed.
  ///
  /// The root row cannot make that trade — its wire form is the ID's, whose `parse` is that type's
  /// own — so its `Error` is the id's, forwarded undecorated.
  ///
  /// # NO BUILDER, where the argument object beside it has one
  ///
  /// `<E>GraphqlInput` ships `Default` and one `with_*` per member because a client's arguments are
  /// BUILT and any subset of them is a legal query. An address is not that: every step is required,
  /// so a defaulted half-address would be a value this type exists to make unrepresentable. The
  /// construction road is the key's own — `<E>Key::new(…)`, whose parameters are these columns in
  /// this order — plus `ToGraphqlInput::carry`, which is public and hands back the object. A
  /// positional constructor here would be a second spelling of `new`.
  ///
  /// # It is emitted with the FACES and therefore only where one is
  ///
  /// `faces` returns early for a record that names no backend, so a declaration with no wire face
  /// gets neither the type nor the row. That matters for the row in particular: `ToGraphqlInput` is
  /// a framework trait, and an impl of one on a record that asked for no wire face would be a
  /// binding nobody declared.
  ///
  /// # It DEMANDS an inward row of every key column, and the reach was measured rather than hoped
  ///
  /// The address object beside it already demands `ToGraphqlOutput` of the same columns
  /// unconditionally, and the two maps register the SAME set: `graphql::carrier`'s `faces_itself!`
  /// and `crosses_through!` lists are `graphql::output`'s, plus the blob row the output side reaches
  /// through the element's own marker. So a key column that renders is a key column that parses, and
  /// this face widens no declaration's obligations past the one already standing next to it.
  ///
  /// The impls are UNGATED, which is what the `derive`-only lane proves: `ToGraphqlInput` is this
  /// crate's own trait and reaches a build with no wire library at all. Only the `InputType` face
  /// over the argument object rides the gate — see `emit::wire`'s `key_input_face`.
  ///
  /// [`ToGraphqlInput`]: ../../../ingraph/trait.ToGraphqlInput.html
  /// [`ToGraphqlInput::cross`]: ../../../ingraph/trait.ToGraphqlInput.html#tymethod.cross
  /// [`Infallible`]: core::convert::Infallible
  fn key_input(&self, model: &RecordModel) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
    let vis = &model.vis;
    let record = &model.record;
    let key_name = &model.key.name;
    let crossing = model.framework(&["graphql"], "ToGraphqlInput");
    let substrate = super::substrate();
    if !model.key.compound() {
      let id = &model.key.id.name;
      let id_ty = &model.key.id.ty;
      return (
        proc_macro2::TokenStream::new(),
        quote! {
          #[automatically_derived]
          impl #crossing for #key_name {
            type Input = <#id_ty as #crossing>::Input;
            type Error = <#id_ty as #crossing>::Error;

            #[inline]
            fn cross(input: Self::Input) -> ::core::result::Result<Self, Self::Error> {
              ::core::result::Result::Ok(Self::new(<#id_ty as #crossing>::cross(input)?))
            }

            #[inline]
            fn carry(operand: &Self) -> Self::Input {
              <#id_ty as #crossing>::carry(&operand.#id)
            }
          }
        },
      );
    }
    let input_ty = crate::model::default_key_input_name(record);
    let members = model.key.columns().map(|column| {
      let name = &column.name;
      let ty = &column.ty;
      let doc = super::leading(&format!(
        "The `{name}` step of the address, in the declaration's own type — see the type's note for \
         where the wire form is crossed."
      ));
      quote! {
        #[doc = #doc]
        #substrate #name: #ty,
      }
    });
    let names: Vec<&syn::Ident> = model.key.columns().map(|column| &column.name).collect();
    let doc = super::leading(&format!(
      "A [`{record}`]'s address, as a client SENDS it — one required field per step of \
       [`{key_name}`], because an address with a step missing is not an address.\n\nEvery field \
       crosses through the operand map, so a step whose declared type has no wire form of its own \
       arrives as the carrier that type's row names."
    ));
    let types = quote! {
      #[doc = #doc]
      #[derive(::core::fmt::Debug, ::core::clone::Clone)]
      #vis struct #input_ty {
        #(#members)*
      }
    };
    let impls = quote! {
      #[automatically_derived]
      impl #crossing for #key_name {
        type Input = #input_ty;
        // INFALLIBLE, and the type's note says why: every column crossed at `parse`, so what is
        // left here is a move.
        type Error = ::core::convert::Infallible;

        #[inline]
        fn cross(input: Self::Input) -> ::core::result::Result<Self, Self::Error> {
          ::core::result::Result::Ok(Self::new(#(input.#names,)*))
        }

        #[inline]
        fn carry(operand: &Self) -> Self::Input {
          // `Clone::clone(&…)` rather than `….clone()`, for the address conversions' own reason:
          // `clone_on_copy` is default-on and a macro cannot know whether a column is `Copy`.
          #input_ty {
            #(#names: ::core::clone::Clone::clone(&operand.#names),)*
          }
        }
      }
    };
    (types, impls)
  }

  /// The ARGUMENT object: what a client sends, in the shape the engine's own find surface takes.
  ///
  /// # Every member MIRRORS a method, and the record's own capability decides which exist
  ///
  /// | member | the engine's | present when |
  /// |---|---|---|
  /// | `filter` | `Find::filter` | always |
  /// | `limit` | `Find::limit` — the UNORDERED ceiling, *any N rows* | always |
  /// | `order` | `Find::order` | the record is orderable |
  /// | `first` / `last` | `Ordered::first` / `Ordered::last` | the record is orderable |
  /// | `after` / `before` | `Paging::after` / `Paging::before` | the record is orderable |
  /// | `skip` | `Paging::skip` | the record is orderable |
  ///
  /// The page arguments ride the ORDER because that is the engine's own law rather than a rule
  /// invented here: `first`, `last`, `after`, `before` and `skip` exist on `Ordered` and nowhere
  /// else, so a cursor over an unordered set is a method that does not resolve. A record with a wire
  /// face and no `persist(…)` block therefore takes a filter and a ceiling and nothing else, which
  /// is exactly the query such a record can be asked.
  ///
  /// What a flat object cannot mirror is the TYPESTATE: a bag with both `limit` and `first` set is
  /// spellable here and refused by the builder, because a GraphQL input object is flat by
  /// construction. That refusal belongs to the round that resolves these arguments, and it is the
  /// one part of the surface a type cannot carry.
  ///
  /// # A cursor is the STRING, and it is forced rather than chosen
  ///
  /// `Cursor<V>` is parameterised by the cursor VALUE, which is per DATABASE — `<Row>Cursor`, the
  /// record's sum over one database's stored types — and this object is per RECORD, because a client
  /// must never see a schema that varies with a deployment's storage choice. So no typed cursor can
  /// be named here at all. What is named is what `Cursor::encode` already produces and
  /// `Cursor::decode` already reads: no codec is invented, and the decode happens where the database
  /// is known.
  ///
  /// # Construction is the FILTER's, not the output object's
  ///
  /// `Default` plus one `with_*` per member, with a borrow beside it — the shape `<E>Filter` already
  /// has, and for its reason: a client's arguments are BUILT, where an output object is minted by a
  /// conversion and sealed against anything else.
  fn arguments(&self, model: &RecordModel) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
    let vis = &model.vis;
    let record = &model.record;
    let input_ty = self.input.safe();
    let filter = self.filter.safe();
    let order_by = model.order_by.safe();

    // The ORDERED half, present exactly where the record has a term type to name — one predicate,
    // `RecordModel::orderable`, which is the same one the order-by is emitted under and the same one
    // the wire binding reads to decide between the enum and `()`.
    let paged: Vec<(syn::Ident, proc_macro2::TokenStream, &'static str)> = if model.orderable() {
      vec![
        (
          format_ident!("first"),
          quote!(::core::primitive::u32),
          "How many rows to take from the start of the order.",
        ),
        (
          format_ident!("last"),
          quote!(::core::primitive::u32),
          "How many rows to take from the far end of the order.",
        ),
        (
          format_ident!("after"),
          quote!(::std::string::String),
          "Resume after the row this cursor was minted at — the string `Cursor::encode` produced.",
        ),
        (
          format_ident!("before"),
          quote!(::std::string::String),
          "Resume before the row this cursor was minted at — the string `Cursor::encode` produced.",
        ),
        (
          format_ident!("skip"),
          quote!(::core::primitive::u64),
          "How many rows of the walk to pass before the page begins.",
        ),
      ]
    } else {
      Vec::new()
    };
    let optional: Vec<(syn::Ident, proc_macro2::TokenStream, &'static str)> = core::iter::once((
      format_ident!("filter"),
      quote!(#filter),
      "The predicate this query is constrained by.",
    ))
    .chain(core::iter::once((
      format_ident!("limit"),
      quote!(::core::primitive::u32),
      "A ceiling on an UNORDERED query — any this many rows, which is what a query with no order \
       can honestly be asked for.",
    )))
    .chain(paged)
    .collect();

    // LAYER 1 again, and here no word could reach it in the first place: these members MIRROR the
    // engine's find surface, which no declaration renames. The visibility is the law's all the same
    // — one spelling for every emitted member, so a reader learns it once.
    let substrate = super::substrate();
    let order = model
      .orderable()
      .then(|| quote!(#substrate order: ::std::vec::Vec<#order_by>,));
    let members = optional
      .iter()
      .map(|(name, ty, _)| quote!(#substrate #name: ::core::option::Option<#ty>,));
    let doc = super::leading(&format!(
      "A query's arguments over the [`{record}`]s a client asks for — the engine's own find surface, \
       in the types a schema can name."
    ));
    let declaration = quote! {
      #[doc = #doc]
      #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::default::Default)]
      #vis struct #input_ty {
        #order
        #(#members)*
      }
    };

    let order_methods = model.orderable().then(|| {
      let with = Member::With.name(&format_ident!("order"));
      let slice = Member::Slice.name(&format_ident!("order"));
      let with_doc = super::leading(
        "The same arguments with the order a client wrote — the terms in the sequence they run, \
         which is the one structure the GraphQL specification calls ordered.",
      );
      let slice_doc = super::leading("The order as written, in the sequence its terms run.");
      quote! {
        #[doc = #with_doc]
        #[must_use]
        #[inline]
        #vis fn #with(mut self, order: ::std::vec::Vec<#order_by>) -> Self {
          self.order = order;
          self
        }

        #[doc = #slice_doc]
        #[inline]
        #vis fn #slice(&self) -> &[#order_by] {
          &self.order
        }
      }
    });
    let methods = optional.iter().map(|(name, ty, what)| {
      let with = Member::With.name(name);
      let borrow = Member::Borrow.name(name);
      let with_doc = super::leading(&format!("The same arguments with `{name}` given. {what}"));
      let borrow_doc = super::leading(&format!("`{name}`, where the client gave one. {what}"));
      quote! {
        #[doc = #with_doc]
        #[must_use]
        #[inline]
        #vis fn #with(mut self, #name: #ty) -> Self {
          self.#name = ::core::option::Option::Some(#name);
          self
        }

        #[doc = #borrow_doc]
        #[inline]
        #vis const fn #borrow(&self) -> ::core::option::Option<&#ty> {
          self.#name.as_ref()
        }
      }
    });
    let implementation = quote! {
      impl #input_ty {
        #order_methods
        #(#methods)*
      }
    };
    (declaration, implementation)
  }

  /// The crossings from a stored ROW onto the wire object — one per database whose row carries the
  /// whole address, each behind that database's own gate.
  ///
  /// # It is the ONLY way into the object, and that is a correctness rule
  ///
  /// A `From<E>` beside it was removed rather than never written. An output object minted from an
  /// INSTANCE can lie about stored truth: a `persist` crossing may be lossy — a `u64` narrowed into
  /// an `i64` column, a duration rounded to whole seconds — so the value a client is handed would be
  /// the one the process happened to hold rather than the one the database will answer with on the
  /// next read. The ROW is the truth witness, and it is the only witness this object accepts.
  /// polarsync draws the same line: its only output leg is database → output.
  ///
  /// # The row is named through the VOCABULARY, not by its own name
  ///
  /// `<E as Record<Sqlite>>::Row` rather than `<E>Sqlite`, and the spelling is the point: the
  /// projection is exactly what a NEIGHBOUR'S expansion has to write, so writing it here is what
  /// proves the member reaches the type. Inside this expansion the two are one type — the impl is
  /// under the same gate as the vocabulary row that supplies it.
  ///
  /// # Which databases get one, and why the others do not
  ///
  /// A row that does not carry every column of the ADDRESS cannot fill the object's `id` and `key`,
  /// and a row missing an exposed column cannot fill that member — so a database missing either gets
  /// NO leg and the call site fails to resolve. That is the same discipline the query face already
  /// follows: nothing is emitted that would not compile, and nothing is silently invented.
  ///
  /// The MONGO family is not excluded. Its document is a row like any other — decoded by serde
  /// rather than by a written `FromRow` — and its `Record<Mongo>` impl names it, so the crossing is
  /// the same walk with a different gate.
  ///
  /// # A DECLARED leg replaces the chain rather than joining it
  ///
  /// `output(<db>(from = "…"))` is handed what THAT database's row field holds and answers with the
  /// wire form — one hop, and the declaration owns the whole of it. A database with no leg takes the
  /// DEFAULT CHAIN instead: the column's own `<db>(into)` back to the domain, then the
  /// domain's own wire face. Two shapes and they cannot be unified, for the reason a declared marker
  /// and an inferred one cannot: what a declared leg SAYS is *do not ask the row how to reach the
  /// wire, I have answered*.
  ///
  /// The ADDRESS columns take the chain always. They are not exposed fields, so no `output(…)` leg
  /// can name them: what a key column crosses through is its `persist` declaration and nothing else.
  fn row_crossings(&self, model: &RecordModel) -> proc_macro2::TokenStream {
    let Some(backend) = self.backends.first() else {
      return proc_macro2::TokenStream::new();
    };
    let record = &model.record;
    let output_ty = self.output.safe();
    let key_output = self.key_output.safe();
    let key_name = &model.key.name;
    let writes_id = model.wire_writes_id();
    let vocabulary = model.framework(&["transform"], "Record");
    let mut emitted = proc_macro2::TokenStream::new();

    for database in model.wire_rows() {
      let kind = database.kind();
      let columns = database.columns();
      let Some(key_at) = model.key_columns_stored(database) else {
        continue;
      };
      let mut fallible = false;
      // WHICH ADDRESS COLUMNS THE OBJECT ALSO PUBLISHES AS MEMBERS OF ITS OWN, and whether the
      // member's reading of the row is the SAME reading the key's is.
      //
      // Every address column is read once into a local and spent by the key. A record publishing
      // that column as an ordinary member too — which the inversion makes the DEFAULT, an address
      // column being a field like any other — reads the same row field a second time, and one row
      // field cannot be moved twice. So the two readings are reconciled here, once, rather than
      // left to collide inside the struct expression:
      //
      // * the SAME reading (no `output(<db>(…))` leg of its own and no wire form to cross into)
      //   binds the local once and hands the member the original, with the key taking the clone —
      //   the shape the framework's own `id` member already had;
      // * a DIFFERENT reading is two conversions of one value, so the local takes the clone and
      //   each side reads the row exactly once.
      //
      // A `Copy` column pays for neither: `Clone::clone` on one is the copy the move would have
      // been.
      let shared: Vec<(syn::Ident, bool)> = model
        .key
        .columns()
        .map(|column| {
          let published = backend
            .fields()
            .iter()
            .find(|field| field.source == column.source);
          let same = published
            .is_some_and(|field| field.output_crossing.leg(kind).is_none() && field.wire.is_none());
          (column.source.clone(), same)
        })
        .collect();
      let cloned_into_the_key = |source: &syn::Ident| {
        shared
          .iter()
          .any(|(column, same)| column == source && *same)
      };
      let locals: Vec<proc_macro2::TokenStream> = model
        .key
        .columns()
        .zip(&key_at)
        .map(|(column, &at)| {
          let stored = &columns[at];
          let local = format_ident!("__ingraph_{}", column.source);
          let field = stored.name.safe();
          fallible |= stored.into.fallible();
          // The clone is on the ROW's own field here rather than on the converted value, because
          // this is the branch where the two readings CONVERT differently: the member is about to
          // read the row for itself, so what has to survive the local is the row's field.
          let read = if backend
            .fields()
            .iter()
            .any(|field| field.source == column.source)
            && !cloned_into_the_key(&column.source)
          {
            quote!(::core::clone::Clone::clone(&__ingraph_row.#field))
          } else {
            quote!(__ingraph_row.#field)
          };
          let value = stored.into.apply(read, stored.stored.is_some());
          quote!(let #local = #value;)
        })
        .collect();
      let arguments = model.key.columns().map(|column| {
        let local = format_ident!("__ingraph_{}", column.source);
        // The column is CLONED into the key exactly where a member takes the original, so a declared
        // conversion runs once per row however many members spend its result.
        if (writes_id && column.source == model.key.id.source)
          || cloned_into_the_key(&column.source)
        {
          return quote!(::core::clone::Clone::clone(&#local));
        }
        quote!(#local)
      });
      let id_local = format_ident!("__ingraph_{}", model.key.id.source);
      let id_read = writes_id.then(|| quote!(id: #id_local,));
      let reads: Vec<proc_macro2::TokenStream> = backend
        .fields()
        .iter()
        .map(|field| {
          // The MEMBER, which is layer 1 and the field's own name: this crossing is an
          // emitted-to-emitted write, and what it fills is the substrate rather than the face.
          let member = &field.source;
          // A column THIS DATABASE narrowed away is supplied by the fill its own word named — the
          // same value the RAISE hands the record, so the wire object and the record agree about
          // what this deployment holds. *Publishing and storing are two axes*: the value exists in
          // memory whatever supplied it, and this is where a narrowing row supplies one.
          //
          // The wire form still applies where a field declared one; the DECLARED output leg does not,
          // because it converts a row field and there is none — a fill is already the domain value
          // this leg would have raised one into.
          let Some(stored) = database.stores(&field.source) else {
            let fill = database
              .storage()
              .fills
              .iter()
              .find(|filled| filled.source == field.source)
              .expect("`RecordModel::wire_rows` refuses a database that supplies no exposed field");
            let ty = model
              .fields
              .iter()
              .find(|declared| declared.column.source == field.source)
              .map(|declared| &declared.column.ty)
              .expect("a filled field is one the record declares");
            let value = fill.fill.value(ty);
            let value = if field.wire.is_some() {
              quote!(::core::convert::Into::into(#value))
            } else {
              value
            };
            let condition = model.gate(&field.source);
            return quote!(#condition #member: #value,);
          };
          let held = stored.name.safe();
          // An address column whose member reads the row exactly as its key local did spends that
          // local, which is what makes ONE reading serve both.
          if cloned_into_the_key(&field.source) {
            let local = format_ident!("__ingraph_{}", field.source);
            let condition = model.gate(&field.source);
            return quote!(#condition #member: #local,);
          }
          let value = match field.output_crossing.leg(kind) {
            // DECLARED: the row field goes straight to the wire form, and the declaration owns both
            // hops. `converted` is false because there is no `Into` to fall back on — the function
            // IS the crossing.
            Some(declared) => {
              fallible |= declared.fallible();
              declared.apply(quote!(__ingraph_row.#held), false)
            }
            // The CHAIN: this database's read crossing back to the domain, then the domain's own
            // wire face — an `Into` exactly where a wire form was declared, and nothing at all where
            // the wire form IS the domain type.
            None => {
              fallible |= stored.into.fallible();
              let raised = stored
                .into
                .apply(quote!(__ingraph_row.#held), stored.stored.is_some());
              if field.wire.is_some() {
                quote!(::core::convert::Into::into(#raised))
              } else {
                raised
              }
            }
          };
          // `gate` is bound below for the FEATURE gate this whole leg rides; the field's own
          // condition is a different question and is asked here, at the struct-expression field.
          let condition = model.gate(&field.source);
          quote!(#condition #member: #value,)
        })
        .collect();

      let backend_ty = database.backend_type(model);
      let gate = model.framework(&["gate"], &kind.gate().to_string());
      // ONE error for every fallible leg of this crossing at this backend, read off the record's own
      // `graphql(output(<db>(error = "…")))` cell — or the boxed refusal where none was declared.
      let error = fallible.then(|| model.error(Crossing::Output, kind));
      let leg = super::conversion(
        quote!(<#record as #vocabulary<#backend_ty>>::Row),
        output_ty,
        &format_ident!("__ingraph_row"),
        quote! {
          {
            #(#locals)*
            let __ingraph_key = <#key_output as ::core::convert::From<#key_name>>::from(
              #key_name::new(#(#arguments,)*),
            );
            Self {
              #id_read
              key: __ingraph_key,
              #(#reads)*
            }
          }
        },
        error.as_ref(),
        &format!(
          "Raise a stored {} row onto the wire — every column through the crossing its declaration \
           names, and the address out of the columns that carry it.",
          kind.as_str()
        ),
      );
      emitted.extend(quote! {
        #gate! { #leg }
      });
    }
    emitted
  }
}

/// An identifier in upper camel case — a variant's name, built from the column or field it stands
/// for.
///
/// `X` in front of a name that would start with a digit or be empty, because a variant is an
/// identifier and neither shape is one.
pub(crate) fn upper_camel(name: &str) -> syn::Ident {
  let mut camel = String::with_capacity(name.len());
  let mut upper = true;
  for c in name.chars() {
    if c == '_' {
      upper = true;
    } else if upper {
      camel.extend(c.to_uppercase());
      upper = false;
    } else {
      camel.push(c);
    }
  }
  if camel.is_empty() || camel.starts_with(|c: char| c.is_ascii_digit()) {
    camel.insert(0, 'X');
  }
  format_ident!("{camel}")
}

impl GraphqlBackend {
  /// A filter field's Rust MEMBER, its SDL name and its WIRE type — layer 1, layer 3, and the type
  /// both of them are about.
  ///
  /// # The member is the RECORD FIELD's name, and `input(rename)` does not reach it
  ///
  /// It used to be the mangled INPUT SCHEMA name, which put a wire word on layer 1: a
  /// `graphql(input(rename = "bitRate"))` over a `checksum` column emitted a member `bit_rate`. The
  /// law says a rename word moves a FACE, and the input position's face is the schema name below —
  /// so the two are a layer apart now and the member is the one no word moves.
  ///
  /// The comparison this filter crosses into is keyed the same way, which is the point: an
  /// interface's consistency equation reads a member's comparison through an accessor built from
  /// the field name it pinned, so a member bending a shared column's Rust name would break a
  /// neighbour's equation. Neither word can spell that any more.
  ///
  /// # The SDL name is the declared one, and a column nobody exposed takes its DOMAIN name
  ///
  /// The fallback used to be [`PersistColumn::name`] — the column's name in the FIRST declared
  /// database — so a `<db>(rename)` on a stored-but-unexposed column put a storage name on
  /// the wire, and a schema varied with a deployment's physical layout. A storage rename moves SQL
  /// strings and stops there, so the fallback is the field's own name; identical wherever no such
  /// rename was written, which is every declaration that had a correct schema to begin with.
  ///
  /// # The TYPE
  ///
  /// The field's ONE wire form, which is the same type its output member carries: the operand a
  /// client filters with and the value it receives back are one thing, and a schema that made them
  /// two would be one a client has to read twice. An unexposed column has no wire form declared for
  /// it and takes its domain type, which is what it always did.
  pub(crate) fn filter_field(&self, column: &PersistColumn) -> (syn::Ident, String, syn::Type) {
    let exposed = self
      .fields()
      .iter()
      .find(|field| field.source == column.source);
    let sdl = exposed.map_or_else(
      || {
        RustSafeName::from_ident(column.member())
          .external()
          .to_owned()
      },
      |field| field.input.name.to_string(),
    );
    let ty = exposed.map_or_else(|| column.domain.clone(), |field| field.wire_ty().clone());
    (column.member().clone(), sdl, ty)
  }
}

impl RecordModel {
  /// Every column the DECLARATION states — the record's shared column list, and the vocabulary its
  /// schema publishes.
  ///
  /// # The DECLARATION's truth, not a deployment's
  ///
  /// *A client must never see a schema that varies with a deployment's storage choice.* That law
  /// forbids the schema varying BY deployment; it does not command shrinking it TO the intersection,
  /// and reading it that way was the mistake this list is the correction of. A word that came and
  /// went with which databases a record happened to declare would be exactly the varying schema the
  /// law forbids — the same record, deployed twice, publishing two vocabularies.
  ///
  /// So a per-database-narrowed column KEEPS its filter word and its order-by word here, and the
  /// deployment answers at RUNTIME: a predicate or an order over a column this database has not got
  /// is a named refusal citing the column and the dialect — `ingraph`'s `query::ColumnNotStored` —
  /// rather than a word a client cannot find or a bare *no such column* out of the driver. The
  /// author owns the combination, having narrowed the column, published the word and deployed that
  /// database; what the framework owes is a legible sentence.
  ///
  /// The ADDRESS is the one column no declaration may narrow, and that stays a COMPILE-time named
  /// refusal at the word — identity is unskippable — so no runtime refusal is ever a page's.
  ///
  /// # A UNION over the declared databases, walked in the RECORD's own order
  ///
  /// The walk is the record's fields rather than any one database's list, which is what makes the
  /// order the declaration's: a database that narrows a column has a shorter list, so merging two
  /// of them would put a column where neither declared it. Each entry is taken from the FIRST
  /// database that carries it, that being as good a representative as any — a filter holds DOMAIN
  /// values, so no per-database refinement reaches the vocabularies this feeds, and what this list
  /// decides is WHICH columns rather than how any of them renders.
  ///
  /// A field wearing the bare `skip` is a column of NO database and is absent here: a value no
  /// store holds is the raise's own fill, one constant for every row, and a predicate over a
  /// constant is a lying schema. That is the compile-time exclusion 4-2's ruling keeps.
  ///
  /// # COMPUTED rather than resolved into the model
  ///
  /// A stored list would be a second statement of a fact the backends already carry, and one that
  /// goes stale the moment a backend's own list moves — so the answer is derived at every ask, from
  /// the one place the columns live.
  ///
  /// # The INDEX into this list is NOT an index into a database's own
  ///
  /// Every database used to mint the same columns in the same order. Under the participation model
  /// a narrowing database has a SHORTER list, and under declaration truth this one is the WIDEST —
  /// so a position read off here would name a different column of that database, or none at all.
  /// Every per-database reader looks a column up by SOURCE: see `DatabaseBackend::stores`, which is
  /// the one lookup, and `DatabaseBackend::compared`, which is what a comparison walks.
  pub(crate) fn stored_columns(&self) -> Vec<&PersistColumn> {
    let Some(persist) = self.persist.as_ref() else {
      return Vec::new();
    };
    self
      .fields
      .iter()
      .filter_map(|field| {
        persist
          .backends
          .iter()
          .find_map(|database| database.stores(&field.column.source))
      })
      .collect()
  }

  /// The stored columns EVERY declared database mints, each with WHERE it sits among the stored
  /// ones — the record's shared QUERY VOCABULARY, and the one list the filter, the order-by and
  /// every database's comparison are all built from.
  ///
  /// # An INTERSECTION, because the vocabularies it feeds are one per RECORD
  ///
  /// A filter is a wire type and there is one of it however many databases a record declares — *a
  /// client must never see a schema that varies with a deployment's storage choice*, which is this
  /// framework's own law and the reason [`stored_columns`](Self::stored_columns) is the intersection
  /// rather than a union. The participation model lets the databases disagree about which columns
  /// exist, and this is the seat where that disagreement is kept off the wire: a column some store
  /// does not carry is stored, written and read back where it lives, and is not a column a client
  /// can name in a predicate or an order.
  ///
  /// # So the narrowing is the WIRE's alone, and the sweep is one line
  ///
  /// `graphql(skip)` withholds a field from every wire vocabulary, and two of the four are built
  /// from this list: the FILTER's members and each database's COMPARISON. The output object is swept
  /// by absence, a withheld field never becoming a `GraphqlField` at all; the ORDER-BY sweeps at its
  /// own face — see [`order_by_face`](super::wire) — because the term TYPE is Rust's and a Rust
  /// caller keeps every field's ordering. One predicate rather than four is also what keeps the
  /// filter's crossing honest: that crossing ZIPS this database's comparison members against the
  /// filter's rows, and two walks over one list cannot fall out of step.
  ///
  /// The ROW is untouched by it. A field the schema never names is still stored, still written and
  /// still read back — publishing and storing are two axes, and this is the one that decides which
  /// vocabularies a CLIENT can name a column in.
  ///
  /// # The INDEX is into [`stored_columns`](Self::stored_columns), and it indexes THAT list alone
  ///
  /// It used to double as an index into each database's own column list, every database carrying the
  /// same entries in the same order. The participation model ended that alignment — a database that
  /// narrows a column has a SHORTER list — so a party wanting this database's entry looks it up by
  /// SOURCE rather than by position; see `DatabaseBackend::compared`.
  pub(crate) fn queried_columns(&self) -> Vec<(usize, &PersistColumn)> {
    self
      .stored_columns()
      .into_iter()
      .enumerate()
      .filter(|(_, column)| self.published(&column.source))
      .collect()
  }

  /// Whether this record's wire face names `source` at all — false where `graphql(skip)` withheld
  /// it, and true for a record with no wire face, which withholds nothing because it publishes
  /// nothing.
  pub(crate) fn published(&self, source: &syn::Ident) -> bool {
    self
      .graphql
      .as_ref()
      .is_none_or(|graphql| graphql.publishes(source))
  }

  /// The stored columns a term may name, each with WHERE it sits among the stored ones — every one
  /// of them except the two shapes a position in an order cannot be.
  ///
  /// # The list is the RECORD's and the WIRE does not narrow it
  ///
  /// `graphql(skip)` never reaches this walk, and the reason is the ruled shape of the type: the
  /// order-by ENUM generates FULL, so a Rust caller keeps every stored column's ordering, and the
  /// SCHEMA's narrowing happens one layer out — the hand-written `InputType` impl registers and
  /// parses only the unskipped variants, which makes a withheld column invisible AND unreachable
  /// from the wire without splitting the type. See [`order_by_face`](super::wire), which is where
  /// the two lists meet.
  ///
  /// The INDEX travels beside the column because an ordering reads two lists at that one position:
  /// the order-by VARIANT comes from [`Self::stored_columns`], which is what the enum was built
  /// from, and the column NAME from the database being emitted for, which `<db>(rename)`
  /// may have moved. One index serves both because participation is the RECORD's shape — every
  /// declared database carries the same columns in the same order, and only their refinements
  /// differ, which is the same fact [`Self::stored_columns`] reads the first database on.
  ///
  /// # A many-valued column IS one, and what it costs is stated on the TERM
  ///
  /// A collection is orderable: PostgreSQL defines `ORDER BY <array column>` element by element,
  /// and that rule is the framework's — `ingraph`'s `query::compare_collections`. So a collection
  /// field is an order subject like any other here, and what varies is what each backend can do
  /// with it: PostgreSQL pushes an array-stored one, every edge-stored one is a remainder because
  /// the row has no such column, and MongoDB refuses because its `$sort` means the extreme element
  /// rather than the sequence. All three are the capability frame's answers, read off the SUBJECT
  /// the per-database term carries — see [`DatabaseBackend::edge_stored`], which is what decides
  /// which subject that is.
  ///
  /// This list used to exclude them, on a sentence that was PostgreSQL-ignorant: *a list has no
  /// scalar order*. What is left of the narrowing is the CURSOR's, and it is
  /// [`DatabaseBackend::paged_columns`] — a boundary is a value THIS database can bind, which an
  /// edge-stored collection is not, there being no column of the row for it.
  ///
  /// What answers *is this column many-valued* is [`Label::collection`](crate::model::Label::collection)
  /// — the declaration's own collection WORD, read off the field's marker — and it is an
  /// independent axis from [`Projection::Repeated`](crate::model::Projection::Repeated), which
  /// shapes an ACCESSOR (`x_slice(&self) -> &[…]`) and says nothing about how many values the
  /// column holds. The two may both be written, and then the word governs. `repeated` ALONE goes on
  /// meaning what it means: a `Vec<u8>` declared `bytes` is one blob in one column, and one blob is
  /// ordered as the scalar it is.
  ///
  /// A marker the DECLARING crate owns ([`Marker::Path`](crate::model::Marker::Path)) is not a word
  /// this can read, so a collection reached that way is ordered as a scalar — the same limit
  /// [`Marker::resolved`] has, and for the same reason: what the framework did not name, it cannot
  /// classify.
  ///
  /// # The element may be COMPOSITE, and the storage has answered how
  ///
  /// This note used to read *only a collection of scalars is declarable at all*, on a claim about
  /// `Carrier<Db>` that was already false — a carrier row for a composite pushes SEVERAL
  /// placeholders with its own separators, which is the arrangement the framework's own instant has
  /// — and it recorded that a collection of composites was a design round of its own whose question
  /// would arrive here when the storage answered it. **The storage has answered.**
  ///
  /// An element occupying several columns takes the EDGE TABLE on every SQL backend, one column per
  /// SEGMENT of the element's own type — `ingraph`'s `EdgeTable::composite`, `EdgeWrite::composite`
  /// and `SqlCompositeEdgeComparison` — and a native sub-document array on MongoDB. The Postgres
  /// array delegation stays scalar-only, an array of two columns not being a thing any dialect has,
  /// so a composite element's ORDER-BY subject is edge-stored on every backend and this list's
  /// answer for it is the one it already gives every edge-stored collection: an order subject, a
  /// remainder, and no cursor slot.
  ///
  /// What is NOT settled here is the WORD. A field whose element is composite reaches its filter
  /// through `label = "a::marker::Path"` — the field's own escape, which the label grammar already
  /// documents — because the framework's eight words name value families and a composite is not one
  /// of them. Minting a ninth is a marker family of its own (a filter type, a GraphQL input object,
  /// a `*FilterMarker` row) and it is not something the storage ruling decided, so nothing here may
  /// be read as admitting a bare word for it.
  ///
  /// # A COMPOSITE is not one either, and it fails one axis over
  ///
  /// A collection is MANY-VALUED; a composite is MANY-COLUMNED, and the order-by breaks on it the
  /// same way. `ORDER BY rate` names the composite's own field name, and a composite has no column
  /// of that name — its parts are `rate_num` and `rate_den`, or, marked `flatten`, the record's own
  /// `num` and `den`. So the term rendered a column no table has, exactly as the collection's did.
  /// A cursor cannot be minted at one either: a position in an order is one value, and a pair is
  /// not.
  ///
  /// Ordering by a composite's LEAF — `rate.num` — is a real question this does not answer, and it
  /// arrives with the nested order rather than here: a term naming a leaf needs a path where the
  /// order-by carries a column, which is a shape change to the emitted type.
  ///
  /// What the declaration marks is `flatten`, so that is what this reads. An UNMARKED composite is a
  /// scalar to anything holding tokens — `rate: Timebase` and `title: String` are the same two
  /// tokens — so it stays in, and that is the same limit as the path marker above rather than a
  /// second rule. The two cases are told apart by the declaration exactly where the declaration
  /// speaks.
  pub(crate) fn ordered_columns(&self) -> Vec<(usize, &PersistColumn)> {
    self
      .stored_columns()
      .into_iter()
      .enumerate()
      .filter(|(_, column)| !column.flatten)
      .collect()
  }

  /// The COLLECTION word the field behind a column was declared with, or `None` where it named no
  /// collection — which is what decides the SHAPE its edge table has: a sequence's rows carry an
  /// ordinal and a set's do not.
  pub(crate) fn shape_of(&self, source: &syn::Ident) -> Option<Label> {
    match self.marker_of(source) {
      Some(Marker::Framework(marker)) if marker.label.collection() => Some(marker.label),
      _ => None,
    }
  }

  /// Whether the field behind a column was declared a COLLECTION — the one question the collection
  /// word answers, asked in one place so the order-by fence and the storage plan cannot disagree
  /// about which columns are many-valued.
  pub(crate) fn collects(&self, source: &syn::Ident) -> bool {
    matches!(
      self.marker_of(source),
      Some(Marker::Framework(marker)) if marker.label.collection()
    )
  }

  /// Whether the field behind a column asked for the ORDER-PRESERVING COMPANION COLUMN — the
  /// `sortable` word, asked in one place for [`collects`](Self::collects)'s reason.
  ///
  /// It answers about the DECLARATION and not about a database. Whether a companion is actually
  /// emitted is this AND the storage form — see `DatabaseBackend::mirrors`, which joins the two —
  /// because a dialect keeping the collection in a native array orders it itself and has nothing to
  /// mirror.
  ///
  /// The FIELD's own fact rather than its marker's: the word is a storage one and sits beside the
  /// label rather than inside it — see [`Field::sortable`](crate::model::Field::sortable).
  pub(crate) fn sortable(&self, source: &syn::Ident) -> bool {
    self
      .fields
      .iter()
      .find(|field| field.column.source == *source)
      .is_some_and(|field| field.sortable)
  }

  /// Whether the field behind a column asked for the VALUE-LED ACCESS PATH — the `indexed` word,
  /// asked in one place for [`collects`](Self::collects)'s reason and read exactly as
  /// [`sortable`](Self::sortable) is.
  ///
  /// It answers about the DECLARATION and not about a database. What a given database DOES with the
  /// word is the join of this and the storage form — see `DatabaseBackend::seeks_by_value`, which is
  /// `mirrors`' shape one word over.
  pub(crate) fn indexed(&self, source: &syn::Ident) -> bool {
    self
      .fields
      .iter()
      .find(|field| field.column.source == *source)
      .is_some_and(|field| field.indexed)
  }

  /// Where the ID column sits among the stored ones, or `None` where the id is not stored at all.
  ///
  /// The INDEX rather than the column, because an ordering reads two lists at that one position:
  /// the order-by VARIANT comes from [`Self::stored_columns`], which is what the enum was built
  /// from, and the column NAME from the database being emitted for, which `<db>(rename)`
  /// may have moved. One index serves both because participation is the RECORD's shape — every
  /// declared database carries the same columns in the same order, and only their refinements
  /// differ, which is the same fact [`Self::stored_columns`] reads the first database on.
  ///
  /// # ONE column, and the lineage is no longer among them
  ///
  /// This used to answer with the whole key — `lineage ⊕ id`, root-first — because the whole key
  /// was the address. The id is the address now: a framework-emitted table's id is UNIQUE, so
  /// `WHERE id = ?` names at most one row and an order ending in the id alone is already total.
  ///
  /// The lineage columns did not leave STORAGE. They are ordinary stored, indexed columns and a
  /// client may still order by one or filter on one — what they left is the ADDRESS, the key tail
  /// and the entry point's signature. So this reads [`Key::id`](crate::model::Key::id) and never
  /// [`Key::columns`](crate::model::Key::columns), and the tail it feeds is one term long.
  ///
  /// # `None` is a database that cannot be ordered, and the absence is the answer
  ///
  /// The tail exists to make an order TOTAL, and an id the row has not got is nothing to end on —
  /// an order without it pages with exactly the skipped and repeated rows the law exists to
  /// prevent, and naming a column the table has not got is a query error one whole lifecycle later.
  /// What such a declaration gets instead is no ordering lowering for any of its databases, and a
  /// call site naming one fails to resolve.
  pub(crate) fn id_column_stored(&self) -> Option<usize> {
    let id = &self.key.id;
    self
      .stored_columns()
      .iter()
      .position(|persisted| persisted.source == id.source)
  }
}

impl PersistColumn {
  /// The RECORD FIELD this column stores — LAYER 1, and the ident every emitted member over this
  /// column is named by.
  ///
  /// [`name`](Self::name) is the other one, and the two are a layer apart: that is *the column's
  /// name in THIS database*, which `<db>(rename)` and the common `persist(rename)` both
  /// move, and it belongs to the SQL strings a statement renders. This one no word moves.
  ///
  /// The distinction is load-bearing rather than tidy, and it is what the comparison axis needed:
  /// an interface's consistency equation reads a member's own comparison through an accessor built
  /// from the field name it pinned, so a member whose storage renamed a shared column would break a
  /// NEIGHBOUR's equation with `E0599`. Keyed on the field, that divergence is unrepresentable.
  pub(crate) const fn member(&self) -> &syn::Ident {
    &self.source
  }

  /// An order-by variant's name: the RECORD FIELD's name in upper camel case.
  ///
  /// LAYER 1, so `<db>(rename)` does not reach it — a storage rename moves SQL strings and
  /// stops there. It used to be built from [`name`](Self::name), which made the variant follow
  /// whichever database happened to be declared FIRST: two deployments of one record could not
  /// agree on the vocabulary, and the name leaked onto the wire through the `OneofObject` derive
  /// that renders a variant as a schema key.
  ///
  /// Every by-variant comparison is rename-proof BY CONSTRUCTION now rather than through a side
  /// channel — the wire door's dedup and [`complete`]'s id tail match on a variant that no
  /// deployment can move. [`identity`] remains the SEMANTIC identity a cursor's signature is folded
  /// from; what changed is that it is no longer the only rename-proof name a term has.
  ///
  /// [`complete`]: RecordModel::ordering
  /// [`identity`]: RecordModel::ordering
  pub(crate) fn order_variant(&self) -> syn::Ident {
    upper_camel(&self.source.to_string())
  }
}

impl DatabaseBackend {
  /// One database's COMPARISON type: one PREDICATE per column, in the types that database stores.
  ///
  /// The layer exists so that a value crosses into a database through the field's `persist`
  /// declaration and ONLY through it. The row and the comparison share that one authority, so a
  /// column's stored bytes and a predicate's bound bytes cannot diverge — before this they were two
  /// mechanisms that happened to agree, and would have stopped agreeing at the first `type`
  /// override the framework did not know about, producing a query that matches nothing, with no
  /// error and no type mismatch.
  ///
  /// polarsync needs no such layer because its domain types are ALREADY storable —
  /// `polarsync-types/src/unsigned.rs` defines `U<N>` with `Type`/`Encode` for Postgres, so a field is
  /// `U<8>` and never a bare `u64`. ingraph reaches the same place by declaration instead of by
  /// domain-type choice: a bare `u64` on Postgres must say `postgres(type = "BeU64", into = "…")`, or
  /// carry a storable domain type. Nothing silently works.
  ///
  /// # A field holds an operator SET, not a value
  ///
  /// One `Option<stored>` per column can say `column = value` and nothing else. A comparison KIND
  /// holds the vocabulary instead — `SqlScalarComparison` carries `eq`/`ne`/`gt`/`gte`/`lt`/`lte`/
  /// `in_`/`not_in`, `SqlTextComparison` twelve more — so a field here is the kind its column's
  /// filter crosses into. Lowering the whole becomes `ComplexComparison::apply` threading ONE
  /// accumulator through the fields in turn rather than a `push_bind` per column: a field renders
  /// as many conjuncts as it has operators set, and which clause they open is the accumulator's
  /// business.
  ///
  /// # The kind is ASKED for, never tabled
  ///
  /// ```text
  /// <<<domain as DefaultMarker>::Marker as ToGraphqlFilter>::Filter
  ///     as ToDatabaseComparison<stored, Db>>::Comparison
  /// ```
  ///
  /// Three projections answering different halves. The DOMAIN type picks its INTERPRETATION — a
  /// `Vec<u8>` is a blob and a `Vec<Label>` a list, which the type alone cannot say and
  /// [`filter_of`] is the seam for — that interpretation picks the filter KIND, which is the
  /// operators the column admits; and the STORED type is what that kind's operands are, so
  /// `type = "BeU64"` on a `u64` column gives a scalar comparison over `BeU64`: the declaration
  /// changed the storage and not the question. All three are authorities the row already reads,
  /// which is why none can drift from another.
  ///
  /// A field that NAMED its interpretation replaces the innermost projection with the marker itself
  /// — [`filter_of`] carries both shapes — and nothing else here moves. Which is the invariant
  /// worth stating: a marker reaches the FILTER, and this crossing is still the one place storage
  /// enters.
  ///
  /// Asking rather than tabling is what keeps the vocabulary OPEN. A downstream type joins by
  /// implementing the traits, with no arm to add here; and a type with no interpretation is an
  /// unsatisfied `DefaultMarker` bound NAMING that type, rather than a macro error naming a
  /// type the macro does not recognise. The price is that a STORED column's domain type must have
  /// one, which the module's own doctrine already asks of it: a field is filterable because it is
  /// stored.
  ///
  /// # Nullability is the domain type's own spelling
  ///
  /// Nothing here detects it and nothing needs to. One blanket maps `Option<T>` onto the null test
  /// over `T`'s own interpretation, so the filter is `Nullable<F>`; and `Nullable<F>` crosses into
  /// `SqlNullable<F::Comparison>` — the inner kind's
  /// conjuncts followed by the null test — so a nullable column reaches its three states through
  /// the type it is DECLARED with, written verbatim exactly as the filter writes it.
  ///
  /// The `Option<Option<T>>` the old shape carried went with the shape rather than being ported.
  /// Its outer layer said whether the column was compared at all, and that is now the kind's own
  /// `is_empty`; a second encoding of one fact is one that can disagree with the first, since
  /// `Some(<empty kind>)` and `None` would both have to mean *no predicate*.
  ///
  /// # The database parameter, and where its bound sits
  ///
  /// The database is a type PARAMETER rather than a spelled dialect, because the comparison kinds
  /// are: one `SqlScalarComparison<V, Db>` serves all three SQL dialects, and the mongo family
  /// takes its own marker in the same position. Naming a dialect here would put a backend's crate
  /// in an expansion, which is what the shelf exists to prevent.
  ///
  /// It is not SPELLED `Db`, and the reason is a defect rather than a taste: a parameter is a type
  /// name resolving at the call site, so a declaration with a field whose type is `Db` has that
  /// type shadowed inside every item emitted here. See [`super::parameter`] for what that costs and
  /// why nothing about a proc macro's hygiene prevents it.
  ///
  /// It carries ONE bound — `Backend` — and that one is not optional. `sqlx::Database` is still not
  /// a name this emitter may write, and it does not have to be: a `where F: ToDatabaseComparison<V,
  /// Db>` is well formed only beside `Db: Backend`, because the trait's own parameter is bounded
  /// that way. Without it every expansion is `E0277: the trait bound Db: Backend is not satisfied`,
  /// reported at the derive. Beyond it, the struct carries the crossing, one predicate per column:
  /// that is what makes the field types well formed, and a caller writing `Comparison<Sqlite>` is
  /// what discharges both.
  ///
  /// # `Debug`, `Clone` and `Default` go, and cannot come back on this shape
  ///
  /// The old shape derived all three. A derive now fails outright: its body needs each field's
  /// projection to carry the trait, and that obligation is not implied by the crossing the struct
  /// assumes.
  ///
  /// Nor can the bound be STATED. `<F as ToDatabaseComparison<V, Db>>::Comparison: Debug` has a
  /// CONCRETE self type, so rustc resolves the projection through the impl that defines it and
  /// demands the very `Db: sqlx::Database` an expansion may not write — the crossing being assumed
  /// in the same `where` clause does not change it, because a param-env candidate does not displace
  /// an impl candidate for a concrete self type.
  ///
  /// The obvious escape is an associated-type BINDING plus one impl parameter per column
  /// (`Comparison = C0`), which moves the bound onto a plain parameter. It holds only while no two
  /// columns share a crossing, and it collapses the moment they do: three `i64` columns — which
  /// `ingraph-derive`'s `Frame` fixture has — bind ONE trait-ref to three parameters, and rustc can
  /// infer none of them (`E0284`, *cannot satisfy `<ScalarFilter<i64> as
  /// ToDatabaseComparison<i64, Db>>::Comparison == _`*). Deduplicating the parameters cannot repair
  /// it either: the emitter may key only on what a declaration WROTE, and a type alias makes two
  /// spellings of one crossing — measured, and it fails identically. Resolving a spelling is
  /// exactly what a macro cannot do, which is the same reason projections here are written
  /// verbatim.
  ///
  /// So the comparison carries none of the three. What a caller loses is real and small — the
  /// empty predicate is `Default` on the KINDS, one field at a time — and what it buys is that the
  /// type stays honest about its own well-formedness instead of shipping an impl that compiles for
  /// some declarations and not others.
  ///
  /// `Default` was the only construction path, though, and the fields are private, so its removal
  /// left a type that could be named and not built. `new` below is what replaces it: one predicate
  /// per column, positional, in the order this database stores them. It is positional because the
  /// alternative — a nullary `new()` returning the empty comparison — is the `Default` bound again
  /// under another name.
  ///
  /// # A database that stores no column
  ///
  /// It gets a `PhantomData` field, and only it does: with no column, the database parameter occurs
  /// nowhere in the struct and `E0392` would land inside an expansion its author cannot edit.
  /// Nothing can collide with the name, because a collision would have to be with a column and
  /// there are none.
  ///
  /// # The LOWERING rides with the struct
  ///
  /// `ComplexComparison` is emitted here rather than beside the map, because the type IS a
  /// comparison whether or not the record has a wire face for one to be reached through — and
  /// because [`comparison_traits`](Self::comparison_traits) cannot keep the map's item bound
  /// without it. See [`Self::lowering`].
  pub(crate) fn comparison(
    &self,
    model: &RecordModel,
  ) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
    let vis = &model.vis;
    let record = &model.record;
    let name = self.comparison_name();
    let db = super::parameter("DB");
    let to_comparison = model.framework(&["comparison"], "ToDatabaseComparison");
    // The record's shared query vocabulary as this database names it — see
    // `DatabaseBackend::compared`, and `RecordModel::queried_columns` for why a comparison holds a
    // seat for exactly the columns every declared database mints.
    let columns = self.compared(model);

    let held = |column: &PersistColumn| {
      let (filter, stored) = (
        filter_of(model, &column.domain, model.marker_of(&column.source)),
        column.ty(),
      );
      quote!(<#filter as #to_comparison<#stored, #db>>::Comparison)
    };

    // LAYER 1: one member per column, named by the RECORD FIELD — see `PersistColumn::member`,
    // where the split from this database's rendered column name is stated.
    let crossings = self.assumptions(model);
    let mut rows: ::std::vec::Vec<crate::unit::ComparisonColumn> = columns
      .iter()
      .map(|column| crate::unit::ComparisonColumn {
        member: column.member().clone(),
        name: format!("`{}` column", column.name),
        held: held(column),
        gate: model.gate(&column.source),
      })
      .collect();
    // LAYER 1, continued: one member per REVERSE POSITION, after the columns. It is held at the
    // crossing map's projection rather than at `SqlDerivedComparison<…>` for the reason the columns
    // are held at theirs — the item bound is what says the member lowers, so no dialect-specific
    // predicate has to be written into a `where` clause an author cannot edit.
    //
    // AFTER the columns because `new` is positional and a column's ordinal is this database's
    // storage order; appending is what keeps that order the one it always was.
    rows.extend(
      self
        .relations(model)
        .into_iter()
        .map(|row| crate::unit::ComparisonColumn {
          name: format!("`{}` reverse position (`{}`)", row.member, row.source),
          held: self.related_comparison(model, &row),
          member: row.member,
          gate: proc_macro2::TokenStream::new(),
        }),
    );
    // LAYER 1, continued: one member per FORWARD position, after the reverse ones. The wire carries
    // ONE field for a `ref` column and the storage carries two predicates — the foreign key's own,
    // and the semi-join through it — so the second half joins here as a member of its own.
    //
    // LAST, and the placement is `new`'s positional arity again: the columns are this database's
    // storage order, the reverse positions are the declaration's, and appending is what keeps both
    // where they were.
    rows.extend(
      self
        .forwards(model)
        .into_iter()
        .map(|row| crate::unit::ComparisonColumn {
          name: format!(
            "`{}` reference's nested predicate (`{}`)",
            row.column, row.spelling
          ),
          held: self.forward_comparison(model, &row),
          // NO gate: a `ref` field may not be conditional at all — see
          // `ingraph_derive::attribute::refuse_a_conditional_reference` — so the position beside it
          // is present whenever the column is.
          gate: proc_macro2::TokenStream::new(),
          member: row.position,
        }),
    );
    let header = crate::unit::UnitHeader {
      vis,
      name: name.clone(),
      subject: format!("[`{record}`]"),
      note: None,
    };
    let (declaration, methods) = crate::unit::comparison(&header, &db, &crossings, &rows);
    // The LOWERING rides with the struct rather than with the unit: what a comparison RENDERS is
    // this database's, where the shape it renders from is every front end's.
    let lowering = self.lowering(model);
    // The COLLAPSE rides beside the lowering, and for the same reason: what a relation may do with
    // this predicate is decided per database, from this database's own columns.
    let collapse = self.collapse(model);
    (declaration, quote! { #methods #lowering #collapse })
  }

  /// ONE reverse position's member type: the crossing map's projection, at THIS database.
  ///
  /// ```text
  /// <RelatedFilter<…> as ToRelatedComparison<<Source as Record<DB>>::Comparison, DB>>::Comparison
  /// ```
  ///
  /// Every name in it is asked for rather than rebuilt. The far side's PREDICATE is
  /// `Record<DB>::Comparison`, which is the one projection a neighbouring declaration can reach it
  /// through — the same pairing `Record::Row` is, one member over — and the map's own answer is what
  /// turns it into a quantified position without this emitter naming a family's kind.
  fn related_comparison(&self, model: &RecordModel, row: &RelationRow) -> proc_macro2::TokenStream {
    let db = super::parameter("DB");
    let to_related = model.framework(&["comparison"], "ToRelatedComparison");
    let record = model.framework(&["transform"], "Record");
    let (held, source) = (&row.held, &row.path);
    quote!(<#held as #to_related<<#source as #record<#db>>::Comparison, #db>>::Comparison)
  }

  /// ONE forward position's member type: the same map, at the same database, over the far side's
  /// predicate BOXED.
  ///
  /// ```text
  /// <RefFilter<…, …> as ToRelatedComparison<Box<<Target as Record<DB>>::Comparison>, DB>>::Comparison
  /// ```
  ///
  /// # The BOX is here and not on the reverse row, and the difference is which side recurses
  ///
  /// A reverse position's neighbour is the SOURCE, whose own comparison holds no member pointing
  /// back at this record unless it declares a `ref` — and where it does, THIS is the member that
  /// holds it. So the storage-side cycle closes through the forward half, and one pointer at this
  /// member is what makes both types finite. It is the same place the wire puts its own: inside the
  /// widened filter, shared by every reference, rather than restated per target.
  fn forward_comparison(&self, model: &RecordModel, row: &ForwardRow) -> proc_macro2::TokenStream {
    let db = super::parameter("DB");
    let to_related = model.framework(&["comparison"], "ToRelatedComparison");
    let record = model.framework(&["transform"], "Record");
    let (held, target) = (&row.held, &row.target);
    quote! {
      <#held as #to_related<
        ::std::boxed::Box<<#target as #record<#db>>::Comparison>,
        #db,
      >>::Comparison
    }
  }

  /// One relation member's LOWERING SEAT: the position's own filter, and the refinement it reaches
  /// its rendering through — `F` and `ToLoweredRelatedComparison<C, DB>`.
  ///
  /// One function for both directions, and `boxed` is the whole difference — a forward position holds
  /// the far side's predicate behind a pointer, because the two comparisons of a mutual relation each
  /// contain the other.
  ///
  /// # Two halves rather than one spelling, because both are needed and must agree
  ///
  /// The lowering CALLS `<F as Trait<…>>::apply(…)` and its `where` clause STATES `F: Trait<…>`.
  /// Derived here once and assembled by each caller, so a call cannot come to name a far side its
  /// bound did not state — see [`Self::lowering_assumptions`] for the clause and [`Self::lowering`]
  /// for the call.
  fn related_seat(
    &self,
    model: &RecordModel,
    held: &proc_macro2::TokenStream,
    far: &syn::Path,
    boxed: bool,
  ) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
    let db = super::parameter("DB");
    let to_lowered = model.framework(&["comparison"], "ToLoweredRelatedComparison");
    let record = model.framework(&["transform"], "Record");
    let nested = if boxed {
      quote!(::std::boxed::Box<<#far as #record<#db>>::Comparison>)
    } else {
      quote!(<#far as #record<#db>>::Comparison)
    };
    (held.clone(), quote!(#to_lowered<#nested, #db>))
  }

  /// The FORWARD positions THIS database's comparison carries a member for.
  ///
  /// [`Self::relations`]'s twin, under the same two conditions and for the same two reasons: the SQL
  /// family only, because the crossing that builds one names a family's own kind, and a wire face
  /// only, because the member exists to receive an arm a client wrote.
  ///
  /// # THIS DATABASE's, because a comparison is a lowering
  ///
  /// The wire's list is the DECLARATION's — a narrowed `ref` column keeps its widened filter field,
  /// like every other narrowed column — and this one is that list less the columns this database has
  /// not got. A semi-join needs a column of THIS row to correlate on, and a database the reference
  /// was narrowed out of has none; what a client that wrote the arm anyway gets is the crossing's
  /// own named refusal, at the column, before any member is built.
  pub(super) fn forwards(&self, model: &RecordModel) -> Vec<ForwardRow> {
    if !self.kind().is_sql() {
      return Vec::new();
    }
    model
      .graphql
      .as_ref()
      .map(|graphql| {
        graphql
          .forward_rows(model)
          .into_iter()
          .filter(|row| self.stores(&row.column).is_some())
          .collect()
      })
      .unwrap_or_default()
  }

  /// The REVERSE positions THIS database's comparison carries a member for.
  ///
  /// # Two conditions, and each is a missing TYPE rather than a policy
  ///
  /// The SQL family only, because the two families' reverse kinds take different constructors —
  /// `SqlDerivedComparison::new` a `RelatedRow` and MongoDB's a `MongoRelatedDocument` — and the
  /// crossing that builds one has to name a family's own. What the crossing map makes family-blind
  /// is the member's TYPE, not its construction; the mongo half is letter B.
  ///
  /// And a wire face, because the member is held at a projection through the far side's FILTER
  /// (`RelatedFilter<<Source as Graphql>::Input::Filter>`) — a record with no `graphql(…)` block has
  /// no such type to name, and the position it declared has nothing to be a predicate over.
  pub(super) fn relations(&self, model: &RecordModel) -> Vec<RelationRow> {
    if !self.kind().is_sql() {
      return Vec::new();
    }
    model
      .graphql
      .as_ref()
      .map(|graphql| graphql.relation_rows(model))
      .unwrap_or_default()
  }

  /// What a comparison over these columns ASSUMES, and what every item that names it repeats
  /// verbatim: that the database is a `Backend` at all, and that each column's filter crosses
  /// into something for it.
  ///
  /// One function rather than one per item, because the identity is load-bearing rather than tidy.
  /// The struct's `where` clause is the whole of what makes its field types well formed; an impl
  /// asserting anything MORE would report a declaration's missing crossing twice, and one asserting
  /// anything less would not apply to the type it is written for.
  ///
  /// `Db: Backend` leads because it is not elaborated from the rest: a `where F:
  /// ToDatabaseComparison<V, Db>` names a trait whose own parameter is bounded that way, so the
  /// predicate is owed at every caller that writes the crossing, and it is a claim about the
  /// DATABASE rather than about any column.
  ///
  /// # A `flatten` column states the REFINED crossing, and only it
  ///
  /// `ToFlattenedComparison<V, Db>` is `ToDatabaseComparison<V, Db>` plus *the comparison occupies more
  /// than one column*, and it carries the crossing as its SUPERTRAIT, so a marked column states ONE
  /// bound and the plain crossing arrives by elaboration. That is the whole of the refusal: a
  /// scalar's comparison does not implement `CompositeComparison`, so a scalar marked `flatten` has
  /// no crossing and the framework's own wording says why.
  ///
  /// Written as a REFINEMENT rather than as a second predicate beside the plain one, because the
  /// requirement cannot be spelled with the comparison as its self type at all — see `ingraph`'s
  /// `ToFlattenedComparison` for what a projection-headed bound resolves to at a generic `Db`, which is
  /// the same wall that keeps `Debug` off this struct.
  pub(crate) fn assumptions(&self, model: &RecordModel) -> proc_macro2::TokenStream {
    let db = super::parameter("DB");
    let backend = model.framework(&["comparison"], "Backend");
    let to_comparison = model.framework(&["comparison"], "ToDatabaseComparison");
    let to_flattened = model.framework(&["comparison"], "ToFlattenedComparison");
    let crossings = self.compared(model).into_iter().map(|column| {
      let (filter, stored) = (
        filter_of(model, &column.domain, model.marker_of(&column.source)),
        column.ty(),
      );
      let crossing = if column.flatten {
        &to_flattened
      } else {
        &to_comparison
      };
      quote!(#filter: #crossing<#stored, #db>,)
    });
    // What a REVERSE position assumes, and it is three claims about the SOURCE rather than about
    // this record: that it is stored in this database at all (so `Record<DB>::Comparison` names a
    // predicate), that it has a wire face (so its filter is a type), and that the position's own
    // crossing answers. All three are stated because a `where` clause carrying a projection has to
    // name the bounds that make it well formed — and each is a refusal that lands on the `derived`
    // entry rather than inside the expansion.
    let graphql = model.framework(&["transform"], "Graphql");
    let graphql_input = model.framework(&["transform"], "GraphqlInput");
    let record = model.framework(&["transform"], "Record");
    let to_related = model.framework(&["comparison"], "ToRelatedComparison");
    let relations = self.relations(model).into_iter().map(|row| {
      let (held, source) = (&row.held, &row.path);
      quote! {
        #source: #record<#db> + #graphql,
        <#source as #graphql>::Input: #graphql_input,
        #held: #to_related<<#source as #record<#db>>::Comparison, #db>,
      }
    });
    // What a FORWARD position assumes, and it is the same three claims about the TARGET one
    // direction over — that it is stored in this database, that it has a wire face for its filter to
    // be a type, and that the position's own crossing answers. The crossing is asked over the BOXED
    // predicate, which is the type the member really holds.
    let forwards = self.forwards(model).into_iter().map(|row| {
      let (held, target) = (&row.held, &row.target);
      quote! {
        #target: #record<#db> + #graphql,
        <#target as #graphql>::Input: #graphql_input,
        #held: #to_related<::std::boxed::Box<<#target as #record<#db>>::Comparison>, #db>,
      }
    });
    quote! {
      #db: #backend,
      #(#crossings)*
      #(#relations)*
      #(#forwards)*
    }
  }

  /// [`Self::assumptions`] plus the one fact a LOWERING needs and a well-formed struct does not:
  /// that each RELATION member really renders.
  ///
  /// # It is the promise the crossing map used to keep, moved to where it is spent
  ///
  /// `ToRelatedComparison::Comparison` carried `ComplexComparison<Db>` as an item bound, so the fact
  /// arrived free wherever the projection was named. **That is what made the ordinary mutual pair
  /// `E0275`**: an item bound is a promise every ROW must keep, the SQL row kept it by demanding the
  /// far side's own lowering, and a `ref` one way with a `derived` the other closes that into a
  /// cycle — measured, at both declarations, as an overflow on the neighbour's very SIZE.
  ///
  /// Stated HERE it is one predicate per member at ONE impl, and it names no dialect: the self type
  /// is the position's own FILTER, so nothing normalises until a caller reaches the impl at a
  /// concrete backend. There the far side's demand terminates at the neighbour's own CONCRETE
  /// [`collapse`](Self::collapse) impl in a single step.
  ///
  /// # NOT on the struct, and that is the load-bearing half
  ///
  /// A struct's `where` clause is proven wherever the type is NAMED, so the same predicate there
  /// re-opens exactly the chain this removes. So the two clauses genuinely differ now, and the rule
  /// the unit's own note states — *an impl asserting anything MORE would report a missing crossing
  /// twice* — holds for the crossings and not for this: nothing else asserts that a relation member
  /// renders, so there is no second report to make.
  ///
  /// Read by [`Self::lowering`] and by [`Self::comparison_traits`], whose own map DOES keep an item
  /// bound and therefore has to prove the whole comparison lowers.
  fn lowering_assumptions(&self, model: &RecordModel) -> proc_macro2::TokenStream {
    let assumptions = self.assumptions(model);
    let relations = self
      .relations(model)
      .into_iter()
      .map(|row| self.related_seat(model, &row.held, &row.path, false))
      .collect::<Vec<_>>();
    let forwards = self
      .forwards(model)
      .into_iter()
      .map(|row| self.related_seat(model, &row.held, &row.target, true))
      .collect::<Vec<_>>();
    let members = relations
      .into_iter()
      .chain(forwards)
      .map(|(held, bound)| quote!(#held: #bound,));
    quote! {
      #assumptions
      #(#members)*
    }
  }

  /// The comparison's LOWERING: `ComplexComparison`, threading one accumulator through the columns.
  ///
  /// # It needs no predicate the struct did not already carry
  ///
  /// That is the whole reason this can be written at all, and it is recent. Each field is held at
  /// `<F as ToDatabaseComparison<V, Db>>::Comparison`, and the map's ITEM BOUND —
  /// `type Comparison: ComplexComparison<Db>` — is what says such a field lowers. A bound stated
  /// HERE instead could not: a projection with a concrete self type resolves through the impl that
  /// defines it, so the bound would demand whatever that impl demands of `Db` — `sqlx::Database`
  /// for most kinds, `CollectionStorage<V>` for the two a collection column crosses through — and
  /// no single spelling serves both. On the associated type the obligation sits with the party that
  /// can discharge it, which is the row for the concrete dialect.
  ///
  /// # The record's comparison is the COMPOSITE case
  ///
  /// It is handed ONE address and each column PUSHES A FRAME below it — its own external name, the
  /// same string the row's decode reads it under, so the predicate and the row name one column and
  /// not two. The frame is a local because the child address borrows it; two lines per column, and
  /// no name is built anywhere.
  ///
  /// What the record's own address is, is the caller's: at the TOP LEVEL it names no column, so the
  /// columns render bare — `title` rather than `media_title` — and a record nested under a field
  /// renders its columns beneath that field's segments. Under a single name there was no argument
  /// that produced the first of those.
  ///
  /// # `flatten` is the ABSENCE of the frame, and nothing else anywhere reads it
  ///
  /// A marked column is handed the address its parent was handed, unchanged, so whatever its
  /// comparison pushes lands at the parent's level: `rate: Timebase` marked `flatten` renders
  /// `num`/`den` where the same field unmarked renders `rate_num`/`rate_den`. There is no
  /// `flatten`-aware code below this line and no kind can tell — a comparison renders at the address
  /// it receives, which is the same contract at every depth.
  ///
  /// It follows that a marked column emits ONE statement rather than two, and the frame local is
  /// simply not bound. Nothing has to suppress a name that was never made.
  ///
  /// Nothing else in the address varies per column: the ROW is the same row for every one of them,
  /// which is what lets this walk carry one value and push only a segment. A column whose predicate
  /// is CORRELATED reads that row and the emitter writes no special case for it — which it could
  /// not, since `Vec<T>` behind an alias is indistinguishable from a scalar in the tokens this
  /// sees.
  ///
  /// A database that stores no column lowers to nothing and says so: no conjunct, the accumulator
  /// handed straight back, and the address left unbound rather than bound and unused.
  fn lowering(&self, model: &RecordModel) -> proc_macro2::TokenStream {
    let seats = crate::unit::LoweringSeats {
      backend: model.framework(&["comparison"], "Backend"),
      complex: model.framework(&["comparison"], "ComplexComparison"),
      frame: model.framework(&["comparison"], "Frame"),
      at: model.framework(&["comparison"], "At"),
      field_name: model.framework(&["field"], "FieldName"),
    };
    let mut rows: ::std::vec::Vec<crate::unit::LoweringColumn> = self
      .compared(model)
      .into_iter()
      .map(|column| crate::unit::LoweringColumn {
        member: column.member().clone(),
        rendered: column.name.to_string(),
        flatten: column.flatten,
        through: None,
        gate: model.gate(&column.source),
      })
      .collect();
    // A REVERSE position pushes NO FRAME, which is what `unframed` says: it names no column of this
    // row — only the child's foreign key and this row's id, both known without it — so it renders at
    // the address it is handed, exactly as a `flatten` column does. Two words, one emitted shape,
    // and the reason each takes it is its own.
    rows.extend(self.relations(model).into_iter().map(|row| {
      let (held, bound) = self.related_seat(model, &row.held, &row.path, false);
      crate::unit::LoweringColumn::unframed(row.member, quote!(<#held as #bound>))
    }));
    // A FORWARD position is FRAMED, and by the same name its column is: the semi-join renders at the
    // FOREIGN KEY — `"cover_id" IN ( SELECT … )` — so the address it needs is the column's own, and
    // the frame is what puts it there. That is the opposite of a reverse position, which names no
    // column of this row at all.
    let framed: ::std::collections::HashMap<syn::Ident, String> = self
      .compared(model)
      .into_iter()
      .map(|column| (column.member().clone(), column.name.to_string()))
      .collect();
    rows.extend(self.forwards(model).into_iter().map(|row| {
      let (held, bound) = self.related_seat(model, &row.held, &row.target, true);
      crate::unit::LoweringColumn::framed(
        row.position,
        framed.get(&row.column).cloned().unwrap_or_default(),
        Some(quote!(<#held as #bound>)),
      )
    }));
    crate::unit::comparison_lowering(
      self.comparison_name(),
      &super::parameter("DB"),
      &self.lowering_assumptions(model),
      &seats,
      &rows,
    )
  }

  /// The COLLAPSE: `CollapsibleComparison`, handing back this row's constraint on its own id when
  /// the id is all it constrains.
  ///
  /// # What it buys, and where the answer is spent
  ///
  /// A relation over a to-one reference is a semi-join —
  /// `fk IN ( SELECT id FROM target WHERE <nested> )` — and when the nested predicate constrains
  /// nothing but the target's id, that subquery answers the same rows as the predicate applied to
  /// `fk` directly. `SqlRefComparison` asks this on every apply and renders the collapsed form
  /// wherever it gets a `Some`; `MongoRefComparison` asks the same question of the same trait.
  ///
  /// # The second half of the law is a BOUND, because a generic body cannot read an operator
  ///
  /// The trait's law has two halves. *Every other field is empty* this body reads directly — the
  /// members are its own and `ComplexComparison::is_empty` answers for each. *The id's own
  /// operators survive the substitution* it cannot: the id's comparison arrives as a PROJECTION
  /// through `ToDatabaseComparison`, so the type is opaque to this body and the only thing it can do
  /// with a value of one is call a trait method. So the impl carries one projection-headed predicate
  /// — bounded by `ReferentialComparison` — and calls the method it buys. A declaration whose id
  /// crosses into a kind that cannot answer gets `E0277` at the POSITION that wanted the collapse,
  /// rather than a comparison that silently declines to optimise for a reason nothing reports.
  ///
  /// # It names the BACKEND CONCRETELY, and that is forced rather than chosen
  ///
  /// Written at a generic `DB` this does not compile, and the module note above already said why
  /// about a different bound: *a projection with a concrete self type resolves through the impl that
  /// defines it, so the bound would demand whatever that impl demands of `Db`*. Measured here, that
  /// is exactly what happens — `<ScalarFilter<u32> as ToDatabaseComparison<u32, DB>>::Comparison:
  /// ReferentialComparison<DB>` sends rustc to `ScalarFilter`'s own row for the normalisation, whose
  /// `where` clause wants `DB: sqlx::Database` and `u32: Carrier<DB>`; neither is available at a
  /// parameter, and the errors land inside an expansion naming the record's own attribute. The
  /// assumption in the param env does not win, because the self type is concrete.
  ///
  /// At a concrete backend the projection NORMALISES and the predicate becomes an ordinary claim
  /// about an ordinary type. This is [`Self::vocabulary`]'s shape and it is taken for the same
  /// reason — including its gate, so the impl exists per DECLARED ∩ COMPILED-IN backend and a
  /// declaration naming three databases in a build carrying one is not asked about the other two.
  ///
  /// It states no `where` clause of the struct's own, also for `vocabulary`'s reason: at a concrete
  /// backend those are well-formedness obligations checked here, and repeating them would report a
  /// declaration's missing crossing a second time.
  ///
  /// An unsatisfied predicate does NOT make this impl an error where it stands. An impl whose
  /// `where` clause does not hold simply does not apply, so a declaration that never puts its record
  /// behind a relation compiles exactly as before and the id's kind is never asked about.
  ///
  /// # A database that does not STORE the id emits nothing
  ///
  /// The collapse hands back a constraint on a column, and a row without the id column has none to
  /// hand back. That is the same condition `queryable` guards the whole query face with, read here
  /// off this database's own columns rather than off the stored list, because what has to be found
  /// is the MEMBER this comparison holds.
  fn collapse(&self, model: &RecordModel) -> proc_macro2::TokenStream {
    // The comparison's OWN members, which is what `only_id` reads — see
    // [`DatabaseBackend::compared`](super::DatabaseBackend::compared), and
    // [`RecordModel::queried_columns`] for the law that decides which columns have a seat here. A
    // column with no seat constrains nothing BY CONSTRUCTION, so leaving it out of the *every other
    // field is empty* test is the honest reading rather than a narrowing.
    let columns = self.compared(model);
    let id = model.key.id.source.clone();
    let Some(id_column) = columns.iter().find(|column| column.source == id) else {
      return proc_macro2::TokenStream::new();
    };

    let backend = self.backend_type(model);
    let (collapsible, referential, complex, to_comparison) = (
      model.framework(&["comparison"], "CollapsibleComparison"),
      model.framework(&["comparison"], "ReferentialComparison"),
      model.framework(&["comparison"], "ComplexComparison"),
      model.framework(&["comparison"], "ToDatabaseComparison"),
    );
    let (filter, stored) = (
      filter_of(model, &id_column.domain, model.marker_of(&id_column.source)),
      id_column.ty(),
    );
    let held = quote!(<#filter as #to_comparison<#stored, #backend>>::Comparison);

    // The OTHER columns, each asked whether it constrains anything. The id is excluded by MEMBER
    // rather than by index: one list is the record's stored columns and the other is this
    // database's, and a member name is the one key no rename can move.
    // Each *other field* the trait's law is about, paired with the CONDITION its column wrote. A
    // REVERSE POSITION is one of them — a predicate holding a live quantifier constrains the child
    // table and not this row's id, so collapsing it onto a foreign key would drop the whole
    // correlated subquery and answer a different question — and so is a FORWARD one, whose live
    // nested predicate constrains the TARGET's columns. The column half of a `ref` is not excluded:
    // it is an ordinary predicate on an ordinary column.
    //
    // The id is excluded by MEMBER rather than by index: one list is the record's stored columns and
    // the other is this database's, and a member name is the one key no rename can move.
    let others: Vec<(proc_macro2::TokenStream, syn::Ident)> = columns
      .iter()
      .filter(|column| column.source != id)
      .map(|column| (model.gate(&column.source), column.member().clone()))
      .chain(
        self
          .relations(model)
          .into_iter()
          .map(|row| (proc_macro2::TokenStream::new(), row.member)),
      )
      .chain(
        self
          .forwards(model)
          .into_iter()
          .map(|row| (proc_macro2::TokenStream::new(), row.position)),
      )
      .collect();
    let member = id_column.member();
    let name = self.comparison_name();
    let gate = model.framework(&["gate"], &self.kind().gate().to_string());
    // TWO SHAPES, and the condition chooses. An OPERAND of `&&` is not an attribute position —
    // `#[cfg(…)] a && b` is not Rust — so where any column is conditional the conjunction is
    // ACCUMULATED in statements a gate can sit on. Where none is, the chain is the one it has always
    // been, `&&` for `&&`.
    let conditional = others.iter().any(|(gate, _)| !gate.is_empty());
    let (accumulated, collapses) = if conditional {
      let terms = others.iter().map(|(gate, member)| {
        quote! {
          #gate
          {
            __ingraph_others_empty &= #complex::<#backend>::is_empty(&self.#member);
          }
        }
      });
      (
        // A PRELUDE rather than a block inside the condition: `if { … } { … }` reads the FIRST brace
        // as the body, so the accumulation is spelled as statements ahead of the `if` and what the
        // `if` takes stays an expression.
        quote! {
          let mut __ingraph_others_empty = true;
          #(#terms)*
        },
        quote!(__ingraph_others_empty && #referential::<#backend>::is_referential(&self.#member)),
      )
    } else {
      let terms = others
        .iter()
        .map(|(_, member)| quote!(#complex::<#backend>::is_empty(&self.#member) &&));
      (
        proc_macro2::TokenStream::new(),
        quote!(#(#terms)* #referential::<#backend>::is_referential(&self.#member)),
      )
    };
    quote! {
      #gate! {
        #[automatically_derived]
        impl #collapsible<#backend> for #name<#backend>
        where
          #held: #referential<#backend>,
        {
          type Id = #held;

          #[inline]
          fn only_id(&self) -> ::core::option::Option<&Self::Id> {
            #accumulated
            if #collapses {
              return ::core::option::Option::Some(&self.#member);
            }
            ::core::option::Option::None
          }
        }
      }
    }
  }

  /// The comparison's TRAIT face: the type-level map a filter reaches it through.
  ///
  /// # `ToDatabaseComparison`, keyed on the ROW
  ///
  /// `ToDatabaseComparison<V, Db>` answers *what does a filter of this kind cross into, for this
  /// storage type, on this backend*. A COLUMN's filter answers it with the column's stored type; an
  /// RECORD's filter answers it with the ROW — one record filter, one comparison per database, and
  /// the row type is exactly what tells the two apart. So a declaration storing a record in three
  /// databases gets three impls that cannot collide, and a caller names which one it means by
  /// naming the row rather than by spelling the comparison type.
  ///
  /// The `where` clause is the STRUCT's, verbatim: the impl asserts nothing the type does not
  /// already assume, so a declaration whose column has no crossing gets one error at the struct
  /// rather than a second one here.
  ///
  /// # The map keeps a PROMISE, and that is why the lowering is emitted at all
  ///
  /// `ToDatabaseComparison::Comparison` carries an item bound — `ComplexComparison<Db>` — so this
  /// impl is well formed only where the comparison it names really lowers. That obligation is
  /// discharged by [`Self::lowering`], emitted beside the struct; without it every declaration with
  /// a wire face fails at the derive on `XComparison<Db>: ComplexComparison<Db>`. The bound is the
  /// map's own, so nothing here states it.
  ///
  /// # The one trait that is NOT here, and the wall it hits
  ///
  /// `TryFromFilter` — the crossing, from a filter INTO this comparison — needs a bound on
  /// `<F as ToDatabaseComparison<V, Db>>::Comparison` that no item bound carries. rustc resolves a
  /// projection whose self type is concrete through the impl that defines it, so a bound stated
  /// here demands whatever that impl demands of `Db` — `sqlx::Database` for most kinds, and
  /// `CollectionStorage<V>` for `ListFilter`, which a `Vec<T>` column crosses through. One
  /// spelled bound cannot serve both, and the emitter may not ask which a column is: it sees the
  /// type's TOKENS, and `Vec<Uuid7>` may be an alias for either.
  ///
  /// **Half of that wall has come down and the record should say which.** It used to read that
  /// moving the crossing onto the map as a second item bound was REFUTED, because a collection's
  /// crossing lands on `SqlEdgeComparison` wherever a dialect keeps a value list in an edge table
  /// and that comparison was constructed WITH its addressing — none of which is in a filter. It no
  /// longer is: the addressing arrives at `apply`, through `At`, and `SqlEdgeComparison` implements
  /// `TryFromFilter` like every other kind. So a comparison that cannot be built from a filter alone
  /// is not what stands in the way any more.
  ///
  /// What still does is the paragraph above — a bound spelled HERE resolves through the defining
  /// impl — so whether the MAP can carry a second item bound is now the whole of the question, and
  /// it is open rather than refuted.
  ///
  /// **The wall is about the DIALECT, and that has been measured.** An INTERFACE's expansion writes
  /// the crossing today, because its comparison is reached at a CONCRETE backend — the one its own
  /// engine face already names — and there every projection normalises: the comparison resolves to a
  /// kind, that kind's `TryFromFilter` row is available, and its inherent `try_from_filter_with` is
  /// callable. The same impl at a generic `Db` fails with exactly the four errors above, verbatim.
  /// So what keeps the crossing off a RECORD's comparison is that the comparison is generic on
  /// purpose — a declaration storing one dialect must not need that dialect's driver to compile.
  ///
  /// **This note ended on *a per-dialect crossing beside a dialect-generic type is a shape nobody has
  /// ruled*, and that shape is ruled now.** It is [`super::cross`]: the crossing is emitted PER
  /// DECLARED ∩ COMPILED-IN backend, inside that backend's own gate, at the concrete
  /// `<E><Db>Comparison<Sqlite>` — which is a type this emission already names concretely one impl
  /// away, in [`Self::vocabulary`]'s `Record<Db>` binding. Nothing about the map below moves: it
  /// stays generic, it stays the type-level question, and the value-level crossing sits beside it at
  /// a dialect somebody actually compiled.
  pub(crate) fn comparison_traits(&self, model: &RecordModel) -> proc_macro2::TokenStream {
    let Some(graphql) = model.graphql.as_ref() else {
      return proc_macro2::TokenStream::new();
    };
    let name = self.comparison_name();
    let row = self.name();
    let db = super::parameter("DB");
    let filter = graphql.filter.safe();
    let to_comparison = model.framework(&["comparison"], "ToDatabaseComparison");
    // The LOWERING's clause rather than the struct's: THIS map keeps an item bound
    // (`Comparison: ComplexComparison<Db>`), so the impl has to prove the comparison it names really
    // renders — which for a record holding a relation member is a fact only
    // `Self::lowering_assumptions` supplies. See its note for why the same predicate must NOT ride
    // the struct.
    let crossings = self.lowering_assumptions(model);
    quote! {
      #[automatically_derived]
      impl<#db> #to_comparison<#row, #db> for #filter
      where
        #crossings
      {
        type Comparison = #name<#db>;
      }
    }
  }
}