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
//! The QUERY face: the cursor value a page is minted from, the two bindings the engine reads a
//! record through, and the entry points a caller writes.
//!
//! ## What is emitted, and what each piece is for
//!
//! | item | per | why it cannot be written by the engine |
//! |---|---|---|
//! | `<Row>Cursor` | SQL database | a cursor's tuple is ONE type across its slots, so a heterogeneous order needs the record's own sum over its orderable columns |
//! | `impl SqlQuery for <Row>` | SQL database | the table, the columns, the address predicate and the way back to the record are all this declaration's |
//! | `impl SqlOrdering for <Row>` | SQL database | the order-by's terms and the row's projection into cursor values |
//! | `impl Describe<Db> for <Record>` | SQL dialect | the SCHEMA: each field's stored word, its nullability, the indexes and unique constraints the declaration asked for, and the second table each collection hangs off |
//! | `find_<db>` / `get_<db>` / `find_<db>_snapshot` | SQL database | the typed face, which fixes the row so a caller never names one |
//!
//! ## The era rule, and why these trait impls are authorised
//!
//! What they bind is the emitter's OWN output plus the ENGINE's public seam — the same ground the
//! address binding stands on. `SqlQuery` and `SqlOrdering` name the row, the order-by and the
//! cursor value, every one of which this emission also declares; the two framework traits they
//! implement are settled surfaces with no consumer type of their own in them. The same holds for
//! the cursor value's `CursorValue` and `Carrier` rows: the self type is emitted here and what it
//! delegates to is the storage types the declaration already named.
//!
//! The COMPARISON is no longer among them, and that is the vocabulary's doing rather than an
//! omission: `SqlQuery` reads `<Self::Record as Record<Db>>::Comparison` instead of declaring a
//! slot, so the binding states which record this row stores and the record's own `Record<Db>` impl
//! states what a predicate over it looks like. Two facts, one place each.
//!
//! ## What is NOT emitted, and the condition each is missing on
//!
//! Nothing is invented and nothing half-works. A database gets the query face only when all of it
//! can be written, and otherwise the call site fails to resolve — the same answer
//! [`RecordModel::id_column_stored`] already gives an ordering it cannot complete:
//!
//! - **No SQL database.** The clause machine is the SQL family's, and so is every entry point below
//!   it: `find_<db>`, `get_<db>`, `insert_<db>`, `upsert_<db>`, `delete_<db>` and `delete_<db>_where`
//!   are emitted per SQL database and for no other backend — which
//!   `tests::the_query_face_is_emitted_per_sql_database_and_never_for_mongo` pins.
//!
//!   **MongoDB's own read AND write lanes have landed, and neither is emitted.** `query::mongo`
//!   ships `documents`/`find`/`get` and `insert`/`upsert`/`delete`/`delete_where` — the same four
//!   write verbs under the same four meanings — as RUNTIME functions over a `MongoQuery`/`MongoWrite`
//!   pair a caller implements. Nothing in this crate writes that pair: there is no emitted
//!   `impl MongoQuery`, so there is no emitted row for an entry point to name, and
//!   [`queryable`](RecordModel::queryable) is therefore not a gate that could be widened — it is the
//!   SQL query face's own list, and every one of `cursor_value`, `bindings` and `entry_points` reads
//!   it to write sqlx.
//!
//!   What a mongo roster costs is that binding, and it has to come first: `MongoWrite` is
//!   `MongoQuery`'s subtrait — a document carrying two `ADDRESS` consts is `E0034` at every use site,
//!   inside an expansion nobody can edit — so the write face cannot be emitted ahead of the read one.
//!   Until then the emitted mongo surface is the document, its `from_document`, its comparison
//!   binding and its conversions, and a caller reaches the lanes through a hand-written binding, which
//!   is what `ingraph`'s own `query::mongo::tests` fixture is.
//! - **No stored column.** A `SELECT` with no fields is not a statement.
//! - **No stored id.** The address predicate names the id, and a row whose id is in no `persist(…)`
//!   block has no column to be addressed by.
//! - **No way back from the row.** A record is what a query returns, and a partial row that
//!   declared no conversion cannot rebuild one — see
//!   [`DatabaseBackend::conversions`](super::DatabaseBackend::conversions), which is the one place
//!   that decides whether the reverse direction is emitted at all.
//! - **No `graphql(…)`.** Only the ORDERED half is missing here, and this is a placement rather
//!   than a design: the order-by is mechanical from the STORED columns and its lowering is pure
//!   SQL, but the type is declared inside the wire block, so a record with no wire face has no term
//!   type to name. It keeps `get`, the unordered lanes and the ceiling; `.order(…)` is a missing
//!   impl. Moving the order-by beside the comparison — where it belongs, and where the comparison
//!   already is — closes it.
//! - **A collection this database keeps in a COLUMN.** The BLUEPRINT's condition and no other
//!   item's, so it costs a declaration its schema and nothing else. A word has TWO readers that
//!   disagree about an array and about nothing else: `CREATE TABLE t (x bigint[])` is legal and
//!   `x ARRAY` is a syntax error, while `information_schema.data_type` for that same column answers
//!   `ARRAY` and never `bigint[]`. `StoredAs` records the measurement and leaves `Vec<T>` without a
//!   row rather than giving it one that is wrong for whichever reader is not looking, so this
//!   emission has no word to write — and a Postgres array column is the one place that arises.
//!   `postgres(edge)` moves the collection into a second table and the blueprint lands.
//!
//! ## The BLUEPRINT is the one item whose absence is a SKIP rather than an `E0277`
//!
//! Every condition above is a fact this macro can READ, and that is what makes the roster a roster:
//! a database that fails one gets no item, and a party that asks for the missing one is refused at
//! its own call site. The schema's condition is read the same way — `RecordModel::describable` is
//! `queryable` less the array columns — and it has to be, because the alternative was MEASURED and
//! does not exist: a `Describe<Sqlite>` impl carrying `where Vec<String>: StoredAs<Sqlite>` is
//! `E0277` AT THE IMPL, since a `where` clause over concrete types that does not hold is
//! `trivial_bounds` and unstable. So an emission at a concrete backend cannot defer an obligation
//! to a call site the way a `Db`-generic one can; it either writes the item or does not.
//!
//! What a macro CANNOT read is a field's TYPE, so the other half of the same wall lands differently
//! and deliberately: a field whose type has no `StoredAs<Db>` row at all — `TimeRanged<T>`, whose
//! arity depends on a type parameter and which stable Rust refuses a `const` for twice over — is
//! `E0277` at the FIELD, spanned there, carrying the trait's own
//! `#[diagnostic::on_unimplemented]` note and the `<db>(type = "…")` road out. A wrong table is
//! the one outcome neither arm admits.
//!
//! ## The nested surface is still not emitted — but the fact this note called missing has LANDED
//!
//! This section used to say the nested ordering term and the nested filter position both waited on
//! ONE emitted fact, spelled `<Keyframe as RowOf<Db>>::Row`: a per-`(record, database)` pairing
//! naming the row, without which a source's expansion could not reach its target's table, id column
//! or cursor slot. **That pairing exists.** It arrived three PRs after the note was written, under
//! the name the note itself predicted the shape of — `ingraph`'s `Record<B>::Row`, whose
//! own doc carries this argument verbatim — and `ingraph-derive`'s `tests/nested_reach.rs` spends
//! it: a target known only by its PATH hands back its address, its scope aliases, its order
//! vocabulary and its cursor slot, and a whole forward semi-join renders over the result.
//!
//! The note is corrected rather than deleted because what it got right is load-bearing: three of
//! those four names hang off the row, the same-proc-macro naming convention does not reach it, and
//! [`default_row_name`](crate::model::default_row_name) beside `<db>(row(rename = "…"))`
//! is why guessing was never available. All of that is still true. What changed is that the name is
//! now ASKED FOR rather than rebuilt.
//!
//! | name | where it lives | reachable from the source? |
//! |---|---|---|
//! | the FK column | this record's own [`PersistColumn`](crate::model::PersistColumn) | yes |
//! | the target's ROW | `<Target as Record<Db>>::Row` | **yes, since G3-T3** |
//! | the target's TABLE and ID column | `<TargetRow as SqlQuery<Db>>::ADDRESS` | yes, through the row |
//! | the target's cursor SLOT | `<TargetRow as SqlOrdering<Db>>::Value` | yes, through the row |
//! | the target's order terms | `<Target as Record<Db>>::OrderBy` | yes, since O4-T2 |
//!
//! ## What each position DOES still wait on — three forks, none of them a missing fact
//!
//! **α — the nested term's cursor IDENTITY. RULED and BUILT: the two-part fold.** The candidate
//! that was a `const` concatenation the language does not have is recorded dead. `OrderTerm` carries
//! the relation BESIDE the leaf — `OrderTerm::through` puts it there — and `OrderSignature` folds
//! both parts under the length-prefix rule one part already had, so `"cover_keyframe_id.title"` is
//! never built at all. That was the whole of the obstacle at this end: the tail is the TARGET
//! declaration's field name, which no projection hands back as a `&'static str` a literal could be
//! built from, and the target's own `identity()` answers it at RUNTIME as a `&'static TermName` this
//! end can fold without owning. `SubjectPath` is the wire half of the same question and keeps the
//! human spelling, which is a RENDER-TIME concern and not this one.
//!
//! What is still open is the DEPTH: the relation slot holds one name, so `cover.strip.label` has no
//! identity to mint — composing a `&'static` chain at runtime is the leak the two-part shape exists
//! to avoid. Nothing here mints such a term today. Nothing else about the ordering term is open: the
//! recursive variant `Cover(::std::sync::Arc<<Target as Record<Db>>::OrderBy>)` is spellable here.
//!
//! **β — where REFERENTIALITY lives on the storage side. RULED and BUILT: the capability trait.**
//! The defaulted `fn is_referential(&self) -> bool { false }` on `ComplexComparison` is recorded
//! rejected — declining is always sound, but declining SILENTLY is the failure this seam cannot
//! afford. `ingraph`'s `ReferentialComparison<B>` is the capability, the emitted
//! `CollapsibleComparison` impl carries one projection-headed `where` predicate over it, and an id
//! whose kind has no row is `E0277` at the position with that trait's own sentence. The statement
//! that no emitted comparison implements `CollapsibleComparison` is no longer true: `collapse`
//! below emits one per declared ∩ compiled-in backend, which is what the forward position
//! `SqlRefComparison<C, Db>` wanted its `C` to be.
//!
//! The impl names the BACKEND CONCRETELY, and that is this note's own rule applied to a new bound:
//! at a generic `Db` the projection-headed predicate sends rustc to the filter kind's own row for
//! the normalisation, and the row's `where` clause — `Db: sqlx::Database`, `V: Carrier<Db>` — is not
//! available at a parameter. See `collapse` for the measurement. The REVERSE position has no such
//! fork: `SqlDerivedComparison`'s `C` is bound by `ComplexComparison` alone.
//!
//! **γ — the relation position's wire shape and its stored back-reference. BOTH CLOSED.** The wire
//! `<E>Filter` gained its field per position and the ruled quantifier vocabulary
//! (`any`/`all`/`none`/`count`) with it, which was the wire round's half. The second end was the one
//! that looked closed and was not: `SqlDerivedComparison::new` takes the source's `ref` column in the
//! name THIS DATABASE STORES it under, and the only publisher of the DECLARED name carried no
//! database's while the only publisher of a stored one could not be probed by a declared name. So a
//! per-database rename was a silent miscorrelation waiting for a corpus that had one.
//!
//! The pairing publishes now — a row's `COLUMNS` carries `ColumnName { declared, stored }` and
//! `stored_column` crosses it — so the emission is here: `emit::cross`'s relation legs resolve the
//! stored spelling in a `const`, at the concrete backend the crossing is written for, and a name the
//! source's row does not store is `E0080` at the `derived` entry rather than SQL nobody can run.
//! `ingraph`'s `tests/reverse_lowering.rs` renders two dialects from two declarations and compares
//! the two columns.
//!
//! One thing the record's comparison does NOT wait on, and it is worth stating because it removes an
//! assumed dependency: the crossing. `TryFromFilter` is still not emitted on the `Db`-GENERIC
//! comparison — only `ToDatabaseComparison` is, and `DatabaseBackend::comparison_traits`'s note says
//! why one cannot be carried there. What IS emitted is the crossing at a CONCRETE dialect, inside
//! that dialect's gate (`emit::cross`), which is the shape `interface::cross` always had; it is built
//! column-wise out of field filters rather than out of any comparison's own generic form. So a
//! relation member on a record's comparison changes the crossing only by adding a leg, and the
//! positional constructor's arity with it — a caller-supplied position is the shape the runtime half
//! already ships in. The filter position's COMPARISON half is therefore free of the wire round; only
//! its client-facing half is γ's.

use quote::{format_ident, quote, quote_spanned};

use crate::model::{DatabaseBackend, Label, PersistColumn, RecordModel, TracingLevel};

/// The type a COMPANION column's value crosses as, in ONE spelling.
///
/// `collection_sort_key` writes these bytes, the write plan binds them, the `CREATE TABLE` declares
/// the column that holds them and a cursor slot resumes at them — four positions and one type, so a
/// boundary cannot be a shape the projection could not fill. A second spelling would be the one place
/// the slot and the bind could drift apart.
fn sort_key_type() -> proc_macro2::TokenStream {
  quote!(::std::vec::Vec<::core::primitive::u8>)
}

impl RecordModel {
  /// The query face for every SQL database that can carry one: the cursor values as types, and the
  /// bindings and entry points as impls.
  pub(super) fn query(&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.queryable() {
      types.extend(database.cursor_value(self));
      impls.extend(database.cursor_value_impls(self));
      impls.extend(database.bindings(self));
      impls.extend(database.entry_points(self));
    }
    // The SCHEMA rides the same walk one roster narrower — see [`RecordModel::describable`], where
    // the one subtraction is, and the module note, where its reason is.
    for database in self.describable() {
      impls.extend(database.blueprint(self));
    }
    (types, impls)
  }

  /// The SQL databases whose query face can be written whole — see the module note for what each
  /// missing condition costs.
  ///
  /// The stored-id condition cannot fire on the MANDATED path: a framework-emitted table stores its
  /// id by construction, that column being the primary key the address is. What it guards is the
  /// CAPABILITY — a user-declared physical layout whose id no `persist(…)` block names.
  pub(crate) fn queryable(&self) -> Vec<&DatabaseBackend> {
    if self.id_column_stored().is_none() {
      return Vec::new();
    }
    self
      .persist
      .iter()
      .flat_map(|persist| &persist.backends)
      .filter(|database| {
        database.kind().is_sql() && !database.columns().is_empty() && database.raises(self)
      })
      .collect()
  }

  /// The SQL databases whose BLUEPRINT can be written whole — [`queryable`](Self::queryable) less
  /// the ones holding a collection in a COLUMN.
  ///
  /// # It is a SUBSET of the query face rather than a condition of its own
  ///
  /// A blueprint states no name twice: its address IS `SqlQuery::ADDRESS` and its columns ARE
  /// `SqlQuery::COLUMNS`, projected rather than rebuilt, which is the whole of what
  /// [`Table::shaped`](../../ingraph/struct.Table.html#method.shaped) is for. So a database with no
  /// query binding has no list for a descriptor to be shaped from, and the schema follows the query
  /// rather than deciding again.
  ///
  /// # The ARRAY column is the one subtraction, and it is a missing WORD rather than a missing name
  ///
  /// See the module note. A collection this database keeps in a column of the row reaches
  /// `<Vec<E> as StoredAs<Db>>::WORDS`, and `Vec<T>` has no row in any dialect — deliberately, the
  /// two readers of a word wanting two different strings for a Postgres array and one `const` being
  /// unable to be both. Postgres is the only dialect where the case arises: the other two have no
  /// array type, so [`edge_stored`](super::DatabaseBackend::edge_stored) is unconditionally true
  /// there and every collection is already in a second table.
  pub(crate) fn describable(&self) -> Vec<&DatabaseBackend> {
    self
      .queryable()
      .into_iter()
      .filter(|database| database.words_every_column(self))
      .collect()
  }

  /// Whether the ORDERED half is emitted too — which is the order-by type existing, and nothing
  /// else about the database.
  ///
  /// It used to be *the record declares a wire face*, and that was a PLACEMENT rather than a rule:
  /// the order-by was declared inside the `graphql(…)` block, so a record with no wire face had no
  /// term type to name and lost `.order(…)` and every page while keeping `get`, the unordered lanes
  /// and the ceiling. The type is emitted beside the comparison now — see
  /// [`RecordModel::ordering`] — so what is left of the condition is that the record is stored at
  /// all, which every caller of this has already established.
  pub(crate) fn orderable(&self) -> bool {
    self.persist.is_some()
  }
}

impl DatabaseBackend {
  /// Whether this database's row can be turned back into the record — the one thing a query needs
  /// that a write does not.
  ///
  /// The same condition [`conversions`](super::DatabaseBackend::conversions) emits the reverse
  /// direction on, read here rather than restated: a row that carries every field rebuilds the
  /// record field-wise, and a partial one does it only through a declared container conversion.
  fn raises(&self, model: &RecordModel) -> bool {
    !matches!(self.into(), crate::model::Conversion::Default) || self.carries_every_field(model)
  }

  /// The name of this database's cursor-value type: the row's, with `Cursor` after it.
  pub(crate) fn cursor_name(&self) -> syn::Ident {
    format_ident!("{}Cursor", self.name())
  }

  /// The ordered columns a CURSOR over THIS database can carry a slot for — the ordered list less
  /// the collections this database keeps in a table of its own.
  ///
  /// # A boundary is a value this DATABASE can bind, which is narrower than *is it orderable*
  ///
  /// A page's boundary is a tuple of values, each written into the cursor as one blob and bound back
  /// as one parameter: `SqlOrdering::Value` is `Carrier<Db> + CursorValue`. A collection satisfies
  /// both where the dialect keeps it in a NATIVE ARRAY — `ingraph`'s `Carrier<Postgres>` row for
  /// `Vec<E>` binds the whole list as one `E[]`, and its `CursorValue` row writes the list into one
  /// slot whose bytes carry their own inner framing — and neither where the dialect keeps it in an
  /// edge table, there being no column of the row to be a value of.
  ///
  /// So the fence is per DATABASE, and it is [`DatabaseBackend::edge_stored`] — the same authority
  /// the order-by term already asks for its SUBJECT. The two cannot disagree about which columns are
  /// array-stored, because there is one place that answers.
  ///
  /// # …and an edge-stored collection with a COMPANION is back in, at the companion's own value
  ///
  /// `sortable` puts a mirrored collection's order in a binary column of the row, and a
  /// blob is a boundary every dialect binds. So the fence is *no column of the row to be a value of*,
  /// and a mirrored collection HAS one — which [`DatabaseBackend::mirrors`] answers, reading
  /// `edge_stored` rather than restating it, so the column a write fills, the column an `ORDER BY`
  /// renders and the slot a cursor holds cannot disagree about which collections have one.
  ///
  /// What the slot holds is the COMPANION's bytes and not the list, and the two are not two spellings
  /// of one thing: the statement ordered by the companion, so the boundary a page resumes at has to
  /// be what the statement compared. See [`Self::cursor_type`], and `SqlOrdering::value`'s own note,
  /// where the boundary is frozen.
  ///
  /// # The list is not a narrowing of one vocabulary but a second one
  ///
  /// The ORDER-BY takes every orderable column, because an ordered scan over an edge-stored
  /// collection is still served — the remainder is completed in memory. The CURSOR takes the ones a
  /// boundary can be taken at, and a page over any of the rest is refused by name at
  /// `OrderPartition::paging` before a row is read.
  ///
  /// # The TAG is this database's, and the cursor type is too
  ///
  /// A slot's tag is its index in THIS list, so a record stored in two dialects whose collection is
  /// array-stored in one of them numbers its slots differently in the two. That is not a new
  /// property: the sum is emitted per (record × database) and `cursor_type` already reads this
  /// database's own column, so `<db>(type = …)` could already give one tag two meanings
  /// across dialects. A cursor STRING is one database's, which the emitted type is what says.
  pub(crate) fn paged_columns<'m>(
    &self,
    model: &'m RecordModel,
  ) -> Vec<(usize, &'m PersistColumn)> {
    model
      .ordered_columns()
      .into_iter()
      .filter(|(_, shared)| {
        // A column THIS DATABASE has not got is no slot either, and it is the narrowing the
        // declaration wrote rather than a storage form: the vocabulary is the DECLARATION's, so the
        // ordered list is the widest of them and this one keeps what a boundary can be taken at
        // here. A page over such a term never reaches a cursor — `SqlOrder::new` refuses the order
        // by name first — so the missing slot is unreachable rather than a hole.
        let Some(column) = self.stores(&shared.source) else {
          return false;
        };
        !self.edge_stored(model, column) || self.mirrors(model, column)
      })
      .collect()
  }

  /// The type ONE column contributes to the cursor value.
  ///
  /// A MIRRORED collection contributes the COMPANION's bytes — [`sort_key_type`], the one spelling
  /// the write plan binds and this slot holds. The list itself is NOT the boundary there: the
  /// statement ordered by `__ig_<field>_sort__`, so a slot holding the elements would resume at a
  /// value nothing compared.
  ///
  /// Every other COLLECTION contributes the whole LIST, and it is read off
  /// [`row_field`](super::DatabaseBackend::row_field) rather than spelled again: the boundary IS
  /// what the row's field holds, and two spellings of that would be two places for the slot and the
  /// projection to disagree about what a page resumes at.
  ///
  /// A NULLABLE column contributes what it holds rather than the `Option` holding it — the cursor's
  /// slot is already `Option<V>`, and a second `Option` inside it would be two spellings of one
  /// absence. The projection goes through the framework's own [`Optional`] rather than by matching
  /// the written type, which is the rule the accessors follow and for the reason they follow it: a
  /// type ALIAS resolves for the compiler and not for a macro. A collection reaches neither branch:
  /// it has no null state, so the empty list is its absence and there is no `Option` to unwrap.
  fn cursor_type(&self, model: &RecordModel, column: &PersistColumn) -> proc_macro2::TokenStream {
    if self.mirrors(model, column) {
      return sort_key_type();
    }
    if model.collects(&column.source) {
      return self.row_field(model, column);
    }
    let ty = column.ty();
    if !column.nullable {
      return self.leaf_type(model, column, quote!(#ty));
    }
    let optional = model.framework(&["project"], "Optional");
    self.leaf_type(model, column, quote!(<#ty as #optional>::Item))
  }

  /// One VALUE column's slot type: the LEAF one level of it compares.
  ///
  /// # It is the ONE spelling, and the compiler is what selects
  ///
  /// A boundary is taken at a LEVEL, and a citizen that states a semantic sequence runs as one level
  /// per leaf — so its slot holds one leaf's value rather than the whole instant, which is what makes
  /// a level's operand one placeholder bound through that leaf's own scalar carrier. Which types
  /// those are is not something this seat can see: `at: MediaTimestamp` and `title: String` are the
  /// same tokens, and reading a leaf off `ColumnKind::SEGMENTS` would be the emitter deriving a Rust
  /// TYPE it was never given.
  ///
  /// So the projection is written at every value column and the marker answers.
  /// `ToOrderLeaves` is keyed on the reading exactly as the filter's own map is, a flat reading
  /// answers with ITSELF, and a composite answers through the vocabulary its own type publishes. A
  /// scalar column's slot is therefore the very type it was before this projection existed, and every
  /// byte of every scalar cursor is what it was.
  ///
  /// A COLLECTION never reaches here: its boundary is the whole list or a companion column's bytes,
  /// which the two branches above name directly. That is not an omission — a collection is a fact
  /// the DECLARATION states, so unlike a width it is one this seat can see.
  ///
  /// # A `type = "…"` COLUMN is not projected, and the reason is the same sentence
  ///
  /// A per-database stored type is a crossing the DECLARATION chose — `sqlite(type =
  /// "::ingraph::BeU128")` — so the row's field holds a type this seat was HANDED rather than one it
  /// inferred, and the slot is that type exactly as it always was. Projecting would demand a
  /// `DefaultMarker` of a storage crossing that has no reading and never needed one: a marker says
  /// what a FIELD means, and what a `type` word names is what a column HOLDS.
  fn leaf_type(
    &self,
    model: &RecordModel,
    column: &PersistColumn,
    ty: proc_macro2::TokenStream,
  ) -> proc_macro2::TokenStream {
    if column.stored.is_some() {
      return ty;
    }
    let leaves = model.framework(&["ordering"], "ToOrderLeaves");
    let marker = self.leaf_marker(model, column, ty);
    quote!(<#marker as #leaves>::Leaf)
  }

  /// The READING one value column is under — the marker the field's own word resolves to, and its
  /// type's `DefaultMarker` row where the declaration wrote none.
  ///
  /// It is `filter_of`'s resolution at the ordering seam, and it is the SAME resolution deliberately:
  /// a field carrying `label = "RollMarker"` is read as that marker everywhere or nowhere, and a
  /// cursor slot that went through `DefaultMarker` while the filter went through the word would be
  /// two readings of one column — which for a type whose word is the reason it is declarable at all
  /// is not a nicety but `E0277` at the record, naming a row the declaration never needed.
  ///
  /// The type handed over is already UNWRAPPED — a nullable column's `<T as Optional>::Item` — so
  /// the word lands on the reading rather than on the `Option` around it, which is exactly what a
  /// slot holds. `Marker::resolved` reads a WRITTEN `Option` off the tokens and finds none in a
  /// projection, so the optional wrapper it would otherwise ask the family for is not asked about.
  fn leaf_marker(
    &self,
    model: &RecordModel,
    column: &PersistColumn,
    ty: proc_macro2::TokenStream,
  ) -> proc_macro2::TokenStream {
    let Some(marker) = model.marker_of(&column.source) else {
      let default_marker = model.framework(&["marker"], "DefaultMarker");
      return quote!(<#ty as #default_marker>::Marker);
    };
    let held: syn::Type = syn::parse2(ty).expect("a column's own type parses as one");
    marker.resolved(&model.krate, &held)
  }

  /// The expression that READS one value column's leaf out of `held` — [`Self::leaf_type`]'s other
  /// half, branching the same way so the slot's type and the value put in it cannot come from two
  /// maps.
  ///
  /// A `type = "…"` column answers with the CLONE this arm always wrote, its slot being the stored
  /// type itself.
  fn leaf_value(
    &self,
    model: &RecordModel,
    column: &PersistColumn,
    held: proc_macro2::TokenStream,
  ) -> proc_macro2::TokenStream {
    if column.stored.is_some() {
      return quote!(::core::option::Option::Some(::core::clone::Clone::clone(#held)));
    }
    let leaves = model.framework(&["ordering"], "ToOrderLeaves");
    let ty = column.ty();
    let ty = if column.nullable {
      let optional = model.framework(&["project"], "Optional");
      quote!(<#ty as #optional>::Item)
    } else {
      quote!(#ty)
    };
    let marker = self.leaf_marker(model, column, ty);
    quote!(<#marker as #leaves>::leaf(#held, __ingraph_leaf))
  }

  /// One slot of a cursor over this database's stored values — the record's own sum over its
  /// orderable columns.
  ///
  /// A variant per STORED column rather than per storage type, and the difference is what makes the
  /// codec safe: a slot read back carries which COLUMN it was written from, so a forged frame
  /// cannot move a text value into an integer column's slot by rearranging the bytes.
  ///
  /// [`Self::paged_columns`] and not the ordered list, which is wider: a boundary is a value this
  /// database can bind, so an EDGE-STORED collection has no slot to be — see that method for why the
  /// two vocabularies are two lists rather than one narrowed twice.
  fn cursor_value(&self, model: &RecordModel) -> proc_macro2::TokenStream {
    let vis = &model.vis;
    let name = self.cursor_name();
    let record = &model.record;
    let column_eq = model.framework(&["column"], "ColumnEq");
    let variants = self.paged_columns(model).into_iter().map(|(_, shared)| {
      let column = self
        .stores(&shared.source)
        .expect("`paged_columns` keeps only the columns this database stores");
      let variant = shared.order_variant();
      let ty = self.cursor_type(model, column);
      let doc = super::leading(&format!("The `{}` column's value.", column.name));
      let gate = model.gate(&column.source);
      quote! {
        #gate
        #[doc = #doc]
        #variant(#ty),
      }
    });
    // A MATCH ARM is a stable attribute position, so the same gate the variant carries carries the
    // arm — a build that removed the column removed both, and the pair cannot drift.
    let arms = self.paged_columns(model).into_iter().map(|(_, shared)| {
      let column = self
        .stores(&shared.source)
        .expect("`paged_columns` keeps only the columns this database stores");
      let variant = shared.order_variant();
      let ty = self.cursor_type(model, column);
      let gate = model.gate(&column.source);
      let at = column.source.span();
      let compared = quote_spanned! {at=>
        <#ty as #column_eq>::column_eq(__ingraph_this, __ingraph_that)
      };
      quote! {
        #gate
        (Self::#variant(__ingraph_this), Self::#variant(__ingraph_that)) => #compared,
      }
    });
    let doc = super::leading(&format!(
      "One slot of a cursor over a [`{record}`] as this database stores it — which column, and the \
       value it held at the boundary row."
    ));
    quote! {
      #[doc = #doc]
      #[derive(::core::fmt::Debug, ::core::clone::Clone)]
      #vis enum #name {
        #(#variants)*
      }

      #[automatically_derived]
      impl ::core::cmp::PartialEq for #name {
        #[inline]
        fn eq(&self, __ingraph_other: &Self) -> ::core::primitive::bool {
          match (self, __ingraph_other) {
            #(#arms)*
            // Two slots naming DIFFERENT columns are two different values, which is the sum's whole
            // point: a boundary carries which column it was written from, so a text value in one
            // column is never the same slot as the same text in another.
            //
            // `allow`ed because the arm's reachability is a fact about THIS build: a sum whose
            // predicates left exactly one variant standing has every pair covered above, and a sum
            // they emptied has no pair at all. Both are ordinary, and neither is a warning a reader
            // could act on.
            #[allow(unreachable_patterns)]
            _ => false,
          }
        }
      }
    }
  }

  /// The cursor value's two rows: its own codec, and how it binds.
  ///
  /// # The codec carries a TAG, and the tag is the column
  ///
  /// A frame's slot is length-delimited by the cursor and holds nothing else, so a sum has to say
  /// which member it is. One byte per slot, in the column order this database stores — and a byte
  /// naming no column is refused rather than read as the nearest one, because the bytes are a
  /// client's.
  ///
  /// The value's own encoding is delegated: `to_blob` and its siblings are the storage type's, so a
  /// cursor holds the same bytes the column does and there is no second encoding to drift.
  ///
  /// # The slot is reached AT THIS DIALECT, which is what lets a value have a byte form per store
  ///
  /// A slot's bytes used to be `CursorValue`'s — one form per value, on every engine — under the
  /// portable-token doctrine, now RETIRED: a page cursor is session-lived pagination state rather
  /// than a durable id, so the only engine that ever has to read a token is the one that minted it.
  /// The slot therefore goes through `DialectCursor<Db>`, at a CONCRETE backend, which this seat has
  /// in hand because the sum itself is per database.
  ///
  /// Nothing moves for a value whose bytes are the same everywhere: the blanket over `CursorValue`
  /// answers at every dialect, so every scalar, vocabulary, newtype and undecorated fragment reaches
  /// this call exactly as it did. What the seam BUYS is the declaration that mounts a codec per
  /// store — `record(sqlite(cursor = "…"), postgres)`, dense here and framed there — which had no
  /// way to be spelled while one row served every engine.
  ///
  /// The obligation is DISCHARGED here rather than carried in a clause, for the reason the comparison
  /// pair's concrete arm gives: a record storing a per-dialect value in a dialect that value never
  /// named is `E0277` at the record's own attribute, in `DialectCursor`'s own words.
  ///
  /// # It names the cursor MARKER, never the driver — which is what keeps this row ungated
  ///
  /// `cursor::dialect::Sqlite` and not `sqlx::Sqlite`. The house rule is that an emission naming a
  /// BACKEND concretely rides that dialect's feature gate, and this row cannot: `SqlOrdering`'s own
  /// `type Value: CursorValue` is stated at a generic `DB` and is therefore checked in every build,
  /// so a gated codec row is `E0277` on the sum in any build that compiled this dialect out.
  /// Measured, on `record(sqlite, postgres)` in a `sqlite`-only crate.
  ///
  /// The marker is what makes that a non-question: `ingraph::cursor` is compiled under no backend's
  /// feature, so the seam that says WHICH STORE's bytes these are exists in every build and this row
  /// stays exactly as unconditional as it always was.
  fn cursor_value_impls(&self, model: &RecordModel) -> proc_macro2::TokenStream {
    let name = self.cursor_name();
    let cursor_value = model.framework(&["cursor"], "CursorValue");
    let dialect_cursor = model.framework(&["cursor"], "DialectCursor");
    let (module, item) = self.kind().dialect();
    let backend = model.framework(module, item);
    let carrier = model.framework(&["comparison", "sql"], "Carrier");
    let database = model.framework(&["sqlx"], "Database");
    let held = model.framework(&["sqlx"], "QueryBuilder");
    let db = super::parameter("DB");
    let columns = self.columns();
    let ordered = self.paged_columns(model);

    // The TAG stays the DECLARATION's position, and a conditional column leaves a HOLE in the
    // numbering rather than closing one. That is deliberate and it is the opposite of what the bind
    // ordinal needs: this byte is the CLIENT's, carried in a cursor a client holds across calls, and
    // renumbering it would make one build's cursor decode as a different column in another. Both
    // legs read the same enumeration, so a build that drops a column drops its tag from the writer
    // and from the reader together, and a frame naming it answers `None` — which is what a frame
    // naming no column already deserved.
    let writes = ordered.iter().enumerate().map(|(tag, (at, shared))| {
      let variant = shared.order_variant();
      let tag = u8::try_from(tag).unwrap_or(u8::MAX);
      let ty = self.cursor_type(model, &columns[*at]);
      let gate = model.gate(&columns[*at].source);
      quote! {
        #gate
        Self::#variant(__ingraph_value) => {
          __ingraph_out.push(#tag);
          <#ty as #dialect_cursor<#backend>>::write_cursor_at(__ingraph_value, __ingraph_out);
        }
      }
    });
    let reads = ordered.iter().enumerate().map(|(tag, (at, shared))| {
      let variant = shared.order_variant();
      let tag = u8::try_from(tag).unwrap_or(u8::MAX);
      let ty = self.cursor_type(model, &columns[*at]);
      let gate = model.gate(&columns[*at].source);
      quote! {
        #gate
        #tag => ::core::option::Option::map(
          <#ty as #dialect_cursor<#backend>>::read_cursor_at(__ingraph_rest),
          Self::#variant,
        ),
      }
    });
    let binds = ordered.iter().map(|(at, shared)| {
      let variant = shared.order_variant();
      let gate = model.gate(&columns[*at].source);
      quote!(#gate Self::#variant(__ingraph_value) => #carrier::push_bind(__ingraph_value, __ingraph_qb),)
    });
    let bounds = ordered.iter().map(|(at, _)| {
      let ty = self.cursor_type(model, &columns[*at]);
      quote!(#ty: #carrier<#db>,)
    });

    // A record whose database stores no column has no query face at all, so the empty `match` a
    // uninhabited sum would need cannot arrive here. The tag read still answers `None` for every
    // byte, which is what a frame naming no column deserves.
    let write_doc = super::leading("Append this slot's tag and its value's own bytes.");
    let read_doc = super::leading("The slot `bytes` holds, or `None` where they name no column.");
    let bind_doc = super::leading("Bind this slot's value, in the type this database stores.");
    quote! {
      #[automatically_derived]
      impl #cursor_value for #name {
        #[doc = #write_doc]
        fn write_cursor(&self, __ingraph_out: &mut ::std::vec::Vec<::core::primitive::u8>) {
          match self {
            #(#writes)*
          }
        }

        #[doc = #read_doc]
        fn read_cursor(__ingraph_bytes: &[::core::primitive::u8]) -> ::core::option::Option<Self> {
          let (__ingraph_tag, __ingraph_rest) =
            <[::core::primitive::u8]>::split_first(__ingraph_bytes)?;
          match *__ingraph_tag {
            #(#reads)*
            _ => ::core::option::Option::None,
          }
        }
      }

      #[automatically_derived]
      impl<#db> #carrier<#db> for #name
      where
        #db: #database,
        #(#bounds)*
      {
        #[doc = #bind_doc]
        fn push_bind(&self, __ingraph_qb: &mut #held<#db>) {
          match self {
            #(#binds)*
          }
        }
      }
    }
  }
}

impl DatabaseBackend {
  /// One `ColumnKind<Db>` obligation per stored FIELD — what every impl in this family's chain owes
  /// before a row's `COLUMNS` can be evaluated.
  ///
  /// # Three impls state it, because a supertrait's obligations are not inherited
  ///
  /// `SqlOrdering` and `SqlWrite` both take `SqlQuery` as a supertrait, and proving THAT bound at a
  /// generic dialect re-asks every question the query binding's own `where` clause answers. A page
  /// or write impl that left this out fails at the `SqlQuery` obligation instead — with the scalar
  /// blanket's `Carrier` in the message and the field it is about nowhere in it.
  ///
  /// It REPLACES the write lane's per-column `Carrier` bound rather than joining it: a bind now goes
  /// through `push_columns`, a scalar's blanket asks its carrier row back, and a composite has no
  /// carrier row to ask for.
  fn shaped(&self, model: &RecordModel) -> proc_macro2::TokenStream {
    let db = super::parameter("DB");
    let _ = db;
    let column_kind = model.framework(&["column"], "ColumnKind");
    let types = self
      .columns()
      .iter()
      .filter(|column| !self.edge_stored(model, column))
      .map(|column| self.row_field(model, column));
    quote!(#(#types: #column_kind,)*)
  }

  /// One [`ColumnShape`](ingraph's `column::ColumnShape`) entry per stored FIELD, in the row's own
  /// order — what `SqlQuery::COLUMNS` holds, and what the fence beside it is evaluated over.
  ///
  /// The two lists PARTITION the row's stored columns: a gathered one has no value on the page row
  /// to select, so naming it here would ask the row's own table for a column it has not got.
  ///
  /// Every entry is the FIELD's TYPE answering. The emitter writes one uniform spelling and judges
  /// nothing about width — it cannot: `tb: Timebase` and `title: String` are the same tokens — so a
  /// scalar takes `ColumnKind`'s default and lands as one column while a composite states its parts
  /// and lands as its segments. The one thing the DECLARATION decides is `flatten`, which is a
  /// per-database naming knob rather than a claim about the type, and it selects the spelling that
  /// drops the field's name.
  ///
  /// # Each entry carries THIS database's half of the pairing
  ///
  /// A name is `ColumnName::new` where nothing moved it and `ColumnName::renamed` where
  /// `<db>(rename = "…")` did — the DECLARED half read off the record's own field and the
  /// STORED half off this database's block. So the same declared field lands under two spellings in
  /// two of these lists, which is what makes a reverse relation's `stored_column` lookup answer per
  /// database rather than per declaration.
  ///
  /// The two constructors rather than one taking both strings always: an un-renamed column would
  /// then state its own name twice in the expanded output, which reads as a fact somebody chose
  /// rather than as the absence of a rename.
  pub(crate) fn column_shapes(&self, model: &RecordModel) -> Vec<proc_macro2::TokenStream> {
    let column_name = model.framework(&["column"], "ColumnName");
    let shape = model.framework(&["column"], "shape");
    let flattened = model.framework(&["column"], "flattened");
    self
      .columns()
      .iter()
      .filter(|column| !self.edge_stored(model, column))
      .map(|column| {
        let ty = self.row_field(model, column);
        // An ARRAY ELEMENT is a stable attribute position, so this list really contracts under the
        // predicate — which is what makes every position derived from it correct without any of them
        // being recomputed.
        let gate = model.gate(&column.source);
        if column.flatten {
          return quote!(#gate #flattened::<#ty>(),);
        }
        let declared = column.declared();
        let stored = column.name.to_string();
        let name = if declared == stored {
          quote!(#column_name::new(#stored))
        } else {
          quote!(#column_name::renamed(#declared, #stored))
        };
        quote!(#gate #shape::<#ty>(#name),)
      })
      .collect()
  }

  /// **No two of this row's RENDERED columns share a name**, asserted where the declaration is
  /// written.
  ///
  /// # It is the same-name refusal reaching what a macro cannot see
  ///
  /// The front end already refuses two columns of one database sharing a name, and it compares the
  /// names it HAS: a field's own, its `rename`, one per declared column. A flattened composite's
  /// segments are not among them — `<db>(flatten)` on a `Timebase` puts `num` and `den` in
  /// the holder's own namespace, and the macro holding `tb: Timebase` cannot tell that type from a
  /// `String`. Which is exactly why the column contract is type-answered, and therefore why this
  /// half of the fence has to be too: it is a `const` over the answers, evaluated here.
  ///
  /// What it costs is that a field's type must have its `ColumnKind` row AT THE DECLARATION rather
  /// than at the first call site naming a dialect. That is the trade
  /// [`vocabulary`](super::DatabaseBackend::vocabulary) already makes for a column's crossing, and it
  /// is cheaper than that one: a width names no database, so no gate is needed and DECLARE-MANY /
  /// BUILD-ONE is untouched.
  ///
  /// # One assertion per FIELD, because a `const` message is a literal
  ///
  /// Nothing a const assertion says can be assembled from what collided, so the sentence is written
  /// HERE, at expansion, where the field's name is known — and asking the question one field at a
  /// time is what makes the assertion that fires the one that can name it.
  ///
  /// # Not gated, and not per-queryable
  ///
  /// Every SQL database's row gets one whether or not its query face is emitted: the collision is in
  /// the `CREATE TABLE` a migration writes, which a row with no `SELECT` still has. MongoDB gets
  /// none — its block has no `flatten` at all, its default being the nested subdocument.
  pub(crate) fn column_fence(&self, model: &RecordModel) -> proc_macro2::TokenStream {
    if !self.kind().is_sql() {
      return proc_macro2::TokenStream::new();
    }
    let shapes = self.column_shapes(model);
    if shapes.is_empty() {
      return proc_macro2::TokenStream::new();
    }
    let column_shape = model.framework(&["column"], "ColumnShape");
    let distinct = model.framework(&["column"], "distinct");
    let row = self.name();
    let selected: Vec<&PersistColumn> = self
      .columns()
      .iter()
      .filter(|column| !self.edge_stored(model, column))
      .collect();
    // The index each assertion asks about is a position in `__INGRAPH_COLUMNS__`, and that array
    // CONTRACTS under the predicates — so the position is a `const` the compiler folds after it has
    // stripped, never a literal this expansion decided. See [`positions`].
    let (places, at) = positions(model, &selected);
    let checked = selected.iter().zip(&at).map(|(column, at)| {
      let refusal = format!(
        "`{row}` would render `{column}` into a column one of its own fields already renders. \
         A `flatten`ed field lends NO name, so its type's segments join this row's own namespace \
         — a segment called `x` renders `x` rather than `{column}_x` — and a value flattened \
         beside a column of that name occupies it twice. Drop the `flatten` in this database's \
         block, or rename whichever column it meets.",
        column = column.name,
      );
      let gate = model.gate(&column.source);
      quote!(#gate ::core::assert!(#distinct(__INGRAPH_COLUMNS__, #at), #refusal);)
    });
    quote! {
      const _: () = {
        const __INGRAPH_COLUMNS__: &[#column_shape] = &[#(#shapes)*];
        #places
        #(#checked)*
      };
    }
  }

  /// Whether every column of this row has a WORD to be declared at — the BLUEPRINT's own condition,
  /// and the one fact about a schema this macro can read off tokens.
  ///
  /// A collection kept in a COLUMN is the only case: its row field is `Vec<E>`, and `Vec<T>` has no
  /// `StoredAs<Db>` row in any dialect. Everything else is a claim about a TYPE, which a macro
  /// holding `tb: Timebase` and `title: String` cannot tell apart — so it is left to the projection,
  /// spanned at the field. See [`RecordModel::describable`].
  fn words_every_column(&self, model: &RecordModel) -> bool {
    !self
      .columns()
      .iter()
      .any(|column| model.collects(&column.source) && !self.edge_stored(model, column))
  }

  /// The SCHEMA binding: `impl Describe<Db> for <Record>`, one per declared ∩ compiled-in SQL
  /// dialect, holding the `Table` a migration creates this record's storage from.
  ///
  /// ```ignore
  /// impl Describe<Sqlite> for Track {
  ///   const BLUEPRINT: Table = {
  ///     const WORDS: &[&[&str]] = &[<i64 as StoredAs<Sqlite>>::WORDS, …];  // one per FIELD
  ///     const NULLS: &[bool] = &[false, true, …];                          // one per FIELD
  ///     Table::shaped(
  ///       <TrackSqliteRow as SqlQuery<Sqlite>>::ADDRESS,
  ///       <TrackSqliteRow as SqlQuery<Sqlite>>::COLUMNS,
  ///       WORDS,
  ///       NULLS,
  ///     )
  ///     .with_indexes(INDEXES).with_uniques(UNIQUES).with_edges(EDGES).with_shadows(SHADOWS)
  ///   };
  /// }
  /// ```
  ///
  /// # It is on the RECORD and never on the row, and the graph's walk is what decides
  ///
  /// `#[ingraph::graph]` writes `type_iter` with one `#node: Describe<V::Db>` predicate per FIELD of
  /// the root, and a root's fields are the record types. A blueprint on the row would leave every
  /// one of those obligations undischarged while an impl existed one type over. It is the same
  /// grain `crate::index`'s `Describe<R>` already lands on for a corpus, and the same self type the
  /// vocabulary binding beside this one takes.
  ///
  /// # Nothing here is a NAME this expansion invents
  ///
  /// The address and the column list are `SqlQuery`'s, projected. The edge table's name is not
  /// stated at all — a descriptor carries the PATH and the renderer joins it, which is
  /// `comparison::sql::edge_table`'s derivation and not a second one. The companion column's name IS
  /// stated, because it is MINTED rather than declared: [`sort_column`](super::DatabaseBackend::sort_column)
  /// is the one mint, and the write plan beside this reads the same call.
  ///
  /// # The `where` clause is EMPTY, and that is measured rather than chosen
  ///
  /// A concrete impl cannot carry `Timebase: StoredAs<Sqlite>` as an assumption: a `where` clause
  /// over concrete types that does not hold is `trivial_bounds`, unstable, and `E0277` AT THE IMPL
  /// rather than at a call site. So every obligation this blueprint has is discharged where the
  /// projection is written, and each projection is spanned at the FIELD that owns it — which is what
  /// puts the caret on the declaration rather than inside generated code.
  ///
  /// # The two `const` REFUSALS, each written where the field's name is known
  ///
  /// A `const` message is a literal, so a sentence that names the field has to be assembled at
  /// EXPANSION — the discipline [`column_fence`](Self::column_fence) already keeps:
  ///
  ///   * an INDEXED or UNIQUE field spanning several columns. `with_indexes` names the column
  ///     directly, and a composite field's columns are `tb_num`/`tb_den` — the field's own name is
  ///     none of them, so the framework's `declares` would refuse it with a sentence that cannot say
  ///     which field it is about;
  ///   * an EDGE-TABLE element spanning several columns. `EdgeTable::new` takes ONE word, and a
  ///     composite element wants `EdgeTable::composite` with a `Column` per leaf — a list whose
  ///     length is the element type's answer, which no `const` here can build. Taking `WORDS[0]`
  ///     would describe a table one column wide where the write binds two, so it is refused.
  ///
  /// A NULLABLE ELEMENT is not a third, and the reason is the grammar rather than a decision here:
  /// `EdgeTable::new` declares its element column `NOT NULL`, and there is no word that makes ONE
  /// ELEMENT of a collection optional — the `optional` marker sits on the FIELD and makes the whole
  /// collection an `Option`, which a collection has no null state to be. So the shape this would
  /// refuse cannot be declared.
  ///
  /// # Per-SEGMENT nullability is not this emission's to state, and that is why it works
  ///
  /// `Table::shaped` takes one flag per FIELD, and this writes it from
  /// [`PersistColumn::nullable`](crate::model::PersistColumn::nullable), which follows the
  /// `optional` MARKER — a marker sits on a field, so the grain matches. There is no spelling in
  /// this grammar for *this segment of this composite holds `NULL` and that one does not*, and
  /// there does not need to be: a leaf that holds `NULL` whatever its field says states so on its
  /// own segment, as `ColumnShape::Nullable`, which reaches the renderer through `COLUMNS` and
  /// never passes through here.
  ///
  /// So the two facts arrive by two roads that cannot drift — the marker through this list, the
  /// leaf through the TYPE's own `SEGMENTS` — and the renderer composes them. A declaration that
  /// writes `at: MediaTimestamp` with no marker gets `at_pts` and the timebase pair `NOT NULL` and
  /// `at_nanos` nullable, which is neither this emission's decision nor a thing it could have
  /// spelled.
  fn blueprint(&self, model: &RecordModel) -> proc_macro2::TokenStream {
    let record = &model.record;
    let row = self.name();
    let backend = self.backend_type(model);
    let describe = model.framework(&["schema"], "Describe");
    let table = model.framework(&["schema"], "Table");
    let edge_table = model.framework(&["schema"], "EdgeTable");
    let edge_shape = model.framework(&["schema"], "EdgeShape");
    let shadow = model.framework(&["schema"], "Shadow");
    let stored_as = model.framework(&["column"], "StoredAs");
    let column_kind = model.framework(&["column"], "ColumnKind");
    let query = model.framework(&["query", "sql"], "SqlQuery");
    let field_name = model.framework(&["field"], "FieldName");
    let gate = model.framework(&["gate"], &self.kind().gate().to_string());

    // The two lists PARTITION the row's stored columns, exactly as `column_shapes` and `edge_writes`
    // partition them: a field in the row's own table has a word and a nullability, and one in a
    // second table has an `EdgeTable` instead. Reading the same predicate is what keeps a column the
    // `SELECT` names from being a column no `CREATE TABLE` declared.
    let held: Vec<&PersistColumn> = self
      .columns()
      .iter()
      .filter(|column| !self.edge_stored(model, column))
      .collect();
    let words = held.iter().map(|column| {
      let ty = self.row_field(model, column);
      let gate = model.gate(&column.source);
      // SPANNED AT THE FIELD: a type with no row for this dialect is `E0277`, and an unspanned
      // projection reports it at the `#[ingraph::record(…)]` — a caret on something the author
      // cannot edit. At the field, the message and the trait's own note land on the very token that
      // named the type.
      let read = quote_spanned!(column.source.span()=> <#ty as #stored_as<#backend>>::WORDS);
      quote!(#gate #read,)
    });
    let nulls = held.iter().map(|column| {
      let gate = model.gate(&column.source);
      let nullable = column.nullable;
      quote!(#gate #nullable,)
    });

    let marked = |wanted: fn(&PersistColumn) -> bool, word: &'static str| {
      let (mut checks, mut names) = (
        proc_macro2::TokenStream::new(),
        proc_macro2::TokenStream::new(),
      );
      for column in &held {
        // A COLLECTION is skipped here as well as refused at the front end, and the double is
        // deliberate: this reads the STORAGE FORM the same way `edge_stored` does, so the emitter
        // owes nothing to the parse having run — which is the discipline `column_fence` already
        // keeps beside a same-name refusal the front end also makes.
        if !wanted(column) || model.collects(&column.source) {
          continue;
        }
        let (gate, ty) = (model.gate(&column.source), self.row_field(model, column));
        let name = self.external(model, column);
        let refusal = format!(
          "`{name}` is marked `{word}` and spans SEVERAL columns — the statement names a column \
           directly, and a composite field's columns are its segments joined under its own name \
           (`{name}_…`) rather than `{name}` itself. Move the word onto a single-column field, or \
           give this one a `{db}(type = \"…\")` that is one column wide.",
          db = self.kind().as_str(),
        );
        checks.extend(quote! {
          #gate
          const _: () = ::core::assert!(<#ty as #column_kind>::SEGMENTS.is_empty(), #refusal);
        });
        names.extend(quote!(#gate #field_name::new(#name),));
      }
      (checks, names)
    };
    let (index_checks, indexes) = marked(|column| column.indexed, "indexed");
    let (unique_checks, uniques) = marked(|column| column.unique, "unique");

    // THE COMPOSITE constraints, already resolved to this database's column names by the front end:
    // every entry names a field this record declares, this database carries and stores in a column
    // of the row, and the duplicate check has run. So nothing is audited here — the list is written
    // out.
    //
    // No `SEGMENTS.is_empty()` check sits beside these, and its absence is the declaration's whole
    // point. The single-column words carry one because `with_indexes` names a column DIRECTLY and a
    // citizen's own name is none of its columns; a composite names ENTRIES and the framework fans a
    // citizen to its value leaves, so the shape those words refuse is the shape this one is for.
    //
    // THE GATES ARE STACKED, one per entry, and the conjunction is what `#[cfg]` already means: a
    // constraint over a column some build does not compile is not a narrower constraint, it is
    // absent — a narrower one would be a different index, under a name derived from a different
    // entry list, silently created by a feature flag.
    let composite = model.framework(&["schema"], "CompositeUnique");
    let composites = self.composite_uniques().iter().map(|constraint| {
      let (mut gates, mut names) = (
        proc_macro2::TokenStream::new(),
        proc_macro2::TokenStream::new(),
      );
      for entry in &constraint.entries {
        if let Some(column) = held
          .iter()
          .find(|column| column.name.external() == entry.external())
        {
          gates.extend(model.gate(&column.source));
        }
        let name = entry.external();
        names.extend(quote!(#field_name::new(#name),));
      }
      quote!(#gates #composite::new(&[#names]),)
    });

    // The collections, in the row's own order: each one's second table, and — where `sortable` put
    // the order in a column of the parent — the companion that carries it. The ELEMENT type is
    // `column.ty()`, which is what the write plan's own bind reads; the row field wraps it in a
    // `Vec` and neither the edge table nor the element word wants that.
    let (mut elements, mut edges, mut shadows) = (
      proc_macro2::TokenStream::new(),
      proc_macro2::TokenStream::new(),
      proc_macro2::TokenStream::new(),
    );
    for (at, column) in self.columns().iter().enumerate() {
      if !self.edge_stored(model, column) {
        continue;
      }
      let (gate, element) = (model.gate(&column.source), column.ty());
      let name = self.external(model, column);
      let word = format_ident!("__INGRAPH_ELEMENT_{at}__");
      let shape = match model.shape_of(&column.source) {
        Some(Label::Set) => quote!(#edge_shape::Set),
        _ => quote!(#edge_shape::Sequence),
      };
      let refusal = format!(
        "`{name}`'s element spans SEVERAL columns, and an edge table's element is declared at ONE \
         word — a composite element's columns are named per leaf, which is a list this expansion \
         cannot build in a `const`. Declare a `{db}(type = \"…\")` whose element is one column \
         wide, or write this record's `Describe` by hand.",
        db = self.kind().as_str(),
      );
      let read = quote_spanned!(column.source.span()=> <#element as #stored_as<#backend>>::WORDS);
      elements.extend(quote! {
        #gate
        const #word: &'static ::core::primitive::str = {
          const __INGRAPH_ELEMENT__: &[&'static ::core::primitive::str] = #read;
          ::core::assert!(<[_]>::len(__INGRAPH_ELEMENT__) == 1, #refusal);
          __INGRAPH_ELEMENT__[0]
        };
      });
      // THE VALUE-LED WORD, appended as the builder a declaration spells it as. A collection that
      // wrote nothing renders the call it rendered before the word existed, which is what keeps an
      // un-worded collection's DDL byte-identical to today's.
      let seek = self
        .seeks_by_value(model, column)
        .then(|| quote!(.indexed()));
      edges.extend(quote! {
        #gate
        #edge_table::new(&[#field_name::new(#name)], #shape, #word) #seek,
      });
      if !self.mirrors(model, column) {
        continue;
      }
      let companion = self.sort_column(model, column);
      shadows.extend(quote! {
        #gate
        #shadow::new(#field_name::new(#companion), &[#field_name::new(#name)]),
      });
    }

    quote! {
      #gate! {
        #[automatically_derived]
        impl #describe<#backend> for #record {
          const BLUEPRINT: #table = {
            #index_checks
            #unique_checks
            #elements
            // ONE WORD LIST PER FIELD and one flag apiece, in `COLUMNS`'s own order — the agreement
            // `Table::shaped` asserts, and the reason both arrays are written from the same walk the
            // column list is. Each contracts under the same `#[cfg]`, so a stripped field leaves
            // three lists of equal length rather than one short one.
            const __INGRAPH_WORDS__: &[&[&'static ::core::primitive::str]] = &[#(#words)*];
            const __INGRAPH_NULLS__: &[::core::primitive::bool] = &[#(#nulls)*];
            const __INGRAPH_INDEXES__: &[&'static #field_name] = &[#indexes];
            const __INGRAPH_UNIQUES__: &[&'static #field_name] = &[#uniques];
            const __INGRAPH_COMPOSITES__: &[#composite] = &[#(#composites)*];
            const __INGRAPH_EDGES__: &[#edge_table] = &[#edges];
            const __INGRAPH_SHADOWS__: &[#shadow] = &[#shadows];
            #table::shaped(
                <#row as #query<#backend>>::ADDRESS,
                <#row as #query<#backend>>::COLUMNS,
                __INGRAPH_WORDS__,
                __INGRAPH_NULLS__,
            )
            .with_indexes(__INGRAPH_INDEXES__)
            // The UNIQUES precede the COMPOSITES, and the order is load-bearing for the reason the
            // pair below carries one: `with_composite_uniques` refuses a one-entry constraint over
            // a column `uniques` already names, so it reads a list the call before it has settled.
            // The front end refuses that pair too, by name and at the authored word — this ordering
            // is what makes the framework's own check a real second gate rather than a dead one.
            .with_uniques(__INGRAPH_UNIQUES__)
            .with_composite_uniques(__INGRAPH_COMPOSITES__)
            // The EDGES precede the SHADOWS, and the order is load-bearing: `with_shadows` refuses a
            // companion whose path names no edge table of THIS descriptor, so it reads a list the
            // call before it has already settled.
            .with_edges(__INGRAPH_EDGES__)
            .with_shadows(__INGRAPH_SHADOWS__)
          };
        }
      }
    }
  }

  /// The two engine bindings: what a query reads this row through, and — where the record has an
  /// order-by type to name — what a PAGE reads it through.
  ///
  /// The `where` clause is the comparison's own assumptions plus one obligation per projection the
  /// impl names. Stating the obligations rather than the predicates that discharge them is what
  /// keeps this emission from having to know which bounds `SqlKeyIn` or the comparison kinds ask a
  /// dialect for: a concrete dialect discharges them at the call site, and a dialect that cannot is
  /// refused there rather than here.
  fn bindings(&self, model: &RecordModel) -> proc_macro2::TokenStream {
    let row = self.name();
    let record = &model.record;
    let cursor = self.cursor_name();
    let comparison = self.comparison_name();
    let db = super::parameter("DB");

    let query = model.framework(&["query", "sql"], "SqlQuery");
    let vocabulary = model.framework(&["transform"], "Record");
    let crossing = model.framework(&["query", "sql"], "CrossingError");
    let complex = model.framework(&["comparison"], "ComplexComparison");
    let carrier = model.framework(&["comparison", "sql"], "Carrier");
    let key_in = model.framework(&["comparison", "sql"], "SqlKeyIn");
    let field_name = model.framework(&["field"], "FieldName");
    let column_shape = model.framework(&["column"], "ColumnShape");
    let shaped = self.shaped(model);
    let address_ty = model.framework(&["comparison"], "RecordAddress");
    let identifiable = model.framework(&["transform"], "Identifiable");
    let database = model.framework(&["sqlx"], "Database");
    let assumptions = self.assumptions(model);

    let shared = model.stored_columns();
    let id_at = model
      .id_column_stored()
      .expect("`RecordModel::queryable` refuses a database whose id is not stored");
    // The ADDRESS is ONE column, and it is the id — see `RecordModel::id_column_stored`. The
    // lineage columns are stored beside it and filterable like any other; what they are not is part
    // of the address, because the id already names at most one row.
    //
    // Looked up by SOURCE, and the `expect` is the unskippable-identity LAW: an address step is a
    // column of every database the record declares, both narrowing spellings being refused on one at
    // the word. The shared list's index is the ORDER-BY variant's and never this database's.
    let id_column = self
      .stores(&shared[id_at].source)
      .expect("an address step is a column of every database the record declares");
    let id_name = id_column.name.to_string();
    let id_value = {
      let variant = shared[id_at].order_variant();
      let value = id_column.from.apply(
        quote!(::core::clone::Clone::clone(__ingraph_id)),
        id_column.stored.is_some(),
      );
      quote!(#cursor::#variant(#value))
    };
    // The DUAL of the address: the same column and the same declared conversion, read the other way,
    // so a rename or a converter moves both at once.
    let id_read = {
      let field = id_column.name.safe();
      id_column.into.apply(
        quote!(::core::clone::Clone::clone(&self.#field)),
        id_column.stored.is_some(),
      )
    };
    let selected = self.column_shapes(model);
    // D2: an edge table correlates on the parent's ADDRESS, and the address is the id — so the
    // gather binds one column and the elements come back keyed by the one column that identifies
    // their parent. The correlation reads this list and nothing else, which is why it did not have
    // to learn anything about the collapse.
    let (plan, crossings, hydration) = self.collections(model, &[id_at]);
    let table = model.table_name(self);
    // Every alias a nested scope may call this row by, minted at EXPANSION: an alias is a pure
    // function of a namespace, the table's name and the depth of the scope wearing it, and all three
    // are known here. The engine indexes rather than building a string, and the depth it indexes
    // with is refused past the LAST ONE MINTED rather than wrapped — see `crate::alias`.
    //
    // Both halves are THIS database's: `<db>(alias(…))` moves them one backend at a time,
    // which is what the emitted item's own shape already allowed — there is one per `SqlQuery<Db>`.
    let alias = &self.storage().aliases;
    let aliases = crate::alias::aliases(alias.prefix_in(&model.prefix), &table, alias.depth());
    // `From` where every column's conversion is infallible, `TryFrom` where any is not — which is
    // the pair `conversions` emits, read here rather than decided again.
    //
    // The fallible arm CONVERTS rather than handing the result straight back, and that is the
    // record's declared error arriving: a row's `TryFrom` answers with whatever
    // `<db>(error = "…")` named, where the engine's seam takes `CrossingError`. `Into` is
    // what carries one into the other, and a declared error that cannot make the crossing is
    // `E0277` HERE, naming it — which is the same tooth every other leg has.
    let raise = if self.reads_fallibly(model) {
      quote! {
        ::core::result::Result::map_err(
          <#record as ::core::convert::TryFrom<#row>>::try_from(self),
          ::core::convert::Into::into,
        )
      }
    } else {
      quote!(::core::result::Result::Ok(
        <#record as ::core::convert::From<#row>>::from(self)
      ))
    };

    let bindings = quote! {
      #[automatically_derived]
      impl<#db> #query<#db> for #row
      where
        // `sqlx::Database` beside the backend, because the CURSOR VALUE's obligation below names
        // `Carrier<Db>`, whose own parameter is bounded that way. The engine's trait asks for less
        // — a query needs a backend and nothing more — and this impl asks for what the projections
        // it states are well formed under.
        #db: #database,
        #assumptions
        // The RECORD's vocabulary binding at this dialect, and the item bound the engine asks of
        // it. Stated as an OBLIGATION rather than named: the vocabulary's impls are one per DECLARED
        // backend and each names a CONCRETE one, so a call site holding a real dialect discharges
        // this and a dialect the declaration does not store in is refused there. Which is the
        // discipline the crossings above already follow, one vocabulary over.
        #record: #vocabulary<#db, Comparison: #complex<#db>>,
        #comparison<#db>: #complex<#db>,
        #cursor: #carrier<#db>,
        #shaped
        // WIDTH ONE, and the type is the general one at its degenerate width rather than a
        // second, scalar machine: the mandated path runs exactly the code a user-declared compound
        // key runs, so the wide path cannot rot unexercised. The membership ceiling at this width
        // is `k` rows, which is what it should be.
        #key_in<#cursor, #db, 1>: #complex<#db>,
        #hydration
      {
        type Record = #record;
        type Address = #key_in<#cursor, #db, 1>;

        const ADDRESS: #address_ty = #address_ty::new(
          #field_name::new(#table),
          &[#field_name::new(#id_name)],
        );
        const ALIASES: &'static [&'static str] = &[#(#aliases),*];
        const COLUMNS: &'static [#column_shape] = &[#(#selected)*];
        #plan

        // The ID is what addresses a row, so it is the whole parameter and this binds one column.
        // The lineage the record's `*Key` also carries stays where storage keeps it — in the row's
        // own columns, where a filter can still reach it.
        //
        // A SLICE, because the predicate is a membership either way: `get` passes one and an
        // interface's hydration passes a page's worth, and the statement is the same at both widths.
        //
        // Spelled through `Identifiable` because qualification selects a trait's OWN items: `Id` is
        // the supertrait's, and naming `Transformer` here would be `E0576`.
        fn addresses(
          ids: &[<#record as #identifiable>::Id],
        ) -> ::core::result::Result<Self::Address, #crossing> {
          let mut __ingraph_keys = ::std::vec::Vec::with_capacity(<[_]>::len(ids));
          for __ingraph_id in ids {
            ::std::vec::Vec::push(&mut __ingraph_keys, [#id_value]);
          }
          ::core::result::Result::Ok(#key_in::new([#id_name], __ingraph_keys))
        }

        // The address read the OTHER way, off a row a gather answered with — which is what lets a
        // batch that came back in the engine's order be lined up with the order it was asked in.
        fn id(&self) -> ::core::result::Result<<#record as #identifiable>::Id, #crossing> {
          ::core::result::Result::Ok(#id_read)
        }

        fn record(self) -> ::core::result::Result<#record, #crossing> {
          #raise
        }
      }

      #crossings
    };
    let mut emitted = bindings;
    if model.orderable() {
      emitted.extend(self.ordering(model, &hydration));
    }
    emitted.extend(self.writing(model, &hydration));
    emitted
  }

  /// The WRITE's half of the binding: the crossing INTO the row, the bind off each of its columns,
  /// and the plan its collections are stored by.
  ///
  /// # It is UNCONDITIONAL where the ordering is not
  ///
  /// `SqlWrite` is `SqlQuery`'s subtrait, so everything that decides whether the query face is
  /// emitted at all has already decided this — [`RecordModel::queryable`] is the one place, and the
  /// caller has walked it. What the ordering adds on top is an order-by TYPE, which is a second
  /// condition and therefore a second `if`; a write needs no type this emission has not already
  /// declared.
  ///
  /// # The two plans are ONE walk over the same columns
  ///
  /// [`collections`](Self::collections) states how each collection is MATERIALIZED and this states
  /// how each is STORED, and both read [`edge_stored`](super::DatabaseBackend::edge_stored) for the
  /// same answer — so a column the read gathers is a column the write puts in an edge table, and no
  /// declaration can be half of each.
  fn writing(
    &self,
    model: &RecordModel,
    hydration: &proc_macro2::TokenStream,
  ) -> proc_macro2::TokenStream {
    let row = self.name();
    let record = &model.record;
    let cursor = self.cursor_name();
    let comparison = self.comparison_name();
    let db = super::parameter("DB");

    let write = model.framework(&["query", "sql"], "SqlWrite");
    let vocabulary = model.framework(&["transform"], "Record");
    let crossing = model.framework(&["query", "sql"], "CrossingError");
    let complex = model.framework(&["comparison"], "ComplexComparison");
    let carrier = model.framework(&["comparison", "sql"], "Carrier");
    let key_in = model.framework(&["comparison", "sql"], "SqlKeyIn");
    let database = model.framework(&["sqlx"], "Database");
    let held = model.framework(&["sqlx"], "QueryBuilder");
    let assumptions = self.assumptions(model);

    let columns = self.columns();
    let id_at = model
      .id_column_stored()
      .expect("`RecordModel::queryable` refuses a database whose id is not stored");
    let (plan, crossings, bounds) = self.edge_writes(model);
    let shaped = self.shaped(model);
    let selected_types: Vec<proc_macro2::TokenStream> = columns
      .iter()
      .filter(|column| !self.edge_stored(model, column))
      .map(|column| self.row_field(model, column))
      .collect();

    // The columns a value of this row is bound for, in `SqlQuery::COLUMNS`'s own order — the two
    // lists PARTITION the row's stored columns, so an edge-stored collection has no bind here for the
    // same reason it has no name in the `SELECT`.
    let selected: Vec<&PersistColumn> = columns
      .iter()
      .filter(|column| !self.edge_stored(model, column))
      .collect();
    let push = |column: &PersistColumn| {
      let (field, ty) = (column.name.safe(), self.row_field(model, column));
      quote!(<#ty as #carrier<#db>>::push_bind(&self.#field, __ingraph_qb))
    };
    let bind = self.dispatch(model, &selected, push);
    // ONE column, always: the address is the id — see the binding's `ADDRESS` above — so the
    // position the engine hands in has nothing to select and the general form is the degenerate one.
    // The id is never conditional, so this dispatch never takes the running-sum shape.
    let bind_address = self.dispatch(model, &[&columns[id_at]], push);

    // `From` where every column's conversion is infallible, `TryFrom` where any is not — the same
    // pair `conversions` emits, read through `writes_fallibly` rather than decided again. The
    // fallible arm CONVERTS, which is the declared error arriving: a row's `TryFrom` answers with
    // whatever `<db>(try_from(error = "…"))` named, where the engine's seam takes
    // `CrossingError`, and a cell that cannot make that crossing is `E0277` HERE, naming it.
    let project = if self.writes_fallibly() {
      quote! {
        ::core::result::Result::map_err(
          <#row as ::core::convert::TryFrom<#record>>::try_from(record),
          ::core::convert::Into::into,
        )
      }
    } else {
      quote!(::core::result::Result::Ok(
        <#row as ::core::convert::From<#record>>::from(record)
      ))
    };

    let bind_doc = super::leading(
      "Bind this row's `at`th column, in the order `SqlQuery::COLUMNS` names them — the values, \
       where the engine writes every bracket and every comma around them.",
    );
    let address_doc = super::leading(
      "Bind this row's `at`th address column. There is ONE, so the position is unread: the id is \
       what names a row, and a framework-emitted table declares it `UNIQUE`.",
    );
    quote! {
      #[automatically_derived]
      impl<#db> #write<#db> for #row
      where
        #db: #database,
        #assumptions
        #record: #vocabulary<#db, Comparison: #complex<#db>>,
        #comparison<#db>: #complex<#db>,
        #cursor: #carrier<#db>,
        // The same width the query binding states, and it has to be the same: this trait's
        // supertrait is that impl, so a different one would name an `Address` the row has not got.
        #key_in<#cursor, #db, 1>: #complex<#db>,
        // `SqlQuery` is the supertrait, so whatever the READ plan's crossings ask of the dialect is
        // owed here too — a row that stores its collections has to be queryable to be writable.
        #hydration
        // What this lane's own binds cost: one per column a value is rendered for, and one per
        // element type an edge table stores. A composite's carrier row is what pushes ITS several,
        // so the list is by field here exactly as `COLUMNS` is.
        #(#selected_types: #carrier<#db>,)*
        #shaped
        #bounds
      {
        #plan

        fn row(record: #record) -> ::core::result::Result<Self, #crossing> {
          #project
        }

        #[doc = #bind_doc]
        fn bind(&self, __ingraph_at: ::core::primitive::usize, __ingraph_qb: &mut #held<#db>) {
          #bind
        }

        #[doc = #address_doc]
        fn bind_address(
          &self,
          __ingraph_at: ::core::primitive::usize,
          __ingraph_qb: &mut #held<#db>,
        ) {
          #bind_address
        }
      }

      #crossings
    }
  }

  /// One position-indexed dispatch over `arms`, in the shape the engine's `usize` selects them by.
  ///
  /// The LAST arm takes the fall-through, so the match is total without an unreachable one — and a
  /// list of ONE has no position to read at all, which is what the discard is for: a `match` over a
  /// single binding is a lint in the crate the expansion lands in.
  ///
  /// # Two shapes, and the CONDITION is what chooses between them
  ///
  /// The position the engine hands in is an index into `SqlQuery::COLUMNS`, and that list CONTRACTS
  /// under a conditional column's predicate — so `0`, `1`, `2` written as literals would be naming
  /// positions this build no longer has. Where a column is conditional the arms are keyed on the
  /// `const` running sum [`positions`] writes, each arm under the same gate as the column it binds,
  /// and the fall-through becomes an explicit nothing rather than the last column's arm.
  ///
  /// Where NO column is conditional the shape is the one it always was, literal for literal. Not
  /// tidiness: the running sum is correct-and-necessary only where something can be absent, and an
  /// expansion that grew a chain of `const`s for every record in the world would be paying for a case
  /// it has not got.
  fn dispatch(
    &self,
    model: &RecordModel,
    columns: &[&PersistColumn],
    arm: impl Fn(&PersistColumn) -> proc_macro2::TokenStream,
  ) -> proc_macro2::TokenStream {
    let width = columns.len();
    let conditional = columns
      .iter()
      .any(|column| !model.gate(&column.source).is_empty());
    if !conditional {
      if width == 1 {
        let only = columns
          .first()
          .map(|column| arm(column))
          .unwrap_or_default();
        return quote! {
          let _ = __ingraph_at;
          #only;
        };
      }
      let arms = columns.iter().enumerate().map(|(at, column)| {
        let arm = arm(column);
        if at + 1 == width {
          return quote!(_ => #arm,);
        }
        quote!(#at => #arm,)
      });
      return quote! {
        match __ingraph_at {
          #(#arms)*
        }
      };
    }
    let (places, at) = positions(model, columns);
    let arms = columns.iter().zip(&at).map(|(column, at)| {
      let (gate, arm) = (model.gate(&column.source), arm(column));
      quote!(#gate #at => #arm,)
    });
    quote! {
      #places
      match __ingraph_at {
        #(#arms)*
        // The engine never asks past the width it read off `COLUMNS`, so this arm is what makes the
        // match total rather than a case with an answer of its own.
        _ => {}
      }
    }
  }

  /// The WRITE plan: what each edge-stored collection contributes, and the two crossings each needs.
  ///
  /// # Two entries where the read plan holds one, and neither is the other's copy
  ///
  /// A read's entry says how a collection is MATERIALIZED — which forks per dialect — and holds the
  /// crossings that DECODE. A write's says how many elements the row holds and how to bind one, and
  /// forks not at all: an aggregate and a gather are both edge tables when they are written. What
  /// the two share is the PATH, and both state the one the column's own external name gives, so the
  /// table a write fills and the table a read gathers from are one derivation.
  ///
  /// The crossings are FREE FUNCTIONS for [`collections`](Self::collections)' reason: an element's
  /// type is the declaration's and nothing generic over the dialect can name it, so a plan entry
  /// holds pointers and a generic free function is what a pointer can be taken of.
  fn edge_writes(
    &self,
    model: &RecordModel,
  ) -> (
    proc_macro2::TokenStream,
    proc_macro2::TokenStream,
    proc_macro2::TokenStream,
  ) {
    let edges: Vec<&PersistColumn> = self
      .columns()
      .iter()
      .filter(|column| self.edge_stored(model, column))
      .collect();
    if edges.is_empty() {
      // Nothing at all rather than an empty plan: the engine DEFAULTS the const, so a record whose
      // collections this database keeps in a column of the row pays one `is_empty` test and no
      // emission.
      return Default::default();
    }

    let row = self.name();
    let db = super::parameter("DB");
    let edge_write = model.framework(&["query", "sql"], "EdgeWrite");
    let edge_shape = model.framework(&["query", "sql"], "EdgeShape");
    let field_name = model.framework(&["field"], "FieldName");
    let carrier = model.framework(&["comparison", "sql"], "Carrier");
    let database = model.framework(&["sqlx"], "Database");
    let held = model.framework(&["sqlx"], "QueryBuilder");

    let shadow_write = model.framework(&["query", "sql"], "ShadowWrite");
    let sort_key = model.framework(&["sort"], "SortKey");
    let collection_sort_key = model.framework(&["sort"], "collection_sort_key");
    let bytes = sort_key_type();

    let mut elements: Vec<&syn::Type> = Vec::new();
    let mut sortable: Vec<&syn::Type> = Vec::new();
    let mut crossings = proc_macro2::TokenStream::new();
    let mut entries = proc_macro2::TokenStream::new();
    let mut companions = proc_macro2::TokenStream::new();
    for column in edges {
      let field = column.name.safe();
      let external = column.name.to_string();
      let element = column.ty();
      elements.push(element);
      let shape = match model.shape_of(&column.source) {
        Some(Label::Set) => quote!(#edge_shape::Set),
        _ => quote!(#edge_shape::Sequence),
      };
      // Named from the DATABASE for the read plan's reason: a kind is one of four words, none of
      // them holding a `_`, so the name splits one way and can never be read as another kind beside
      // a different column.
      let kind = self.kind().as_str();
      let count = format_ident!("__ingraph_count_{kind}_{field}");
      let bind = format_ident!("__ingraph_element_{kind}_{field}");
      let count_doc = super::leading(&format!(
        "How many elements this row's `{external}` holds — the count the engine renders that many \
         value rows for."
      ));
      let bind_doc = super::leading(&format!(
        "Bind this row's `at`th `{external}` element. The engine writes the parentheses, the commas \
         and the ORDINAL beside it: a position is the plan's own counter, so an element's crossing \
         states the value and nothing about where in the collection it sits."
      ));
      // The CONDITION, on the plan entry and on each free function it points at. Both are items, so
      // the gate rides each of them; the WHERE-PREDICATES the element contributes below cannot carry
      // one — Rust has no attribute position on a where-predicate — and stay, which is the seat's one
      // stated limit. See the guide's `record` chapter.
      let gate = model.gate(&column.source);
      crossings.extend(quote! {
        #gate
        #[doc = #count_doc]
        fn #count(__ingraph_row: &#row) -> ::core::primitive::usize {
          ::std::vec::Vec::len(&__ingraph_row.#field)
        }

        #gate
        #[doc = #bind_doc]
        fn #bind<#db>(
          __ingraph_row: &#row,
          __ingraph_at: ::core::primitive::usize,
          __ingraph_qb: &mut #held<#db>,
        )
        where
          #db: #database,
          #element: #carrier<#db>,
        {
          <#element as #carrier<#db>>::push_bind(&__ingraph_row.#field[__ingraph_at], __ingraph_qb);
        }
      });
      entries.extend(quote! {
        #gate
        #edge_write::new(
          &[#field_name::new(#external)],
          #shape,
          #count,
          #bind::<#db>,
        ),
      });
      if !self.mirrors(model, column) {
        continue;
      }
      // The `sortable` word's write half: ONE more bind on the PARENT statement, computed from the
      // collection this row holds. It is not a second statement and could not be — a companion is a
      // column of the row — which is what puts the dual write inside the single-transaction law with
      // nothing to arrange.
      sortable.push(element);
      let companion = self.sort_column(model, column);
      let key = format_ident!("__ingraph_sort_{kind}_{field}");
      let key_doc = super::leading(&format!(
        "This row's `{external}`, as the ORDER-PRESERVING bytes `{companion}` holds. The engine \
         writes the column and the placeholder; what the declaration owns is the value, and the \
         value is the framework's own encoding of the collection this row carries."
      ));
      crossings.extend(quote! {
        #gate
        #[doc = #key_doc]
        fn #key<#db>(__ingraph_row: &#row, __ingraph_qb: &mut #held<#db>)
        where
          #db: #database,
          #element: #sort_key,
          #bytes: #carrier<#db>,
        {
          <#bytes as #carrier<#db>>::push_bind(
            &#collection_sort_key(&__ingraph_row.#field),
            __ingraph_qb,
          );
        }
      });
      companions.extend(quote! {
        #gate
        #shadow_write::new(#field_name::new(#companion), #key::<#db>),
      });
    }

    // Naming a crossing in the plan is USING it, so what each of them asks of the dialect is owed at
    // the impl that takes its pointer — the same restatement the read plan's own obligations make.
    // The companions add two: the ELEMENT answering `SortKey`, which is where a collection of floats
    // is refused at the declaration, and the byte carrier the companion binds through.
    let mut bounds = quote!(#(#elements: #carrier<#db>,)*);
    let companion_plan = if sortable.is_empty() {
      // Nothing at all rather than an empty const, for the reason an edgeless record emits no plan:
      // the engine DEFAULTS `SHADOWS`, so a record that never wrote the word gets back the tokens it
      // got before the word existed.
      proc_macro2::TokenStream::new()
    } else {
      bounds.extend(quote!(#(#sortable: #sort_key,)* #bytes: #carrier<#db>,));
      quote! {
        const SHADOWS: &'static [#shadow_write<Self, #db>] = &[#companions];
      }
    };
    let plan = quote! {
      const EDGES: &'static [#edge_write<Self, #db>] = &[#entries];
      #companion_plan
    };
    (plan, crossings, bounds)
  }

  /// The COLLECTION PLAN: what this database materializes each of the row's collections with, the
  /// two typed crossings each one needs, and the obligations naming them adds to the binding.
  ///
  /// # Every name in it is DERIVED, and this emission is the naming contract's FOURTH party
  ///
  /// The plan states a PATH — the column's own external name in this database — and the engine makes
  /// the rest of it: the edge table is `edge_table`'s join of the row's table with that path, the
  /// ordinal is `<field>_ordinal` one frame below the value column, and the parent keys are the
  /// row's own address. Nothing here joins a name.
  ///
  /// That is what puts this emission beside the two kinds in `ingraph`'s `comparison::sql::edge` and
  /// the engine's own materialization: three parties, one derivation, so none of them can drift from
  /// another. The fourth is the caller's migration, which has a TEXT and is therefore the one that
  /// can be wrong; a first-party DDL emitter would be the fifth and would close that by deriving too.
  /// The contract itself is stated where the derivation lives — see that module's note, which lists
  /// the parties.
  ///
  /// The failure mode is worth stating because it is the good one: a plan naming the wrong path
  /// names a wrong TABLE rather than rendering a subtly wrong statement over the right one.
  ///
  /// # The crossings are FREE FUNCTIONS, and they have to be
  ///
  /// A plan entry holds `fn` POINTERS, because an element's type is the declaration's and nothing
  /// generic over the dialect can name it. A generic free function instantiated at this impl's own
  /// `DB` is what a pointer can be taken of; an inherent method could not be, being on a type whose
  /// impl is not generic in the dialect. They live inside the record's anonymous const, so their
  /// names cannot collide with anything the declaring module wrote.
  ///
  /// # What is emitted per DIALECT
  ///
  /// | dialect | a declared collection emits | said by |
  /// |---|---|---|
  /// | SQLite, MySQL | a GATHER — a second statement, batched over the page's keys | the DIALECT: neither has an array type, so neither has a choice |
  /// | Postgres, `edge` written | an AGGREGATE — a correlated subselect on the page's own SELECT list | the DECLARATION: `PersistColumn::edge` |
  /// | Postgres, no word | nothing; the column rides the row as a native array | the DEFAULT, guarded by the storability audit |
  ///
  /// The last row is where the absence of a word is checked rather than assumed: a collection with
  /// no word binds `Vec<E>: Carrier<Postgres>`, so an element no array can hold is `E0277` at the
  /// `#[ingraph::record(…)]` — and this word is that refusal's ANSWER. Nothing here manufactures a
  /// diagnostic for it; the audit already names the type at the declaration.
  fn collections(
    &self,
    model: &RecordModel,
    key_at: &[usize],
  ) -> (
    proc_macro2::TokenStream,
    proc_macro2::TokenStream,
    proc_macro2::TokenStream,
  ) {
    let columns = self.columns();
    let edges: Vec<&PersistColumn> = self
      .columns()
      .iter()
      .filter(|column| self.edge_stored(model, column))
      .collect();
    if edges.is_empty() {
      // Nothing at all rather than an empty plan: the engine DEFAULTS the const, so a record whose
      // collections this database does not gather pays one `is_empty` test and no emission.
      return Default::default();
    }

    let row = self.name();
    let db = super::parameter("DB");
    let edge_collection = model.framework(&["query", "sql"], "EdgeCollection");
    let edge_shape = model.framework(&["query", "sql"], "EdgeShape");
    let element_alias = model.framework(&["query", "sql"], "ELEMENT");
    let distribute = model.framework(&["query", "sql"], "distribute");
    let aggregated = model.framework(&["query", "sql"], "aggregated");
    let field_name = model.framework(&["field"], "FieldName");
    let carrier = model.framework(&["comparison", "sql"], "Carrier");
    let database = model.framework(&["sqlx"], "Database");
    let held = model.framework(&["sqlx"], "QueryBuilder");
    let row_trait = model.framework(&["sqlx"], "Row");
    let decode = model.framework(&["sqlx"], "Decode");
    let column_type = model.framework(&["sqlx"], "Type");
    let column_index = model.framework(&["sqlx"], "ColumnIndex");
    let sqlx_error = model.framework(&["sqlx"], "Error");

    let key_types: Vec<&syn::Type> = key_at.iter().map(|&at| columns[at].ty()).collect();
    let key_fields: Vec<&syn::Ident> = key_at.iter().map(|&at| columns[at].name.safe()).collect();
    let key_names: Vec<String> = key_at
      .iter()
      .map(|&at| columns[at].name.to_string())
      .collect();

    // Named from the DATABASE rather than from the row, and that is what makes a collision
    // unspellable rather than unlikely: a kind is one of four words, none of them holding a `_`, so
    // `__ingraph_take_<kind>_<column>` splits one way and can never be read as another kind beside a
    // different column. A row's name could not promise that — `MediaSqlite`'s `tags` and `Media`'s
    // `sqlite_tags` would run together. One backend per kind is the parser's `set_once`, so the kind
    // identifies the database uniquely inside this record's own anonymous const.
    let binder = format_ident!("__ingraph_key_{}", self.kind().as_str());
    // The `usize` the engine hands in is a position in `SqlQuery::ADDRESS`'s key list, and the last
    // column takes the fall-through so the match is total without an unreachable arm. A key of ONE
    // column has no position to read, and a `match` over a single binding is a lint in the crate the
    // expansion lands in.
    let bind = if key_fields.len() == 1 {
      let (field, ty) = (&key_fields[0], &key_types[0]);
      quote! {
        let _ = __ingraph_at;
        <#ty as #carrier<#db>>::push_bind(&__ingraph_row.#field, __ingraph_qb);
      }
    } else {
      let arms = key_fields.iter().zip(&key_types).enumerate().map(
        |(position, (field, ty))| -> proc_macro2::TokenStream {
          let bind = quote!(<#ty as #carrier<#db>>::push_bind(&__ingraph_row.#field, __ingraph_qb));
          if position + 1 == key_fields.len() {
            return quote!(_ => #bind,);
          }
          quote!(#position => #bind,)
        },
      );
      quote! {
        match __ingraph_at {
          #(#arms)*
        }
      }
    };
    let binder_doc = super::leading(
      "Bind one of this row's key columns, in the order `SqlQuery::ADDRESS` names them — the plan's \
       half of a gather's membership, where the engine writes every bracket around it.",
    );
    // Only where a GATHER needs one. An aggregate rides the page statement and binds no membership
    // of its own, so a plan that is all aggregates has no key to bind — and an emitted function
    // nothing names is `dead_code` in the crate the expansion lands in.
    let gathers = edges.iter().any(|column| !self.aggregates(model, column));
    let mut crossings = if gathers {
      quote! {
        #[doc = #binder_doc]
        fn #binder<#db>(
          __ingraph_row: &#row,
          __ingraph_at: ::core::primitive::usize,
          __ingraph_qb: &mut #held<#db>,
        )
        where
          #db: #database,
          #(#key_types: #carrier<#db>,)*
        {
          #bind
        }
      }
    } else {
      proc_macro2::TokenStream::new()
    };

    let mut gathered_elements: Vec<&syn::Type> = Vec::new();
    let mut aggregated_elements: Vec<&syn::Type> = Vec::new();
    let mut entries = proc_macro2::TokenStream::new();
    for column in edges {
      let field = column.name.safe();
      let external = column.name.to_string();
      let element = column.ty();
      let shape = match model.shape_of(&column.source) {
        Some(Label::Set) => quote!(#edge_shape::Set),
        _ => quote!(#edge_shape::Sequence),
      };
      let take = format_ident!(
        "__ingraph_take_{}_{}",
        self.kind().as_str(),
        column.name.safe()
      );
      // The CONDITION, on the crossing item and on the plan entry that points at it — the read
      // plan's half of what the write plan already carries.
      let gate = model.gate(&column.source);
      if self.aggregates(model, column) {
        aggregated_elements.push(element);
        let take_doc = super::leading(&format!(
          "Take the `{external}` array off the page row it rode in on — the plan's whole crossing \
           for an aggregate, and one call. The ALIAS is the ENGINE's: several aggregates ride one \
           statement, so the party that wrote the names is the party that hands them over."
        ));
        crossings.extend(quote! {
          #gate
          #[doc = #take_doc]
          fn #take<#db>(
            __ingraph_row: &mut #row,
            __ingraph_from: &<#db as #database>::Row,
            __ingraph_alias: &::core::primitive::str,
          ) -> ::core::result::Result<(), #sqlx_error>
          where
            #db: #database,
            for<'__ingraph_r> ::core::option::Option<::std::vec::Vec<#element>>:
              #decode<'__ingraph_r, #db> + #column_type<#db>,
            for<'__ingraph_a> &'__ingraph_a ::core::primitive::str:
              #column_index<<#db as #database>::Row>,
          {
            __ingraph_row.#field = #aggregated::<#element, #db>(__ingraph_from, __ingraph_alias)?;
            ::core::result::Result::Ok(())
          }
        });
        entries.extend(quote! {
          #gate
          #edge_collection::aggregate(
            &[#field_name::new(#external)],
            #shape,
            #take::<#db>,
          ),
        });
        continue;
      }
      gathered_elements.push(element);
      let take_doc = super::leading(&format!(
        "Give every page row the `{external}` elements gathered for it — the plan's other half, \
         which names the four types and nothing else: `distribute` owns the grouping and the \
         collapse."
      ));
      crossings.extend(quote! {
        #gate
        #[doc = #take_doc]
        fn #take<#db>(
          __ingraph_page: &mut [#row],
          __ingraph_gathered: &[<#db as #database>::Row],
        ) -> ::core::result::Result<(), #sqlx_error>
        where
          #db: #database,
          #(#key_types: ::core::clone::Clone + ::core::cmp::Eq + ::core::hash::Hash,)*
          #(for<'__ingraph_r> #key_types: #decode<'__ingraph_r, #db> + #column_type<#db>,)*
          for<'__ingraph_r> #element: #decode<'__ingraph_r, #db> + #column_type<#db>,
          for<'__ingraph_a> &'__ingraph_a ::core::primitive::str:
            #column_index<<#db as #database>::Row>,
        {
          // The alias the ENGINE projected every element under, taken from the engine rather than
          // rebuilt — two spellings of one name are two things free to drift.
          let __ingraph_element: &::core::primitive::str =
            ::core::convert::AsRef::as_ref(#element_alias);
          #distribute(
            __ingraph_page,
            __ingraph_gathered,
            |__ingraph_row| (#(::core::clone::Clone::clone(&__ingraph_row.#key_fields),)*),
            |__ingraph_row| ::core::result::Result::Ok((
              #(#row_trait::try_get::<#key_types, _>(__ingraph_row, #key_names)?,)*
            )),
            |__ingraph_row| #row_trait::try_get::<#element, _>(__ingraph_row, __ingraph_element),
            |__ingraph_row| &mut __ingraph_row.#field,
          )
        }
      });
      entries.extend(quote! {
        #gate
        #edge_collection::gather(
          &[#field_name::new(#external)],
          #shape,
          #binder::<#db>,
          #take::<#db>,
        ),
      });
    }

    // Naming a crossing in the plan is USING it, so what each of them asks of the dialect is owed
    // here. Every predicate is the one the function beside it states, restated at the impl that
    // takes its pointer — which is what makes a dialect that cannot decode this row's key or its
    // elements a refusal at the call site rather than inside the expansion.
    //
    // They are split by MATERIALIZATION, because the two crossings ask for different things: a
    // gather reads the page's own key back off the gathered rows, where an aggregate reads one
    // array off the row the page already returned and never touches a key.
    let membership = gathers.then(|| {
      quote! {
        #(#key_types: ::core::clone::Clone + ::core::cmp::Eq + ::core::hash::Hash,)*
        #(#key_types: #carrier<#db>,)*
        #(for<'__ingraph_r> #key_types: #decode<'__ingraph_r, #db> + #column_type<#db>,)*
      }
    });
    let hydration = quote! {
      #membership
      #(for<'__ingraph_r> #gathered_elements: #decode<'__ingraph_r, #db> + #column_type<#db>,)*
      #(
        for<'__ingraph_r> ::core::option::Option<::std::vec::Vec<#aggregated_elements>>:
          #decode<'__ingraph_r, #db> + #column_type<#db>,
      )*
      for<'__ingraph_a> &'__ingraph_a ::core::primitive::str:
        #column_index<<#db as #database>::Row>,
    };
    let plan = quote! {
      const COLLECTIONS: &'static [#edge_collection<Self, #db>] = &[#entries];
    };
    (plan, crossings, hydration)
  }

  /// The PAGE's half of the binding: the term type, the cursor value, and the three functions one
  /// completed order drives.
  fn ordering(
    &self,
    model: &RecordModel,
    hydration: &proc_macro2::TokenStream,
  ) -> proc_macro2::TokenStream {
    let row = self.name();
    let record = &model.record;
    let cursor = self.cursor_name();
    let comparison = self.comparison_name();
    let db = super::parameter("DB");
    let ordering = model.framework(&["query", "sql"], "SqlOrdering");
    let vocabulary = model.framework(&["transform"], "Record");
    let complex = model.framework(&["comparison"], "ComplexComparison");
    let carrier = model.framework(&["comparison", "sql"], "Carrier");
    let key_in = model.framework(&["comparison", "sql"], "SqlKeyIn");
    let order_term = model.framework(&["cursor"], "OrderTerm");
    let optional = model.framework(&["project"], "Optional");
    let database = model.framework(&["sqlx"], "Database");
    let subjects = model.framework(&["comparison", "sql"], "TermColumns");
    let order_subjects = model.framework(&["comparison", "sql"], "OrderSubjects");
    let sqlx_error = model.framework(&["sqlx"], "Error");
    let assumptions = self.assumptions(model);
    let shaped = self.shaped(model);
    let order_by = model.order_by.safe();
    let term = self.kind().order_term();

    let row_trait = model.framework(&["sqlx"], "Row");
    // Whether ANY term of this order reads the raw driver row, which is what decides the two parameter
    // names below and the decode bound the impl owes. A record with no mirrored collection gets back
    // exactly the tokens it got before the companion existed.
    let projected = model.ordered_columns().iter().any(|(_, shared)| {
      self
        .stores(&shared.source)
        .is_some_and(|column| self.mirrors(model, column))
    });
    let (raw, alias) = if projected {
      (quote!(__ingraph_raw), quote!(__ingraph_alias))
    } else {
      (quote!(_), quote!(_))
    };
    // WHICH LEAF of the term's column this level compares. Every VALUE column reads it; a record
    // whose orderable columns are all collections has no arm that does, so the parameter takes the
    // same unnamed spelling the raw row does rather than an `allow` — the two are one discipline.
    let leafed = model.ordered_columns().iter().any(|(_, shared)| {
      self.stores(&shared.source).is_some_and(|column| {
        column.stored.is_none()
          && !self.mirrors(model, column)
          && !self.edge_stored(model, column)
          && !model.collects(&column.source)
      })
    });
    let leaf_param = if leafed {
      quote!(__ingraph_leaf)
    } else {
      quote!(_)
    };
    let bytes = sort_key_type();
    // What reading the companion off the driver's row COSTS, stated as an obligation rather than as
    // the predicate that discharges it — the discipline every other row of this `where` clause
    // follows. The `&str` INDEX it also needs is already owed through the collection plan's own
    // obligations: a mirrored column is edge-stored by construction, so the plan exists wherever this
    // is emitted, and restating the predicate would be one fact with two homes.
    let boundary = projected.then(|| {
      let decode = model.framework(&["sqlx"], "Decode");
      let column_type = model.framework(&["sqlx"], "Type");
      quote! {
        for<'__ingraph_r> #bytes: #decode<'__ingraph_r, #db> + #column_type<#db>,
      }
    });
    let values = model.ordered_columns().into_iter().map(|(_, shared)| {
      let variant = shared.order_variant();
      // The CONDITION, on every arm: the order-by variant this arm matches carries the same gate, so
      // an arm without it would name a variant the build removed.
      let gate = model.gate(&shared.source);
      // A column THIS DATABASE has not got still has a VARIANT, the vocabulary being the
      // DECLARATION's, so the match needs an arm for it — and the row holds no value to answer with.
      // The arm is reached by nobody: an order naming such a term is refused whole at
      // `SqlOrder::new`, by name, before a row is read. `None` for the reason the edge-stored arm
      // below gives: the honest reading of *this row has no cursor value here* is the absence.
      let Some(column) = self.stores(&shared.source) else {
        return quote! {
          #gate
          #order_by::#variant(_) => ::core::result::Result::Ok(::core::option::Option::None),
        };
      };
      let field = column.name.safe();
      // A MIRRORED collection's boundary is the COMPANION COLUMN's own bytes, and they come off the
      // RAW driver row under the alias the engine projected them: `sorts` puts
      // `"__ig_<field>_sort__" AS "__ig_ord<n>__"` on the page's SELECT list, exactly as it does an
      // expression term's value. `self.#field` is the same collection and is NOT read — it arrives
      // from the gather, a SECOND statement, so a boundary taken from it would be a boundary the
      // `ORDER BY` never produced. The frozen-boundary law, at the one term where the two readings
      // are both to hand.
      if self.mirrors(model, column) {
        return quote! {
          #gate
          #order_by::#variant(_) => ::core::result::Result::map(
            #row_trait::try_get::<#bytes, _>(__ingraph_raw, __ingraph_alias),
            |__ingraph_key| ::core::option::Option::Some(#cursor::#variant(__ingraph_key)),
          ),
        };
      }
      // An EDGE-STORED collection with NO companion is an order subject and is NOT a cursor slot, so
      // the sum has no
      // variant to build. The arm is reached by nobody: a page over such a term is refused at
      // `OrderPartition::paging` before a row is read, and the ordered scan that may carry one
      // projects no sort values at all. `None` rather than a panic, because the honest reading of
      // *this row has no cursor value here* is the absence — see `Self::paged_columns` for why the
      // two vocabularies differ.
      if self.edge_stored(model, column) {
        return quote! {
          #gate
          #order_by::#variant(_) => ::core::result::Result::Ok(::core::option::Option::None),
        };
      }
      // An ARRAY-STORED one IS a slot, and it holds the whole list — the row's own field, which is
      // what `cursor_type` names. It takes the present arm whatever the declaration wrote around it:
      // a collection has no null state, so the EMPTY list is its absence and there is no `Option`
      // for `Optional::as_option` to open.
      if model.collects(&column.source) {
        return quote! {
          #gate
          #order_by::#variant(_) => ::core::result::Result::Ok(::core::option::Option::Some(
            #cursor::#variant(::core::clone::Clone::clone(&self.#field)),
          )),
        };
      }
      // The LEAF this level compares, read through the same map the slot's type came from — so the
      // value a row answers with and the type the slot holds are one projection rather than two that
      // agree. A flat reading hands back the field itself at leaf `0`, which is exactly the clone
      // this arm used to write; a citizen hands back one leaf of it, recomputing a derived one.
      if column.nullable {
        let leaf = self.leaf_value(model, column, quote!(__ingraph_value));
        return quote! {
          #gate
          #order_by::#variant(_) => ::core::result::Result::Ok(::core::option::Option::map(
            ::core::option::Option::and_then(
              #optional::as_option(&self.#field),
              |__ingraph_value| #leaf,
            ),
            #cursor::#variant,
          )),
        };
      }
      let leaf = self.leaf_value(model, column, quote!(&self.#field));
      quote! {
        #gate
        #order_by::#variant(_) => ::core::result::Result::Ok(::core::option::Option::map(
          #leaf,
          #cursor::#variant,
        )),
      }
    });
    let value_doc = super::leading(
      "The value this row holds at `order`'s column at LEVEL `leaf`, or `None` where it holds SQL \
       `NULL` — a citizen that states a semantic sequence runs as one level per leaf and is asked \
       once for each, through its own `OrderLeaves` vocabulary, while every other column has one \
       level and answers with its field. A DERIVED leaf is recomputed at this call rather than \
       carried, which is what keeps a boundary the value the statement sorted by. It is also `None` \
       at an \
       EDGE-STORED collection term with no companion, which is an order subject and not a cursor \
       slot, so a page over one is refused before this is asked. An ARRAY-STORED collection IS a \
       slot and answers with the whole list. A MIRRORED one answers with its COMPANION COLUMN's \
       bytes, read off the RAW driver row under the alias the engine projected them: the statement \
       ordered by the companion, so the boundary a page resumes at is what the statement compared, \
       and never the sort key of the collection the gather put on this row afterwards. Every other \
       term of this order is a COLUMN of the row, so the decoded row answers it and neither the raw \
       row nor the alias is read.",
    );
    let subjects_doc =
      super::leading("What each term of this order COMPARES: its own column, at every term.");

    quote! {
      #[automatically_derived]
      impl<#db> #ordering<#db> for #row
      where
        #db: #database,
        #assumptions
        #record: #vocabulary<#db, Comparison: #complex<#db>>,
        #comparison<#db>: #complex<#db>,
        #cursor: #carrier<#db>,
        // The same width the binding above states, and it has to be the same: this trait's
        // supertrait is that impl, so a different one would name an `Address` the row has not got.
        #key_in<#cursor, #db, 1>: #complex<#db>,
        // What this row's SUBJECTS cost, stated as an obligation rather than as the predicate that
        // discharges it — the discipline every other row of this `where` clause follows. It is what
        // a rendered COLUMN has always cost, moved to the party that renders one.
        #subjects: #order_subjects<#db>,
        // What a COMPANION boundary costs, where this row has one — see above.
        #boundary
        // `SqlQuery` is this trait's SUPERTRAIT, so whatever the plan's crossings ask of the dialect
        // is owed here as well — a page over a row that hydrates has to be able to prove the row is
        // queryable at all, and that includes every column's own shape.
        #hydration
        #shaped
      {
        type Order = #order_by;
        type Value = #cursor;
        type Subjects = #subjects;

        #[inline]
        fn complete(written: &[#order_by]) -> ::std::vec::Vec<#order_by> {
          #order_by::complete(written)
        }

        #[inline]
        fn term(order: #order_by) -> #order_term {
          #order_by::#term(order)
        }

        #[doc = #subjects_doc]
        #[inline]
        fn subjects(_: &[#order_by]) -> #subjects {
          #subjects
        }

        #[doc = #value_doc]
        fn value(
          &self,
          order: #order_by,
          #leaf_param: ::core::primitive::usize,
          #raw: &<#db as #database>::Row,
          #alias: &::core::primitive::str,
        ) -> ::core::result::Result<::core::option::Option<#cursor>, #sqlx_error> {
          match order {
            #(#values)*
          }
        }
      }
    }
  }

  /// The typed face a caller writes: `find_<db>`, its snapshot twin, and `get_<db>`.
  ///
  /// # The row is FIXED here, and that is the whole of what these buy
  ///
  /// Each entry point names this database's row so a caller never does: `Media::find_sqlite(&pool)`
  /// picks which column names are rendered, and the DIALECT is still inferred from the pool that
  /// was passed. An expansion may not spell `sqlx::Sqlite`, so the method NAME is where the
  /// database is chosen and the type parameter is where the driver is.
  ///
  /// # `get` takes the ID, because the ID is the address
  ///
  /// The parameter and the address used to be the whole `*Key` together, then the address collapsed
  /// to one column — see the binding's `ADDRESS` above — and the parameter followed it here. A
  /// caller hands over one value and the statement reads one column, so there is no longer a
  /// lineage handed over that nothing reads. The `*Key` is unnarrowed by that: it is what a search
  /// hit and a record's own `key()` still carry, which is the whole chain.
  ///
  /// # There is no snapshot twin of it
  ///
  /// One statement is atomic without help, and `get` is one statement. The snapshot exists for a
  /// call whose statements are several — which is what a materialization pass makes of a page — so
  /// a `get_<db>_snapshot` would be a promise with nothing to keep.
  ///
  /// # `insert_<db>` and `upsert_<db>` take the RECORD, and there is no transaction knob on either
  ///
  /// The crossing into the row is the lane's — [`SqlWrite::row`], the dual of the read's
  /// `SqlQuery::record` — so a caller hands over the domain value and never the row, and every bind
  /// goes through the declaration's own write legs. There is no `insert_<db>_transaction` beside
  /// them for the read side's reason inverted: the bracket is not a MODE a caller chooses but a
  /// consequence of the record's shape, and a caller who wants several writes inside one opens it
  /// and passes it, which the lane sees through `BeginWrite` and passes through.
  ///
  /// # `delete_<db>` and `delete_<db>_where` are TWO doors, because a removal has to be told what it
  /// means
  ///
  /// A store verb is handed a record, so it needs no way to say which rows it is about. A removal
  /// does, and the roster already has the two shapes a caller can know that in: `get_<db>` holds the
  /// ID, `find_<db>` holds the PREDICATE. So the removal half mirrors the read half rather than the
  /// write half — and inherits both of its narrowings, the id door answering `bool` where `get`
  /// answers `Option` and the filter door answering a COUNT where `find` answers a `Vec`, on the one
  /// law that the id is `UNIQUE`.
  ///
  /// The FILTER door is the re-index road, and the reason it cannot be spelled with the other four:
  /// a source that produced fourteen rows and now produces nine leaves five behind, and *what it
  /// used to produce* is a set nobody holds. A record is not enough to say it and neither is an id.
  fn entry_points(&self, model: &RecordModel) -> proc_macro2::TokenStream {
    let vis = &model.vis;
    let record = &model.record;
    let row = self.name();
    let kind = self.kind();
    let db = super::parameter("DB");
    let executor = super::parameter("EXEC");

    let find_ty = model.framework(&["query", "sql"], "Find");
    let query = model.framework(&["query", "sql"], "SqlQuery");
    let dialect = model.framework(&["query", "sql"], "SqlDialect");
    let snapshot_trait = model.framework(&["query", "sql"], "ReadSnapshot");
    let error = model.framework(&["query", "sql"], "SqlQueryError");
    let get = model.framework(&["query", "sql"], "get");
    let identifiable = model.framework(&["transform"], "Identifiable");
    let backend = model.framework(&["comparison"], "Backend");
    let acquire = model.framework(&["sqlx"], "Acquire");
    let from_row = model.framework(&["sqlx"], "FromRow");
    let sqlx_executor = model.framework(&["sqlx"], "Executor");
    let into_arguments = model.framework(&["sqlx"], "IntoArguments");
    let database = model.framework(&["sqlx"], "Database");

    let write = model.framework(&["query", "sql"], "SqlWrite");
    let write_error = model.framework(&["query", "sql"], "SqlWriteError");
    let write_transaction = model.framework(&["query", "sql"], "WriteTransaction");
    let begin_write = model.framework(&["query", "sql"], "BeginWrite");
    let upsert_clause = model.framework(&["query", "sql"], "Upsert");
    let affected = model.framework(&["query", "sql"], "Affected");
    let insert = model.framework(&["query", "sql"], "insert");
    let upsert = model.framework(&["query", "sql"], "upsert");
    let delete = model.framework(&["query", "sql"], "delete");
    let delete_where = model.framework(&["query", "sql"], "delete_where");
    let vocabulary = model.framework(&["transform"], "Record");
    let complex = model.framework(&["comparison"], "ComplexComparison");
    let carrier = model.framework(&["comparison", "sql"], "Carrier");

    let (find, snapshot, get_name) = (kind.finder(), kind.snapshot_finder(), kind.getter());
    let (insert_name, upsert_name) = (kind.inserter(), kind.upserter());
    let (delete_name, purge_name) = (kind.deleter(), kind.purger());
    let insert_doc = super::leading(&format!(
      "Store this [`{record}`] in {} as a NEW row.\n\nAn address that already holds one is the \
       dialect's own constraint violation, carried rather than translated — a caller that means \
       *store this whatever was there* has [`{upsert_name}`](Self::{upsert_name}) and does not have \
       to read an error to get it. The record crosses to its row through the declaration's own \
       write legs, and a record whose collections are edge-stored is written in ONE transaction \
       with them.",
      kind.as_str()
    ));
    let upsert_doc = super::leading(&format!(
      "Store this [`{record}`] in {} at its address, REPLACING whatever was there.\n\nThe row is the \
       dialect's keyed replace and every edge-stored collection is replaced as a SET — the old rows \
       removed, the new ones written with the new collection's own ordinals, in the same \
       transaction as the row. A collection that arrives shorter comes back shorter: the value \
       handed over is the whole of it.",
      kind.as_str()
    ));
    let find_doc = super::leading(&format!(
      "Query the [`{record}`]s stored in {} — the unordered lanes, the row ceiling, and the ordered \
       page.",
      kind.as_str()
    ));
    let snapshot_doc = super::leading(&format!(
      "[`{find}`](Self::{find}) inside a read transaction this dialect opens, so every statement of \
       the call sees one state of the database."
    ));
    let get_doc = super::leading(&format!(
      "The [`{record}`] at `id` in {}, or `None` where no row lives there — the miss is `Ok(None)` \
       on every path. The id is the whole address: it is `UNIQUE`, so it names at most one row, and \
       the lineage a [`{key}`] carries is stored beside it rather than looked up with it.",
      kind.as_str(),
      key = model.key.name,
    ));
    let delete_doc = super::leading(&format!(
      "Remove the [`{record}`] at `id` from {}, and everything stored FOR it — `true` where a row \
       was there.\n\nThe id is the whole address, as it is for \
       [`{get_name}`](Self::{get_name}), so the answer is a yes-or-no rather than a count. Every \
       edge-stored collection's rows and every provenance row go with it, in ONE transaction, by \
       statements this lane writes rather than by a cascade the schema does not declare. A miss is \
       `Ok(false)` and never an error.",
      kind.as_str()
    ));
    let purge_doc = super::leading(&format!(
      "Remove every [`{record}`] in {} that `filter` names, and everything stored for each of them \
       — answering with how many RECORDS went.\n\nThis is the RE-INDEX road: a source that produced \
       fourteen rows and now produces nine leaves five behind, and *what it used to produce* is a \
       set nobody holds — the predicate those rows are under is what a caller has. The filter is \
       REQUIRED, and one that lowers to no predicate at all is refused with \
       `SqlWriteError::Unscoped` before anything runs, rather than emptying the table.",
      kind.as_str()
    ));
    // THE FIVE DOORS THAT CROSS TO A DATABASE, written twice — once with a span around the call
    // and once without — with the `if_tracing!` pair discarding whichever half this build of
    // `ingraph` did not compile. See `observed` for why the two exist rather than one carrying a
    // `cfg_attr`, and `entries` for what the duplication is over.
    let gate = model.framework(&["gate"], "if_tracing");
    let ungated = model.framework(&["gate"], "if_no_tracing");
    let entries = |observed: bool| {
      let get_body = self.observed(
        model,
        observed,
        "get",
        quote!(#get::<#row, #db, #executor>(executor, id, false)),
      );
      let insert_body = self.observed(
        model,
        observed,
        "insert",
        quote!(#insert::<#row, #db, #executor>(executor, record)),
      );
      let upsert_body = self.observed(
        model,
        observed,
        "upsert",
        quote!(#upsert::<#row, #db, #executor>(executor, record)),
      );
      let delete_body = self.observed(
        model,
        observed,
        "delete",
        quote!(#delete::<#row, #db, #executor>(executor, id)),
      );
      let purge_body = self.observed(
        model,
        observed,
        "delete_where",
        quote!(#delete_where::<#row, #db, #executor>(executor, filter)),
      );
      quote! {
        impl #record {
          #[doc = #get_doc]
          #vis async fn #get_name<'c, #db, #executor>(
            executor: #executor,
            id: &<#record as #identifiable>::Id,
          ) -> ::core::result::Result<::core::option::Option<#record>, #error>
          where
            #db: #dialect,
            #row: #query<#db, Record = #record> + for<'r> #from_row<'r, <#db as #database>::Row>,
            for<'e> &'e mut <#db as #database>::Connection:
              #sqlx_executor<'e, Database = #db>,
            <#db as #database>::Arguments: #into_arguments<#db>,
            #executor: #acquire<'c, Database = #db>,
          {
            #get_body
          }

          #[doc = #insert_doc]
          #vis async fn #insert_name<'c, #db, #executor>(
            executor: #executor,
            record: #record,
          ) -> ::core::result::Result<(), #write_error>
          where
            #db: #dialect + #write_transaction,
            #row: #write<#db, Record = #record>,
            // The ORDINAL every edge row carries, stated as the obligation the lane spends rather
            // than as the carrier row that discharges it — which every shipped dialect has.
            ::core::primitive::i64: #carrier<#db>,
            for<'e> &'e mut <#db as #database>::Connection:
              #sqlx_executor<'e, Database = #db>,
            <#db as #database>::Arguments: #into_arguments<#db>,
            #executor: #acquire<'c, Database = #db> + #begin_write,
          {
            #insert_body
          }

          #[doc = #upsert_doc]
          #vis async fn #upsert_name<'c, #db, #executor>(
            executor: #executor,
            record: #record,
          ) -> ::core::result::Result<(), #write_error>
          where
            // One predicate more than the insert beside it, and it is the whole of the difference: a
            // keyed replace is a clause the dialect spells and a plain write renders none.
            #db: #dialect + #write_transaction + #upsert_clause,
            #row: #write<#db, Record = #record>,
            ::core::primitive::i64: #carrier<#db>,
            for<'e> &'e mut <#db as #database>::Connection:
              #sqlx_executor<'e, Database = #db>,
            <#db as #database>::Arguments: #into_arguments<#db>,
            #executor: #acquire<'c, Database = #db> + #begin_write,
          {
            #upsert_body
          }

          #[doc = #delete_doc]
          #vis async fn #delete_name<'c, #db, #executor>(
            executor: #executor,
            id: &<#record as #identifiable>::Id,
          ) -> ::core::result::Result<::core::primitive::bool, #write_error>
          where
            // `Affected` where the store verbs take `Carrier<i64>`, and the swap is what the two
            // halves respectively need: a store BINDS an ordinal per edge row, and a removal binds
            // none and reads a COUNT back. Neither predicate is in `SqlDialect`'s bundle, for the
            // reason that bundle's own note gives.
            #db: #dialect + #write_transaction + #affected,
            #row: #write<#db, Record = #record>,
            for<'e> &'e mut <#db as #database>::Connection:
              #sqlx_executor<'e, Database = #db>,
            <#db as #database>::Arguments: #into_arguments<#db>,
            #executor: #acquire<'c, Database = #db> + #begin_write,
          {
            #delete_body
          }

          #[doc = #purge_doc]
          #vis async fn #purge_name<'c, #db, #executor>(
            executor: #executor,
            // The RECORD's own comparison, read off the vocabulary binding exactly as the read
            // lane's `.filter(…)` reads it — so a caller checks a predicate with `find` and removes
            // with the same value, rather than writing a second one that agrees today.
            filter: &<#record as #vocabulary<#db>>::Comparison,
          ) -> ::core::result::Result<::core::primitive::u64, #write_error>
          where
            #db: #dialect + #write_transaction + #affected,
            #row: #write<#db, Record = #record>,
            // STATED rather than left to elaboration, and the projection in the signature is why:
            // `SqlQuery`'s own `Record` item carries this bound, so a solver reasoning from
            // `#row: SqlWrite<#db, Record = #record>` has it — but the ARGUMENT TYPE is
            // `<#record as Record<#db>>::Comparison`, which has to resolve where the signature is
            // written rather than where a body proves things. Without the line every declaration is
            // `E0277: Record<__INGRAPH_DB__> is not satisfied`, reported at the `#[record(…)]`.
            #record: #vocabulary<#db, Comparison: #complex<#db>>,
            for<'e> &'e mut <#db as #database>::Connection:
              #sqlx_executor<'e, Database = #db>,
            <#db as #database>::Arguments: #into_arguments<#db>,
            #executor: #acquire<'c, Database = #db> + #begin_write,
          {
            #purge_body
          }
        }
      }
    };
    let watched = entries(true);
    let plain = entries(false);
    quote! {
      impl #record {
        #[doc = #find_doc]
        #[inline]
        #vis fn #find<'a, #db, #executor>(
          executor: #executor,
        ) -> #find_ty<'a, #row, #db, #executor>
        where
          // `sqlx::Database` beside the backend, because a query's binding names the dialect's own
          // ROW: a record's collections are MATERIALIZED through it, and the plan stating how each
          // is materialized is an item of the engine's trait.
          #db: #backend + #database,
          #row: #query<#db>,
        {
          #find_ty::new(executor, false)
        }

        #[doc = #snapshot_doc]
        #[inline]
        #vis fn #snapshot<'a, #db, #executor>(
          executor: #executor,
        ) -> #find_ty<'a, #row, #db, #executor>
        where
          #db: #backend + #database + #snapshot_trait,
          #row: #query<#db>,
        {
          #find_ty::new(executor, true)
        }
      }

      #gate! { #watched }
      #ungated! { #plain }
    }
  }

  /// One entry's BODY, with a span around it or without — the G6 instrument clause.
  ///
  /// # Why the entry is written twice rather than carrying an attribute
  ///
  /// `#[instrument]` cannot be reached from here at all, and the reason is `sqlx`'s rather than
  /// async-graphql's: `tracing-attributes` 0.1 declares no crate-path key, and its expansion writes
  /// `::tracing::span!`, `::tracing::event!` and `::tracing::field::debug` ABSOLUTELY — fourteen
  /// such templates. Those paths resolve in the DECLARING crate, which names no tracing. So the span
  /// is opened by hand through the `macro_rules!` family, whose `$crate` follows the definition
  /// rather than the invocation and therefore lands on the shelf whatever path reached it.
  ///
  /// A `#[cfg_attr(feature = "tracing", …)]` would not help either, and for the reason every gate in
  /// this emitter exists: that predicate asks whether the DECLARING crate has a feature by that
  /// name. So the two halves are written out and `if_tracing!`/`if_no_tracing!` keep exactly one —
  /// the shape the options spine already uses for its `Deserialize`, and for the same reason: an
  /// attribute cannot be added by a macro that expands to nothing.
  ///
  /// # The LEVEL is a constant here, and that is the one place it can be
  ///
  /// `span!` builds its metadata in a `static`, so the level has to be const-evaluable. At expansion
  /// time it IS one — the declaration's word, or `Info` where it wrote none — so the emitted call
  /// names one level and the runtime's own spans, which cannot know a declaration at compile time,
  /// are the half that pays for a match. One knob, two costs, and this is the cheap side.
  ///
  /// # The write lane is instrumented too
  ///
  /// `insert`, `upsert` and both removals are entries of THIS module, which is the query face, and
  /// each crosses to a database exactly as `get` does. Instrumenting some of one module's doors and
  /// not the rest would need a rule nobody has written; a reader filters by the `entry` field, which
  /// is what it is for.
  fn observed(
    &self,
    model: &RecordModel,
    observed: bool,
    entry: &str,
    call: proc_macro2::TokenStream,
  ) -> proc_macro2::TokenStream {
    if !observed {
      return quote!(#call.await);
    }
    let instrument = model.framework(&["tracing"], "Instrument");
    let span = model.framework(&["tracing"], "span");
    let level = model.framework(&["tracing"], "Level");
    let constant = model.tracing.unwrap_or(TracingLevel::Info).constant();
    let record = model.record.to_string();
    let database = self.kind().as_str();
    quote! {
      {
        use #instrument as _;
        #call
          .instrument(#span!(
            #level::#constant,
            "ingraph.query",
            record = #record,
            entry = #entry,
            db = #database,
          ))
          .await
      }
    }
  }
}

/// The POSITIONS a list of columns occupies once the compiler has answered their predicates — one
/// `const` per column, each the previous plus that column's own presence.
///
/// # A count is not a thing a macro may know
///
/// Every ordinal this emission writes is an index into a list the predicates CONTRACT:
/// `SqlQuery::COLUMNS` is an array whose elements each carry their column's `#[cfg]`, so a build
/// that removes the second column makes the third's position `1`. An expansion that had written `2`
/// there would be naming 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 column 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 the same expansion serves every
/// configuration and K conditional columns cost K constants rather than 2ᴷ expansions.
///
/// The names are the emission's own and are scoped to whatever block they are written into; the
/// index in the name is the DECLARATION's position, which is stable, and never the runtime one.
///
/// A list with NO conditional column 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.
///
/// The ARITHMETIC is [`crate::emit::positions`]'s, and this is the record's own lookup in front of
/// it: the fragment tier's segment list runs the identical sum over a list its own predicates
/// contract, and a second copy of a running sum is how one of them comes to start at the wrong
/// index.
fn positions(
  model: &RecordModel,
  columns: &[&PersistColumn],
) -> (proc_macro2::TokenStream, Vec<proc_macro2::TokenStream>) {
  let declared: Vec<Option<&crate::model::Condition>> = columns
    .iter()
    .map(|column| model.condition(&column.source))
    .collect();
  super::positions(&declared)
}