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
//! [`Table::shaped`] — the blueprint that states a row's FIELDS and lets the renderer join their
//! columns.
//!
//! # What is put to the test, and where
//!
//! A shaped descriptor carries no column NAME. `tb_num` is not in it, `span_timebase_den` is not in
//! it, and the whole claim is that both come out of the renderer identically to the way a flat
//! descriptor spells them by hand. So the corpus is arranged around that one claim:
//!
//! | proof | what it shows |
//! |---|---|
//! | the RENDERED text, per dialect | the joined names reach a statement, brackets and all |
//! | the EQUIVALENCE, byte for byte | a shaped blueprint and the hand-flat twin are one statement |
//! | the words are [`StoredAs`]'s | no type text is written here — T1's rows are read |
//! | nullability | a field's flag reaches every column it spans, and a LEAF's reaches its own |
//! | composition | `with_indexes`/`with_uniques`/`with_edges` read the shaped grain |
//! | LIVE SQLite | the engine takes it, the catalogue echoes it, and the audit agrees |
//!
//! The equivalence proof is the load-bearing one. Everything else could be right about a shaped
//! blueprint and still describe a table the read lane cannot select from; that one says the two
//! roads reach the SAME `CREATE TABLE`, which is the only claim that makes the second road safe to
//! move a record onto.
//!
//! # The words are NEVER written here
//!
//! Every type word in this module is `<T as StoredAs<Db>>::WORDS`, on both roads — the flat twins
//! included. A golden below asserting `INTEGER` is therefore asserting what T1's row says an `i64`
//! is stored as in SQLite, and a dialect that changed its mind about that would move the goldens
//! rather than leave them agreeing with a stale string.

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

use crate::{
  Column, ColumnName, ColumnShape, Describe, EdgeShape, EdgeTable, FieldName, RecordAddress,
  StoredAs, Table, TableColumns, describes,
};

/// An ALL-LEAF record: three fields, three columns, and no join to make.
///
/// It is the case a shaped descriptor has to get right FIRST, because it is the one where the two
/// roads have nothing to disagree about — a plain field's path is one segment, so the join is the
/// identity and the equivalence below is exact by construction rather than by luck.
struct Asset;

const ASSET: RecordAddress = RecordAddress::new(FieldName::new("asset"), &[FieldName::new("id")]);

/// The row's own list, as a `SqlQuery<Db>` binding publishes it — and the very list the shaped
/// descriptors below are handed, which is the whole difference from the flat road: there is no
/// second list to drift.
const ASSET_COLUMNS: &[ColumnShape] = &[
  ColumnShape::Plain(ColumnName::new("id")),
  ColumnShape::Plain(ColumnName::new("title")),
  ColumnShape::Plain(ColumnName::new("checksum")),
];

/// The fields a plain index is asked for, and the one a UNIQUE constraint is.
const INDEXED: &[&FieldName] = &[FieldName::new("title")];
const UNIQUE: &[&FieldName] = &[FieldName::new("checksum")];

/// The collection that hangs off it — in no column list on either road, which is the partition
/// [`Table::with_edges`] states and the one a shaped descriptor inherits unchanged.
const TAGS: &[&FieldName] = &[FieldName::new("tags")];

/// The scalar words the fixtures below spend, hoisted into named `const`s.
///
/// A `&[…]` written inline reaches `'static` by CONST PROMOTION, and promotion refuses an
/// expression that could panic — an INDEX is one, so `<i64 as StoredAs<Db>>::WORDS[0]` inside a
/// promoted literal is `E0716` while the same read through a `const` is not. The values are still
/// T1's rows and nothing here spells a type.
#[cfg(feature = "sqlite")]
const SQLITE_INT: &str = <i64 as StoredAs<sqlx::Sqlite>>::WORDS[0];
#[cfg(feature = "sqlite")]
const SQLITE_TEXT: &str = <String as StoredAs<sqlx::Sqlite>>::WORDS[0];
#[cfg(feature = "postgres")]
const POSTGRES_TEXT: &str = <String as StoredAs<sqlx::Postgres>>::WORDS[0];
#[cfg(feature = "mysql")]
const MYSQL_TEXT: &str = <String as StoredAs<sqlx::MySql>>::WORDS[0];

/// The one collection's edge table, per dialect — a `const` for the reason the words above are.
#[cfg(feature = "sqlite")]
const SQLITE_TAGS: &[EdgeTable] = &[EdgeTable::new(TAGS, EdgeShape::Sequence, SQLITE_TEXT)];
#[cfg(feature = "postgres")]
const POSTGRES_TAGS: &[EdgeTable] = &[EdgeTable::new(TAGS, EdgeShape::Sequence, POSTGRES_TEXT)];
#[cfg(feature = "mysql")]
const MYSQL_TAGS: &[EdgeTable] = &[EdgeTable::new(TAGS, EdgeShape::Sequence, MYSQL_TEXT)];

/// The three word lists each shaped descriptor states, per dialect — one per FIELD.
#[cfg(feature = "sqlite")]
const SQLITE_ASSET_WORDS: &[&[&str]] = &[
  <i64 as StoredAs<sqlx::Sqlite>>::WORDS,
  // The OPTIONAL field's words are its value's — T1's `Option<T>` row — so a nullable column is
  // declared at the type it holds and the `NULL` rides the flag beside it.
  <Option<String> as StoredAs<sqlx::Sqlite>>::WORDS,
  <String as StoredAs<sqlx::Sqlite>>::WORDS,
];
#[cfg(feature = "postgres")]
const POSTGRES_ASSET_WORDS: &[&[&str]] = &[
  <i64 as StoredAs<sqlx::Postgres>>::WORDS,
  <Option<String> as StoredAs<sqlx::Postgres>>::WORDS,
  <String as StoredAs<sqlx::Postgres>>::WORDS,
];
#[cfg(feature = "mysql")]
const MYSQL_ASSET_WORDS: &[&[&str]] = &[
  <i64 as StoredAs<sqlx::MySql>>::WORDS,
  <Option<String> as StoredAs<sqlx::MySql>>::WORDS,
  <String as StoredAs<sqlx::MySql>>::WORDS,
];

/// Which of the row's fields hold `NULL` — one flag per FIELD, and the same list on both roads.
const ASSET_NULLS: &[bool] = &[false, true, false];

#[cfg(feature = "sqlite")]
impl Describe<sqlx::Sqlite> for Asset {
  const BLUEPRINT: Table = Table::shaped(ASSET, ASSET_COLUMNS, SQLITE_ASSET_WORDS, ASSET_NULLS)
    .with_indexes(INDEXED)
    .with_uniques(UNIQUE)
    .with_edges(SQLITE_TAGS);
}

#[cfg(feature = "postgres")]
impl Describe<sqlx::Postgres> for Asset {
  const BLUEPRINT: Table = Table::shaped(ASSET, ASSET_COLUMNS, POSTGRES_ASSET_WORDS, ASSET_NULLS)
    .with_indexes(INDEXED)
    .with_uniques(UNIQUE)
    .with_edges(POSTGRES_TAGS);
}

#[cfg(feature = "mysql")]
impl Describe<sqlx::MySql> for Asset {
  const BLUEPRINT: Table = Table::shaped(ASSET, ASSET_COLUMNS, MYSQL_ASSET_WORDS, ASSET_NULLS)
    .with_indexes(INDEXED)
    .with_uniques(UNIQUE)
    .with_edges(MYSQL_TAGS);
}

/// The HAND-FLAT twin of the same record, per dialect — the descriptor a person writes today, with
/// each column's name spelled out.
///
/// Its type words are read off the same [`StoredAs`] rows, so the ONLY difference between it and the
/// shaped blueprint above is where the column names come from. That is what makes the equivalence
/// assertions a statement about the JOIN rather than about the vocabulary.
#[cfg(feature = "sqlite")]
const ASSET_FLAT: Table = Table::new(ASSET, ASSET_FLAT_COLUMNS)
  .with_indexes(INDEXED)
  .with_uniques(UNIQUE)
  .with_edges(SQLITE_TAGS);

/// The flat twin's own column list, with every name spelled out and every word still read.
#[cfg(feature = "sqlite")]
const ASSET_FLAT_COLUMNS: &[Column] = &[
  Column::new(FieldName::new("id"), SQLITE_INT, false),
  Column::new(FieldName::new("title"), SQLITE_TEXT, true),
  Column::new(FieldName::new("checksum"), SQLITE_TEXT, false),
];

/// The audit a descriptor states against the row it describes, asked of the SHAPED road — where it
/// is the *same list* rather than a restatement of one. See [`describes`], whose shaped arm this
/// exercises.
#[cfg(feature = "sqlite")]
const _: () = assert!(describes(
  &<Asset as Describe<sqlx::Sqlite>>::BLUEPRINT,
  ASSET_COLUMNS
));
#[cfg(feature = "postgres")]
const _: () = assert!(describes(
  &<Asset as Describe<sqlx::Postgres>>::BLUEPRINT,
  ASSET_COLUMNS
));
#[cfg(feature = "mysql")]
const _: () = assert!(describes(
  &<Asset as Describe<sqlx::MySql>>::BLUEPRINT,
  ASSET_COLUMNS
));

/// **A shaped blueprint reads its columns back as SHAPES, and a flat one as a LIST.** The two roads
/// are held apart at the accessor rather than blurred into one empty answer, which is what an
/// `Option` buys over a slice that could be empty for two different reasons.
#[cfg(feature = "sqlite")]
#[test]
fn a_shaped_descriptor_answers_shapes_where_a_flat_one_answers_columns() {
  let shaped = <Asset as Describe<sqlx::Sqlite>>::BLUEPRINT.columns();
  assert!(shaped.flat().is_none());
  assert_eq!(shaped.shapes(), Some(ASSET_COLUMNS));
  assert_eq!(shaped.width(), 3);

  let flat = ASSET_FLAT.columns();
  assert!(flat.shapes().is_none());
  assert_eq!(flat.flat().map(<[Column]>::len), Some(3));
  assert_eq!(flat.width(), 3);

  assert!(matches!(shaped, TableColumns::Shaped { .. }));
  assert!(matches!(flat, TableColumns::Flat(_)));
}

/// **The word a column is stored at is answered through the JOIN**, so a caller asking a shaped
/// descriptor for a column's type asks by the name the statement will carry.
///
/// BOTH words in the gate, because the subject needs both: the descriptor is SQLite's and [`Clip`]
/// — the composite fixture whose `tb` field is what there is a join to make — is `mediatime`'s. A
/// gate naming the dialect alone made the whole `--features runtime,sqlite` lane fail to compile,
/// which is a lane `ci/test-matrix.sh` runs and `--all-features` cannot see.
#[cfg(all(feature = "mediatime", feature = "sqlite"))]
#[test]
fn a_shaped_descriptor_answers_a_columns_word_by_the_name_the_renderer_joins() {
  const CLIP: Table = <Clip as Describe<sqlx::Sqlite>>::BLUEPRINT;

  assert_eq!(CLIP.stored(FieldName::new("id")), "INTEGER");
  // Neither of these is a string anywhere in the descriptor: `tb` is the field and `num` is the
  // segment, and the name below is what the two run together into.
  assert_eq!(CLIP.stored(FieldName::new("tb_num")), "INTEGER");
  assert_eq!(CLIP.stored(FieldName::new("tb_den")), "INTEGER");
}

/// **A key column may be a SEGMENT**, and the const check that admits it is the same comparison the
/// renderer's join is checked by — which is what [`crate::joins`] is for.
#[cfg(feature = "sqlite")]
#[test]
fn a_key_naming_a_segment_is_admitted_and_typed_by_the_field_that_owns_it() {
  const COLUMNS: &[ColumnShape] = &[ColumnShape::Composite {
    field: Some(ColumnName::new("tb")),
    segments: &[ColumnShape::Plain(ColumnName::new("num"))],
  }];
  const KEYED: Table = Table::shaped(
    RecordAddress::new(FieldName::new("keyed"), &[FieldName::new("tb_num")]),
    COLUMNS,
    &[<i32 as StoredAs<sqlx::Sqlite>>::WORDS],
    &[false],
  );

  assert_eq!(KEYED.stored(FieldName::new("tb_num")), "INTEGER");
  assert_eq!(
    KEYED.create::<sqlx::Sqlite>().expect("it renders"),
    [r#"CREATE TABLE IF NOT EXISTS "keyed" ("tb_num" INTEGER NOT NULL, PRIMARY KEY ("tb_num"))"#]
  );
}

/// A COMPOSITE-BEARING record: a leaf, a two-column citizen, a SIX-column one, and a nullable leaf.
///
/// `tb` and `span` are the whole reason this constructor exists — neither of the eight columns they
/// occupy is a string in the descriptor, and the widths come from the types rather than from a count
/// anybody wrote down.
#[cfg(feature = "mediatime")]
struct Clip;

#[cfg(feature = "mediatime")]
const CLIP: RecordAddress = RecordAddress::new(FieldName::new("clip"), &[FieldName::new("id")]);

/// The row's own list. `tb` spans two columns and `span` spans six, and [`crate::shape`] is what
/// reads each width off the type rather than restating it.
#[cfg(feature = "mediatime")]
const CLIP_COLUMNS: &[ColumnShape] = &[
  ColumnShape::Plain(ColumnName::new("id")),
  crate::shape::<crate::Timebase>(ColumnName::new("tb")),
  crate::shape::<crate::MediaTimeRange>(ColumnName::new("span")),
  ColumnShape::Plain(ColumnName::new("title")),
];

#[cfg(all(feature = "mediatime", feature = "sqlite"))]
impl Describe<sqlx::Sqlite> for Clip {
  const BLUEPRINT: Table = Table::shaped(
    CLIP,
    CLIP_COLUMNS,
    &[
      <i64 as StoredAs<sqlx::Sqlite>>::WORDS,
      <crate::Timebase as StoredAs<sqlx::Sqlite>>::WORDS,
      <crate::MediaTimeRange as StoredAs<sqlx::Sqlite>>::WORDS,
      <Option<String> as StoredAs<sqlx::Sqlite>>::WORDS,
    ],
    &[false, false, false, true],
  );
}

#[cfg(all(feature = "mediatime", feature = "postgres"))]
impl Describe<sqlx::Postgres> for Clip {
  const BLUEPRINT: Table = Table::shaped(
    CLIP,
    CLIP_COLUMNS,
    &[
      <i64 as StoredAs<sqlx::Postgres>>::WORDS,
      <crate::Timebase as StoredAs<sqlx::Postgres>>::WORDS,
      <crate::MediaTimeRange as StoredAs<sqlx::Postgres>>::WORDS,
      <Option<String> as StoredAs<sqlx::Postgres>>::WORDS,
    ],
    &[false, false, false, true],
  );
}

#[cfg(all(feature = "mediatime", feature = "mysql"))]
impl Describe<sqlx::MySql> for Clip {
  const BLUEPRINT: Table = Table::shaped(
    CLIP,
    CLIP_COLUMNS,
    &[
      <i64 as StoredAs<sqlx::MySql>>::WORDS,
      <crate::Timebase as StoredAs<sqlx::MySql>>::WORDS,
      <crate::MediaTimeRange as StoredAs<sqlx::MySql>>::WORDS,
      <Option<String> as StoredAs<sqlx::MySql>>::WORDS,
    ],
    &[false, false, false, true],
  );
}

/// The HAND-FLAT twin of the composite record, with every one of the nine columns spelled out.
///
/// This is the descriptor a person writes today, and writing it is the argument for the other road:
/// eight of these names exist nowhere but here, each has to agree with a join nothing checked, and
/// the type beside each has to agree with a `StoredAs` row by hand. The equivalence assertion below
/// is what says the shaped blueprint replaces it exactly.
#[cfg(all(feature = "mediatime", feature = "sqlite"))]
const CLIP_FLAT: Table = Table::new(CLIP, CLIP_FLAT_COLUMNS);

/// The composite twin's own column list — nine names, eight of which exist nowhere else.
#[cfg(all(feature = "mediatime", feature = "sqlite"))]
const CLIP_FLAT_COLUMNS: &[Column] = &[
  Column::new(FieldName::new("id"), SQLITE_INT, false),
  Column::new(FieldName::new("tb_num"), SQLITE_INT, false),
  Column::new(FieldName::new("tb_den"), SQLITE_INT, false),
  Column::new(FieldName::new("span_start_pts"), SQLITE_INT, false),
  Column::new(FieldName::new("span_end_pts"), SQLITE_INT, false),
  Column::new(FieldName::new("span_timebase_num"), SQLITE_INT, false),
  Column::new(FieldName::new("span_timebase_den"), SQLITE_INT, false),
  // The DERIVED pair, nullable — which on the flat road is a fact a person has to KNOW and write,
  // and on the shaped road is one the range's own segments state. The equivalence assertion is
  // therefore also the measurement of what the leaf grain buys: this pair is exactly the two
  // columns a hand-written descriptor got wrong before there was one.
  Column::new(FieldName::new("span_start_nanos"), SQLITE_INT, true),
  Column::new(FieldName::new("span_end_nanos"), SQLITE_INT, true),
  Column::new(FieldName::new("title"), SQLITE_TEXT, true),
];

#[cfg(feature = "mediatime")]
const _: () = assert!(CLIP_COLUMNS[2].width() == 6);

/// The graph's walk, as a root's emitted `init` writes one.
fn type_iter<V>(v: &mut V) -> Result<(), V::Error>
where
  V: crate::TypeVisitor,
  Asset: Describe<V::Db>,
{
  v.next_type::<Asset>()
}

/// Every statement one dialect renders for a descriptor, in order.
fn statements<Db: super::AsyncSchemaDialect>(table: &Table) -> Vec<String> {
  table.create::<Db>().expect("this descriptor renders")
}

/// SQLite's rendering, and the equivalence.
#[cfg(feature = "sqlite")]
mod sqlite {
  use super::{Asset, Describe, statements};

  /// **The whole schema a SHAPED all-leaf descriptor renders**, composition and all: the table, the
  /// unique index, the plain one, and the collection's edge table with its containment index.
  #[test]
  fn a_shaped_all_leaf_record_renders_its_whole_schema() {
    assert_eq!(
      statements::<sqlx::Sqlite>(&<Asset as Describe<sqlx::Sqlite>>::BLUEPRINT),
      [
        r#"CREATE TABLE IF NOT EXISTS "asset" ("id" INTEGER NOT NULL, "title" TEXT, "checksum" TEXT NOT NULL, PRIMARY KEY ("id"))"#,
        r#"CREATE UNIQUE INDEX IF NOT EXISTS "__ig_asset_checksum" ON "asset" ("checksum")"#,
        r#"CREATE INDEX IF NOT EXISTS "__ig_asset_title" ON "asset" ("title")"#,
        r#"CREATE TABLE IF NOT EXISTS "asset_tags" ("id" INTEGER NOT NULL, "tags_ordinal" INTEGER NOT NULL, "tags" TEXT NOT NULL, PRIMARY KEY ("id", "tags_ordinal"))"#,
        r#"CREATE INDEX IF NOT EXISTS "__ig_asset_tags_element" ON "asset_tags" ("id", "tags")"#,
      ]
    );
  }

  /// **THE EQUIVALENCE, byte for byte.** A shaped blueprint and the hand-flat descriptor naming the
  /// same columns render the IDENTICAL statement sequence — which is the whole claim the second road
  /// rests on, and the one an assertion about either road alone cannot make.
  #[test]
  fn a_shaped_blueprint_and_its_hand_flat_twin_render_one_statement_sequence() {
    assert_eq!(
      statements::<sqlx::Sqlite>(&<Asset as Describe<sqlx::Sqlite>>::BLUEPRINT),
      statements::<sqlx::Sqlite>(&super::ASSET_FLAT)
    );
  }

  /// **The join reaches a statement**, and it reaches it bracketed: `tb_num` and the SIX columns a
  /// `MediaTimeRange` field spans are what the renderer makes of `tb` above `num` and `span` above a
  /// range's own five segments — none of them a string in the descriptor.
  /// **The two grains, in one statement.** `span` is a REQUIRED field, so its four value columns
  /// take `NOT NULL` — and its two nanosecond ones do not, because that bit is the LEAF's
  /// (`ColumnShape::Nullable`, a computation that declines past the ceiling) and the field's marker
  /// never reaches it. Being derived is not what drops the `NOT NULL`: a derived leaf whose
  /// computation is total says `ColumnShape::Derived` and keeps it, which is `BoundingBox`'s `area`
  /// one house over. `title` is the mirror case: an optional SCALAR, nullable by the field's own
  /// flag. One statement, both grains, and neither one able to state the other.
  #[cfg(feature = "mediatime")]
  #[test]
  fn a_composite_field_renders_the_columns_its_type_names() {
    assert_eq!(
      statements::<sqlx::Sqlite>(&<super::Clip as Describe<sqlx::Sqlite>>::BLUEPRINT),
      [
        r#"CREATE TABLE IF NOT EXISTS "clip" ("id" INTEGER NOT NULL, "tb_num" INTEGER NOT NULL, "tb_den" INTEGER NOT NULL, "span_start_pts" INTEGER NOT NULL, "span_end_pts" INTEGER NOT NULL, "span_timebase_num" INTEGER NOT NULL, "span_timebase_den" INTEGER NOT NULL, "span_start_nanos" INTEGER, "span_end_nanos" INTEGER, "title" TEXT, PRIMARY KEY ("id"))"#,
      ]
    );
  }

  /// The same equivalence at the COMPOSITE grain, which is where the two roads could actually
  /// differ: nine names, eight of them joined on one side and hand-written on the other.
  #[cfg(feature = "mediatime")]
  #[test]
  fn the_composite_shaped_blueprint_matches_its_hand_flat_twin_byte_for_byte() {
    assert_eq!(
      statements::<sqlx::Sqlite>(&<super::Clip as Describe<sqlx::Sqlite>>::BLUEPRINT),
      statements::<sqlx::Sqlite>(&super::CLIP_FLAT)
    );
  }

  /// **A field's OPTIONALITY reaches every column it spans**, which is the other grain: the
  /// declaration says the whole field may be absent, so the same descriptor with `span` marked
  /// nullable renders all SIX of its columns without `NOT NULL` — the two the type already made
  /// nullable and the four it did not — and the plain leaf beside it is untouched.
  ///
  /// Read beside `a_composite_field_renders_the_columns_its_type_names`, this is the composition's
  /// second half: there the marker is absent and only the derived pair is bare; here the marker is
  /// present and all six are. Neither grain can produce the other's statement.
  #[cfg(feature = "mediatime")]
  #[test]
  fn a_nullable_composite_field_renders_every_one_of_its_columns_nullable() {
    const NULLABLE: crate::Table = crate::Table::shaped(
      super::CLIP,
      super::CLIP_COLUMNS,
      &[
        <i64 as crate::StoredAs<sqlx::Sqlite>>::WORDS,
        <crate::Timebase as crate::StoredAs<sqlx::Sqlite>>::WORDS,
        <Option<crate::MediaTimeRange> as crate::StoredAs<sqlx::Sqlite>>::WORDS,
        <Option<String> as crate::StoredAs<sqlx::Sqlite>>::WORDS,
      ],
      &[false, false, true, true],
    );

    assert_eq!(
      statements::<sqlx::Sqlite>(&NULLABLE),
      [
        r#"CREATE TABLE IF NOT EXISTS "clip" ("id" INTEGER NOT NULL, "tb_num" INTEGER NOT NULL, "tb_den" INTEGER NOT NULL, "span_start_pts" INTEGER, "span_end_pts" INTEGER, "span_timebase_num" INTEGER, "span_timebase_den" INTEGER, "span_start_nanos" INTEGER, "span_end_nanos" INTEGER, "title" TEXT, PRIMARY KEY ("id"))"#,
      ]
    );
  }
}

/// PostgreSQL's, which this repository provisions no server for: what is recorded is the statement
/// the dialect is SENT.
#[cfg(feature = "postgres")]
mod postgres {
  use super::{Asset, Describe, statements};

  #[test]
  fn a_shaped_all_leaf_record_renders_its_whole_schema() {
    assert_eq!(
      statements::<sqlx::Postgres>(&<Asset as Describe<sqlx::Postgres>>::BLUEPRINT),
      [
        r#"CREATE TABLE IF NOT EXISTS "asset" ("id" bigint NOT NULL, "title" text, "checksum" text NOT NULL, PRIMARY KEY ("id"))"#,
        r#"CREATE UNIQUE INDEX IF NOT EXISTS "__ig_asset_checksum" ON "asset" ("checksum")"#,
        r#"CREATE INDEX IF NOT EXISTS "__ig_asset_title" ON "asset" ("title")"#,
        r#"CREATE TABLE IF NOT EXISTS "asset_tags" ("id" bigint NOT NULL, "tags_ordinal" bigint NOT NULL, "tags" text NOT NULL, PRIMARY KEY ("id", "tags_ordinal"))"#,
        r#"CREATE INDEX IF NOT EXISTS "__ig_asset_tags_element" ON "asset_tags" ("id", "tags")"#,
      ]
    );
  }

  /// The composite grain in the dialect whose words are the STANDARD's — `smallint` for the
  /// timebase's two `i32`s beside `bigint` for the range's four `i64`s, which is a word list a
  /// hand-written descriptor gets wrong by grouping the integers together.
  #[cfg(feature = "mediatime")]
  #[test]
  fn a_composite_field_renders_the_columns_its_type_names() {
    assert_eq!(
      statements::<sqlx::Postgres>(&<super::Clip as Describe<sqlx::Postgres>>::BLUEPRINT),
      [
        r#"CREATE TABLE IF NOT EXISTS "clip" ("id" bigint NOT NULL, "tb_num" integer NOT NULL, "tb_den" integer NOT NULL, "span_start_pts" bigint NOT NULL, "span_end_pts" bigint NOT NULL, "span_timebase_num" integer NOT NULL, "span_timebase_den" integer NOT NULL, "span_start_nanos" bigint, "span_end_nanos" bigint, "title" text, PRIMARY KEY ("id"))"#,
      ]
    );
  }
}

/// MySQL's, whose bracket is a BACKTICK — the one place a wrong quote character would be a silent
/// wrong answer rather than a syntax error, and the reason the whole statement is asserted here too.
#[cfg(feature = "mysql")]
mod mysql {
  use super::{Asset, Describe, statements};

  #[test]
  fn a_shaped_all_leaf_record_renders_its_whole_schema() {
    assert_eq!(
      statements::<sqlx::MySql>(&<Asset as Describe<sqlx::MySql>>::BLUEPRINT),
      [
        "CREATE TABLE IF NOT EXISTS `asset` (`id` bigint NOT NULL, `title` varchar(255), `checksum` varchar(255) NOT NULL, PRIMARY KEY (`id`))",
        "CREATE UNIQUE INDEX IF NOT EXISTS `__ig_asset_checksum` ON `asset` (`checksum`)",
        "CREATE INDEX IF NOT EXISTS `__ig_asset_title` ON `asset` (`title`)",
        "CREATE TABLE IF NOT EXISTS `asset_tags` (`id` bigint NOT NULL, `tags_ordinal` BIGINT NOT NULL, `tags` varchar(255) NOT NULL, PRIMARY KEY (`id`, `tags_ordinal`))",
        "CREATE INDEX IF NOT EXISTS `__ig_asset_tags_element` ON `asset_tags` (`id`, `tags`)",
      ]
    );
  }

  #[cfg(feature = "mediatime")]
  #[test]
  fn a_composite_field_renders_the_columns_its_type_names() {
    assert_eq!(
      statements::<sqlx::MySql>(&<super::Clip as Describe<sqlx::MySql>>::BLUEPRINT),
      [
        "CREATE TABLE IF NOT EXISTS `clip` (`id` bigint NOT NULL, `tb_num` int NOT NULL, `tb_den` int NOT NULL, `span_start_pts` bigint NOT NULL, `span_end_pts` bigint NOT NULL, `span_timebase_num` int NOT NULL, `span_timebase_den` int NOT NULL, `span_start_nanos` bigint, `span_end_nanos` bigint, `title` varchar(255), PRIMARY KEY (`id`))",
      ]
    );
  }
}

/// The half no statement's text can show, put to a real engine — the shaped road's own two-readers
/// proof.
#[cfg(feature = "sqlite")]
mod live {
  use sqlx::Sqlite;

  use super::type_iter;
  use crate::query::sql::{Create, SqlSchemaError, Validate};

  /// An EMPTY in-memory database on ONE connection — the ddl corpus's own fixture, minus the
  /// foreign-key pragma, there being no provenance table here to enforce one for.
  async fn empty() -> sqlx::sqlite::SqliteConnection {
    use sqlx::Connection as _;

    sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
      .await
      .expect("an in-memory database")
  }

  async fn create(db: &mut sqlx::sqlite::SqliteConnection) -> Result<(), SqlSchemaError> {
    let mut create = Create::<Sqlite>::new();
    type_iter(&mut create)?;
    create.run(db).await
  }

  /// The COMPOSITE record's own schema, through the same visitor — so the statements the engine is
  /// sent are the ones the walk renders and not a second spelling assembled here.
  #[cfg(feature = "mediatime")]
  async fn create_clip(db: &mut sqlx::sqlite::SqliteConnection) -> Result<(), SqlSchemaError> {
    let mut create = Create::<Sqlite>::new();
    crate::TypeVisitor::next_type::<super::Clip>(&mut create)?;
    create.run(db).await
  }

  async fn validate(db: &mut sqlx::sqlite::SqliteConnection) -> Result<(), SqlSchemaError> {
    let mut validate = Validate::<Sqlite>::new();
    type_iter(&mut validate)?;
    validate.audit(db).await
  }

  /// Every column SQLite says a table has, and the type it says each is stored at — the CATALOGUE's
  /// own answer, read outside the lane so that nothing here is comparing the create against itself.
  ///
  /// Gated with its ONE caller: the live-engine test below is `mediatime`'s, so a build without that
  /// word compiles a helper nobody asks — which is dead code, and is what `--each-feature` exists to
  /// find.
  #[cfg(feature = "mediatime")]
  async fn echoed(db: &mut sqlx::sqlite::SqliteConnection, table: &str) -> Vec<(String, String)> {
    sqlx::query_as::<_, (String, String)>(
      r#"SELECT "name", "type" FROM pragma_table_info(?) ORDER BY "cid""#,
    )
    .bind(table)
    .fetch_all(db)
    .await
    .expect("the catalogue answers")
  }

  /// **The engine takes a shaped blueprint, and the catalogue echoes the joined names back.** No
  /// rendering assertion can say either half: a statement that renders is not a statement that runs,
  /// and a name this crate joined is only a real column once the engine holds one.
  #[cfg(feature = "mediatime")]
  #[tokio::test]
  async fn a_live_engine_takes_the_joined_columns_and_names_them_back() {
    let mut db = empty().await;
    create_clip(&mut db).await.expect("the engine takes it");

    assert_eq!(
      echoed(&mut db, "clip").await,
      [
        ("id", "INTEGER"),
        ("tb_num", "INTEGER"),
        ("tb_den", "INTEGER"),
        ("span_start_pts", "INTEGER"),
        ("span_end_pts", "INTEGER"),
        ("span_timebase_num", "INTEGER"),
        ("span_timebase_den", "INTEGER"),
        ("span_start_nanos", "INTEGER"),
        ("span_end_nanos", "INTEGER"),
        ("title", "TEXT"),
      ]
      .map(|(name, ty)| (name.to_owned(), ty.to_owned()))
    );
  }

  /// **The audit passes what the create made, at the SHAPED grain.** The two visitors are the same
  /// two the flat road has and neither is told what the other did — one joins the names into a
  /// `CREATE TABLE` and the other joins them into a question for the catalogue.
  #[tokio::test]
  async fn the_audit_passes_the_shaped_schema_the_create_made() {
    let mut db = empty().await;
    create(&mut db).await.expect("the schema is created");
    validate(&mut db).await.expect("and it is the declared one");
  }

  /// **A drift under a joined name is reported under that name.** `span_timebase_den` is not a
  /// string in the descriptor, so the audit that names it built it — through the same walk the
  /// create built it with, which is the whole of what makes the two readers one reader.
  #[cfg(feature = "mediatime")]
  #[tokio::test]
  async fn a_dropped_segment_column_is_named_as_the_renderer_joins_it() {
    let mut db = empty().await;
    create_clip(&mut db).await.expect("the schema is created");
    sqlx::query(r#"ALTER TABLE "clip" DROP COLUMN "span_timebase_den""#)
      .execute(&mut db)
      .await
      .expect("the drift is applied");

    let mut validate = Validate::<Sqlite>::new();
    crate::TypeVisitor::next_type::<super::Clip>(&mut validate)
      .expect("collecting refuses nothing");
    let Err(SqlSchemaError::Column { table, column }) = validate.audit(&mut db).await else {
      panic!("a declared column that is gone is drift");
    };
    assert_eq!(table, crate::FieldName::new("clip"));
    assert_eq!(column, "span_timebase_den");
  }

  /// **A second create over the same database changes nothing**, which is what `IF NOT EXISTS` buys
  /// a boot sequence — and it is asserted here too because a shaped blueprint renders the clause
  /// through the same path.
  #[tokio::test]
  async fn a_second_create_over_the_same_database_changes_nothing() {
    let mut db = empty().await;
    create(&mut db).await.expect("the first create lands");
    create(&mut db).await.expect("and so does the second");
    validate(&mut db).await.expect("and it is still declared");
  }

  /// **The unique index has TEETH**, which is the half of the composition proof a rendered statement
  /// cannot show: the word reached the engine as a constraint rather than as a plain index.
  #[tokio::test]
  async fn the_unique_word_on_a_shaped_descriptor_refuses_a_duplicate() {
    let mut db = empty().await;
    create(&mut db).await.expect("the schema is created");

    sqlx::query(r#"INSERT INTO "asset" ("id", "checksum") VALUES (1, 'abc')"#)
      .execute(&mut db)
      .await
      .expect("the first row lands");
    let Err(why) = sqlx::query(r#"INSERT INTO "asset" ("id", "checksum") VALUES (2, 'abc')"#)
      .execute(&mut db)
      .await
    else {
      panic!("a second row with the same checksum is what the unique word refuses");
    };
    assert!(
      why.to_string().contains("UNIQUE constraint failed"),
      "the engine's own sentence: {why}"
    );
  }
}