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
//! Model in, tokens out.
//!
//! **Twenty-three AUTHORISED framework trait implementations, and no other.** The rule was *none of any
//! kind*, because the framework's trait layer was moving and an expansion that named a half-settled
//! trait would owe every consumer a revision the day it settled. That layer has settled for
//! `ToDatabaseComparison`, the type-level map from a filter to the comparison it crosses into, so
//! the rule lifted for that item; and the map's own ITEM BOUND — `Comparison: ComplexComparison<Db>`
//! — then made the lowering the second, because an expansion that names the map has to keep the
//! promise the map makes. INHERENT impls were never covered by the rule: they bind nothing in the
//! framework and are stable whatever that layer becomes, so `new` and the accessors are emitted.
//!
//! `Transformer` is the third, and it settled differently from the other two: what it binds is
//! entirely the emitter's OWN output. Its faces are the `*Key` written here, the `*Lineage` beside
//! it and the record itself — no consumer type, no backend type, nothing this emission does not also
//! declare or sit on. An expansion naming it therefore owes a revision to nobody the emission was
//! not already going to move.
//!
//! `Record` is the fourth and stands on the third's ground: it is the settled VOCABULARY the entity
//! binding's row-form member answers, and what an impl of it binds is the `<Row>Comparison` this
//! emission also declares. It differs in one way that matters — its argument is a CONCRETE backend,
//! the only one the emission names — and that is what makes it the storability audit and what makes
//! it ride a gate. See [`DatabaseBackend::vocabulary`].
//!
//! `Related<Target>` and `Reference` are the fifth and sixth, admitted on the third's ground and
//! on one more of their own: a relation is declared in TWO derives that cannot see each other, so
//! the pairing is the only way a reverse declaration's audit can reach the forward one's fields.
//! What they bind is the emission's own artifacts and the paths the declaration itself wrote. See
//! [`relate`].
//!
//! `Identifiable` is the seventh and the eighth — the SAME trait twice, because it is admitted on
//! two self types and the allowlist is a (trait, self type) pair rather than a trait. It is
//! `Transformer`'s supertrait, so an expansion naming the entity binding has to name it or the
//! binding is not well formed, and what it binds is the declared type of the key's last column: the
//! third's ground, one member of it. One impl is on the RECORD and one on the `*Key` — the two types
//! the emission gives that column to. See [`RecordModel::binding`].
//!
//! `KeySegments` is the ninth, and it is on the `*Key` — the second impl that type carries. What it
//! binds is the third's ground again: the key written here, walked into a sink the framework owns,
//! with nothing named that this emission did not also declare. It is the filesystem blob store's
//! own key requirement, and it is emitted because the store's seam says so — that seam KEEPS the
//! full key, since a directory tree nested by lineage is browsable where a flat one is not. The
//! sentence in `ingraph`'s `store::fs` promising the derive emits it is what this makes true. See
//! [`RecordModel::address_segments`].
//!
//! The ORDER is not a tenth impl. It was one — `Orderable` on the RECORD, with a condition of its
//! own where the nine before it ride whatever condition already emitted the type they bind — and it
//! is retired: the order is a MEMBER of the `Record<Db>` vocabulary now, so it rides that impl's
//! condition and a record stored nowhere has neither the row, the comparison nor the order. See
//! [`DatabaseBackend::vocabulary`], which is where all three are bound.
//!
//! `Implements<Interface>` is the fourteenth, on the RECORD, admitted on the fifth and sixth's
//! ground alone: a membership is declared in two derives that cannot see each other, so the record's
//! `implements(…)` is the only way an interface's expansion can know its member agreed. It carries
//! nothing — a relation needs the referring fields crossing that boundary, and a membership needs
//! only the fact — and what it binds is a path the declaration itself wrote. See [`relate`].
//!
//! `Graphql`, `GraphqlInput` and `GraphqlOutput` are the eleventh, twelfth and thirteenth, admitted
//! on the third's ground and on the fifth and sixth's: the two halves' impls are on CARRIERS this
//! emission mints, exactly as the pairing's are on artifacts it mints, and an expansion that writes
//! the face has to write them or the face names types answering nothing. What they bind is the
//! filter, the key output and the order-by this emission also declares. Conditional like the tenth,
//! on the block's presence. See [`RecordModel::wire_binding`].
//!
//! The TOPOLOGY family is the fifteenth through nineteenth, and it stands on the third's ground with
//! one addition of its own: `Emits<N>` and `SoleProduct` on the RECORD are how a node states what it
//! puts on an edge, which is the ONE fact a downstream declaration cannot read for itself — the
//! fifth and sixth's argument seen from the other end of the edge. `Products` and `ProductKind` are
//! on the product sum and its vocabulary, and `Sink<Out>` is on the DOWNSTREAM: all three are types
//! this emission declares, so what they bind is its own output. Conditional on `emits` naming
//! several, exactly as the tenth is conditional on its block. See [`topology`].
//!
//! `Describe<Db>` is the TWENTY-THIRD, on the RECORD, and it stands on the fourth's ground with the
//! fourth's own argument: the SCHEMA a migration creates this record's storage from, built out of
//! what the row's `SqlQuery` binding already publishes — its address and its column shapes — with
//! each field's `StoredAs<Db>` word and its nullability beside them. It names the backend
//! CONCRETELY and rides that dialect's gate for `Record<Db>`'s reason, and it carries one condition
//! of its own on top of the query face's: a collection this database keeps in a COLUMN has no word
//! to be declared at, so that database gets no blueprint. See [`query`], where the roster is.
//!
//! `Declared` is the TWENTIETH, on the RECORD, and it is the only one on this list whose reason is
//! a party OUTSIDE the declaration that emits it. What it binds is nothing at all — an effect, a
//! lane, a table of upstreams, an options path and a shelf — but a graph root sees a field's TYPE
//! and no more, so a node's own facts have to reach it as an impl or the root's entry can name none
//! of them. It is the other side of the same wall the fifth and sixth cross, one organ up: those
//! carry a fact between two node declarations, and this carries one from a node to the root that
//! mounts it. See [`declared`].
//!
//! The line is not left to memory. `tests::the_emission_declares_only_the_authorised_trait_impl`
//! reads the emission back and fails on any framework trait impl that is not
//! `ToDatabaseComparison<Row, Db>` on the record's own filter, keyed on a row a declared database
//! really stores, `ComplexComparison<Db>` on a comparison that same model names, `Transformer` on
//! the record itself, `Record<Db>` on it keyed on a backend a declared database really is,
//! `Related<Target>` on the record at a target the model's own `ref` names, `Reference` on an
//! artifact the emitter mints for one of those fields, `Identifiable` on the record or on the
//! `*Key` the model names, `KeySegments` on that same `*Key`, `Graphql` on the
//! record, or `GraphqlInput`/`GraphqlOutput` on the carrier the emitter mints for each half — self
//! type and argument both checked against the MODEL, so an authorised trait on the wrong type is
//! refused exactly as a fourteenth would be. The walk OPENS the gates first, so wrapping an impl in
//! one is not a way past the rule.
//!
//! **`TryFromFilter` is the one that stays absent HERE, and the reason is the DIALECT.** A record's
//! comparison is generic in its database and stays that way, so the crossing would need a bound on
//! `<F as ToDatabaseComparison<V, Db>>::Comparison` that no item bound carries — see
//! [`DatabaseBackend::comparison_traits`] for what was measured, and why the LOWERING is reachable
//! where the crossing is not.
//!
//! An INTERFACE's expansion writes it, and nothing about the wall moved: an interface's engine face
//! is per database already — the row equations, `SqlInterface` and the hydration all name a concrete
//! backend and ride its gate — so its crossing is stated at that backend, where every projection
//! normalises and the bound is not owed. See `crate::interface::cross`. Whether a RECORD could be
//! given the same treatment is a real question this does not answer: its comparison is generic on
//! purpose, so the crossing would have to be per dialect where the type is not.
//!
//! ## What is emitted
//!
//! Three inherent impls at most: the `*Key`'s, the `*Lineage`'s, and the RECORD's own. The first
//! two come with a struct each; the record already exists — the derive only adds methods to it.
//!
//! The record also gets its ENTITY BINDING — `impl Transformer for Record` — naming those two
//! emitted types, the row form the declaration asked for and the wire face it declared, with
//! `impl Identifiable` beside it on the record and on the `*Key`, each binding the id column's
//! declared type. Every record has all three, a root included: a root has no `*Lineage` to name, so
//! it binds `()`; a record that persists nowhere binds `()` for its row form; and a record with no
//! `graphql(…)` block binds `()` for its wire face. The `*Lineage` is identified by nothing — a
//! chain of ancestors has no one id.
//!
//! ONE CONDITIONAL binding rides beside that total one, and it is conditional because what it names
//! is. An EXPOSED record gets `impl Graphql for Record` with a carrier per half — `<E>GraphqlInput`
//! naming the filter and the order-by, `<E>GraphqlOutput` naming the key output — minted in the
//! const on the relation artifacts' terms. The STORED half of the pair this used to describe is no
//! longer a binding of its own: a stored record's order rides its `Record<Db>` impl. A record
//! meeting neither condition implements neither, which is what a
//! projection through the missing impl refuses on.
//!
//! The `*Key` gets one more of its own: `impl KeySegments`, walking its columns into a path, root
//! first and the id last. That is the address the local filesystem blob store nests directories by,
//! and it is emitted for every declaration rather than for the ones that store bytes — see
//! [`RecordModel::address_segments`] for why, and for the vocabulary bound it lands under.
//!
//! A declaration stating RELATIONS gets more, all of it inside the same const: one id equation per
//! `ref` field, one pairing per target it names, an artifact per referring field, and one audit per
//! `derived(…)` position. [`relate`] carries the whole of that story.
//!
//! Each emitted type also gets a PAIR of conversions from the record: `From<Record>`, which moves
//! its columns out, and `From<&Record>`, which clones them. Two rather than one because the choice
//! is the caller's and should be visible at the call site — `TrackAddress::from(track)` gives the
//! record up, `TrackAddress::from(&track)` pays for a clone and keeps it. Neither can be `const`;
//! a trait method cannot be. They need no bound of their own: the emitted struct derives `Clone`,
//! so its column types are `Clone` by construction.
//!
//! **No constructor on the record.** A real aggregate has twenty-odd fields, so a positional `new`
//! would be unusable and transposition-prone; and the product schema hand-writes VALIDATING
//! constructors (`try_new` rejecting nil ids) that a macro cannot replicate from a declaration.
//! The application keeps its own constructor; this emits accessors and mutators only.
//!
//! A declaration that WRAPS a foreign type gets one family more, and two of the above change their
//! bodies rather than their shape: the reference family and the two conversions over the wrapped
//! type, and readers and a raise that go through that type's own accessors and constructor. All of
//! it is `crate::remote`'s, including why none of it lands on this list — the family is `core`'s
//! traits over a type the declaration names, and the allowlist above is about the FRAMEWORK's.
//!
//! ## The shape of an emitted type, and why
//!
//! **Private fields, with accessors.** A key is a value type with a construction path, not a
//! transparent carrier whose representation is the API.
//!
//! **One `new`, positional, in key order** — lineage root-first, then the id. A key has exactly
//! one unsurprising way to be built, so there are no named constructors and no builder: a builder
//! guards invariants, and a key has none — every combination of ids is a valid address, whether or
//! not a row lives at it. No `Default` either; a default key is a nil address. `new` is `const`
//! for every column shape, because moving a value into a struct drops nothing.
//!
//! **The mutators are the repository's pair**: `set_x(&mut self, T) -> &mut Self` to change one in
//! place and chain, `with_x(mut self, T) -> Self` to derive a neighbouring key from this one.
//! `with_*` carries `#[must_use]` — it returns the change rather than applying it, so dropping the
//! result is always a mistake. There is no `clear_*` and no `*_mut`: a key's columns are all
//! required, and handing out `&mut` to one would let a caller mutate a live map key in place.
//!
//! Both take `T` rather than `impl Into<T>`. A `const fn` cannot call `Into::into`, so an
//! `Into`-taking setter could not be `const` for a marked column — and splitting the signature by
//! markedness would make the two forms differ in more than constness, which is the one axis the
//! marker is meant to control. This is a deliberate divergence from the hand-written style in the
//! product schema.
//!
//! ## How a field is handed out
//!
//! The projections are the product schema's, reproduced rather than invented (`mediaschema`
//! `video/facet.rs`, `media.rs`):
//!
//! | field type | accessor | schema |
//! |---|---|---|
//! | `#[ingraph(repeated)]` | `x_slice(&self) -> &[<T as Repeated>::Item]` | `video/facet.rs:115` |
//! | `#[ingraph(optional)]` | `x_ref(&self) -> Option<&<T as Optional>::Item>` | `media.rs:197` |
//! | unmarked | `x_ref(&self) -> &T` | `video/facet.rs:121` |
//! | `#[ingraph(copy)]` | `x(&self) -> T`, IN ADDITION to the borrow | `video/facet.rs:110` |
//!
//! A many-valued or optional field gets the PROJECTED shape — `&[T]` and `Option<&T>` — rather
//! than `&Vec<T>` and `&Option<T>`, because those are what a caller can use without a second step.
//!
//! The projection is chosen by the declaration's MARKER, and the field's declared type is written
//! verbatim into a trait qualification: `&[<Ids as Repeated>::Item]`. Nothing pattern-matches the
//! type's spelling, so a type ALIAS projects exactly as the type it names would.
//!
//! That is a bug fix, not a preference. The emitter used to match `Vec<…>`/`Option<…>` on the
//! written type, and a field declared `files: Ids` was silently handed back as `&Ids` with nothing
//! to catch it. A macro sees tokens, not resolved types — so the resolution is left to the
//! compiler, which has the type.
//!
//! Nothing is INFERRED either: an unmarked field takes the plain borrow. Removing a marker changes
//! an accessor's shape, and that should be a visible source change rather than a silent one.
//!
//! A marked accessor is NOT `const`: it calls a trait method, and const trait methods are
//! unstable. The plain and `copy` accessors, which touch no trait, stay `const`.
//!
//! ## `copy`, and what the marker changes
//!
//! Every column gets `x_ref(&self) -> &T`. A column marked `copy` gets `x(&self) -> T` **as well**,
//! and its mutators become `const`.
//!
//! The marker is ADDITIVE, which is the point: adding it adds `x()`, removing it removes `x()`, and
//! neither renames anything — so toggling `copy` on a column never breaks a caller that was
//! borrowing it through `x_ref()`. A shape where the bare name switched between a copy and a borrow
//! would rename the accessor at every call site instead.
//!
//! It also makes the NAME state the return shape uniformly: `x()` is always a copy and `x_ref()`
//! always a borrow, whatever the column's type. The accessor convention's default is not to demand
//! `_ref` for every borrow, and this departs from it deliberately — a reader of generated code
//! cannot see the emission to check, so predictability outranks terseness here, and additivity is
//! what it buys.
//!
//! The CONSTNESS asymmetry is the marker's whole reason. `set_x` assigns over the column's previous
//! value and therefore drops it; a `const` destructor is unstable, so an unmarked column's mutators
//! cannot be `const`. A `Copy` value drops nothing, so a marked column's can. The product schema
//! already draws exactly this line by hand — a `u32` setter is `const fn`, a `Vec<Id>` setter is
//! not — and the marker automates it.
//!
//! Whether a type really is `Copy` is NOT checkable here: a model carries names and types, not
//! trait implementations. A wrongly marked column produces an emission that does not compile,
//! reported at the generated accessor as "cannot move out of `self.x`", which names the column.
//!
//! ## Every `std` name an expansion writes is QUALIFIED
//!
//! An expansion lands in a module the framework does not control, and a bare path resolves THERE. A
//! user with their own `trait Debug` in scope would capture `#[derive(Debug)]` on every emitted
//! type at once, and a `struct Option` would break every projected accessor — with an error inside
//! generated code the author cannot edit.
//!
//! The anonymous const does **not** help. It scopes `use` statements; it does not change how a bare
//! path in the enclosing module resolves. So every `std` item an expansion writes is spelled at its
//! real path — `::core::fmt::Debug`, `::core::option::Option`, `::core::convert::From` — derive
//! macros included, which accept a path exactly as a trait bound does.
//!
//! Not left to habit: `fixtures::shadowed` declares its own `Debug`, `Clone`, `Option`, `Result`
//! and the rest, and derives the whole shape inside that module. If any bare path survived, that
//! module would not compile.
//!
//! ## Where the impls sit
//!
//! Every emitted impl goes inside ONE anonymous `const _: () = { … };` per record — serde's
//! hygiene shape. The block is a scope, so the `use` statements the impl era will need (the
//! framework traits, reached through the model's `krate` path) can sit beside the impls without
//! leaking a single name into the caller's namespace. Today it holds only the inherent impls; the
//! imports arrive with the traits.
//!
//! The STRUCTS stay at top level — they are the API. Inherent impls inside the block remain fully
//! reachable from another crate, `const` contexts included (verified cross-crate), so nothing about
//! `Key::new(7)`, `.id()` or `.id_ref()` changes for a caller.
//!
//! Note for whoever reads the emission back: an impl-walking check that looks only at
//! `syn::File::items` finds NOTHING now and passes vacuously. `tests::impls` descends into the
//! block, and `tests::the_impl_walk_descends_into_the_const_wrapper` pins that it does.
//!
//! **No `#[automatically_derived]`.** It is valid on TRAIT impls only — on an inherent impl this
//! toolchain warns "can only be applied to trait impl blocks … will become a hard error in a
//! future release". The current emission has no trait impl, so the attribute has no valid subject
//! and nothing is emitted. It belongs on each emitted trait impl, and lands with impl-era emission.
//!
//! ## `#[inline]`, not `#[inline(always)]`
//!
//! Every emitted method carries `#[inline]`. These are one-line cross-crate wrappers, which is the
//! case the repository's `rust-type-conventions` reference names for plain `#[inline]`, and it
//! records that `#[inline(always)]` is NOT a house default. The product schema writes
//! `#[inline(always)]` by hand throughout (`mediaschema` `video/facet.rs:109`, `:114`, `:120`).
//!
//! The divergence is deliberate, with both citations here so that neither side is "fixed" into the
//! other by someone who has only read one of them.
//!
//! **Not `#[non_exhaustive]`** — a decision, not an oversight. Nothing outside would be able to
//! call `new`.
//!
//! **Not `Ord`, not `Copy`.** `Ord` waits for a consumer; sorted output and `BTreeMap` keys are
//! the case that will want it, and neither exists yet. `Copy` cannot be decided here at all — the
//! field types come from the declaration, a macro cannot know whether they are `Copy`, and a
//! derive cannot be conditional.

mod cross;
mod graphql;
mod mongo;
mod queries;
mod query;
mod relate;
mod sql;
pub(crate) mod wire;

pub(crate) use graphql::upper_camel;
use quote::{format_ident, quote, quote_spanned};

mod channel;
mod declared;
mod grant;
mod poll;
mod topology;

/// The BATCHING seam's emission half — the single leg's two lanes, and the five bounds an id owes.
/// Beside the emitters it reads, for the reason the three suites below are.
#[cfg(test)]
mod batching_tests;
/// The `indexed` word's own emission suite — the builder a collection's edge table carries, and the
/// two shapes that get nothing. Beside `sortable_tests`, which is the sibling word's.
#[cfg(test)]
mod indexed_tests;
/// The `sortable` word's CURSOR half — the slot a companion joins and the arm that reads it back.
/// Beside the suite above, which is the same word's write half.
#[cfg(test)]
mod shadow_cursor_tests;
/// The `sortable` word's own emission suite — the write plan's companion entry and the term that
/// renders it. Beside the emitters it reads, for the reason the suite below is.
#[cfg(test)]
mod sortable_tests;
/// The `tracing(level = …)` word's own emission suite — the level const and the instrumented query
/// entries. Beside the emitters it reads rather than in `crate::tests`, which keeps the ROSTERS.
#[cfg(test)]
mod tracing_tests;

pub use topology::PAIRED;

use crate::{
  method,
  model::{
    Column, Conversion, Crossing, DatabaseBackend, DatabaseKind, Kind, PersistColumn, Projection,
    RecordModel, Shape, Upstreams, fanned_lineage, fanned_lineage_column, one_storage_marker,
  },
};

/// What one database FAMILY answers differently about a row.
///
/// Four questions and no more, which is the measure of how much the two families really differ:
/// what the row derives, what those derives need said at the container, how a column's external
/// name reaches the field that holds it, and what to call the thing in a doc comment. Everything
/// else about a row — its fields, its accessors, its conversions — is the same on both sides and is
/// assembled once, in [`DatabaseBackend::row`].
struct Family {
  /// The derive list, verbatim.
  derives: proc_macro2::TokenStream,
  /// What the derives need told at the CONTAINER — empty for a family whose derives need nothing.
  /// Mongo's is `#[serde(crate = "…")]`, which is half of reaching serde through the shelf.
  attrs: proc_macro2::TokenStream,
  /// The module EVERY field of this family's row crosses, for a derive that would otherwise demand a
  /// foreign trait OF A DECLARED FIELD TYPE.
  ///
  /// Mongo's is `…::query::mongo::via`, spelled as the string a `#[serde(with = "…")]` takes. [`None`]
  /// for a family whose derives ask nothing of a field type — which the SQL family's do not, its
  /// decode being emitted rather than derived.
  ///
  /// # ONE path for every column, which is what keeps this emitter from reading a type's SPELLING
  ///
  /// The module's two functions are generic over the field's own type and answer through this
  /// crate's per-type document tables, so WHICH row runs is the compiler's answer to the tokens the
  /// declaration wrote. A per-type `with` path — one module for a pattern, another for everything
  /// else — would have had to match `Regex` in the tokens, which is the one thing `graphql`'s own
  /// `written_option` note says this emitter does not do outside the one seat that names it.
  via: Option<String>,
  /// How a column's external name is bound to the field that carries it.
  mapping: Mapping,
  /// The database's name, for a doc comment.
  what: fn(DatabaseKind) -> &'static str,
  /// What the emitted type IS: a "row", or a "document".
  noun: &'static str,
}

/// How a family binds a stored column's EXTERNAL name to the Rust field that holds it.
///
/// # It was two ALTERNATIVES, and the second backend's read lane made it three
///
/// A family either hands the mapping to a vendored derive through a field attribute, or writes the
/// decode itself and spells each column's name at the read that fetches it — and the choice was not
/// a preference, it followed whether the vendored derive can be TOLD where the framework keeps its
/// crate. serde's can, so [`mongo`] shelved the derive; sqlx's cannot, so [`sql`] writes the
/// `FromRow` impl and the attribute disappeared with the derive that was its only reader.
///
/// [`AttributeAndDecode`](Self::AttributeAndDecode) is the case that argument did not cover: a
/// family whose derive CAN be shelved and whose DECODE is refused anyway. Nothing about a
/// `Serialize` erases a typed refusal — there is none to erase — but a `Deserialize` refuses through
/// `serde::de::Error::custom`, which takes a `Display` and hands back the FORMAT's error, so every
/// declared refusal would reach a caller as a `bson::de::Error` carrying a string and the
/// `mongo(try_into(error = "…"))` cell would hold nothing. So the write side keeps the
/// derive and the read side is emitted.
///
/// # It puts the external name in TWO places, and that is the cost
///
/// A `#[serde(rename = "…")]` and a read under the same string are two spellings of one fact, which
/// is exactly what this enum's original note said not to do. What holds them together is that both
/// come from [`DatabaseBackend::external`] — ONE function, called twice — so the two cannot differ
/// without that function changing, and `tests::the_mongo_document_reads_the_id_out_of_underscore_id`
/// is what reads them back beside each other.
enum Mapping {
  /// The attribute a shelved derive reads the name from — mongo's `#[serde(rename = "…")]`, or its
  /// `flatten` where the column has no key of its own.
  ///
  /// No family uses it ALONE today, and it stays a variant of its own rather than being folded into
  /// the pair below: it is the shape a family with a shelvable derive on BOTH sides takes, which is
  /// what mongo was before the read lane and what a future format with a redirectable decode would
  /// be again.
  #[allow(dead_code)]
  Attribute(&'static str),
  /// The decode the family emits ITSELF, naming each column at the read that fetches it.
  Decode(fn(&DatabaseBackend, &RecordModel) -> proc_macro2::TokenStream),
  /// BOTH — the attribute for the derive that survives, and the decode for the direction that could
  /// not be left to one.
  AttributeAndDecode(
    &'static str,
    fn(&DatabaseBackend, &RecordModel) -> proc_macro2::TokenStream,
  ),
}

/// One conversion, in whichever of the two shapes its fallibility calls for.
///
/// **One shape or the other, never both.** `core` carries `impl<T, U: Into<T>> TryFrom<U> for T`, so
/// an emitted `From` ALREADY yields the `TryFrom` — writing both is `E0119`, and writing the
/// fallible one where the infallible would do costs a caller nothing, since `try_into()` resolves
/// either way.
fn conversion(
  from: proc_macro2::TokenStream,
  into: &syn::Ident,
  binding: &syn::Ident,
  body: proc_macro2::TokenStream,
  error: Option<&proc_macro2::TokenStream>,
  doc: &str,
) -> proc_macro2::TokenStream {
  let doc = leading(doc);
  if let Some(error) = error {
    return quote! {
      #[automatically_derived]
      impl ::core::convert::TryFrom<#from> for #into {
        type Error = #error;

        #[doc = #doc]
        #[inline]
        fn try_from(#binding: #from) -> ::core::result::Result<Self, Self::Error> {
          ::core::result::Result::Ok(#body)
        }
      }
    };
  }
  quote! {
    #[automatically_derived]
    impl ::core::convert::From<#from> for #into {
      #[doc = #doc]
      #[inline]
      fn from(#binding: #from) -> Self {
        #body
      }
    }
  }
}

/// The leading space a `///` comment desugars to, so an expansion a human reads back looks like
/// the hand-written code it stands in for.
pub(crate) fn leading(doc: &str) -> String {
  format!(" {doc}")
}

/// A generic TYPE parameter an expansion introduces, under a name a declaration cannot collide
/// with.
///
/// A proc macro has no hygiene for types. `Span::mixed_site` covers local bindings and `$crate`;
/// a type or a path still resolves at the CALL SITE, so a parameter spelled `Db` shadows a
/// declaration's own `Db` inside every item that declares it. What follows is silent rather than
/// loud: `<Db as DefaultMarker>::Marker` in a field's type then names the parameter, the crossing
/// the struct assumes makes it well formed anyway, and the emitted crossing resolves for no
/// database at all — with nothing reported at the declaration.
///
/// `__NAME__` is the namespace the framework already reserves: `ingraph-derive` refuses a COLUMN
/// whose name has `__` at both ends, so one rule covers a parameter shadowing a type and a column
/// colliding with the framework's own.
///
/// Every parameter emitted code introduces takes this shape. LIFETIMES do not, and need not: the
/// derive refuses a generic declaration outright, so no lifetime of a declarer's is ever in scope
/// where an emitted `'a` or `'q` is bound, and a lifetime cannot shadow a type in any case.
/// The shelf path to one framework item, from a crate root rather than from a model.
///
/// The RULE lives at [`RecordModel::framework`], which is the reader every emission goes through
/// and where the `__private` law is written down. This is the same assembly with the root spelled,
/// for the emissions whose owner is not a record — a column's accessor family reaches the
/// projection traits and does not know what declared it.
pub(crate) fn framework(
  krate: &syn::Path,
  module: &[&str],
  name: &str,
) -> proc_macro2::TokenStream {
  let module = module.iter().map(|segment| format_ident!("{segment}"));
  let name = format_ident!("{name}");
  quote!(#krate::__private #(:: #module)* :: #name)
}

/// The shelf path to a whole VENDORED crate, from a crate root rather than from a model — the free
/// twin of [`RecordModel::vendored`], which is where the rule is written down.
/// A published TYPE name as a root FIELD names it: the same word with a lower-case initial.
///
/// GraphQL's own convention, and the one rename a root field performs. It is NOT
/// [`wire::wire_member`]'s camelCase, which turns a snake-cased Rust member into a camel-cased
/// field: what arrives here is already a type name in upper camel case, and lowering its initial is
/// the whole transformation. A declared `output(rename = "…")` or `plural = "…"` therefore reaches
/// the field verbatim but for that initial.
///
/// In `emit` rather than beside one front end's legs, because BOTH root-field emitters spend it —
/// a record's trio and an interface's list leg — and one word resolved twice is one word two
/// answers can disagree about.
pub(crate) fn lower_initial(published: &str) -> String {
  let mut characters = published.chars();
  match characters.next() {
    Some(first) => first.to_lowercase().chain(characters).collect(),
    None => published.to_owned(),
  }
}

/// The same word as a TYPE name spells it: an upper-case initial, and not one other letter touched.
///
/// [`lower_initial`]'s exact inverse, written the same way for the same reason — so
/// `plural = "Corpora"` and `plural = "corpora"` reach ONE field and ONE pair of page names,
/// whichever way a declaration wrote the word.
///
/// `heck`'s `UpperCamelCase` is what this is NOT, and the difference is not cosmetic: it re-cases
/// the WHOLE word, so a `plural = "IPTCRecords"` would reach a schema as `IptcRecords`.
/// `wire::wire_type` states the law this obeys — a name a declaration chose is a name it chose, and
/// no convention of this emitter may move it — and raising one initial is the least this position
/// can do while still handing GraphQL a type name.
pub(crate) fn raise_initial(published: &str) -> String {
  let mut characters = published.chars();
  match characters.next() {
    Some(first) => first.to_uppercase().chain(characters).collect(),
    None => published.to_owned(),
  }
}

/// A declared type's name in snake case — what an emitted function ident is built from before the
/// `__async_graphql_` prefix.
///
/// The RUST side only. What a client reads is written out per item, so this never reaches a schema
/// and a rename of the published type moves the field without moving the ident.
/// Every token in a stream, moved to one span.
///
/// The origin layer's respanning, generalised from an ident to a path: a `where` predicate is
/// reported at the span its tokens carry, and a predicate whose trait path came from the emitter
/// would report a broken hop at the macro. Only the REPORT moves — resolution is unaffected, the
/// span being a real one from the file the declaration is in.
///
/// Here rather than in one emitter, because the tower's head pin and the recipe's BINDING are the
/// same move at two grains: both mint a projection out of a declaration's own words and both have to
/// report it at the word rather than at the attribute.
pub(crate) fn respan(
  tokens: proc_macro2::TokenStream,
  at: proc_macro2::Span,
) -> proc_macro2::TokenStream {
  tokens
    .into_iter()
    .map(|token| match token {
      proc_macro2::TokenTree::Group(group) => {
        let mut respanned = proc_macro2::Group::new(group.delimiter(), respan(group.stream(), at));
        respanned.set_span(at);
        proc_macro2::TokenTree::Group(respanned)
      }
      mut other => {
        other.set_span(at);
        other
      }
    })
    .collect()
}

pub(crate) fn snake(name: &str) -> String {
  use heck::ToSnakeCase as _;

  name.to_snake_case()
}

/// THE ROOT FAMILY'S NAME, read off the root key's own TYPE.
///
/// `MediaId` is the family `media`, `TrackId` is `track`, and `u64` is `u64`. The rule is the type's
/// last path segment, snake-cased, with one trailing `Id` taken off — which is what makes the two
/// records that share a root agree without either of them saying so: a `Keyframe` whose lineage root
/// is `MediaId` and the `Media` whose own id is `MediaId` are ONE family, exactly as
/// [`Registry`](../ingraph/struct.Registry.html) already makes them one table.
///
/// Reading the TYPE rather than the column name is what makes that true. A column name is scoped and
/// renameable — one record may call its root step `media` and another `owner` — while the type is
/// the same fact the registry keys its tables by, so a name derived from it cannot disagree with the
/// table it names.
///
/// A root whose type is not a path — a tuple, a reference — has no name to read and answers the
/// empty string, which the registry already means *unnamed, read the defaults*.
pub(crate) fn family(ty: &syn::Type) -> String {
  let syn::Type::Path(path) = ty else {
    return String::new();
  };
  let Some(last) = path.path.segments.last() else {
    return String::new();
  };
  let name = last.ident.to_string();
  let stem = name.strip_suffix("Id").filter(|rest| !rest.is_empty());
  snake(stem.unwrap_or(&name))
}

/// The POSITIONS a list occupies once the compiler has answered its members' predicates — one
/// `const` per member, each the previous plus that member's own presence.
///
/// # A count is not a thing a macro may know
///
/// Every ordinal an emission writes into a `#[cfg]`-carrying list is an index into a list the
/// predicates CONTRACT: an array element is a legal attribute position, so a build that removes the
/// second entry makes the third's position `1`. An expansion that had written `2` there would name a
/// position that build has not got — and a macro cannot evaluate a predicate, so it cannot write the
/// right literal either.
///
/// What it CAN write is the arithmetic. `1` or `0` per member is a `const` the compiler folds after
/// stripping (see [`Condition::present`](crate::model::Condition::present)), the running sum of them
/// is the position, and a `const` is a legal pattern — so one expansion serves every configuration
/// and K conditional members cost K constants rather than 2ᴷ expansions.
///
/// A list with NO conditional member gets the literals back and no constants at all, which is what
/// keeps an ordinary declaration's expansion identical to the one before this seat existed.
///
/// `declared` is one entry per member, in the list's own order — the [`Condition`] it was declared
/// under, or [`None`] for a member no condition seat covers. It lives here rather than beside either
/// caller because a record's row and a fragment's segment list ask one question, and two copies of a
/// running sum is how one of them starts at the wrong index.
///
/// [`Condition`]: crate::model::Condition
pub(crate) fn positions(
  declared: &[Option<&crate::model::Condition>],
) -> (proc_macro2::TokenStream, Vec<proc_macro2::TokenStream>) {
  if declared
    .iter()
    .all(|condition| condition.is_none_or(crate::model::Condition::always_present))
  {
    return (
      proc_macro2::TokenStream::new(),
      (0..declared.len()).map(|at| quote!(#at)).collect(),
    );
  }
  let names: Vec<syn::Ident> = (0..declared.len())
    .map(|at| format_ident!("__INGRAPH_AT_{at}"))
    .collect();
  let mut places = proc_macro2::TokenStream::new();
  for (at, name) in names.iter().enumerate() {
    let place = match at.checked_sub(1) {
      None => quote!(0usize),
      Some(before) => {
        let previous = &names[before];
        let term =
          declared[before].map_or_else(|| quote!(1usize), crate::model::Condition::present);
        quote!(#previous + #term)
      }
    };
    places.extend(quote!(const #name: ::core::primitive::usize = #place;));
  }
  (places, names.iter().map(|name| quote!(#name)).collect())
}

pub(crate) fn vendored(krate: &syn::Path, name: &str) -> String {
  let name = format_ident!("{name}");
  quote!(#krate::__private::#name)
    .to_string()
    .replace(' ', "")
}

/// WHICH of a reading's two filters a door is asking for — the 2026-08-22 *each face tells its own
/// truth* ruling, read at the one seam that spells a filter type.
///
/// A composite's predicate depends on the host kind: a row-holding host may compare only what it
/// stores, and a rowless one asks about the whole value. Every other reading answers both with one
/// type, so a door that picked the wrong face would be invisible until a fragment activated for both
/// kinds arrived — which is why the fact is a PARAMETER here rather than a default anywhere.
///
/// The rule at a call site is mechanical rather than a judgement: a filter that is projected into a
/// `ToDatabaseComparison` takes [`FilterFace::Column`], that row existing on the stored face alone.
/// Everything else takes [`FilterFace::Full`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FilterFace {
  /// What a ROWLESS host publishes: every field the value declares.
  Full,
  /// What a ROW-HOLDING host publishes: the columns the value is actually stored in.
  Column,
}

impl FilterFace {
  /// The associated type this face resolves through on `ToGraphqlFilter`.
  fn item(self) -> syn::Ident {
    match self {
      Self::Full => format_ident!("Filter"),
      Self::Column => format_ident!("ColumnFilter"),
    }
  }
}

/// The FILTER one declared position is asked for by: the WORD's own marker where one was written,
/// and the type's own registry row where none was.
///
/// # Two declarations, one routing
///
/// A record's field and an interface's PIN both carry an interpretation word now, and the filter
/// KIND is what the word decides — `list(scalar)` over a `Vec<u64>` resolves to the sequence filter
/// whatever that type's own row says, and a field naming nothing takes the row. Written once here so
/// the two front ends cannot come to route differently: a filter asked for twice is a filter two
/// answers can disagree about, and between those two there is no conversion.
///
/// `face` says WHICH of the reading's two filters — see [`FilterFace`] — and it rides the same
/// routing for the same reason: two doors asking about one field must not come to ask different
/// questions of it.
///
/// `krate` rather than a model, for [`Marker::resolved`](crate::model::Marker)'s reason.
pub(crate) fn filter_of(
  krate: &syn::Path,
  ty: &syn::Type,
  marker: Option<&crate::model::Marker>,
  face: FilterFace,
) -> proc_macro2::TokenStream {
  let to_filter = framework(krate, &["graphql"], "ToGraphqlFilter");
  let item = face.item();
  let Some(marker) = marker else {
    let inferred = framework(krate, &["marker"], "DefaultMarker");
    return quote!(<<#ty as #inferred>::Marker as #to_filter>::#item);
  };
  let resolved = marker.resolved(krate, ty);
  quote!(<#resolved as #to_filter>::#item)
}

pub(super) fn parameter(name: &str) -> syn::Ident {
  format_ident!("__INGRAPH_{name}__")
}

/// What a WIDE emitted signature carries — the sites whose parameter count the emitter cannot
/// reduce without giving up the shape.
///
/// Two kinds, and the second is why this is not called `wide_constructor` any more:
///
/// - the POSITIONAL constructors, whose arity is the DECLARATION's — an address type's `new`, which
///   takes a key's or a lineage path's columns, and a comparison's, which takes one predicate per
///   stored column;
/// - the emitted LIST RESOLVER, whose arity is the EMITTER's own and is eight: a context, an order,
///   four page arguments and a predicate. Nothing there is a column, and the count is fixed for
///   every record that has the leg at all.
///
/// `clippy::too_many_arguments` warns above seven, so either kind makes the DECLARING crate fail its
/// own `-D warnings` build — reported at `#[ingraph::record(…)]`, inside an expansion its author
/// cannot edit. A real aggregate reaches eight columns routinely and the list leg reaches eight
/// always, so the attribute rides every one of these rather than being chosen by a count here: an
/// emitter that counted would have clippy's threshold written into it, and a consumer may configure
/// that threshold to anything.
///
/// `allow` rather than `expect`, and the difference is load-bearing: an unfulfilled `expect` is
/// itself a warning, so `expect` would fail every declaration NARROWER than the threshold — which
/// is most of them. An `allow` over code no lint fires on costs nothing.
pub(crate) fn wide_signature() -> proc_macro2::TokenStream {
  quote!(#[allow(clippy::too_many_arguments)])
}

/// The visibility an emitted type's MEMBERS carry — layer 1 of the three-layer naming law.
///
/// `pub(crate)` and never `pub`, and never private either, because the member is a SUBSTRATE rather
/// than a face:
///
/// - **not private**, because emitted-to-emitted reads spend the FIELD. A crossing, a row equation,
///   a gather and an audit each read a member of a type some OTHER expansion wrote, and an expansion
///   lands where its declaration is written — so two declarations in two modules of one crate have
///   to be able to see each other's members. Private is visible to the declaring module and its
///   descendants alone, which makes that a fact about where an author happened to put a `mod`.
/// - **not `pub`**, because a member is not API. What a downstream crate is offered is the ACCESSOR
///   face beside it, which is the layer a rename word may move; publishing the representation would
///   make every field name a compatibility promise and leave the accessors decorative.
///
/// One spelling in one place, because a visibility written at each emission site is a visibility
/// that can be written differently at one of them.
pub(crate) fn substrate() -> proc_macro2::TokenStream {
  quote!(pub(crate))
}

impl RecordModel {
  /// A record's key type, plus its lineage type when it has a lineage.
  ///
  /// The key is FLAT — `lineage ⊕ id`, root-first, one struct with no nesting — because every use of
  /// it is columnar: a row's key columns, a prefix range scan, a leading-column attribution.
  ///
  /// A root record gets NO lineage type. An empty path has no type worth naming, and its absence is
  /// what tells a reader the record is a root.
  ///
  /// Both names come from the MODEL. Whether they are the convention's or an author's rename was
  /// settled before this point, so there is exactly one place a name can be decided.
  pub fn emit(&self) -> proc_macro2::TokenStream {
    let record = &self.record;
    let (key_doc, new_doc) = match self.lineage {
      Some(_) => (
        format!("The address of a [`{record}`] row: its lineage path followed by its own id."),
        "Construct an address from its lineage path and the row's own id.".to_owned(),
      ),
      None => (
        format!("The address of a [`{record}`] row: its own id."),
        "Construct an address from the row's own id.".to_owned(),
      ),
    };
    let (key_type, key_impl) = self.address_type(
      &self.key.name,
      &key_doc,
      &new_doc,
      self.key.columns(),
      Some(&self.key.id),
    );
    let key_from = self.address_conversions(&self.key.name, self.key.columns());
    let (lineage_type, lineage_impl, lineage_from) = match self
      .lineage
      .as_ref()
      .map(|lineage| (lineage, &lineage.shape))
    {
      Some((lineage, Shape::Path(columns))) => {
        let (declaration, methods) = self.address_type(
          &lineage.name,
          &format!("The path from the root to a [`{record}`] row, root-first."),
          "Construct a path from its steps, root-first.",
          columns.iter(),
          None,
        );
        (
          Some(declaration),
          Some(methods),
          Some(self.address_conversions(&lineage.name, columns.iter())),
        )
      }
      Some((lineage, Shape::Kinds(kinds))) => {
        let (declaration, conversions) = self.lineage_kinds(&lineage.name, kinds);
        (Some(declaration), None, Some(conversions))
      }
      None => (None, None, None),
    };
    let storage_marker = self.storage_marker();
    let (topology_types, topology_impls) = self.topology();
    let declared = self.declared();
    // The `receipt` word's SIBLING impl, and `None` on every declaration that wrote no word — see
    // [`receipts`](RecordModel::receipts) for why it is not a member of the facts trait.
    let receipts = self.receipts();
    let (poll_types, poll_impls) = self.poll_face();
    let (grant_types, grant_impls) = self.polling_face();
    let (channel_types, channel_impls) = self.channel_face();
    let subscription = self.subscription();
    let goodbye = self.goodbye();
    let face = self.face();
    let key_parent = self.key_parent();
    // THE ROOT PROJECTION, on EVERY record: a key is root-first, so every declaration has a root
    // and every one of them gets the impl that names it — see `root_projection`.
    let root_projection = self.root_projection();
    let record_impl = self.methods();
    let binding = self.binding();
    let wire_binding = self.wire_binding();
    let hydration_binding = self.hydration_binding();
    let address_segments = self.address_segments();
    let relations = self.relations();
    let (row_types, row_impls) = self.rows();
    let (wire_types, wire_impls) = self
      .graphql
      .as_ref()
      .map_or_else(Default::default, |graphql| graphql.faces(self));
    // The BINDING, behind the binding gate: what makes an emitted type a SCHEMA type rather than a
    // structure. It joins the anonymous const because every item in it is an impl — see [`wire`],
    // where the split from the shapes is stated, and where the one face that ships today is.
    let wire = self.wire();
    let queries_type = self.queries_type();
    // THE REWRITE's two blocks, empty on every ordinary declaration: the bridge every manifest read
    // crosses, and the reference family that makes a wrapper usable where the wrapped type was.
    let remote_prelude = self.remote_prelude();
    let remote_family = self.remote_family();
    quote! {
      #key_type
      #lineage_type
      #row_types
      #wire_types
      #queries_type
      #topology_types
      #poll_types
      #grant_types
      #channel_types

      #storage_marker

      const _: () = {
        #remote_prelude
        #remote_family
        #key_impl
        #lineage_impl
        #record_impl
        #binding
        #wire_binding
        #hydration_binding
        #address_segments
        #relations
        #key_from
        #lineage_from
        #row_impls
        #wire_impls
        #wire
        #subscription
        #topology_impls
        #declared
        #receipts
        #root_projection
        #poll_impls
        #grant_impls
        #channel_impls
        #goodbye
        #face
        #key_parent
      };
    }
  }

  /// The GOODBYE audit — what the `teardown` word buys at the declaration.
  ///
  /// The word enrols the constructed value in the shutdown's chain, and the chain is the LAUNCH's
  /// to walk: nothing about it can be emitted here, because the value does not exist until a
  /// deployment builds one. What CAN be said here is the thing an author would otherwise learn at
  /// start-up — that the type has a goodbye at all — so the expansion states the bound, and a
  /// declaration that opted in without an impl is `E0277` at its own name.
  ///
  /// It is [`subscription`](Self::subscription)'s shape for the same reason: the monomorphised
  /// function item is what discharges the bound, an initialiser is where naming it is legal, and
  /// neither leaks a name into the declarer's scope.
  fn goodbye(&self) -> Option<proc_macro2::TokenStream> {
    if !self.teardown {
      return None;
    }
    let record = &self.record;
    let teardown = self.framework(&["drive"], "AsyncTeardown");
    Some(quote! {
      const _: () = {
        fn __ig_says_goodbye<__INGRAPH_NODE__: #teardown>() {}
        const _: fn() = __ig_says_goodbye::<#record>;
      };
    })
  }

  /// The FACE audit — what the `async` and `stream` words buy at the declaration, and where a
  /// mismatch lands.
  ///
  /// A word is a CLAIM about the body, so the expansion checks it: an `async` declaration whose type
  /// carries the blocking `Operator` instead is `E0277`, WITH THE CARET ON THE WORD. That span is
  /// the point of keeping the path rather than a `bool` — [`goodbye`](Self::goodbye) blames the
  /// whole attribute because `teardown` collapses to a `bool` before it gets here, and this one has
  /// somewhere better to point.
  ///
  /// # TWO AXES, four cells, one audit
  ///
  /// `stream` picks the PAIR and `async` picks the HALF, so the trait this demands is the cell the
  /// two words select together:
  ///
  /// | words | the face the bound demands |
  /// |---|---|
  /// | *(none)* | nothing is demanded — see below |
  /// | `async` | `AsyncOperator` |
  /// | `stream` | `StreamOperator` |
  /// | `stream, async` | `AsyncStreamOperator` |
  /// | `autonomous` | `AutonomousOperator` |
  /// | `autonomous, async` | `AsyncAutonomousOperator` |
  ///
  /// `stream` and `autonomous` are values of ONE axis and the grammar refuses them together, so the
  /// two halves of the table never compete: what multiplies is the MODE word, which cuts across
  /// both.
  ///
  /// The CARET goes on `async` where it was written and on `stream` otherwise, which is the same
  /// rule read twice: blame the word that names the half a reader has to change, and where only the
  /// pair was written the pair's word is that word.
  ///
  /// A BARE declaration emits nothing, and that asymmetry is deliberate rather than a gap: a
  /// declaration is not required to have an operator impl at all — a great many exist only to be
  /// expanded — so demanding one of every silent node would refuse the ordinary case. What catches
  /// a bare declaration over an awaited body is the LAUNCH, whose per-node bound is spelled through
  /// the same const the mode word sets: `Driven<Selected<{ … }>>` is `Driven<Block>` there, and an
  /// `AsyncOperator`-only type does not satisfy it.
  ///
  /// A `stream` declaration is never bare in that sense — the word IS a claim — so the streaming
  /// rows are audited at both halves and a `stream` node with no streaming face at all is refused
  /// here rather than at whatever first tried to mount it. An `autonomous` one is a claim in
  /// exactly the same way and is audited exactly the same way.
  fn face(&self) -> Option<proc_macro2::TokenStream> {
    // The `async` word where it was written, and the `stream` word where it was the only one: the
    // caret sits on the half a reader changes, and the pair's word is that half where no mode word
    // was written.
    let word = self
      .asynchronous
      .as_ref()
      .or(self.streaming.as_ref())
      .or(self.autonomous.as_ref())?;
    let named = match (
      self.streaming.is_some(),
      self.autonomous.is_some(),
      self.asynchronous.is_some(),
    ) {
      (true, _, true) => "AsyncStreamOperator",
      (true, _, false) => "StreamOperator",
      (false, true, true) => "AsyncAutonomousOperator",
      (false, true, false) => "AutonomousOperator",
      // `(false, false, false)` is unreachable: `word` above is `None` there and this function has
      // already returned. The pair words are refused together by the grammar, so the first two arms
      // never compete with the second two.
      (false, false, _) => "AsyncOperator",
    };
    let operator = self.framework(&["operator"], named);
    // The NODE's name, respanned onto the word — and only it. The bound's own tokens stay at the
    // call site, because a generic parameter carrying a user span is linted as if the author had
    // written its name (`non_camel_case_types` on `__INGRAPH_NODE__`, at the word). Respanning the
    // instantiated type instead moves the E0277's primary span without moving anything a lint reads.
    let mut node = self.record.clone();
    node.set_span(syn::spanned::Spanned::span(word));
    Some(quote! {
      const _: () = {
        fn __ig_awaits<__INGRAPH_NODE__: #operator>() {}
        const _: fn() = __ig_awaits::<#node>;
      };
    })
  }

  /// The ONE-STORAGE MARKER, for a node that holds a storage — see [`one_storage_marker`] for the
  /// collision it exists to make.
  ///
  /// It is emitted at MODULE SCOPE and cannot be anywhere else: each derive writes its own
  /// `const _: () = { … }`, so two markers placed inside two of those would be two items in two
  /// distinct scopes, colliding with nothing. The whole mechanism is one scope holding one name
  /// twice.
  ///
  /// An [`Operator`](crate::model::NodeKind::Operator) emits none, and the absence is the same
  /// shape the rest of this model uses for a thing it does not have: a node with no storage has no
  /// second storage to refuse.
  fn storage_marker(&self) -> Option<proc_macro2::TokenStream> {
    self.kind.stores().then(|| {
      let marker = one_storage_marker(&self.prefix, &self.record);
      quote! {
        #[doc(hidden)]
        #[allow(dead_code, non_upper_case_globals)]
        const #marker: () = ();
      }
    })
  }

  /// The SUBSCRIPTION audit — every upstream this node names, emitted so that the compiler resolves
  /// it.
  ///
  /// One path where `subscribe = "path::To::Upstream"` was written, and one per `upstream(…)` entry
  /// where the node fuses several. Both spellings reach the same audit because the claim is the
  /// same one: this path names a node.
  ///
  /// The derive resolves nothing here and could not: the upstream is another declaration's, and two
  /// derives cannot see each other. What it can do is put the path where rustc will read it, under a
  /// bound that says what a subscribe target has to BE — so a path naming nothing is `E0412` and a
  /// path naming something that is not a node is `E0277`, both at the string the author wrote.
  ///
  /// The bound is [`Transformer`], and the choice is worth naming rather than assuming: the design
  /// record's own table writes the refusal as *missing `Node` impl*, and no `Node` trait exists. The
  /// entity binding is what every node derive emits and nothing else does, so *implements
  /// `Transformer`* is what *is a node* means in the shipped crate. A `Node` trait arriving later
  /// moves one path in this function.
  ///
  /// A `const` item inside the anonymous const rather than a statement: the monomorphised function
  /// item is what discharges the bound, an initialiser is where naming it is legal, and neither
  /// leaks a name into the declarer's scope.
  fn subscription(&self) -> Option<proc_macro2::TokenStream> {
    let upstreams: Vec<&syn::Path> = self
      .subscribe
      .iter()
      .chain(self.upstreams.iter().flat_map(Upstreams::upstreams))
      .collect();
    if upstreams.is_empty() {
      return None;
    }
    let transformer = self.framework(&["transform"], "Transformer");
    Some(quote! {
      const _: () = {
        fn __ig_subscribes_to<__INGRAPH_UPSTREAM__: #transformer>() {}
        #(const _: fn() = __ig_subscribes_to::<#upstreams>;)*
      };
    })
  }

  /// A lineage that is a CHOICE: the enum, and the two conversions off the record.
  ///
  /// ```text
  /// pub enum CaptionLineage {
  ///   Frame(<media::Frame as Transformer>::Key),
  ///   Segment(<asr::Segment as Transformer>::Key),
  /// }
  /// ```
  ///
  /// One variant per upstream, each carrying that upstream's WHOLE key — so a row's ancestry is
  /// exactly the address of the message it came from, with nothing restated and nothing to keep in
  /// step. The payload is a PROJECTION rather than a named type for the reason every upstream
  /// reference in this crate is: two expansions cannot see each other, so the compiler resolves it
  /// at the string the declaration wrote, and a path naming something that is not a node is `E0277`
  /// there.
  ///
  /// # No constructor, no accessors, and that is the shape rather than an omission
  ///
  /// An enum is built by naming a variant and read by matching on one. A `new` would have to pick a
  /// variant for its caller, and an accessor family would be a fallible read of a value that may not
  /// be there — both of which the language already spells better. What IS emitted beside it is the
  /// pair of conversions off the record, so a caller reaches a row's ancestry the same way it
  /// reaches a path's.
  fn lineage_kinds(
    &self,
    name: &syn::Ident,
    kinds: &[Kind],
  ) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
    let record = &self.record;
    let vis = &self.vis;
    let injected = fanned_lineage(&self.prefix);
    let transformer = self.framework(&["transform"], "Transformer");
    let doc = leading(&format!(
      "Which upstream a [`{record}`] row descends from, and that message's own address."
    ));
    let variants = kinds.iter().map(|kind| {
      let (variant, node) = (&kind.variant, &kind.node);
      let doc = leading(&format!("Descended from a `{variant}` message."));
      quote! {
        #[doc = #doc]
        #variant(<#node as #transformer>::Key),
      }
    });
    let declaration = quote! {
      #[doc = #doc]
      #[derive(
        ::core::fmt::Debug,
        ::core::clone::Clone,
        ::core::cmp::PartialEq,
        ::core::cmp::Eq,
        ::core::hash::Hash
      )]
      #vis enum #name {
        #(#variants)*
      }
    };
    let conversions = quote! {
      #[automatically_derived]
      impl ::core::convert::From<#record> for #name {
        #[inline]
        fn from(record: #record) -> Self {
          record.#injected
        }
      }

      #[automatically_derived]
      impl<'a> ::core::convert::From<&'a #record> for #name {
        #[inline]
        fn from(record: &'a #record) -> Self {
          ::core::clone::Clone::clone(&record.#injected)
        }
      }
    };
    (declaration, conversions)
  }

  /// The KEY-PARENT EQUATION — *this node's lineage IS the designated parent's key*, written as the
  /// one thing the compiler can check it as: a function from that key to this lineage.
  ///
  /// ```text
  /// const _: fn(<Parent as Transformer>::Key) -> CaptionLineage =
  ///   |k| CaptionLineage { media: k.media, frame: k.id };
  /// ```
  ///
  /// A STRUCT LITERAL and not a cast, because a literal is what makes each half of the claim fail
  /// separately and by name: a parent that renamed a key column is `E0609` naming the field that is
  /// gone, a column whose type drifted is `E0308` naming that column, and a lineage column with no
  /// mapping at all is `E0063`. Every one of them lands at the declaration that wrote the mapping.
  ///
  /// # Why a fusion DECLARES its mirror and a derived index is INJECTED with one
  ///
  /// The boundary is *indexes inject, records declare*, and it is about who reads the columns. A
  /// derived index's key has one consumer — the engine addressing its documents — so a carried field
  /// the expansion mints is the whole of what anyone needs, and the declaration is spared writing
  /// it. A fusing node's lineage columns are first-class query surface: filters name them, order
  /// tails end in them, cursors carry them and foreign keys point at them. A column a user's query
  /// spells is a column that user's declaration must have spelled.
  ///
  /// # The parent's id collides with this node's, and the rename is the feature
  ///
  /// A parent's key ends in ITS id, so a child mirroring the whole key would want a column called
  /// `id` — which the child's own `#[ingraph(id)]` field already is. The collision is refused where
  /// every field-name collision is, at the declaration, and the way out is a DOMAIN name for what
  /// the column means here: a caption's parent frame is `frame`, mapped with `frame(source = "id")`.
  /// The grammar forces a reader of the child's table to be told which id each column holds.
  fn key_parent(&self) -> Option<proc_macro2::TokenStream> {
    let fusion = self.upstreams.as_ref()?.fused()?;
    let lineage = &self.lineage.as_ref()?.name;
    let parent = &fusion.parent;
    let transformer = self.framework(&["transform"], "Transformer");
    // Each read is spanned AT THE MAPPING — the `source = "…"` string where one was written, and the
    // name inside `fields(…)` where the two agree. That is what decides where the type half of the
    // claim is reported: without it the whole expression is `call_site`, and a column whose type
    // drifted underlines the macro invocation instead of the mapping the author can edit.
    let mirrors = fusion.mirrors.iter().map(|mirror| {
      let (column, from) = (&mirror.column, &mirror.from);
      let read = quote_spanned!(from.span() => __ingraph_key.#from);
      quote!(#column: #read,)
    });
    Some(quote! {
      const _: fn(<#parent as #transformer>::Key) -> #lineage = |__ingraph_key| #lineage {
        #(#mirrors)*
      };
    })
  }

  /// **THE ROOT PROJECTION**: which root key a record of this type descends from, as the
  /// [`Attributes`](crate::drive) impl the root-key registry reads it through.
  ///
  /// ```text
  /// impl Attributes<Keyframe> for RootProjection<Keyframe> {
  ///   const FAMILY: &'static str = "media";
  ///   type Root = MediaId;
  ///   fn root(&self, record: &Keyframe) -> MediaId { Clone::clone(&record.media) }
  ///   fn observe(&self, _: &MediaId, _: &NodeName, _: &Arrival) {}
  /// }
  /// ```
  ///
  /// # The root is the key's FIRST column, and that is derived rather than declared
  ///
  /// A declared key is `lineage ⊕ id`, flat and ROOT-FIRST, so the root of a record is its leading
  /// lineage step — and, for a record with no lineage at all, its own id. Nothing is written for it
  /// and nothing could be: a declared root would be a second statement about a fact the key already
  /// carries, and two statements can disagree.
  ///
  /// # Why the impl is on a FRAMEWORK type and not on the record
  ///
  /// [`Attributes`] is implemented BY THE ATTRIBUTION, for the output type — the projection is a
  /// hook a node wires, not a method a record has — so an impl of it needs a self type. Writing one
  /// on the record would mean *a record attributes things*, which is not what a record is;
  /// `RootProjection<T>` is the framework's own zero-sized seat for exactly this, and the impl is
  /// legal in a declaring crate because its self type carries that crate's own record.
  ///
  /// # EVERY record gets one, and that is the point
  ///
  /// Unlike [`receipts`](Self::receipts), this is not opt-in. A record's root is not something a
  /// declaration chooses to have — it has one the moment it has a key — so there is no word to
  /// write, no silence to interpret, and no declaration that could be surprised by acquiring it.
  ///
  /// # What INSTALLS it, and why that is a different question
  ///
  /// The impl makes the projection SPELLABLE; what puts one on a node is the `attributed` word, one
  /// module over in [`declared_attribution`](RecordModel::declared_attribution). The two are
  /// separate because they answer different questions: a record HAS a root the moment it has a key,
  /// and whether a NODE attributes its outputs to one depends on what that node emits — which may
  /// be somebody else's record, or a `String`.
  ///
  /// It could not have been the GRAPH root's expansion, and that is the wall this pair is shaped
  /// around: a root sees a node's output only as a type it can name and cannot ask whether that type
  /// is a declared record at all, so an unconditional install written there would refuse to compile
  /// for every node emitting a `String` or a `u64`. The seat crosses that wall, `()` is what the
  /// silent declaration puts in it, and the walk installs whatever it finds.
  fn root_projection(&self) -> proc_macro2::TokenStream {
    let record = &self.record;
    let root = self
      .key
      .columns()
      .next()
      .expect("a key always has its id, so it always has a first column");
    let ty = &root.ty;
    let family = family(ty);
    let attributes = self.framework(&["drive"], "Attributes");
    let projection = self.framework(&["drive"], "RootProjection");
    let node_name = self.framework(&["drive"], "NodeName");
    let arrival = self.framework(&["drive"], "Arrival");
    let binding = format_ident!("record");
    let source = &root.source;
    // A REWRITE reads through the wrapped type's accessors, exactly as its key conversion does —
    // there is no field to reach on a wrapper.
    let read = if self.remote.is_some() {
      self.remote_read(&binding, source)
    } else {
      quote!(::core::clone::Clone::clone(&record.#source))
    };
    let doc = leading(&format!(
      "Which root key a [`{record}`] descends from — its key's FIRST column, which is the \
       `{source}` field. The root-key registry tables one machine per family, and this is what \
       tells it which family a record of this type belongs to."
    ));
    let family_doc = leading(
      "This root family's own name, read off the root type rather than off a column name so that \
       every record sharing a root agrees on it without saying so.",
    );
    quote! {
      #[automatically_derived]
      impl #attributes<#record> for #projection<#record> {
        #[doc = #family_doc]
        const FAMILY: &'static str = #family;

        #[doc = #doc]
        type Root = #ty;

        #[inline]
        fn root(&self, record: &#record) -> Self::Root {
          #read
        }

        // THE EMPTY PROGRAM, and it is the honest state of this seat rather than a stub: what an
        // observation is COUNTED into is the resident's own registries handle, which the projection
        // does not hold and is not the party to join.
        #[inline]
        fn observe(&self, _root: &Self::Root, _worker: &#node_name, _arrival: &#arrival) {}
      }
    }
  }

  /// One row per declared database, split the way [`RecordModel::emit`] places them: the structs are
  /// the API and stay at top level, the impls join the record's anonymous const.
  ///
  /// A record with no `persist(…)` emits nothing here, and that is the whole of the check — a
  /// pure-compute record is `None` on the model rather than an empty list to walk.
  fn rows(&self) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
    let mut types = proc_macro2::TokenStream::new();
    let mut impls = proc_macro2::TokenStream::new();
    for database in self.persist.iter().flat_map(|persist| &persist.backends) {
      let (declaration, methods) = database.row(self);
      types.extend(declaration);
      impls.extend(methods);
      // The comparison rides beside the row, always: it is the storage form of a PREDICATE, and a
      // programmatic query needs one whether or not the record has a wire face. Only the conversion
      // FROM a filter depends on `graphql(…)` being declared.
      let (declaration, methods) = database.comparison(self);
      types.extend(declaration);
      impls.extend(methods);
      impls.extend(database.comparison_traits(self));
      // The CROSSING beside the map, and gated where the map is not: it names the backend
      // concretely, so it rides the dialect's own gate and exists per DECLARED ∩ COMPILED-IN
      // database. See `emit::cross` for why a concrete backend is what makes it writable at all.
      impls.extend(database.filter_crossing(self));
      impls.extend(database.vocabulary(self));
      impls.extend(database.column_fence(self));
    }
    // The ORDER-BY, once per record and beside the comparisons: its content is mechanical from the
    // stored columns and its lowering is pure SQL, so nothing about it is a wire fact — see
    // [`RecordModel::ordering`] for the gap that closes.
    let (order_type, order_impls) = self.ordering();
    types.extend(order_type);
    impls.extend(order_impls);
    let (query_types, query_impls) = self.query();
    types.extend(query_types);
    impls.extend(query_impls);
    (types, impls)
  }

  /// The RECORD's own inherent impl: an accessor family for every field it declares, and mutators
  /// for the ones that do not bear identity.
  ///
  /// No constructor — see the module doc.
  fn methods(&self) -> proc_macro2::TokenStream {
    // A REWRITE's fields are a MANIFEST rather than storage, so its readers are the remote's own
    // accessors crossed by `Into` — a different family, written where that mode is written.
    if self.remote.is_some() {
      return self.remote_methods();
    }
    let record = &self.record;
    let families = self.fields.iter().map(|field| {
      // The CONDITION, on the reader family of the field that wrote it: the echoed field really
      // disappears under the predicate, so an ungated accessor would be `E0609` on a field that is
      // not there. See [`Condition`](crate::model::Condition).
      field.column.methods(
        &self.vis,
        &self.krate,
        &format!("`{}` field of this [`{record}`]", field.column.name),
        !field.identity,
        &field.condition.gate(),
      )
    });
    quote! {
      impl #record {
        #(#families)*
      }
    }
  }

  /// The record's ENTITY BINDING: `Transformer`, tying the record to the types this emission
  /// already declares and to the row form the declaration asked for — with `Identifiable`, its
  /// supertrait, on the two types that carry the id.
  ///
  /// Every face is the emitter's OWN output or the declaration's own type, which is what makes
  /// naming these traits different from naming a still-moving one. `Key` is the `*Key` struct
  /// written above, `Lineage` the `*Lineage` beside it, `Id` the declared type of the key's last
  /// column, carried through verbatim — so an alias stays an alias, as it does everywhere else here
  /// — and `Record` the record itself.
  ///
  /// TWO `Identifiable` impls, and they are the trait's whole reason for existing separately: the
  /// RECORD borrows the id out of its own column, and the `*Key` borrows it out of the last step of
  /// the address. Same type both times, read from two places — which is why the id is the supertrait
  /// rather than a member of the entity set, since a key is no entity.
  ///
  /// The `*Lineage` gets NONE. A path from the root is a chain of ancestors' ids and no single one
  /// of them addresses the row, so there is nothing for the member to bind.
  ///
  /// A ROOT binds `()` for its lineage. The model has no [`Lineage`](crate::model::Lineage) for one
  /// and this emits no type for it, so there is nothing named to bind; the empty product is what an
  /// empty path is.
  ///
  /// A record that persists NOWHERE binds `()` for its row form, by the same argument one level
  /// over: it becomes no row, and the empty product is what becoming nothing is. The model is the
  /// check — a pure-compute record is `None` there rather than an empty list of databases, which is
  /// exactly what [`rows`](Self::rows) reads — so the binding and the rows cannot disagree about
  /// whether a declaration is stored.
  ///
  /// A record with NO `graphql(…)` block binds `()` for its wire face, by the same argument again,
  /// and a record with one binds `Self` — the [`wire_binding`](Self::wire_binding) beside this is
  /// where the face's own types are written, and the record is what carries them, so a bundle type
  /// named here would be a second name for the record. The predicate is `graphql.is_some()`, which
  /// is the same one [`Graphql::faces`] emits those types under.
  ///
  /// Neither QUERY FACE is a member of this set. The filter rides the wire face above; the ORDER
  /// rides [`DatabaseBackend::vocabulary`], an impl written under a DIFFERENT predicate — the
  /// record persists in that database. A declaration meeting one condition and not the other is
  /// what makes them two, and this is where that shows: a persist-only declaration gets a real
  /// order on its `Record<Db>` beside a `Graphql` of `()`.
  ///
  /// `key` is the borrowing conversion, which [`address_conversions`](Self::address_conversions)
  /// has already emitted: a key is built from the record's columns, and `From<&Record>` is that
  /// build. Writing the field reads by hand would be the same body twice, and the two would drift
  /// the first time a scoped rename moved a column.
  ///
  /// `id_ref` cannot borrow through that conversion and does not try: the field reads are ONE
  /// expression each, and the two sites read different structs — the record's own field on one side,
  /// the key's column on the other. Both names come from the model's id column, so a scoped rename
  /// moves them together.
  ///
  /// # The ID's FIVE BOUNDS are instantiated here, and that is the ruling's *强制*
  ///
  /// *id有这些属性应该是必须的* — `Hash + Eq + Clone + Send + Sync`. The obligation rides
  /// [`ids_are_keys`](../../../ingraph/fn.ids_are_keys.html) as `const _: fn() = …::<Id>;`, the
  /// same shape [`relate`](super::relate)'s forward equation takes, and it is emitted UNCONDITIONALLY
  /// — beside the impl that names the id rather than beside the batching seam that first wanted
  /// them, because a mandate conditional on a consumer is not a mandate. A record that persists
  /// nowhere, publishes no wire face and is never batched still owes them, and finds out at its own
  /// `id` field.
  ///
  /// It costs the corpus nothing: the sealed id vocabulary satisfies all five, measured before the
  /// rule was written. What it buys is that the FIRST declaration whose id would not answer is
  /// refused where it is written.
  fn binding(&self) -> proc_macro2::TokenStream {
    let record = &self.record;
    let key = &self.key.name;
    let id = &self.key.id.ty;
    let field = &self.key.id.source;
    let column = &self.key.id.name;
    let lineage = match &self.lineage {
      Some(lineage) => {
        let name = &lineage.name;
        quote!(#name)
      }
      None => quote!(()),
    };
    let row = if self.persist.is_some() {
      quote!(Self)
    } else {
      quote!(())
    };
    let wire = if self.graphql.is_some() {
      quote!(Self)
    } else {
      quote!(())
    };
    let transformer = self.framework(&["transform"], "Transformer");
    let identifiable = self.framework(&["transform"], "Identifiable");
    // THE FIVE BOUNDS, instantiated at the declaration — see [`Self::binding`]'s note. Beside the
    // impl that NAMES the id rather than in a family of its own, so the obligation and the type it
    // is about are one item apart.
    let keyable = self.framework(&["transform"], "ids_are_keys");
    // A REWRITE has no field to borrow out of: the id is behind the wrapped type's own accessor,
    // which this seat requires to hand it back BY REFERENCE. See [`crate::remote`].
    let id_read = if self.remote.is_some() {
      self.remote_id_ref()
    } else {
      quote!(&self.#field)
    };
    quote! {
      const _: fn() = #keyable::<#id>;

      #[automatically_derived]
      impl #identifiable for #record {
        type Id = #id;

        #[inline]
        fn id_ref(&self) -> &#id {
          #id_read
        }
      }

      #[automatically_derived]
      impl #transformer for #record {
        type Key = #key;
        type Lineage = #lineage;
        type Record = #row;
        type Graphql = #wire;

        #[inline]
        fn key(&self) -> #key {
          <#key as ::core::convert::From<&#record>>::from(self)
        }
      }

      #[automatically_derived]
      impl #identifiable for #key {
        type Id = #id;

        #[inline]
        fn id_ref(&self) -> &#id {
          &self.#column
        }
      }
    }
  }

  /// The record's WIRE FACE: `Graphql` on the record, and the two carriers its halves are — NOTHING
  /// at all where the declaration wrote no `graphql(…)` block.
  ///
  /// The predicate is the block's presence, which is what [`Graphql::faces`] emits the three wire
  /// types under, so no impl here can name a type this emission never wrote.
  ///
  /// # The halves used to be CARRIERS, and they are the OBJECTS now
  ///
  /// A face's half is a BUNDLE, so binding one to a NEIGHBOURING wire type would have made that
  /// type the namespace for its siblings: `Input = <E>Filter` reads *the filter's filter is itself*.
  /// What that argument never required was that the bundle be EMPTY — and both halves have their own
  /// content now, so each names its siblings from a type that is one of the things it is about. The
  /// output object HAS a key; the argument object HAS a filter and an order.
  ///
  /// With content they are API, so they leave the anonymous const for the top level, take the
  /// RECORD's visibility — an associated type binding on a public record's impl is public interface
  /// and anything less visible is `E0446` — and join
  /// [`emitted_types`](RecordModel::emitted_types), which is what the collision rule reads. That
  /// last is a real change: an author who wrote a `<E>GraphqlInput` of their own was not refused
  /// while the carrier hid in the const, and is now, because the name lands in their scope.
  ///
  /// [`Graphql::faces`] writes both types; this writes only what BINDS them, which is why the two
  /// sit apart.
  ///
  /// # `Input::OrderBy` is the STORAGE term, and one type is the law rather than a shortcut
  ///
  /// The order a client asks for and the order a page is resumed from are one type because every
  /// variant a client can name has to be one the engine can PUSH into the statement — a wire variant
  /// honoured in memory would put a sort between the database's `LIMIT` and the page's delivery. So
  /// this names [`RecordModel::ordering`]'s enum where it exists, and `()` where it does not: a
  /// declaration with a wire face and no `persist(…)` block has no column to order by, and the two
  /// predicates part exactly there.
  fn wire_binding(&self) -> proc_macro2::TokenStream {
    let Some(graphql) = &self.graphql else {
      return proc_macro2::TokenStream::new();
    };
    let record = &self.record;
    let input = graphql.input.safe();
    let output = graphql.output.safe();
    let filter = graphql.filter.safe();
    let key_output = graphql.key_output.safe();
    let order_by = if self.orderable() {
      let name = self.order_by.safe();
      quote!(#name)
    } else {
      quote!(())
    };
    // The QUERY UNIT where this record has root fields, and `()` where it has none — the same shape
    // `order_by` above takes, and the same kind of statement: a record whose store carries no query
    // face has nothing a root could mount, and the empty product is what a fold measures its
    // membership against.
    let queries = match self.wire_query_row() {
      Some(_) => {
        let name = crate::model::default_queries_name(record);
        quote!(#name)
      }
      None => quote!(()),
    };
    let face = self.framework(&["transform"], "Graphql");
    let input_face = self.framework(&["transform"], "GraphqlInput");
    let output_face = self.framework(&["transform"], "GraphqlOutput");
    quote! {
      #[automatically_derived]
      impl #input_face for #input {
        type Filter = #filter;
        type OrderBy = #order_by;
      }

      #[automatically_derived]
      impl #output_face for #output {
        type Key = #key_output;
      }

      #[automatically_derived]
      impl #face for #record {
        type Input = #input;
        type Output = #output;
        type Query = #queries;
      }
    }
  }

  /// The record's HYDRATION PROJECTION: `Hydrates`, naming the database a hydrated read of this
  /// record's rows runs against — and NOTHING at all where there is no such database.
  ///
  /// # It is [`wire_query_row`](Self::wire_query_row)'s answer, and never a first-declared computed
  /// again
  ///
  /// That function is already the authority on where this record's ROOT FIELDS read — the first
  /// declared database with a query face whose row raises onto the wire — and its own note carries
  /// the law: *a client must never see a field that varies with a deployment's storage choice*. A
  /// record answering `reel(id:)` out of one store and a hydrated hit out of another would be that
  /// variance one road over, and a schema installing one `SqlDoor` per store would have to install
  /// two for one record. Reading the one function is what makes the two identical by construction;
  /// two independent walks agreeing today is what would let them stop agreeing.
  ///
  /// It also settles the PRESENCE question for free. `wire_query_row` is `None` for a record with no
  /// `graphql(…)` block, for one with no queryable database, and for one whose row does not raise —
  /// a record with no `persist(…)` block being an instance of the second — so there is no separate
  /// condition here to keep in step, and the projection cannot be well formed where
  /// [`queries_type`](Self::queries_type) minted no unit.
  ///
  /// # It rides the DATABASE's gate, where the entity binding beside it rides none
  ///
  /// [`binding`](Self::binding) and [`wire_binding`](Self::wire_binding) name only this emission's
  /// own types, so they exist in every build. This one binds [`DatabaseBackend::backend_type`], which is the one place an
  /// expansion names a backend CONCRETELY — so it takes the same gate
  /// [`vocabulary`](DatabaseBackend::vocabulary) takes, and for that impl's reason: ungated, a
  /// declaration naming Postgres would fail to compile in a build with no Postgres driver.
  ///
  /// What a shut gate costs is stated rather than hidden: a build carrying the SQL family but not
  /// THIS record's dialect has no impl, so a derived index over it is `E0277` at the road that
  /// hydrates — the same refusal a record with no `persist(…)` block gets, at the same span, and one
  /// a build that compiled the dialect its declaration named never sees.
  fn hydration_binding(&self) -> proc_macro2::TokenStream {
    let Some(database) = self.wire_query_row() else {
      return proc_macro2::TokenStream::new();
    };
    let record = &self.record;
    let backend = database.backend_type(self);
    let hydrates = self.framework(&["transform"], "Hydrates");
    let gate = self.framework(&["gate"], &database.kind().gate().to_string());
    quote! {
      #gate! {
        #[automatically_derived]
        impl #hydrates for #record {
          type Db = #backend;
        }
      }
    }
  }

  /// The `*Key`'s FILESYSTEM face: `KeySegments`, walking the key's columns into the sink one
  /// segment each, lineage root-first and the id last.
  ///
  /// It is the address the local blob store nests directories by, so the order IS the tree — the
  /// parents are the directories and the id is the file. A root has one column, so it pushes one
  /// segment and the file sits directly under the slot; no branch here says so, because
  /// [`Key::columns`](crate::model::Key::columns) already hands back the whole key in that order
  /// and a root's whole key is its id.
  ///
  /// Emitted for EVERY declaration rather than for the ones that store bytes, and that is the
  /// choice worth stating: a declaration carries no word saying which stores will hold it, and the
  /// trait is satisfied by the key's shape alone. What it costs a record that never becomes a file
  /// is one impl; what it buys is that no declaration has to be revisited the day something asks
  /// for its blobs.
  ///
  /// The bound it lands under is the sealed identity VOCABULARY: `Segments::push` takes a
  /// `Segment`, which is the framework's `Id` plus a rendering the framework owns, so a key column
  /// of a type that vocabulary never admitted is `E0277` at the `#[ingraph::record(…)]`. That is the
  /// storability audit's shape one layer over — the refusal lands at the declaration that wrote
  /// the column rather than at the first store that could not address it.
  ///
  /// Every column is pushed BY REFERENCE, `copy` marked or not. `push` takes `&I` whatever the
  /// column's projection is, so the marker — which decides what an accessor hands back — changes
  /// nothing here, and there is no second spelling for the walk to pick between.
  ///
  /// The field names are the KEY's, so a `key(rename = "…")` reaches the walk as it reaches the
  /// struct: the segment order is the key's own column order and the reads are its own fields.
  fn address_segments(&self) -> proc_macro2::TokenStream {
    let key = &self.key.name;
    let key_segments = self.framework(&["store"], "KeySegments");
    let segments = self.framework(&["store"], "Segments");
    // A lineage that is a CHOICE is not a column the vocabulary can render — it is a whole address
    // of its own — so it walks rather than pushes, and the walk is emitted beside this one.
    let fanned = self.fanned_lineage_name();
    let columns = self.key.columns().map(|column| {
      let name = &column.name;
      if fanned.is_some_and(|_| name == &fanned_lineage_column()) {
        quote!(#key_segments::segments(&self.#name, out);)
      } else {
        quote!(out.push(&self.#name);)
      }
    });
    let choice = fanned.map(|(name, kinds)| {
      let arms = kinds.iter().map(|kind| {
        let variant = &kind.variant;
        let word = variant.to_string();
        quote! {
          Self::#variant(__ingraph_key) => {
            out.push_word(#word);
            #key_segments::segments(__ingraph_key, out);
          }
        }
      });
      quote! {
        #[automatically_derived]
        impl #key_segments for #name {
          #[inline]
          fn segments(&self, out: &mut #segments) {
            match self { #(#arms)* }
          }
        }
      }
    });
    quote! {
      #[automatically_derived]
      impl #key_segments for #key {
        #[inline]
        fn segments(&self, out: &mut #segments) {
          #(#columns)*
        }
      }

      #choice
    }
  }

  /// This node's lineage where it is a CHOICE: the emitted enum's name, and its variants.
  fn fanned_lineage_name(&self) -> Option<(&syn::Ident, &[Kind])> {
    let lineage = self.lineage.as_ref()?;
    match &lineage.shape {
      Shape::Kinds(kinds) => Some((&lineage.name, kinds)),
      Shape::Path(_) => None,
    }
  }

  /// One emitted type, as two pieces the caller places separately: the STRUCT, which is the API and
  /// stays at top level, and its inherent IMPL, which goes inside the record's anonymous const.
  ///
  /// The type and its methods are exactly as visible as the record — a private record's key must not
  /// leak into its crate's public API — and the FIELDS carry `pub(crate)` whatever that visibility
  /// is, which is [`crate::host`]'s stamp one type over: an address's columns are read by the
  /// emitted code and by the crate around it, and they are never wider than the crate, so a public
  /// record's key still hands its columns out through the accessors alone.
  ///
  /// The stamp is what the KEY-PARENT EQUATION is written against. A fusing node reads its parent's
  /// key COLUMN BY NAME, and a private field would make every such read `E0616` at a span the author
  /// cannot act on — so the error an author sees is the one the ruling names, `E0609` for a column
  /// that moved. Fusion across CRATES is out of reach by the same rule, and deliberately: widening
  /// to `pub` would put a declaration's columns in its crate's public API without anyone writing
  /// the word.
  ///
  /// Every item `missing_docs` covers is documented, because a consumer that denies the lint cannot
  /// edit a generated type to satisfy it. Crate-visible fields are not covered, and are left to the
  /// accessor that projects them rather than described twice.
  fn address_type<'a>(
    &self,
    name: &syn::Ident,
    doc: &str,
    new_doc: &str,
    columns: impl Iterator<Item = &'a Column> + Clone,
    id: Option<&Column>,
  ) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
    let vis = &self.vis;
    let (names, types): (Vec<&syn::Ident>, Vec<&syn::Type>) = columns
      .clone()
      .map(|column| (&column.name, &column.ty))
      .unzip();
    let families = columns.map(|column| {
      // Identity by IDENTITY, not by name: a scoped rename can give a lineage step the same name the
      // id carries in another type, and comparing strings would mis-describe it.
      let subject = if id.is_some_and(|id| core::ptr::eq(id, column)) {
        "row\'s own id".to_owned()
      } else {
        format!("`{}` step of the lineage path", column.name)
      };
      // NO gate: a key column is the row's own address, and `identity is not conditional` is a
      // refusal at the front end — see `ingraph_derive::attribute`.
      column.methods(
        &self.vis,
        &self.krate,
        &subject,
        true,
        &proc_macro2::TokenStream::new(),
      )
    });
    let doc = leading(doc);
    let new_doc = leading(new_doc);
    let declaration = quote! {
      #[doc = #doc]
      #[derive(
        ::core::fmt::Debug,
        ::core::clone::Clone,
        ::core::cmp::PartialEq,
        ::core::cmp::Eq,
        ::core::hash::Hash
      )]
      #vis struct #name {
        #(pub(crate) #names: #types,)*
      }
    };
    let arity = wide_signature();
    let methods = quote! {
      impl #name {
        #[doc = #new_doc]
        #arity
        #[inline]
        #vis const fn new(#(#names: #types,)*) -> Self {
          Self { #(#names,)* }
        }

        #(#families)*
      }
    };
    (declaration, methods)
  }

  /// One emitted type's pair of conversions from the record.
  ///
  /// `#[automatically_derived]` belongs on these and only on these: it is valid on a TRAIT impl and
  /// warns on an inherent one, so the inherent impls beside them carry nothing.
  ///
  /// The borrowing one clones through `Clone::clone(&…)` rather than `….clone()`. That is not
  /// style: `clone_on_copy` is a default-on clippy lint, and a generated `.clone()` on a `Copy`
  /// column would fail any consumer building under `-D warnings` — which a macro cannot avoid, since
  /// it cannot know whether a column's type is `Copy`. The call form it does not fire on is the one
  /// to keep.
  fn address_conversions<'a>(
    &self,
    name: &syn::Ident,
    columns: impl Iterator<Item = &'a Column> + Clone,
  ) -> proc_macro2::TokenStream {
    let record = &self.record;
    let (names, sources): (Vec<&syn::Ident>, Vec<&syn::Ident>) =
      columns.map(|column| (&column.name, &column.source)).unzip();
    // A REWRITE reads its columns through the wrapped type's accessors, so the two bodies collapse
    // into one: there is nothing to move OUT of a wrapper, and the borrowing read is the only read.
    let binding = format_ident!("record");
    let (moved, borrowed): (Vec<_>, Vec<_>) = if self.remote.is_some() {
      let reads: Vec<proc_macro2::TokenStream> = sources
        .iter()
        .map(|source| self.remote_read(&binding, source))
        .collect();
      (reads.clone(), reads)
    } else {
      (
        sources
          .iter()
          .map(|source| quote!(record.#source))
          .collect(),
        sources
          .iter()
          .map(|source| quote!(::core::clone::Clone::clone(&record.#source)))
          .collect(),
      )
    };
    quote! {
      #[automatically_derived]
      impl ::core::convert::From<#record> for #name {
        #[inline]
        fn from(record: #record) -> Self {
          Self { #(#names: #moved,)* }
        }
      }

      #[automatically_derived]
      impl<'a> ::core::convert::From<&'a #record> for #name {
        #[inline]
        fn from(record: &'a #record) -> Self {
          Self { #(#names: #borrowed,)* }
        }
      }
    }
  }

  /// A path to one of the names the framework SHELVES, reached the ONE way emitted code is allowed
  /// to reach them: the model's crate path, then `__private`, then the module the item lives in.
  ///
  /// Emitted code depends on that shelf rather than on where the framework keeps an item, so the
  /// framework can move or rename one without regenerating anyone's expansion. The shelf mirrors the
  /// crate's modules rather than flattening them, which is why the module segments are here: a glob
  /// per module needs no maintenance as the crate grows, and two modules that each define a `Column`
  /// stay apart.
  ///
  /// **The module is a PATH, not one segment.** Mirroring is recursive, so a family that is a module
  /// inside a module is shelved that way too and is named that way here:
  /// `framework(&["comparison", "sql"], "SqlScalarComparison")` is
  /// `#krate::__private::comparison::sql::SqlScalarComparison`. Flattening the shelf to keep the
  /// segment single would give up exactly what mirroring buys — two modules that each define a
  /// `Column` would collide — so the depth belongs here rather than in the shelf's shape.
  ///
  /// A SLICE rather than a `"comparison::sql"` string: every element becomes one identifier, so
  /// nothing here parses `::` and no element can carry a separator that a later ident would choke
  /// on. An empty slice would name an item directly beneath `__private`, which is the flattened
  /// shape the guard below refuses.
  ///
  /// A VENDORED crate the framework re-exports takes that segment under its OWN name, so
  /// `framework(&["serde"], "Serialize")` is `#krate::__private::serde::Serialize`. The shape is the
  /// same, which is what lets one rule and one check cover both.
  ///
  /// The rule is not left to habit — `tests::every_framework_path_goes_through_a_private_module`
  /// walks the emission's tokens and fails on any path rooted at the crate that skips `__private`
  /// OR names an item directly beneath it.
  pub(crate) fn framework(&self, module: &[&str], name: &str) -> proc_macro2::TokenStream {
    framework(&self.krate, module, name)
  }

  /// The shelf path to a whole VENDORED crate — `#krate::__private::serde` — as the string a derive
  /// that takes a crate-path override wants.
  ///
  /// A `String` rather than tokens because its only use is inside a string literal: serde's
  /// `#[serde(crate = "…")]` is spelled that way, and the derive parses the string back into a path.
  /// The token walk cannot see a literal, so the emitted one is pinned by a test of its own
  /// (`tests::the_mongo_document_reaches_serde_through_the_shelf`).
  ///
  /// A path a DECLARER wrote (`#[ingraph(crate = "…")]`) is carried through verbatim, so whatever
  /// prefix that path uses has to work in a `use` statement as well as in type position — serde
  /// binds its internal `_serde` to it with one. `::krate` and `self::path::to::krate` both do.
  pub(crate) fn vendored(&self, krate: &str) -> String {
    vendored(&self.krate, krate)
  }
}

impl DatabaseBackend {
  /// Whether this database keeps `column`'s elements in an EDGE TABLE — the one question that
  /// decides whether the column is a value of this row or a second table correlated to it.
  ///
  /// Two facts and no inference. The DECLARATION classified the column a collection (the word, read
  /// by [`RecordModel::collects`]), which alone answers nothing — a scalar is a scalar in every
  /// dialect. And the strategy is stated, by one of the two parties that can state it:
  ///
  /// * the DIALECT, where it has no choice — [`DatabaseKind::edge_collections`], which is
  ///   `ingraph`'s `CollectionStorage` read one layer up, and true for the two dialects with no
  ///   array type;
  /// * the DECLARATION, where it has — [`PersistColumn::edge`], Postgres's optional word, the
  ///   element-level fact a macro holding tokens cannot read out of a trait row.
  ///
  /// An `or` rather than a branch, and it is not a shortcut: `ingraph-derive` refuses `edge` in
  /// every block but Postgres's, so the two halves are disjoint by construction and neither can
  /// quietly cover for the other.
  pub(crate) fn edge_stored(&self, model: &RecordModel, column: &PersistColumn) -> bool {
    (self.kind().edge_collections() || column.edge) && model.collects(&column.source)
  }

  /// This database's own entry for the record field `source`, or [`None`] where the declaration
  /// narrowed the column out of this database.
  ///
  /// The ONE lookup every per-database reader goes through, and it is by SOURCE rather than by
  /// position for a reason a position cannot express: the shared list is the DECLARATION's, so it is
  /// the widest of them, and a database that narrowed a column has a shorter one. An index read off
  /// the shared list would name a different column here, or run off the end.
  pub(crate) fn stores(&self, source: &syn::Ident) -> Option<&PersistColumn> {
    self
      .columns()
      .iter()
      .find(|column| column.source == *source)
  }

  /// The columns the wire face publishes AND THIS DATABASE STORES, at this database's own names,
  /// types and refinements.
  ///
  /// [`RecordModel::queried_columns`] states the schema's vocabulary; this is the STORAGE-true
  /// subset of it, and the two now differ. It is what the comparison's members, its `where` clause
  /// and its lowering walk — a member for a column this table has not got would render a predicate
  /// naming a column no statement can name.
  ///
  /// # The CROSSING joins the two lists rather than zipping them
  ///
  /// The filter's rows are the declaration's and this list is this database's, so a narrowing
  /// database's comparison has FEWER members than the filter has fields. The crossing therefore
  /// walks the filter's rows and asks [`stores`](Self::stores) for each — a row whose column is here
  /// crosses as before, and one whose column is not answers with `ColumnNotStored` where the client
  /// wrote an operand and with nothing at all where it wrote none. See
  /// `DatabaseBackend::filter_crossing`, which is the one place the join is spelled.
  pub(crate) fn compared(&self, model: &RecordModel) -> Vec<&PersistColumn> {
    model
      .queried_columns()
      .into_iter()
      .filter_map(|(_, shared)| self.stores(&shared.source))
      .collect()
  }

  /// Whether this database MIRRORS `column` into an order-preserving companion column — the join of
  /// the DECLARATION's `sortable` word and this database's storage form.
  ///
  /// Two facts and no inference, exactly as [`edge_stored`](Self::edge_stored) is two: the word was
  /// written, and this database keeps the collection in a table of its own. A dialect with a native
  /// array orders the collection itself, so there is nothing for a companion to carry and none is
  /// emitted — which is the ruled per-backend answer rather than a per-database knob a declaration
  /// could turn.
  ///
  /// It reads [`edge_stored`](Self::edge_stored) rather than restating it, so the column a write
  /// fills, the column a `CREATE TABLE` declares and the column an `ORDER BY` renders cannot
  /// disagree about which collections have one.
  pub(crate) fn mirrors(&self, model: &RecordModel, column: &PersistColumn) -> bool {
    self.edge_stored(model, column) && model.sortable(&column.source)
  }

  /// Whether this database gives `column` the VALUE-LED ACCESS PATH on its ELEMENTS' OWN TABLE — the
  /// join of the DECLARATION's `indexed` word and this database's storage form.
  ///
  /// [`mirrors`](Self::mirrors)' shape one word over, and it reads
  /// [`edge_stored`](Self::edge_stored) for that method's reason: the party that declares the edge
  /// table and the party that asks it for a second index cannot disagree about which collections
  /// have one.
  ///
  /// # The OTHER storage form's half is not emitted from here, and cannot be
  ///
  /// A collection this database keeps in a COLUMN is a Postgres array, and a record carrying one
  /// gets no blueprint at all: `Vec<T>` has no `StoredAs` row, deliberately — a `CREATE TABLE`
  /// spells that column `bigint[]` and `information_schema` answers `ARRAY`, and one `const` cannot
  /// be both — so `RecordModel::describable` subtracts the database and there is nothing for
  /// `Table::with_collection_indexes` to be written onto. See this module's own roster note, where
  /// the subtraction is measured. The word is carried on the FIELD either way, so the day that wall
  /// comes down is the day the array half starts rendering; the framework's side of it is written
  /// already.
  pub(crate) fn seeks_by_value(&self, model: &RecordModel, column: &PersistColumn) -> bool {
    self.edge_stored(model, column) && model.indexed(&column.source)
  }

  /// The name this database's companion column for `column` wears.
  ///
  /// The mint is [`alias::sort_column`](crate::alias::sort_column) and this is the one call to it
  /// from an emission: it takes the column's EXTERNAL name — what a rename left it called here — so
  /// a companion follows the column it is the order of.
  ///
  /// It also takes THIS database's resolved namespace, for the reason the mint states: the fence a
  /// declaration is held to is the union of what its databases declared, so a record that moved the
  /// prefix everywhere may legally declare a column in the framework's own namespace — and a
  /// companion minted there anyway would be the collision the fence exists to make impossible.
  pub(crate) fn sort_column(&self, model: &RecordModel, column: &PersistColumn) -> String {
    crate::alias::sort_column(
      self.storage().aliases.prefix_in(&model.prefix),
      &self.external(model, column),
    )
  }

  /// Whether this database materializes `column` as a correlated AGGREGATE on the page statement
  /// rather than as a gather of its own.
  ///
  /// The dialect with a native array is the dialect that can aggregate into one, so the split is
  /// exactly [`DatabaseKind::edge_collections`]'s: a dialect that has no array has nothing to
  /// `array_agg` INTO, and its edge-stored collections take the second statement. Postgres's
  /// edge-stored ones take the subselect, which is one statement and no tear — see the engine's own
  /// `query::sql::hydrate`, where both materializations live.
  pub(crate) fn aggregates(&self, model: &RecordModel, column: &PersistColumn) -> bool {
    self.edge_stored(model, column) && !self.kind().edge_collections()
  }

  /// Whether this database's row carries an EXTRACTION — the emitted `from_document`, which is
  /// MongoDB's alone.
  ///
  /// ONE condition, and it used to be two. A flattened column took the extraction away: its type's
  /// keys were the document's own, so a read at the column's name found nothing whatever the
  /// document held, and a partial extraction would have left a field unset. `flatten` is a SQL
  /// family's word now — a document NESTS a held value, which is the composite form the server
  /// indexes — so a mongo row has no flattened column to be defeated by and the condition went with
  /// the word.
  ///
  /// It is here rather than inside that emitter because TWO parties ask: the emission, and the
  /// method enumeration that has to name every method the emission declares. Two predicates would be
  /// a declaration refused for a name it does not get, or a name nothing knew was taken.
  pub(crate) fn extracts(&self) -> bool {
    !self.kind().is_sql()
  }

  /// The name `column` is stored under in this database — the ONE authority on an external name,
  /// wherever an emission writes one.
  ///
  /// It is the column's own name everywhere except ONE row: MongoDB stores a record's id as `_id`.
  /// That is the server's name rather than this framework's — MongoDB mints an `_id` for every
  /// document that arrives without one and indexes it uniquely, so a document carrying both the
  /// minted one and a declared `id` would be one row with two identities, with the wrong one
  /// indexed.
  ///
  /// The declaration and the wire face still say `id`, so the mapping lives in exactly two places
  /// and this is one of them: the derive's `rename` and the emitted extraction's read BOTH come
  /// through here, so they cannot differ. The other is `ingraph`'s own `field_key`, which is where
  /// every RENDERED field path goes — a filter's key, a `$sort` entry, a keyset arm — and the two
  /// agree because both are keyed on the id COLUMN rather than on the word `id`.
  ///
  /// The column is identified by its SOURCE field rather than by its name, for the reason every
  /// other identity check in this emitter is: a `<db>(rename)` moves the name, and a
  /// comparison on the string would then map a column that is not the id or fail to map the one
  /// that is.
  pub(crate) fn external(&self, model: &RecordModel, column: &PersistColumn) -> String {
    if self.kind().is_sql() || column.source != model.key.id.source {
      return column.name.to_string();
    }
    crate::model::MONGO_ID.to_owned()
  }

  /// The type this database's row FIELD carries for `column`.
  ///
  /// The stored type as declared, except for an edge-stored collection: there the declared type is
  /// ONE ELEMENT's — which is what the comparison layer already reads it as, since a collection
  /// operand binds one member at a time — and the row holds the LIST of them, which is what a
  /// materialization fills and what the record is rebuilt from.
  ///
  /// So a column declared `sqlite(type = "BeU128")` under `list(scalar)` is
  /// `::std::vec::Vec<BeU128>` on the row and `BeU128` in the predicate, from one declaration. The
  /// crossing the declaration names is the whole collection's — domain in, `Vec<element>` out —
  /// because that is the one place an `Option<Vec<…>>` collapse and an element conversion can both
  /// be written, and it is where the declaration already puts every other column's crossing.
  pub(crate) fn row_field(
    &self,
    model: &RecordModel,
    column: &PersistColumn,
  ) -> proc_macro2::TokenStream {
    let ty = column.ty();
    if self.kind().is_sql() && model.collects(&column.source) {
      return quote!(::std::vec::Vec<#ty>);
    }
    quote!(#ty)
  }

  /// One self's projection of a record: the struct, and its impls.
  ///
  /// **No constructor.** The argument is the record's own, at the top of this module: a real
  /// aggregate has twenty-odd fields, so a positional `new` would be unusable and
  /// transposition-prone. A row also has two construction paths already — the conversion from the
  /// record, and the decode a database reads it back through (`FromRow`, emitted here;
  /// `Deserialize`, derived) — so a third would be the only one that could put the columns in the
  /// wrong order.
  ///
  /// **Accessors only, no mutators.** A key gets `set_*`/`with_*` because stepping to a neighbouring
  /// key has a consumer; nothing edits a row in place. It is produced by a conversion or a decode and
  /// consumed by a write or a conversion, and the accessors are what those need.
  ///
  /// Every column's external name is written out UNIFORMLY, not only when the name had to be
  /// mangled — so the mapping never depends on how a derive happens to treat an identifier, and a
  /// reader of the expansion can see each column's real name without knowing the mangling rule.
  /// WHERE it is written is the family's answer: a `rename` attribute on the field, or the read
  /// inside the decode the family emits. See [`Mapping`].
  ///
  /// **Every column carries a name here, including a held value's**, and the family that maps by
  /// ATTRIBUTE is the one where that is the whole story: a document nests a held value under this
  /// field's own key, so the name is the key and nothing is flattened. The FLATTENING entry that
  /// used to stand in `flatten`'s place is gone with the word, which is now the SQL family's.
  ///
  /// A family that maps by DECODE is where the gap still is, and it is worth stating plainly: a
  /// decode reads ONE column per field under one name, so a held value spanning several columns is
  /// stored today as one column of its own type — which is what the SQL predicate over it does NOT
  /// assume, since that renders `rate_num`/`rate_den` from the segments it walks. The two disagree,
  /// the disagreement predates `flatten` in either position, and what closes it is statement
  /// emission reading `CompositeComparison::SEGMENTS`. See that trait for the measurement.
  pub(crate) fn row(
    &self,
    model: &RecordModel,
  ) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
    let family = &self.kind().family(model);
    let vis = &model.vis;
    let record = &model.record;
    let name = self.name();
    let derives = &family.derives;
    let attrs = &family.attrs;
    let what = (family.what)(self.kind());
    let noun = family.noun;

    let fields = self.columns().iter().map(|column| {
      let field = column.name.safe();
      let ty = self.row_field(model, column);
      let naming = match family.mapping {
        Mapping::Attribute(attribute) | Mapping::AttributeAndDecode(attribute, _) => {
          let attribute = format_ident!("{attribute}");
          let external = self.external(model, column);
          // The VIA rides the same attribute as the name, one list rather than two, because it is
          // the same derive being told two things about one field — and it is written for EVERY
          // column or for none, which is what keeps the choice out of this emitter's hands. See
          // [`Family::via`].
          family.via.as_ref().map_or_else(
            || Some(quote!(#[#attribute(rename = #external)])),
            |via| Some(quote!(#[#attribute(rename = #external, with = #via)])),
          )
        }
        Mapping::Decode(_) => None,
      };
      // The CONDITION on the ROW's field, read off the record field this column projects: a record
      // that loses a field loses its column, and a row holding a column for a field the build
      // removed is exactly the orphan the seat exists to close.
      let gate = model.gate(&column.source);
      quote! {
        #gate
        #naming
        #field: #ty,
      }
    });
    let families = self.columns().iter().map(|column| {
      let subject = format!("`{}` column", column.name);
      let mut shaped = column.as_column();
      // The accessor hands back what the FIELD holds, which for an edge-stored collection is the
      // list rather than one element — see [`row_field`](Self::row_field).
      let held = self.row_field(model, column);
      shaped.ty = syn::parse2(held).expect("a field type is a type");
      shaped.methods(
        &model.vis,
        &model.krate,
        &subject,
        false,
        &model.gate(&column.source),
      )
    });

    // WHAT THE ROW DOES NOT HOLD, said on the row itself. A reader who finds a declared field
    // missing here has one question, and the doc answers it at the type rather than at the
    // declaration: the word is on the field, and the consequence is here.
    //
    // TWO absences, and the sentence tells them apart because the reader's next question differs.
    // A `skip`ped field is missing from EVERY row of this record; a narrowed one is missing from
    // this row and is a column of the record's other databases, which is a fact a reader holding
    // one row type cannot find out anywhere else.
    let withheld: Vec<String> = model
      .fields
      .iter()
      .filter(|field| field.skip.is_some())
      .map(|field| format!("`{}`", field.column.source))
      .collect();
    let narrowed: Vec<String> = self
      .storage()
      .fills
      .iter()
      .map(|filled| format!("`{}`", filled.source))
      .collect();
    let mut omissions = String::new();
    if !withheld.is_empty() {
      omissions.push_str(&format!(
        "\n\n# Omitted\n\nThe declaration wears `skip` for {list}, so no row of this record \
         mints a column for {them} — a read fills {them} from `Default::default()`, or from the \
         function `skip(default = \"…\")` named.",
        list = withheld.join(", "),
        them = if withheld.len() == 1 { "it" } else { "them" },
      ));
    }
    if !narrowed.is_empty() {
      omissions.push_str(&format!(
        "\n\n# Narrowed out of this database\n\n{list} {are} {a}columns of this record's other \
         databases and not of `{db}`, so this row mints none — a read supplies {them} from the \
         function `{db}(skip(default = \"…\"))` named.",
        list = narrowed.join(", "),
        are = if narrowed.len() == 1 { "is" } else { "are" },
        a = if narrowed.len() == 1 { "a " } else { "" },
        them = if narrowed.len() == 1 { "it" } else { "them" },
        db = self.kind().as_str(),
      ));
    }
    let doc = leading(&format!(
      "The {what} {noun} a [`{record}`] is stored as.{omissions}"
    ));
    let declaration = quote! {
      #[doc = #doc]
      #[derive(#derives)]
      #attrs
      #vis struct #name {
        #(#fields)*
      }
    };
    let conversions = self.conversions(model);
    let decode = match family.mapping {
      Mapping::Attribute(_) => proc_macro2::TokenStream::new(),
      Mapping::Decode(emit) | Mapping::AttributeAndDecode(_, emit) => emit(self, model),
    };
    let equality = self.equality(model);
    let methods = quote! {
      impl #name {
        #(#families)*
      }

      // AFTER the conversions, which is where the derive it replaced effectively sat: a derive is
      // expanded at the container and the conversions are the first impls written by hand, so a
      // reader walking this expansion — and a test finding "the first impl on the row" — sees the
      // same item it always did.
      #conversions
      #equality
      #decode
    };
    (declaration, methods)
  }

  /// **THE ROW'S `PartialEq`, WRITTEN RATHER THAN DERIVED** — one `ColumnEq` call per stored column,
  /// folded.
  ///
  /// # Why the derive left, and what did NOT leave with it
  ///
  /// `#[derive(PartialEq)]` demands `PartialEq` of every declared field type, and that demand is
  /// made by generated code an author cannot edit. `regex::Regex` implements none and cannot be
  /// given one outside `regex` itself — both the trait and the type are foreign, so the impl is
  /// `E0117` here and in every other crate — which made a pattern column `E0369` raised inside an
  /// expansion, pointing at a field the author wrote and at code the author cannot reach.
  ///
  /// What replaces it is not a weaker row but the SAME row with its obligation moved: this fold asks
  /// each field type for [`ColumnEq`], whose answer is `self == other` for every type that has a
  /// `PartialEq` and is the pattern TEXT for the one that has not. So a record that compared before
  /// compares identically, field for field, and one that could not compile now does.
  ///
  /// # The gate is `Condition::either`'s, because a folded `&&` is the seat an attribute cannot sit
  /// in
  ///
  /// `#[cfg]` on a TERM of an expression is `stmt_expr_attributes` and unstable, so a per-column
  /// predicate cannot ride the `&&` chain the way it rides a struct-expression field or an array
  /// element. [`Condition::either`] is the crate's own answer: the fork moves one grain out into a
  /// block of two `let` STATEMENTS, and a column the build removed contributes the identity for
  /// `&&` rather than a term. An unconditional field pays not one token for the seat.
  ///
  /// # The SPAN is the field's, which is the whole of the refusal seat
  ///
  /// The call is [`quote_spanned!`] at the record field this column projects, exactly as the
  /// storability audit's `StoredAs` projection is: a type with no `ColumnEq` row is `E0277` naming
  /// the trait, with the caret on the token the AUTHOR wrote, not on a fold inside an expansion.
  /// `ColumnEq`'s own `#[diagnostic::on_unimplemented]` says the rest.
  ///
  /// # It is ungated, as the row it sits beside is
  ///
  /// `ColumnEq` names no backend, so nothing here rides a dialect's feature — the same discipline
  /// the cursor codec's rows keep by naming `cursor::dialect` markers rather than `sqlx` ones.
  ///
  /// [`ColumnEq`]: https://docs.rs/ingraph
  /// [`Condition::either`]: crate::model::Condition::either
  fn equality(&self, model: &RecordModel) -> proc_macro2::TokenStream {
    let name = self.name();
    let column_eq = model.framework(&["column"], "ColumnEq");
    let same = quote!(true);
    let comparisons: Vec<proc_macro2::TokenStream> = self
      .columns()
      .iter()
      .map(|column| {
        let field = column.name.safe();
        let ty = self.row_field(model, column);
        let at = column.source.span();
        let compared = quote_spanned! {at=>
          <#ty as #column_eq>::column_eq(&self.#field, &__ingraph_other.#field)
        };
        model
          .condition(&column.source)
          .map_or(compared.clone(), |condition| {
            condition.either(&compared, &same)
          })
      })
      .collect();
    // A row with no stored columns at all is a row whose values are all equal, which is what an
    // empty `&&` fold means — spelled as the literal rather than reached by folding nothing.
    let body = if comparisons.is_empty() {
      same
    } else {
      quote!(#(#comparisons)&&*)
    };
    quote! {
      #[automatically_derived]
      impl ::core::cmp::PartialEq for #name {
        #[inline]
        fn eq(&self, __ingraph_other: &Self) -> ::core::primitive::bool {
          #body
        }
      }
    }
  }

  /// The conversions between a record and one self's row — one per direction, and never two.
  ///
  /// **`From` when every conversion is infallible, `TryFrom` when any is fallible, never both.** That
  /// is not a preference: `core` carries `impl<T, U: Into<T>> TryFrom<U> for T`, so an emitted `From`
  /// ALREADY yields a `TryFrom`, and emitting both would collide under coherence. Which is also why
  /// emitting the fallible one costs a caller nothing — `try_into()` resolves either way, so calling
  /// code does not have to know which was emitted.
  ///
  /// The error type is `Box<dyn Error + Send + Sync>` because a row's columns may each fail
  /// differently and there is no type that names all of them. `?` converts through `core`'s blanket
  /// `From<E: Error + Send + Sync + 'static>`, so a conversion function returning any ordinary error
  /// works unchanged. A generated per-row error enum is the better long-term answer and belongs with
  /// the trait layer.
  ///
  /// **The verb rule decides which declaration fills which direction: `from` BUILDS the row and
  /// `into` LEAVES it.** So `<db>(from)` is the write and `<db>(into)` is the read, and
  /// the emitted impl reads literally — `impl From<VideoTrack> for VideoTrackPostgres` is the row
  /// FROM the domain. It is relative to the PROJECTION, not to the domain, which is what makes one
  /// rule serve the rows, the wire faces and the comparisons alike.
  ///
  /// The REVERSE direction — the row back to the record — is emitted only when it can be: field-wise
  /// when the row carries EVERY field of the record, and otherwise only when the database declared a
  /// conversion for the whole row. A partial row cannot rebuild a record it does not carry, and the
  /// container conversion is exactly the seam for supplying what it is missing. Nothing is emitted
  /// that would not compile, and nothing is silently invented.
  fn conversions(&self, model: &RecordModel) -> proc_macro2::TokenStream {
    let record = &model.record;
    let row = self.name();

    // WHERE a column's value comes from — the record's own field, or, under a rewrite, the wrapped
    // type's accessor crossed by `Into`. One seam, so the write leg cannot read a wrapper the way
    // it reads a struct.
    let binding = format_ident!("record");
    let writes = self.columns().iter().map(|column| {
      let field = column.name.safe();
      let source = &column.source;
      let read = if model.remote.is_some() {
        model.remote_read(&binding, source)
      } else {
        quote!(record.#source)
      };
      let value = column.from.apply(read, column.stored.is_some());
      // The struct-expression field carries the gate, which is a stable attribute position — so the
      // write leg builds exactly the row this build declares.
      let gate = model.gate(source);
      quote!(#gate #field: #value,)
    });
    let write = match self.from() {
      Conversion::Default => quote!(Self { #(#writes)* }),
      declared => declared.apply(quote!(record), false),
    };
    // The fallibility of what is ACTUALLY emitted: a container conversion replaces the field-wise
    // body, so the columns' own conversions say nothing about it — read through
    // [`writes_fallibly`](Self::writes_fallibly) rather than decided here, so the query face's own
    // crossing cannot call `From` where a `TryFrom` was written.
    let write_fallible = self.writes_fallibly();
    // The WRITE leg's own cell — `<db>(try_from(error = "…"))` — or the boxed refusal. It
    // was held while nothing stored a record; what types it now is the impl the write lane crosses
    // through, which is this very conversion.
    let write_error = model.error(Crossing::PersistWrite, self.kind());
    let to_row = conversion(
      quote!(#record),
      row,
      &format_ident!("record"),
      write,
      write_fallible.then_some(&write_error),
      &format!("Project a [`{record}`] into the row that stores it."),
    );

    // ONE VALUE PER FIELD the raise supplies, gathered as `(field, expression)` before either body
    // is written: a struct literal spells them as members and a rewrite's BUILDER spells them as
    // the wrapped type's own constructor arguments, and both need the same pairs.
    let mut values: Vec<(syn::Ident, proc_macro2::TokenStream)> = self
      .columns()
      .iter()
      .map(|column| {
        let field = column.name.safe();
        let value = column
          .into
          .apply(quote!(row.#field), column.stored.is_some());
        (column.source.clone(), value)
      })
      .collect();
    // THE FILLS — every field this raise has no column to read, each from the word that said so.
    // Two absences and one walk: the record's own `skip`, which is every database's, and this
    // database's own narrowing. Spanned at the word, so a type with no `Default` is `E0277` where
    // the author can act on it.
    values.extend(self.fills(model));
    let members = values.iter().map(|(source, value)| {
      let gate = model.gate(source);
      quote!(#gate #source: #value,)
    });
    let read = match self.into() {
      Conversion::Default if self.carries_every_field(model) => {
        if model.remote.is_some() {
          model.remote_build(&values)
        } else {
          quote!(Self { #(#members)* })
        }
      }
      Conversion::Default => return to_row,
      declared => declared.apply(quote!(row), false),
    };
    // READ rather than decided here, so the impl this emits and every binding that crosses through
    // it cannot disagree about which of `From` and `TryFrom` was written.
    let read_fallible = self.reads_fallibly(model);
    // The READ leg's own cell — `<db>(try_into(error = "…"))` — or the boxed refusal.
    let read_error = model.error(Crossing::PersistRead, self.kind());
    let to_record = conversion(
      quote!(#row),
      record,
      &format_ident!("row"),
      read,
      read_fallible.then_some(&read_error),
      &format!("Raise a stored row back into the [`{record}`] it came from."),
    );

    quote! {
      #to_row
      #to_record
    }
  }

  /// Whether projecting the record INTO this row can fail — the answer
  /// [`conversions`](Self::conversions) shapes the forward direction from, so an emitted write
  /// binding cannot call `From` where a `TryFrom` was written.
  ///
  /// It takes no model where its twin below does, and the asymmetry is the row's: a write is emitted
  /// field-wise or through a container conversion whatever the row carries, where a READ field-wise
  /// needs every field of the record to be there.
  pub(crate) fn writes_fallibly(&self) -> bool {
    match self.from() {
      Conversion::Default => self.columns().iter().any(|column| column.from.fallible()),
      container => container.fallible(),
    }
  }

  /// Whether raising this row back into the record can FAIL — the same answer
  /// [`conversions`](Self::conversions) shapes the reverse direction from, read rather than decided
  /// again, so an emitted binding cannot call `From` where a `TryFrom` was written.
  /// # A REWRITE has one source of failure that is not a column's
  ///
  /// `builder(fallible)` says the wrapped type's terminal construction step hands back a `Result`,
  /// so the raise carries a `?` and the impl has to be the `TryFrom` that `?` is legal inside. It
  /// is joined here rather than beside the emitted body precisely so that the query face's own
  /// crossing sees it: a reader that knew only about the columns would call `From` on a record no
  /// `From` was written for. See
  /// [`Construction::fallible`](crate::construct::Construction::fallible) for which step is the
  /// terminal one and which error road its `Err` joins.
  pub(crate) fn reads_fallibly(&self, model: &RecordModel) -> bool {
    // The FILLS are infallible by construction — a `Default` and a `fn() -> T` each hand back a
    // value or do not exist — so they say nothing here, and only the columns a row actually carries
    // and the protocol that reassembles them decide which conversion is written.
    match self.into() {
      Conversion::Default if self.carries_every_field(model) => {
        self.columns().iter().any(|column| column.into.fallible())
          || (model.remote.is_some() && model.construction.fallible)
      }
      Conversion::Default => false,
      container => container.fallible(),
    }
  }

  /// Every field this raise supplies rather than reads, as the struct-literal members that supply
  /// it — the `skip` family's own half of the field-wise body.
  ///
  /// # TWO absences, one walk, and the second is why this takes `&self`
  ///
  /// A field wearing the bare `skip` is a column of NO database, so every raise supplies it from the
  /// one fill that word named and the answer does not vary — that half is read off the record's own
  /// fields. The participation model adds the other: a field that is a column of the record's other
  /// databases and not of THIS one, whose fill is this database's own and whose absence is invisible
  /// from anywhere else.
  ///
  /// The two cannot collide. A field wearing `skip` is in no database's column list and in no
  /// database's [`Storage::fills`] either — the narrowing words are refused beside the word at the
  /// declaration — so the concatenation names each field at most once.
  ///
  /// The method stays here rather than on the model so that the raise which spends it and the raise
  /// which decides it are one walk.
  ///
  /// [`Storage::fills`]: crate::model::Storage::fills
  fn fills(&self, model: &RecordModel) -> Vec<(syn::Ident, proc_macro2::TokenStream)> {
    let withheld = model.fields.iter().filter_map(|field| {
      let fill = field.skip.as_ref()?;
      let source = &field.column.source;
      let value = fill.value(&field.column.ty);
      Some((source.clone(), value))
    });
    // SPANNED at this database's own `skip` word, which is where an author reads the demand: a fill
    // whose named function does not answer the field's type reports at the database that asked for
    // it rather than inside the raise.
    let narrowed = self.storage().fills.iter().map(|filled| {
      let ty = model
        .fields
        .iter()
        .find(|field| field.column.source == filled.source)
        .map(|field| &field.column.ty)
        .expect("a filled field is one the record declares");
      (filled.source.clone(), filled.fill.value(ty))
    });
    withheld.chain(narrowed).collect()
  }

  /// Whether this row can be turned back into the record FIELD BY FIELD — every field the record
  /// declares is either a column of this row or one the `skip` word answered for.
  ///
  /// # The word is what turns an absence into an answer
  ///
  /// A field carrying neither `persist` nor `skip` leaves the row PARTIAL, and a partial row rebuilds
  /// nothing: the reverse conversion is not emitted, `raises` is false, and the whole SQL query face
  /// goes with it. That is unchanged and deliberate — a field nobody spoke about is a field this
  /// emission will not invent a value for.
  ///
  /// What `skip` adds is the DECLARATION. A skipped field is answered for — `Default::default()`, or
  /// the function the word named — so the row carries every field it is answerable for and the query
  /// face survives. Which is the whole of L12: an engine-resident `Embedding` wears the word, and the
  /// record it lives on keeps its rows, its filter, its order and its pages.
  ///
  /// The PARTIAL absence answers here through the same door and per database: a field this database
  /// alone does not carry is answered for by this database's own fill, so a narrowed record keeps
  /// its field-wise read in every store rather than losing the query face in the narrowed one.
  pub(crate) fn carries_every_field(&self, model: &RecordModel) -> bool {
    model
      .fields
      .iter()
      .all(|field| field.skip.is_some() || self.supplies(&field.column.source))
  }

  /// Whether a READ of this database hands back a value for the record field `source` — a column of
  /// this row, or the fill this database's own narrowing word named.
  ///
  /// The RAISE's question, asked in one place so the parties that decide whether a database can
  /// answer a read cannot disagree: `carries_every_field` above, and
  /// [`RecordModel::wire_rows`](crate::model::RecordModel::wire_rows), which is the wire's own.
  /// Storing and supplying are two different questions and `stores` is the other one — a per-column
  /// lowering asks that, and a read asks this.
  pub(crate) fn supplies(&self, source: &syn::Ident) -> bool {
    self.stores(source).is_some()
      || self
        .storage()
        .fills
        .iter()
        .any(|filled| filled.source == *source)
  }

  /// The CONCRETE backend type this database is — `sqlx::Sqlite` for the three dialects, and this
  /// crate's own uninhabited `Mongo` for the second family.
  ///
  /// It is the ONE place in the emission that names a backend concretely, and everywhere else
  /// deliberately does not: a row, a comparison and a query binding all keep the dialect a
  /// parameter, so a declaration naming one database does not need that database's driver to
  /// COMPILE. What buys the exception here is the gate — see [`vocabulary`](Self::vocabulary).
  pub(crate) fn backend_type(&self, model: &RecordModel) -> proc_macro2::TokenStream {
    let (module, name) = self.kind().backend();
    model.framework(module, name)
  }

  /// The record's VOCABULARY row for this database: `Record<Db>`, naming the row this record becomes
  /// in it and the comparison a predicate over that row takes.
  ///
  /// # It is a STORABILITY AUDIT, and that is the point rather than a side effect
  ///
  /// Every other emitted item keeps the dialect a parameter, so its column crossings are obligations
  /// deferred to a call site. This one names the backend concretely, and well-formedness at a
  /// concrete impl is checked THERE — so writing `<Row>Comparison<Sqlite>` here discharges every
  /// column's crossing at SQLite, at the `#[ingraph::record(…)]` that declared it. A column whose type
  /// has no carrier row in a database the declaration names is a compile error where the declaration
  /// is written, rather than at whatever call site first asked for a comparison.
  ///
  /// # The gate is what keeps DECLARE-MANY/BUILD-ONE
  ///
  /// Ungated, the audit would also make a declaration naming Postgres fail to compile in a build
  /// without the Postgres driver — the invariant `ingraph`'s `query::sql` states from the other
  /// side. Wrapped in `ingraph`'s conditional-expansion gate, the impl — and therefore the audit —
  /// exists per DECLARED ∩ COMPILED-IN backend: a declaration naming three databases in a build
  /// carrying one is audited against the one, and the other two have no impl at all, which is
  /// `E0277` for a party that asks and silence for one that does not.
  ///
  /// A build carrying TWO engines and choosing between them by an options file at runtime is the
  /// case this shape exists for: both gates are open, so both audits run, and every record it may
  /// store is proved storable in both before the process starts.
  ///
  /// # `Row` is what a NEIGHBOUR'S expansion reads, and it is why the member exists
  ///
  /// Every other name in this impl is reachable from the declaration that wrote it. The row's is not
  /// reachable from any OTHER declaration: it is per database and `<db>(row(rename = "…"))`
  /// moves it, so a record nesting through a `ref` holds a path to the target and nothing that names
  /// the target's row. Binding it here is what turns that into a projection —
  /// `<Target as Record<Sqlite>>::Row` — instead of a suffix an emitter would have to guess.
  ///
  /// # The era rule
  ///
  /// The same ground the entity binding stands on, plus one step. `Record` is the framework's
  /// vocabulary for what a `Transformer`'s row-form member answers, and it is settled; what the impl
  /// BINDS is the emitter's own output — the row and the `<Row>Comparison` written beside it — and
  /// the backend type, which is the declaration's own choice of database. Nothing here is a consumer
  /// type.
  fn vocabulary(&self, model: &RecordModel) -> proc_macro2::TokenStream {
    let record = &model.record;
    let row = self.name();
    let comparison = self.comparison_name();
    let backend = self.backend_type(model);
    let vocabulary = model.framework(&["transform"], "Record");
    let gate = model.framework(&["gate"], &self.kind().gate().to_string());
    // The ORDER this database sorts by. It is emitted HERE rather than on a capability trait of its
    // own, which is where the retired `Orderable` put it: a record's storability is ONE fact, and
    // stating it twice meant two predicates an emitter had to keep in step. This impl exists exactly
    // where the record persists, so the order's absence is the row's absence and there is no second
    // condition to drift.
    //
    // What it binds is the record's own order-by enum — the same type the wire face names — and the
    // per-database seat is what makes the word count and the LEVEL count two different numbers: a
    // term of that enum lowers through `<db>_term` into this database's `OrderTerm`, which
    // `OrderTerm::levels` then expands into the levels this dialect really sorts by. A citizen's one
    // word becomes four levels at a table family and stays one word on the wire, which is the
    // full-form law at this seam; a database-free type could not hold both readings.
    let order_by = model.order_by.safe();
    // A doc comment cannot ride a macro INVOCATION — `unused_doc_comments` refuses one, since
    // rustdoc documents no such item — so what this impl has to say is said here and the emission
    // carries only `#[automatically_derived]`, as every other trait impl does.
    quote! {
      #gate! {
        #[automatically_derived]
        impl #vocabulary<#backend> for #record {
          type Row = #row;
          type Comparison = #comparison<#backend>;
          type OrderBy = #order_by;
        }
      }
    }
  }
}

impl PersistColumn {
  /// A row self as the accessor emitter reads a self.
  ///
  /// The row's name is the SAFE face — an accessor is Rust and a self called `bit-rate` has to
  /// reach one — and the projection is the DATABASE's `copy` claim rather than the domain field's.
  /// The two are different claims about different types: the same field may be a `BeU64` on one
  /// backend and a `Vec<u8>` on another, and a macro has no type information to bridge them.
  ///
  /// `Repeated` and `Optional` never appear. Those project a domain field through a framework trait;
  /// a stored self is whatever the database holds, and nullability is the schema's business rather
  /// than the accessor's.
  pub(crate) fn as_column(&self) -> Column {
    Column {
      name: self.name.safe().clone(),
      source: self.source.clone(),
      ty: self.ty().clone(),
      project: if self.copy {
        Projection::Copied
      } else {
        Projection::Borrowed
      },
    }
  }
}

impl Column {
  /// One self's whole method family: its accessors, then — when the site allows it — its two
  /// mutators.
  ///
  /// `subject` is the noun phrase every doc line is built from, so the same shapes read correctly on
  /// a key ("the `media_id` step of the lineage path") and on a record ("the `tracks` field of this
  /// \[`Video`\]" — the brackets are escaped HERE and written literally THERE, since the link
  /// resolves in the consumer's crate, where `Video` exists).
  ///
  /// `mutable` is FALSE for a record's identity-bearing fields, which are set at construction. It is
  /// true everywhere else, key columns included — those are addresses being built.
  ///
  /// The two things it takes from its OWNER are spelled rather than reached through a model: the
  /// visibility to mirror, and the crate the projection traits are rooted at. What owns a column is
  /// not always a record — the value tier declares columns and no record at all — and a parameter
  /// that named one would have made this family a record's rather than a column's.
  ///
  /// `gate` is the field's own CONDITION, and it rides EVERY member rather than the group: an
  /// attribute governs the ONE item after it, so a `#[cfg]` written once in front of four methods
  /// would take the first away and leave three behind. See
  /// [`Condition::gate`](crate::model::Condition::gate); it is empty for every column that wrote no
  /// condition, which is what keeps an unconditional expansion identical to the one before the seat
  /// existed.
  pub(crate) fn methods(
    &self,
    vis: &syn::Visibility,
    krate: &syn::Path,
    subject: &str,
    mutable: bool,
    gate: &proc_macro2::TokenStream,
  ) -> proc_macro2::TokenStream {
    let Column {
      name, ty, project, ..
    } = self;
    // The names, from the one place they are shaped — see [`crate::method`] for why they are not
    // spelled here. A DESTRUCTURE rather than a value read field by field, so a member added there
    // is one this site has to acknowledge.
    let method::Family {
      value,
      borrow,
      slice,
      set,
      with,
    } = self.family(mutable);

    // The projection the DECLARATION asked for. Nothing is inferred from the type's spelling — see
    // the module doc for why that had to stop.
    let accessors = match project {
      Projection::Repeated => slice.map(|slice| {
        let doc = leading(&format!("The {subject}, as a slice."));
        let repeated = framework(krate, &["project"], "Repeated");
        quote! {
          #gate
          #[doc = #doc]
          #[inline]
          #vis fn #slice(&self) -> &[<#ty as #repeated>::Item] {
            #repeated::as_slice(&self.#name)
          }
        }
      }),
      Projection::Optional => borrow.map(|borrow| {
        let doc = leading(&format!("The {subject}, by reference."));
        let optional = framework(krate, &["project"], "Optional");
        quote! {
          #gate
          #[doc = #doc]
          #[inline]
          #vis fn #borrow(&self) -> ::core::option::Option<&<#ty as #optional>::Item> {
            #optional::as_option(&self.#name)
          }
        }
      }),
      Projection::Borrowed | Projection::Copied => borrow.map(|borrow| {
        let doc = leading(&format!("The {subject}, by reference."));
        // Emitted only for a marked self, and only ever IN ADDITION to the borrow.
        let value = value.map(|value| {
          let doc = leading(&format!("The {subject}."));
          quote! {
            #gate
            #[doc = #doc]
            #[inline]
            #vis const fn #value(&self) -> #ty {
              self.#name
            }
          }
        });
        quote! {
          #value

          #gate
          #[doc = #doc]
          #[inline]
          #vis const fn #borrow(&self) -> &#ty {
            &self.#name
          }
        }
      }),
    };

    // A `copy` self's assignment drops nothing, so its mutators may be `const`.
    let constness = project.copies().then(|| quote!(const));
    let mutators = set.zip(with).map(|(set, with)| {
      let set_doc = leading(&format!("Set the {subject}."));
      let with_doc = leading(&format!("The same value with a different `{name}`."));
      quote! {
        #gate
        #[doc = #set_doc]
        #[inline]
        #vis #constness fn #set(&mut self, value: #ty) -> &mut Self {
          self.#name = value;
          self
        }

        #gate
        #[doc = #with_doc]
        #[must_use]
        #[inline]
        #vis #constness fn #with(mut self, value: #ty) -> Self {
          self.#name = value;
          self
        }
      }
    });

    quote! {
      #accessors
      #mutators
    }
  }
}

impl Conversion {
  /// One column's value, as the declaration says to obtain it.
  ///
  /// `Into::into` appears only when the STORED type differs from the domain one. With no override
  /// the two are the same type, and a reflexive self would be noise a reader has to look
  /// through — and a `useless_conversion` lint for anyone whose build sees it.
  pub(crate) fn apply(
    &self,
    value: proc_macro2::TokenStream,
    converted: bool,
  ) -> proc_macro2::TokenStream {
    match self {
      Conversion::Infallible(path) => quote!(#path(#value)),
      // A plain `?`, so the record's declared error absorbs the function's through `From` — and a
      // pair that cannot is `E0277` AT THE `?`, naming that function's error. The ESCAPE is for
      // where that bound genuinely cannot hold; it is applied at the crossing, so a map whose
      // signature does not line up is `E0308` at the call rather than anywhere further along.
      Conversion::Fallible(fallible) => {
        let path = &fallible.path;
        match &fallible.escape {
          None => quote!(#path(#value)?),
          Some(escape) => quote! {
            ::core::result::Result::map_err(#path(#value), #escape)?
          },
        }
      }
      Conversion::Default if converted => quote!(::core::convert::Into::into(#value)),
      Conversion::Default => value,
    }
  }
}

impl DatabaseKind {
  /// What this database's FAMILY answers differently about a row.
  ///
  /// The dispatch is here and the answers are in the two family modules, which is the split those
  /// files were always for. What it REPLACES is four functions: `sql::row` and `mongo::document`
  /// were the same function differing only in this value, and `sql::owns`/`mongo::owns` were a
  /// wrapper around [`DatabaseKind::is_sql`] and its negation. A database knows its own family, so
  /// nothing has to ask on its behalf.
  ///
  /// Only MONGO's answers depend on the model, and only for one reason: its derives are reached
  /// through the declarer's own crate path, which is a value the model carries. The SQL family
  /// reaches sqlx through that same path — but from inside a [`Mapping::Decode`] emitter, which is
  /// handed the model when it runs, so its own answers need nothing from the declaration.
  fn family(self, model: &RecordModel) -> Family {
    if self.is_sql() {
      sql::family()
    } else {
      mongo::family(model)
    }
  }
}