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
//! What a node's storage LOOKS LIKE, stated once per database: [`Table`], the [`Column`]s it
//! carries, the [`EdgeTable`]s a collection hangs off it, the [`Shadow`]s a `sortable` collection's
//! order is mirrored into, the [`SideTable`]s a fan-in's provenance goes in, and [`Describe`], the
//! binding that ties one to the node it describes.
//!
//! ```text
//! Table      <table>:          (columns…[, companions…])  PRIMARY KEY (key…)[, UNIQUE (id)]
//! Sequence   <table>_<field>:  (key…, <field>_ordinal, <field>_<seg>…)
//! Set        <table>_<field>:  (key…, <field>_<seg>…)
//! Companion  <table>:          __ig_<field>_sort__        the order of one `sortable` collection
//! Side       <side>:           (id, ancestors…)    PRIMARY KEY (id), FOREIGN KEY (id) → <table>
//! ```
//!
//! A SCALAR element is the one-segment case of that spelling and its single column is the
//! collection's own name — see [`ElementColumns`], where the width is the element TYPE's answer and
//! the emitter judges nothing.
//!
//! # It is DATA here and SQL one module over
//!
//! Everything in this module is a `const`-constructible description with no rendering in it, and
//! that split is what puts it at the crate root rather than inside the SQL family. A table's name,
//! its columns and the type this database stores each at are facts about a DECLARATION; the
//! brackets around them, the `CREATE TABLE IF NOT EXISTS` in front and the dialect that decides both
//! are the SQL family's, and they live at [`query::sql`](crate::query::sql) with the rest of what
//! only that family spells. So a build with no backend can still name a descriptor, exactly as it
//! can name [`BeU64`](crate::BeU64) — a big-endian encoding and a column list each name no database.
//!
//! # The names are READ rather than restated
//!
//! A descriptor states no name the query layer does not already carry. Its
//! [`address`](Table::address) IS [`SqlQuery::ADDRESS`](crate::query::sql::SqlQuery::ADDRESS) — the
//! same type, projected rather than rebuilt — its columns are
//! [`COLUMNS`](crate::query::sql::SqlQuery::COLUMNS) with each one's stored type beside it, and an
//! edge table's NAME is not here at all: it is derived where the read and the write lanes derive
//! theirs, from the address and the collection's path. [`describes`] is the audit that holds the one
//! list this module does restate against the one the query layer publishes, and it is a `const`, so
//! a descriptor that drifted from its row is a compile error.
//!
//! That closes the gap [`comparison::sql`](crate::comparison::sql)'s own edge module names: it lists
//! four parties that spell an edge table's names and records that three of them DERIVE while the
//! fourth — a hand-written migration — has a text. The DDL renderer is the fifth party, and it
//! derives.
//!
//! [`Table::shaped`] removes the restatement rather than auditing it. A shaped descriptor IS the
//! query layer's list with a word beside each field, so there is no second list of names to drift
//! and `tb_num` is a string in neither of them — it is what the renderer joins `tb` and `num` into,
//! at the one place every other spelling of that column is joined.
//!
//! # The SPLIT LAYOUT is one fact, so it is one method
//!
//! A node several independent upstreams feed stores its rows in a COMMON table — its own id, the
//! discriminant naming which upstream a row descends from, and the uniform payload — with one
//! PROVENANCE table per upstream holding that variant's ancestors, each `NOT NULL` and keyed on the
//! common row's id. Which ancestor columns a row has depends on which upstream produced it, so a
//! single table would need every one of them nullable and every impossible combination — one
//! upstream's ancestors beside another's, or neither — would be writable.
//!
//! [`with_provenance`](Table::with_provenance) takes both halves at once because a descriptor
//! carrying one without the other describes a layout that cannot be read: a discriminant with no
//! provenance table names a row whose ancestry is stored nowhere, and a provenance table with no
//! discriminant leaves a reader to find out which of them holds the row by looking in each.

use crate::{ColumnShape, FieldName, Habitat, Path, RecordAddress};

/// One stored COLUMN: its name, the type THIS database keeps it at, and whether it holds `NULL`.
///
/// # The type is the DIALECT's own spelling, and it is text
///
/// `INTEGER` on SQLite, `int8` on PostgreSQL, `BIGINT` on MySQL — one column, three declarations,
/// and no vocabulary here to select among them. A closed enum was measured against the same wall
/// [`comparison::sql`](crate::comparison::sql)'s dialect module records: the set of types a dialect
/// stores is the DIALECT's, a fourth one this crate does not ship has its own, and a framework enum
/// over three shipped dialects' storage classes is a vocabulary the fourth cannot join. So the
/// declaration states the word and the renderer writes it.
///
/// It reaches the DDL text UNQUOTED and unescaped, which is the one asymmetry on this path: a type
/// is not an identifier and no bracketing makes `INTEGER` mean anything else. `&'static str` is what
/// keeps a caller's runtime string out of it — the same posture
/// [`ALIASES`](crate::query::sql::SqlQuery::ALIASES) takes for the names an expansion mints — and a
/// type an engine refuses is refused at execution, where it is loud.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Column {
  name: &'static FieldName,
  ty: &'static str,
  nullable: bool,
}

impl Column {
  /// A column called `name`, stored as `ty`, holding `NULL` or not.
  #[inline]
  #[must_use]
  pub const fn new(name: &'static FieldName, ty: &'static str, nullable: bool) -> Self {
    Self { name, ty, nullable }
  }

  /// This column's name, as the declaration spells it for this database.
  #[inline]
  #[must_use]
  pub const fn name(&self) -> &'static FieldName {
    self.name
  }

  /// The type this database stores it at.
  #[inline]
  #[must_use]
  pub const fn ty(&self) -> &'static str {
    self.ty
  }

  /// Whether it holds SQL `NULL`.
  #[inline]
  #[must_use]
  pub const fn nullable(&self) -> bool {
    self.nullable
  }
}

/// The shape an edge table keeps a collection in — which decides whether its rows carry an ordinal,
/// and therefore what a materialization can order by.
///
/// ```text
/// Sequence   <table>_<field>:  (key…, <field>_ordinal, <field>)   order and duplicates preserved
/// Set        <table>_<field>:  (key…, <field>)                    membership unique, order absent
/// ```
///
/// The same two shapes [`SqlEdgeComparison`](crate::comparison::sql::SqlEdgeComparison) and
/// [`SqlEdgeSetComparison`](crate::comparison::sql::SqlEdgeSetComparison) are the predicates of, and
/// the ordinal is the same 0-based dense column they read.
///
/// Here rather than beside the materialization that reads it, because the DDL that CREATES an edge
/// table asks the same question the gather asks — and this module is reachable in a build with no
/// SQL family at all, where [`query::sql`](crate::query::sql) is not.
/// [`query::sql`](crate::query::sql) re-exports it, so the path a materialization plan is written
/// through is unchanged.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EdgeShape {
  /// Order and duplicates preserved, in the `<field>_ordinal` column.
  Sequence,
  /// Membership unique and order absent — the rows are `(key…, value)` and there is no ordinal.
  Set,
}

impl EdgeShape {
  /// Whether this shape's rows carry an ordinal column.
  ///
  /// Read by all three directions: a materialization orders by it, a write BINDS it, and the DDL
  /// declares it — which is the one question that decides how many columns an edge row has.
  #[inline]
  #[must_use]
  pub const fn ordered(self) -> bool {
    matches!(self, Self::Sequence)
  }
}

/// What ONE ELEMENT of a collection occupies in its edge table.
///
/// ```text
/// Plain     <field>                                one column, named by the collection itself
/// Segments  <field>_<seg>, <field>_<seg>, …        one per SEGMENT of the element's own type
/// ```
///
/// # It is [`ColumnShape`]'s two arms with a stored TYPE on each column
///
/// A width is the element type's answer — [`ColumnKind`](crate::ColumnKind) — and the emitter judges
/// nothing: a scalar element leaves `SEGMENTS` at its default and lands on
/// [`Plain`](Self::Plain), a composite states its parts and lands on
/// [`Segments`](Self::Segments). What a descriptor adds is the word THIS database stores each column
/// at, which is a fact no shape carries; the NAMES are not carried either way, because they are
/// derived — a segment's column is the collection's own path extended by that segment, joined
/// exactly as [`Backend::write_column`](crate::Backend::write_column) joins one.
///
/// # A composite's segments are the DESCRIPTOR's, and that is where the SET refusal can be made
///
/// A [`Column`] carries nullability and a [`ColumnShape`] does not, which is what lets
/// [`EdgeTable::composite`] refuse a nullable segment on a SET in a `const`. Reading the flag off
/// the shape instead would have meant a second nullability record beside the one the parent table
/// already keeps.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ElementColumns {
  /// ONE column, named by the collection's own path, stored at this word.
  Plain(&'static str),
  /// One column per LEAF of the element's type, each named under the collection's path.
  ///
  /// The [`Column`] names stop at the ELEMENT: `secs`, `nanos` — and never the collection's own
  /// prefix, since that join is the renderer's and a descriptor spelling `stamps_secs` here would be
  /// the second spelling of a name the whole family derives.
  ///
  /// **Inside the element the names ARE joined**, because a part may itself be composite and the
  /// columns are the leaves: a detection whose identity lends no name states `language`, `script`,
  /// `region`, `rest`, `confidence`, and a part that DOES lend one states `rate_num`. That is the
  /// same list the direct table's descriptor holds for the same element, and
  /// [`leaf_names`](crate::leaf_names) is the `const` that holds either against the type's own
  /// answer.
  Segments(&'static [Column]),
}

impl ElementColumns {
  /// How many COLUMNS one element occupies — `1` for the plain answer and the segment count for a
  /// composite.
  ///
  /// It is what the write lane's bind arithmetic is multiplied by and what the `PRIMARY KEY` of a
  /// set's table is as wide as, so the two cannot disagree about one element's width.
  #[inline]
  #[must_use]
  pub const fn width(&self) -> usize {
    match self {
      Self::Plain(_) => 1,
      Self::Segments(segments) => segments.len(),
    }
  }

  /// The segments this element states, or EMPTY for the plain answer — which is exactly what
  /// [`ColumnKind::SEGMENTS`](crate::ColumnKind::SEGMENTS) answers for a scalar.
  #[inline]
  #[must_use]
  pub const fn segments(&self) -> &'static [Column] {
    match self {
      Self::Plain(_) => &[],
      Self::Segments(segments) => segments,
    }
  }
}

/// One collection column's SECOND TABLE, as this database creates it.
///
/// It holds no name. An edge table is the row's table run together with the column's path, and that
/// join is [`edge_table`](crate::comparison::sql::edge_table)'s — the same operation the correlated
/// comparison, the page's aggregate, the gather and the write all reach for. What a descriptor
/// states is the PATH the join is made from, which is the same thing
/// [`EdgeCollection`](crate::query::sql::EdgeCollection) and
/// [`EdgeWrite`](crate::query::sql::EdgeWrite) state, so no party spells a table two ways.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct EdgeTable {
  path: &'static [&'static FieldName],
  shape: EdgeShape,
  element: ElementColumns,
  indexed: bool,
}

impl EdgeTable {
  /// The table holding the collection `path` names, in `shape`, whose elements this database stores
  /// as `element`.
  ///
  /// # The EMPTY path is refused here
  ///
  /// An edge table holds a FIELD's elements, so a path naming no field has none: extended by
  /// nothing, the row's table is its own name, and every correlation built from it joins the row to
  /// itself. That is [`edge_table`](crate::comparison::sql::edge_table)'s own refusal, and it lands
  /// one layer earlier here — where a descriptor is WRITTEN — because a descriptor is a `const` and
  /// a refusal it can give at compile time is a refusal no run has to carry:
  ///
  /// ```compile_fail,E0080
  /// use ingraph::{EdgeShape, EdgeTable};
  ///
  /// const TAGS: EdgeTable = EdgeTable::new(&[], EdgeShape::Sequence, "TEXT");
  /// ```
  ///
  /// Its twin, which must COMPILE — stable rustdoc runs a `compile_fail` block just far enough to
  /// see it fail and never checks why, so the pair shares its call shape and one half is positive:
  ///
  /// ```
  /// use ingraph::{EdgeShape, EdgeTable, FieldName};
  ///
  /// const TAGS: EdgeTable =
  ///   EdgeTable::new(&[FieldName::new("tags")], EdgeShape::Sequence, "TEXT");
  /// assert!(TAGS.shape().ordered());
  /// ```
  #[inline]
  #[must_use]
  pub const fn new(
    path: &'static [&'static FieldName],
    shape: EdgeShape,
    element: &'static str,
  ) -> Self {
    Self::with_element(path, shape, ElementColumns::Plain(element))
  }

  /// The table holding the collection `path` names, in `shape`, whose elements are COMPOSITE and
  /// occupy the columns `segments` names.
  ///
  /// The segments are the element type's own LEAVES —
  /// [`ColumnKind::SEGMENTS`](crate::ColumnKind::SEGMENTS) flattened, with a stored type beside each,
  /// in the same order — and each is named under the collection's path by the renderer, so a
  /// `Vec<Timestamp>` at `stamps` reaches `(key…, stamps_ordinal, stamps_secs, stamps_nanos)` and a
  /// `Vec<DetectedLanguage>` at `heard` reaches `(key…, heard_ordinal, heard_language, heard_script,
  /// heard_region, heard_rest, heard_confidence)`.
  ///
  /// The list is a RESTATEMENT — this constructor is not handed the element type, so it cannot check
  /// it — and [`leaf_names`](crate::leaf_names) is what a declaration holds the two together with, in
  /// a `const` beside the descriptor.
  ///
  /// # A SET with an OPTIONAL segment is refused here, BY NAME
  ///
  /// A set's rows ARE its primary key — `(key…, <field>_<seg>…)` — so an optional segment puts
  /// `NULL` inside the identity, and the three engines disagree about what that means: SQLite admits
  /// the duplicates a `NULL` never equals, PostgreSQL and MySQL cannot store the `None` in a
  /// `NOT NULL` key column at all, and `UNIQUE` over a nullable column diverges per dialect. There is
  /// no reading of the operator that is right on all three, so it is refused where the descriptor is
  /// written:
  ///
  /// ```compile_fail,E0080
  /// use ingraph::{Column, EdgeShape, EdgeTable, FieldName};
  ///
  /// const STAMPS: EdgeTable = EdgeTable::composite(
  ///   &[FieldName::new("stamps")],
  ///   EdgeShape::Set,
  ///   &[
  ///     Column::new(FieldName::new("secs"), "BIGINT", false),
  ///     Column::new(FieldName::new("nanos"), "INTEGER", true),
  ///   ],
  /// );
  /// ```
  ///
  /// A SEQUENCE is untouched: its identity is the ORDINAL, so an optional segment is an ordinary
  /// nullable column and the same declaration is admitted —
  ///
  /// ```
  /// use ingraph::{Column, EdgeShape, EdgeTable, FieldName};
  ///
  /// const STAMPS: EdgeTable = EdgeTable::composite(
  ///   &[FieldName::new("stamps")],
  ///   EdgeShape::Sequence,
  ///   &[
  ///     Column::new(FieldName::new("secs"), "BIGINT", false),
  ///     Column::new(FieldName::new("nanos"), "INTEGER", true),
  ///   ],
  /// );
  /// assert_eq!(STAMPS.element().width(), 2);
  /// ```
  ///
  /// # A composite element of NO segments is refused too
  ///
  /// It is the scalar answer written the composite way — a column list of nothing, so the element
  /// would occupy no column and every row of the table would be its key. The scalar form is
  /// [`new`](Self::new), and a type that reached here with an empty `SEGMENTS` is one:
  ///
  /// ```compile_fail,E0080
  /// use ingraph::{EdgeShape, EdgeTable, FieldName};
  ///
  /// const TAGS: EdgeTable =
  ///   EdgeTable::composite(&[FieldName::new("tags")], EdgeShape::Sequence, &[]);
  /// ```
  #[inline]
  #[must_use]
  pub const fn composite(
    path: &'static [&'static FieldName],
    shape: EdgeShape,
    segments: &'static [Column],
  ) -> Self {
    assert!(
      !segments.is_empty(),
      "a composite element states its parts, and an element of no columns is the scalar answer — \
       `EdgeTable::new` is the form that spells one"
    );
    if !shape.ordered() {
      let mut at = 0;
      while at < segments.len() {
        assert!(
          !segments[at].nullable,
          "a set's identity covers every segment, and NULL has no equality to key on — make the \
           segment total, or store a sequence"
        );
        at += 1;
      }
    }
    Self::with_element(path, shape, ElementColumns::Segments(segments))
  }

  /// The two constructors' shared body: the EMPTY-path refusal, which is about the collection rather
  /// than about its element, and therefore stated once.
  #[inline]
  const fn with_element(
    path: &'static [&'static FieldName],
    shape: EdgeShape,
    element: ElementColumns,
  ) -> Self {
    assert!(
      !path.is_empty(),
      "an edge table holds a field's elements, and the empty path names no field"
    );
    Self {
      path,
      shape,
      element,
      indexed: false,
    }
  }

  /// The same table with the VALUE-LED access path — what the declaration's `indexed` word asks for.
  ///
  /// ```text
  /// __ig_<edge>_element   (key…, value…)   the KEY-LED probe: does THIS row's collection hold it
  /// __ig_<edge>_value     (value…, key…)   the VALUE-LED entry: WHICH rows' collections hold it
  /// ```
  ///
  /// # The two indexes answer two questions, and only one of them was ever derived
  ///
  /// A sequence's [containment index](Table::create) leads on the KEY, so it serves the correlated
  /// per-row membership probe — *this row again, does its list contain `dog`* — and a set's primary
  /// key leads on the key for the same reason. Neither can be seeked by a VALUE the caller has and a
  /// row it has not: *every row whose objects contain `dog`* is a full scan of the edge table under
  /// both, which is the shape a label search over a library is. This word is what puts the value
  /// first.
  ///
  /// It is OPT-IN because the cost is real and one-directional: a second B-tree over the same rows,
  /// maintained on every insert and delete of an element. A collection nobody searches by value pays
  /// nothing, which is why the framework does not derive this one the way it derives the other.
  ///
  /// # It is a WORD on the collection and not on a database's column
  ///
  /// The mechanism differs per dialect — a second index here, a GIN index over the array column
  /// where a dialect stores the collection in one, see
  /// [`Table::with_collection_indexes`] — and the INTENT is one, which is
  /// [`Shadow`]'s own arrangement for `sortable`. It has a second reason `sortable` does not need:
  /// on SQLite the path carries a CASE FOLD, which is visible in a set's identity, so a word that
  /// could be written for one database and not another would be a declaration meaning two different
  /// things in two stores.
  ///
  /// ```
  /// use ingraph::{EdgeShape, EdgeTable, FieldName};
  ///
  /// const TAGS: EdgeTable =
  ///   EdgeTable::new(&[FieldName::new("tags")], EdgeShape::Set, "TEXT").indexed();
  /// assert!(TAGS.is_indexed());
  /// ```
  #[inline]
  #[must_use]
  pub const fn indexed(mut self) -> Self {
    self.indexed = true;
    self
  }

  /// The collection column's path, from the ROW down — one segment for a column of the row itself,
  /// and one per level for a column of a composite inside it.
  #[inline]
  #[must_use]
  pub const fn path(&self) -> &'static [&'static FieldName] {
    self.path
  }

  /// Whether this collection asked for the VALUE-LED access path — [`indexed`](Self::indexed)'s own
  /// answer, and `false` for a collection that wrote no word.
  ///
  /// `is_indexed` rather than `indexed` because the WORD is the builder: a declaration writes
  /// `indexed` and a reader asks whether it did, and one name cannot be both.
  #[inline]
  #[must_use]
  pub const fn is_indexed(&self) -> bool {
    self.indexed
  }

  /// Order and duplicates, or membership alone.
  #[inline]
  #[must_use]
  pub const fn shape(&self) -> EdgeShape {
    self.shape
  }

  /// What one ELEMENT occupies here — one column at a stated type, or one per segment.
  #[inline]
  #[must_use]
  pub const fn element(&self) -> ElementColumns {
    self.element
  }
}

/// One collection's ORDER-PRESERVING COMPANION COLUMN — what `sortable` adds to the row
/// when this database keeps the collection in a table of its own.
///
/// ```text
/// clip:       (…, __ig_tags_sort__)          the companion, holding the whole collection's order
/// clip_tags:  (key…, tags_ordinal, tags)     the collection itself, unchanged
/// ```
///
/// The column holds [`collection_sort_key`](crate::collection_sort_key)'s bytes, whose BYTEWISE
/// order is [`compare_collections`](crate::query::compare_collections). So a statement that orders
/// by it orders the rows the way the framework means a collection order, on a dialect that has no
/// column to order the collection by — which is the whole of what the word buys.
///
/// # It is NOT one of [`Table::columns`], and that is the partition rather than an omission
///
/// [`describes`] holds the descriptor's column list against
/// [`SqlQuery::COLUMNS`](crate::query::sql::SqlQuery::COLUMNS), which is the RECORD's columns: every
/// one of them is selected, decoded back into a field and written from one. A companion column is
/// none of those — the framework writes it, the statement orders by it, and nothing reads it back,
/// the collection itself being what the edge table holds — so listing it there would put a column
/// no record has in the row's own vocabulary.
///
/// # It carries its NAME, for the reason [`SideTable`] carries one
///
/// An edge table's name is DERIVED wherever it is spelled, so no party declares it. A companion
/// column's is minted once, where the declaration is read — `__ig_<field>_sort__`, inside the
/// synthesized-column fence a declaration cannot spell — and carried from there, so the party that
/// creates the column, the party that writes it and the term that orders by it cannot name three
/// columns.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Shadow {
  column: &'static FieldName,
  path: &'static [&'static FieldName],
}

impl Shadow {
  /// The companion column `column` names, mirroring the collection at `path`.
  ///
  /// `path` is the collection's own — the same one its [`EdgeTable`] states — so a reader holding a
  /// descriptor can say which collection a companion is the order of.
  ///
  /// # The EMPTY path is refused here
  ///
  /// A companion mirrors a FIELD's elements, and a path naming no field has none — [`EdgeTable`]'s
  /// own refusal, in the same position and for the same reason:
  ///
  /// ```compile_fail,E0080
  /// use ingraph::{FieldName, Shadow};
  ///
  /// const TAGS: Shadow = Shadow::new(FieldName::new("__ig_tags_sort__"), &[]);
  /// ```
  ///
  /// Its twin, which must COMPILE — stable rustdoc runs a `compile_fail` block just far enough to
  /// see it fail and never checks why, so the pair shares its call shape and one half is positive:
  ///
  /// ```
  /// use ingraph::{FieldName, Shadow};
  ///
  /// const TAGS: Shadow =
  ///   Shadow::new(FieldName::new("__ig_tags_sort__"), &[FieldName::new("tags")]);
  /// assert_eq!(TAGS.path().len(), 1);
  /// ```
  #[inline]
  #[must_use]
  pub const fn new(column: &'static FieldName, path: &'static [&'static FieldName]) -> Self {
    assert!(
      !path.is_empty(),
      "a companion column mirrors a field's elements, and the empty path names no field"
    );
    Self { column, path }
  }

  /// The companion column's own name — what the `CREATE TABLE` declares, the write binds and the
  /// order term renders.
  #[inline]
  #[must_use]
  pub const fn column(&self) -> &'static FieldName {
    self.column
  }

  /// The collection this companion is the order of, by the path its edge table is derived from.
  #[inline]
  #[must_use]
  pub const fn path(&self) -> &'static [&'static FieldName] {
    self.path
  }
}

/// ONE UNIQUE constraint over SEVERAL of a row's declared entries — the composite
/// [`with_uniques`](Table::with_uniques) states it cannot express.
///
/// ```text
/// CREATE UNIQUE INDEX IF NOT EXISTS "__ig_<table>_<entry>_<entry>…" ON "<table>" (<leaf…>, <leaf…>)
/// ```
///
/// # It names ENTRIES, and an entry is a LEAF or a CITIZEN
///
/// [`Table::uniques`] names one column apiece and the statement it renders names that column
/// directly. This one names what the DECLARATION named, which is not always a column: a shaped
/// citizen — `span: MediaTimeRange` — is one entry of a row and SEVERAL of its columns, and the
/// renderer is the party that joins its leaves. So an entry resolves one of two ways, both settled
/// where the descriptor is written:
///
/// | the entry names | the constraint takes |
/// |---|---|
/// | a LEAF column — `media_id`, `checksum`, or a citizen's own leaf `at_timebase_num` | that one column |
/// | a CITIZEN — `span`, `at` | its VALUE leaves, in [`ColumnKind::SEGMENTS`](crate::ColumnKind::SEGMENTS) order |
///
/// # A CITIZEN FANS TO ITS VALUE LEAVES, AND THE DERIVED ONES ARE EXCLUDED
///
/// This is [`ColumnShape`]'s own law applied where a constraint is: *a derived leaf serves the
/// semantic order only, and every STRUCTURAL judgment walks value leaves only.* A uniqueness
/// constraint is a structural judgment — it is row-value equality, asked of the engine — so it is
/// measured against exactly the columns an equality is, which is [`ColumnShape::holds_value`]'s
/// answer and nothing else.
///
/// Including a derived leaf would not merely widen the constraint, it would BREAK it in the
/// direction that loses rows: `MediaTimestamp`'s `at_nanos` is `NULL` past the ±292-year ceiling,
/// two rows holding the same instant past it would carry `NULL` there, and `NULL`s do not collide
/// in a SQL unique index — so a pair the value columns call equal would be admitted twice. The
/// exclusion is what makes the constraint mean what its author wrote.
///
/// A citizen with no value leaves at all constrains nothing, and is refused where the descriptor is
/// written — see [`Table::with_composite_uniques`].
///
/// # The ORDER is the AUTHORED order
///
/// A composite index answers a seek by a leading prefix of its columns, so `(media, track, index)`
/// and `(index, track, media)` are different structures serving different reads. The declaration's
/// order is therefore carried rather than sorted: what the author wrote is what is created.
///
/// # It carries no NAME, for the reason [`EdgeTable`] carries none
///
/// The name is DERIVED — the table run together with the entries this states — so no party declares
/// one and there is no second spelling for a rename to drift from. See [`Table::create`], where the
/// derivation is, and [`Table::with_composite_uniques`], where a collision with a name another
/// declaration already derived is refused.
///
/// # Examples
///
/// ```
/// use ingraph::{CompositeUnique, FieldName};
///
/// const NATURAL_KEY: CompositeUnique = CompositeUnique::new(&[
///   FieldName::new("media"),
///   FieldName::new("track"),
///   FieldName::new("index"),
/// ]);
/// assert_eq!(NATURAL_KEY.entries().len(), 3);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CompositeUnique {
  entries: &'static [&'static FieldName],
}

impl CompositeUnique {
  /// The constraint over `entries`, in the order it states them.
  ///
  /// # The EMPTY list is refused here
  ///
  /// A constraint over no column constrains nothing, and the statement it would render is not
  /// legal SQL — [`EdgeTable::new`]'s own refusal, in the same position and for the same reason:
  ///
  /// ```compile_fail,E0080
  /// use ingraph::CompositeUnique;
  ///
  /// const NOTHING: CompositeUnique = CompositeUnique::new(&[]);
  /// ```
  ///
  /// Its twin, which must COMPILE — stable rustdoc runs a `compile_fail` block just far enough to
  /// see it fail and never checks why, so the pair shares its call shape and one half is positive:
  ///
  /// ```
  /// use ingraph::{CompositeUnique, FieldName};
  ///
  /// const PAIR: CompositeUnique =
  ///   CompositeUnique::new(&[FieldName::new("media"), FieldName::new("ordinal")]);
  /// assert_eq!(PAIR.entries().len(), 2);
  /// ```
  ///
  /// # A SINGLE entry is legal, and it is not the field marker's duplicate
  ///
  /// One entry is admitted deliberately. The field-level `unique` marker speaks to EVERY database a
  /// record declares; this list is one database's own, so a constraint wanted on SQLite alone has
  /// no other spelling — and refusing arity one would have left that want unsayable while buying
  /// nothing, the two roads being told apart by their SCOPE rather than by their width. Where both
  /// roads do name the same one column, the collision is refused rather than deduplicated — see
  /// [`Table::with_composite_uniques`].
  #[inline]
  #[must_use]
  pub const fn new(entries: &'static [&'static FieldName]) -> Self {
    assert!(
      !entries.is_empty(),
      "a composite unique constrains the entries it names, and the empty list names none"
    );
    Self { entries }
  }

  /// The entries this constraint names, in the authored order.
  #[inline]
  #[must_use]
  pub const fn entries(&self) -> &'static [&'static FieldName] {
    self.entries
  }
}

/// ONE upstream's PROVENANCE table, on a node several independent upstreams feed.
///
/// ```text
/// <side>: (<id>, <ancestors…>)   PRIMARY KEY (<id>), FOREIGN KEY (<id>) REFERENCES <table> (<id>)
/// ```
///
/// # It holds a NAME where an edge table holds none, and the difference is who decides it
///
/// An edge table's name is the row's table run together with the collection's path, so every party
/// that spells one DERIVES it and none of them declares it. A provenance table's name is DECLARED —
/// the upstream's own word in snake case by default, and renameable per database — so it is carried
/// here, which is the same slot [`Table`] gives the row's own name through [`RecordAddress`].
///
/// # The COLUMNS are the ancestors and nothing else
///
/// The leading `id` is not among them. It is the common row's id at the common row's own type, so
/// stating it here would be a second spelling of a column [`Table`] already carries — and the one
/// thing a descriptor never does is restate what it can read. What that leaves is exactly the
/// variant's ancestry, which is the only part of a provenance table nothing else knows.
///
/// Every column of it is `NOT NULL`, and that is the whole point of the split rather than a policy:
/// a provenance row exists because a row descends from THIS upstream, so there is no state for a
/// `NULL` to stand for.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SideTable {
  table: &'static FieldName,
  columns: &'static [Column],
}

impl SideTable {
  /// The provenance table `table` names, holding one variant's ancestors.
  ///
  /// # A provenance table with NO ancestor column is refused here
  ///
  /// Its rows would be the common row's id and nothing else — a table that records only that a row
  /// exists, which the common row already says. The refusal lands in a `const`, where a descriptor
  /// is written:
  ///
  /// ```compile_fail,E0080
  /// use ingraph::{FieldName, SideTable};
  ///
  /// const FROM_FRAME: SideTable = SideTable::new(FieldName::new("caption_frame"), &[]);
  /// ```
  ///
  /// Its positive twin, for the reason [`EdgeTable::new`]'s pair carries one:
  ///
  /// ```
  /// use ingraph::{Column, FieldName, SideTable};
  ///
  /// const FROM_FRAME: SideTable = SideTable::new(
  ///   FieldName::new("caption_frame"),
  ///   &[Column::new(FieldName::new("media_id"), "INTEGER", false)],
  /// );
  /// assert_eq!(FROM_FRAME.columns().len(), 1);
  /// ```
  ///
  /// # A NULLABLE ancestor is refused here too
  ///
  /// The whole of what the split buys is that an ancestor column is present because the row
  /// descends from this upstream, so a provenance table admitting `NULL` is the one-table layout
  /// again under another name:
  ///
  /// ```compile_fail,E0080
  /// use ingraph::{Column, FieldName, SideTable};
  ///
  /// const FROM_FRAME: SideTable = SideTable::new(
  ///   FieldName::new("caption_frame"),
  ///   &[Column::new(FieldName::new("media_id"), "INTEGER", true)],
  /// );
  /// ```
  #[must_use]
  pub const fn new(table: &'static FieldName, columns: &'static [Column]) -> Self {
    assert!(
      !columns.is_empty(),
      "a provenance table holds one variant's ancestors, and a variant with none is already \
       recorded by the common row's discriminant"
    );
    let mut at = 0;
    while at < columns.len() {
      assert!(
        !columns[at].nullable,
        "a provenance row exists because a row descends from this upstream, so its ancestors are \
         NOT NULL — a nullable one is the single-table layout the split exists to prevent"
      );
      at += 1;
    }
    Self { table, columns }
  }

  /// The table this variant's ancestors are stored in.
  #[inline]
  #[must_use]
  pub const fn table(&self) -> &'static FieldName {
    self.table
  }

  /// That variant's ancestor columns, in the order the DDL declares them — the common row's id
  /// leads them and is not among them.
  #[inline]
  #[must_use]
  pub const fn columns(&self) -> &'static [Column] {
    self.columns
  }
}

/// ONE node's storage in ONE database: the table, its columns, the columns an index seeks it by,
/// the columns a UNIQUE index constrains, and the edge tables its collections hang off.
///
/// # It is an ITEM, and every part of it is `&'static`
///
/// [`new`](Self::new) is `const` and takes borrowed lists, which is [`RecordAddress`]'s shape one
/// layer up and for its reason: a schema is DECLARED, once, beside the record it describes, and a
/// descriptor built per boot would be a schema that could differ between two of them. A `&[…]`
/// written in a `let` is `E0716`, so a descriptor is spelled in a `const` — which is where it
/// already is, on the [`Describe`] impl that carries it.
///
/// # Five members and the split layout's two
///
/// The address is the table's NAME and its key columns, so it is not restated here; the columns are
/// the row's own, each with the type this database keeps it at; the indexes are the FIELDS a plain
/// index is created over, one apiece; the uniques are the fields a UNIQUE index constrains, held
/// apart from the indexes for [`with_uniques`](Self::with_uniques)'s own reason; and the edges are
/// its collections' second tables. Beside the edges sits the one list that is about a collection
/// this dialect keeps in a COLUMN — see
/// [`with_collection_indexes`](Self::with_collection_indexes), which is `indexed`'s array-storage
/// half. The last two are the split layout's, and they arrive together — see
/// [`with_provenance`](Self::with_provenance).
///
/// # TWO CONSTRUCTORS, and the difference is who spells a column's NAME
///
/// [`new`](Self::new) takes the FLAT list a person writes: one entry per column, its name spelled
/// out. [`shaped`](Self::shaped) takes the row's own [`ColumnShape`] list with the word this
/// database stores each FIELD at beside it, and leaves the names to the renderer — which is what an
/// EMISSION can hand over, `tb_num` being a join and a `const` here having no joining rule.
///
/// Everything else composes onto both identically: `with_indexes`, `with_uniques`, `with_edges`,
/// `with_shadows` and `with_provenance` each ask whether a name is one of the table's own columns,
/// and each road answers that its own way. See [`TableColumns`], where the partition is stated, and
/// [`shaped`](Self::shaped), where the checks a shaped descriptor is held to are.
///
/// # Examples
///
/// A record with a two-column key, one nullable column, one indexed field and a sequence:
///
/// ```
/// use ingraph::{Column, EdgeShape, EdgeTable, FieldName, RecordAddress, Table};
///
/// const CLIP: Table = Table::new(
///   RecordAddress::new(
///     FieldName::new("clip"),
///     &[FieldName::new("media_id"), FieldName::new("id")],
///   ),
///   &[
///     Column::new(FieldName::new("media_id"), "INTEGER", false),
///     Column::new(FieldName::new("id"), "INTEGER", false),
///     Column::new(FieldName::new("title"), "TEXT", true),
///   ],
/// )
/// .with_indexes(&[FieldName::new("title")])
/// .with_edges(&[EdgeTable::new(
///   &[FieldName::new("tags")],
///   EdgeShape::Sequence,
///   "TEXT",
/// )]);
///
/// assert_eq!(CLIP.address().table(), FieldName::new("clip"));
/// assert_eq!(CLIP.columns().width(), 3);
/// assert_eq!(CLIP.stored(FieldName::new("id")), "INTEGER");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Table {
  address: RecordAddress,
  columns: TableColumns,
  indexes: &'static [&'static FieldName],
  uniques: &'static [&'static FieldName],
  composites: &'static [CompositeUnique],
  edges: &'static [EdgeTable],
  collection_indexes: &'static [&'static FieldName],
  shadows: &'static [Shadow],
  source: Option<&'static FieldName>,
  sides: &'static [SideTable],
}

/// How a [`Table`] STATES its columns — the two roads a descriptor is written down.
///
/// ```text
/// Flat     one entry per COLUMN   name, type, nullability     a person writes it
/// Shaped   one entry per FIELD    shape, words, nullability   an emission hands the row's own
/// ```
///
/// # The names are the whole difference
///
/// A FLAT descriptor carries the name of every column it declares, so `tb_num` is a string in the
/// declaration. A SHAPED one carries the row's [`ColumnShape`] list — `tb` above `num` and `den` —
/// and `tb_num` exists nowhere as data, being what the renderer joins the segments into. That is the
/// ban [`ColumnShape`]'s own module states: the join is `push_segments`, at render time, and
/// a `const` here that concatenated a name would be a second joining rule beside it.
///
/// So a shaped descriptor is not a flat one with the writing left out. It is the SAME LIST the query
/// layer publishes as [`SqlQuery::COLUMNS`](crate::query::sql::SqlQuery::COLUMNS), with the word
/// this database stores each field at beside it — which is why the restatement [`describes`] audits
/// on the flat road has no content on this one.
///
/// # THREE PARALLEL LISTS, all at the FIELD's grain
///
/// [`shapes`](Self::Shaped::shapes) is by field, so its siblings are too: one word LIST per field —
/// [`StoredAs::WORDS`](crate::StoredAs::WORDS), which is one word per column that field spans — and
/// one nullability flag per field. A composite is nullable as a WHOLE or not at all, which is the
/// same fact [`StoredAs`](crate::StoredAs)'s `Option` row states: an absent value leaves every
/// column of the field `NULL`, so a flag per column would be a state no declaration can reach.
///
/// The agreement between a field's word count and its width is asserted where a shaped table is
/// written — see [`Table::shaped`], where the `const` refusal is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TableColumns {
  /// One entry per COLUMN, each carrying the name this database stores it under.
  Flat(&'static [Column]),
  /// One entry per FIELD, with the column names left to the renderer.
  Shaped {
    /// The row's own shapes — one entry per field, innermost last.
    shapes: &'static [ColumnShape],
    /// One word list per FIELD, each as long as that field is wide, in
    /// [`SEGMENTS`](crate::ColumnKind::SEGMENTS) order.
    words: &'static [&'static [&'static str]],
    /// Whether each FIELD's columns hold `NULL`, one flag per field.
    nulls: &'static [bool],
  },
}

impl TableColumns {
  /// The FLAT list, where the descriptor states one — [`None`] for a shaped blueprint, whose column
  /// names exist nowhere as data.
  ///
  /// Absence IS the answer here, and it is the standing [`Describe`] takes one trait over: a caller
  /// that wants a `&'static FieldName` per column wants something a shaped descriptor does not have,
  /// and an empty slice would have said it had none.
  #[inline]
  #[must_use]
  pub const fn flat(&self) -> Option<&'static [Column]> {
    match *self {
      Self::Flat(columns) => Some(columns),
      Self::Shaped { .. } => None,
    }
  }

  /// The SHAPES, where the descriptor states them — [`None`] for a flat one.
  #[inline]
  #[must_use]
  pub const fn shapes(&self) -> Option<&'static [ColumnShape]> {
    match *self {
      Self::Flat(_) => None,
      Self::Shaped { shapes, .. } => Some(shapes),
    }
  }

  /// How many COLUMNS the row's own table has — the list's length on the flat road and the
  /// [`width`](crate::width) of the shapes on the other.
  ///
  /// The one question both roads answer, and the reason a caller counting columns need not know
  /// which it is holding.
  #[inline]
  #[must_use]
  pub const fn width(&self) -> usize {
    match *self {
      Self::Flat(columns) => columns.len(),
      Self::Shaped { shapes, .. } => crate::width(shapes),
    }
  }
}

impl Table {
  /// The table `address` names, carrying `columns`, with no index, no edge table and no
  /// discriminant.
  ///
  /// The three absent members are the COMMON case and each is added by a method of its own, so a
  /// record with no collection and no index states two arguments rather than five — which is what
  /// keeps the shape readable where it is actually written, inside a `const` beside a record.
  ///
  /// # A key column is one of the table's OWN columns, and that is checked here
  ///
  /// The key columns are what an edge table's rows lead with and what its `PRIMARY KEY` names, so
  /// the DDL has to know the type each is stored at — and it reads that off `columns`. A key naming
  /// a column the table does not carry is therefore a descriptor with no rendering, and it is
  /// refused where it is written:
  ///
  /// ```compile_fail,E0080
  /// use ingraph::{Column, FieldName, RecordAddress, Table};
  ///
  /// const CLIP: Table = Table::new(
  ///   RecordAddress::new(FieldName::new("clip"), &[FieldName::new("media_id")]),
  ///   &[Column::new(FieldName::new("id"), "INTEGER", false)],
  /// );
  /// ```
  ///
  /// Its positive twin, for the reason [`EdgeTable::new`]'s pair carries one:
  ///
  /// ```
  /// use ingraph::{Column, FieldName, RecordAddress, Table};
  ///
  /// const CLIP: Table = Table::new(
  ///   RecordAddress::new(FieldName::new("clip"), &[FieldName::new("id")]),
  ///   &[Column::new(FieldName::new("id"), "INTEGER", false)],
  /// );
  /// assert!(CLIP.columns().width() == 1);
  /// ```
  #[must_use]
  pub const fn new(address: RecordAddress, columns: &'static [Column]) -> Self {
    Self::stating(address, TableColumns::Flat(columns))
  }

  /// The table `address` names, whose columns are the row's own SHAPES with the word this database
  /// stores each FIELD at beside them — the same table, stated the way an emission can state it.
  ///
  /// ```text
  /// Table::new     &[Column::new(FieldName::new("tb_num"), "INTEGER", false), …]   names joined
  /// Table::shaped  COLUMNS, &[<Timebase as StoredAs<Db>>::WORDS, …], &[false, …]  names rendered
  /// ```
  ///
  /// # The names are NOT here, and that is the whole of what the word buys
  ///
  /// A flat descriptor spells `tb_num`, which is the join written down — so an emission producing
  /// one would have to concatenate a name in a `const`, where this crate has no joining rule by
  /// design (see [`ColumnShape`]'s own module, and [`FieldName`], which states it does not
  /// join). What arrives here instead is the list the query layer already publishes, and the join
  /// happens where every other spelling of that column happens: at render time, through
  /// `push_segments`, which a `SELECT` of `tb_num` and a filter over `tb.num` both reach. A shaped
  /// `CREATE TABLE` therefore cannot name a column the read lane would not find.
  ///
  /// # Three lists at the FIELD's grain, and the WIDTH is what holds them together
  ///
  /// `columns` is by field. So `words` is one [`StoredAs::WORDS`](crate::StoredAs::WORDS) per field
  /// — one word per COLUMN that field spans, flattened, in [`SEGMENTS`](crate::ColumnKind::SEGMENTS)
  /// order — and `nulls` is one flag per field. Each field's word count is held against its own
  /// width in a `const`, which is the agreement [`spans`](crate::spans) asserts one type at a time
  /// and this asserts for a whole row:
  ///
  /// ```compile_fail,E0080
  /// use ingraph::{ColumnName, ColumnShape, FieldName, RecordAddress, Table};
  ///
  /// const COLUMNS: &[ColumnShape] = &[ColumnShape::Composite {
  ///   field: Some(ColumnName::new("tb")),
  ///   segments: &[
  ///     ColumnShape::Plain(ColumnName::new("num")),
  ///     ColumnShape::Plain(ColumnName::new("den")),
  ///   ],
  /// }];
  ///
  /// // TWO columns wide, and ONE word offered for them.
  /// const CLIP: Table = Table::shaped(
  ///   RecordAddress::new(FieldName::new("clip"), &[FieldName::new("tb_num")]),
  ///   COLUMNS,
  ///   &[&["INTEGER"]],
  ///   &[false],
  /// );
  /// ```
  ///
  /// # NULLABILITY IS TWO GRAINS, and `nulls` states only the DECLARATION's
  ///
  /// One flag per field says the whole field may be ABSENT, which is what
  /// [`StoredAs`](crate::StoredAs)'s `Option<T>` row already means — an absent value leaves every
  /// column of the field `NULL`. It is the `optional` marker, and a marker sits on a field.
  ///
  /// It cannot say that ONE of a composite's columns holds `NULL` while its siblings do not, and
  /// there is a shipped type that wants exactly that:
  /// [`MediaTimeRange`](crate::MediaTimeRange)'s two DERIVED nanosecond columns bind `NULL` for an
  /// endpoint past `i64` nanoseconds while its tick counts stay exact. **That fact is not a third
  /// list here.** It is stated by the TYPE, beside the segment it belongs to, as
  /// [`ColumnShape::Nullable`](crate::ColumnShape::Nullable) — so it arrives through `columns` and
  /// needs no seat of its own.
  ///
  /// The renderer composes the two: a column admits `NULL` when its FIELD is optional **or** when
  /// its LEAF says so. A required `span: MediaTimeRange` renders its four value columns `NOT NULL`
  /// and its two derived ones bare — which is the schema its own write path promised and, while the
  /// field grain was the only one, could not have been given.
  ///
  /// A derived leaf is not thereby a nullable one. `NOT NULL` is kept off the leaves that say
  /// [`Nullable`](crate::ColumnShape::Nullable), and a leaf whose computation is total says
  /// [`Derived`](crate::ColumnShape::Derived) instead and takes it —
  /// [`BoundingBox`](crate::BoundingBox)'s `area` is the shipped case. Both are outside the VALUE;
  /// only one of them may be `NULL`.
  ///
  /// What stays the declaration's is the whole-field absence, and the division is the honest one: a
  /// marker author knows whether a field may be missing, and only the TYPE knows which of its
  /// columns are the value.
  ///
  /// # A COLLECTION field is not here either, exactly as it is not in a flat descriptor
  ///
  /// A collection is an [`EdgeTable`] — it appears in no column list, which is the partition
  /// [`with_edges`](Self::with_edges) states — so it is in neither `columns` nor `words`, and
  /// [`StoredAs`](crate::StoredAs) having no `Vec<T>` row in any dialect is the same fact from the
  /// other side. The one collection that could be a COLUMN is a PostgreSQL ARRAY, whose declared
  /// spelling and whose catalogue spelling are two different strings; `StoredAs`'s own note records
  /// that no single `WORDS` can be both, and nothing in this crate stores one today. So an array
  /// column has no word to hand this constructor, and that is where the question stays until
  /// something needs one.
  ///
  /// # Examples
  ///
  /// A record with a composite field, and the six columns it renders under one:
  ///
  /// ```
  /// use ingraph::{ColumnName, ColumnShape, FieldName, RecordAddress, Table};
  ///
  /// const TIMEBASE: &[ColumnShape] = &[
  ///   ColumnShape::Plain(ColumnName::new("num")),
  ///   ColumnShape::Plain(ColumnName::new("den")),
  /// ];
  /// const COLUMNS: &[ColumnShape] = &[
  ///   ColumnShape::Plain(ColumnName::new("id")),
  ///   ColumnShape::Composite { field: Some(ColumnName::new("tb")), segments: TIMEBASE },
  /// ];
  ///
  /// const CLIP: Table = Table::shaped(
  ///   RecordAddress::new(FieldName::new("clip"), &[FieldName::new("id")]),
  ///   COLUMNS,
  ///   &[&["INTEGER"], &["INTEGER", "INTEGER"]],
  ///   &[false, true],
  /// );
  ///
  /// assert_eq!(CLIP.columns().width(), 3);
  /// // The joined name is not stored — it is ASKED FOR, and answered by the same walk the
  /// // renderer makes.
  /// assert_eq!(CLIP.stored(FieldName::new("tb_den")), "INTEGER");
  /// ```
  ///
  /// # A KEY column is one of the columns the shapes RENDER, and that is checked here
  ///
  /// [`new`](Self::new)'s own refusal, asked of a shaped descriptor: the key is compared against
  /// each column the fields join to, through [`joins`](crate::joins), which is the `const` family's
  /// whole knowledge of the join and is a COMPARISON rather than a lookup — so the check is made
  /// without a name ever being built.
  ///
  /// ```compile_fail,E0080
  /// use ingraph::{ColumnName, ColumnShape, FieldName, RecordAddress, Table};
  ///
  /// const COLUMNS: &[ColumnShape] = &[ColumnShape::Plain(ColumnName::new("id"))];
  ///
  /// const CLIP: Table = Table::shaped(
  ///   RecordAddress::new(FieldName::new("clip"), &[FieldName::new("media_id")]),
  ///   COLUMNS,
  ///   &[&["INTEGER"]],
  ///   &[false],
  /// );
  /// ```
  ///
  /// A key naming a SEGMENT is admitted, because a segment is a column: the join is what decides,
  /// not the nesting.
  ///
  /// ```
  /// use ingraph::{ColumnName, ColumnShape, FieldName, RecordAddress, Table};
  ///
  /// const COLUMNS: &[ColumnShape] = &[ColumnShape::Composite {
  ///   field: Some(ColumnName::new("tb")),
  ///   segments: &[ColumnShape::Plain(ColumnName::new("num"))],
  /// }];
  ///
  /// const CLIP: Table = Table::shaped(
  ///   RecordAddress::new(FieldName::new("clip"), &[FieldName::new("tb_num")]),
  ///   COLUMNS,
  ///   &[&["INTEGER"]],
  ///   &[false],
  /// );
  /// assert_eq!(CLIP.columns().width(), 1);
  /// ```
  #[must_use]
  pub const fn shaped(
    address: RecordAddress,
    columns: &'static [ColumnShape],
    words: &'static [&'static [&'static str]],
    nulls: &'static [bool],
  ) -> Self {
    assert!(
      words.len() == columns.len(),
      "a shaped table states one WORD LIST per field — a list of another length describes a row \
       with a different number of fields from the one the shapes name"
    );
    assert!(
      nulls.len() == columns.len(),
      "a shaped table states one OPTIONALITY per field — whether the WHOLE field may be absent, \
       which is what the `optional` marker says — so the flag is the field's and there is one \
       apiece. A leaf that holds NULL whatever its field says states that on its own segment, as \
       `ColumnShape::Nullable`, and is not counted here"
    );
    let mut at = 0;
    while at < columns.len() {
      assert!(
        words[at].len() == columns[at].width(),
        "a field's words are one per COLUMN it spans — the same agreement `spans` holds a single \
         type's row to, asked of every field of a row"
      );
      at += 1;
    }
    Self::stating(
      address,
      TableColumns::Shaped {
        shapes: columns,
        words,
        nulls,
      },
    )
  }

  /// The two constructors' shared body: the KEY-COVERAGE refusal, which is about the address rather
  /// than about how the columns are stated, and therefore asked once of both roads.
  const fn stating(address: RecordAddress, columns: TableColumns) -> Self {
    let keys = address.keys();
    let mut at = 0;
    while at < keys.len() {
      assert!(
        declares(columns, keys[at]),
        "a key column is one of the table's own columns — the DDL reads the type it is stored at"
      );
      at += 1;
    }
    Self {
      address,
      columns,
      indexes: &[],
      uniques: &[],
      composites: &[],
      edges: &[],
      collection_indexes: &[],
      shadows: &[],
      source: None,
      sides: &[],
    }
  }

  /// The same table with one index per named FIELD.
  ///
  /// A field rather than a column list, because that is what the declaration says: an index is asked
  /// for at a field, and its NAME is derived from the table and the column so that nothing spells one
  /// twice. A composite index over several columns is a different declaration and is not expressible
  /// here — said rather than left for a reader to try, since the list's shape looks as though it
  /// might be one.
  ///
  /// # Every indexed field is one of THIS table's OWN columns, and that is checked here
  ///
  /// The statement this list renders names the column directly — `CREATE INDEX … ON <table>
  /// (<field>)` — so a field the table does not carry is an index over a column no `CREATE TABLE`
  /// ever declared, and the ENGINE would be the first party to say so, at boot, on a connection the
  /// caller had already opened. The two members beside this one refuse their own version of that
  /// where the descriptor is written, and this one now lands the same way:
  ///
  /// ```compile_fail,E0080
  /// use ingraph::{Column, FieldName, RecordAddress, Table};
  ///
  /// const CLIP: Table = Table::new(
  ///   RecordAddress::new(FieldName::new("clip"), &[FieldName::new("id")]),
  ///   &[Column::new(FieldName::new("id"), "INTEGER", false)],
  /// )
  /// .with_indexes(&[FieldName::new("title")]);
  /// ```
  ///
  /// Its positive twin, for the reason [`EdgeTable::new`]'s pair carries one:
  ///
  /// ```
  /// use ingraph::{Column, FieldName, RecordAddress, Table};
  ///
  /// const CLIP: Table = Table::new(
  ///   RecordAddress::new(FieldName::new("clip"), &[FieldName::new("id")]),
  ///   &[
  ///     Column::new(FieldName::new("id"), "INTEGER", false),
  ///     Column::new(FieldName::new("title"), "TEXT", true),
  ///   ],
  /// )
  /// .with_indexes(&[FieldName::new("title")]);
  /// assert_eq!(CLIP.indexes().len(), 1);
  /// ```
  ///
  /// A COMPANION column is not named here and does not have to be: it is none of the record's own
  /// columns — see [`Shadow`], where that partition is stated — and the walk indexes every one of
  /// them itself, where the dialect can index a binary column with no key length.
  ///
  /// The check reads `self.columns`, which [`new`](Self::new) has already settled, so this call may
  /// be written in any position among its neighbours — the property [`with_shadows`](Self::with_shadows)
  /// states for the same reason.
  #[must_use]
  pub const fn with_indexes(mut self, indexes: &'static [&'static FieldName]) -> Self {
    let mut at = 0;
    while at < indexes.len() {
      assert!(
        declares(self.columns, indexes[at]),
        "an indexed field is one of the table's own columns — the statement names the column \
         directly, so a field this table does not carry is an index over one nothing declared"
      );
      at += 1;
    }
    self.indexes = indexes;
    self
  }

  /// The same table with one UNIQUE index per named FIELD.
  ///
  /// [`with_indexes`](Self::with_indexes)'s own shape, one word over: a field rather than a column
  /// list, its NAME derived the same way, and a composite constraint over several columns is the
  /// same different declaration this list does not express either.
  ///
  /// # A field named here and ALSO in `indexes` renders ONE statement, not two
  ///
  /// A unique index already answers what a plain one seeks a row by, so a column carrying both
  /// words has nothing left for the plain statement to do that the unique one has not — the
  /// dedup, and the argument for it, are [`Table::create`]'s, which is where both lists are read
  /// together. This method does not refuse the overlap: an author who wrote `indexed` beside
  /// `unique` on one field stated two intents about it, and the SPELLING stays legal even though
  /// the render collapses it to the index that already implies the other.
  ///
  /// # Every unique field is one of THIS table's OWN columns, and that is checked here
  ///
  /// The same check [`with_indexes`](Self::with_indexes) runs, for the same reason: the statement
  /// this list renders names the column directly, so a field the table does not carry is a
  /// constraint over a column no `CREATE TABLE` ever declared.
  ///
  /// ```compile_fail,E0080
  /// use ingraph::{Column, FieldName, RecordAddress, Table};
  ///
  /// const CLIP: Table = Table::new(
  ///   RecordAddress::new(FieldName::new("clip"), &[FieldName::new("id")]),
  ///   &[Column::new(FieldName::new("id"), "INTEGER", false)],
  /// )
  /// .with_uniques(&[FieldName::new("checksum")]);
  /// ```
  ///
  /// Its positive twin:
  ///
  /// ```
  /// use ingraph::{Column, FieldName, RecordAddress, Table};
  ///
  /// const ASSET: Table = Table::new(
  ///   RecordAddress::new(FieldName::new("asset"), &[FieldName::new("id")]),
  ///   &[
  ///     Column::new(FieldName::new("id"), "INTEGER", false),
  ///     Column::new(FieldName::new("checksum"), "TEXT", false),
  ///   ],
  /// )
  /// .with_uniques(&[FieldName::new("checksum")]);
  /// assert_eq!(ASSET.uniques().len(), 1);
  /// ```
  ///
  /// The check reads `self.columns`, so this call may be written in any position among its
  /// neighbours — [`with_indexes`](Self::with_indexes)'s own property, for the same reason.
  #[must_use]
  pub const fn with_uniques(mut self, uniques: &'static [&'static FieldName]) -> Self {
    let mut at = 0;
    while at < uniques.len() {
      assert!(
        declares(self.columns, uniques[at]),
        "a unique field is one of the table's own columns — the statement names the column \
         directly, so a field this table does not carry is a constraint over one nothing declared"
      );
      at += 1;
    }
    self.uniques = uniques;
    self
  }

  /// The same table with one UNIQUE index per COMPOSITE constraint — the declaration
  /// [`with_uniques`](Self::with_uniques) states it does not express.
  ///
  /// Each [`CompositeUnique`] names the row's own entries and the renderer joins what they resolve
  /// to; see that type, where the two kinds of entry and the value-leaf fan are stated, and
  /// [`create`](Self::create), where the statement is.
  ///
  /// # THIS CALL COMES AFTER `with_uniques`, and the order is load-bearing
  ///
  /// The collision check below reads `self.uniques`, so a chain that writes this first would check
  /// against an empty list and admit the very pair it exists to refuse. It is the property
  /// [`with_shadows`](Self::with_shadows) already carries for [`with_edges`](Self::with_edges), and
  /// it is the one place this family's *write these in any order* freedom does not hold.
  ///
  /// # Every entry names something THIS table carries, and that is checked here
  ///
  /// [`with_uniques`](Self::with_uniques)'s own check, widened by exactly what this list widens: an
  /// entry may name a LEAF column, as that one does, or a CITIZEN whose value leaves the statement
  /// names instead. What it may not name is neither — a column no `CREATE TABLE` ever declared:
  ///
  /// ```compile_fail,E0080
  /// use ingraph::{Column, CompositeUnique, FieldName, RecordAddress, Table};
  ///
  /// const CLIP: Table = Table::new(
  ///   RecordAddress::new(FieldName::new("clip"), &[FieldName::new("id")]),
  ///   &[Column::new(FieldName::new("id"), "INTEGER", false)],
  /// )
  /// .with_composite_uniques(&[CompositeUnique::new(&[
  ///   FieldName::new("id"),
  ///   FieldName::new("checksum"),
  /// ])]);
  /// ```
  ///
  /// Its positive twin, for the reason [`EdgeTable::new`]'s pair carries one:
  ///
  /// ```
  /// use ingraph::{Column, CompositeUnique, FieldName, RecordAddress, Table};
  ///
  /// const CLIP: Table = Table::new(
  ///   RecordAddress::new(FieldName::new("clip"), &[FieldName::new("id")]),
  ///   &[
  ///     Column::new(FieldName::new("id"), "INTEGER", false),
  ///     Column::new(FieldName::new("checksum"), "TEXT", false),
  ///   ],
  /// )
  /// .with_composite_uniques(&[CompositeUnique::new(&[
  ///   FieldName::new("id"),
  ///   FieldName::new("checksum"),
  /// ])]);
  /// assert_eq!(CLIP.composite_uniques().len(), 1);
  /// ```
  ///
  /// # A CITIZEN WITH NO VALUE LEAVES is refused, rather than rendered as nothing
  ///
  /// An entry that resolves to a citizen contributes that citizen's value leaves, and a citizen
  /// whose every leaf is derived has none — see [`CompositeUnique`], where the exclusion and its
  /// reason are. Rendering it would emit a statement naming fewer columns than the author wrote, or
  /// none at all; so the descriptor refuses it, and the sentence says which of the two facts is
  /// wrong.
  ///
  /// # AN EXACT DUPLICATE IS REFUSED, and it is never deduplicated
  ///
  /// Two declarations of the same constraint derive the SAME NAME, and the second `CREATE UNIQUE
  /// INDEX IF NOT EXISTS` over it is a statement the engine discards — a silent no-op, which is
  /// exactly the outcome an author who wrote the constraint twice needs told about. So the
  /// collision is the tell and it is refused here, in both directions it can arrive:
  ///
  ///   * TWO COMPOSITES naming the same entries in the same order;
  ///   * A SINGLE-ENTRY COMPOSITE naming a column [`uniques`](Self::uniques) already names — the two
  ///     roads meeting on one column, which derives `__ig_<table>_<column>` from either road.
  ///
  /// A different ORDER is a different constraint and collides with neither: `(a, b)` and `(b, a)`
  /// derive different names and serve different seeks. See [`CompositeUnique`], where the order's
  /// own meaning is stated.
  ///
  /// ```compile_fail,E0080
  /// use ingraph::{Column, CompositeUnique, FieldName, RecordAddress, Table};
  ///
  /// const ASSET: Table = Table::new(
  ///   RecordAddress::new(FieldName::new("asset"), &[FieldName::new("id")]),
  ///   &[
  ///     Column::new(FieldName::new("id"), "INTEGER", false),
  ///     Column::new(FieldName::new("checksum"), "TEXT", false),
  ///   ],
  /// )
  /// .with_uniques(&[FieldName::new("checksum")])
  /// .with_composite_uniques(&[CompositeUnique::new(&[FieldName::new("checksum")])]);
  /// ```
  #[must_use]
  pub const fn with_composite_uniques(mut self, composites: &'static [CompositeUnique]) -> Self {
    let mut which = 0;
    while which < composites.len() {
      let entries = composites[which].entries();
      let mut at = 0;
      while at < entries.len() {
        let width = constrained_width(self.columns, entries[at]);
        assert!(
          width != usize::MAX,
          "a composite unique names the table's own entries — an entry this table carries neither \
           as a column nor as a citizen is a constraint over one nothing declared"
        );
        assert!(
          width > 0,
          "a composite unique constrains a citizen's VALUE leaves, and this entry names a citizen \
           that has none — a derived leaf is computed beside the value and constrains nothing"
        );
        at += 1;
      }
      // The SAME NAME from an earlier declaration, by either road. Both loops run over what is
      // already settled — `uniques` because the chain order says so, and the composites before this
      // one because a list is checked front to back — so each collision is reported once, at the
      // second spelling of it.
      if entries.len() == 1 {
        let mut other = 0;
        while other < self.uniques.len() {
          assert!(
            !self.uniques[other].is(entries[0].as_str()),
            "this column is `unique` already, and a one-entry composite over it derives the same \
             constraint name — one of the two spellings is the one to keep"
          );
          other += 1;
        }
      }
      let mut other = 0;
      while other < which {
        assert!(
          !same_entries(composites[other].entries(), entries),
          "two composite uniques name the same entries in the same order, so both derive one \
           constraint name and the second creates nothing"
        );
        other += 1;
      }
      which += 1;
    }
    self.composites = composites;
    self
  }

  /// The same table with the second tables its collections are stored in.
  ///
  /// A collection column named here is NOT among [`columns`](Self::columns), which is the partition
  /// [`SqlQuery::COLLECTIONS`](crate::query::sql::SqlQuery::COLLECTIONS) already draws from the
  /// query side: a gathered column has no value on the parent row, so a `CREATE TABLE` that named
  /// one would declare a column no statement ever writes.
  #[inline]
  #[must_use]
  pub const fn with_edges(mut self, edges: &'static [EdgeTable]) -> Self {
    self.edges = edges;
    self
  }

  /// The same table with the VALUE-LED access path over each named COLLECTION COLUMN —
  /// [`EdgeTable::indexed`]'s other half, for the dialect that keeps a collection in a column of the
  /// row instead of in a second table.
  ///
  /// ```sql
  /// CREATE INDEX IF NOT EXISTS "__ig_clip_tags_value" ON "clip" USING GIN ("tags")
  /// ```
  ///
  /// # ONE word, two storage forms, and the NAME is the same string in both
  ///
  /// An edge table's name IS the row's table run together with the column's path, so the index this
  /// list renders and the one [`EdgeTable::indexed`] renders for the same collection derive the
  /// SAME identifier — `__ig_clip_tags_value` whether `clip.tags` is a second table or an array
  /// column. That is not a coincidence to be worked around: a collection has ONE containment index
  /// in whichever database is holding it, and a reader looking at two catalogues sees one name.
  ///
  /// # A dialect with NO array column renders nothing for this list
  ///
  /// The access method is [`AsyncSchemaDialect::COLLECTION_INDEX`](crate::query::sql::AsyncSchemaDialect::COLLECTION_INDEX)
  /// and it is `None` on the two dialects that have no array type — where every collection is
  /// already a second table, so a descriptor for them carries no such column to name and this list
  /// is empty by construction. The precedent for a dialect dropping an index it cannot make is
  /// [`AsyncSchemaDialect::SORT_KEY_INDEX`](crate::query::sql::AsyncSchemaDialect::SORT_KEY_INDEX),
  /// where MySQL's `ERROR 1170` is measured.
  ///
  /// # Every named collection is one of THIS table's OWN columns, and that is checked here
  ///
  /// [`with_indexes`](Self::with_indexes)' own check, for its reason: the statement names the column
  /// directly, so a field this table does not carry is an index over one no `CREATE TABLE` declared.
  ///
  /// ```compile_fail,E0080
  /// use ingraph::{Column, FieldName, RecordAddress, Table};
  ///
  /// const CLIP: Table = Table::new(
  ///   RecordAddress::new(FieldName::new("clip"), &[FieldName::new("id")]),
  ///   &[Column::new(FieldName::new("id"), "bigint", false)],
  /// )
  /// .with_collection_indexes(&[FieldName::new("tags")]);
  /// ```
  ///
  /// Its positive twin, for the reason [`EdgeTable::new`]'s pair carries one:
  ///
  /// ```
  /// use ingraph::{Column, FieldName, RecordAddress, Table};
  ///
  /// const CLIP: Table = Table::new(
  ///   RecordAddress::new(FieldName::new("clip"), &[FieldName::new("id")]),
  ///   &[
  ///     Column::new(FieldName::new("id"), "bigint", false),
  ///     Column::new(FieldName::new("tags"), "text[]", false),
  ///   ],
  /// )
  /// .with_collection_indexes(&[FieldName::new("tags")]);
  /// assert_eq!(CLIP.collection_indexes().len(), 1);
  /// ```
  #[must_use]
  pub const fn with_collection_indexes(
    mut self,
    collections: &'static [&'static FieldName],
  ) -> Self {
    let mut at = 0;
    while at < collections.len() {
      assert!(
        declares(self.columns, collections[at]),
        "an indexed collection column is one of the table's own columns — the statement names the \
         column directly, so a field this table does not carry is an index over one nothing \
         declared. A collection this database keeps in a SECOND TABLE is `EdgeTable::indexed`"
      );
      at += 1;
    }
    self.collection_indexes = collections;
    self
  }

  /// The same table with an ORDER-PRESERVING COMPANION COLUMN per `sortable` collection — see
  /// [`Shadow`].
  ///
  /// # Every companion names one of THIS table's edge tables, and that is checked here
  ///
  /// A companion is the order of a collection kept in a table of its own, so a path naming no edge
  /// table of this row is a column that mirrors nothing: the write lane would have no elements to
  /// encode and the `ORDER BY` would order by whatever was last written into it. The refusal lands
  /// where the descriptor is written:
  ///
  /// ```compile_fail,E0080
  /// use ingraph::{Column, FieldName, RecordAddress, Shadow, Table};
  ///
  /// const CLIP: Table = Table::new(
  ///   RecordAddress::new(FieldName::new("clip"), &[FieldName::new("id")]),
  ///   &[Column::new(FieldName::new("id"), "INTEGER", false)],
  /// )
  /// .with_shadows(&[Shadow::new(
  ///   FieldName::new("__ig_tags_sort__"),
  ///   &[FieldName::new("tags")],
  /// )]);
  /// ```
  ///
  /// Its positive twin, for the reason [`EdgeTable::new`]'s pair carries one — and the shape a
  /// `sortable` collection's descriptor actually takes, both halves together:
  ///
  /// ```
  /// use ingraph::{Column, EdgeShape, EdgeTable, FieldName, RecordAddress, Shadow, Table};
  ///
  /// const CLIP: Table = Table::new(
  ///   RecordAddress::new(FieldName::new("clip"), &[FieldName::new("id")]),
  ///   &[Column::new(FieldName::new("id"), "INTEGER", false)],
  /// )
  /// .with_edges(&[EdgeTable::new(
  ///   &[FieldName::new("tags")],
  ///   EdgeShape::Sequence,
  ///   "TEXT",
  /// )])
  /// .with_shadows(&[Shadow::new(
  ///   FieldName::new("__ig_tags_sort__"),
  ///   &[FieldName::new("tags")],
  /// )]);
  /// assert_eq!(CLIP.shadows().len(), 1);
  /// ```
  ///
  /// The ORDER of the two calls does not matter — the check reads `self.edges`, which
  /// [`new`](Self::new) leaves empty, so a `with_shadows` written first refuses for the same reason
  /// a companion naming a scalar column does. That is the honest failure: a descriptor whose two
  /// halves are stated in either order is one a reader can write from memory, and the one shape that
  /// cannot be spelled is a companion with no collection.
  #[must_use]
  pub const fn with_shadows(mut self, shadows: &'static [Shadow]) -> Self {
    let mut at = 0;
    while at < shadows.len() {
      assert!(
        mirrors(self.edges, shadows[at].path()),
        "a companion column is the ORDER of one of this table's collections — its path names no \
         edge table here, so there would be nothing to encode into it"
      );
      at += 1;
    }
    self.shadows = shadows;
    self
  }

  /// The same table under the SPLIT LAYOUT: `source` names the discriminant column, and `sides`
  /// are the provenance tables one variant's ancestors go in apiece.
  ///
  /// # The discriminant is one of the table's OWN columns
  ///
  /// It is stored, selected, bound and read back like every other column, so it is declared like
  /// every other column and this names WHICH of them it is. A second, appended column would be one
  /// the row's own list does not carry — and [`describes`] holds that list against the query
  /// layer's, so the drift would be a compile error one direction and an unwritable column the
  /// other.
  ///
  /// # Both halves at once, because a layout is not half a layout
  ///
  /// A discriminant with no provenance table names a row whose ancestry is stored nowhere; a
  /// provenance table with no discriminant leaves a reader to open each of them in turn to find
  /// out which one holds the row. Neither is a state a descriptor should be able to spell, so both
  /// arrive in one call and each is refused where it is written:
  ///
  /// ```compile_fail,E0080
  /// use ingraph::{Column, FieldName, RecordAddress, Table};
  ///
  /// const CLIP: Table = Table::new(
  ///   RecordAddress::new(FieldName::new("clip"), &[FieldName::new("id")]),
  ///   &[Column::new(FieldName::new("id"), "INTEGER", false)],
  /// )
  /// .with_provenance(FieldName::new("__ig_source__"), &[]);
  /// ```
  ///
  /// Its positive twin, for the reason [`EdgeTable::new`]'s pair carries one:
  ///
  /// ```
  /// use ingraph::{Column, FieldName, RecordAddress, SideTable, Table};
  ///
  /// const CLIP: Table = Table::new(
  ///   RecordAddress::new(FieldName::new("clip"), &[FieldName::new("id")]),
  ///   &[
  ///     Column::new(FieldName::new("id"), "INTEGER", false),
  ///     Column::new(FieldName::new("__ig_source__"), "TEXT", false),
  ///   ],
  /// )
  /// .with_provenance(
  ///   FieldName::new("__ig_source__"),
  ///   &[SideTable::new(
  ///     FieldName::new("clip_frame"),
  ///     &[Column::new(FieldName::new("media_id"), "INTEGER", false)],
  ///   )],
  /// );
  /// assert_eq!(CLIP.sides().len(), 1);
  /// ```
  #[must_use]
  pub const fn with_provenance(
    mut self,
    source: &'static FieldName,
    sides: &'static [SideTable],
  ) -> Self {
    assert!(
      !sides.is_empty(),
      "a discriminant names which upstream a row descends from, and a layout with no provenance \
       table stores that upstream's ancestors nowhere"
    );
    assert!(
      declares(self.columns, source),
      "the discriminant is one of the table's own columns — it is written, selected and read back \
       like any other"
    );
    self.source = Some(source);
    self.sides = sides;
    self
  }

  /// The table this node is stored in, and the key columns identifying one of its rows.
  #[inline]
  #[must_use]
  pub const fn address(&self) -> RecordAddress {
    self.address
  }

  /// Every column of the parent table, in the order the DDL declares them — as the descriptor
  /// STATES them, which is one of two roads.
  ///
  /// [`TableColumns`] is where the two are, and a caller that wants one of them says which:
  /// [`flat`](TableColumns::flat) for the names a hand-written descriptor carries,
  /// [`shapes`](TableColumns::shapes) for the fields an emitted one hands over. What both answer is
  /// [`width`](TableColumns::width), which is the question a caller counting columns is asking.
  #[inline]
  #[must_use]
  pub const fn columns(&self) -> TableColumns {
    self.columns
  }

  /// The fields a PLAIN index is created over, one apiece.
  ///
  /// A field named ALSO in [`uniques`](Self::uniques) still appears here — this list is what was
  /// DECLARED — and it is [`Table::create`] that reads the two together and renders the one
  /// statement the pair implies.
  #[inline]
  #[must_use]
  pub const fn indexes(&self) -> &'static [&'static FieldName] {
    self.indexes
  }

  /// The fields a UNIQUE index constrains, one apiece.
  #[inline]
  #[must_use]
  pub const fn uniques(&self) -> &'static [&'static FieldName] {
    self.uniques
  }

  /// The COMPOSITE unique constraints, each over the entries it names.
  ///
  /// Held apart from [`uniques`](Self::uniques) rather than folded into it, because the two carry
  /// different things: that list is one column apiece, and an entry here may be a citizen the
  /// renderer fans. See [`CompositeUnique`].
  #[inline]
  #[must_use]
  pub const fn composite_uniques(&self) -> &'static [CompositeUnique] {
    self.composites
  }

  /// The second tables this node's collections are stored in.
  #[inline]
  #[must_use]
  pub const fn edges(&self) -> &'static [EdgeTable] {
    self.edges
  }

  /// The COLLECTION COLUMNS of this row that take the value-led containment index — see
  /// [`with_collection_indexes`](Self::with_collection_indexes).
  ///
  /// Empty on every dialect with no array type, where a collection is a second table and the word
  /// lands on [`EdgeTable::indexed`] instead.
  #[inline]
  #[must_use]
  pub const fn collection_indexes(&self) -> &'static [&'static FieldName] {
    self.collection_indexes
  }

  /// The order-preserving companion columns this node's `sortable` collections are mirrored into —
  /// empty for a node that declared none, which is every node written before the word existed.
  #[inline]
  #[must_use]
  pub const fn shadows(&self) -> &'static [Shadow] {
    self.shadows
  }

  /// The discriminant column, where the layout carries one — one of [`columns`](Self::columns), and
  /// which of them a row's upstream is read out of.
  #[inline]
  #[must_use]
  pub const fn source(&self) -> Option<&'static FieldName> {
    self.source
  }

  /// The provenance tables one variant's ancestors go in apiece — empty for a node whose ancestry
  /// is columns of its own row.
  #[inline]
  #[must_use]
  pub const fn sides(&self) -> &'static [SideTable] {
    self.sides
  }

  /// The column a row is identified by — the key's LAST, `key = lineage ⊕ id` being root-first.
  ///
  /// The one column a provenance table points back at, and the one the schema declares `UNIQUE` so
  /// that it can: a foreign key names a parent column the parent table constrains uniquely, and
  /// [`create`](Table::create)'s own `UNIQUE (<id>)` is what makes that true for a lineage-bearing
  /// record. A ROOT's key is its id, so the primary key already carries it.
  #[inline]
  #[must_use]
  pub const fn id(&self) -> &'static FieldName {
    let keys = self.address.keys();
    keys[keys.len() - 1]
  }

  /// The type this database stores `column` at.
  ///
  /// Infallible, and [`new`](Self::new) is what makes it so for the one caller that has to be sure:
  /// the DDL asks this for every KEY column, and a key naming a column the table does not carry is
  /// refused in a `const` before any rendering. A column that is neither a key nor one of the
  /// table's own has no type to answer with, and asking is the caller's error rather than the
  /// table's.
  ///
  /// A SHAPED descriptor answers the same question through the join rather than through a name it
  /// carries: the column is compared against what each field's segments run together into, by
  /// [`joins`](crate::joins), and the word is the one its field states for that leaf. So a key
  /// column that is a SEGMENT — `tb_num` under a `tb` — is answered exactly as a top-level field is.
  ///
  /// # Panics
  ///
  /// Where `column` is not one of [`columns`](Self::columns).
  #[must_use]
  pub const fn stored(&self, column: &FieldName) -> &'static str {
    match self.columns {
      TableColumns::Flat(columns) => {
        let mut at = 0;
        while at < columns.len() {
          if columns[at].name.is(column.as_str()) {
            return columns[at].ty;
          }
          at += 1;
        }
      }
      TableColumns::Shaped {
        shapes,
        words,
        nulls: _,
      } => {
        let ordinal = leaf_named(shapes, None, 0, column);
        if ordinal != usize::MAX {
          return word_at(shapes, words, ordinal);
        }
      }
    }
    panic!("this table carries no such column")
  }
}

/// Whether the columns `columns` states carry one called `name` — the key-coverage test
/// [`Table::stating`] runs and the own-columns test its three `with_` members run, in a `const`.
///
/// The two roads answer it differently and neither builds a name: a FLAT descriptor compares the
/// name it carries, and a SHAPED one compares against the JOINED form through
/// [`joins`](crate::joins) — the `const` family's whole knowledge of the join, which is a comparison
/// and not a concatenation.
const fn declares(columns: TableColumns, name: &FieldName) -> bool {
  match columns {
    TableColumns::Flat(flat) => carries(flat, name),
    TableColumns::Shaped { shapes, .. } => leaf_named(shapes, None, 0, name) != usize::MAX,
  }
}

/// HOW MANY COLUMNS a composite unique's entry constrains — `usize::MAX` where the descriptor
/// carries no such entry at all, which is the sentinel [`leaf_named`] already uses for its reason.
///
/// The two answers a found entry can give are what [`CompositeUnique`] states: a LEAF is one
/// column, and a CITIZEN is its VALUE leaves — [`value_width`](crate::value_width), which excludes
/// the derived ones. Zero is therefore reachable and is NOT absence: it is a citizen every leaf of
/// which is derived, and [`Table::with_composite_uniques`] refuses it in its own sentence.
///
/// # It is [`leaf_named`]'s walk with the composite arm answering for ITSELF
///
/// That walk descends THROUGH a composite looking for one of its leaves; this one asks the
/// composite first, because an entry naming `span` is naming the citizen and not a column beneath
/// it. Where the composite does not answer, the descent is the same — so a name that is a leaf is
/// found identically by both, and the two cannot disagree about which columns exist.
///
/// This is the CONST half of a rule spent twice; the renderer's half is `constrained_leaves` beside
/// [`Table::create`], and the two walk the same order for the same reason [`leaf_named`]'s note
/// gives: a `const fn` takes no closure, so the descent is written twice and the agreement is
/// pinned by a test rather than by sharing.
const fn constrained_width(columns: TableColumns, name: &FieldName) -> usize {
  match columns {
    TableColumns::Flat(flat) => {
      if carries(flat, name) {
        1
      } else {
        usize::MAX
      }
    }
    TableColumns::Shaped { shapes, .. } => shaped_constrained_width(shapes, None, name),
  }
}

/// [`constrained_width`]'s recursion over a shaped descriptor's own segments.
const fn shaped_constrained_width(
  shapes: &[ColumnShape],
  under: Option<&Path<'_>>,
  name: &FieldName,
) -> usize {
  let mut which = 0;
  while which < shapes.len() {
    match shapes[which] {
      // A LEAF answers for one column, and all three leaf words are one: an entry naming a derived
      // leaf DIRECTLY has named a column of this table, which is a different act from a citizen
      // fanning to its own — see `CompositeUnique`, where the two entries are told apart.
      ColumnShape::Plain(field) | ColumnShape::Nullable(field) | ColumnShape::Derived(field) => {
        let path = Path::under(field.stored(), under);
        if crate::joins(&path, name) {
          return 1;
        }
      }
      ColumnShape::Composite {
        field: Some(field),
        segments,
      } => {
        let path = Path::under(field.stored(), under);
        // THE CITIZEN IS ASKED BEFORE ITS LEAVES ARE. A name that is the citizen's own is the
        // citizen, and the descent below is only for a name that is not.
        if crate::joins(&path, name) {
          return crate::value_width(segments);
        }
        let found = shaped_constrained_width(segments, Some(&path), name);
        if found != usize::MAX {
          return found;
        }
      }
      // A FLATTENED citizen lends no name, so there is nothing here for an entry to match — its
      // leaves join the holder's namespace and are matched there, by the names they are rendered
      // under. See `ColumnShape::Composite::field`, where the `None` is the naming knob.
      ColumnShape::Composite {
        field: None,
        segments,
      } => {
        let found = shaped_constrained_width(segments, under, name);
        if found != usize::MAX {
          return found;
        }
      }
    }
    which += 1;
  }
  usize::MAX
}

/// Whether two composite uniques name the SAME entries in the SAME order — the collision
/// [`Table::with_composite_uniques`] refuses, which is exactly when both derive one name.
const fn same_entries(left: &[&FieldName], right: &[&FieldName]) -> bool {
  if left.len() != right.len() {
    return false;
  }
  let mut at = 0;
  while at < left.len() {
    if !left[at].is(right[at].as_str()) {
      return false;
    }
    at += 1;
  }
  true
}

/// Which COLUMN of `shapes` — counted from `at`, the ordinal the walk has reached — joins to
/// `name`, or [`usize::MAX`] where none of them does.
///
/// The sentinel is what a `const fn` has instead of `?` — [`described`]'s own, for its reason — and
/// a column ordinal cannot reach it.
///
/// A FLATTENED field passes `under` along unchanged, which is the same descent
/// [`described`] makes and the same one the renderer makes: three walks, one rule.
const fn leaf_named(
  shapes: &[ColumnShape],
  under: Option<&Path<'_>>,
  mut at: usize,
  name: &FieldName,
) -> usize {
  let mut which = 0;
  while which < shapes.len() {
    match shapes[which] {
      // A key may name a derived leaf exactly as it may name any other column: this answers WHICH
      // column a name is, and all three leaf words are one.
      ColumnShape::Plain(field) | ColumnShape::Nullable(field) | ColumnShape::Derived(field) => {
        let path = Path::under(field.stored(), under);
        if crate::joins(&path, name) {
          return at;
        }
        at += 1;
      }
      ColumnShape::Composite {
        field: Some(field),
        segments,
      } => {
        let path = Path::under(field.stored(), under);
        let found = leaf_named(segments, Some(&path), at, name);
        if found != usize::MAX {
          return found;
        }
        at += crate::width(segments);
      }
      ColumnShape::Composite {
        field: None,
        segments,
      } => {
        let found = leaf_named(segments, under, at, name);
        if found != usize::MAX {
          return found;
        }
        at += crate::width(segments);
      }
    }
    which += 1;
  }
  usize::MAX
}

/// The word the `ordinal`th COLUMN of a shaped descriptor is stored at.
///
/// The words are by FIELD and the ordinal is by COLUMN, so the field is found by running the widths
/// up — and [`Table::shaped`] is what makes the index inside it safe, having asserted that a field's
/// word count IS its width.
///
/// # Panics
///
/// Where `ordinal` is past the row's own width, which is [`leaf_named`]'s sentinel unchecked — both
/// callers check it.
const fn word_at(
  shapes: &[ColumnShape],
  words: &[&'static [&'static str]],
  ordinal: usize,
) -> &'static str {
  let mut at = 0;
  let mut base = 0;
  while at < shapes.len() {
    let width = shapes[at].width();
    if ordinal < base + width {
      return words[at][ordinal - base];
    }
    base += width;
    at += 1;
  }
  panic!("this shaped table renders no column at that ordinal")
}

/// Whether `edges` holds a table at exactly `path` — the join a companion column is checked by.
///
/// Segment by segment, because a path is what an edge table is NAMED from: two composites of one row
/// may each carry a `tags` field, and a companion matched on the last segment alone would be the
/// order of whichever of them was declared first.
const fn mirrors(edges: &[EdgeTable], path: &[&FieldName]) -> bool {
  let mut at = 0;
  while at < edges.len() {
    let declared = edges[at].path();
    if declared.len() == path.len() {
      let mut segment = 0;
      while segment < declared.len() && declared[segment].is(path[segment].as_str()) {
        segment += 1;
      }
      if segment == declared.len() {
        return true;
      }
    }
    at += 1;
  }
  false
}

/// Whether `columns` holds a column called `name` — [`declares`]'s FLAT arm, where the descriptor
/// carries the name and the comparison is over it.
const fn carries(columns: &[Column], name: &FieldName) -> bool {
  let mut at = 0;
  while at < columns.len() {
    if columns[at].name.is(name.as_str()) {
      return true;
    }
    at += 1;
  }
  false
}

/// Whether `table`'s columns are exactly what `columns` names, in order — the audit a descriptor
/// states against the row it describes.
///
/// # It is the one restatement this module makes, so it is the one it checks
///
/// A descriptor carries a column's stored TYPE, which the query layer does not, so its column list
/// cannot be a projection of [`SqlQuery::COLUMNS`](crate::query::sql::SqlQuery::COLUMNS) — it is a
/// second list with the same names in it. Two lists that agree today are two lists that can drift,
/// and the drift is silent: a `CREATE TABLE` missing a column renders, executes, and fails at the
/// first `INSERT` that names it.
///
/// So the agreement is asserted where the descriptor is written, in a `const`, and a descriptor that
/// has drifted from its row is `E0080` rather than a statement. That is the position
/// [`refers_through`](crate::refers_through) already occupies one family over — a fact known at
/// compile time, checked where it is declared.
///
/// # A FLAT list against a NESTED one, and that is the prefixing rule proved
///
/// A descriptor is the physical table, so its columns are flat and each carries a stored type; the
/// row's list is by FIELD, and a field whose type spans two columns is one entry. What this walk
/// therefore checks is not two lists of the same shape but the JOIN between them — a `tb: Timebase`
/// entry has to be met by a `tb_num` and a `tb_den`, in that order — which is the only compile-time
/// statement anybody makes about the names a `SELECT` will render. See [`joins`](crate::joins),
/// which compares against the joined form without building it.
///
/// # Examples
///
/// ```
/// use ingraph::{Column, ColumnName, ColumnShape, FieldName, RecordAddress, Table, describes};
///
/// const COLUMNS: &[ColumnShape] = &[
///   ColumnShape::Plain(ColumnName::new("id")),
///   ColumnShape::Plain(ColumnName::new("title")),
/// ];
/// const CLIP: Table = Table::new(
///   RecordAddress::new(FieldName::new("clip"), &[FieldName::new("id")]),
///   &[
///     Column::new(FieldName::new("id"), "INTEGER", false),
///     Column::new(FieldName::new("title"), "TEXT", true),
///   ],
/// );
///
/// const _: () = assert!(describes(&CLIP, COLUMNS));
/// const _: () = assert!(!describes(&CLIP, &[ColumnShape::Plain(ColumnName::new("id"))]));
/// ```
///
/// A composite field is met by its PREFIXED columns:
///
/// ```
/// use ingraph::{Column, ColumnName, ColumnShape, FieldName, RecordAddress, Table, describes};
///
/// const TIMEBASE: &[ColumnShape] = &[
///   ColumnShape::Plain(ColumnName::new("num")),
///   ColumnShape::Plain(ColumnName::new("den")),
/// ];
/// const COLUMNS: &[ColumnShape] = &[
///   ColumnShape::Plain(ColumnName::new("id")),
///   ColumnShape::Composite { field: Some(ColumnName::new("tb")), segments: TIMEBASE },
/// ];
/// const CLIP: Table = Table::new(
///   RecordAddress::new(FieldName::new("clip"), &[FieldName::new("id")]),
///   &[
///     Column::new(FieldName::new("id"), "INTEGER", false),
///     Column::new(FieldName::new("tb_num"), "INTEGER", false),
///     Column::new(FieldName::new("tb_den"), "INTEGER", false),
///   ],
/// );
///
/// const _: () = assert!(describes(&CLIP, COLUMNS));
/// ```
///
/// # A SHAPED descriptor makes no restatement, so what is checked is that it holds the SAME LIST
///
/// [`Table::shaped`] takes the row's shapes rather than a flat list with the names joined into it,
/// so the drift this audit exists to catch — one list growing a column the other has not — cannot be
/// spelled by writing a name wrongly. What CAN still be spelled is a descriptor built from a
/// DIFFERENT list, which is what an emission minting two of them would produce, so the comparison is
/// over the shapes themselves: same fields, same nesting, both of each field's names.
///
/// ```
/// use ingraph::{ColumnName, ColumnShape, FieldName, RecordAddress, Table, describes};
///
/// const COLUMNS: &[ColumnShape] = &[
///   ColumnShape::Plain(ColumnName::new("id")),
///   ColumnShape::Composite {
///     field: Some(ColumnName::new("tb")),
///     segments: &[ColumnShape::Plain(ColumnName::new("num"))],
///   },
/// ];
/// const CLIP: Table = Table::shaped(
///   RecordAddress::new(FieldName::new("clip"), &[FieldName::new("id")]),
///   COLUMNS,
///   &[&["INTEGER"], &["INTEGER"]],
///   &[false, false],
/// );
///
/// const _: () = assert!(describes(&CLIP, COLUMNS));
/// const _: () = assert!(!describes(&CLIP, &[ColumnShape::Plain(ColumnName::new("id"))]));
/// ```
#[must_use]
pub const fn describes(table: &Table, columns: &[ColumnShape]) -> bool {
  match table.columns {
    TableColumns::Flat(stored) => {
      if stored.len() != crate::width(columns) {
        return false;
      }
      described(stored, columns, None, 0) == stored.len()
    }
    TableColumns::Shaped { shapes, .. } => same_shapes(shapes, columns),
  }
}

/// Whether two shape lists are the SAME LIST — [`describes`]'s shaped arm.
///
/// Structural rather than by the columns the two RENDER, and the difference is spellable: a flat
/// `Plain("tb_num")` renders what a `Composite("tb")` over a `Plain("num")` renders, and a shaped
/// descriptor holding the first where the row publishes the second is two lists that agree about
/// their columns and disagree about their fields. The write lane binds by FIELD, so that is a drift
/// and this reports it.
///
/// Both of a [`ColumnName`](crate::ColumnName)'s halves are compared: the declared name is what a
/// reverse relation looks a column up by, so a descriptor that agreed only about the stored half
/// would be one a `<db>(rename = "…")` could move under.
///
/// # ONE ARM PER LEAF WORD, and `_ => false` means CROSS-VARIANT and nothing else
///
/// [`ColumnShape`] has three leaf words and they are three different facts about a column — whether
/// it is part of the VALUE, and whether its own arithmetic may decline. The comparison is therefore
/// *same word, same name*: a `Plain("at")` and a `Nullable("at")` render one column under one name
/// and are NOT one shape, because the DDL writes `NOT NULL` over one of them and not the other, and
/// because every structural reader in the crate walks value leaves only.
///
/// The fallthrough is what the shape of the match says it is: a pair whose two sides took different
/// words. It was ALSO, until this arm roster was completed, the answer for two identical
/// [`Nullable`](ColumnShape::Nullable) leaves and two identical [`Derived`](ColumnShape::Derived)
/// ones — so [`describes`] reported drift against a descriptor built from the very list the row
/// publishes, wherever that row carried a derived leaf. `MediaTimestamp` and `BoundingBox` are both
/// such rows, which is the whole reach of the defect: an audit that answered *these are two
/// different lists* about one list.
const fn same_shapes(left: &[ColumnShape], right: &[ColumnShape]) -> bool {
  if left.len() != right.len() {
    return false;
  }
  let mut at = 0;
  while at < left.len() {
    match (left[at], right[at]) {
      // The VALUE leaf.
      (ColumnShape::Plain(one), ColumnShape::Plain(two)) => {
        if !same_name(one, two) {
          return false;
        }
      }
      // The INDEX leaf whose computation may DECLINE — nullable whatever its field is declared.
      (ColumnShape::Nullable(one), ColumnShape::Nullable(two)) => {
        if !same_name(one, two) {
          return false;
        }
      }
      // The INDEX leaf whose computation is TOTAL — the one the DDL writes `NOT NULL` over.
      (ColumnShape::Derived(one), ColumnShape::Derived(two)) => {
        if !same_name(one, two) {
          return false;
        }
      }
      (
        ColumnShape::Composite {
          field: Some(one),
          segments: ours,
        },
        ColumnShape::Composite {
          field: Some(two),
          segments: theirs,
        },
      ) => {
        if !same_name(one, two) || !same_shapes(ours, theirs) {
          return false;
        }
      }
      (
        ColumnShape::Composite {
          field: None,
          segments: ours,
        },
        ColumnShape::Composite {
          field: None,
          segments: theirs,
        },
      ) => {
        if !same_shapes(ours, theirs) {
          return false;
        }
      }
      _ => return false,
    }
    at += 1;
  }
  true
}

/// Whether two column names are one name, in BOTH of the spellings a [`ColumnName`](crate::ColumnName)
/// carries — [`PartialEq`] said in a `const`, which the derive cannot be called in.
const fn same_name(left: crate::ColumnName, right: crate::ColumnName) -> bool {
  left.declared().is(right.declared().as_str()) && left.stored().is(right.stored().as_str())
}

/// [`describes`]'s walk: how many of `stored` — starting at `at` — the shapes in `columns` account
/// for, or [`usize::MAX`] where one of them does not.
///
/// The sentinel is what a `const fn` has instead of `?`: [`Option`] is constructible in one, but
/// matching it back out at every level is more machinery than the one saturating comparison the
/// caller already makes. A count that has run past the list can only be this value.
const fn described(
  stored: &[Column],
  columns: &[ColumnShape],
  under: Option<&Path<'_>>,
  mut at: usize,
) -> usize {
  let mut which = 0;
  while which < columns.len() {
    match columns[which] {
      // All three leaf words are audited against the flat restatement: a hand-written descriptor
      // states one `Column` per COLUMN, and a derived one is a column under either of its words.
      ColumnShape::Plain(field) | ColumnShape::Nullable(field) | ColumnShape::Derived(field) => {
        if at >= stored.len() {
          return usize::MAX;
        }
        let path = Path::under(field.stored(), under);
        if !crate::joins(&path, stored[at].name) {
          return usize::MAX;
        }
        at += 1;
      }
      ColumnShape::Composite {
        field: Some(field),
        segments,
      } => {
        let path = Path::under(field.stored(), under);
        at = described(stored, segments, Some(&path), at);
        if at == usize::MAX {
          return usize::MAX;
        }
      }
      // A flattened field lends no name, so its segments are audited against the holder's own
      // namespace — the same walk one prefix shorter, which is exactly what the renderer does.
      ColumnShape::Composite {
        field: None,
        segments,
      } => {
        at = described(stored, segments, under, at);
        if at == usize::MAX {
          return usize::MAX;
        }
      }
    }
    which += 1;
  }
  at
}

/// What ONE node's storage looks like in `Db` — the per-type, per-TARGET self-description a walk
/// hands to a visitor.
///
/// # The parameter is the TARGET, and one impl names each
///
/// A node stored in three databases has three descriptors: the column names may be renamed per
/// database, the type each is stored at certainly differs, and which collections take an edge table
/// is the dialect's own answer. No single associated type selects among those, so the target is
/// what the trait is parameterised by — the arrangement [`Record<B>`](crate::Record) already has,
/// one trait over, and for the same reason.
///
/// # WHAT a description is, is the TARGET's own answer
///
/// `Db: Habitat`, and [`Blueprint`](Habitat::Blueprint) is what the target says a home looks like:
/// a [`Table`] for a SQL dialect, the corpora a declaration owns for a full-text mount, the
/// coordinate slots for a vector one. A record's descriptor is therefore unchanged in every member
/// — only the name it is read under moved, from `TABLE` to
/// [`BLUEPRINT`](Self::BLUEPRINT) — and the engine kinds join with descriptors of their own rather
/// than by being bent into a table's shape.
///
/// # Absence IS the refusal
///
/// The impl SET states where a node's storage is described, so a node stored in SQLite alone refuses
/// `<Video as Describe<Postgres>>` with `E0277` AT THE BOUND — which is where the walk proves it,
/// once per field of the graph root, rather than somewhere further along.
///
/// # It is EMITTED for a `#[ingraph::record(…)]`, and hand-written for everything else
///
/// A record's expansion writes one of these per declared ∩ compiled-in SQL dialect, built from
/// [`Table::shaped`] over the row's own `SqlQuery::COLUMNS` — so the type each column is stored at,
/// its nullability, its `indexed`/`unique` markers and its collections' edge tables come from the
/// declaration rather than from a second, hand-kept text. What stays hand-written is everything the
/// macro does not declare: a graph node written by hand, and a node persisting into a dialect where
/// one of its collections rides an ARRAY column, which is the one case a blueprint cannot be spelled
/// for (see the note on the diagnostic below).
///
/// **An emitted impl and a hand-written one for the same pair is `E0119`**, and that is the ordinary
/// coherence rule rather than a special refusal: a record that used to carry a hand-written
/// descriptor deletes it when the emission arrives. There is no opt-out word, since a descriptor
/// this crate emits and one an author keeps beside it would be two answers to a question with one.
///
/// # It is the walk's BOUND, and that is the whole of what it is for
///
/// [`TypeVisitor::next_type`](crate::TypeVisitor::next_type) declares it, so every visitor inherits
/// it and every walk site must prove it. A node with no storage description is refused where the
/// INGRAPH is written — which is where it can be fixed — rather than inside whichever visitor
/// reached it first.
///
/// # Examples
///
/// ```
/// use ingraph::{Column, Describe, FieldName, Habitat, RecordAddress, Table};
///
/// struct Sqlite;
/// struct Clip;
///
/// impl Habitat for Sqlite {
///   type Blueprint = Table;
/// }
///
/// impl Describe<Sqlite> for Clip {
///   const BLUEPRINT: Table = Table::new(
///     RecordAddress::new(FieldName::new("clip"), &[FieldName::new("id")]),
///     &[Column::new(FieldName::new("id"), "INTEGER", false)],
///   );
/// }
///
/// fn described_in<Db: Habitat<Blueprint = Table>, E: Describe<Db>>() -> Table {
///   E::BLUEPRINT
/// }
///
/// assert_eq!(
///   described_in::<Sqlite, Clip>().address().table(),
///   FieldName::new("clip")
/// );
/// ```
///
/// A node this target does not store has no descriptor, and the projection is where that is
/// refused:
///
/// ```compile_fail,E0277
/// use ingraph::{Describe, Habitat, Table};
///
/// struct Postgres;
/// struct Cue;
///
/// impl Habitat for Postgres {
///   type Blueprint = Table;
/// }
///
/// fn described_in<Db: Habitat<Blueprint = Table>, E: Describe<Db>>() -> Table {
///   E::BLUEPRINT
/// }
///
/// described_in::<Postgres, Cue>();
/// ```
#[diagnostic::on_unimplemented(
  message = "`{Self}` describes no storage in `{Db}`, so a graph holding it cannot be walked — \
             every field of the root is a node this target knows how to create",
  label = "no blueprint for `{Db}`",
  note = "a node earns one by persisting there: `#[ingraph(persist(…))]`, or by electing a field \
          into a resource: `#[ingraph(searchable, <label>(resource = \"…\"))]`",
  note = "a record that DOES persist there and still has none is holding a collection in a COLUMN \
          — a PostgreSQL array, whose declared spelling and whose catalogue spelling are two \
          different strings, so `StoredAs` has no one word for it and the blueprint is skipped \
          rather than guessed. `postgres(edge)` puts the collection in a second table and the \
          blueprint lands"
)]
pub trait Describe<Db: Habitat> {
  /// This node's home in `Db`, in whatever vocabulary that target describes one.
  ///
  /// A `const` rather than a function, because there is nothing to compute: a schema is declared,
  /// and every part of the descriptor is `&'static`. What that buys is the property the whole module
  /// rests on — a descriptor is an ITEM, so the audits over it run at compile time and nothing
  /// builds one per boot.
  ///
  /// It is also why an author's per-slot KNOBS are not in here. A tokenizer or an `ef` is a value a
  /// DEPLOYMENT decides, arriving at boot, and a `const` is exactly the wrong place for one; they
  /// live on the visitor's own per-slot table — see [`Habitat`]'s note.
  const BLUEPRINT: Db::Blueprint;
}

#[cfg(test)]
mod tests;