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
//! The statements a three-node graph creates, per dialect — and, against a live SQLite, what a
//! rendered statement cannot show.
//!
//! # The graph is hand-written, for the write lane'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: three [`Describe`] impls per dialect and a walk over
//! them, through nothing but this crate's public items.
//!
//! The three are a root, a child, and a FAN-IN under the split layout — so every shape the DDL has a
//! clause for is created by the same walk: the address law's `UNIQUE`, an edge table per collection,
//! and a provenance table per upstream with the foreign key that ties it to the common row.
//!
//! # What is asserted where
//!
//! The TEXT is asserted per dialect, in a module apiece, so an assertion whose subject is a dialect
//! runs in the lane carrying only that dialect. What the text cannot show — a schema that renders
//! and does not execute, a foreign key that is parsed and not enforced, an audit that passes a
//! database it never read, a drift it does not name — runs live against SQLite, in `mod live`.

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

use crate::{
  Column, ColumnName, ColumnShape, Describe, EdgeShape, EdgeTable, FieldName, RecordAddress,
  SideTable, Table, TypeVisitor,
  query::sql::{AsyncSchemaDialect, Create},
};

/// A ROOT: one key column, one nullable column, and one indexed field.
///
/// Its key is ONE column, so its primary key already carries the uniqueness the address law needs
/// and no `UNIQUE` clause is rendered — which is the half of that law a child cannot show.
struct Media;

/// A CHILD: a two-column key whose address is the id alone, a nullable column, and one collection of
/// each SHAPE.
///
/// The same fixture shape the write lane's own corpus carries, for the same reason: an edge table
/// correlates on the WHOLE key, so a one-column key could not show what the leading columns of a
/// second table are.
struct Clip;

/// A FAN-IN: two independent upstreams, a uniform payload, and the SPLIT LAYOUT its ancestry goes
/// in.
///
/// Its key is the id alone, which is what an M×N node's is: it mints its own identity, and which
/// upstream a row descends from is the discriminant beside the payload rather than a column of the
/// key. So no `UNIQUE` clause is rendered and the foreign keys point at the primary key itself.
struct Caption;

/// The parent table's columns, as a row's own `SELECT` list names them — what the descriptors below
/// state their agreement with.
const CLIP_COLUMNS: &[ColumnShape] = &[
  ColumnShape::Plain(ColumnName::new("media_id")),
  ColumnShape::Plain(ColumnName::new("id")),
  ColumnShape::Plain(ColumnName::new("title")),
  ColumnShape::Plain(ColumnName::new("bit_rate")),
];

/// The address, written ONCE and projected by all three descriptors: a table's name and its key
/// columns are the same in every database, and only the types are not.
const CLIP: RecordAddress = RecordAddress::new(
  FieldName::new("clip"),
  &[FieldName::new("media_id"), FieldName::new("id")],
);

const MEDIA: RecordAddress = RecordAddress::new(FieldName::new("media"), &[FieldName::new("id")]);

const CAPTION: RecordAddress =
  RecordAddress::new(FieldName::new("caption"), &[FieldName::new("id")]);

/// The discriminant column, named once for all three dialects: the WORD a row's upstream is read
/// out of is one vocabulary everywhere it is spelled, so what differs per dialect is the type it is
/// stored at and nothing else.
const SOURCE: &FieldName = FieldName::new("__ig_source__");

/// The provenance tables' names, likewise. `snake(variant)` under the record's own table is the
/// convention a declaration takes by default, and it is a NAME rather than a derivation — a
/// provenance table can be renamed per database where an edge table cannot be renamed at all.
const FROM_FRAME: &FieldName = FieldName::new("caption_frame");
const FROM_TURN: &FieldName = FieldName::new("caption_turn");

/// The collections, likewise: which column is a collection and what shape it takes are facts about
/// the DECLARATION, so only the element's stored type is per dialect.
const TAGS: &[&FieldName] = &[FieldName::new("tags")];
const NOTES: &[&FieldName] = &[FieldName::new("notes")];

#[cfg(feature = "sqlite")]
impl Describe<sqlx::Sqlite> for Media {
  const BLUEPRINT: Table = Table::new(
    MEDIA,
    &[
      Column::new(FieldName::new("id"), "INTEGER", false),
      Column::new(FieldName::new("title"), "TEXT", true),
    ],
  )
  .with_indexes(&[FieldName::new("title")]);
}

#[cfg(feature = "sqlite")]
impl Describe<sqlx::Sqlite> for Clip {
  const BLUEPRINT: Table = Table::new(
    CLIP,
    &[
      Column::new(FieldName::new("media_id"), "INTEGER", false),
      Column::new(FieldName::new("id"), "INTEGER", false),
      Column::new(FieldName::new("title"), "TEXT", true),
      Column::new(FieldName::new("bit_rate"), "INTEGER", false),
    ],
  )
  .with_edges(&[
    EdgeTable::new(TAGS, EdgeShape::Sequence, "TEXT"),
    EdgeTable::new(NOTES, EdgeShape::Set, "TEXT"),
  ]);
}

/// The SPLIT LAYOUT, in the dialect the live walk below puts it to: a common table carrying the id,
/// the discriminant and the uniform payload, and one provenance table per upstream carrying that
/// variant's ancestors.
///
/// A `Frame` is a child of a media, so its key is two columns and its provenance table carries both.
/// A `SpeakerTurn` is a root, so its key is its id and its provenance table carries one. The two
/// shapes are the point: a single table would have to hold every one of these columns nullable.
#[cfg(feature = "sqlite")]
impl Describe<sqlx::Sqlite> for Caption {
  const BLUEPRINT: Table = Table::new(
    CAPTION,
    &[
      Column::new(FieldName::new("id"), "INTEGER", false),
      Column::new(
        SOURCE,
        <sqlx::Sqlite as AsyncSchemaDialect>::DISCRIMINANT,
        false,
      ),
      Column::new(FieldName::new("text"), "TEXT", false),
    ],
  )
  .with_provenance(
    SOURCE,
    &[
      SideTable::new(
        FROM_FRAME,
        &[
          Column::new(FieldName::new("media_id"), "INTEGER", false),
          Column::new(FieldName::new("frame"), "INTEGER", false),
        ],
      ),
      SideTable::new(
        FROM_TURN,
        &[Column::new(FieldName::new("turn"), "INTEGER", false)],
      ),
    ],
  );
}

#[cfg(feature = "postgres")]
impl Describe<sqlx::Postgres> for Media {
  const BLUEPRINT: Table = Table::new(
    MEDIA,
    &[
      Column::new(FieldName::new("id"), "bigint", false),
      Column::new(FieldName::new("title"), "text", true),
    ],
  )
  .with_indexes(&[FieldName::new("title")]);
}

#[cfg(feature = "postgres")]
impl Describe<sqlx::Postgres> for Clip {
  const BLUEPRINT: Table = Table::new(
    CLIP,
    &[
      Column::new(FieldName::new("media_id"), "bigint", false),
      Column::new(FieldName::new("id"), "bigint", false),
      Column::new(FieldName::new("title"), "text", true),
      Column::new(FieldName::new("bit_rate"), "bigint", false),
    ],
  )
  .with_edges(&[
    EdgeTable::new(TAGS, EdgeShape::Sequence, "text"),
    EdgeTable::new(NOTES, EdgeShape::Set, "text"),
  ]);
}

#[cfg(feature = "postgres")]
impl Describe<sqlx::Postgres> for Caption {
  const BLUEPRINT: Table = Table::new(
    CAPTION,
    &[
      Column::new(FieldName::new("id"), "bigint", false),
      Column::new(
        SOURCE,
        <sqlx::Postgres as AsyncSchemaDialect>::DISCRIMINANT,
        false,
      ),
      Column::new(FieldName::new("text"), "text", false),
    ],
  )
  .with_provenance(
    SOURCE,
    &[
      SideTable::new(
        FROM_FRAME,
        &[
          Column::new(FieldName::new("media_id"), "bigint", false),
          Column::new(FieldName::new("frame"), "bigint", false),
        ],
      ),
      SideTable::new(
        FROM_TURN,
        &[Column::new(FieldName::new("turn"), "bigint", false)],
      ),
    ],
  );
}

#[cfg(feature = "mysql")]
impl Describe<sqlx::MySql> for Media {
  const BLUEPRINT: Table = Table::new(
    MEDIA,
    &[
      Column::new(FieldName::new("id"), "BIGINT", false),
      Column::new(FieldName::new("title"), "VARCHAR(255)", true),
    ],
  )
  .with_indexes(&[FieldName::new("title")]);
}

#[cfg(feature = "mysql")]
impl Describe<sqlx::MySql> for Clip {
  const BLUEPRINT: Table = Table::new(
    CLIP,
    &[
      Column::new(FieldName::new("media_id"), "BIGINT", false),
      Column::new(FieldName::new("id"), "BIGINT", false),
      Column::new(FieldName::new("title"), "VARCHAR(255)", true),
      Column::new(FieldName::new("bit_rate"), "BIGINT", false),
    ],
  )
  .with_edges(&[
    EdgeTable::new(TAGS, EdgeShape::Sequence, "VARCHAR(255)"),
    EdgeTable::new(NOTES, EdgeShape::Set, "VARCHAR(255)"),
  ]);
}

#[cfg(feature = "mysql")]
impl Describe<sqlx::MySql> for Caption {
  const BLUEPRINT: Table = Table::new(
    CAPTION,
    &[
      Column::new(FieldName::new("id"), "BIGINT", false),
      Column::new(
        SOURCE,
        <sqlx::MySql as AsyncSchemaDialect>::DISCRIMINANT,
        false,
      ),
      Column::new(FieldName::new("text"), "VARCHAR(255)", false),
    ],
  )
  .with_provenance(
    SOURCE,
    &[
      SideTable::new(
        FROM_FRAME,
        &[
          Column::new(FieldName::new("media_id"), "BIGINT", false),
          Column::new(FieldName::new("frame"), "BIGINT", false),
        ],
      ),
      SideTable::new(
        FROM_TURN,
        &[Column::new(FieldName::new("turn"), "BIGINT", false)],
      ),
    ],
  );
}

/// The graph root's walk, as `#[ingraph::graph]` writes it — one
/// [`Describe`](crate::Describe) predicate per field, discharged by whoever drives the walk.
fn type_iter<V>(v: &mut V) -> Result<(), V::Error>
where
  V: TypeVisitor,
  Media: Describe<V::Db>,
  Clip: Describe<V::Db>,
  Caption: Describe<V::Db>,
{
  v.next_type::<Media>()?;
  v.next_type::<Clip>()?;
  v.next_type::<Caption>()
}

/// Every statement the graph renders for one dialect, in walk order.
fn schema<Db>() -> Vec<String>
where
  Db: super::AsyncSchemaDialect,
  Media: Describe<Db>,
  Clip: Describe<Db>,
  Caption: Describe<Db>,
{
  let mut create = Create::<Db>::new();
  type_iter(&mut create).expect("every descriptor in this graph renders");
  create.statements().to_vec()
}

/// The audit the descriptors state against the row's own column list, in the position an emitted one
/// would occupy. It is per DIALECT, because a rename is per database and the audit is what would
/// catch one that moved on the row and not on the descriptor.
#[cfg(feature = "sqlite")]
const _: () = assert!(crate::describes(
  &<Clip as Describe<sqlx::Sqlite>>::BLUEPRINT,
  CLIP_COLUMNS
));
#[cfg(feature = "postgres")]
const _: () = assert!(crate::describes(
  &<Clip as Describe<sqlx::Postgres>>::BLUEPRINT,
  CLIP_COLUMNS
));
#[cfg(feature = "mysql")]
const _: () = assert!(crate::describes(
  &<Clip as Describe<sqlx::MySql>>::BLUEPRINT,
  CLIP_COLUMNS
));

/// The statement one dialect's audit sends to ask what it stores.
fn probe<Db: super::AsyncSchemaDialect>() -> String {
  Db::probe(FieldName::new("clip"))
    .into_sql()
    .as_str()
    .to_owned()
}

/// SQLite's rendering, verbatim.
#[cfg(feature = "sqlite")]
mod sqlite {
  use super::{probe, schema};

  /// The CATALOGUE probe the audit runs, whose text is the whole of what this dialect was measured
  /// on where no server exists to answer it.
  #[test]
  fn the_audit_probes_this_dialects_own_catalogue() {
    assert_eq!(
      probe::<sqlx::Sqlite>(),
      r#"SELECT "name", "type" FROM pragma_table_info(?)"#
    );
  }

  /// The whole graph, statement for statement.
  ///
  /// The root renders NO `UNIQUE`: its key is one column and the primary key already carries the
  /// uniqueness the address law asks for. The child renders one, because its primary key is the
  /// whole two-column chain and `get` names a row by the id alone.
  ///
  /// The FAN-IN's three statements are the split layout: the common table carrying the id, the
  /// discriminant and the payload, then one provenance table per upstream whose id is at once its
  /// primary key and the foreign key into the common row.
  #[test]
  fn the_graph_renders_its_whole_schema() {
    assert_eq!(
      schema::<sqlx::Sqlite>(),
      [
        r#"CREATE TABLE IF NOT EXISTS "media" ("id" INTEGER NOT NULL, "title" TEXT, PRIMARY KEY ("id"))"#,
        r#"CREATE INDEX IF NOT EXISTS "__ig_media_title" ON "media" ("title")"#,
        r#"CREATE TABLE IF NOT EXISTS "clip" ("media_id" INTEGER NOT NULL, "id" INTEGER NOT NULL, "title" TEXT, "bit_rate" INTEGER NOT NULL, PRIMARY KEY ("media_id", "id"), UNIQUE ("id"))"#,
        r#"CREATE TABLE IF NOT EXISTS "clip_tags" ("media_id" INTEGER NOT NULL, "id" INTEGER NOT NULL, "tags_ordinal" INTEGER NOT NULL, "tags" TEXT NOT NULL, PRIMARY KEY ("media_id", "id", "tags_ordinal"))"#,
        r#"CREATE INDEX IF NOT EXISTS "__ig_clip_tags_element" ON "clip_tags" ("media_id", "id", "tags")"#,
        r#"CREATE TABLE IF NOT EXISTS "clip_notes" ("media_id" INTEGER NOT NULL, "id" INTEGER NOT NULL, "notes" TEXT NOT NULL, PRIMARY KEY ("media_id", "id", "notes"))"#,
        r#"CREATE TABLE IF NOT EXISTS "caption" ("id" INTEGER NOT NULL, "__ig_source__" TEXT NOT NULL, "text" TEXT NOT NULL, PRIMARY KEY ("id"))"#,
        r#"CREATE TABLE IF NOT EXISTS "caption_frame" ("id" INTEGER NOT NULL, "media_id" INTEGER NOT NULL, "frame" INTEGER NOT NULL, PRIMARY KEY ("id"), FOREIGN KEY ("id") REFERENCES "caption" ("id"))"#,
        r#"CREATE TABLE IF NOT EXISTS "caption_turn" ("id" INTEGER NOT NULL, "turn" INTEGER NOT NULL, PRIMARY KEY ("id"), FOREIGN KEY ("id") REFERENCES "caption" ("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::{probe, schema};

  /// The CATALOGUE probe the audit runs, whose text is the whole of what this dialect was measured
  /// on where no server exists to answer it.
  #[test]
  fn the_audit_probes_this_dialects_own_catalogue() {
    assert_eq!(
      probe::<sqlx::Postgres>(),
      "SELECT column_name, data_type FROM information_schema.columns WHERE table_name = $1"
    );
  }

  #[test]
  fn the_graph_renders_its_whole_schema() {
    assert_eq!(
      schema::<sqlx::Postgres>(),
      [
        r#"CREATE TABLE IF NOT EXISTS "media" ("id" bigint NOT NULL, "title" text, PRIMARY KEY ("id"))"#,
        r#"CREATE INDEX IF NOT EXISTS "__ig_media_title" ON "media" ("title")"#,
        r#"CREATE TABLE IF NOT EXISTS "clip" ("media_id" bigint NOT NULL, "id" bigint NOT NULL, "title" text, "bit_rate" bigint NOT NULL, PRIMARY KEY ("media_id", "id"), UNIQUE ("id"))"#,
        r#"CREATE TABLE IF NOT EXISTS "clip_tags" ("media_id" bigint NOT NULL, "id" bigint NOT NULL, "tags_ordinal" bigint NOT NULL, "tags" text NOT NULL, PRIMARY KEY ("media_id", "id", "tags_ordinal"))"#,
        r#"CREATE INDEX IF NOT EXISTS "__ig_clip_tags_element" ON "clip_tags" ("media_id", "id", "tags")"#,
        r#"CREATE TABLE IF NOT EXISTS "clip_notes" ("media_id" bigint NOT NULL, "id" bigint NOT NULL, "notes" text NOT NULL, PRIMARY KEY ("media_id", "id", "notes"))"#,
        r#"CREATE TABLE IF NOT EXISTS "caption" ("id" bigint NOT NULL, "__ig_source__" text NOT NULL, "text" text NOT NULL, PRIMARY KEY ("id"))"#,
        r#"CREATE TABLE IF NOT EXISTS "caption_frame" ("id" bigint NOT NULL, "media_id" bigint NOT NULL, "frame" bigint NOT NULL, PRIMARY KEY ("id"), FOREIGN KEY ("id") REFERENCES "caption" ("id"))"#,
        r#"CREATE TABLE IF NOT EXISTS "caption_turn" ("id" bigint NOT NULL, "turn" bigint NOT NULL, PRIMARY KEY ("id"), FOREIGN KEY ("id") REFERENCES "caption" ("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, which is why the whole schema is asserted here too
/// rather than the difference alone.
#[cfg(feature = "mysql")]
mod mysql {
  use super::{probe, schema};

  /// The CATALOGUE probe the audit runs, whose text is the whole of what this dialect was measured
  /// on where no server exists to answer it.
  #[test]
  fn the_audit_probes_this_dialects_own_catalogue() {
    assert_eq!(
      probe::<sqlx::MySql>(),
      "SELECT COLUMN_NAME, COLUMN_TYPE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = \
       DATABASE() AND TABLE_NAME = ?"
    );
  }

  #[test]
  fn the_graph_renders_its_whole_schema() {
    assert_eq!(
      schema::<sqlx::MySql>(),
      [
        "CREATE TABLE IF NOT EXISTS `media` (`id` BIGINT NOT NULL, `title` VARCHAR(255), PRIMARY KEY (`id`))",
        "CREATE INDEX IF NOT EXISTS `__ig_media_title` ON `media` (`title`)",
        "CREATE TABLE IF NOT EXISTS `clip` (`media_id` BIGINT NOT NULL, `id` BIGINT NOT NULL, `title` VARCHAR(255), `bit_rate` BIGINT NOT NULL, PRIMARY KEY (`media_id`, `id`), UNIQUE (`id`))",
        "CREATE TABLE IF NOT EXISTS `clip_tags` (`media_id` BIGINT NOT NULL, `id` BIGINT NOT NULL, `tags_ordinal` BIGINT NOT NULL, `tags` VARCHAR(255) NOT NULL, PRIMARY KEY (`media_id`, `id`, `tags_ordinal`))",
        "CREATE INDEX IF NOT EXISTS `__ig_clip_tags_element` ON `clip_tags` (`media_id`, `id`, `tags`)",
        "CREATE TABLE IF NOT EXISTS `clip_notes` (`media_id` BIGINT NOT NULL, `id` BIGINT NOT NULL, `notes` VARCHAR(255) NOT NULL, PRIMARY KEY (`media_id`, `id`, `notes`))",
        "CREATE TABLE IF NOT EXISTS `caption` (`id` BIGINT NOT NULL, `__ig_source__` VARCHAR(255) NOT NULL, `text` VARCHAR(255) NOT NULL, PRIMARY KEY (`id`))",
        "CREATE TABLE IF NOT EXISTS `caption_frame` (`id` BIGINT NOT NULL, `media_id` BIGINT NOT NULL, `frame` BIGINT NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`id`) REFERENCES `caption` (`id`))",
        "CREATE TABLE IF NOT EXISTS `caption_turn` (`id` BIGINT NOT NULL, `turn` BIGINT NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`id`) REFERENCES `caption` (`id`))",
      ]
    );
  }
}

/// A CHILD under the split layout: the provenance tables point at the id, and the id is unique
/// because the address law's `UNIQUE` clause says so rather than because the primary key does.
///
/// Asserted apart from the graph above because it is the pairing that makes the foreign key
/// legal at all — a constraint naming a parent column no constraint constrains is refused by every
/// dialect here — and the graph's own fan-in is a root, where the primary key carries it.
#[cfg(feature = "sqlite")]
#[test]
fn a_lineage_bearing_fan_in_points_its_provenance_at_the_unique_id() {
  const CUE: Table = Table::new(
    RecordAddress::new(
      FieldName::new("cue"),
      &[FieldName::new("media_id"), FieldName::new("id")],
    ),
    &[
      Column::new(FieldName::new("media_id"), "INTEGER", false),
      Column::new(FieldName::new("id"), "INTEGER", false),
      Column::new(
        SOURCE,
        <sqlx::Sqlite as AsyncSchemaDialect>::DISCRIMINANT,
        false,
      ),
    ],
  )
  .with_provenance(
    SOURCE,
    &[SideTable::new(
      FieldName::new("cue_frame"),
      &[Column::new(FieldName::new("frame"), "INTEGER", false)],
    )],
  );

  assert_eq!(
    CUE
      .create::<sqlx::Sqlite>()
      .expect("this descriptor renders"),
    [
      r#"CREATE TABLE IF NOT EXISTS "cue" ("media_id" INTEGER NOT NULL, "id" INTEGER NOT NULL, "__ig_source__" TEXT NOT NULL, PRIMARY KEY ("media_id", "id"), UNIQUE ("id"))"#,
      r#"CREATE TABLE IF NOT EXISTS "cue_frame" ("id" INTEGER NOT NULL, "frame" INTEGER NOT NULL, PRIMARY KEY ("id"), FOREIGN KEY ("id") REFERENCES "cue" ("id"))"#,
    ]
  );
}

/// The half no statement's text can show, put to a real engine.
#[cfg(feature = "sqlite")]
mod live {
  use sqlx::Sqlite;

  use super::{Caption, Clip, Describe, Media, type_iter};
  use crate::{
    FieldName,
    query::sql::{Create, SqlSchemaError, Validate},
  };

  /// An EMPTY in-memory database, on ONE connection, with FOREIGN KEYS ON.
  ///
  /// 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
  /// created on a second one would be invisible here.
  ///
  /// The pragma is the CONNECTION's posture and it is sent here because here is where the connection
  /// is made. SQLite parses a foreign key and ignores it unless a connection asks, the default being
  /// OFF for backwards compatibility — so a caller that wants the constraint the schema declares
  /// sends this, and this corpus is what measures that the constraint has teeth once it does.
  async fn empty() -> sqlx::sqlite::SqliteConnection {
    use sqlx::Connection as _;

    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");
    db
  }

  /// Create the graph's whole schema on `db`.
  async fn create(db: &mut sqlx::sqlite::SqliteConnection) -> Result<(), SqlSchemaError> {
    let mut create = Create::<Sqlite>::new();
    type_iter(&mut create)?;
    create.run(db).await
  }

  /// Audit it against what the database actually stores.
  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 table SQLite holds, in name order — read outside the lane, which is the only way to see
  /// that a statement did more than render.
  async fn tables(db: &mut sqlx::sqlite::SqliteConnection) -> Vec<String> {
    sqlx::query_scalar::<_, String>(
      "SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY \
       name",
    )
    .fetch_all(db)
    .await
    .expect("the catalogue answers")
  }

  /// Every index SQLite holds that a `CREATE INDEX` made, in name order. The implicit ones a
  /// `UNIQUE` or a primary key builds are excluded — they carry no `sql`, which is exactly what
  /// tells them apart.
  async fn indexes(db: &mut sqlx::sqlite::SqliteConnection) -> Vec<String> {
    sqlx::query_scalar::<_, String>(
      "SELECT name FROM sqlite_schema WHERE type = 'index' AND sql IS NOT NULL ORDER BY name",
    )
    .fetch_all(db)
    .await
    .expect("the catalogue answers")
  }

  /// Every table the graph declares, in the order the catalogue lists them.
  const DECLARED: [&str; 7] = [
    "caption",
    "caption_frame",
    "caption_turn",
    "clip",
    "clip_notes",
    "clip_tags",
    "media",
  ];

  /// **The whole schema, created.** Nine statements, seven tables and two indexes — and the engine
  /// accepted every one of them, which no rendering assertion can say. The three provenance tables
  /// are among them, with their foreign keys taken rather than merely rendered.
  #[tokio::test]
  async fn the_walk_creates_every_table_and_index_the_graph_declares() {
    let mut db = empty().await;
    create(&mut db).await.expect("an empty database takes it");

    assert_eq!(tables(&mut db).await, DECLARED);
    assert_eq!(
      indexes(&mut db).await,
      ["__ig_clip_tags_element", "__ig_media_title"]
    );
  }

  /// **The foreign key has TEETH**, which is what the pragma buys and what no rendered statement can
  /// show: a provenance row whose common row is not there is the engine's own refusal.
  ///
  /// The pair is what makes it a measurement rather than an assertion about SQLite: the same insert
  /// is run twice, once after the common row exists and once before, and only the second is refused.
  /// A schema whose constraint were merely parsed would take both.
  #[tokio::test]
  async fn an_orphan_provenance_row_is_refused_by_the_engine() {
    let mut db = empty().await;
    create(&mut db).await.expect("the schema is created");

    let orphan = sqlx::query(r#"INSERT INTO "caption_turn" ("id", "turn") VALUES (1, 9)"#)
      .execute(&mut db)
      .await;
    let Err(why) = orphan else {
      panic!("a provenance row with no common row to point at is an orphan");
    };
    assert!(
      why.to_string().contains("FOREIGN KEY constraint failed"),
      "the engine's own sentence, rather than a rule re-checked here: {why}"
    );

    sqlx::query(
      r#"INSERT INTO "caption" ("id", "__ig_source__", "text") VALUES (1, 'Turn', 'hi')"#,
    )
    .execute(&mut db)
    .await
    .expect("the common row lands");
    sqlx::query(r#"INSERT INTO "caption_turn" ("id", "turn") VALUES (1, 9)"#)
      .execute(&mut db)
      .await
      .expect("and the same provenance row is taken once it has one to point at");
  }

  /// **A second create is the same create.** `IF NOT EXISTS` is what makes a boot sequence safe to
  /// re-run, and it is also what makes a half-created schema survivable — which matters here because
  /// the lane opens no transaction, MySQL having no DDL to roll back.
  #[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");

    assert_eq!(tables(&mut db).await, DECLARED);
    assert_eq!(
      indexes(&mut db).await,
      ["__ig_clip_tags_element", "__ig_media_title"]
    );
  }

  /// **The audit passes what the create made**, which is the claim the two visitors exist to keep
  /// together: one renders the schema and the other reads it back out of the catalogue, and neither
  /// is told what the other did.
  #[tokio::test]
  async fn the_audit_passes_the_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 table that was never created is named**, rather than reported as a database that failed.
  #[tokio::test]
  async fn the_audit_names_a_table_the_database_does_not_have() {
    let mut db = empty().await;
    let Err(SqlSchemaError::Missing(table)) = validate(&mut db).await else {
      panic!("an empty database has none of the declared tables");
    };
    assert_eq!(table, FieldName::new("media"));
  }

  /// **A column's type moved, and the audit names the table and the column.** This is the drift a
  /// re-run of the create cannot see: `CREATE TABLE IF NOT EXISTS` over an altered table succeeds
  /// and changes nothing.
  #[tokio::test]
  async fn the_audit_names_the_column_whose_stored_type_drifted() {
    let mut db = empty().await;
    create(&mut db).await.expect("the schema is created");

    // SQLite has no `ALTER COLUMN`, so the table is rebuilt — which is what a real migration doing
    // this would do, and which is why the audit reads the catalogue rather than a migration log.
    for statement in [
      r#"ALTER TABLE "media" RENAME TO "media_old""#,
      r#"CREATE TABLE "media" ("id" INTEGER NOT NULL, "title" BLOB, PRIMARY KEY ("id"))"#,
      r#"DROP TABLE "media_old""#,
    ] {
      sqlx::query(statement)
        .execute(&mut db)
        .await
        .expect("the drift is applied");
    }

    let Err(SqlSchemaError::Type {
      table,
      column,
      declared,
      stored,
    }) = validate(&mut db).await
    else {
      panic!("a column stored at another type is drift");
    };
    assert_eq!(table, FieldName::new("media"));
    assert_eq!(column, "title");
    assert_eq!(declared, "TEXT");
    assert_eq!(stored, "BLOB");
  }

  /// **A declared column the live table does not carry is named too**, which is the drift a dropped
  /// column leaves.
  #[tokio::test]
  async fn the_audit_names_a_column_the_live_table_lost() {
    let mut db = empty().await;
    create(&mut db).await.expect("the schema is created");
    sqlx::query(r#"ALTER TABLE "clip" DROP COLUMN "bit_rate""#)
      .execute(&mut db)
      .await
      .expect("the drift is applied");

    let Err(SqlSchemaError::Column { table, column }) = validate(&mut db).await else {
      panic!("a declared column that is gone is drift");
    };
    assert_eq!(table, FieldName::new("clip"));
    assert_eq!(column, "bit_rate");
  }

  /// **An EXTRA live column is not drift**, and that is a ruling rather than a gap: a column the
  /// declaration does not know about is what an additive migration leaves behind, and an audit that
  /// reported one would fail every forward-compatible deployment.
  #[tokio::test]
  async fn a_column_the_declaration_does_not_know_about_is_not_drift() {
    let mut db = empty().await;
    create(&mut db).await.expect("the schema is created");
    sqlx::query(r#"ALTER TABLE "clip" ADD COLUMN "extra" TEXT"#)
      .execute(&mut db)
      .await
      .expect("the column is added");

    validate(&mut db)
      .await
      .expect("every declared column is still there, at its declared type");
  }

  /// The two visitors read the SAME walk, so the audit cannot be auditing a different graph from
  /// the one the create made: both are driven by `type_iter`, and the list is written once.
  #[tokio::test]
  async fn both_visitors_are_driven_by_one_list() {
    let mut create = Create::<Sqlite>::new();
    type_iter(&mut create).expect("every descriptor renders");
    let mut validate = Validate::<Sqlite>::new();
    type_iter(&mut validate).expect("collecting refuses nothing");

    let walked: Vec<&str> = validate
      .tables()
      .iter()
      .map(|table| table.address().table().as_str())
      .collect();
    assert_eq!(walked, ["media", "clip", "caption"]);
    assert_eq!(
      create.statements().len(),
      <Media as Describe<Sqlite>>::BLUEPRINT
        .create::<Sqlite>()
        .expect("it renders")
        .len()
        + <Clip as Describe<Sqlite>>::BLUEPRINT
          .create::<Sqlite>()
          .expect("it renders")
          .len()
        + <Caption as Describe<Sqlite>>::BLUEPRINT
          .create::<Sqlite>()
          .expect("it renders")
          .len()
    );
  }

  /// **A provenance table's own drift is named**, which is what distinguishes it from an edge table:
  /// its name and its columns are DECLARED, so the audit reads them off the declaration and compares
  /// them against the catalogue with nothing derived in between.
  #[tokio::test]
  async fn the_audit_names_a_column_a_provenance_table_lost() {
    let mut db = empty().await;
    create(&mut db).await.expect("the schema is created");
    sqlx::query(r#"ALTER TABLE "caption_frame" DROP COLUMN "frame""#)
      .execute(&mut db)
      .await
      .expect("the drift is applied");

    let Err(SqlSchemaError::Column { table, column }) = validate(&mut db).await else {
      panic!("a declared ancestor column that is gone is drift");
    };
    assert_eq!(table, FieldName::new("caption_frame"));
    assert_eq!(column, "frame");
  }
}