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
//! The statements each verb renders, over a record whose bindings are written BY HAND — and the
//! walk that measures what a statement's text cannot show.
//!
//! # The fixture is hand-written, for [`find`](super::super::find)'s reason
//!
//! `ingraph-codegen` cannot reach this crate, so a test here cannot be an expansion. What it can be
//! is the same thing a third party writes, and for the write lane that is the whole of the new seam:
//! [`SqlWrite`] is implemented here through nothing but its public items, so a member only an
//! emitter could have supplied would not compile in this file.
//!
//! The fixture's `bit_rate` crosses in BOTH directions and can fail in both — `u64` on the record,
//! `i64` on the row — which is what makes *the record reached storage through its declared
//! conversions* a claim the live walk can check rather than a sentence: a lane that bound the
//! record's own field would not typecheck, and one that bound the row's had to have crossed to get
//! it.
//!
//! # TWO fixtures, and the second is the shape the first cannot be
//!
//! `Clip`'s ancestry is columns of its own row. `Caption` is drawn from two INDEPENDENT upstreams,
//! so which ancestor columns a row has depends on which upstream produced it — the split layout —
//! and its two variants are deliberately different widths. What the pair measures is that the two
//! shapes go through one lane: the provenance row rides the same bracket the collections do, and a
//! record with neither writes one statement.
//!
//! # What is asserted where
//!
//! The TEXT and the BIND COUNT are asserted per dialect, in a module apiece, so an assertion whose
//! subject is a dialect runs in the lane that carries only that dialect. What the text cannot show —
//! an edge set appended to rather than replaced, an ordinal that is not the collection's, a row left
//! carrying two ancestries, a parent row left behind by a write that failed part-way — runs live
//! against SQLite, in `mod live`.

#![cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]

use super::{
  EdgeWrite, SideWrite, SqlWrite, Upsert, delete_statements, insert_statement, statements,
  upsert_statement,
};
use crate::{
  Carrier, ColumnName, ColumnShape, ComplexComparison, FieldName, Identifiable, Record,
  RecordAddress, Transformer,
  comparison::{Backend, sql::SqlKeyIn},
  query::sql::{
    CrossingError, ELEMENT, EdgeCollection, EdgeShape, SqlDialect, SqlQuery, distribute,
  },
};

/// A clip inside a media: a two-column key whose ADDRESS is the id alone, a text column, a column
/// whose stored type is not its domain type, and one collection of each SHAPE.
///
/// The two-column key is the same capability pin [`find`](super::super::find)'s fixture carries, and
/// the write lane is where it earns a second keep: an edge table correlates on the whole key, so a
/// delete and every element row bind both columns and the width-one path cannot stand in for them.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Clip {
  media: i64,
  id: i64,
  title: String,
  /// UNSIGNED on the record and signed in the row — the declared crossing, in both directions, and
  /// fallible in both.
  bit_rate: u64,
  /// A SEQUENCE, stored in `clip_tags` as `(media_id, id, tags_ordinal, tags)`.
  tags: Vec<String>,
  /// A SET, stored in `clip_notes` as `(media_id, id, notes)` — no ordinal, because a set's rows are
  /// unique and its order is absent.
  notes: Vec<String>,
}

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

impl Identifiable for Clip {
  type Id = i64;

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

impl Transformer for Clip {
  type Key = ClipKey;
  type Lineage = i64;
  type Record = Self;
  type Graphql = ();

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

/// The stored row: the scalars at the types this database keeps them, and the collections a
/// materialization fills or a write reads.
#[derive(Debug, Clone, PartialEq, Eq)]
struct ClipRow {
  media: i64,
  id: i64,
  title: String,
  bit_rate: i64,
  tags: Vec<String>,
  notes: Vec<String>,
}

/// The row as one statement's row decodes — every scalar by name, and the collections EMPTY, which
/// is the whole of the decode's part in the collapse.
impl<'r, R> sqlx::FromRow<'r, R> for ClipRow
where
  R: sqlx::Row,
  i64: sqlx::Decode<'r, R::Database> + sqlx::Type<R::Database>,
  String: sqlx::Decode<'r, R::Database> + sqlx::Type<R::Database>,
  for<'a> &'a str: sqlx::ColumnIndex<R>,
{
  fn from_row(row: &'r R) -> Result<Self, sqlx::Error> {
    Ok(Self {
      media: row.try_get("media_id")?,
      id: row.try_get("id")?,
      title: row.try_get("title")?,
      bit_rate: row.try_get("bit_rate")?,
      tags: Vec::new(),
      notes: Vec::new(),
    })
  }
}

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

/// Give every page row the tags gathered for it.
fn clip_tags<Db>(page: &mut [ClipRow], gathered: &[Db::Row]) -> Result<(), sqlx::Error>
where
  Db: sqlx::Database,
  for<'r> i64: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'r> String: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
{
  use sqlx::Row as _;
  let element: &str = ELEMENT;
  distribute(
    page,
    gathered,
    |row| (row.media, row.id),
    |row| Ok((row.try_get("media_id")?, row.try_get("id")?)),
    |row| row.try_get::<String, _>(element),
    |row| &mut row.tags,
  )
}

/// The same for the SET, whose gather differs only in what the engine ordered it by.
fn clip_notes<Db>(page: &mut [ClipRow], gathered: &[Db::Row]) -> Result<(), sqlx::Error>
where
  Db: sqlx::Database,
  for<'r> i64: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'r> String: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
{
  use sqlx::Row as _;
  let element: &str = ELEMENT;
  distribute(
    page,
    gathered,
    |row| (row.media, row.id),
    |row| Ok((row.try_get("media_id")?, row.try_get("id")?)),
    |row| row.try_get::<String, _>(element),
    |row| &mut row.notes,
  )
}

/// How many elements the sequence holds — the WRITE plan's half, and the count the engine renders
/// that many value rows for.
fn tags_len(row: &ClipRow) -> usize {
  row.tags.len()
}

/// Bind the sequence's `at`th element. The engine writes the parentheses, the commas and the ordinal
/// beside it.
fn tags_element<Db>(row: &ClipRow, at: usize, qb: &mut sqlx::QueryBuilder<Db>)
where
  Db: sqlx::Database,
  String: Carrier<Db>,
{
  row.tags[at].push_bind(qb);
}

/// The set's count.
fn notes_len(row: &ClipRow) -> usize {
  row.notes.len()
}

/// The set's element, which is bound with no ordinal beside it because its edge table has no column
/// for one.
fn notes_element<Db>(row: &ClipRow, at: usize, qb: &mut sqlx::QueryBuilder<Db>)
where
  Db: sqlx::Database,
  String: Carrier<Db>,
{
  row.notes[at].push_bind(qb);
}

/// The RECORD's vocabulary binding. The comparison is the ADDRESS's own type, which is all this
/// fixture asks a predicate to be: what the write lane spends is the row, the columns and the key,
/// and none of them is a filter.
impl<Db> Record<Db> for Clip
where
  Db: Backend,
{
  type Row = ClipRow;
  type Comparison = SqlKeyIn<i64, Db, 1>;
  // A write fixture is never ordered, so the empty product is the honest binding.
  type OrderBy = ();
}

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

  /// TWO columns, where [`Self::Address`] binds one: this const is what an edge table correlates on,
  /// and it is what the write's delete and its element rows bind.
  const ADDRESS: RecordAddress = RecordAddress::new(
    FieldName::new("clip"),
    &[FieldName::new("media_id"), FieldName::new("id")],
  );
  const ALIASES: &'static [&'static str] = &[
    "__ig_clip_0__",
    "__ig_clip_1__",
    "__ig_clip_2__",
    "__ig_clip_3__",
    "__ig_clip_4__",
    "__ig_clip_5__",
    "__ig_clip_6__",
    "__ig_clip_7__",
  ];
  /// The collections are ABSENT, which is the plan's contract in both directions: they name no
  /// column of `clip`, so neither a `SELECT` nor an `INSERT` over that table may name one.
  const COLUMNS: &'static [ColumnShape] = &[
    ColumnShape::Plain(ColumnName::new("media_id")),
    ColumnShape::Plain(ColumnName::new("id")),
    ColumnShape::Plain(ColumnName::new("title")),
    ColumnShape::Plain(ColumnName::new("bit_rate")),
  ];
  const COLLECTIONS: &'static [EdgeCollection<Self, Db>] = &[
    EdgeCollection::gather(
      &[FieldName::new("tags")],
      EdgeShape::Sequence,
      clip_key::<Db>,
      clip_tags::<Db>,
    ),
    EdgeCollection::gather(
      &[FieldName::new("notes")],
      EdgeShape::Set,
      clip_key::<Db>,
      clip_notes::<Db>,
    ),
  ];

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

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

  /// The READ half of the declared crossing: the stored `i64` narrowed back to the record's `u64`,
  /// refusing where it will not fit.
  fn record(self) -> Result<Clip, CrossingError> {
    Ok(Clip {
      media: self.media,
      id: self.id,
      title: self.title,
      bit_rate: u64::try_from(self.bit_rate)?,
      tags: self.tags,
      notes: self.notes,
    })
  }
}

impl<Db> SqlWrite<Db> for ClipRow
where
  Db: Backend + sqlx::Database,
  SqlKeyIn<i64, Db, 1>: ComplexComparison<Db>,
  i64: Carrier<Db>,
  String: Carrier<Db>,
  for<'r> i64: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'r> String: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
{
  /// Both collections, in the order the plan renders their statements — one of each shape, so the
  /// ordinal's presence and its absence both run on every test run.
  const EDGES: &'static [EdgeWrite<Self, Db>] = &[
    EdgeWrite::new(
      &[FieldName::new("tags")],
      EdgeShape::Sequence,
      tags_len,
      tags_element::<Db>,
    ),
    EdgeWrite::new(
      &[FieldName::new("notes")],
      EdgeShape::Set,
      notes_len,
      notes_element::<Db>,
    ),
  ];

  /// The WRITE half of the declared crossing — the dual of [`SqlQuery::record`], refusing at the
  /// same column the other direction refuses at.
  fn row(record: Clip) -> Result<Self, CrossingError> {
    Ok(Self {
      media: record.media,
      id: record.id,
      title: record.title,
      bit_rate: i64::try_from(record.bit_rate)?,
      tags: record.tags,
      notes: record.notes,
    })
  }

  fn bind(&self, at: usize, qb: &mut sqlx::QueryBuilder<Db>) {
    match at {
      0 => self.media.push_bind(qb),
      1 => self.id.push_bind(qb),
      2 => self.title.push_bind(qb),
      _ => self.bit_rate.push_bind(qb),
    }
  }

  fn bind_address(&self, at: usize, qb: &mut sqlx::QueryBuilder<Db>) {
    match at {
      0 => self.media.push_bind(qb),
      _ => self.id.push_bind(qb),
    }
  }
}

/// A caption drawn from two INDEPENDENT upstreams: a uniform payload, its own id, and an ancestry
/// that is a CHOICE among the upstreams rather than a path through one.
///
/// The second fixture in this file, and it earns its place by being the shape the first cannot be: a
/// record whose ancestor columns depend on which upstream produced the row, which is the whole of
/// what the split layout exists for.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Caption {
  id: i64,
  from: CaptionSource,
  text: String,
}

/// The ancestry as a CHOICE — the shape a node several independent upstreams feed takes, and the two
/// variants are deliberately different WIDTHS: a frame is a child of a media and carries two
/// ancestor columns, a speaker turn is a root and carries one.
#[derive(Debug, Clone, PartialEq, Eq)]
enum CaptionSource {
  Frame { media: i64, frame: i64 },
  Turn { turn: i64 },
}

impl CaptionSource {
  /// The WORD — the upstream's own name, which is what the discriminant IS everywhere it is spelled.
  const fn word(&self) -> &'static str {
    match self {
      Self::Frame { .. } => "Frame",
      Self::Turn { .. } => "Turn",
    }
  }
}

/// The key, `lineage ⊕ id`, where the lineage is the choice above.
#[derive(Debug, Clone, PartialEq, Eq)]
struct CaptionKey {
  from: CaptionSource,
  id: i64,
}

impl Identifiable for Caption {
  type Id = i64;

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

impl Transformer for Caption {
  type Key = CaptionKey;
  type Lineage = CaptionSource;
  type Record = Self;
  type Graphql = ();

  fn key(&self) -> CaptionKey {
    CaptionKey {
      from: self.from.clone(),
      id: self.id,
    }
  }
}

/// The stored row. It keeps the ancestry as one value rather than as nullable columns, which is the
/// model half of what the split layout is: the common table holds what every row has, and the
/// provenance table this value selects holds what only rows from that upstream have.
#[derive(Debug, Clone, PartialEq, Eq)]
struct CaptionRow {
  id: i64,
  from: CaptionSource,
  text: String,
}

/// Bind one ancestor of a row that came from a FRAME. The engine writes the statement around it.
fn caption_frame<Db>(row: &CaptionRow, at: usize, qb: &mut sqlx::QueryBuilder<Db>)
where
  Db: sqlx::Database,
  i64: Carrier<Db>,
{
  let CaptionSource::Frame { media, frame } = &row.from else {
    panic!("this plan is reached through `side`, which selects it by the row's own variant")
  };
  match at {
    0 => media.push_bind(qb),
    _ => frame.push_bind(qb),
  }
}

/// The same for a row that came from a TURN, whose ancestry is one column wide.
fn caption_turn<Db>(row: &CaptionRow, _at: usize, qb: &mut sqlx::QueryBuilder<Db>)
where
  Db: sqlx::Database,
  i64: Carrier<Db>,
{
  let CaptionSource::Turn { turn } = &row.from else {
    panic!("this plan is reached through `side`, which selects it by the row's own variant")
  };
  turn.push_bind(qb);
}

impl<Db> Record<Db> for Caption
where
  Db: Backend,
{
  type Row = CaptionRow;
  type Comparison = SqlKeyIn<i64, Db, 1>;
  type OrderBy = ();
}

impl<Db> SqlQuery<Db> for CaptionRow
where
  Db: Backend + sqlx::Database,
  SqlKeyIn<i64, Db, 1>: ComplexComparison<Db>,
  i64: Carrier<Db>,
{
  type Record = Caption;
  type Address = SqlKeyIn<i64, Db, 1>;

  /// ONE column, which is what an M×N node's address is: it mints its own id, and which upstream a
  /// row descends from is beside the payload rather than part of the key.
  const ADDRESS: RecordAddress =
    RecordAddress::new(FieldName::new("caption"), &[FieldName::new("id")]);
  const ALIASES: &'static [&'static str] = &[
    "__ig_caption_0__",
    "__ig_caption_1__",
    "__ig_caption_2__",
    "__ig_caption_3__",
    "__ig_caption_4__",
    "__ig_caption_5__",
    "__ig_caption_6__",
    "__ig_caption_7__",
  ];
  /// The DISCRIMINANT is one of them, so it is selected, bound and created like any other column —
  /// which is the arrangement [`Table::with_provenance`](crate::Table::with_provenance) refuses a
  /// descriptor for not having.
  const COLUMNS: &'static [ColumnShape] = &[
    ColumnShape::Plain(ColumnName::new("id")),
    ColumnShape::Plain(ColumnName::new("__ig_source__")),
    ColumnShape::Plain(ColumnName::new("text")),
  ];

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

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

  fn record(self) -> Result<Caption, CrossingError> {
    Ok(Caption {
      id: self.id,
      from: self.from,
      text: self.text,
    })
  }
}

impl<Db> SqlWrite<Db> for CaptionRow
where
  Db: Backend + sqlx::Database,
  SqlKeyIn<i64, Db, 1>: ComplexComparison<Db>,
  i64: Carrier<Db>,
  String: Carrier<Db>,
{
  /// Both upstreams, in the order the declaration named them — the SHAPE, which is what an `upsert`
  /// clears every one of and what decides the bracket.
  const SIDES: &'static [SideWrite<Self, Db>] = &[
    SideWrite::new(
      FieldName::new("caption_frame"),
      &[FieldName::new("media_id"), FieldName::new("frame")],
      caption_frame::<Db>,
    ),
    SideWrite::new(
      FieldName::new("caption_turn"),
      &[FieldName::new("turn")],
      caption_turn::<Db>,
    ),
  ];

  fn side(&self) -> Option<&'static SideWrite<Self, Db>> {
    Some(match self.from {
      CaptionSource::Frame { .. } => &Self::SIDES[0],
      CaptionSource::Turn { .. } => &Self::SIDES[1],
    })
  }

  fn row(record: Caption) -> Result<Self, CrossingError> {
    Ok(Self {
      id: record.id,
      from: record.from,
      text: record.text,
    })
  }

  /// The discriminant is bound as the WORD the row's own ancestry answers with, so a row and the
  /// provenance table it goes in cannot disagree about which upstream it came from — there is one
  /// value and both read it.
  ///
  /// It goes through [`Carrier`] like every other bind, and the word is `&'static str` where the
  /// table's one text row is `String` — so this fixture owns it for the bind. An emission would too
  /// until the carrier table admits a static string, which nothing has asked it for.
  fn bind(&self, at: usize, qb: &mut sqlx::QueryBuilder<Db>) {
    match at {
      0 => self.id.push_bind(qb),
      1 => self.from.word().to_owned().push_bind(qb),
      _ => self.text.push_bind(qb),
    }
  }

  fn bind_address(&self, _at: usize, qb: &mut sqlx::QueryBuilder<Db>) {
    self.id.push_bind(qb);
  }
}

/// The fan-in's storage IN SQLITE — the common table, the discriminant among its columns, and one
/// provenance table per upstream.
#[cfg(feature = "sqlite")]
impl crate::Describe<sqlx::Sqlite> for Caption {
  const BLUEPRINT: crate::Table = crate::Table::new(
    <CaptionRow as SqlQuery<sqlx::Sqlite>>::ADDRESS,
    &[
      crate::Column::new(FieldName::new("id"), "INTEGER", false),
      crate::Column::new(
        FieldName::new("__ig_source__"),
        <sqlx::Sqlite as crate::query::sql::AsyncSchemaDialect>::DISCRIMINANT,
        false,
      ),
      crate::Column::new(FieldName::new("text"), "TEXT", false),
    ],
  )
  .with_provenance(
    FieldName::new("__ig_source__"),
    &[
      crate::SideTable::new(
        FieldName::new("caption_frame"),
        &[
          crate::Column::new(FieldName::new("media_id"), "INTEGER", false),
          crate::Column::new(FieldName::new("frame"), "INTEGER", false),
        ],
      ),
      crate::SideTable::new(
        FieldName::new("caption_turn"),
        &[crate::Column::new(FieldName::new("turn"), "INTEGER", false)],
      ),
    ],
  );
}

/// The same audit the record above states, over the fan-in — so the common table's column list and
/// the row's `SELECT` list cannot drift, the discriminant included.
#[cfg(feature = "sqlite")]
const _: () = assert!(crate::describes(
  &<Caption as crate::Describe<sqlx::Sqlite>>::BLUEPRINT,
  <CaptionRow as SqlQuery<sqlx::Sqlite>>::COLUMNS
));

/// The record's storage IN SQLITE, stated once — and the same names the bindings above carry.
///
/// It is here rather than in the schema lane's own corpus because of what it lets the LIVE tests
/// below do: they create their tables through the DDL this descriptor renders, so the write lane and
/// the read lane run against a schema no test hand-wrote. A descriptor that named another table, or
/// left a column out, or spelled an edge table differently, is a suite that stops — where a corpus
/// with its own `CREATE TABLE` beside its own bindings can agree with itself and with nothing else.
#[cfg(feature = "sqlite")]
impl crate::Describe<sqlx::Sqlite> for Clip {
  const BLUEPRINT: crate::Table = crate::Table::new(
    <ClipRow as SqlQuery<sqlx::Sqlite>>::ADDRESS,
    &[
      crate::Column::new(FieldName::new("media_id"), "INTEGER", false),
      crate::Column::new(FieldName::new("id"), "INTEGER", false),
      crate::Column::new(FieldName::new("title"), "TEXT", false),
      crate::Column::new(FieldName::new("bit_rate"), "INTEGER", false),
    ],
  )
  .with_edges(&[
    crate::EdgeTable::new(&[FieldName::new("tags")], EdgeShape::Sequence, "TEXT"),
    crate::EdgeTable::new(&[FieldName::new("notes")], EdgeShape::Set, "TEXT"),
  ]);
}

/// The descriptor's column list against the ROW's own, in a `const` — so the two cannot drift apart
/// without the file failing to compile.
#[cfg(feature = "sqlite")]
const _: () = assert!(crate::describes(
  &<Clip as crate::Describe<sqlx::Sqlite>>::BLUEPRINT,
  <ClipRow as SqlQuery<sqlx::Sqlite>>::COLUMNS
));

/// One clip, whichever dialect is about to render it.
fn clip(tags: &[&str], notes: &[&str]) -> Clip {
  Clip {
    media: 1,
    id: 7,
    title: "alpha".to_owned(),
    bit_rate: 320,
    tags: tags.iter().map(|tag| (*tag).to_owned()).collect(),
    notes: notes.iter().map(|note| (*note).to_owned()).collect(),
  }
}

/// One caption, descended from whichever upstream the caller names.
fn caption(from: CaptionSource) -> Caption {
  Caption {
    id: 7,
    from,
    text: "hello".to_owned(),
  }
}

/// The row that caption becomes AT `Db` — the same crossing, over the fixture whose ancestry is a
/// choice.
fn caption_row<Db>(from: CaptionSource) -> CaptionRow
where
  CaptionRow: SqlWrite<Db, Record = Caption>,
  Db: Backend + sqlx::Database,
{
  <CaptionRow as SqlWrite<Db>>::row(caption(from)).expect("this crossing refuses nothing")
}

/// The row that clip becomes AT `Db`, through the crossing every bind below is rendered off.
///
/// Generic in the dialect because the crossing is: a row is one database's, so a rendering assertion
/// names which one produced the value it is about — and this file's only dialect-free line would
/// otherwise be the one that names a dialect.
fn row<Db>(tags: &[&str], notes: &[&str]) -> ClipRow
where
  ClipRow: SqlWrite<Db, Record = Clip>,
  Db: Backend + sqlx::Database,
{
  <ClipRow as SqlWrite<Db>>::row(clip(tags, notes)).expect("a bit rate of 320 is inside `i64`")
}

/// Every statement one write renders, as `(sql, bind count)`.
///
/// The count is half the assertion, for the reason the comparison family's own harness records: the
/// text shows a placeholder and says nothing about what went into it, so a lane that dropped an
/// element or bound one twice renders a string that is byte-identical to the right answer.
fn rendered<Row, Db>(row: &Row, replace: bool) -> Vec<(String, usize)>
where
  Row: SqlWrite<Db>,
  Db: SqlDialect + Upsert,
  i64: Carrier<Db>,
  <Db as sqlx::Database>::Arguments: sqlx::IntoArguments<Db>,
{
  let parent = if replace {
    upsert_statement::<Row, Db>(row)
  } else {
    insert_statement::<Row, Db>(row)
  };
  statements::<Row, Db>(row, parent, replace)
    .expect("the fixture's collections are inside every ceiling")
    .into_iter()
    .map(|mut statement| {
      use sqlx::Execute as _;

      let mut built = statement.build();
      let binds = match built.take_arguments() {
        Ok(Some(arguments)) => sqlx::Arguments::len(&arguments),
        Ok(None) | Err(_) => 0,
      };
      (built.sql().as_str().to_owned(), binds)
    })
    .collect()
}

/// Every statement one REMOVAL renders, as `(sql, bind count)` — [`rendered`]'s twin over the verb
/// that has no row.
///
/// The count matters twice as much here as it does for a store: a delete's predicate is rendered
/// once per statement, so a cascade that forgot to re-bind the filter — or bound it twice — renders
/// text that is byte-identical to the right answer and sends the wrong parameters.
fn removed<Row, Db, P>(filter: &P) -> Vec<(String, usize)>
where
  Row: SqlWrite<Db>,
  Db: SqlDialect,
  P: ComplexComparison<Db>,
  <Db as sqlx::Database>::Arguments: sqlx::IntoArguments<Db>,
{
  delete_statements::<Row, Db, P>(filter)
    .expect("the fixture's filter names a row")
    .into_iter()
    .map(|mut statement| {
      use sqlx::Execute as _;

      let mut built = statement.build();
      let binds = match built.take_arguments() {
        Ok(Some(arguments)) => sqlx::Arguments::len(&arguments),
        Ok(None) | Err(_) => 0,
      };
      (built.sql().as_str().to_owned(), binds)
    })
    .collect()
}

/// The predicate a REMOVAL is asked with in these tests: the rows whose `column` is one of `values`.
///
/// The fixture's comparison is the key membership — see [`Clip`]'s own `Record` impl — so *this one
/// row* and *every row of this media* are the same type asked over a different column, which is
/// exactly the pair the two doors take.
fn matching<Db: Backend>(column: &'static str, values: &[i64]) -> SqlKeyIn<i64, Db, 1> {
  SqlKeyIn::new(
    [column],
    values.iter().map(|value| [*value]).collect::<Vec<_>>(),
  )
}

/// A comparison that CLAIMS a conjunct and renders none — the one shape that reaches the removal's
/// SECOND refusal.
///
/// Not a hypothesis about somebody else's code: `conjuncts` is a number an implementor supplies and
/// `apply` is text an implementor writes, and the pre-render check reads exactly that number. So an
/// over-reporting count walks past it, and what the statement would then be is `DELETE FROM "clip"`
/// with no `WHERE` at all.
struct Overcounting;

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

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

/// The COMPOSITE COLLECTION's own corpus — an element spanning two columns, through both table
/// forms, the write, the gather and a live engine. Its own file for the reason the one below has
/// one: it declares its own record, row and descriptor rather than refining this one's.
mod composite;
/// The FLATTENED composite's own corpus — a field whose type spans two columns, through the DDL, the
/// write, the read and a live engine. Its own file because it declares its own record, row and
/// descriptor rather than refining this one's: the experiment is what a COLUMN LIST can hold, and
/// putting a second shape into `ClipRow` would have made every golden above about two things.
mod flattened;

/// The statements SQLite is sent — and the module the lane's own refusals are pinned in, both of
/// them being dialect-free rules that need one dialect named to be asked.
#[cfg(feature = "sqlite")]
mod sqlite {
  use sqlx::Sqlite;

  use super::{
    CaptionRow, CaptionSource, ClipRow, caption_row, clip, delete_statements, matching, removed,
    rendered, row,
  };
  use crate::{
    comparison::sql::{BindCeiling, SqlKeyIn, SqlLoweringError},
    query::sql::{SqlQuery, SqlWrite, SqlWriteError},
  };

  /// A plain write names every column of the row and binds one value row — and renders NO conflict
  /// clause at all, which is the whole of what makes a taken address the engine's own refusal.
  #[test]
  fn an_insert_names_every_column_and_binds_one_value_row() {
    assert_eq!(
      rendered::<ClipRow, Sqlite>(&row::<Sqlite>(&[], &[]), false),
      [(
        "INSERT INTO \"clip\" (\"media_id\", \"id\", \"title\", \"bit_rate\") VALUES (?, ?, ?, ?)"
          .to_owned(),
        4
      )],
      "a record whose collections are empty is one statement"
    );
  }

  /// The keyed replace names the ADDRESS as its conflict target and assigns every column — one list
  /// read twice, so the assignment set and the insert's own column list cannot disagree.
  ///
  /// The PARENT statement alone: the two deletes behind it are the collections', and what clears an
  /// emptied one is asserted below.
  #[test]
  fn an_upsert_replaces_on_the_address_and_assigns_every_column() {
    assert_eq!(
      rendered::<ClipRow, Sqlite>(&row::<Sqlite>(&[], &[]), true)[0],
      (
        "INSERT INTO \"clip\" (\"media_id\", \"id\", \"title\", \"bit_rate\") VALUES (?, ?, ?, ?) \
         ON CONFLICT (\"media_id\", \"id\") DO UPDATE SET \"media_id\" = \"excluded\".\"media_id\", \
         \"id\" = \"excluded\".\"id\", \"title\" = \"excluded\".\"title\", \
         \"bit_rate\" = \"excluded\".\"bit_rate\""
          .to_owned(),
        4
      ),
      "the conflict target is the address and the assignment list is the row"
    );
  }

  /// A sequence writes its ordinal and a set does not, and both bind the parent's WHOLE key — which
  /// is the same list an edge table's own primary key leads with.
  #[test]
  fn a_sequence_writes_its_ordinal_and_a_set_writes_none() {
    let statements = rendered::<ClipRow, Sqlite>(&row::<Sqlite>(&["a", "b"], &["n"]), false);
    assert_eq!(
      statements.len(),
      3,
      "the parent, then one insert per collection"
    );
    assert_eq!(
      statements[1],
      (
        "INSERT INTO \"clip_tags\" (\"media_id\", \"id\", \"tags_ordinal\", \"tags\") \
         VALUES (?, ?, ?, ?), (?, ?, ?, ?)"
          .to_owned(),
        8
      ),
      "two elements, four binds each: the key twice over, the ordinal and the value"
    );
    assert_eq!(
      statements[2],
      (
        "INSERT INTO \"clip_notes\" (\"media_id\", \"id\", \"notes\") VALUES (?, ?, ?)".to_owned(),
        3
      ),
      "a set's edge table has no ordinal column, so none is named and none is bound"
    );
  }

  /// A replacement REMOVES the parent's edge rows before it writes them, and the delete binds the
  /// same key columns the insert does.
  #[test]
  fn a_replacement_deletes_the_parents_edge_rows_before_it_writes_them() {
    let statements = rendered::<ClipRow, Sqlite>(&row::<Sqlite>(&["a"], &["n"]), true);
    assert_eq!(
      statements.len(),
      5,
      "the parent, then a delete and an insert per collection"
    );
    assert_eq!(
      statements[1],
      (
        "DELETE FROM \"clip_tags\" WHERE \"media_id\" = ? AND \"id\" = ?".to_owned(),
        2
      )
    );
    assert_eq!(
      statements[3],
      (
        "DELETE FROM \"clip_notes\" WHERE \"media_id\" = ? AND \"id\" = ?".to_owned(),
        2
      )
    );
  }

  /// An EMPTY collection writes no row at all — which is what *this parent has no elements* is, and
  /// what a materialization reads back as the empty collection. Its DELETE still runs, because the
  /// parent may have had elements a moment ago.
  #[test]
  fn an_empty_collection_writes_no_edge_row_and_still_clears_the_old_ones() {
    assert_eq!(
      rendered::<ClipRow, Sqlite>(&row::<Sqlite>(&[], &["n"]), false).len(),
      2,
      "the parent and the set — an empty sequence renders nothing"
    );

    let replaced = rendered::<ClipRow, Sqlite>(&row::<Sqlite>(&[], &["n"]), true);
    assert_eq!(replaced.len(), 4, "both deletes run, one insert does not");
    assert_eq!(
      replaced[1].0, "DELETE FROM \"clip_tags\" WHERE \"media_id\" = ? AND \"id\" = ?",
      "an emptied collection is cleared rather than left alone"
    );
  }

  /// A collection whose elements cost more parameters than the dialect binds is REFUSED with the
  /// three numbers, never chunked — the write side of
  /// [`SqlKeyIn`](crate::comparison::sql::SqlKeyIn)'s own doctrine.
  ///
  /// The refusal is reported BEFORE anything runs: the whole sequence renders first, so a plan over
  /// the ceiling costs no write at all rather than a parent row and a rollback.
  #[test]
  fn a_collection_past_the_bind_ceiling_is_refused_rather_than_split() {
    // Four parameters per element — the two key columns, the ordinal and the value — so the ceiling
    // is passed at a quarter of it.
    let elements = <Sqlite as BindCeiling>::MAX_BIND_PARAMETERS / 4 + 1;
    let mut wide = row::<Sqlite>(&[], &[]);
    wide.tags = (0..elements).map(|at| at.to_string()).collect();

    let parent = super::insert_statement::<ClipRow, Sqlite>(&wide);
    let refused = super::statements::<ClipRow, Sqlite>(&wide, parent, false);
    let Err(SqlWriteError::Lowering(SqlLoweringError::BindCeiling(why))) = refused else {
      panic!("a collection past the ceiling is refused rather than chunked");
    };
    assert_eq!(why.keys(), elements);
    assert_eq!(
      why.columns(),
      4,
      "the key's two columns, the ordinal and the value"
    );
    assert_eq!(why.ceiling(), <Sqlite as BindCeiling>::MAX_BIND_PARAMETERS);
  }

  /// A record whose write leg refuses never reaches a statement — the crossing is the only way in,
  /// so a value that cannot cross has nothing rendered for it.
  #[test]
  fn a_record_that_will_not_cross_renders_nothing() {
    let mut record = clip(&[], &[]);
    record.bit_rate = u64::MAX;
    assert!(
      <ClipRow as SqlWrite<Sqlite>>::row(record).is_err(),
      "a bit rate past `i64::MAX` is not this row's column"
    );
  }

  /// The two lists PARTITION the row's stored columns, and the write reads the partition the same
  /// way the read does: a collection names no column of the parent table, so an `INSERT` over it
  /// binds exactly the columns a `SELECT` selects.
  #[test]
  fn the_write_names_the_same_columns_the_read_selects() {
    let bound = <ClipRow as SqlQuery<Sqlite>>::COLUMNS.len();
    assert_eq!(
      rendered::<ClipRow, Sqlite>(&row::<Sqlite>(&["a"], &["n"]), false)[0].1,
      bound
    );
    assert_eq!(
      <ClipRow as SqlWrite<Sqlite>>::EDGES.len(),
      <ClipRow as SqlQuery<Sqlite>>::COLLECTIONS.len(),
      "one write plan entry per collection the read plan materializes"
    );
  }

  /// **The SPLIT LAYOUT's insert**: the common row, then the ONE provenance row its ancestry goes
  /// in. Two statements, and the second is the upstream the row's own lineage names.
  #[test]
  fn a_fan_in_writes_the_common_row_and_the_one_provenance_row() {
    assert_eq!(
      rendered::<CaptionRow, Sqlite>(
        &caption_row::<Sqlite>(CaptionSource::Frame { media: 1, frame: 5 }),
        false
      ),
      [
        (
          "INSERT INTO \"caption\" (\"id\", \"__ig_source__\", \"text\") VALUES (?, ?, ?)"
            .to_owned(),
          3
        ),
        (
          "INSERT INTO \"caption_frame\" (\"id\", \"media_id\", \"frame\") VALUES (?, ?, ?)"
            .to_owned(),
          3
        ),
      ],
      "the id leads the provenance row, then that variant's ancestors"
    );
  }

  /// The OTHER variant renders the other table, at its own width — which is the whole reason the
  /// ancestry is not columns of one table: a turn has one ancestor column and a frame has two.
  #[test]
  fn the_other_upstream_renders_its_own_table_at_its_own_width() {
    assert_eq!(
      rendered::<CaptionRow, Sqlite>(
        &caption_row::<Sqlite>(CaptionSource::Turn { turn: 9 }),
        false
      )[1],
      (
        "INSERT INTO \"caption_turn\" (\"id\", \"turn\") VALUES (?, ?)".to_owned(),
        2
      )
    );
  }

  /// **A replacement clears EVERY provenance table** before writing the one, because a row whose
  /// upstream changed would otherwise keep both ancestries — which is the state the split layout
  /// exists to make unrepresentable.
  #[test]
  fn a_replacement_clears_every_provenance_table_before_it_writes_one() {
    let statements = rendered::<CaptionRow, Sqlite>(
      &caption_row::<Sqlite>(CaptionSource::Turn { turn: 9 }),
      true,
    );
    assert_eq!(
      statements.len(),
      4,
      "the common row, a delete per upstream, and the one insert"
    );
    assert_eq!(
      statements[1],
      (
        "DELETE FROM \"caption_frame\" WHERE \"id\" = ?".to_owned(),
        1
      ),
      "the upstream this row did NOT come from is cleared too"
    );
    assert_eq!(
      statements[2],
      (
        "DELETE FROM \"caption_turn\" WHERE \"id\" = ?".to_owned(),
        1
      ),
      "and so is the one it did, which is what makes the insert after it a replacement"
    );
  }

  /// A record whose ancestry is columns of its own row names no provenance table at all, which is
  /// the default both members carry — and the reason the pair is honest: nothing to name, nothing
  /// named.
  #[test]
  fn a_record_whose_ancestry_is_its_own_columns_writes_no_provenance_row() {
    assert!(<ClipRow as SqlWrite<Sqlite>>::SIDES.is_empty());
    assert!(<ClipRow as SqlWrite<Sqlite>>::side(&row::<Sqlite>(&[], &[])).is_none());
  }

  /// **THE REMOVAL's whole sequence**: every collection's rows, then the rows themselves — the
  /// insert walk read backwards, with the parent LAST because each cascade names its parents by
  /// reading the parent table.
  ///
  /// Each statement carries the filter's own binds, which is what the counts say: one key, one
  /// parameter, three times over.
  #[test]
  fn a_removal_clears_every_collection_before_it_removes_the_rows() {
    assert_eq!(
      removed::<ClipRow, Sqlite, _>(&matching::<Sqlite>("id", &[7])),
      [
        (
          "DELETE FROM \"clip_tags\" WHERE \"id\" IN (SELECT \"id\" FROM \"clip\" \
           WHERE (\"id\") IN ((?)))"
            .to_owned(),
          1
        ),
        (
          "DELETE FROM \"clip_notes\" WHERE \"id\" IN (SELECT \"id\" FROM \"clip\" \
           WHERE (\"id\") IN ((?)))"
            .to_owned(),
          1
        ),
        ("DELETE FROM \"clip\" WHERE (\"id\") IN ((?))".to_owned(), 1),
      ],
      "the collections lead, the rows follow, and the predicate is the same one throughout"
    );
  }

  /// The cascade correlates on the ID and NOT on the whole key, and this is the fixture that can
  /// tell the two apart: `clip`'s key is two columns and its edge tables lead with both.
  ///
  /// The id alone is enough because the schema says so — `UNIQUE ("id")` beside the compound primary
  /// key, which the DDL lane writes and this crate's whole addressing rests on — so naming the
  /// second column would bind a value for a question already answered.
  #[test]
  fn the_cascade_correlates_on_the_id_where_the_edge_rows_carry_the_whole_key() {
    let keys = <ClipRow as SqlQuery<Sqlite>>::ADDRESS.keys();
    assert_eq!(keys.len(), 2, "the fixture's key is compound");

    let statements = removed::<ClipRow, Sqlite, _>(&matching::<Sqlite>("id", &[7]));
    assert!(
      !statements[0].0.contains("media_id"),
      "the first key column has no part in the correlation: {}",
      statements[0].0
    );
  }

  /// **The PROVENANCE tables cascade too**, and every one of them is cleared rather than the row's
  /// own — the same reasoning an `upsert`'s clearing walk states, and here it is not even a choice:
  /// nothing in this lane holds a row, so which upstream a matched record descended from is not a
  /// question it can ask.
  #[test]
  fn a_removal_clears_every_provenance_table() {
    assert_eq!(
      removed::<CaptionRow, Sqlite, _>(&matching::<Sqlite>("id", &[3])),
      [
        (
          "DELETE FROM \"caption_frame\" WHERE \"id\" IN (SELECT \"id\" FROM \"caption\" \
           WHERE (\"id\") IN ((?)))"
            .to_owned(),
          1
        ),
        (
          "DELETE FROM \"caption_turn\" WHERE \"id\" IN (SELECT \"id\" FROM \"caption\" \
           WHERE (\"id\") IN ((?)))"
            .to_owned(),
          1
        ),
        (
          "DELETE FROM \"caption\" WHERE (\"id\") IN ((?))".to_owned(),
          1
        ),
      ],
      "one delete per upstream, then the common rows"
    );
  }

  /// **The UNSCOPED refusal**, which is the whole reason a required parameter was not enough: an
  /// all-absent comparison is an ordinary value, and the statement it lowers to is
  /// `DELETE FROM "clip"` with no `WHERE` — the table, gone, reported as success.
  ///
  /// [`Option::None`] is the crate's own canonical such value — the impl of
  /// [`ComplexComparison`](crate::ComplexComparison) for it renders nothing and counts zero, which
  /// is exactly what an emitted comparison with no operator set does.
  ///
  /// It is refused BEFORE anything renders, so a purge with a filter somebody forgot to fill in
  /// costs no statement at all rather than a cleared collection and a rollback.
  #[test]
  fn a_filter_that_lowers_to_no_predicate_is_refused_rather_than_run() {
    let unscoped: Option<SqlKeyIn<i64, Sqlite, 1>> = None;
    let Err(SqlWriteError::Unscoped(table)) = delete_statements::<ClipRow, Sqlite, _>(&unscoped)
    else {
      panic!("a filter naming no row is refused rather than run");
    };
    assert!(table.is("clip"), "the refusal names the table it saved");
  }

  /// **The SECOND refusal**, which the first cannot reach: a comparison whose COUNT says one
  /// conjunct and whose RENDERING writes none.
  ///
  /// The pre-render check reads the count, so this value walks past it — and the statement waiting
  /// on the other side is `DELETE FROM "clip"` with no `WHERE`. The refusal at the parent's own
  /// rendering is what stops it, and this fixture is the only way to arrive there: every shipped
  /// comparison counts what it writes.
  #[test]
  fn a_comparison_whose_count_and_rendering_disagree_is_refused_at_the_statement() {
    let Err(SqlWriteError::Unscoped(table)) =
      delete_statements::<ClipRow, Sqlite, _>(&super::Overcounting)
    else {
      panic!("a filter that renders nothing is refused however it counts itself");
    };
    assert!(table.is("clip"));
  }

  /// A key set that came out EMPTY is not the same refusal, and this is the pin: *match nothing* is
  /// an operand, where *no predicate* is an absence. The first renders `1 = 0` and removes no rows;
  /// only the second could empty a table.
  #[test]
  fn a_membership_of_nothing_is_a_statement_rather_than_a_refusal() {
    assert_eq!(
      removed::<ClipRow, Sqlite, _>(&matching::<Sqlite>("id", &[]))[2],
      ("DELETE FROM \"clip\" WHERE 1 = 0".to_owned(), 0),
      "an empty membership asks for no rows rather than for all of them"
    );
  }
}

/// PostgreSQL's own bracketing and placeholder — RENDERED and not measured: this repository
/// provisions no server, so what is pinned here is the statement the lane sends.
#[cfg(feature = "postgres")]
mod postgres {
  use sqlx::Postgres;

  use super::{ClipRow, matching, removed, rendered, row};

  /// The same conflict clause SQLite spells, under `$n` placeholders — the two dialects share the
  /// standard `ON CONFLICT`, which is why one function renders both.
  #[test]
  fn the_keyed_replace_is_the_standard_conflict_clause() {
    assert_eq!(
      rendered::<ClipRow, Postgres>(&row::<Postgres>(&[], &[]), true)[0],
      (
        "INSERT INTO \"clip\" (\"media_id\", \"id\", \"title\", \"bit_rate\") \
         VALUES ($1, $2, $3, $4) ON CONFLICT (\"media_id\", \"id\") DO UPDATE SET \
         \"media_id\" = \"excluded\".\"media_id\", \"id\" = \"excluded\".\"id\", \
         \"title\" = \"excluded\".\"title\", \"bit_rate\" = \"excluded\".\"bit_rate\""
          .to_owned(),
        4
      )
    );
  }

  /// The edge statements, whose placeholders run on across the value rows — which is what makes the
  /// bind count the half the text cannot show.
  #[test]
  fn the_edge_statements_number_their_binds_across_the_value_rows() {
    let statements = rendered::<ClipRow, Postgres>(&row::<Postgres>(&["a", "b"], &["n"]), true);
    assert_eq!(
      statements[1],
      (
        "DELETE FROM \"clip_tags\" WHERE \"media_id\" = $1 AND \"id\" = $2".to_owned(),
        2
      )
    );
    assert_eq!(
      statements[2],
      (
        "INSERT INTO \"clip_tags\" (\"media_id\", \"id\", \"tags_ordinal\", \"tags\") \
         VALUES ($1, $2, $3, $4), ($5, $6, $7, $8)"
          .to_owned(),
        8
      )
    );
    assert_eq!(
      statements[4],
      (
        "INSERT INTO \"clip_notes\" (\"media_id\", \"id\", \"notes\") VALUES ($1, $2, $3)"
          .to_owned(),
        3
      )
    );
  }

  /// The REMOVAL under `$n`, whose placeholders run on INTO the subquery — the one shape of this
  /// verb a numbered dialect can get wrong, the filter being rendered inside a nested statement
  /// rather than at the top level.
  #[test]
  fn the_removal_numbers_its_binds_through_the_subquery() {
    assert_eq!(
      removed::<ClipRow, Postgres, _>(&matching::<Postgres>("media_id", &[4, 5])),
      [
        (
          "DELETE FROM \"clip_tags\" WHERE \"id\" IN (SELECT \"id\" FROM \"clip\" \
           WHERE (\"media_id\") IN (($1), ($2)))"
            .to_owned(),
          2
        ),
        (
          "DELETE FROM \"clip_notes\" WHERE \"id\" IN (SELECT \"id\" FROM \"clip\" \
           WHERE (\"media_id\") IN (($1), ($2)))"
            .to_owned(),
          2
        ),
        (
          "DELETE FROM \"clip\" WHERE (\"media_id\") IN (($1), ($2))".to_owned(),
          2
        ),
      ],
      "each statement numbers from one, and each binds the whole membership"
    );
  }
}

/// MySQL's, which is the one dialect whose keyed replace names no target — RENDERED and not
/// measured, for PostgreSQL's reason.
#[cfg(feature = "mysql")]
mod mysql {
  use sqlx::MySql;

  use super::{ClipRow, matching, removed, rendered, row};

  /// `ON DUPLICATE KEY UPDATE` and no conflict target, reading the incoming row back through
  /// `VALUES(…)` rather than through a pseudo-table — see [`Upsert`](crate::query::sql::Upsert) for
  /// why the deprecated spelling is the portable one.
  #[test]
  fn the_keyed_replace_names_no_target_and_reads_the_row_back_through_values() {
    assert_eq!(
      rendered::<ClipRow, MySql>(&row::<MySql>(&[], &[]), true)[0],
      (
        "INSERT INTO `clip` (`media_id`, `id`, `title`, `bit_rate`) VALUES (?, ?, ?, ?) \
         ON DUPLICATE KEY UPDATE `media_id` = VALUES(`media_id`), `id` = VALUES(`id`), \
         `title` = VALUES(`title`), `bit_rate` = VALUES(`bit_rate`)"
          .to_owned(),
        4
      )
    );
  }

  /// The edge statements under backtick bracketing, which is the whole of what differs from SQLite's
  /// here — the delete, the ordinal and the value rows are one rendering.
  #[test]
  fn the_edge_statements_carry_the_dialects_own_bracketing() {
    let statements = rendered::<ClipRow, MySql>(&row::<MySql>(&["a", "b"], &["n"]), true);
    assert_eq!(
      statements[1],
      (
        "DELETE FROM `clip_tags` WHERE `media_id` = ? AND `id` = ?".to_owned(),
        2
      )
    );
    assert_eq!(
      statements[2],
      (
        "INSERT INTO `clip_tags` (`media_id`, `id`, `tags_ordinal`, `tags`) \
         VALUES (?, ?, ?, ?), (?, ?, ?, ?)"
          .to_owned(),
        8
      )
    );
  }

  /// The REMOVAL under backticks — and the statement this dialect has ONE documented hazard with.
  ///
  /// The subquery reads the PARENT while the delete targets a CHILD, so the two tables are different
  /// and MySQL's error 1093 does not fire on the shape rendered here. It fires when the filter
  /// itself asks a question about a collection, whose lowering is a correlated subquery over that
  /// collection's own edge table — the module note weighs that case and records why the derived-table
  /// workaround was declined. Nothing about the text below changes either way, which is exactly why
  /// the hazard is written down rather than asserted.
  #[test]
  fn the_removal_carries_the_dialects_own_bracketing() {
    assert_eq!(
      removed::<ClipRow, MySql, _>(&matching::<MySql>("id", &[7]))[0],
      (
        "DELETE FROM `clip_tags` WHERE `id` IN (SELECT `id` FROM `clip` WHERE (`id`) IN ((?)))"
          .to_owned(),
        1
      )
    );
  }
}

/// The half no statement's text can show, put to a real engine.
///
/// A write that appends where it should replace, one whose ordinals are not the collection's, and
/// one whose statements are not one transaction all render SQL a reader would pass. What sees them
/// is a corpus this lane writes itself.
#[cfg(feature = "sqlite")]
mod live {
  use sqlx::Sqlite;

  use super::{Caption, CaptionRow, CaptionSource, Clip, ClipRow, caption, clip};
  use crate::query::sql::{SqlWriteError, delete, delete_where, get, insert, upsert};

  /// An EMPTY in-memory database with both fixtures' tables, on ONE connection — created by
  /// the SCHEMA LANE rather than by hand.
  ///
  /// A bare [`SqliteConnection`](sqlx::sqlite::SqliteConnection) and never a `Pool`: this crate
  /// enables no sqlx runtime, so a pool would panic spawning its reaper. It is also what makes the
  /// one-connection promise observable — `sqlite::memory:` is a database per connection, so anything
  /// this engine ran on a second one would find no table at all.
  ///
  /// Nothing is inserted here, and that is the difference from every other corpus in this crate:
  /// what fills these tables is the lane under test, so a hand-written row would prove the read half
  /// and nothing about the write.
  ///
  /// # The DDL is DERIVED, and that is what makes this walk the naming check
  ///
  /// The tables come from [`Clip`]'s and [`Caption`]'s own descriptors, through the same
  /// [`edge`](super::super::hydrate) derivation the statements under test spell their edge tables
  /// with — so the party that CREATES a table and the party that writes to it cannot name two
  /// different ones. Every claim below therefore carries a second one for free: the schema this lane
  /// was measured against is the schema the schema lane makes.
  ///
  /// `UNIQUE ("id")` beside the compound primary key is the law the address rests on, and the
  /// PRIMARY KEY on each edge table is what makes a repeated ordinal a refusal rather than a
  /// duplicate element. Both are the DDL's now, and neither is written here.
  ///
  /// # `PRAGMA foreign_keys = ON`, because a declared constraint SQLite ignores is not one
  ///
  /// It is per connection and defaults OFF, so it is sent where the connection is made — see the
  /// schema lane's own note, which is where the posture is written down. Without it the provenance
  /// tables' foreign keys would be parsed and never checked, and the orphan below would be taken.
  async fn empty() -> sqlx::sqlite::SqliteConnection {
    use sqlx::Connection as _;

    use crate::{TypeVisitor as _, query::sql::Create};

    let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
      .await
      .expect("an in-memory database");
    sqlx::query("PRAGMA foreign_keys = ON")
      .execute(&mut db)
      .await
      .expect("the connection enforces what the schema declares");
    let mut create = Create::<Sqlite>::new();
    create
      .next_type::<Clip>()
      .expect("this descriptor renders for SQLite");
    create
      .next_type::<Caption>()
      .expect("and so does the fan-in's");
    create.run(&mut db).await.expect("and the engine takes it");
    db
  }

  /// The rows the FRAME upstream's provenance table holds, as `id:media_id:frame` — read outside the
  /// lane, which is the only way to see that a write did more than render.
  async fn from_frame(db: &mut sqlx::sqlite::SqliteConnection) -> Vec<String> {
    sqlx::query_scalar::<_, String>(
      r#"SELECT "id" || ':' || "media_id" || ':' || "frame" FROM "caption_frame" ORDER BY "id""#,
    )
    .fetch_all(db)
    .await
    .expect("the provenance table is there")
  }

  /// The same for the TURN upstream, whose ancestry is one column wide.
  async fn from_turn(db: &mut sqlx::sqlite::SqliteConnection) -> Vec<String> {
    sqlx::query_scalar::<_, String>(
      r#"SELECT "id" || ':' || "turn" FROM "caption_turn" ORDER BY "id""#,
    )
    .fetch_all(db)
    .await
    .expect("the provenance table is there")
  }

  /// How many rows the parent table holds, read outside the engine — which is what a torn write is
  /// visible as.
  async fn parents(db: &mut sqlx::sqlite::SqliteConnection) -> i64 {
    sqlx::query_scalar::<_, i64>(r#"SELECT count(*) FROM "clip""#)
      .fetch_one(db)
      .await
      .expect("the parent table is there")
  }

  /// How many rows the SEQUENCE's edge table holds, read outside the lane — which is the only way
  /// to see an element row that OUTLIVED the record it belonged to.
  ///
  /// A read cannot see one: a gather is keyed on the parents a page returned, so an orphan is
  /// invisible until an id is reused and it comes back as somebody else's collection. The table is
  /// counted directly for that reason.
  ///
  /// One helper per table rather than one taking a name, which is the shape [`from_frame`] and
  /// [`from_turn`] already have beside them — and here it is not only style: `query_scalar` takes a
  /// statement its type says is safe, and a name joined into one at runtime is exactly what that
  /// bound exists to keep out.
  async fn tag_rows(db: &mut sqlx::sqlite::SqliteConnection) -> i64 {
    sqlx::query_scalar::<_, i64>(r#"SELECT count(*) FROM "clip_tags""#)
      .fetch_one(db)
      .await
      .expect("the sequence's edge table is there")
  }

  /// The same for the SET's, whose table carries no ordinal — see [`tag_rows`].
  async fn note_rows(db: &mut sqlx::sqlite::SqliteConnection) -> i64 {
    sqlx::query_scalar::<_, i64>(r#"SELECT count(*) FROM "clip_notes""#)
      .fetch_one(db)
      .await
      .expect("the set's edge table is there")
  }

  /// **A record stored and read back**, through the declared crossing in both directions: the row
  /// holds a signed `bit_rate` and the record an unsigned one, so a value that reached storage
  /// crossed on the way in and crossed back on the way out.
  #[tokio::test]
  async fn an_inserted_record_reads_back_through_its_own_conversions() {
    let mut db = empty().await;
    let stored = clip(&["a", "b", "c"], &["beta-note", "alpha-note"]);
    insert::<ClipRow, Sqlite, _>(&mut db, stored.clone())
      .await
      .expect("an empty table takes the record");

    assert_eq!(
      get::<ClipRow, Sqlite, _>(&mut db, &7, false)
        .await
        .expect("the record is there"),
      Some(Clip {
        notes: vec!["alpha-note".to_owned(), "beta-note".to_owned()],
        ..stored
      }),
      "the sequence keeps the order it was written in and the set comes back in its own"
    );
  }

  /// A second `insert` at a taken address is the ENGINE's refusal, surfaced rather than swallowed —
  /// which is the whole of what makes the two verbs two.
  #[tokio::test]
  async fn a_second_insert_at_a_taken_address_is_the_engines_own_refusal() {
    let mut db = empty().await;
    insert::<ClipRow, Sqlite, _>(&mut db, clip(&["a"], &[]))
      .await
      .expect("the first write lands");

    let refused = insert::<ClipRow, Sqlite, _>(&mut db, clip(&["b"], &[])).await;
    let Err(SqlWriteError::Sql(why)) = refused else {
      panic!("a taken address is the dialect's own constraint violation");
    };
    assert!(
      why.to_string().contains("UNIQUE constraint failed"),
      "the engine's own sentence reaches the caller: {why}"
    );
    assert_eq!(parents(&mut db).await, 1, "and nothing was written twice");
  }

  /// **The keyed replace**, at one address: the payload changes and the OLD payload is gone. It is
  /// the same statement whether or not a row was there, which is what a caller that means *store
  /// this* is asking for.
  #[tokio::test]
  async fn an_upsert_replaces_the_payload_at_one_address() {
    let mut db = empty().await;
    upsert::<ClipRow, Sqlite, _>(&mut db, clip(&[], &[]))
      .await
      .expect("an upsert onto nothing is an insert");
    assert_eq!(parents(&mut db).await, 1);

    let mut replacement = clip(&[], &[]);
    replacement.title = "omega".to_owned();
    replacement.bit_rate = 128;
    upsert::<ClipRow, Sqlite, _>(&mut db, replacement.clone())
      .await
      .expect("an upsert onto a stored row replaces it");

    assert_eq!(parents(&mut db).await, 1, "one address, one row");
    assert_eq!(
      get::<ClipRow, Sqlite, _>(&mut db, &7, false)
        .await
        .expect("the record is there"),
      Some(replacement),
      "the old payload is gone rather than merged with the new one"
    );
  }

  /// **The edge set is REPLACED**, not appended to: the elements that were stored and are not in
  /// this record are gone, and the ordinals are the new collection's rather than a continuation of
  /// the old one's.
  ///
  /// This is what a statement's text cannot show. A lane that skipped the delete renders the same
  /// insert over the same table and answers without an error, and what comes back is the two
  /// collections concatenated.
  #[tokio::test]
  async fn an_upsert_replaces_the_edge_set_and_the_ordinals_are_the_new_collections() {
    let mut db = empty().await;
    upsert::<ClipRow, Sqlite, _>(&mut db, clip(&["a", "b"], &["one", "two"]))
      .await
      .expect("the first write lands");

    upsert::<ClipRow, Sqlite, _>(&mut db, clip(&["c"], &["three"]))
      .await
      .expect("the replacement lands");

    assert_eq!(
      get::<ClipRow, Sqlite, _>(&mut db, &7, false)
        .await
        .expect("the record is there")
        .map(|clip| (clip.tags, clip.notes)),
      Some((vec!["c".to_owned()], vec!["three".to_owned()])),
      "the old elements are gone rather than kept beside the new ones"
    );

    assert_eq!(
      sqlx::query_scalar::<_, i64>(
        r#"SELECT "tags_ordinal" FROM "clip_tags" ORDER BY "tags_ordinal""#
      )
      .fetch_all(&mut db)
      .await
      .expect("the edge table is there"),
      [0],
      "the replacement's ordinals start at zero rather than after the old collection's"
    );
  }

  /// **An emptied collection comes back EMPTY**, and this is the half of the replacement that fails
  /// SILENTLY when the delete is not there.
  ///
  /// The test beside this one is caught by the engine rather than by an assertion: a sequence's edge
  /// table is keyed on `(key…, ordinal)`, so writing a second element at ordinal zero is a
  /// constraint violation and a lane that skipped the delete stops loudly. Neither half of THIS one
  /// collides — an emptied sequence writes no row at all, and a set's rows are keyed on their VALUES
  /// — so a lane that appends answers without an error and hands back a collection no caller ever
  /// stored.
  #[tokio::test]
  async fn an_emptied_collection_comes_back_empty_rather_than_holding_what_it_held() {
    let mut db = empty().await;
    upsert::<ClipRow, Sqlite, _>(&mut db, clip(&["a", "b"], &["one", "two"]))
      .await
      .expect("the first write lands");

    upsert::<ClipRow, Sqlite, _>(&mut db, clip(&[], &["three"]))
      .await
      .expect("the replacement lands");

    assert_eq!(
      get::<ClipRow, Sqlite, _>(&mut db, &7, false)
        .await
        .expect("the record is there")
        .map(|clip| (clip.tags, clip.notes)),
      Some((Vec::new(), vec!["three".to_owned()])),
      "an emptied sequence keeps nothing, and a set is replaced rather than merged"
    );
  }

  /// **The multi-statement write lands whole** — the first half of the pair, and the half that
  /// proves nothing on its own: a lane with no transaction at all passes exactly this.
  ///
  /// Its twin is [`a_failure_part_way_through_leaves_no_parent_row`], which runs the SAME sequence
  /// with the second statement made to fail. Nothing but that differs.
  #[tokio::test]
  async fn the_multi_statement_write_lands_whole() {
    let mut db = empty().await;
    insert::<ClipRow, Sqlite, _>(&mut db, clip(&["a", "b"], &["n"]))
      .await
      .expect("three statements, one transaction");

    assert_eq!(parents(&mut db).await, 1);
    assert_eq!(
      get::<ClipRow, Sqlite, _>(&mut db, &7, false)
        .await
        .expect("the record is there")
        .map(|clip| clip.tags),
      Some(vec!["a".to_owned(), "b".to_owned()])
    );
  }

  /// **A failure part-way through leaves NO parent row** — the half that measures the bracket.
  ///
  /// The sequence is the one above and the injection is the edge table's absence: the parent
  /// statement runs and lands, the edge insert after it refuses, and what a caller finds afterwards
  /// is the state before the call. Without the transaction the parent row survives its own
  /// collection, which is a record stored holding a collection it never had.
  #[tokio::test]
  async fn a_failure_part_way_through_leaves_no_parent_row() {
    let mut db = empty().await;
    sqlx::query(r#"DROP TABLE "clip_tags""#)
      .execute(&mut db)
      .await
      .expect("the sequence's edge table goes away");

    assert!(
      insert::<ClipRow, Sqlite, _>(&mut db, clip(&["a", "b"], &["n"]))
        .await
        .is_err(),
      "the second statement has no table to write to"
    );
    assert_eq!(
      parents(&mut db).await,
      0,
      "and the parent statement that already ran is rolled back with it"
    );
  }

  /// **The common row and its ONE provenance row land together.** Two statements, one transaction,
  /// and the provenance row is in the table the row's own lineage names and in no other.
  #[tokio::test]
  async fn a_fan_ins_common_row_and_its_provenance_row_land_together() {
    let mut db = empty().await;
    insert::<CaptionRow, Sqlite, _>(
      &mut db,
      caption(CaptionSource::Frame { media: 1, frame: 5 }),
    )
    .await
    .expect("two statements, one transaction");

    assert_eq!(from_frame(&mut db).await, ["7:1:5"]);
    assert!(
      from_turn(&mut db).await.is_empty(),
      "a row descends from ONE upstream, so the other table holds nothing for it"
    );
    assert_eq!(
      sqlx::query_scalar::<_, String>(r#"SELECT "__ig_source__" FROM "caption""#)
        .fetch_one(&mut db)
        .await
        .expect("the common row is there"),
      "Frame",
      "and the discriminant names the table the provenance row went in"
    );
  }

  /// **A row whose upstream CHANGED keeps one ancestry**, which is the whole reason an `upsert`
  /// clears every provenance table rather than the one it is about to write.
  ///
  /// A lane that cleared only the matching table passes every rendering assertion and leaves this
  /// row with two ancestries — a state the split layout is built to make unrepresentable, and one
  /// nothing but a live read can see.
  #[tokio::test]
  async fn a_replacement_that_changes_upstream_leaves_one_ancestry() {
    let mut db = empty().await;
    upsert::<CaptionRow, Sqlite, _>(
      &mut db,
      caption(CaptionSource::Frame { media: 1, frame: 5 }),
    )
    .await
    .expect("the first write lands");
    upsert::<CaptionRow, Sqlite, _>(&mut db, caption(CaptionSource::Turn { turn: 9 }))
      .await
      .expect("and the replacement lands");

    assert!(
      from_frame(&mut db).await.is_empty(),
      "the ancestry the row no longer has is gone"
    );
    assert_eq!(from_turn(&mut db).await, ["7:9"]);
  }

  /// **A failure part-way through leaves NEITHER row** — the split layout's half of the pair the
  /// collections' own torn write is the other half of.
  ///
  /// The injection is the provenance table's absence: the common statement runs and lands, the
  /// provenance insert after it refuses, and what a caller finds afterwards is the state before the
  /// call. Without the bracket the common row survives with no ancestry at all, which is a row
  /// whose upstream can never be read back.
  #[tokio::test]
  async fn a_fan_ins_torn_write_leaves_neither_row() {
    let mut db = empty().await;
    sqlx::query(r#"DROP TABLE "caption_frame""#)
      .execute(&mut db)
      .await
      .expect("the provenance table goes away");

    assert!(
      insert::<CaptionRow, Sqlite, _>(
        &mut db,
        caption(CaptionSource::Frame { media: 1, frame: 5 })
      )
      .await
      .is_err(),
      "the second statement has no table to write to"
    );
    assert_eq!(
      sqlx::query_scalar::<_, i64>(r#"SELECT count(*) FROM "caption""#)
        .fetch_one(&mut db)
        .await
        .expect("the common table is there"),
      0,
      "and the common statement that already ran is rolled back with it"
    );
  }

  /// **THE SHORTENED RE-INDEX**, which is the production bite this verb was written for.
  ///
  /// A source produces fourteen segments; it is re-run and now produces nine. Without a removal the
  /// five that vanished stay stored — a keyed replace only reaches the nine addresses it is handed —
  /// so a search over the table keeps answering with segments 9 through 13, which no longer exist
  /// anywhere upstream. `get` on one of them returns a whole record.
  ///
  /// The purge is what the re-indexer runs FIRST: every row of this media goes, then the nine that
  /// survived are written. What the assertion below sees is that the table holds exactly nine
  /// afterwards and that the ghost is gone rather than merely unreferenced.
  #[tokio::test]
  async fn a_shortened_reindex_leaves_no_ghost_rows_behind() {
    let mut db = empty().await;
    for id in 0..14 {
      let mut segment = clip(&["a"], &["n"]);
      segment.id = id;
      insert::<ClipRow, Sqlite, _>(&mut db, segment)
        .await
        .expect("the first indexing pass writes fourteen segments");
    }
    assert_eq!(parents(&mut db).await, 14);

    let removed =
      delete_where::<ClipRow, Sqlite, _>(&mut db, &super::matching::<Sqlite>("media_id", &[1]))
        .await
        .expect("the media's rows are removed by their own predicate");
    assert_eq!(removed, 14, "the count is the RECORDS that went");
    assert_eq!(parents(&mut db).await, 0);

    for id in 0..9 {
      let mut segment = clip(&["a"], &["n"]);
      segment.id = id;
      insert::<ClipRow, Sqlite, _>(&mut db, segment)
        .await
        .expect("the second pass writes nine");
    }

    assert_eq!(
      parents(&mut db).await,
      9,
      "exactly nine, where a lane without this verb would answer fourteen"
    );
    assert_eq!(
      get::<ClipRow, Sqlite, _>(&mut db, &12, false)
        .await
        .expect("the read runs"),
      None,
      "segment 12 is GONE rather than orphaned — the ghost a search used to hit"
    );
    assert!(
      get::<ClipRow, Sqlite, _>(&mut db, &8, false)
        .await
        .expect("the read runs")
        .is_some(),
      "and the nine the source still produces are there"
    );
  }

  /// **The CASCADE**: a record's edge rows go WITH it, and nothing in the schema makes that happen.
  ///
  /// No edge table declares a foreign key at all, so an engine has nothing to cascade along — a lane
  /// that removed only the parent would leave every element row behind, keyed on an id that names
  /// nothing, and the next record to take that id would read them back as its own collection. That
  /// is the silent failure this test exists for: the parent count alone cannot see it, so the edge
  /// tables are counted directly.
  #[tokio::test]
  async fn a_removal_takes_the_records_collection_rows_with_it() {
    let mut db = empty().await;
    insert::<ClipRow, Sqlite, _>(&mut db, clip(&["a", "b", "c"], &["one", "two"]))
      .await
      .expect("the record and its two collections land");
    assert_eq!(tag_rows(&mut db).await, 3);
    assert_eq!(note_rows(&mut db).await, 2);

    assert!(
      delete::<ClipRow, Sqlite, _>(&mut db, &7)
        .await
        .expect("the removal runs"),
      "a row was there"
    );

    assert_eq!(parents(&mut db).await, 0);
    assert_eq!(
      tag_rows(&mut db).await,
      0,
      "the sequence's rows went with the record rather than outliving it"
    );
    assert_eq!(note_rows(&mut db).await, 0, "and so did the set's");
  }

  /// The cascade is REAL rather than incidental: a SECOND record at another address keeps every one
  /// of its element rows.
  ///
  /// This is the mutation the test above cannot catch. A cascade that ignored its predicate and
  /// cleared the whole edge table would pass every assertion there, and it fails here.
  #[tokio::test]
  async fn the_cascade_reaches_the_removed_records_rows_and_no_others() {
    let mut db = empty().await;
    insert::<ClipRow, Sqlite, _>(&mut db, clip(&["a", "b"], &["one"]))
      .await
      .expect("the first record lands");
    let mut second = clip(&["c", "d", "e"], &["two", "three"]);
    second.id = 8;
    insert::<ClipRow, Sqlite, _>(&mut db, second)
      .await
      .expect("and the second");

    assert!(
      delete::<ClipRow, Sqlite, _>(&mut db, &7)
        .await
        .expect("the removal runs")
    );

    assert_eq!(parents(&mut db).await, 1);
    assert_eq!(
      tag_rows(&mut db).await,
      3,
      "the surviving record keeps its whole sequence"
    );
    assert_eq!(note_rows(&mut db).await, 2, "and its whole set");
    assert_eq!(
      get::<ClipRow, Sqlite, _>(&mut db, &8, false)
        .await
        .expect("the read runs")
        .map(|clip| (clip.tags.len(), clip.notes.len())),
      Some((3, 2)),
      "and reads back complete"
    );
  }

  /// A MISS is `Ok(false)`, exactly as `get`'s is `Ok(None)` — an address that holds nothing is a
  /// fact about the database rather than a failure of the call, which is what a caller purging a
  /// root that was already purged needs it to be.
  #[tokio::test]
  async fn a_removal_at_an_empty_address_is_false_rather_than_an_error() {
    let mut db = empty().await;
    assert!(
      !delete::<ClipRow, Sqlite, _>(&mut db, &7)
        .await
        .expect("a miss is not an error"),
      "nothing was there"
    );
  }

  /// **The PROVENANCE row goes too**, and the foreign key is what makes this the one cascade an
  /// engine could have caught: `PRAGMA foreign_keys = ON` is sent on this connection, so a lane that
  /// removed the common row first — or did not remove the provenance row at all — is refused by the
  /// constraint rather than answering.
  ///
  /// The count afterwards is what says the ancestry is gone rather than merely unreachable.
  #[tokio::test]
  async fn a_removal_takes_the_records_ancestry_with_it() {
    let mut db = empty().await;
    insert::<CaptionRow, Sqlite, _>(
      &mut db,
      caption(CaptionSource::Frame { media: 1, frame: 5 }),
    )
    .await
    .expect("the common row and its provenance row land");
    assert_eq!(from_frame(&mut db).await, ["7:1:5"]);

    assert!(
      delete::<CaptionRow, Sqlite, _>(&mut db, &7)
        .await
        .expect("the removal runs — the constraint is satisfied by the ORDER"),
      "a row was there"
    );

    assert!(
      from_frame(&mut db).await.is_empty(),
      "the ancestry went with the row it belonged to"
    );
    assert_eq!(
      sqlx::query_scalar::<_, i64>(r#"SELECT count(*) FROM "caption""#)
        .fetch_one(&mut db)
        .await
        .expect("the common table is there"),
      0
    );
  }

  /// The UNSCOPED refusal on a LIVE database — the half a rendering test cannot show, which is that
  /// the table is still there afterwards.
  #[tokio::test]
  async fn an_unscoped_filter_leaves_every_row_where_it_was() {
    let mut db = empty().await;
    insert::<ClipRow, Sqlite, _>(&mut db, clip(&["a"], &["n"]))
      .await
      .expect("the record lands");

    let unscoped: Option<crate::comparison::sql::SqlKeyIn<i64, Sqlite, 1>> = None;
    let Err(SqlWriteError::Unscoped(table)) =
      super::delete_statements::<ClipRow, Sqlite, _>(&unscoped)
    else {
      panic!("an unscoped filter is refused");
    };
    assert!(table.is("clip"));
    assert_eq!(
      parents(&mut db).await,
      1,
      "and the row a filterless statement would have taken is still there"
    );
  }

  /// Inside a caller's transaction the lane is PASSTHROUGH, so what the write is subject to is the
  /// CALLER's own rollback — which is how two records land together or not at all.
  #[tokio::test]
  async fn a_write_inside_a_callers_transaction_is_subject_to_the_callers_rollback() {
    use sqlx::Acquire as _;

    let mut db = empty().await;
    let mut held = db.begin().await.expect("the caller's own transaction");
    insert::<ClipRow, Sqlite, _>(&mut held, clip(&["a"], &[]))
      .await
      .expect("the write passes through");
    let mut second = clip(&["b"], &[]);
    second.id = 8;
    insert::<ClipRow, Sqlite, _>(&mut held, second)
      .await
      .expect("and so does the one beside it");
    held.rollback().await.expect("the caller abandons both");

    assert_eq!(
      parents(&mut db).await,
      0,
      "neither write opened a transaction of its own to commit"
    );
  }
}