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
//! The arm facts, over a binding written BY HAND.
//!
//! `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 — which is the split `query::sql::find`'s own fixture
//! records, applied one family over: everything the engine asks of a declaration is asked of this
//! file too, and a seam only satisfiable from inside the emitter would not compile here.
#![cfg(feature = "sqlite")]

use sqlx::{Row as _, Sqlite};

use super::{InterfaceFind, SqlInterface, total_order, union};
use crate::{
  Carrier, ComplexComparison, Cursor, CursorValue, FieldName, InterfaceArm, InterfaceColumn,
  InterfaceKind, OrderDirection, OrderTerm, RecordAddress, ScalarFilter, TermName, TryFromFilter,
  Walk,
  comparison::{
    At, Backend, Frame,
    sql::{SqlKeyset, SqlLoweringError, SqlOrder, SqlScalarComparison},
  },
  query::Page,
};

/// Two members, one of which calls the shared column something else — which is what makes every
/// reader of a member's column measurable at once.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MediaKind {
  Video,
  Audio,
}

impl InterfaceKind for MediaKind {
  const INTERFACE: &'static str = "Media";
  const ALL: &'static [Self] = &[Self::Video, Self::Audio];

  fn as_str(self) -> &'static str {
    match self {
      Self::Video => "video",
      Self::Audio => "audio",
    }
  }
}

/// The ADDRESS of one row, as a hand-written binding declares it: a sum over the members' OWN ids,
/// which the two members here deliberately disagree about.
#[derive(Debug, Clone, PartialEq)]
enum MediaId {
  Video(i64),
  Audio(String),
}

impl MediaId {
  /// Which member this address is of — the same fact the discriminant column carries, read back off
  /// the address so the pair cannot disagree.
  const fn kind(&self) -> MediaKind {
    match self {
      Self::Video(_) => MediaKind::Video,
      Self::Audio(_) => MediaKind::Audio,
    }
  }
}

/// The interface's own projection, decoded the way an emitted one is: the DISCRIMINANT first,
/// because it decides which variant the address is.
#[derive(Debug, Clone, PartialEq)]
struct MediaSqliteRow {
  kind: MediaKind,
  id: MediaId,
  title: String,
}

impl sqlx::FromRow<'_, sqlx::sqlite::SqliteRow> for MediaSqliteRow {
  fn from_row(row: &sqlx::sqlite::SqliteRow) -> sqlx::Result<Self> {
    let word: String = row.try_get("__ig_kind__")?;
    let kind = MediaKind::parse(&word).map_err(|unknown| sqlx::Error::ColumnDecode {
      index: "__ig_kind__".to_owned(),
      source: Box::new(unknown),
    })?;
    let id = match kind {
      MediaKind::Video => MediaId::Video(row.try_get("id")?),
      MediaKind::Audio => MediaId::Audio(row.try_get("id")?),
    };
    Ok(Self {
      kind,
      id,
      title: row.try_get("title")?,
    })
  }
}

enum Media {}

const VIDEO: &[InterfaceColumn] = &[InterfaceColumn::new(
  FieldName::new("title"),
  FieldName::new("title"),
)];

/// `Audio` carries the shared column under its own name, which is the pair an arm exists to keep.
const AUDIO: &[InterfaceColumn] = &[InterfaceColumn::new(
  FieldName::new("title"),
  FieldName::new("label"),
)];

/// The one term this interface promises — the shared column, in the interface's own vocabulary.
#[derive(Debug, Clone, Copy, PartialEq)]
enum MediaOrderBy {
  Title(OrderDirection),
}

impl SqlInterface<Sqlite> for Media {
  type Kind = MediaKind;
  type Row = MediaSqliteRow;
  type Comparison = TitleIs;
  type Value = MediaValue;
  type Order = MediaOrderBy;

  const ARMS: &'static [InterfaceArm<MediaKind>] = &[
    InterfaceArm::new(MediaKind::Video, VIDEO),
    InterfaceArm::new(MediaKind::Audio, AUDIO),
  ];

  fn address(kind: MediaKind) -> RecordAddress {
    match kind {
      MediaKind::Video => VIDEO_ADDRESS,
      MediaKind::Audio => AUDIO_ADDRESS,
    }
  }

  fn term(order: MediaOrderBy) -> OrderTerm {
    match order {
      MediaOrderBy::Title(direction) => {
        OrderTerm::new(TermName::new("title"), FieldName::new("title"), direction)
      }
    }
  }

  /// The two tail slots are MINTED from the address rather than carried beside it, which is the
  /// one-slot ruling as a binding honours it: `__ig_kind__` is what the address says it is.
  fn value(row: &MediaSqliteRow, term: &OrderTerm) -> Option<MediaValue> {
    match term.column().as_str() {
      "title" => Some(MediaValue::Title(row.title.clone())),
      "__ig_kind__" => Some(MediaValue::Kind(row.id.kind().as_str())),
      "id" => Some(MediaValue::Address(row.id.clone())),
      _ => None,
    }
  }
}

// An address is an ITEM, which is what its `'static` key list says — see `RecordAddress::new`. An
// expansion reaches its members' through `SqlQuery::ADDRESS`, which is a `const` of theirs; a
// hand-written binding declares its own.
const VIDEO_ADDRESS: RecordAddress =
  RecordAddress::new(FieldName::new("video"), &[FieldName::new("id")]);
const AUDIO_ADDRESS: RecordAddress =
  RecordAddress::new(FieldName::new("audio"), &[FieldName::new("audio_id")]);

/// **An arm is reached by the member it reads**, which is the lookup every position of a statement
/// makes: the engine holds a kind and needs that member's columns.
#[test]
fn each_member_reaches_its_own_arm() {
  for kind in MediaKind::ALL.iter().copied() {
    let arm = <Media as SqlInterface<Sqlite>>::arm(kind).expect("every member has an arm");
    assert_eq!(arm.kind(), kind);
  }
}

/// **The two names differ exactly where a member calls the column something else**, and the arm
/// carries both — the rename and the default are one rendering.
#[test]
fn an_arm_carries_what_its_member_calls_the_shared_column() {
  let video = <Media as SqlInterface<Sqlite>>::arm(MediaKind::Video).expect("an arm");
  let audio = <Media as SqlInterface<Sqlite>>::arm(MediaKind::Audio).expect("an arm");

  assert_eq!(video.columns()[0].field().as_str(), "title");
  assert_eq!(video.columns()[0].column().as_str(), "title");
  assert_eq!(audio.columns()[0].field().as_str(), "title");
  assert_eq!(audio.columns()[0].column().as_str(), "label");
}

/// **Every arm promises the same shared columns in the same order**, which is what makes a `UNION
/// ALL` of them decode into ONE projection: the arms differ in what each member calls a column and
/// never in which columns there are.
#[test]
fn every_arm_projects_the_interfaces_own_columns_in_one_order() {
  let promised: Vec<&str> = <Media as SqlInterface<Sqlite>>::ARMS[0]
    .columns()
    .iter()
    .map(|column| column.field().as_str())
    .collect();

  for arm in <Media as SqlInterface<Sqlite>>::ARMS {
    let names: Vec<&str> = arm
      .columns()
      .iter()
      .map(|column| column.field().as_str())
      .collect();
    assert_eq!(
      names,
      promised,
      "`{}` promises something else",
      arm.kind().as_str()
    );
  }
}

/// **The table is the MEMBER's own**, asked through its address rather than restated — so a member
/// that moves its table moves the arm that reads it, and nothing here has a copy to update.
#[test]
fn the_table_is_the_members_address_and_not_a_second_copy() {
  assert_eq!(
    <Media as SqlInterface<Sqlite>>::table(MediaKind::Audio).as_str(),
    "audio"
  );
  assert_eq!(
    <Media as SqlInterface<Sqlite>>::address(MediaKind::Audio)
      .keys()
      .first()
      .expect("a row is addressed by at least one column")
      .as_str(),
    "audio_id",
    "the address column is the member's too, and the members need not agree about its name"
  );
}

/// **The binding is per DATABASE**, and the parameter is where that is said: a dialect the
/// declaration is not about has no impl, which is `E0277` AT THE BOUND rather than a projection that
/// is well formed and answers for the wrong database.
fn _the_parameter_is_the_database<Db: Backend + sqlx::Database, I: SqlInterface<Db>>() {}

/// The impl set states which databases an interface is about, and this is the one it has.
fn _media_is_about_sqlite() {
  _the_parameter_is_the_database::<Sqlite, Media>();
}

/// The statement `union` renders, as text — which is what this layer produces. Whether the page it
/// describes walks correctly is not visible in it, exactly as `query::sql::find`'s own note records
/// for the record lanes.
/// ONE slot of a cursor over an interface: a shared column's value, or the ADDRESS.
///
/// The tail's two terms take ONE variant between them — see `resumed` below for what the engine
/// mints for the discriminant — and the address carries the member's own id beside the word that
/// says which member, which is `<I>Id` in an emitted vocabulary and this pair by hand.
#[derive(Debug, Clone, PartialEq)]
enum MediaValue {
  Title(String),
  Kind(&'static str),
  Address(MediaId),
}

impl CursorValue for MediaValue {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    match self {
      Self::Title(value) => {
        out.push(0);
        value.write_cursor(out);
      }
      Self::Kind(value) => {
        out.push(1);
        (*value).to_owned().write_cursor(out);
      }
      Self::Address(MediaId::Video(value)) => {
        out.push(2);
        value.write_cursor(out);
      }
      Self::Address(MediaId::Audio(value)) => {
        out.push(3);
        value.write_cursor(out);
      }
    }
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let (tag, rest) = <[u8]>::split_first(bytes)?;
    match *tag {
      0 => String::read_cursor(rest).map(Self::Title),
      1 => String::read_cursor(rest).and_then(|word| {
        MediaKind::parse(&word)
          .ok()
          .map(|kind| Self::Kind(kind.as_str()))
      }),
      2 => i64::read_cursor(rest).map(|id| Self::Address(MediaId::Video(id))),
      3 => String::read_cursor(rest).map(|id| Self::Address(MediaId::Audio(id))),
      _ => None,
    }
  }
}

impl Carrier<Sqlite> for MediaValue {
  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Sqlite>) {
    match self {
      Self::Title(value) => Carrier::<Sqlite>::push_bind(value, qb),
      Self::Kind(value) => Carrier::<Sqlite>::push_bind(&(*value).to_owned(), qb),
      Self::Address(MediaId::Video(value)) => Carrier::<Sqlite>::push_bind(value, qb),
      Self::Address(MediaId::Audio(value)) => Carrier::<Sqlite>::push_bind(value, qb),
    }
  }
}

/// A predicate over the shared `title`, written in the INTERFACE's vocabulary — which is the whole
/// point: no arm's table has a column of that name in both members, and the arms' aliases are what
/// make one predicate answer for either.
struct TitleIs(SqlScalarComparison<String, Sqlite>);

impl ComplexComparison<Sqlite> for TitleIs {
  fn conjuncts(&self) -> usize {
    ComplexComparison::<Sqlite>::conjuncts(&self.0)
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: <Sqlite as Backend>::Builder<'q>,
  ) -> Result<<Sqlite as Backend>::Builder<'q>, SqlLoweringError> {
    let frame = At::frame(at, FieldName::new("title"));
    ComplexComparison::<Sqlite>::apply(&self.0, Frame::at(&frame), builder)
  }
}

fn titled() -> TitleIs {
  TitleIs(
    SqlScalarComparison::try_from_filter(
      ScalarFilter::<std::string::String>::new().with_eq("a".to_owned()),
    )
    .expect("a text equality crosses into SQLite"),
  )
}

fn rendered(filter: Option<&TitleIs>, written: &[OrderTerm], limit: Option<u32>) -> String {
  let order = total_order::<Media, sqlx::Sqlite>(written);
  let order = SqlOrder::<Sqlite>::new(&order).expect("SQLite places NULL either way");
  let statement = union::<Media, Sqlite>(filter, &order, None, Walk::Forward, limit)
    .expect("the binding renders");
  ::core::convert::AsRef::<str>::as_ref(&statement.sql()).to_owned()
}

/// **The whole statement, verbatim** — one arm per member, each aliasing its member's column to the
/// interface's name, the discriminant as a literal, and the member's address under one output name.
#[test]
fn the_union_projects_every_member_under_the_interfaces_own_names() {
  assert_eq!(
    rendered(None, &[], None),
    r#"SELECT * FROM ( SELECT "title" AS "title", 'video' AS "__ig_kind__", "id" AS "id" FROM "video" UNION ALL SELECT "label" AS "title", 'audio' AS "__ig_kind__", "audio_id" AS "id" FROM "audio" ) AS "__ig_union__" ORDER BY "__ig_kind__" ASC, "id" ASC"#
  );
}

/// **The shared filter is lowered ONCE, over the interface's own names**, and it sits above the
/// union — where every arm has already aliased its member's column to the name the predicate speaks.
///
/// One wrapper rather than one per arm is what makes "lowered once" literal: the operand is bound a
/// single time whatever the member count.
#[test]
fn the_shared_predicate_speaks_the_interfaces_vocabulary_once() {
  let filter = titled();
  let statement = rendered(Some(&filter), &[], None);

  assert!(
    statement
      .ends_with(r#") AS "__ig_union__" WHERE "title" = ? ORDER BY "__ig_kind__" ASC, "id" ASC"#),
    "{statement}"
  );
  assert_eq!(statement.matches('?').count(), 1, "{statement}");
}

/// **The total order ends `…, __ig_kind__, id`**, and the discriminant comes FIRST: an id is
/// `UNIQUE` within its own table, so it is the discriminant that tells two members' rows apart.
#[test]
fn the_tail_is_the_discriminant_and_then_the_address() {
  let written = [OrderTerm::new(
    TermName::new("title"),
    FieldName::new("title"),
    OrderDirection::Desc,
  )];
  let statement = rendered(None, &written, Some(3));

  assert!(
    statement.ends_with(r#"ORDER BY "title" DESC, "__ig_kind__" ASC, "id" ASC LIMIT ?"#),
    "{statement}"
  );
}

/// **A declaration that moved its alias prefix moves the SYNTHETIC WORDS with it**, and the
/// statement is the only place that shows.
///
/// The knob a record spends on its row-source names is the same knob here, and what it moves is
/// everything the union INVENTS: the discriminant's output column and the derived table's name. The
/// members' own columns do not move — `title` and `id` are real, one promised by the interface and
/// one each arm's own — which is the line the fence draws in both directions.
///
/// The mutation this catches is a renderer that reached for `interface::KIND` or `interface::SOURCE`
/// directly instead of the binding's: every existing pin here states the defaults, so it would pass
/// all of them.
#[test]
fn a_moved_prefix_moves_the_words_the_union_invents() {
  let order = total_order::<Legacy, sqlx::Sqlite>(&[]);
  let order = SqlOrder::<Sqlite>::new(&order).expect("SQLite places NULL either way");
  let statement =
    union::<Legacy, Sqlite>(None, &order, None, Walk::Forward, None).expect("the binding renders");

  assert_eq!(
    ::core::convert::AsRef::<str>::as_ref(&statement.sql()),
    r#"SELECT * FROM ( SELECT "title" AS "title", 'video' AS "__mine_kind__", "id" AS "id" FROM "video" UNION ALL SELECT "label" AS "title", 'audio' AS "__mine_kind__", "audio_id" AS "id" FROM "audio" ) AS "__mine_union__" ORDER BY "__mine_kind__" ASC, "id" ASC"#
  );
}

/// **The term's IDENTITY does not move with the column**, which is what keeps a cursor portable.
///
/// A [`TermName`] is the rename-proof name a page freezes, so a cursor minted against a deployment
/// that moved the prefix has to resume against one that did not. The two bindings therefore agree
/// about the term and disagree about the column, and this is that stated as an equality and an
/// inequality over the same pair.
#[test]
fn a_moved_prefix_leaves_the_terms_identity_alone() {
  let defaulted = <Media as SqlInterface<Sqlite>>::KIND_TERM;
  let moved = <Legacy as SqlInterface<Sqlite>>::KIND_TERM;

  assert_eq!(
    defaulted.identity(),
    moved.identity(),
    "a cursor freezes this"
  );
  assert_eq!(defaulted.identity(), TermName::new("__ig_kind__"));
  assert_ne!(defaulted.column(), moved.column(), "and renders that");
}

/// The same interface under a declaration that moved its alias namespace — the two synthetic words
/// stated, and every other answer inherited from [`Media`]'s.
///
/// A second binding rather than a second fixture, because what is under test is exactly the two
/// items: the arms, the addresses and the terms are the same facts, and restating them would let the
/// pair drift for a reason the knob has nothing to do with.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Legacy;

impl SqlInterface<Sqlite> for Legacy {
  type Kind = MediaKind;
  type Row = MediaSqliteRow;
  type Comparison = TitleIs;
  type Value = MediaValue;
  type Order = MediaOrderBy;

  const ARMS: &'static [InterfaceArm<MediaKind>] = <Media as SqlInterface<Sqlite>>::ARMS;
  const KIND: &'static FieldName = FieldName::new("__mine_kind__");
  const SOURCE: &'static FieldName = FieldName::new("__mine_union__");

  fn address(kind: MediaKind) -> RecordAddress {
    <Media as SqlInterface<Sqlite>>::address(kind)
  }

  fn term(order: MediaOrderBy) -> OrderTerm {
    <Media as SqlInterface<Sqlite>>::term(order)
  }

  fn value(row: &MediaSqliteRow, term: &OrderTerm) -> Option<MediaValue> {
    <Media as SqlInterface<Sqlite>>::value(row, term)
  }
}

/// **A client term naming a tail column MOVES it rather than repeating it** — the rule a record's
/// own completed order already follows.
#[test]
fn a_written_term_over_the_tail_moves_it() {
  let written = [OrderTerm::new(
    TermName::new("id"),
    FieldName::new("id"),
    OrderDirection::Desc,
  )];
  let completed = total_order::<Media, sqlx::Sqlite>(&written);

  assert_eq!(completed.len(), 2, "{completed:?}");
  assert_eq!(completed[0].column(), FieldName::new("__ig_kind__"));
  assert_eq!(completed[1].column(), FieldName::new("id"));
  assert_eq!(
    completed[1].direction(),
    OrderDirection::Asc,
    "the tail is the framework's, so a client cannot invert half of it and keep the other half"
  );
}

/// The cursor a page resumes at, minted as the engine mints one: the client's terms, then the TAIL,
/// whose discriminant is DERIVED from the address rather than carried beside it.
///
/// That derivation is the one-slot ruling as this machinery can honour it. A cursor's frame is one
/// value per ORDER TERM — `Cursor::resume` checks the width against the order it replays — so a
/// two-term tail has two slots whatever the caller supplied, and honouring one slot in the FRAME
/// would need a wire codec of its own, which this round does not add. What a CALLER supplies is one
/// address, and the discriminant beside it is minted here from that address's own member: the two
/// cannot disagree, which is the whole of what one slot was for.
fn resumed(written: &[OrderTerm], title: &str, id: MediaId) -> Cursor<MediaValue> {
  let order = total_order::<Media, sqlx::Sqlite>(written);
  let mut values: Vec<Option<MediaValue>> = written
    .iter()
    .map(|_| Some(MediaValue::Title(title.to_owned())))
    .collect();
  values.push(Some(MediaValue::Kind(id.kind().as_str())));
  values.push(Some(MediaValue::Address(id)));
  Cursor::at(&order, values)
}

/// **A resumed page is the general keyset over `(…, __ig_kind__, id)`**, and there is no
/// interface-specific comparison in it: above the union the discriminant is an ordinary column that
/// varies, so the expansion every record page renders is exactly right — which is what the wrapper
/// bought over a per-arm `WHERE` that would have had to fold its own kind literal.
#[test]
fn a_resumed_page_renders_the_general_keyset_over_the_tail() {
  let written = [OrderTerm::new(
    TermName::new("title"),
    FieldName::new("title"),
    OrderDirection::Asc,
  )];
  let cursor = resumed(&written, "a", MediaId::Audio("a-7".to_owned()));
  let order = total_order::<Media, sqlx::Sqlite>(&written);
  let order = SqlOrder::<Sqlite>::new(&order).expect("SQLite places NULL either way");
  let keyset =
    SqlKeyset::resume(order, &cursor, Walk::Forward).expect("the cursor is this order's");
  let statement = union::<Media, Sqlite>(None, &order, Some(&keyset), Walk::Forward, Some(2))
    .expect("the binding renders");

  assert!(
    ::core::convert::AsRef::<str>::as_ref(&statement.sql()).ends_with(
      r#") AS "__ig_union__" WHERE ("title" > ? OR ("title" = ? AND ("__ig_kind__" > ? OR ("__ig_kind__" = ? AND ("id" > ?))))) ORDER BY "title" ASC, "__ig_kind__" ASC, "id" ASC LIMIT ?"#
    ),
    "{}",
    ::core::convert::AsRef::<str>::as_ref(&statement.sql())
  );
}

/// **A filter and a page are ONE `WHERE`**, threaded through one accumulator — so a resumed page is
/// *the client's filter AND this* and neither conjunct knows what the other was.
#[test]
fn a_filtered_page_joins_both_conjuncts() {
  let cursor = resumed(&[], "a", MediaId::Audio("a-7".to_owned()));
  let order = total_order::<Media, sqlx::Sqlite>(&[]);
  let order = SqlOrder::<Sqlite>::new(&order).expect("SQLite places NULL either way");
  let keyset =
    SqlKeyset::resume(order, &cursor, Walk::Forward).expect("the cursor is this order's");
  let filter = titled();
  let statement = union::<Media, Sqlite>(Some(&filter), &order, Some(&keyset), Walk::Forward, None)
    .expect("the binding renders");
  let sql = ::core::convert::AsRef::<str>::as_ref(&statement.sql()).to_owned();

  assert!(
    sql.contains(r#"WHERE "title" = ? AND ("__ig_kind__" > ?"#),
    "{sql}"
  );
}

/// The two-member corpus every live test below runs against: `Video` keyed by an INTEGER and
/// `Audio` by TEXT, each calling the shared column something else, with titles that TIE across the
/// two tables — which is what makes the tail load-bearing rather than decorative.
///
/// A bare [`SqliteConnection`](sqlx::sqlite::SqliteConnection) and never a `Pool`, which is the
/// arrangement `query::sql::find`'s own fixture records: this crate turns on none of sqlx's runtime
/// features, and a pool needs one.
async fn corpus() -> sqlx::sqlite::SqliteConnection {
  use sqlx::Connection as _;

  let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
    .await
    .expect("an in-memory database");
  for statement in [
    r#"CREATE TABLE "video" ("id" INTEGER PRIMARY KEY, "title" TEXT NOT NULL)"#,
    r#"CREATE TABLE "audio" ("audio_id" TEXT PRIMARY KEY, "label" TEXT NOT NULL)"#,
    r#"INSERT INTO "video" VALUES (1, 'a'), (2, 'b'), (3, 'c')"#,
    r#"INSERT INTO "audio" VALUES ('a-1', 'a'), ('a-2', 'b')"#,
  ] {
    sqlx::query(statement)
      .execute(&mut db)
      .await
      .expect("the fixture's own DDL");
  }
  db
}

/// The one written term the live tests page by.
fn by_title() -> [MediaOrderBy; 1] {
  [MediaOrderBy::Title(OrderDirection::Asc)]
}

/// What one page of the corpus reads as, for an assertion that is one line rather than five.
fn rows(page: &Page<MediaSqliteRow, MediaValue>) -> Vec<(String, MediaId)> {
  page
    .edges()
    .iter()
    .map(|edge| (edge.node().title.clone(), edge.node().id.clone()))
    .collect()
}

/// **The whole page walk, against a live engine** — the half that rendering cannot show: two
/// members' rows arriving interleaved in ONE title order, the tail breaking the tie across TABLES,
/// and the second page resuming exactly where the first stopped.
///
/// `a` is carried by both members, which is the case the tail exists for: the two rows sort by the
/// discriminant and then by an id neither member shares with the other.
#[tokio::test]
async fn a_page_walks_both_members_in_one_order_and_resumes_across_the_tie() {
  let mut db = corpus().await;
  let written = by_title();

  let first = InterfaceFind::<Media, Sqlite, _>::new(&mut db)
    .order(&written)
    .first(3)
    .fetch()
    .await
    .expect("the first page");

  assert_eq!(
    rows(&first),
    [
      ("a".to_owned(), MediaId::Audio("a-1".to_owned())),
      ("a".to_owned(), MediaId::Video(1)),
      ("b".to_owned(), MediaId::Audio("a-2".to_owned())),
    ],
    "the tie on `a` is broken by the DISCRIMINANT first — `audio` sorts before `video` — and only \
     then by an id"
  );
  assert!(first.has_next_page(), "two rows are still behind it");
  assert!(!first.has_previous_page());

  let boundary = first.end_cursor().expect("a non-empty page ends somewhere");
  let second = InterfaceFind::<Media, Sqlite, _>::new(&mut db)
    .order(&written)
    .after(boundary)
    .fetch()
    .await
    .expect("the second page");

  assert_eq!(
    rows(&second),
    [
      ("b".to_owned(), MediaId::Video(2)),
      ("c".to_owned(), MediaId::Video(3)),
    ]
  );
  assert!(!second.has_next_page(), "the walk is exhausted");
  assert!(second.has_previous_page(), "a position was given");
}

/// **The cursor a page hands out survives its wire form** — which is the only form a client ever
/// holds, and the one a hand-written value's codec has to be right about.
#[tokio::test]
async fn a_pages_cursor_round_trips_through_the_string_a_client_holds() {
  let mut db = corpus().await;
  let written = by_title();

  let first = InterfaceFind::<Media, Sqlite, _>::new(&mut db)
    .order(&written)
    .first(1)
    .fetch()
    .await
    .expect("the first page");
  let text = first
    .end_cursor()
    .expect("a non-empty page ends somewhere")
    .encode();
  let decoded = Cursor::<MediaValue>::decode(&text).expect("the framework's own encoding");

  let second = InterfaceFind::<Media, Sqlite, _>::new(&mut db)
    .order(&written)
    .after(&decoded)
    .fetch()
    .await
    .expect("the second page");

  assert_eq!(
    rows(&second)[0],
    ("a".to_owned(), MediaId::Video(1)),
    "the page after the first `a` is the OTHER `a`, which only the tail can say"
  );
}

/// **The filter is the interface's own vocabulary and both members answer it** — `Audio` stores the
/// column as `label` and a caller never writes that word.
#[tokio::test]
async fn a_filtered_page_reads_both_members_through_their_own_column_names() {
  let mut db = corpus().await;
  let filter = titled();

  let page = InterfaceFind::<Media, Sqlite, _>::new(&mut db)
    .filter(&filter)
    .order(&by_title())
    .first(10)
    .fetch()
    .await
    .expect("the page");

  assert_eq!(
    rows(&page),
    [
      ("a".to_owned(), MediaId::Audio("a-1".to_owned())),
      ("a".to_owned(), MediaId::Video(1)),
    ],
    "one predicate, written once, reaching `video.title` and `audio.label` through the aliases"
  );
}

/// **The backward walk is the same order read from the far end**, re-reversed into display order —
/// so a client pages either way against ONE set of cursors.
#[tokio::test]
async fn the_backward_walk_comes_back_in_display_order() {
  let mut db = corpus().await;

  let page = InterfaceFind::<Media, Sqlite, _>::new(&mut db)
    .order(&by_title())
    .last(2)
    .fetch()
    .await
    .expect("the page");

  assert_eq!(
    rows(&page),
    [
      ("b".to_owned(), MediaId::Video(2)),
      ("c".to_owned(), MediaId::Video(3)),
    ]
  );
  assert!(page.has_previous_page(), "three rows are still ahead of it");
}

/// **A row's two halves cannot disagree**, which is what reading the discriminant FIRST buys: the
/// column the decode read and the member the address names are one answer.
#[tokio::test]
async fn the_decoded_rows_discriminant_and_address_are_one_answer() {
  let mut db = corpus().await;

  let page = InterfaceFind::<Media, Sqlite, _>::new(&mut db)
    .order(&by_title())
    .first(10)
    .fetch()
    .await
    .expect("the page");

  for edge in page.edges() {
    assert_eq!(edge.node().kind, edge.node().id.kind(), "{:?}", edge.node());
  }
}

/// **The surface says whether a read is already open**, and the framework never nests: a bare
/// connection begins one, a caller's transaction is passed through.
#[test]
fn the_surface_is_what_says_whether_a_read_is_already_open() {
  // A `const` block, because the answer IS a constant, and that is half the assertion: the surface
  // decides at compile time, so no call has to ask a connection what state it is in.
  const {
    assert!(!<&mut sqlx::sqlite::SqliteConnection as super::BeginRead>::IN_TRANSACTION);
    assert!(<&mut sqlx::Transaction<'_, Sqlite> as super::BeginRead>::IN_TRANSACTION);
  }
}

/// **A page inside a caller's own transaction opens nothing and closes nothing** — which is the
/// whole of the passthrough: a nested `BEGIN` is an error on SQLite, so a page that ran at all is a
/// page that did not nest, and the transaction is still the caller's afterwards.
#[tokio::test]
async fn a_page_inside_a_callers_read_passes_through_and_leaves_it_open() {
  let mut db = corpus().await;
  let mut read = sqlx::Connection::begin(&mut db)
    .await
    .expect("the caller's own transaction");

  let page = InterfaceFind::<Media, Sqlite, _>::new(&mut read)
    .order(&by_title())
    .first(2)
    .fetch()
    .await
    .expect("a page inside a transaction");
  assert_eq!(rows(&page).len(), 2);

  // Still the caller's, which a committed or rolled-back one would not be: a second statement on it
  // is what proves the framework closed nothing.
  let held: i64 = sqlx::query_scalar(r#"SELECT COUNT(*) FROM "video""#)
    .fetch_one(&mut *read)
    .await
    .expect("the transaction is still open");
  assert_eq!(held, 3);
  read.commit().await.expect("the caller closes their own");
}