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
//! **A COLLECTION whose element spans two columns, through every lane that names one.**
//!
//! ```text
//! struct Take { id: i64, stamps: Vec<Timestamp>, marks: Vec<Timestamp> }
//! CREATE TABLE "take_stamps" ("id" …, "stamps_ordinal" …, "stamps_secs" …, "stamps_nanos" …)
//!               PRIMARY KEY ("id", "stamps_ordinal")
//! CREATE TABLE "take_marks"  ("id" …, "marks_secs" …, "marks_nanos" …)
//!               PRIMARY KEY ("id", "marks_secs", "marks_nanos")
//! INSERT INTO "take_stamps" ("id", "stamps_ordinal", "stamps_secs", "stamps_nanos") VALUES …
//! SELECT "id", "stamps_secs" AS "__element_secs", "stamps_nanos" AS "__element_nanos", …
//! ```
//!
//! The two SHAPES are both here and their difference is physical rather than rendered: a sequence's
//! identity is its ORDINAL, so its segments are ordinary columns and one of them may hold `NULL`; a
//! set's identity is every segment, which is why an optional one is refused at the descriptor and
//! why its `PRIMARY KEY` ends on the whole element rather than on one column.
//!
//! # What each half is measured against
//!
//! | half | measured how |
//! |---|---|
//! | the two table forms | the rendered DDL, per dialect |
//! | the `INSERT`'s column list and bind count | rendered, per dialect |
//! | the round trip | live, in-memory SQLite: created from the descriptor, written through the write lane, gathered back through the read lane |
//! | filtering BY ELEMENT | live, against a corpus whose rows differ in the ways the predicate distinguishes |
//! | **the cartesian trap** | live, and NEGATIVELY: the per-column spelling is executed beside the row value and returns rows nobody asked for |
//!
//! The last is the one a rendered golden cannot make. Both statements are well-formed, both bind the
//! same four operands, and only the ROW SET separates them — so the assertion is two engine answers
//! against one corpus.

use sqlx::QueryBuilder;

#[cfg(feature = "sqlite")]
use super::insert_statement;
use crate::{
  Carrier, ColumnName, ColumnShape, ComplexComparison, FieldName, Identifiable, Record,
  RecordAddress, Timestamp, Transformer,
  comparison::{Backend, sql::SqlKeyIn},
  query::sql::{
    CrossingError, EdgeCollection, EdgeShape, EdgeWrite, SqlQuery, SqlWrite, distribute,
    element_alias,
  },
};

/// The record: an id, one SEQUENCE of instants and one SET of them.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Take {
  id: i64,
  stamps: Vec<Timestamp>,
  marks: Vec<Timestamp>,
}

impl Identifiable for Take {
  type Id = i64;

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

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

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

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

/// The stored row — the collections are FIELDS of it and columns of neither table it is selected
/// from, which is the partition `COLUMNS` already draws for a gathered column.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
struct TakeRow {
  id: i64,
  stamps: Vec<Timestamp>,
  marks: Vec<Timestamp>,
}

const TAKE: RecordAddress = RecordAddress::new(FieldName::new("take"), &[FieldName::new("id")]);
const ALIASES: &[&str] = &["__ig_take_0__", "__ig_take_1__"];

/// The two collections' paths.
const STAMPS: &[&FieldName] = &[FieldName::new("stamps")];
const MARKS: &[&FieldName] = &[FieldName::new("marks")];

/// The SEGMENTS one element spans, as a plan states them: the LEAF names, in the order the element
/// type answers with.
///
/// It is a restatement of [`ColumnKind::SEGMENTS`](crate::ColumnKind::SEGMENTS), and it is one
/// because a `const` on stable cannot filter a `&[ColumnShape]` into a `&'static [&'static
/// FieldName]` — there is no allocation to hold the result. The comparison side needs no such list
/// and reads the type's own `const` directly; the PLAN side states leaf names, exactly as the
/// descriptor beside it states leaf columns with a stored type on each.
///
/// So it is a restatement that is CHECKED, which is the standing [`describes`](crate::describes)
/// takes for the other one: a list that drifted from the type's answer is `E0080` here rather than a
/// statement naming a column the schema never wrote.
const SEGMENTS: &[&FieldName] = &[FieldName::new("secs"), FieldName::new("nanos")];

/// The audit, through [`leaf_names`](crate::leaf_names) — the crate's one `const` on what an
/// element's parts flatten into.
///
/// It replaced a positional walk written out here, which held `answered[at].field()` against
/// `SEGMENTS[at]` and so said *a part is a column*. That is true of an instant and false of any
/// element whose own part is composite: a `field: None` entry has no name to compare and stands for
/// several leaves. One authority answers for both, and it is the same one
/// [`describes`](crate::describes) reaches for the row's descriptor.
const _: () = assert!(
  crate::leaf_names(<Timestamp as crate::ColumnKind>::SEGMENTS, SEGMENTS),
  "the plan's leaf names are the element type's own, joined as the renderer joins them"
);

/// Bind this row's one key column.
fn take_key<Db>(row: &TakeRow, _index: usize, qb: &mut QueryBuilder<Db>)
where
  Db: sqlx::Database,
  i64: Carrier<Db>,
{
  row.id.push_bind(qb);
}

/// Give every page row the instants gathered for it, recomposed from the TWO columns the gather
/// projected — which is the composite's own `from_parts`, refusing a pair the type does not admit
/// exactly as the scalar decode refuses a value of the wrong type.
fn gathered<Db>(
  page: &mut [TakeRow],
  rows: &[Db::Row],
  into: fn(&mut TakeRow) -> &mut Vec<Timestamp>,
) -> Result<(), sqlx::Error>
where
  Db: sqlx::Database,
  for<'r> i64: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'r> i32: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
{
  use sqlx::Row as _;

  let secs = element_alias(FieldName::new("secs"));
  let nanos = element_alias(FieldName::new("nanos"));
  distribute(
    page,
    rows,
    |row| row.id,
    |row| row.try_get("id"),
    |row| {
      let second: i64 = row.try_get(secs.as_str())?;
      let nanosecond: i32 = row.try_get(nanos.as_str())?;
      Timestamp::from_parts(second, nanosecond)
        .map_err(|error| sqlx::Error::Decode(Box::new(error)))
    },
    into,
  )
}

fn take_stamps<Db>(page: &mut [TakeRow], rows: &[Db::Row]) -> Result<(), sqlx::Error>
where
  Db: sqlx::Database,
  for<'r> i64: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'r> i32: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
{
  gathered::<Db>(page, rows, |row| &mut row.stamps)
}

fn take_marks<Db>(page: &mut [TakeRow], rows: &[Db::Row]) -> Result<(), sqlx::Error>
where
  Db: sqlx::Database,
  for<'r> i64: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'r> i32: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
{
  gathered::<Db>(page, rows, |row| &mut row.marks)
}

fn stamps_len(row: &TakeRow) -> usize {
  row.stamps.len()
}

fn marks_len(row: &TakeRow) -> usize {
  row.marks.len()
}

/// **N BINDS FOR ONE ELEMENT.** The plan writes one element at one position and the composite's own
/// [`Carrier`] row fills two placeholders with its own comma between them — so a declaration's write
/// leg is the same function it would be for a scalar.
fn stamps_element<Db>(row: &TakeRow, at: usize, qb: &mut QueryBuilder<Db>)
where
  Db: sqlx::Database,
  Timestamp: Carrier<Db>,
{
  row.stamps[at].push_bind(qb);
}

fn marks_element<Db>(row: &TakeRow, at: usize, qb: &mut QueryBuilder<Db>)
where
  Db: sqlx::Database,
  Timestamp: Carrier<Db>,
{
  row.marks[at].push_bind(qb);
}

impl<Db> SqlQuery<Db> for TakeRow
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> i32: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
{
  type Record = Take;
  type Address = SqlKeyIn<i64, Db, 1>;

  const ADDRESS: RecordAddress = TAKE;
  const ALIASES: &'static [&'static str] = ALIASES;
  const COLUMNS: &'static [ColumnShape] = &[ColumnShape::Plain(ColumnName::new("id"))];
  /// Both collections take the GATHER, and a composite element has no other materialization to take
  /// — `array_agg` names one expression, and this element is two columns that arrive together.
  const COLLECTIONS: &'static [EdgeCollection<Self, Db>] = &[
    EdgeCollection::gather_composite(
      STAMPS,
      EdgeShape::Sequence,
      SEGMENTS,
      take_key::<Db>,
      take_stamps::<Db>,
    ),
    EdgeCollection::gather_composite(
      MARKS,
      EdgeShape::Set,
      SEGMENTS,
      take_key::<Db>,
      take_marks::<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)
  }

  fn record(self) -> Result<Take, CrossingError> {
    Ok(Take {
      id: self.id,
      stamps: self.stamps,
      marks: self.marks,
    })
  }
}

impl<Db> SqlWrite<Db> for TakeRow
where
  Db: Backend + sqlx::Database,
  SqlKeyIn<i64, Db, 1>: ComplexComparison<Db>,
  i64: Carrier<Db>,
  Timestamp: Carrier<Db>,
  for<'r> i64: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'r> i32: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
{
  const EDGES: &'static [EdgeWrite<Self, Db>] = &[
    EdgeWrite::composite(
      STAMPS,
      EdgeShape::Sequence,
      SEGMENTS,
      stamps_len,
      stamps_element::<Db>,
    ),
    EdgeWrite::composite(
      MARKS,
      EdgeShape::Set,
      SEGMENTS,
      marks_len,
      marks_element::<Db>,
    ),
  ];

  fn row(record: Take) -> Result<Self, CrossingError> {
    Ok(Self {
      id: record.id,
      stamps: record.stamps,
      marks: record.marks,
    })
  }

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

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

impl<'a, R: sqlx::Row> sqlx::FromRow<'a, R> for TakeRow
where
  i64: crate::Assemble<'a, R>,
{
  fn from_row(row: &'a R) -> sqlx::Result<Self> {
    Ok(Self {
      id: crate::assembled(row, FieldName::new("id"), None)?,
      stamps: Vec::new(),
      marks: Vec::new(),
    })
  }
}

/// The DESCRIPTOR, per dialect: the parent table's ONE column, and the two edge tables whose element
/// columns are the instant's own segments with this dialect's word beside each.
macro_rules! describe {
  ($db:ty, $int:literal, $big:literal) => {
    impl crate::Describe<$db> for Take {
      const BLUEPRINT: crate::Table = crate::Table::new(
        TAKE,
        &[crate::Column::new(FieldName::new("id"), $big, false)],
      )
      .with_edges(&[
        crate::EdgeTable::composite(
          STAMPS,
          EdgeShape::Sequence,
          &[
            crate::Column::new(FieldName::new("secs"), $big, false),
            crate::Column::new(FieldName::new("nanos"), $int, false),
          ],
        ),
        crate::EdgeTable::composite(
          MARKS,
          EdgeShape::Set,
          &[
            crate::Column::new(FieldName::new("secs"), $big, false),
            crate::Column::new(FieldName::new("nanos"), $int, false),
          ],
        ),
      ]);
    }
  };
}

#[cfg(feature = "sqlite")]
describe!(sqlx::Sqlite, "INTEGER", "BIGINT");
#[cfg(feature = "postgres")]
describe!(sqlx::Postgres, "integer", "bigint");
#[cfg(feature = "mysql")]
describe!(sqlx::MySql, "INT", "BIGINT");

/// **The descriptor's agreement with the row, in a `const`.** A collection column is NOT among
/// either list — a gathered column has no value on the parent row — so what this audit says here is
/// that both sides agree about that partition as well as about the columns.
#[cfg(feature = "sqlite")]
const _: () = assert!(crate::describes(
  &<Take as crate::Describe<sqlx::Sqlite>>::BLUEPRINT,
  <TakeRow as SqlQuery<sqlx::Sqlite>>::COLUMNS
));

/// The schema this descriptor renders for one dialect.
fn schema<Db: crate::query::sql::AsyncSchemaDialect>() -> Vec<String>
where
  Take: crate::Describe<Db>,
{
  <Take as crate::Describe<Db>>::BLUEPRINT
    .create::<Db>()
    .expect("every collection names a field")
}

/// The `INSERT` one collection's plan renders, with its bind count beside it.
#[cfg(feature = "sqlite")]
fn edge_text<Db>(row: &TakeRow, which: usize) -> (String, usize)
where
  TakeRow: SqlWrite<Db>,
  Db: crate::query::sql::SqlDialect,
  i64: Carrier<Db>,
  <Db as sqlx::Database>::Arguments: sqlx::IntoArguments<Db>,
{
  use sqlx::Execute as _;

  let mut rendered = crate::query::sql::write::statements::<TakeRow, Db>(
    row,
    insert_statement::<TakeRow, Db>(row),
    false,
  )
  .expect("every collection renders");
  let mut built = rendered[which + 1].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)
}

#[cfg(feature = "sqlite")]
fn at(second: i64, nanosecond: i32) -> Timestamp {
  Timestamp::from_parts(second, nanosecond).expect("a legal instant")
}

#[cfg(feature = "sqlite")]
fn take() -> Take {
  Take {
    id: 7,
    stamps: vec![at(10, 250), at(90, 0)],
    marks: vec![at(400, 1)],
  }
}

/// **SQLite: both table forms, and the difference between them is the identity.**
///
/// A sequence is keyed on `(key…, ordinal)` and indexed on `(key…, every segment)` for the
/// containment seeks; a set is keyed on `(key…, every segment)` and has nothing left to index.
#[cfg(feature = "sqlite")]
#[test]
fn both_table_forms_name_every_segment() {
  assert_eq!(
    schema::<sqlx::Sqlite>(),
    [
      r#"CREATE TABLE IF NOT EXISTS "take" ("id" BIGINT NOT NULL, PRIMARY KEY ("id"))"#,
      r#"CREATE TABLE IF NOT EXISTS "take_stamps" ("id" BIGINT NOT NULL, "stamps_ordinal" INTEGER NOT NULL, "stamps_secs" BIGINT NOT NULL, "stamps_nanos" INTEGER NOT NULL, PRIMARY KEY ("id", "stamps_ordinal"))"#,
      r#"CREATE INDEX IF NOT EXISTS "__ig_take_stamps_element" ON "take_stamps" ("id", "stamps_secs", "stamps_nanos")"#,
      r#"CREATE TABLE IF NOT EXISTS "take_marks" ("id" BIGINT NOT NULL, "marks_secs" BIGINT NOT NULL, "marks_nanos" INTEGER NOT NULL, PRIMARY KEY ("id", "marks_secs", "marks_nanos"))"#,
    ]
  );
}

/// **Postgres, whose ordinal is its own word and whose element types are the standard's spellings.**
#[cfg(feature = "postgres")]
#[test]
fn postgres_renders_both_table_forms() {
  assert_eq!(
    schema::<sqlx::Postgres>(),
    [
      r#"CREATE TABLE IF NOT EXISTS "take" ("id" bigint NOT NULL, PRIMARY KEY ("id"))"#,
      r#"CREATE TABLE IF NOT EXISTS "take_stamps" ("id" bigint NOT NULL, "stamps_ordinal" bigint NOT NULL, "stamps_secs" bigint NOT NULL, "stamps_nanos" integer NOT NULL, PRIMARY KEY ("id", "stamps_ordinal"))"#,
      r#"CREATE INDEX IF NOT EXISTS "__ig_take_stamps_element" ON "take_stamps" ("id", "stamps_secs", "stamps_nanos")"#,
      r#"CREATE TABLE IF NOT EXISTS "take_marks" ("id" bigint NOT NULL, "marks_secs" bigint NOT NULL, "marks_nanos" integer NOT NULL, PRIMARY KEY ("id", "marks_secs", "marks_nanos"))"#,
    ]
  );
}

/// **MySQL, whose bracket is a BACKTICK** — the one place a wrong quote is a silent wrong answer
/// rather than a syntax error, so the whole schema is asserted here rather than the difference.
#[cfg(feature = "mysql")]
#[test]
fn mysql_renders_both_table_forms() {
  assert_eq!(
    schema::<sqlx::MySql>(),
    [
      "CREATE TABLE IF NOT EXISTS `take` (`id` BIGINT NOT NULL, PRIMARY KEY (`id`))",
      "CREATE TABLE IF NOT EXISTS `take_stamps` (`id` BIGINT NOT NULL, `stamps_ordinal` BIGINT NOT NULL, `stamps_secs` BIGINT NOT NULL, `stamps_nanos` INT NOT NULL, PRIMARY KEY (`id`, `stamps_ordinal`))",
      "CREATE INDEX IF NOT EXISTS `__ig_take_stamps_element` ON `take_stamps` (`id`, `stamps_secs`, `stamps_nanos`)",
      "CREATE TABLE IF NOT EXISTS `take_marks` (`id` BIGINT NOT NULL, `marks_secs` BIGINT NOT NULL, `marks_nanos` INT NOT NULL, PRIMARY KEY (`id`, `marks_secs`, `marks_nanos`))",
    ]
  );
}

/// **The `INSERT` names every segment, and the bind count is `elements × (key + ordinal + width)`.**
///
/// Two instants at one key with an ordinal apiece is `2 × (1 + 1 + 2)`, and the set's one instant is
/// `1 × (1 + 0 + 2)` — the arithmetic the bind ceiling is checked against, so a statement that bound
/// one column per element would be under a ceiling it is not actually under.
#[cfg(feature = "sqlite")]
#[test]
fn the_insert_binds_every_segment_of_every_element() {
  let row = <TakeRow as SqlWrite<sqlx::Sqlite>>::row(take()).expect("nothing converts");

  assert_eq!(
    edge_text::<sqlx::Sqlite>(&row, 0),
    (
      concat!(
        r#"INSERT INTO "take_stamps" ("id", "stamps_ordinal", "stamps_secs", "stamps_nanos")"#,
        " VALUES (?, ?, ?, ?), (?, ?, ?, ?)"
      )
      .to_owned(),
      8
    )
  );
  assert_eq!(
    edge_text::<sqlx::Sqlite>(&row, 1),
    (
      r#"INSERT INTO "take_marks" ("id", "marks_secs", "marks_nanos") VALUES (?, ?, ?)"#.to_owned(),
      3
    )
  );
}

/// **THE ROUND TRIP, LIVE.** Created from the descriptor, written through the write lane, gathered
/// back through the read lane — so `stamps_secs` is spelled by the `CREATE TABLE`, by the `INSERT`,
/// by the gather's `SELECT` and by the decode, and no two of those may disagree.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn a_composite_collection_makes_the_whole_round_trip() {
  use sqlx::Connection as _;

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

  let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
    .await
    .expect("an in-memory database");
  let mut create = Create::<sqlx::Sqlite>::new();
  create
    .next_type::<Take>()
    .expect("this descriptor renders for SQLite");
  create.run(&mut db).await.expect("and the engine takes it");

  insert::<TakeRow, sqlx::Sqlite, _>(&mut db, take())
    .await
    .expect("four values for one element");

  assert_eq!(
    get::<TakeRow, sqlx::Sqlite, _>(&mut db, &7, false)
      .await
      .expect("the record is there"),
    Some(take()),
    "two columns per element, back into one instant, in the stored order"
  );

  // The columns really are two per element, under the names the walk joined — read outside this
  // crate's own vocabulary so the claim is about the TABLE rather than about a rendering.
  let stored: Vec<(i64, i64, i32)> = sqlx::query_as(
    r#"SELECT "stamps_ordinal", "stamps_secs", "stamps_nanos" FROM "take_stamps" ORDER BY "stamps_ordinal""#,
  )
  .fetch_all(&mut db)
  .await
  .expect("the segment columns are what the schema holds");
  assert_eq!(stored, [(0, 10, 250), (1, 90, 0)]);
}

/// **THE COMPOSITE CASCADE, LIVE** — a record whose elements span several columns takes ALL of them
/// with it, in both table forms at once.
///
/// This is the DRIVING shape rather than an extra case of the scalar one: a `Vec<TimeRanged<…>>`
/// class column is what a real declaration holds, and its rows are several columns wide. The cascade
/// correlates on the parent's id alone whatever the element's width is, so a removal that derived
/// the child table differently from the way the write derived it would leave every element row
/// standing — and the party that reads them back is the NEXT record to take that id.
///
/// Both shapes are asserted because their tables are keyed differently — the sequence on
/// `("id", <ordinal>)`, the set on `("id", <every segment>)` — so a delete correlating on a KEY
/// column rather than on the id would have to be right about two different keys.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn a_removal_takes_every_segment_of_every_element_with_it() {
  use sqlx::Connection as _;

  use crate::{
    TypeVisitor as _,
    comparison::sql::SqlKeyIn,
    query::sql::{Create, delete, delete_where, get, insert},
  };

  /// The element rows one parent still has, in both tables — read outside this crate's vocabulary,
  /// which is the only way to see a row that outlived the record it belonged to.
  async fn rows(db: &mut sqlx::sqlite::SqliteConnection, id: i64) -> (i64, i64) {
    let stamps: i64 = sqlx::query_scalar(r#"SELECT count(*) FROM "take_stamps" WHERE "id" = ?"#)
      .bind(id)
      .fetch_one(&mut *db)
      .await
      .expect("the sequence's table is there");
    let marks: i64 = sqlx::query_scalar(r#"SELECT count(*) FROM "take_marks" WHERE "id" = ?"#)
      .bind(id)
      .fetch_one(&mut *db)
      .await
      .expect("the set's table is there");
    (stamps, marks)
  }

  let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
    .await
    .expect("an in-memory database");
  let mut create = Create::<sqlx::Sqlite>::new();
  create.next_type::<Take>().expect("it renders");
  create.run(&mut db).await.expect("and it is taken");

  insert::<TakeRow, sqlx::Sqlite, _>(&mut db, take())
    .await
    .expect("the record and both collections land");
  let mut beside = take();
  beside.id = 8;
  insert::<TakeRow, sqlx::Sqlite, _>(&mut db, beside)
    .await
    .expect("and a second record beside it");
  assert_eq!(rows(&mut db, 7).await, (2, 1), "two stamps and one mark");

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

  assert_eq!(
    rows(&mut db, 7).await,
    (0, 0),
    "every segment of every element went with the record"
  );
  assert_eq!(
    rows(&mut db, 8).await,
    (2, 1),
    "and the record beside it kept all of its own"
  );
  assert_eq!(
    get::<TakeRow, sqlx::Sqlite, _>(&mut db, &7, false)
      .await
      .expect("the read runs"),
    None
  );

  // The FILTER road over the same shape, so the cascade is proved for BOTH doors rather than for
  // the one that happens to share its statements with the other.
  assert_eq!(
    delete_where::<TakeRow, sqlx::Sqlite, _>(
      &mut db,
      &SqlKeyIn::<i64, sqlx::Sqlite, 1>::new(["id"], vec![[8]]),
    )
    .await
    .expect("the purge runs"),
    1,
    "one record went"
  );
  assert_eq!(rows(&mut db, 8).await, (0, 0));
}

/// **Filtering BY ELEMENT, live — and the CARTESIAN TRAP beside it.**
///
/// The corpus holds three takes whose instants cross: `(10, 250)` and `(90, 0)` on one, `(10, 0)` and
/// `(90, 250)` on another, and neither pair on a third. A membership over `{(10, 250), (90, 0)}`
/// therefore admits the FIRST and not the second — and the per-column spelling admits both, because
/// the second's instants are exactly the two cross pairs.
///
/// Both statements are executed against the same rows, so what separates them is neither text nor
/// bind count but the engine's own answer.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn the_per_column_membership_admits_rows_the_row_value_does_not() {
  use sqlx::{Connection as _, Executor as _, Row as _};

  use crate::{
    At, TypeVisitor as _,
    comparison::sql::{
      QueryBuilder as Statement, SelectClause, SqlCompositeEdgeComparison, SqlConjunction,
      SqlScalarComparison,
    },
    query::sql::{Create, insert},
  };

  let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
    .await
    .expect("an in-memory database");
  let mut create = Create::<sqlx::Sqlite>::new();
  create.next_type::<Take>().expect("it renders");
  create.run(&mut db).await.expect("and it is taken");

  for record in [
    Take {
      id: 1,
      stamps: vec![at(10, 250), at(90, 0)],
      marks: Vec::new(),
    },
    Take {
      id: 2,
      stamps: vec![at(10, 0), at(90, 250)],
      marks: Vec::new(),
    },
    Take {
      id: 3,
      stamps: vec![at(11, 11)],
      marks: Vec::new(),
    },
  ] {
    insert::<TakeRow, sqlx::Sqlite, _>(&mut db, record)
      .await
      .expect("a take");
  }

  let mut comparison = SqlCompositeEdgeComparison::<
    Timestamp,
    SqlScalarComparison<i64, sqlx::Sqlite>,
    sqlx::Sqlite,
  >::new();
  comparison.has_any_of = Some(Box::new([at(10, 250), at(90, 0)]));

  let mut statement = Statement::<SelectClause, sqlx::Sqlite>::select()
    .push_field("\"id\"")
    .from("\"take\"")
    .begin_where();
  {
    let frame = At::new(&TAKE).frame(FieldName::new("stamps"));
    let accumulator = SqlConjunction::new(statement.inner_mut());
    comparison
      .apply(frame.at(), accumulator)
      .expect("a rendered predicate");
  }
  let admitted: Vec<i64> = statement
    .order_by(FieldName::new("id"), false)
    .finalize()
    .build()
    .fetch_all(&mut db)
    .await
    .expect("the engine answers")
    .iter()
    .map(|row| row.get::<i64, _>(0))
    .collect();

  assert_eq!(
    admitted,
    [1],
    "the row value admits exactly the take holding one of the two PAIRS"
  );

  // The trap, executed: the same four operands, decomposed per column.
  let product: Vec<i64> = db
    .fetch_all(
      r#"SELECT "id" FROM "take" WHERE EXISTS (SELECT 1 FROM "take_stamps"
           WHERE "take_stamps"."id" = "take"."id"
             AND "take_stamps"."stamps_secs" IN (10, 90)
             AND "take_stamps"."stamps_nanos" IN (250, 0)) ORDER BY "id""#,
    )
    .await
    .expect("the engine answers this one too")
    .iter()
    .map(|row| row.get::<i64, _>(0))
    .collect();

  assert_eq!(
    product,
    [1, 2],
    "the per-column spelling admits the CROSS pairs, which is the trap the row value closes"
  );
}