ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
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
//! The statement each lane renders, over a record whose bindings are written BY HAND.
//!
//! # Why the fixture is hand-written, and what that buys twice
//!
//! `ingraph-codegen` cannot reach this crate, so a test here cannot be an expansion. What it can be
//! is the same thing a third party writes: a record, its row, its order-by and its cursor value,
//! bound to the engine through nothing but the two public traits. So the fixture is the
//! THIRD-PARTY-IMPLEMENTOR proof as well as the rendering harness — everything the engine asks of a
//! declaration is asked of this file too, and a seam that could only be satisfied from inside the
//! emitter would not compile here.
//!
//! # What is asserted here, and what cannot be
//!
//! The TEXT of the statement: which columns, which table, which predicates, which order, and
//! whether a clause is present at all. That is what this layer produces.
//!
//! The page's own correctness is NOT visible in the text and is deliberately not attempted. A
//! `LIMIT` binds its number rather than spelling it, so *one row more than the page holds* does not
//! appear in the statement a reader can see; and a keyset that skips a row is valid SQL that
//! answers without an error. Both are measured against real engines, and the module note beside
//! [`SqlKeyset`](crate::comparison::sql::SqlKeyset) records the same split for the same reason.
//!
//! # One lane of this file DOES execute, and it is the one whose text says nothing
//!
//! A materialized collection is the case where the statement and the answer are furthest apart: a
//! gather that never runs, one correlated to the wrong parent, and one whose order lost the ordinal
//! all render SQL a reader would pass. So the collection walk at the end runs against a real
//! in-memory SQLite — a bare [`SqliteConnection`](sqlx::sqlite::SqliteConnection) and never a
//! `Pool`, because this crate enables no sqlx runtime and constructing a pool would panic asking
//! for one.
#![cfg(feature = "sqlite")]

use sqlx::Sqlite;

use super::{Find, Ordering, Position, SortValues, address, ordered, scan};
use crate::{
  Carrier, ColumnName, ColumnShape, ComplexComparison, Cursor, CursorValue, FieldName,
  Identifiable, OrderDirection, OrderTerm, Record, RecordAddress, ScalarFilter, TermName,
  Transformer, Walk,
  comparison::{
    At, Backend, Frame, TryFromFilter,
    sql::{
      OrderSubjects, SqlKeyIn, SqlKeyset, SqlLoweringError, SqlOrder, SqlScalarComparison,
      TermColumns,
    },
  },
  query::{
    DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE,
    sql::{
      CrossingError, ELEMENT, EdgeCollection, EdgeShape, SqlOrdering, SqlQuery, distribute,
      hydrate::gathers,
    },
  },
};

/// A clip inside a media: a two-column key, a text column, a NULLABLE sort column — which is what
/// makes the ordering exercise the null position rather than skipping past it — and a COLLECTION
/// kept in an edge table, which is what makes it exercise materialization.
///
/// # The two-column KEY is the CAPABILITY PIN, and it stays — the ADDRESS is the id
///
/// The engine face takes the id: `SqlQuery::address` is handed a `<Clip as Identifiable>::Id` and
/// nothing else, so one column is what any row of any layout is addressed by and the `UNIQUE` law
/// is what makes that name at most one row. This fixture's `id` is unique across the table for
/// exactly that reason, and its DDL says so.
///
/// What stays wide here is everything the key still IS. `ClipKey` carries the lineage and the id
/// together, the `ADDRESS` const names both columns, and the completed order ends in both — so the
/// multi-column gather correlation and the N-slot cursor tail run on every test run, which is where
/// they would otherwise rot. The row-value `IN` above width one keeps its callers in
/// [`SqlKeyIn`](crate::comparison::sql::SqlKeyIn)'s own tests and in the gather this module renders;
/// what no longer reaches it is an ADDRESS, at this fixture as in every expansion.
///
/// A layout whose rows really are named by several columns states that as a COMPOSITE `Id` — the
/// capability moved from the key to the id rather than being retired, which is what keeps the seam
/// open to a physical layout the framework did not emit.
#[derive(Debug, Clone, PartialEq)]
struct Clip {
  media: i64,
  id: i64,
  title: String,
  score: Option<f64>,
  /// A SEQUENCE, stored in `clip_tags` as `(media_id, id, tags_ordinal, tags)`.
  tags: Vec<String>,
  /// A SET, stored in `clip_notes` as `(media_id, id, notes)` — no ordinal, because a set's rows
  /// are unique and its order is absent.
  notes: Vec<String>,
}

/// The key, `lineage ⊕ id` — the OUTPUT vocabulary a record hands over, no longer the address.
#[derive(Debug, Clone, PartialEq, Eq)]
struct ClipKey {
  media: i64,
  id: i64,
}

impl Identifiable for Clip {
  type Id = i64;

  fn id_ref(&self) -> &i64 {
    &self.id
  }
}

impl Transformer for Clip {
  type Key = ClipKey;
  type Lineage = i64;
  type Record = Self;
  // The PERSIST-ONLY shape, and this fixture is the one that has it. Nothing exposes a clip on a
  // wire, so there is no filter type a client could send one in — `ClipFilter` below is the LOWERED
  // comparison, generic in the database and bound at `Record::Comparison`, which is the other half
  // of that split.
  type Graphql = ();

  fn key(&self) -> ClipKey {
    ClipKey {
      media: self.media,
      id: self.id,
    }
  }
}

/// The other half of the persist-only shape: a clip IS stored, so it has an order, and the term
/// type is the one `SqlOrdering` binds — the same enum read from the entity's side rather than a
/// second vocabulary beside it.
/// The stored row — the four scalar columns under the names this database spells them, and the
/// collection the engine materializes onto it.
///
/// `tags` is a field of the row and is NOT in [`SqlQuery::COLUMNS`], which is the plan's contract:
/// the elements live in a second table, so there is no column of `clip` to select for it.
#[derive(Debug, Clone, PartialEq)]
struct ClipRow {
  media: i64,
  id: i64,
  title: String,
  score: Option<f64>,
  tags: Vec<String>,
  notes: Vec<String>,
}

/// The row as one page statement's row decodes — every scalar read by name, and the collection
/// EMPTY.
///
/// The empty collection is the whole of the decode's part in the collapse: materialization only
/// appends, so a parent with no elements ends holding exactly what this wrote.
impl<'r, R> sqlx::FromRow<'r, R> for ClipRow
where
  R: sqlx::Row,
  i64: sqlx::Decode<'r, R::Database> + sqlx::Type<R::Database>,
  String: sqlx::Decode<'r, R::Database> + sqlx::Type<R::Database>,
  f64: sqlx::Decode<'r, R::Database> + sqlx::Type<R::Database>,
  for<'a> &'a str: sqlx::ColumnIndex<R>,
{
  fn from_row(row: &'r R) -> Result<Self, sqlx::Error> {
    Ok(Self {
      media: row.try_get("media_id")?,
      id: row.try_get("id")?,
      title: row.try_get("title")?,
      score: row.try_get("score")?,
      tags: Vec::new(),
      notes: Vec::new(),
    })
  }
}

/// Bind one of this row's key columns, in the order [`SqlQuery::ADDRESS`] names them — the plan's
/// half of the gather's membership, where the engine writes every bracket around it.
fn clip_key<Db>(row: &ClipRow, index: usize, qb: &mut sqlx::QueryBuilder<Db>)
where
  Db: sqlx::Database,
  i64: Carrier<Db>,
{
  match index {
    0 => row.media.push_bind(qb),
    _ => row.id.push_bind(qb),
  }
}

/// Give every page row the tags gathered for it — the plan's other half, which is a name for the
/// four types and nothing else: [`distribute`] owns the grouping and the collapse.
fn clip_tags<Db>(page: &mut [ClipRow], gathered: &[Db::Row]) -> Result<(), sqlx::Error>
where
  Db: sqlx::Database,
  for<'r> i64: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'r> String: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
{
  use sqlx::Row as _;
  let element: &str = ELEMENT;
  distribute(
    page,
    gathered,
    |row| (row.media, row.id),
    |row| Ok((row.try_get("media_id")?, row.try_get("id")?)),
    |row| row.try_get::<String, _>(element),
    |row| &mut row.tags,
  )
}

/// The same for the SET, whose gather differs only in what the engine ordered it by — a set's edge
/// table carries no ordinal, so its own primary key `(key…, value)` is its canonical order.
fn clip_notes<Db>(page: &mut [ClipRow], gathered: &[Db::Row]) -> Result<(), sqlx::Error>
where
  Db: sqlx::Database,
  for<'r> i64: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'r> String: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
{
  use sqlx::Row as _;
  let element: &str = ELEMENT;
  distribute(
    page,
    gathered,
    |row| (row.media, row.id),
    |row| Ok((row.try_get("media_id")?, row.try_get("id")?)),
    |row| row.try_get::<String, _>(element),
    |row| &mut row.notes,
  )
}

/// One ordering term: which column, and which way it runs. The shape an emitted `<E>OrderBy` takes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ClipOrder {
  Media(OrderDirection),
  Id(OrderDirection),
  Title(OrderDirection),
  Score(OrderDirection),
}

/// One cursor slot: the record's own sum over its orderable columns, which is what makes a
/// heterogeneous order expressible in one `Cursor<V>`.
#[derive(Debug, Clone, PartialEq)]
enum ClipValue {
  Media(i64),
  Id(i64),
  Title(String),
  Score(f64),
}

/// The tag says WHICH column, so a slot read back is the column it was written from rather than
/// whichever type happened to parse its bytes.
impl CursorValue for ClipValue {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    match self {
      Self::Media(value) => {
        out.push(0);
        value.write_cursor(out);
      }
      Self::Id(value) => {
        out.push(1);
        value.write_cursor(out);
      }
      Self::Title(value) => {
        out.push(2);
        value.write_cursor(out);
      }
      Self::Score(value) => {
        out.push(3);
        value.write_cursor(out);
      }
    }
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let (tag, rest) = bytes.split_first()?;
    match tag {
      0 => i64::read_cursor(rest).map(Self::Media),
      1 => i64::read_cursor(rest).map(Self::Id),
      2 => String::read_cursor(rest).map(Self::Title),
      3 => f64::read_cursor(rest).map(Self::Score),
      _ => None,
    }
  }
}

impl<Db> Carrier<Db> for ClipValue
where
  Db: sqlx::Database,
  i64: Carrier<Db>,
  String: Carrier<Db>,
  f64: Carrier<Db>,
{
  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    match self {
      Self::Media(value) | Self::Id(value) => value.push_bind(qb),
      Self::Title(value) => value.push_bind(qb),
      Self::Score(value) => value.push_bind(qb),
    }
  }
}

/// The record's filter, lowered — one predicate over one column, pushing its own frame exactly as
/// an emitted comparison does.
struct ClipFilter<Db> {
  title: SqlScalarComparison<String, Db>,
}

impl<Db> ComplexComparison<Db> for ClipFilter<Db>
where
  Db: Backend<Error = SqlLoweringError>,
  SqlScalarComparison<String, Db>: ComplexComparison<Db>,
{
  fn conjuncts(&self) -> usize {
    ComplexComparison::<Db>::conjuncts(&self.title)
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: <Db as Backend>::Builder<'q>,
  ) -> Result<<Db as Backend>::Builder<'q>, <Db as Backend>::Error> {
    let frame = At::frame(at, FieldName::new("title"));
    ComplexComparison::<Db>::apply(&self.title, Frame::at(&frame), builder)
  }
}

/// The RECORD's own vocabulary binding, which is where a comparison lives now — one impl per
/// database, as an expansion emits one per DECLARED database. Generic in `Db` here because this
/// fixture's comparison is, and because a hand-written record may bind whatever it can prove; what
/// the emitter writes instead is one CONCRETE backend apiece, which is what makes its version an
/// audit.
impl<Db> Record<Db> for Clip
where
  Db: Backend,
  ClipFilter<Db>: ComplexComparison<Db>,
{
  // ONE row at every database here, where an expansion binds each database's own: this fixture
  // stores one shape and a declaration may store three, and the member is per backend either way.
  type Row = ClipRow;
  type Comparison = ClipFilter<Db>;
  type OrderBy = ClipOrder;
}

impl<Db> SqlQuery<Db> for ClipRow
where
  Db: Backend + sqlx::Database,
  ClipFilter<Db>: ComplexComparison<Db>,
  SqlKeyIn<ClipValue, Db, 1>: ComplexComparison<Db>,
  i64: Carrier<Db>,
  for<'r> i64: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'r> String: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
{
  type Record = Clip;
  type Address = SqlKeyIn<ClipValue, Db, 1>;

  /// TWO columns, where [`Self::Address`] binds one: this const is what an edge table CORRELATES
  /// on, and this layout's edge tables lead with the whole key. The address is the id, by the
  /// `UNIQUE` law the DDL below states.
  const ADDRESS: RecordAddress = RecordAddress::new(
    FieldName::new("clip"),
    &[FieldName::new("media_id"), FieldName::new("id")],
  );
  /// Every name a nested scope may call this row by — what an expansion mints and what a hand
  /// written fixture therefore spells out. Eight, because that is `DEPTH_CEILING`; `[0]` is never
  /// worn, the outermost `FROM` naming the real table.
  const ALIASES: &'static [&'static str] = &[
    "__ig_clip_0__",
    "__ig_clip_1__",
    "__ig_clip_2__",
    "__ig_clip_3__",
    "__ig_clip_4__",
    "__ig_clip_5__",
    "__ig_clip_6__",
    "__ig_clip_7__",
  ];
  /// The collection column is ABSENT here, which is the plan's contract — `tags` names no column of
  /// `clip`, so a `SELECT` asking for one would refuse.
  const COLUMNS: &'static [ColumnShape] = &[
    ColumnShape::Plain(ColumnName::new("media_id")),
    ColumnShape::Plain(ColumnName::new("id")),
    ColumnShape::Plain(ColumnName::new("title")),
    ColumnShape::Plain(ColumnName::new("score")),
  ];
  /// One collection of each SHAPE, both gathered — the strategy the two dialects with no array type
  /// take, declared here as an expansion declares it per database. Two entries rather than one so
  /// the plan's own arity is exercised: a page runs one statement per entry, on one connection.
  const COLLECTIONS: &'static [EdgeCollection<Self, Db>] = &[
    EdgeCollection::gather(
      &[FieldName::new("tags")],
      EdgeShape::Sequence,
      clip_key::<Db>,
      clip_tags::<Db>,
    ),
    EdgeCollection::gather(
      &[FieldName::new("notes")],
      EdgeShape::Set,
      clip_key::<Db>,
      clip_notes::<Db>,
    ),
  ];

  fn addresses(ids: &[i64]) -> Result<Self::Address, CrossingError> {
    Ok(SqlKeyIn::new(
      ["id"],
      ids
        .iter()
        .map(|id| [ClipValue::Id(*id)])
        .collect::<Vec<_>>(),
    ))
  }

  fn id(&self) -> Result<i64, CrossingError> {
    Ok(self.id)
  }

  fn record(self) -> Result<Clip, CrossingError> {
    Ok(Clip {
      media: self.media,
      id: self.id,
      title: self.title,
      score: self.score,
      tags: self.tags,
      notes: self.notes,
    })
  }
}

impl<Db> SqlOrdering<Db> for ClipRow
where
  Db: Backend + sqlx::Database,
  ClipFilter<Db>: ComplexComparison<Db>,
  SqlKeyIn<ClipValue, Db, 1>: ComplexComparison<Db>,
  ClipValue: Carrier<Db>,
  // What this row's SUBJECTS cost, stated as the obligation rather than as the predicate that
  // discharges it — which is the discipline every other row here already follows, and is what a
  // rendered COLUMN has always cost one layer down.
  TermColumns: OrderSubjects<Db>,
  i64: Carrier<Db>,
  for<'r> i64: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'r> String: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
{
  type Order = ClipOrder;
  type Value = ClipValue;
  /// Every term of this order is a COLUMN, which is what `TermColumns` says — the ordinary answer,
  /// stated rather than defaulted, because a row that said nothing about its subjects would be a row
  /// nobody could ask.
  type Subjects = TermColumns;

  /// The written terms, then the key columns none of them named, ascending — and a term that
  /// already named one MOVES it rather than repeating it.
  fn complete(written: &[ClipOrder]) -> Vec<ClipOrder> {
    let mut order = written.to_vec();
    for tail in [
      ClipOrder::Media(OrderDirection::Asc),
      ClipOrder::Id(OrderDirection::Asc),
    ] {
      if !written
        .iter()
        .any(|term| core::mem::discriminant(term) == core::mem::discriminant(&tail))
      {
        order.push(tail);
      }
    }
    order
  }

  fn subjects(_: &[ClipOrder]) -> TermColumns {
    TermColumns
  }

  fn term(order: ClipOrder) -> OrderTerm {
    match order {
      ClipOrder::Media(direction) => OrderTerm::new(
        TermName::new("media"),
        FieldName::new("media_id"),
        direction,
      ),
      ClipOrder::Id(direction) => {
        OrderTerm::new(TermName::new("id"), FieldName::new("id"), direction)
      }
      ClipOrder::Title(direction) => {
        OrderTerm::new(TermName::new("title"), FieldName::new("title"), direction)
      }
      // The one NULLABLE column, DECLARED as such rather than inferred from a cursor's value.
      ClipOrder::Score(direction) => {
        OrderTerm::nullable(TermName::new("score"), FieldName::new("score"), direction)
      }
    }
  }

  /// Every term reads the DECODED row, so neither the raw row nor the alias is touched — which is
  /// what a record with no nested ordering term looks like from this seam, and is the shape the
  /// emitter writes for one.
  fn value(
    &self,
    order: ClipOrder,
    _: usize,
    _: &Db::Row,
    _: &str,
  ) -> Result<Option<ClipValue>, sqlx::Error> {
    Ok(match order {
      ClipOrder::Media(_) => Some(ClipValue::Media(self.media)),
      ClipOrder::Id(_) => Some(ClipValue::Id(self.id)),
      ClipOrder::Title(_) => Some(ClipValue::Title(self.title.clone())),
      ClipOrder::Score(_) => self.score.map(ClipValue::Score),
    })
  }
}

/// A filter over the title, so every lane can be rendered with and without a predicate.
fn titled() -> ClipFilter<Sqlite> {
  titled_as("a")
}

/// The same filter at a named operand — what the SCOPE slot is measured with, since the whole of
/// what two slots buy is that ONE column can be named at TWO operands.
fn titled_as(operand: &str) -> ClipFilter<Sqlite> {
  ClipFilter {
    title: SqlScalarComparison::try_from_filter(
      ScalarFilter::<std::string::String>::new().with_eq(operand.to_owned()),
    )
    .expect("a text equality crosses into SQLite"),
  }
}

/// The completed order's terms, which every ordered assertion below renders through.
fn terms(written: &[ClipOrder]) -> Vec<OrderTerm> {
  <ClipRow as SqlOrdering<Sqlite>>::complete(written)
    .iter()
    .map(|term| <ClipRow as SqlOrdering<Sqlite>>::term(*term))
    .collect()
}

/// The four columns of the fixture, as every statement below opens.
const SELECT: &str = "SELECT \"media_id\", \"id\", \"title\", \"score\" FROM \"clip\"";

/// Lane 1: no order and no ceiling. The `ORDER BY` is ABSENT rather than defaulted, which is the
/// ruling — a sort nobody asked for is work every row pays for.
#[test]
fn an_unordered_query_renders_no_order_by_at_all() {
  let statement = scan::<ClipRow, Sqlite>(None, None, None).expect("no predicate lowers");
  assert_eq!(statement.sql(), SELECT);

  let filter = titled();
  let filtered =
    scan::<ClipRow, Sqlite>(Some(&filter), None, None).expect("a text equality lowers");
  assert_eq!(filtered.sql(), format!("{SELECT} WHERE \"title\" = ?"));
}

/// **THE SCOPE IS A SECOND CONJUNCT, AND A CONTRADICTION RENDERS AS ONE** — the slot the lineage
/// leg's `where` rides on, measured where it becomes a statement.
///
/// The two predicates name the SAME column at DIFFERENT operands, which is the case no merge can
/// express: a column's operand slot holds one operand, so a filter merged with a scope keeps
/// whichever was written last and asks for the wrong rows. Two values threaded through one
/// accumulator render both, and the store answers the intersection — empty here, by set law and
/// with no refusal anywhere in the engine.
///
/// The scope ALONE is asserted beside it, so the conjunction above cannot pass on a rendering that
/// silently dropped one side.
#[test]
fn a_scope_renders_beside_the_filter_rather_than_replacing_it() {
  let scope = titled_as("b");
  let scoped = scan::<ClipRow, Sqlite>(None, Some(&scope), None).expect("a text equality lowers");
  assert_eq!(scoped.sql(), format!("{SELECT} WHERE \"title\" = ?"));

  let filter = titled();
  let both =
    scan::<ClipRow, Sqlite>(Some(&filter), Some(&scope), None).expect("two text equalities lower");
  assert_eq!(
    both.sql(),
    format!("{SELECT} WHERE \"title\" = ? AND \"title\" = ?"),
    "both operands reach the statement — a merge would have rendered one"
  );
}

/// Lane 2: a row ceiling with no order — *any N rows*, which needs the `FROM → LIMIT` edge and
/// still renders no `ORDER BY`.
#[test]
fn a_row_ceiling_over_an_unordered_query_orders_nothing() {
  let statement = scan::<ClipRow, Sqlite>(None, None, Some(10)).expect("no predicate lowers");
  assert_eq!(statement.sql(), format!("{SELECT} LIMIT ?"));

  let filter = titled();
  let filtered =
    scan::<ClipRow, Sqlite>(Some(&filter), None, Some(10)).expect("a text equality lowers");
  assert_eq!(
    filtered.sql(),
    format!("{SELECT} WHERE \"title\" = ? LIMIT ?")
  );
}

/// Lane 3: a written order ends with the KEY, and a term that named a key column moves it rather
/// than repeating it — which is what makes the order total and the page resumable.
#[test]
fn a_written_order_is_completed_with_the_key() {
  let terms = terms(&[ClipOrder::Title(OrderDirection::Desc)]);
  let rendered = ordered::<ClipRow, Sqlite>(
    None,
    None,
    Ordering {
      order: SqlOrder::new(&terms).unwrap(),
      subjects: &TermColumns,
      keyset: None,
      values: SortValues::Unread,
    },
    Walk::Forward,
    None,
    None,
  )
  .expect("an order over stored columns lowers");
  assert_eq!(
    rendered.sql(),
    format!("{SELECT} ORDER BY \"title\" DESC, \"media_id\" ASC, \"id\" ASC")
  );

  assert_eq!(
    <ClipRow as SqlOrdering<Sqlite>>::complete(&[ClipOrder::Id(OrderDirection::Desc)]),
    [
      ClipOrder::Id(OrderDirection::Desc),
      ClipOrder::Media(OrderDirection::Asc)
    ],
    "a term naming a key column moves it and does not repeat it"
  );
}

/// A backward walk inverts EVERY term — which is what makes it the same order read from the far end
/// rather than a second order.
#[test]
fn a_backward_walk_inverts_every_term() {
  let terms = terms(&[ClipOrder::Score(OrderDirection::Asc)]);
  let forward = ordered::<ClipRow, Sqlite>(
    None,
    None,
    Ordering {
      order: SqlOrder::new(&terms).unwrap(),
      subjects: &TermColumns,
      keyset: None,
      values: SortValues::Unread,
    },
    Walk::Forward,
    None,
    None,
  )
  .expect("an order over stored columns lowers");
  assert_eq!(
    forward.sql(),
    format!("{SELECT} ORDER BY \"score\" ASC, \"media_id\" ASC, \"id\" ASC")
  );

  let backward = ordered::<ClipRow, Sqlite>(
    None,
    None,
    Ordering {
      order: SqlOrder::new(&terms).unwrap(),
      subjects: &TermColumns,
      keyset: None,
      values: SortValues::Unread,
    },
    Walk::Backward,
    None,
    None,
  )
  .expect("an order over stored columns lowers");
  assert_eq!(
    backward.sql(),
    format!("{SELECT} ORDER BY \"score\" DESC, \"media_id\" DESC, \"id\" DESC")
  );
}

/// A page is *the client's filter AND the keyset*, threaded through ONE accumulator — so the two
/// join with `AND` and neither has to know what the other was.
#[test]
fn a_page_resumes_beside_the_filter_and_not_instead_of_it() {
  let terms = terms(&[ClipOrder::Title(OrderDirection::Asc)]);
  let order = SqlOrder::<Sqlite>::new(&terms).unwrap();
  let cursor = Cursor::at(
    &terms,
    [
      Some(ClipValue::Title("a".to_owned())),
      Some(ClipValue::Media(1)),
      Some(ClipValue::Id(2)),
    ],
  );
  let keyset = SqlKeyset::resume_with(order, &cursor, Walk::Forward, &TermColumns)
    .expect("minted under this very order");
  let filter = titled();
  let statement = ordered::<ClipRow, Sqlite>(
    Some(&filter),
    None,
    Ordering {
      order,
      subjects: &TermColumns,
      keyset: Some(&keyset),
      values: SortValues::Projected,
    },
    Walk::Forward,
    Some(101),
    Some(20),
  )
  .expect("a page over stored columns lowers");

  assert_eq!(
    statement.sql(),
    format!(
      "{SELECT} WHERE \"title\" = ? AND (\"title\" > ? OR (\"title\" = ? AND (\"media_id\" > ? OR \
       (\"media_id\" = ? AND (\"id\" > ?))))) ORDER BY \"title\" ASC, \"media_id\" ASC, \"id\" ASC \
       LIMIT ? OFFSET ?"
    )
  );
}

/// An address names the ID COLUMN and nothing else, through the family's compound-key membership at
/// its degenerate width — the existing machinery rather than a second lowering of equality.
///
/// The lineage column is a stored column of this row and is absent from the statement, which is what
/// the collapse means where it is observable: `media_id` is still selected, filterable and
/// orderable, and it is not part of the lookup.
#[test]
fn an_address_names_the_id_column_alone() {
  let statement = address::<ClipRow, Sqlite>(&[2]).expect("an address lowers");
  assert_eq!(statement.sql(), format!("{SELECT} WHERE (\"id\") IN ((?))"));
  let batch = address::<ClipRow, Sqlite>(&[2, 3, 5]).expect("a batch of addresses lowers");
  assert_eq!(
    batch.sql(),
    format!("{SELECT} WHERE (\"id\") IN ((?), (?), (?))"),
    "the id-gather lane is the SAME predicate at a wider `k`"
  );
}

/// The framework's ceiling CLAMPS, and every way into a page goes through the one call that does
/// it — the ask, the default, and the widest number a client can send.
#[test]
fn a_page_size_is_clamped_to_the_framework_ceiling() {
  assert_eq!(
    Find::<ClipRow, Sqlite, ()>::new((), false)
      .order(&[ClipOrder::Title(OrderDirection::Asc)])
      .first(10)
      .size(),
    10
  );
  assert_eq!(
    Find::<ClipRow, Sqlite, ()>::new((), false)
      .order(&[])
      .first(u32::MAX)
      .size(),
    MAX_PAGE_SIZE,
    "the widest ask is narrowed to the cap"
  );
  assert_eq!(
    Find::<ClipRow, Sqlite, ()>::new((), false)
      .order(&[])
      .last(5_000)
      .size(),
    MAX_PAGE_SIZE,
    "and so is the backward walk's"
  );
}

/// A client that names no size gets the documented default, and the statement asks for ONE row more
/// than the page holds — the row that answers *is there more*.
#[test]
fn a_default_page_asks_for_one_row_more_than_it_holds() {
  let cursor = Cursor::at(
    &[OrderTerm::new(
      TermName::new("id"),
      FieldName::new("id"),
      OrderDirection::Asc,
    )],
    [Some(ClipValue::Id(1))],
  );
  let page = Find::<ClipRow, Sqlite, ()>::new((), false)
    .order(&[])
    .after(&cursor);
  assert_eq!(page.size(), DEFAULT_PAGE_SIZE);
  assert_eq!(page.window(), DEFAULT_PAGE_SIZE + 1);
}

/// A `skip` of ZERO is the start of the walk rather than a position, so it neither binds an
/// `OFFSET` nor claims there is anything behind the page.
#[test]
fn a_zero_skip_is_not_a_position() {
  let zero = Position::<ClipValue>::Skip(0);
  assert!(!zero.is_set());
  assert_eq!(zero.offset().unwrap(), None);

  let one = Position::<ClipValue>::Skip(1);
  assert!(one.is_set());
  assert_eq!(one.offset().unwrap(), Some(1));

  assert!(!Position::<ClipValue>::Start.is_set());
}

/// The gather is a statement of its own, and every name in it is DERIVED — the edge table from the
/// row's table run together with the column's path, the element and ordinal columns as the backend
/// renders one, the parent key from the row's own address.
///
/// The membership is the row-value `IN` over the page's keys, which is the shape `SqlKeyIn` renders
/// and is measured on all three engines there.
#[test]
fn a_gather_names_the_edge_table_and_the_page_it_is_for() {
  let page = [row(1, 2), row(1, 3)];
  let gathers = gathers::<ClipRow, Sqlite>(&page).expect("two collections, two statements");
  assert_eq!(gathers.len(), 2, "one statement per gathered collection");
  assert_eq!(
    gathers[0].0.sql(),
    "SELECT \"media_id\", \"id\", \"tags\" AS \"__element\", \"tags_ordinal\" AS \"__ordinal\" \
     FROM \"clip_tags\" WHERE (\"media_id\", \"id\") IN ((?, ?), (?, ?)) \
     ORDER BY \"media_id\" ASC, \"id\" ASC, \"__ordinal\" ASC"
  );
  // The SET has no ordinal to select or to order by, so its own value column is what makes the
  // materialized collection deterministic — and it is the edge table's primary key, so the order
  // costs nothing.
  assert_eq!(
    gathers[1].0.sql(),
    "SELECT \"media_id\", \"id\", \"notes\" AS \"__element\" \
     FROM \"clip_notes\" WHERE (\"media_id\", \"id\") IN ((?, ?), (?, ?)) \
     ORDER BY \"media_id\" ASC, \"id\" ASC, \"__element\" ASC"
  );
}

/// A collection column is NOT in the page's `SELECT` list, whichever lane rendered it — it names no
/// column of the row's own table, so asking for one would refuse.
#[test]
fn a_gathered_collection_is_absent_from_every_page_statement() {
  let scan = scan::<ClipRow, Sqlite>(None, None, None).expect("no predicate lowers");
  assert_eq!(scan.sql(), SELECT);
  assert!(!scan.sql().as_str().contains("tags"));

  let addressed = address::<ClipRow, Sqlite>(&[2]).expect("an address lowers");
  assert!(!addressed.sql().as_str().contains("tags"));
}

/// An EMPTY page renders no gather at all — a membership over no keys is a statement whose answer
/// is known before it is sent, and `IN ()` parses in no dialect.
#[test]
fn an_empty_page_gathers_nothing() {
  let empty: [ClipRow; 0] = [];
  assert!(
    gathers::<ClipRow, Sqlite>(&empty)
      .expect("a plan over no rows lowers")
      .is_empty()
  );
}

/// A page row, with the collection materialization would fill.
fn row(media: i64, id: i64) -> ClipRow {
  ClipRow {
    media,
    id,
    title: String::new(),
    score: None,
    tags: Vec::new(),
    notes: Vec::new(),
  }
}

/// One row of the corpus: the address, the two scalar columns, and the collection's elements in
/// their stored order.
type CorpusRow = (i64, i64, &'static str, Option<f64>, &'static [&'static str]);

/// The SET's rows, written in an order that is not their value order — which is what the gather's
/// `ORDER BY` over the element column makes deterministic.
const NOTES: [(i64, i64, &[&str]); 2] = [(1, 1, &["beta-note", "alpha-note"]), (2, 5, &["solo"])];

/// The corpus the collection walk runs over: four shapes a collection can have, and two lineages.
///
/// The tags are what make it a materialization test rather than a paging one — an empty collection,
/// a single element, a REPEATED element, and one whose stored ordinals are not the order its rows
/// were written in.
///
/// The ids are unique ACROSS the table rather than within a lineage, which is the law the address
/// rests on: one column names at most one row, so two rows sharing an id would be two rows at one
/// address. The DDL below states it as a constraint, so a corpus breaking it is refused at the
/// `INSERT` rather than answering the wrong row.
const CORPUS: [CorpusRow; 6] = [
  (1, 1, "alpha", Some(1.0), &["a", "b", "c"]),
  (1, 2, "beta", None, &[]),
  (1, 3, "gamma", Some(2.0), &["dup", "dup"]),
  (1, 4, "delta", Some(3.0), &["z"]),
  (2, 5, "epsilon", Some(4.0), &["m", "n"]),
  (2, 6, "zeta", Some(5.0), &[]),
];

/// The corpus as the completed order `title ASC` reads it — the reference every walk below is
/// checked against, computed in Rust rather than asked of the engine.
fn ordered_corpus() -> Vec<Clip> {
  let mut clips: Vec<Clip> = CORPUS
    .iter()
    .map(|&(media, id, title, score, tags)| Clip {
      media,
      id,
      title: title.to_owned(),
      score,
      tags: tags.iter().map(|&tag| tag.to_owned()).collect(),
      notes: {
        let mut notes: Vec<String> = NOTES
          .iter()
          .find(|&&(at_media, at_id, _)| at_media == media && at_id == id)
          .map(|&(_, _, notes)| notes.iter().map(|&note| note.to_owned()).collect())
          .unwrap_or_default();
        // A set's materialized order is its value order, which is what its edge table's primary key
        // is — so the reference sorts rather than keeping the order the rows were written in.
        notes.sort();
        notes
      },
    })
    .collect();
  clips.sort_by(|a, b| {
    a.title
      .cmp(&b.title)
      .then(a.media.cmp(&b.media))
      .then(a.id.cmp(&b.id))
  });
  clips
}

/// An in-memory database holding the corpus, on ONE connection.
///
/// A bare [`SqliteConnection`](sqlx::sqlite::SqliteConnection) and never a `Pool`: this crate
/// enables no sqlx runtime, so a pool would panic spawning its reaper. It is also what makes the
/// one-connection promise OBSERVABLE — `sqlite::memory:` is a database per connection, so anything
/// this engine ran on a second one would find no table at all.
///
/// The edge rows are written in an order that is NOT their ordinal order, so a gather that ordered
/// by nothing would answer with the physical order and be wrong for the first row of the corpus.
async fn corpus() -> sqlx::sqlite::SqliteConnection {
  use sqlx::Connection as _;

  let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
    .await
    .expect("an in-memory database");
  // The compound PRIMARY KEY is the physical layout this fixture pins — the edge tables lead with
  // both of its columns and the gather correlates on both. `UNIQUE ("id")` beside it is the LAW the
  // address rests on, stated where the engine can enforce it: an address binds that one column, so
  // a second row sharing an id is refused at the `INSERT` rather than found at the lookup.
  sqlx::query(
    r#"CREATE TABLE "clip" ("media_id" INTEGER, "id" INTEGER, "title" TEXT, "score" REAL,
       PRIMARY KEY ("media_id", "id"), UNIQUE ("id"))"#,
  )
  .execute(&mut db)
  .await
  .expect("the row table");
  sqlx::query(
    r#"CREATE TABLE "clip_tags" ("media_id" INTEGER, "id" INTEGER, "tags_ordinal" INTEGER,
       "tags" TEXT, PRIMARY KEY ("media_id", "id", "tags_ordinal"))"#,
  )
  .execute(&mut db)
  .await
  .expect("the sequence's edge table");
  sqlx::query(
    r#"CREATE TABLE "clip_notes" ("media_id" INTEGER, "id" INTEGER, "notes" TEXT,
       PRIMARY KEY ("media_id", "id", "notes"))"#,
  )
  .execute(&mut db)
  .await
  .expect("the set's edge table");

  for &(media, id, title, score, tags) in &CORPUS {
    sqlx::query(r#"INSERT INTO "clip" VALUES (?, ?, ?, ?)"#)
      .bind(media)
      .bind(id)
      .bind(title)
      .bind(score)
      .execute(&mut db)
      .await
      .expect("a clip");
    // Written back to front, so the physical order of these rows disagrees with their ordinals —
    // which is what the gather's `ORDER BY` is for and what a mutation dropping it loses.
    for (ordinal, tag) in (0..tags.len()).rev().zip(tags.iter().rev()) {
      sqlx::query(r#"INSERT INTO "clip_tags" VALUES (?, ?, ?, ?)"#)
        .bind(media)
        .bind(id)
        .bind(i64::try_from(ordinal).expect("a corpus of four elements"))
        .bind(*tag)
        .execute(&mut db)
        .await
        .expect("an element");
    }
  }
  for &(media, id, notes) in &NOTES {
    for note in notes {
      sqlx::query(r#"INSERT INTO "clip_notes" VALUES (?, ?, ?)"#)
        .bind(media)
        .bind(id)
        .bind(*note)
        .execute(&mut db)
        .await
        .expect("a member");
    }
  }
  db
}

/// `get` answers with the WHOLE record — the scalars from the row and the collection from the
/// gather that ran on the same connection.
///
/// It is the same materialization a page takes, which is the point: a `get` that hydrated less than
/// a `find` would answer the same question two ways.
///
/// The LOOKUP is the id alone, and the corpus is what makes that observable: `epsilon` and `zeta`
/// belong to the second lineage and are reached with nothing about `media_id` on the call or in the
/// statement. The record that comes back still carries the whole chain, which is what the `*Key`
/// went on being for.
#[tokio::test]
async fn a_single_get_carries_the_collection_its_page_would() {
  let mut db = corpus().await;
  for expected in ordered_corpus() {
    let got = crate::query::sql::get::<ClipRow, Sqlite, _>(&mut db, &expected.id, false)
      .await
      .expect("the corpus is there");
    assert_eq!(got.as_ref(), Some(&expected));
    assert_eq!(
      got.map(|clip| clip.key()),
      Some(ClipKey {
        media: expected.media,
        id: expected.id,
      }),
      "one column named the row, and the key it hands back is whole"
    );
  }

  assert_eq!(
    crate::query::sql::get::<ClipRow, Sqlite, _>(&mut db, &9, false)
      .await
      .expect("a miss is not an error"),
    None,
    "the miss stays `Ok(None)` with a collection plan on the row"
  );
}

/// The unordered lane hydrates too, and the empty collection comes back as the empty collection
/// rather than as an absent row or a refusal.
#[tokio::test]
async fn every_lane_hydrates_and_an_empty_collection_stays_empty() {
  let mut db = corpus().await;

  let mut scanned = Find::<ClipRow, Sqlite, _>::new(&mut db, false)
    .fetch()
    .await
    .expect("the unordered scan");
  scanned.sort_by(|a, b| {
    a.title
      .cmp(&b.title)
      .then(a.media.cmp(&b.media))
      .then(a.id.cmp(&b.id))
  });
  assert_eq!(scanned, ordered_corpus());
  assert!(
    scanned.iter().any(|clip| clip.tags.is_empty()),
    "and the corpus really does hold a row with no elements"
  );
  assert_eq!(
    scanned
      .iter()
      .find(|clip| clip.media == 1 && clip.id == 1)
      .map(|clip| clip.notes.as_slice()),
    Some(&["alpha-note".to_owned(), "beta-note".to_owned()][..]),
    "the set comes back in its own value order, not the order its rows were written in"
  );

  let ceilinged = Find::<ClipRow, Sqlite, _>::new(&mut db, false)
    .limit(2)
    .fetch()
    .await
    .expect("the row ceiling");
  assert_eq!(ceilinged.len(), 2);

  let ordered = Find::<ClipRow, Sqlite, _>::new(&mut db, false)
    .order(&[ClipOrder::Title(OrderDirection::Asc)])
    .fetch()
    .await
    .expect("the ordered scan");
  assert_eq!(ordered, ordered_corpus());
}

/// The PAGE walk, forwards and backwards, two rows at a time — every page's collections compared
/// against the same collections computed in Rust, and every cursor round-tripped through its
/// base64 STRING as a client's would be.
///
/// This is what the statement's text cannot show: a gather correlated to the wrong parent and one
/// that never ran are both well-formed SQL, and both are visible here as the wrong collection on a
/// right row. The ORDER of a sequence is not, on this engine — SQLite seeks the edge table's own
/// primary-key index, which is `(key…, ordinal)`, so it answers in ordinal order whether or not the
/// statement asked. That half is pinned by the rendering test above and measured where a plan reads
/// the heap instead; see [`hydrate`](super::super::hydrate).
#[tokio::test]
async fn a_collection_survives_the_whole_walk_in_both_directions() {
  let mut db = corpus().await;
  let expected = ordered_corpus();
  let order = [ClipOrder::Title(OrderDirection::Asc)];

  let mut forward: Vec<Clip> = Vec::new();
  let mut resume: Option<String> = None;
  loop {
    let page = match &resume {
      None => Find::<ClipRow, Sqlite, _>::new(&mut db, false)
        .order(&order)
        .first(2)
        .fetch()
        .await
        .expect("the first page"),
      Some(encoded) => {
        let cursor = Cursor::<ClipValue>::decode(encoded).expect("a cursor this engine minted");
        Find::<ClipRow, Sqlite, _>::new(&mut db, false)
          .order(&order)
          .first(2)
          .after(&cursor)
          .fetch()
          .await
          .expect("the next page")
      }
    };
    let more = page.has_next_page();
    let last = page.edges().last().map(|edge| edge.cursor().encode());
    forward.extend(
      page
        .into_edges()
        .into_iter()
        .map(|edge| edge.into_parts().0),
    );
    if !more {
      break;
    }
    resume = last;
  }
  assert_eq!(forward, expected, "the forward walk is the ordered scan");

  let mut backward: Vec<Clip> = Vec::new();
  let mut resume: Option<String> = None;
  loop {
    let page = match &resume {
      None => Find::<ClipRow, Sqlite, _>::new(&mut db, false)
        .order(&order)
        .last(2)
        .fetch()
        .await
        .expect("the last page"),
      Some(encoded) => {
        let cursor = Cursor::<ClipValue>::decode(encoded).expect("a cursor this engine minted");
        Find::<ClipRow, Sqlite, _>::new(&mut db, false)
          .order(&order)
          .last(2)
          .before(&cursor)
          .fetch()
          .await
          .expect("the page before")
      }
    };
    let more = page.has_previous_page();
    let first = page.edges().first().map(|edge| edge.cursor().encode());
    let mut rows: Vec<Clip> = page
      .into_edges()
      .into_iter()
      .map(|edge| edge.into_parts().0)
      .collect();
    rows.append(&mut backward);
    backward = rows;
    if !more {
      break;
    }
    resume = first;
  }
  assert_eq!(
    backward, expected,
    "the backward walk comes back as the scan in display order, collections and all"
  );
}

/// **The ROW leg is the SAME page** — lane 乙, stated as an equality rather than as a description.
///
/// One page fetched twice against one corpus: once crossed into records, once left as rows. The
/// cursors match string for string, the sequence matches, both boundary answers match, and each row
/// crosses into exactly the record the other leg produced — collections and all, which is what says
/// the hydration ran on this lane too rather than being something the crossing did.
///
/// That last equality is also the lane's whole justification: a wire face mints its output object
/// from the ROW, so a page that could only hand back records would make that face run this crossing
/// and discard it.
#[tokio::test]
async fn the_row_page_and_the_record_page_are_one_page() {
  let mut db = corpus().await;
  let order = [ClipOrder::Title(OrderDirection::Asc)];

  let records = Find::<ClipRow, Sqlite, _>::new(&mut db, false)
    .order(&order)
    .first(3)
    .fetch()
    .await
    .expect("the record leg");
  let rows = Find::<ClipRow, Sqlite, _>::new(&mut db, false)
    .order(&order)
    .first(3)
    .rows()
    .await
    .expect("the row leg");

  assert!(
    !records.edges().is_empty(),
    "an empty page would make every equality below vacuous"
  );
  assert_eq!(records.edges().len(), rows.edges().len());
  assert_eq!(records.has_next_page(), rows.has_next_page());
  assert_eq!(records.has_previous_page(), rows.has_previous_page());

  let mut materialized = false;
  for (crossed, kept) in records.edges().iter().zip(rows.edges()) {
    assert_eq!(crossed.cursor().encode(), kept.cursor().encode());
    // Qualified at the dialect, because `record` is `SqlQuery<Db>`'s and this fixture implements it
    // for every database — the same reason the lane below spells its own.
    let crossed_here =
      <ClipRow as SqlQuery<Sqlite>>::record(kept.node().clone()).expect("the row crosses");
    assert_eq!(&crossed_here, crossed.node());
    materialized |= !kept.node().tags.is_empty() || !kept.node().notes.is_empty();
  }
  assert!(
    materialized,
    "the collections are materialized onto the ROWS this leg hands back"
  );
}

/// The snapshot sugar wraps the WHOLE call — the page statement and every gather — in the dialect's
/// read transaction, and the collections come back unchanged by it.
///
/// The transaction is what the ruling asks for over the cells that can tear, and this is the lane
/// that has them: SQLite gathers, so a page is `1 + N` statements.
#[tokio::test]
async fn the_snapshot_wraps_the_page_and_its_gathers_alike() {
  let mut db = corpus().await;
  let ordered = Find::<ClipRow, Sqlite, _>::new(&mut db, true)
    .order(&[ClipOrder::Title(OrderDirection::Asc)])
    .fetch()
    .await
    .expect("the ordered scan inside a read transaction");
  assert_eq!(ordered, ordered_corpus());

  let paged = Find::<ClipRow, Sqlite, _>::new(&mut db, true)
    .order(&[ClipOrder::Title(OrderDirection::Asc)])
    .first(3)
    .fetch()
    .await
    .expect("a page inside a read transaction");
  assert_eq!(
    paged
      .edges()
      .iter()
      .map(|edge| edge.node().tags.clone())
      .collect::<Vec<_>>(),
    ordered_corpus()[..3]
      .iter()
      .map(|clip| clip.tags.clone())
      .collect::<Vec<_>>()
  );
}

/// The dialect with a native array does not gather: the same collection rides the PAGE statement,
/// as a correlated aggregate under an alias the engine wrote.
///
/// A second row rather than a second plan on the first, because `COLLECTIONS` is a const of the
/// impl and this fixture's `SqlQuery` is generic over the dialect — which is exactly the shape an
/// expansion has, one row and one plan per DECLARED database.
///
/// # What was put to a real one, and what it caught
///
/// **PostgreSQL 17.10**, over a record shaped as a declaration now writes one — a collection with no
/// storage word riding the row as `text[]` beside a collection whose declaration wrote `edge`, so
/// BOTH of this dialect's strategies are on one statement:
///
/// | what was put to it | answer |
/// |---|---|
/// | the page statement, both strategies at once | exact — `{a,b,c}` off the array column and `{alpha-note,beta-note}` off the aggregate, in VALUE order for a set whose rows were written the other way round |
/// | the row with neither | the array column is `{}` and the aggregate is SQL **`NULL`** — the fork [`aggregated`] decodes `Option<Vec<E>>` to absorb, measured as `IS NULL` true on that row and false on its neighbours |
///
/// | mutation | what came back |
/// |---|---|
/// | the aggregate correlated to ITSELF | every row answers with the WHOLE edge table — `{alpha-note,beta-note,solo}` on all three — which is well-formed SQL turning a per-parent question into a global one, and is the first of the four mutations the correlated kinds' own module records |
#[cfg(feature = "postgres")]
mod aggregate {
  use sqlx::Postgres;

  use super::{
    Clip, ClipFilter, ClipValue, ColumnName, ColumnShape, ComplexComparison, EdgeCollection,
    EdgeShape, FieldName, RecordAddress, SqlKeyIn, scan,
  };
  use crate::query::sql::{CrossingError, SqlQuery, aggregated};

  /// The same four scalar columns and the same two collections, stored where an array can hold
  /// them.
  struct AggregatedRow {
    media: i64,
    id: i64,
    title: String,
    score: Option<f64>,
    tags: Vec<String>,
    notes: Vec<String>,
  }

  /// Take the aggregated array off the page row — the plan's whole crossing, and one call.
  ///
  /// The ALIAS is the engine's rather than this fixture's: several aggregates ride one statement, so
  /// they have to be told apart, and the party that wrote the names is the party that hands them
  /// over. Nothing here re-derives one.
  fn take_tags(
    row: &mut AggregatedRow,
    from: &sqlx::postgres::PgRow,
    alias: &str,
  ) -> Result<(), sqlx::Error> {
    row.tags = aggregated::<String, Postgres>(from, alias)?;
    Ok(())
  }

  /// The set's twin.
  fn take_notes(
    row: &mut AggregatedRow,
    from: &sqlx::postgres::PgRow,
    alias: &str,
  ) -> Result<(), sqlx::Error> {
    row.notes = aggregated::<String, Postgres>(from, alias)?;
    Ok(())
  }

  impl SqlQuery<Postgres> for AggregatedRow
  where
    ClipFilter<Postgres>: ComplexComparison<Postgres>,
  {
    type Record = Clip;
    type Address = SqlKeyIn<ClipValue, Postgres, 1>;

    const ADDRESS: RecordAddress = RecordAddress::new(
      FieldName::new("clip"),
      &[FieldName::new("media_id"), FieldName::new("id")],
    );
    /// Every name a nested scope may call this row by — what an expansion mints and what a hand
    /// written fixture therefore spells out. Eight, because that is `DEPTH_CEILING`; `[0]` is never
    /// worn, the outermost `FROM` naming the real table.
    const ALIASES: &'static [&'static str] = &[
      "__ig_clip_0__",
      "__ig_clip_1__",
      "__ig_clip_2__",
      "__ig_clip_3__",
      "__ig_clip_4__",
      "__ig_clip_5__",
      "__ig_clip_6__",
      "__ig_clip_7__",
    ];
    const COLUMNS: &'static [ColumnShape] = &[
      ColumnShape::Plain(ColumnName::new("media_id")),
      ColumnShape::Plain(ColumnName::new("id")),
      ColumnShape::Plain(ColumnName::new("title")),
      ColumnShape::Plain(ColumnName::new("score")),
    ];
    const COLLECTIONS: &'static [EdgeCollection<Self, Postgres>] = &[
      EdgeCollection::aggregate(&[FieldName::new("tags")], EdgeShape::Sequence, take_tags),
      EdgeCollection::aggregate(&[FieldName::new("notes")], EdgeShape::Set, take_notes),
    ];

    fn addresses(ids: &[i64]) -> Result<Self::Address, CrossingError> {
      Ok(SqlKeyIn::new(
        ["id"],
        ids
          .iter()
          .map(|id| [ClipValue::Id(*id)])
          .collect::<Vec<_>>(),
      ))
    }

    fn id(&self) -> Result<i64, CrossingError> {
      Ok(self.id)
    }

    fn record(self) -> Result<Clip, CrossingError> {
      Ok(Clip {
        media: self.media,
        id: self.id,
        title: self.title,
        score: self.score,
        tags: self.tags,
        notes: self.notes,
      })
    }
  }

  /// One statement, no second round trip and nothing to tear: each aggregate is a correlated
  /// subselect on the SELECT list, the sequence ordered by the edge table's ordinal and the set by
  /// its own value — which is the order its primary key already keeps it in.
  ///
  /// Both ride one statement, so their aliases carry the plan's INDEX. That is what makes several
  /// collections on one record expressible at all.
  #[test]
  fn every_aggregated_collection_rides_the_one_page_statement() {
    let statement = scan::<AggregatedRow, Postgres>(None, None, None).expect("no predicate lowers");
    assert_eq!(
      statement.sql(),
      "SELECT \"media_id\", \"id\", \"title\", \"score\", \
       (SELECT array_agg(\"clip_tags\".\"tags\" ORDER BY \"clip_tags\".\"tags_ordinal\") \
       FROM \"clip_tags\" \
       WHERE \"clip_tags\".\"media_id\" = \"clip\".\"media_id\" \
       AND \"clip_tags\".\"id\" = \"clip\".\"id\") AS \"__element_0\", \
       (SELECT array_agg(\"clip_notes\".\"notes\" ORDER BY \"clip_notes\".\"notes\") \
       FROM \"clip_notes\" \
       WHERE \"clip_notes\".\"media_id\" = \"clip\".\"media_id\" \
       AND \"clip_notes\".\"id\" = \"clip\".\"id\") AS \"__element_1\" \
       FROM \"clip\""
    );
  }
}

/// The OTHER dialect that gathers, and the one whose brackets are not SQLite's.
///
/// The plan is the same plan — `ClipRow`'s `SqlQuery` impl is generic over the dialect, so both
/// gathers below are rendered from the very entries the SQLite tests above read — and what differs
/// is everything the DIALECT owns: the identifier quoting is a backtick, and the parameter marker is
/// `?` in both, which is why the membership reads alike.
///
/// It is a RENDERING test and deliberately not a walk: this crate enables no MySQL server, so what
/// runs in-tree is the text. What that text DOES was put to a real one — **MySQL 8.4.11**, both
/// statements below verbatim through `PREPARE`/`EXECUTE … USING`, over the corpus the SQLite walk
/// uses, with the sequence's rows written back to front and the set's members written out of value
/// order, and one edge row added under a parent the page does NOT hold:
///
/// | what was put to it | answer |
/// |---|---|
/// | the sequence gather | exact — `a, b, c` in ORDINAL order for the row written `c, b, a`, and `dup, dup` kept |
/// | the set gather | exact — `alpha-note, beta-note` in VALUE order for the row written the other way round |
/// | both, against the off-page parent | it is absent, which is the correlation doing its work |
///
/// Two mutations on the same corpus, and the second is the one worth recording:
///
/// | mutation | what came back |
/// |---|---|
/// | the correlation dropped | the off-page parent's element ARRIVES — one extra row, no error, and the page's other collections all still right |
/// | the ordinal term dropped | nothing at all. `EXPLAIN` answers `type=range, key=PRIMARY, key_len=16` with no filesort: the plan seeks the edge table's own primary key, which IS `(key…, ordinal)`, so the rows arrive in that order whether or not the statement asked |
///
/// The second is the same blind spot SQLite has, for the same reason — see the note beside
/// [`hydrate`](super::super::hydrate), where PostgreSQL is the engine that takes a heap scan and
/// hands the insertion order back. So two of the three dialects cannot see a dropped ordinal, which
/// is exactly why the term is STATED rather than left to the index.
#[cfg(feature = "mysql")]
mod mysql {
  use sqlx::MySql;

  use super::{ClipRow, gathers, row};

  /// Both gathers, byte for byte, at the dialect whose bracket is a backtick.
  ///
  /// The select-list ALIAS ordered by and the bare `AS` projection of an edge column are the two
  /// forms the engine's own note calls out as beyond what `SqlKeyIn` had already measured on MySQL;
  /// they are what these two strings carry.
  #[test]
  fn both_gathers_render_in_mysqls_own_brackets() {
    let page = [row(1, 2), row(1, 3)];
    let gathers = gathers::<ClipRow, MySql>(&page).expect("two collections, two statements");
    assert_eq!(gathers.len(), 2, "one statement per gathered collection");
    assert_eq!(
      gathers[0].0.sql(),
      "SELECT `media_id`, `id`, `tags` AS `__element`, `tags_ordinal` AS `__ordinal` \
       FROM `clip_tags` WHERE (`media_id`, `id`) IN ((?, ?), (?, ?)) \
       ORDER BY `media_id` ASC, `id` ASC, `__ordinal` ASC"
    );
    assert_eq!(
      gathers[1].0.sql(),
      "SELECT `media_id`, `id`, `notes` AS `__element` \
       FROM `clip_notes` WHERE (`media_id`, `id`) IN ((?, ?), (?, ?)) \
       ORDER BY `media_id` ASC, `id` ASC, `__element` ASC"
    );
  }

  /// An EMPTY page renders no gather here either — the check is the engine's and not a dialect's,
  /// and `IN ()` parses in MySQL exactly as little as it does in SQLite.
  #[test]
  fn an_empty_page_gathers_nothing_here_either() {
    let empty: [ClipRow; 0] = [];
    assert!(
      gathers::<ClipRow, MySql>(&empty)
        .expect("a plan over no rows lowers")
        .is_empty()
    );
  }
}

/// The NESTED order: a term that sorts by a to-one target's column, lowered as a correlated scalar
/// subquery and paged through a frozen boundary.
///
/// # This fixture plays the EMITTER's part, and one thing it plays is still not emittable
///
/// Everything below is what a `#[ingraph::record(…)]` over three declarations would write — the
/// recursive order-by, the per-level subjects, the cursor sum and the value projection — and it
/// compiles against nothing but the two public traits, which is this file's standing standard.
///
/// **The ROW half of that gap has closed.** This note used to say a source's expansion could not
/// name its target's row, so the table, the id column and the cursor slot were all out of reach and
/// the missing fact was one — a per-`(record, database)` pairing naming the row. That pairing
/// exists: [`Record<B>::Row`](crate::Record::Row), whose own doc carries this argument, and
/// `ingraph-derive`'s `tests/nested_reach.rs` spends it at a concrete dialect — the address, the
/// scope aliases and a whole rendered semi-join, off a target the caller knows only by path.
///
/// What is still not emittable is the term's IDENTITY, and it is one fork rather than one fact.
/// `"cover_id.title"`'s tail is the TARGET declaration's field name, which no projection hands back
/// as a `&'static str` a literal can be built from at the source's end; the target's own
/// `identity()` answers it at RUNTIME as a `&'static TermName`. So `HOPS` and the identities below
/// stand in for a spelling that has to be chosen — a two-part identity folded by
/// [`OrderSignature`](crate::OrderSignature), which already length-prefixes and is therefore at
/// least as injective, or a `const` concatenation the language does not have. See
/// `ingraph-codegen`'s `emit::query` module note, flag α.
///
/// # The shape
///
/// ```text
/// shot ── cover_id ──► keyframe ── strip_id ──► strip
///     └── hero_id  ──►
/// ```
///
/// Two refs at ONE target, which is the pin fork 3 exists for, and one hop beyond it, which is the
/// depth the ruling refuses to put a ceiling on.
///
/// # What was MEASURED, and what each mutation cost
///
/// The goldens below are text and the walks below are a real in-memory SQLite 3.51.0, for the split
/// this file already keeps: a page that skips or repeats a row is valid SQL that answers without an
/// error. Three mutations were put to both halves, each leaving the rest of the page right:
///
/// | mutation | what came back |
/// |---|---|
/// | the alias decode dropped — a nested slot mints `None` | the bounded pin answers `[3, 2]` where the page holds `[2, 1]`: the row page 1 already returned comes back on page 2. A `NULL` boundary under an ascending term resumes with `IS NOT NULL`, which re-admits the whole head of the order — so the full walk NEVER TERMINATES, page after page of the same rows |
/// | the identity keyed on the TARGET TYPE rather than the ref field | `cover.title` and `hero.title` fold to one `OrderSignature(2010449004582713950)`, so a cursor from one walk is ACCEPTED by the other — and this corpus orders `[3, 1, 2, 4]` by one and `[3, 2, 1, 4]` by the other, so the resumed page is neither |
/// | the `SubSelect` slot arm stops wrapping | every golden reds, and SQLite refuses the statement outright: `near "SELECT": syntax error` |
///
/// The third is worth reading against O4-T1's own measurement of the same mutation, which found
/// SQLite and MySQL answering with a silently EMPTY page. The difference is the projection: a bare
/// `SELECT` in the keyset's parenthesised `WHERE` is absorbed as a scalar subquery, and the same
/// text on the SELECT LIST is a parse error. So the page lane cannot reach the silent shape — but
/// the ordered SCAN, which projects nothing, still can, and the silent half is why the pair sits
/// behind a TYPE: this fixture hands every position a body, the slot writes the pair at each, and a
/// provider that could omit it in one of them is not a thing this seam can express.
#[cfg(feature = "sqlite")]
mod nested {
  use std::sync::Arc;

  use sqlx::Sqlite;

  use super::{Find, Ordering, SortValues, ordered};
  use crate::{
    Carrier, ColumnName, ColumnShape, ComplexComparison, Cursor, CursorError, CursorValue,
    FieldName, Identifiable, OrderDirection, OrderTerm, Record, RecordAddress, TermName,
    Transformer, Walk,
    comparison::{
      At, Backend,
      sql::{
        OrderSubjects, QuoteIdent, SqlKeyIn, SqlKeyset, SqlOrder, SubjectShape, SubjectSlot,
        TermColumns, quote_ident, quote_qualified,
      },
    },
    query::sql::{CrossingError, SqlOrdering, SqlQuery},
  };

  /// A shot, and the two keyframes it may point at.
  #[derive(Debug, Clone, PartialEq)]
  struct Shot {
    id: i64,
    slate: String,
    /// NULLABLE, and that is the pin: a shot with no cover has no target row, so every nested term
    /// through it is SQL `NULL` — which the framework already puts below every value.
    cover: Option<i64>,
    hero: Option<i64>,
  }

  impl Identifiable for Shot {
    type Id = i64;

    fn id_ref(&self) -> &i64 {
      &self.id
    }
  }

  impl Transformer for Shot {
    type Key = i64;
    type Lineage = ();
    type Record = Self;
    // Nothing sends a shot over a wire, so no filter type was ever written for a client to send one
    // in — `ShotFilter` below is the LOWERED comparison, which is the other half of that split.
    type Graphql = ();

    fn key(&self) -> i64 {
      self.id
    }
  }

  /// A shot IS stored, so it has an order, and the term type is the one `SqlOrdering` binds — the
  /// same enum read from the entity's side rather than a second vocabulary beside it.
  /// The stored row, which is the record here — every column carried, so the crossing is field-wise.
  #[derive(Debug, Clone, PartialEq)]
  struct ShotRow {
    id: i64,
    slate: String,
    cover: Option<i64>,
    hero: Option<i64>,
  }

  impl<'r, R> sqlx::FromRow<'r, R> for ShotRow
  where
    R: sqlx::Row,
    i64: sqlx::Decode<'r, R::Database> + sqlx::Type<R::Database>,
    Option<i64>: sqlx::Decode<'r, R::Database> + sqlx::Type<R::Database>,
    String: sqlx::Decode<'r, R::Database> + sqlx::Type<R::Database>,
    for<'a> &'a str: sqlx::ColumnIndex<R>,
  {
    fn from_row(row: &'r R) -> Result<Self, sqlx::Error> {
      Ok(Self {
        id: row.try_get("id")?,
        slate: row.try_get("slate")?,
        cover: row.try_get("cover_id")?,
        hero: row.try_get("hero_id")?,
      })
    }
  }

  /// The STRIP's order vocabulary — the far end of the chain, where the recursion stops.
  #[derive(Debug, Clone, PartialEq, Eq)]
  enum StripOrder {
    Label(OrderDirection),
  }

  /// The KEYFRAME's, which is recursive in its turn: a target is a source too.
  ///
  /// The direction lives at the LEAF, so a nested variant carries no direction of its own and there
  /// is no second place for one to disagree with.
  #[derive(Debug, Clone, PartialEq, Eq)]
  enum KeyframeOrder {
    Title(OrderDirection),
    /// `<Strip as Record<Db>>::OrderBy` is what the emission spells here — the projection, never the
    /// name.
    Strip(Arc<StripOrder>),
  }

  /// The SHOT's: two columns of its own, and one variant per to-one ref carrying the TARGET's whole
  /// order-by.
  ///
  /// `Arc` rather than `Box`, measured at the clone sites this bound created — see
  /// [`SqlOrdering::Order`](crate::query::sql::SqlOrdering::Order). It is not `Copy`, which is the
  /// whole of why that bound moved.
  #[derive(Debug, Clone, PartialEq, Eq)]
  enum ShotOrder {
    Id(OrderDirection),
    Slate(OrderDirection),
    Cover(Arc<KeyframeOrder>),
    Hero(Arc<KeyframeOrder>),
  }

  /// One cursor slot. A nested term's slot holds the DECODED VALUE the boundary row sorted at, which
  /// is the ruling: a cursor means *where I stopped*, never *whom I stopped beside*.
  #[derive(Debug, Clone, PartialEq)]
  enum ShotValue {
    Id(i64),
    Slate(String),
    CoverTitle(String),
    CoverStripLabel(String),
    HeroTitle(String),
  }

  impl CursorValue for ShotValue {
    fn write_cursor(&self, out: &mut Vec<u8>) {
      match self {
        Self::Id(value) => {
          out.push(0);
          value.write_cursor(out);
        }
        Self::Slate(value) => {
          out.push(1);
          value.write_cursor(out);
        }
        Self::CoverTitle(value) => {
          out.push(2);
          value.write_cursor(out);
        }
        Self::CoverStripLabel(value) => {
          out.push(3);
          value.write_cursor(out);
        }
        Self::HeroTitle(value) => {
          out.push(4);
          value.write_cursor(out);
        }
      }
    }

    fn read_cursor(bytes: &[u8]) -> Option<Self> {
      let (tag, rest) = bytes.split_first()?;
      match tag {
        0 => i64::read_cursor(rest).map(Self::Id),
        1 => String::read_cursor(rest).map(Self::Slate),
        2 => String::read_cursor(rest).map(Self::CoverTitle),
        3 => String::read_cursor(rest).map(Self::CoverStripLabel),
        4 => String::read_cursor(rest).map(Self::HeroTitle),
        _ => None,
      }
    }
  }

  impl<Db> Carrier<Db> for ShotValue
  where
    Db: sqlx::Database,
    i64: Carrier<Db>,
    String: Carrier<Db>,
  {
    fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
      match self {
        Self::Id(value) => value.push_bind(qb),
        Self::Slate(value)
        | Self::CoverTitle(value)
        | Self::CoverStripLabel(value)
        | Self::HeroTitle(value) => value.push_bind(qb),
      }
    }
  }

  /// Nothing sends a filter over a shot, so the lowered comparison asks nothing.
  struct ShotFilter;

  impl<Db: Backend> ComplexComparison<Db> for ShotFilter {
    fn conjuncts(&self) -> usize {
      0
    }

    fn apply<'q>(
      &'q self,
      _: At<'_>,
      builder: Db::Builder<'q>,
    ) -> Result<Db::Builder<'q>, Db::Error> {
      Ok(builder)
    }
  }

  impl<Db: Backend> Record<Db> for Shot {
    type Row = ShotRow;
    type Comparison = ShotFilter;
    type OrderBy = ShotOrder;
  }

  /// ONE hop of a nested term: the FK on the row above, and the table and id column it points at.
  ///
  /// The three names an emitted hop would DERIVE rather than carry — the FK from the source's own
  /// columns, the table and the id from `<TargetRow as SqlQuery<Db>>::ADDRESS` — see this module's
  /// note for the one of those three that no projection reaches today.
  #[derive(Debug, Clone, Copy)]
  struct Hop {
    /// The table holding `fk`, which is the page's own row at the first hop and the previous hop's
    /// target after it.
    from: &'static FieldName,
    fk: &'static FieldName,
    table: &'static FieldName,
    id: &'static FieldName,
  }

  const SHOT: &FieldName = FieldName::new("shot");
  const KEYFRAME: &FieldName = FieldName::new("keyframe");
  const STRIP: &FieldName = FieldName::new("strip");
  const ID: &FieldName = FieldName::new("id");

  const VIA_COVER: Hop = Hop {
    from: SHOT,
    fk: FieldName::new("cover_id"),
    table: KEYFRAME,
    id: ID,
  };
  const VIA_HERO: Hop = Hop {
    from: SHOT,
    fk: FieldName::new("hero_id"),
    table: KEYFRAME,
    id: ID,
  };
  const VIA_STRIP: Hop = Hop {
    from: KEYFRAME,
    fk: FieldName::new("strip_id"),
    table: STRIP,
    id: ID,
  };

  /// A nested term's SUBJECT: the hops from the page's own row down to the column it orders by.
  #[derive(Debug, Clone)]
  struct Nested {
    hops: Vec<Hop>,
    column: &'static FieldName,
  }

  impl Nested {
    /// `SELECT <inner> FROM <table> WHERE <table>.<id> = <from>.<fk>` — the subject's BODY, with no
    /// pair of its own, because the brackets around a sub-select subject are the
    /// [`SubjectSlot`](crate::comparison::sql::SubjectSlot)'s.
    ///
    /// Every name is QUALIFIED, which is the discipline the edge-table strategy already holds: the
    /// correlation reaches OUT to the page's row, and an unqualified name resolves to the innermost
    /// scope — so a target carrying a column of the source's name would silently correlate the row
    /// to itself.
    fn push_body<Db: sqlx::Database + QuoteIdent>(
      &self,
      qb: &mut sqlx::QueryBuilder<Db>,
      hops: &[Hop],
    ) {
      let (hop, rest) = hops
        .split_first()
        .expect("a nested subject is built from at least one hop");
      qb.push("SELECT ");
      self.push(qb, rest, hop.table);
      qb.push(" FROM ");
      qb.push(quote_ident::<Db>(hop.table));
      qb.push(" WHERE ");
      qb.push(quote_qualified::<Db>(hop.table, hop.id));
      qb.push(" = ");
      qb.push(quote_qualified::<Db>(hop.from, hop.fk));
    }

    /// One level DOWN from a subject: the statement bracketed, or the target's own column qualified
    /// by the table holding it where the hops run out.
    ///
    /// This pair IS the subject's, and that is not the slot's coming back: an inner subquery sits in
    /// another statement's select list, where no position of this framework's reaches it and no slot
    /// is ever opened for it.
    fn push<Db: sqlx::Database + QuoteIdent>(
      &self,
      qb: &mut sqlx::QueryBuilder<Db>,
      hops: &[Hop],
      table: &FieldName,
    ) {
      if hops.is_empty() {
        qb.push(quote_qualified::<Db>(table, self.column));
        return;
      }
      qb.push("(");
      self.push_body(qb, hops);
      qb.push(")");
    }
  }

  /// What every term of one completed order compares, INDEXED BY LEVEL — the parallel structure a
  /// generated provider builds, where a plain level holds [`None`] and defers to [`TermColumns`].
  ///
  /// Built once per query from the completed order, and spent in three positions: the SELECT list,
  /// the `ORDER BY` and the resume predicate.
  #[derive(Debug, Clone)]
  struct ShotSubjects(Vec<Option<Nested>>);

  impl<Db: sqlx::Database + QuoteIdent + Backend<Buffer: core::fmt::Display>> OrderSubjects<Db>
    for ShotSubjects
  {
    fn push_subject(
      &self,
      slot: SubjectSlot<'_, Db>,
      at: At<'_>,
      terms: &[OrderTerm],
      level: usize,
    ) {
      match &self.0[level] {
        Some(nested) => slot.write(|qb| nested.push_body(qb, &nested.hops)),
        None => TermColumns.push_subject(slot, at, terms, level),
      }
    }

    /// A nested term IS a whole sub-select, and a plain one is its own column — which is the one
    /// answer both halves of the question follow from: a sub-select has no column on the returned
    /// row, so it rides the SELECT list, and it is what the slot brackets.
    fn shape(&self, terms: &[OrderTerm], level: usize) -> SubjectShape {
      match &self.0[level] {
        Some(_) => SubjectShape::SubSelect,
        // Handed BACK rather than answered with a literal — the same delegation `push_subject`
        // above already makes, and what the trait's own note asks of an override: it answers for
        // the levels it mints and leaves the rest to the default, which reads the TERM. A literal
        // `Column` here is a second opinion about a companion term's storage form, free to
        // disagree with the `ORDER BY` rendered from that same term.
        None => OrderSubjects::<Db>::shape(&TermColumns, terms, level),
      }
    }
  }

  /// The hops and leaf column one term compares, or [`None`] where it compares its own column.
  fn nested(order: &ShotOrder) -> Option<Nested> {
    let (hop, target) = match order {
      ShotOrder::Id(_) | ShotOrder::Slate(_) => return None,
      ShotOrder::Cover(target) => (VIA_COVER, target),
      ShotOrder::Hero(target) => (VIA_HERO, target),
    };
    let mut nested = match &**target {
      KeyframeOrder::Title(_) => Nested {
        hops: Vec::new(),
        column: FieldName::new("title"),
      },
      KeyframeOrder::Strip(strip) => match &**strip {
        StripOrder::Label(_) => Nested {
          hops: vec![VIA_STRIP],
          column: FieldName::new("label"),
        },
      },
    };
    nested.hops.insert(0, hop);
    Some(nested)
  }

  /// The identity of one term, and the DIRECTION at its leaf.
  ///
  /// One minted literal per nested term, keyed on the REF FIELD and never on the target type: two
  /// refs at one target are two different orders, so `cover_id.title` and `hero_id.title` are two
  /// identities and a cursor from one walk is refused by the other. `.` is injective over Rust
  /// idents and the signature already length-prefixes, so nothing here can alias.
  fn identity(order: &ShotOrder) -> (&'static TermName, OrderDirection) {
    fn through(strip: &KeyframeOrder) -> (&'static str, OrderDirection) {
      match strip {
        KeyframeOrder::Title(direction) => ("title", *direction),
        KeyframeOrder::Strip(strip) => match &**strip {
          StripOrder::Label(direction) => ("strip_id.label", *direction),
        },
      }
    }
    match order {
      ShotOrder::Id(direction) => (TermName::new("id"), *direction),
      ShotOrder::Slate(direction) => (TermName::new("slate"), *direction),
      ShotOrder::Cover(target) => match through(target) {
        ("title", direction) => (TermName::new("cover_id.title"), direction),
        (_, direction) => (TermName::new("cover_id.strip_id.label"), direction),
      },
      ShotOrder::Hero(target) => match through(target) {
        ("title", direction) => (TermName::new("hero_id.title"), direction),
        (_, direction) => (TermName::new("hero_id.strip_id.label"), direction),
      },
    }
  }

  impl<Db> SqlQuery<Db> for ShotRow
  where
    Db: Backend + sqlx::Database,
    SqlKeyIn<ShotValue, Db, 1>: ComplexComparison<Db>,
    ShotFilter: ComplexComparison<Db>,
    i64: Carrier<Db>,
    for<'r> i64: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
    for<'r> Option<i64>: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
    for<'r> String: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
    for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
  {
    type Record = Shot;
    type Address = SqlKeyIn<ShotValue, Db, 1>;

    const ADDRESS: RecordAddress = RecordAddress::new(SHOT, &[ID]);
    const ALIASES: &'static [&'static str] = &[
      "__ig_shot_0__",
      "__ig_shot_1__",
      "__ig_shot_2__",
      "__ig_shot_3__",
      "__ig_shot_4__",
      "__ig_shot_5__",
      "__ig_shot_6__",
      "__ig_shot_7__",
    ];
    const COLUMNS: &'static [ColumnShape] = &[
      ColumnShape::Plain(ColumnName::of(ID)),
      ColumnShape::Plain(ColumnName::new("slate")),
      ColumnShape::Plain(ColumnName::new("cover_id")),
      ColumnShape::Plain(ColumnName::new("hero_id")),
    ];

    fn addresses(ids: &[i64]) -> Result<Self::Address, CrossingError> {
      Ok(SqlKeyIn::new(
        ["id"],
        ids
          .iter()
          .map(|id| [ShotValue::Id(*id)])
          .collect::<Vec<_>>(),
      ))
    }

    fn id(&self) -> Result<i64, CrossingError> {
      Ok(self.id)
    }

    fn record(self) -> Result<Shot, CrossingError> {
      Ok(Shot {
        id: self.id,
        slate: self.slate,
        cover: self.cover,
        hero: self.hero,
      })
    }
  }

  impl<Db> SqlOrdering<Db> for ShotRow
  where
    Db: Backend + sqlx::Database + QuoteIdent,
    SqlKeyIn<ShotValue, Db, 1>: ComplexComparison<Db>,
    ShotFilter: ComplexComparison<Db>,
    ShotValue: Carrier<Db>,
    ShotSubjects: OrderSubjects<Db>,
    i64: Carrier<Db>,
    for<'r> i64: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
    for<'r> Option<i64>: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
    for<'r> String: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
    for<'r> Option<String>: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
    for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
  {
    type Order = ShotOrder;
    type Value = ShotValue;
    type Subjects = ShotSubjects;

    fn complete(written: &[ShotOrder]) -> Vec<ShotOrder> {
      let mut order = written.to_vec();
      if !written.iter().any(|term| matches!(term, ShotOrder::Id(_))) {
        order.push(ShotOrder::Id(OrderDirection::Asc));
      }
      order
    }

    fn subjects(order: &[ShotOrder]) -> ShotSubjects {
      ShotSubjects(order.iter().map(nested).collect())
    }

    /// A nested term is ALWAYS nullable, whatever the target's own column says: the row it reads may
    /// not be there. A shot whose `cover_id` is `NULL`, and one whose `cover_id` points at nothing,
    /// both give the subquery no row — and SQL answers a scalar subquery over no rows with `NULL`.
    /// The framework's pinned position takes it from there, in the ordering and in the resume
    /// predicate alike.
    ///
    /// The COLUMN a nested term carries is the FK it correlates on, and nothing renders it: the
    /// subject is written by [`ShotSubjects`] in all three positions. It is what a level whose
    /// subject was forgotten would order by, which is what the byte-exact goldens below are for.
    fn term(order: ShotOrder) -> OrderTerm {
      let (identity, direction) = identity(&order);
      match order {
        ShotOrder::Id(_) => OrderTerm::new(identity, ID, direction),
        ShotOrder::Slate(_) => OrderTerm::new(identity, FieldName::new("slate"), direction),
        ShotOrder::Cover(_) => OrderTerm::nullable(identity, FieldName::new("cover_id"), direction),
        ShotOrder::Hero(_) => OrderTerm::nullable(identity, FieldName::new("hero_id"), direction),
      }
    }

    fn value(
      &self,
      order: ShotOrder,
      _: usize,
      raw: &Db::Row,
      alias: &str,
    ) -> Result<Option<ShotValue>, sqlx::Error> {
      // The two nested terms read the RAW row at the alias the engine projected them under; the two
      // plain ones read the decoded row, where the SELECT list already put them.
      let projected = |mint: fn(String) -> ShotValue| {
        sqlx::Row::try_get::<Option<String>, _>(raw, alias).map(|value| value.map(mint))
      };
      match order {
        ShotOrder::Id(_) => Ok(Some(ShotValue::Id(self.id))),
        ShotOrder::Slate(_) => Ok(Some(ShotValue::Slate(self.slate.clone()))),
        ShotOrder::Cover(target) => match &*target {
          KeyframeOrder::Title(_) => projected(ShotValue::CoverTitle),
          KeyframeOrder::Strip(_) => projected(ShotValue::CoverStripLabel),
        },
        ShotOrder::Hero(_) => projected(ShotValue::HeroTitle),
      }
    }
  }

  /// `cover.title` ascending, the order every walk below runs.
  fn by_cover_title() -> [ShotOrder; 1] {
    [ShotOrder::Cover(Arc::new(KeyframeOrder::Title(
      OrderDirection::Asc,
    )))]
  }

  /// `hero.title` ascending — the same target through the OTHER ref, which is a different order.
  fn by_hero_title() -> [ShotOrder; 1] {
    [ShotOrder::Hero(Arc::new(KeyframeOrder::Title(
      OrderDirection::Asc,
    )))]
  }

  /// `cover.strip.label` ascending — two hops.
  fn by_cover_strip_label() -> [ShotOrder; 1] {
    [ShotOrder::Cover(Arc::new(KeyframeOrder::Strip(Arc::new(
      StripOrder::Label(OrderDirection::Asc),
    ))))]
  }

  /// The completed order's terms, which every assertion below renders through.
  fn terms(written: &[ShotOrder]) -> Vec<OrderTerm> {
    <ShotRow as SqlOrdering<Sqlite>>::complete(written)
      .iter()
      .map(|term| <ShotRow as SqlOrdering<Sqlite>>::term(term.clone()))
      .collect()
  }

  /// The subjects of that completed order.
  fn subjects(written: &[ShotOrder]) -> ShotSubjects {
    <ShotRow as SqlOrdering<Sqlite>>::subjects(&<ShotRow as SqlOrdering<Sqlite>>::complete(written))
  }

  /// The correlated scalar subquery `cover.title` lowers to — written out once, because the whole
  /// claim of the byte-exact goldens is that the SAME text reaches three positions.
  const COVER_TITLE: &str = "(SELECT \"keyframe\".\"title\" FROM \"keyframe\" \
                             WHERE \"keyframe\".\"id\" = \"shot\".\"cover_id\")";

  /// Two hops, and the recursion is the nesting: the inner subquery is the outer one's SELECT list.
  const COVER_STRIP_LABEL: &str = "(SELECT (SELECT \"strip\".\"label\" FROM \"strip\" WHERE \"strip\".\"id\" = \
     \"keyframe\".\"strip_id\") FROM \"keyframe\" \
     WHERE \"keyframe\".\"id\" = \"shot\".\"cover_id\")";

  /// The page's own statement, for `written` resumed at `cursor`.
  fn page(written: &[ShotOrder], cursor: &Cursor<ShotValue>) -> String {
    let terms = terms(written);
    let subjects = subjects(written);
    let order = SqlOrder::<Sqlite>::new(&terms).expect("a renderable order");
    let keyset = SqlKeyset::resume_with(order, cursor, Walk::Forward, &subjects)
      .expect("minted under this very order");
    ordered::<ShotRow, Sqlite>(
      None,
      None,
      Ordering {
        order,
        subjects: &subjects,
        keyset: Some(&keyset),
        values: SortValues::Projected,
      },
      Walk::Forward,
      Some(3),
      None,
    )
    .expect("a nested page lowers")
    .into_string()
  }

  /// **The byte-exact page.** One subject, three positions: projected onto the SELECT list under the
  /// alias the cursor is decoded by, compared in the `ORDER BY`, and compared again in every arm of
  /// the resume predicate.
  ///
  /// Rendering it three times rather than aliasing the ordering to `"__ig_ord0__"` is deliberate
  /// and is fork 1's: the clause grammar is unchanged, so nothing here has to know whether a dialect
  /// resolves an output name in an ordering position, and the keyset — which is a `WHERE`, where no
  /// dialect resolves one — could not have used the alias anyway. What keeps the three identical is
  /// that they come from ONE subjects value, which is what this text is asserting.
  #[test]
  fn a_nested_page_renders_one_subject_in_three_positions() {
    let cursor = Cursor::at(
      &terms(&by_cover_title()),
      [
        Some(ShotValue::CoverTitle("Autumn".to_owned())),
        Some(ShotValue::Id(1)),
      ],
    );

    assert_eq!(
      page(&by_cover_title(), &cursor),
      format!(
        "SELECT \"id\", \"slate\", \"cover_id\", \"hero_id\", {COVER_TITLE} AS \"__ig_ord0__\" \
         FROM \"shot\" \
         WHERE ({COVER_TITLE} > ? OR ({COVER_TITLE} = ? AND (\"id\" > ?))) \
         ORDER BY {COVER_TITLE} ASC, \"id\" ASC LIMIT ?"
      )
    );
  }

  /// **Depth two**, and the ceiling the ruling refuses to put on it: a ref's ref nests one subquery
  /// inside another, and every position takes the whole of it.
  #[test]
  fn a_refs_ref_nests_one_subquery_inside_the_other() {
    let cursor = Cursor::at(
      &terms(&by_cover_strip_label()),
      [
        Some(ShotValue::CoverStripLabel("inner".to_owned())),
        Some(ShotValue::Id(1)),
      ],
    );

    assert_eq!(
      page(&by_cover_strip_label(), &cursor),
      format!(
        "SELECT \"id\", \"slate\", \"cover_id\", \"hero_id\", \
         {COVER_STRIP_LABEL} AS \"__ig_ord0__\" FROM \"shot\" \
         WHERE ({COVER_STRIP_LABEL} > ? OR ({COVER_STRIP_LABEL} = ? AND (\"id\" > ?))) \
         ORDER BY {COVER_STRIP_LABEL} ASC, \"id\" ASC LIMIT ?"
      )
    );
  }

  /// The ordered SCAN projects NOTHING, and that is the whole of what `SortValues` decides: it mints
  /// no cursor, so a projected sort value would be a correlated subquery evaluated once per row for
  /// a number nobody reads. The `ORDER BY` is the page's, term for term.
  #[test]
  fn an_ordered_scan_orders_by_the_subquery_and_projects_none_of_it() {
    let written = by_cover_title();
    let terms = terms(&written);
    let subjects = subjects(&written);
    let order = SqlOrder::<Sqlite>::new(&terms).expect("a renderable order");
    let statement = ordered::<ShotRow, Sqlite>(
      None,
      None,
      Ordering {
        order,
        subjects: &subjects,
        keyset: None,
        values: SortValues::Unread,
      },
      Walk::Forward,
      None,
      None,
    )
    .expect("a nested order lowers");

    assert_eq!(
      statement.into_string(),
      format!(
        "SELECT \"id\", \"slate\", \"cover_id\", \"hero_id\" FROM \"shot\" \
         ORDER BY {COVER_TITLE} ASC, \"id\" ASC"
      )
    );
  }

  /// **The MIXED order**, which is the one a nested term actually produces: some levels are
  /// columns and some are not, and the subjects party answers for its own and defers the rest to
  /// `TermColumns` — the shape O4-T1 forecast when it handed the whole order and the level to
  /// `push_subject`.
  ///
  /// The alias carries the TERM's position and not a count of the projections, which is what keeps
  /// the SELECT list and the decode reading one index: the nested term is second here, so it is
  /// `__ig_ord1__` and there is no `__ig_ord0__` on the statement at all.
  #[test]
  fn a_mixed_order_defers_its_plain_levels_and_aliases_by_position() {
    let written = [
      ShotOrder::Slate(OrderDirection::Asc),
      ShotOrder::Cover(Arc::new(KeyframeOrder::Title(OrderDirection::Asc))),
    ];
    let cursor = Cursor::at(
      &terms(&written),
      [
        Some(ShotValue::Slate("alpha".to_owned())),
        Some(ShotValue::CoverTitle("Autumn".to_owned())),
        Some(ShotValue::Id(1)),
      ],
    );

    assert_eq!(
      page(&written, &cursor),
      format!(
        "SELECT \"id\", \"slate\", \"cover_id\", \"hero_id\", {COVER_TITLE} AS \"__ig_ord1__\" \
         FROM \"shot\" \
         WHERE (\"slate\" > ? OR (\"slate\" = ? AND ({COVER_TITLE} > ? \
         OR ({COVER_TITLE} = ? AND (\"id\" > ?))))) \
         ORDER BY \"slate\" ASC, {COVER_TITLE} ASC, \"id\" ASC LIMIT ?"
      )
    );
  }

  /// **Two refs at ONE target are two orders.** The identity is keyed on the REF FIELD, so a cursor
  /// minted walking `cover.title` is REFUSED by a walk over `hero.title` — before any SQL renders.
  ///
  /// Keyed on the target TYPE instead, the two would share a signature and the cursor would resume
  /// the wrong walk silently: this corpus orders `[3, 1, 2, 4]` by one and `[3, 2, 1, 4]` by the
  /// other, so the rows would be neither page.
  #[test]
  fn a_cursor_through_one_ref_is_refused_by_a_walk_through_the_other() {
    let cover = terms(&by_cover_title());
    let hero = terms(&by_hero_title());
    assert_ne!(
      crate::OrderSignature::of(&cover),
      crate::OrderSignature::of(&hero),
      "one target reached through two refs is two orders"
    );

    let cursor = Cursor::at(
      &cover,
      [
        Some(ShotValue::CoverTitle("Autumn".to_owned())),
        Some(ShotValue::Id(1)),
      ],
    );
    let subjects = subjects(&by_hero_title());
    let order = SqlOrder::<Sqlite>::new(&hero).expect("a renderable order");
    assert!(matches!(
      SqlKeyset::resume_with(order, &cursor, Walk::Forward, &subjects),
      Err(CursorError::Order { .. })
    ));
  }

  /// The corpus: four shots over three keyframes over two strips, with one shot pointing NOWHERE and
  /// the two refs crossed so that the same target set gives two different orders.
  ///
  /// ```text
  /// shot  slate  cover → title    hero → title      by cover.title   by hero.title
  ///  1    alpha   10   → Autumn    11  → Meadow           2nd              3rd
  ///  2    bravo   11   → Meadow    10  → Autumn           3rd              2nd
  ///  3    delta   NULL → NULL      NULL→ NULL             1st              1st
  ///  4    echo    12   → Zebra     12  → Zebra            4th              4th
  /// ```
  async fn corpus() -> sqlx::sqlite::SqliteConnection {
    use sqlx::Connection as _;

    let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
      .await
      .expect("an in-memory database");
    for ddl in [
      r#"CREATE TABLE "strip" ("id" INTEGER PRIMARY KEY, "label" TEXT NOT NULL)"#,
      r#"CREATE TABLE "keyframe" ("id" INTEGER PRIMARY KEY, "title" TEXT NOT NULL,
         "strip_id" INTEGER)"#,
      r#"CREATE TABLE "shot" ("id" INTEGER PRIMARY KEY, "slate" TEXT NOT NULL,
         "cover_id" INTEGER, "hero_id" INTEGER)"#,
    ] {
      sqlx::query(ddl).execute(&mut db).await.expect("a table");
    }
    for (id, label) in [(20i64, "inner"), (21, "outer")] {
      sqlx::query(r#"INSERT INTO "strip" VALUES (?, ?)"#)
        .bind(id)
        .bind(label)
        .execute(&mut db)
        .await
        .expect("a strip");
    }
    for (id, title, strip) in [
      (10i64, "Autumn", 20i64),
      (11, "Meadow", 21),
      (12, "Zebra", 20),
    ] {
      sqlx::query(r#"INSERT INTO "keyframe" VALUES (?, ?, ?)"#)
        .bind(id)
        .bind(title)
        .bind(strip)
        .execute(&mut db)
        .await
        .expect("a keyframe");
    }
    for (id, slate, cover, hero) in [
      (1i64, "alpha", Some(10i64), Some(11i64)),
      (2, "bravo", Some(11), Some(10)),
      (3, "delta", None, None),
      (4, "echo", Some(12), Some(12)),
    ] {
      sqlx::query(r#"INSERT INTO "shot" VALUES (?, ?, ?, ?)"#)
        .bind(id)
        .bind(slate)
        .bind(cover)
        .bind(hero)
        .execute(&mut db)
        .await
        .expect("a shot");
    }
    db
  }

  /// Every page of `written`, `size` at a time, each cursor round-tripped through its base64 STRING
  /// as a client's would be — and the ids in the sequence they came back.
  async fn walk(
    db: &mut sqlx::sqlite::SqliteConnection,
    written: &[ShotOrder],
    size: u32,
  ) -> Vec<i64> {
    let mut ids = Vec::new();
    let mut resume: Option<String> = None;
    loop {
      let page = match &resume {
        None => Find::<ShotRow, Sqlite, _>::new(&mut *db, false)
          .order(written)
          .first(size)
          .fetch()
          .await
          .expect("the first page"),
        Some(encoded) => {
          let cursor = Cursor::<ShotValue>::decode(encoded).expect("a cursor this engine minted");
          Find::<ShotRow, Sqlite, _>::new(&mut *db, false)
            .order(written)
            .first(size)
            .after(&cursor)
            .fetch()
            .await
            .expect("the next page")
        }
      };
      let more = page.has_next_page();
      let last = page.edges().last().map(|edge| edge.cursor().encode());
      ids.extend(
        page
          .into_edges()
          .into_iter()
          .map(|edge| edge.into_parts().0.id),
      );
      if !more {
        break;
      }
      resume = last;
    }
    ids
  }

  /// **The whole walk, live.** A page over a correlated subquery pages exactly, in every size, and a
  /// shot with NO cover sorts below every shot that has one — the framework's pinned `NULL` position
  /// answering the missing target with no case of its own.
  ///
  /// Two orders over ONE target set, differing only in which ref they go through, and they come back
  /// as two different sequences: that is what makes the refusal above worth having.
  #[tokio::test]
  async fn a_nested_order_pages_exactly_and_puts_a_missing_target_below_everything() {
    let mut db = corpus().await;

    for size in [1, 2, 3, 9] {
      assert_eq!(
        walk(&mut db, &by_cover_title(), size).await,
        [3, 1, 2, 4],
        "by cover.title, {size} at a time — the shot with no cover first"
      );
      assert_eq!(
        walk(&mut db, &by_hero_title(), size).await,
        [3, 2, 1, 4],
        "by hero.title, {size} at a time — the same targets, the other ref, another order"
      );
      assert_eq!(
        walk(&mut db, &by_cover_strip_label(), size).await,
        [3, 1, 4, 2],
        "by cover.strip.label, {size} at a time — two hops, ties broken by the id tail"
      );
      assert_eq!(
        walk(
          &mut db,
          &[
            ShotOrder::Slate(OrderDirection::Asc),
            ShotOrder::Cover(Arc::new(KeyframeOrder::Title(OrderDirection::Asc))),
          ],
          size
        )
        .await,
        [1, 2, 3, 4],
        "and a MIXED order pages exactly too, {size} at a time — one column term, one nested"
      );
    }
  }

  /// **The frozen boundary, and the row a re-derived one loses.**
  ///
  /// The spec's own example. Page 1 by `cover.title` returns the shot with no cover and then
  /// `alpha`, whose cover is `Autumn`; the cursor carries the STRING `Autumn`, because that is where
  /// the page stopped. Between the pages the target row is renamed `Autumn → Zebra`.
  ///
  /// Resumed from the frozen boundary, page 2 begins at `bravo` — whose cover `Meadow` is still
  /// after `Autumn` — and the page is fresh, so `alpha` reappears under its new title. Every row of
  /// the corpus is accounted for.
  ///
  /// A cursor that re-derived the boundary through the FOREIGN KEY would compare against `Zebra`,
  /// which is what the target holds NOW: `bravo` is then before the boundary and is DROPPED. The
  /// second assertion builds exactly that cursor and shows the loss — no error, no warning, one row
  /// gone. That is the measurement fork 2 was ruled on, made here rather than argued.
  #[tokio::test]
  async fn a_rename_between_pages_cannot_drop_a_row_from_a_frozen_boundary() {
    let mut db = corpus().await;
    let written = by_cover_title();

    let first = Find::<ShotRow, Sqlite, _>::new(&mut db, false)
      .order(&written)
      .first(2)
      .fetch()
      .await
      .expect("the first page");
    let ids: Vec<i64> = first.edges().iter().map(|edge| edge.node().id).collect();
    assert_eq!(ids, [3, 1]);
    let boundary = first
      .edges()
      .last()
      .expect("a page of two")
      .cursor()
      .encode();

    sqlx::query(r#"UPDATE "keyframe" SET "title" = 'Zebra' WHERE "id" = 10"#)
      .execute(&mut db)
      .await
      .expect("the rename");

    let frozen = Cursor::<ShotValue>::decode(&boundary).expect("a cursor this engine minted");
    let resumed = Find::<ShotRow, Sqlite, _>::new(&mut db, false)
      .order(&written)
      .first(2)
      .after(&frozen)
      .fetch()
      .await
      .expect("the page after");
    assert_eq!(
      resumed
        .edges()
        .iter()
        .map(|edge| edge.node().id)
        .collect::<Vec<_>>(),
      [2, 1],
      "the boundary is where the page stopped, so `bravo` is still after it"
    );

    // The same walk with the boundary RE-DERIVED through the foreign key — `Autumn` became `Zebra`,
    // so the cursor now names a place further along the order than the page ever reached.
    let terms = terms(&written);
    let rederived = Cursor::at(
      &terms,
      [
        Some(ShotValue::CoverTitle("Zebra".to_owned())),
        Some(ShotValue::Id(1)),
      ],
    );
    let drifted = Find::<ShotRow, Sqlite, _>::new(&mut db, false)
      .order(&written)
      .first(2)
      .after(&rederived)
      .fetch()
      .await
      .expect("the page after the drifted boundary");
    assert_eq!(
      drifted
        .edges()
        .iter()
        .map(|edge| edge.node().id)
        .collect::<Vec<_>>(),
      [4],
      "`bravo` is gone — one row lost, no error anywhere, which is why the boundary freezes"
    );
  }
}

/// **ONE SPELLING ACROSS THE TWO FAMILIES.** A sort value is one position in one written order
/// wherever it is stored, so the alias the SQL statement projects it under and the field the MongoDB
/// pipeline materializes it into are the same string, byte for byte.
///
/// The two consts are held apart because the feature edge does not let one family name the other's —
/// the same reason `ALIAS_PREFIX` is held in three crates — so this is the pair that CAN see both,
/// and it is what keeps them from drifting.
///
/// It also fences the frame law from this side: the body carries no `_`, so no row-source alias this
/// framework mints can equal it.
#[cfg(feature = "mongo")]
#[test]
fn a_sort_alias_is_one_spelling_across_the_two_families() {
  for level in [0, 1, 7, 42] {
    let sql = super::sort_alias(level);

    assert_eq!(sql.as_str(), crate::query::mongo::sort_alias(level));

    let body = sql
      .as_str()
      .strip_prefix("__ig_")
      .and_then(|body| body.strip_suffix("__"))
      .expect("a minted word wears the prefix and the terminator");

    assert!(
      !body.contains('_'),
      "`{sql}` has a body a `<table>_<depth>` split could reach"
    );
  }
}