ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
//! A PAGE OVER A `sortable` COLLECTION — the statement each dialect renders for one, and the walk a
//! live engine actually returns.
//!
//! A suite of its own beside [`super::tests`], for the reason `query::sql::ddl`'s shadow suite gives:
//! what is asserted here is ONE term kind's effect on a page — the column the SELECT list grows, the
//! boundary the cursor freezes, and the walk that neither loses nor doubles a row across the seam —
//! and holding that apart from the lanes' own rendering tests keeps a change to either visible.
//!
//! # The fixture is hand-written, which is the third-party proof as well as the harness
//!
//! `ingraph-codegen` cannot reach this crate, so what stands in for an expansion is the same thing a
//! third party writes: a record, its row, its order-by and its cursor value, bound to the engine
//! through nothing but the public traits. The one term of interest is
//! [`TermSubject::Shadow`](crate::TermSubject) — a collection kept in a table of its own and mirrored
//! into `__ig_tags_sort__` — and everything the engine asks of a declaration carrying one is asked of
//! this file too.
//!
//! # What the TEXT can say, and the one claim it cannot
//!
//! The statement shows that the companion rides the SELECT list under the engine's own sort alias,
//! that the `ORDER BY` and the keyset name the same column, and that a scan projects none of it. What
//! it cannot show is the claim the round exists for: **that the boundary a page resumes at is the
//! bytes that page was ORDERED by.** A cursor rebuilt from the collection instead renders exactly the
//! same SQL, so the disagreement is invisible in the text and is measured against a live engine —
//! `mod live`, an in-memory SQLite, including one row whose companion and whose edge rows deliberately
//! DISAGREE.

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

use core::marker::PhantomData;

use super::{Ordering, SortValues, ordered};
use crate::{
  Carrier, ColumnName, ColumnShape, ComplexComparison, Cursor, CursorValue, FieldName,
  Identifiable, OrderDirection, OrderTerm, Record, RecordAddress, TermName, Transformer, Walk,
  comparison::{
    At, Backend,
    sql::{OrderSubjects, SqlKeyIn, SqlKeyset, SqlOrder, TermColumns},
  },
  query::sql::{
    CrossingError, ELEMENT, EdgeCollection, EdgeShape, SqlDialect, SqlOrdering, SqlQuery,
    distribute,
  },
};

/// A reel: an id, a title, and a SEQUENCE collection kept in an edge table AND mirrored into an
/// order-preserving companion column.
///
/// The `sortable` word's own shape, and the smallest one that has it: one key column, so every
/// statement below is about the companion rather than about a key chain.
#[derive(Debug, Clone, PartialEq)]
struct Reel {
  id: i64,
  title: String,
  /// Stored in `reel_tags` as `(id, tags_ordinal, tags)`, and ORDERED by `__ig_tags_sort__` on the
  /// row itself.
  tags: Vec<String>,
}

impl Identifiable for Reel {
  type Id = i64;

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

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

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

/// The stored row. `tags` is a field of it and is NOT in [`SqlQuery::COLUMNS`] — the elements live in
/// a second table — and neither is the COMPANION, which is the gap this round closes: the companion
/// is a column of `reel` that no field of this row holds, so a page projects it under the engine's
/// alias instead.
#[derive(Debug, Clone, PartialEq)]
struct ReelRow {
  id: i64,
  title: String,
  tags: Vec<String>,
}

impl<'r, R> sqlx::FromRow<'r, R> for ReelRow
where
  R: sqlx::Row,
  i64: sqlx::Decode<'r, R::Database> + sqlx::Type<R::Database>,
  String: sqlx::Decode<'r, R::Database> + sqlx::Type<R::Database>,
  for<'a> &'a str: sqlx::ColumnIndex<R>,
{
  fn from_row(row: &'r R) -> Result<Self, sqlx::Error> {
    Ok(Self {
      id: row.try_get("id")?,
      title: row.try_get("title")?,
      tags: Vec::new(),
    })
  }
}

/// Bind this row's key column — the plan's half of the gather's membership.
fn reel_key<Db>(row: &ReelRow, _: usize, qb: &mut sqlx::QueryBuilder<Db>)
where
  Db: sqlx::Database,
  i64: Carrier<Db>,
{
  row.id.push_bind(qb);
}

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

/// One ordering term. `Tags` is the `sortable` word's — the term whose two names come apart.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ReelOrder {
  Tags(OrderDirection),
  Title(OrderDirection),
  Id(OrderDirection),
}

/// One cursor slot. The companion's slot holds BYTES — the sort key itself, which is one ordinary
/// blob and needs no codec of its own.
#[derive(Debug, Clone, PartialEq)]
enum ReelValue {
  Tags(Vec<u8>),
  Title(String),
  Id(i64),
}

impl CursorValue for ReelValue {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    match self {
      Self::Tags(value) => {
        out.push(0);
        value.write_cursor(out);
      }
      Self::Title(value) => {
        out.push(1);
        value.write_cursor(out);
      }
      Self::Id(value) => {
        out.push(2);
        value.write_cursor(out);
      }
    }
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let (tag, rest) = bytes.split_first()?;
    match tag {
      0 => Vec::<u8>::read_cursor(rest).map(Self::Tags),
      1 => String::read_cursor(rest).map(Self::Title),
      2 => i64::read_cursor(rest).map(Self::Id),
      _ => None,
    }
  }
}

impl<Db> Carrier<Db> for ReelValue
where
  Db: sqlx::Database,
  Vec<u8>: Carrier<Db>,
  String: Carrier<Db>,
  i64: Carrier<Db>,
{
  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    match self {
      Self::Tags(value) => value.push_bind(qb),
      Self::Title(value) => value.push_bind(qb),
      Self::Id(value) => value.push_bind(qb),
    }
  }
}

/// The record's filter: nothing at all. Every lane here passes `None`, so what this type owes is
/// EXISTENCE — `Record<Db>::Comparison` is a slot the query face reads — and an empty comparison
/// renders no conjunct rather than a tautology that would show up in every golden below.
struct ReelFilter<Db>(PhantomData<fn() -> Db>);

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

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

impl<Db: Backend> Record<Db> for Reel {
  type Row = ReelRow;
  type Comparison = ReelFilter<Db>;
  type OrderBy = ReelOrder;
}

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

  const ADDRESS: RecordAddress =
    RecordAddress::new(FieldName::new("reel"), &[FieldName::new("id")]);
  const ALIASES: &'static [&'static str] = &[
    "__ig_reel_0__",
    "__ig_reel_1__",
    "__ig_reel_2__",
    "__ig_reel_3__",
    "__ig_reel_4__",
    "__ig_reel_5__",
    "__ig_reel_6__",
    "__ig_reel_7__",
  ];
  /// The COLLECTION is absent, the plan's contract; and so is the COMPANION, which is the fact this
  /// round is about — `__ig_tags_sort__` is a column of `reel` and no field of this row, so it
  /// reaches the page under the engine's own sort alias and never through here.
  const COLUMNS: &'static [ColumnShape] = &[
    ColumnShape::Plain(ColumnName::new("id")),
    ColumnShape::Plain(ColumnName::new("title")),
  ];
  const COLLECTIONS: &'static [EdgeCollection<Self, Db>] = &[EdgeCollection::gather(
    &[FieldName::new("tags")],
    EdgeShape::Sequence,
    reel_key::<Db>,
    reel_tags::<Db>,
  )];

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

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

  fn record(self) -> Result<Reel, CrossingError> {
    Ok(Reel {
      id: self.id,
      title: self.title,
      tags: self.tags,
    })
  }
}

impl<Db> SqlOrdering<Db> for ReelRow
where
  Db: Backend + sqlx::Database,
  SqlKeyIn<ReelValue, Db, 1>: ComplexComparison<Db>,
  ReelValue: Carrier<Db>,
  TermColumns: OrderSubjects<Db>,
  i64: Carrier<Db>,
  for<'r> i64: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'r> String: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'r> Vec<u8>: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
{
  type Order = ReelOrder;
  type Value = ReelValue;
  type Subjects = TermColumns;

  fn complete(written: &[ReelOrder]) -> Vec<ReelOrder> {
    let mut order = written.to_vec();
    if !written.iter().any(|term| matches!(term, ReelOrder::Id(_))) {
      order.push(ReelOrder::Id(OrderDirection::Asc));
    }
    order
  }

  fn subjects(_: &[ReelOrder]) -> TermColumns {
    TermColumns
  }

  fn term(order: ReelOrder) -> OrderTerm {
    match order {
      // The one term whose rendered name is not the field's: the statement orders by the companion
      // and the identity stays the collection's.
      ReelOrder::Tags(direction) => OrderTerm::shadow(TermName::new("tags"), COMPANION, direction),
      ReelOrder::Title(direction) => {
        OrderTerm::new(TermName::new("title"), FieldName::new("title"), direction)
      }
      ReelOrder::Id(direction) => {
        OrderTerm::new(TermName::new("id"), FieldName::new("id"), direction)
      }
    }
  }

  /// The two column terms read the DECODED row. The COMPANION reads the RAW one under the engine's
  /// alias — the value this statement's own `ORDER BY` sorted by, which is what freezes the boundary
  /// where the page actually stopped.
  ///
  /// `self.tags` is deliberately not touched here: it is the same collection, arriving from a second
  /// statement, and a boundary read from it would be a boundary the ordering never produced.
  fn value(
    &self,
    order: ReelOrder,
    _: usize,
    raw: &Db::Row,
    alias: &str,
  ) -> Result<Option<ReelValue>, sqlx::Error> {
    match order {
      ReelOrder::Tags(_) => {
        sqlx::Row::try_get::<Vec<u8>, _>(raw, alias).map(|bytes| Some(ReelValue::Tags(bytes)))
      }
      ReelOrder::Title(_) => Ok(Some(ReelValue::Title(self.title.clone()))),
      ReelOrder::Id(_) => Ok(Some(ReelValue::Id(self.id))),
    }
  }
}

/// The companion column's own name, under the synthesized-column law.
const COMPANION: &FieldName = FieldName::new("__ig_tags_sort__");

/// The completed order's terms, at one dialect.
fn terms<Db>(written: &[ReelOrder]) -> Vec<OrderTerm>
where
  Db: SqlDialect,
  ReelRow: SqlOrdering<Db, Order = ReelOrder>,
{
  <ReelRow as SqlOrdering<Db>>::complete(written)
    .iter()
    .map(|term| <ReelRow as SqlOrdering<Db>>::term(*term))
    .collect()
}

/// The PAGE statement for `written`, resumed at `boundary` where one is given — the whole of what a
/// dialect is sent.
fn paged<Db>(written: &[ReelOrder], boundary: Option<&Cursor<ReelValue>>, walk: Walk) -> String
where
  Db: SqlDialect,
  ReelRow: SqlOrdering<Db, Order = ReelOrder, Value = ReelValue, Subjects = TermColumns>,
  ReelValue: Carrier<Db>,
  i64: sqlx::Type<Db> + for<'t> sqlx::Encode<'t, Db>,
{
  let terms = terms::<Db>(written);
  let order = SqlOrder::<Db>::new(&terms).expect("a companion column is a column");
  let subjects = &TermColumns;
  let keyset = boundary
    .map(|cursor| SqlKeyset::resume_with(order, cursor, walk, subjects))
    .transpose()
    .expect("this cursor is this order's");
  ordered::<ReelRow, Db>(
    None,
    None,
    Ordering {
      order,
      subjects,
      keyset: keyset.as_ref(),
      values: SortValues::Projected,
    },
    walk,
    Some(2),
    None,
  )
  .expect("a renderable page")
  .into_string()
}

/// The ordered SCAN's statement — the lane that mints no cursor.
#[cfg(feature = "sqlite")]
fn scanned<Db>(written: &[ReelOrder]) -> String
where
  Db: SqlDialect,
  ReelRow: SqlOrdering<Db, Order = ReelOrder, Value = ReelValue, Subjects = TermColumns>,
  ReelValue: Carrier<Db>,
  i64: sqlx::Type<Db> + for<'t> sqlx::Encode<'t, Db>,
{
  let terms = terms::<Db>(written);
  let order = SqlOrder::<Db>::new(&terms).expect("a companion column is a column");
  ordered::<ReelRow, Db>(
    None,
    None,
    Ordering {
      order,
      subjects: &TermColumns,
      keyset: None,
      values: SortValues::Unread,
    },
    Walk::Forward,
    None,
    None,
  )
  .expect("a renderable scan")
  .into_string()
}

/// A boundary at the sort key of `tags` — what an earlier page's last row would have handed back.
#[cfg(feature = "sqlite")]
fn boundary(tags: &[&str], id: i64, written: &[ReelOrder]) -> Cursor<ReelValue> {
  let collection: Vec<String> = tags.iter().map(|tag| (*tag).to_owned()).collect();
  Cursor::at(
    &terms::<sqlx::Sqlite>(written),
    [
      Some(ReelValue::Tags(crate::collection_sort_key(&collection))),
      Some(ReelValue::Id(id)),
    ],
  )
}

/// `tags ASC, id ASC` — the order every assertion below is about.
const BY_TAGS: &[ReelOrder] = &[ReelOrder::Tags(OrderDirection::Asc)];

/// **THE DELIVERABLE, IN SQLITE.** The companion rides the SELECT list under the engine's own sort
/// alias, the `ORDER BY` names it, and the keyset resumes at it — three readings of one column, and
/// the row's own two columns beside them exactly as before.
#[cfg(feature = "sqlite")]
#[test]
fn a_page_over_a_companion_projects_it_orders_by_it_and_resumes_at_it() {
  let resumed = boundary(&["a"], 4, BY_TAGS);

  assert_eq!(
    paged::<sqlx::Sqlite>(BY_TAGS, Some(&resumed), Walk::Forward),
    r#"SELECT "id", "title", "__ig_tags_sort__" AS "__ig_ord0__" FROM "reel" WHERE ("__ig_tags_sort__" > ? OR ("__ig_tags_sort__" = ? AND ("id" > ?))) ORDER BY "__ig_tags_sort__" ASC, "id" ASC LIMIT ?"#
  );
}

/// **The BACKWARD walk inverts every term**, companion included — which is what makes it the same
/// order read from the far end rather than a second order the cursor cannot resume in.
#[cfg(feature = "sqlite")]
#[test]
fn the_backward_walk_inverts_the_companion_with_everything_else() {
  let resumed = boundary(&["a"], 4, BY_TAGS);

  assert_eq!(
    paged::<sqlx::Sqlite>(BY_TAGS, Some(&resumed), Walk::Backward),
    r#"SELECT "id", "title", "__ig_tags_sort__" AS "__ig_ord0__" FROM "reel" WHERE ("__ig_tags_sort__" < ? OR ("__ig_tags_sort__" = ? AND ("id" < ?))) ORDER BY "__ig_tags_sort__" DESC, "id" DESC LIMIT ?"#
  );
}

/// **PostgreSQL renders the same three readings**, in its own brackets and with numbered
/// placeholders — the companion being `bytea` there and a column like any other.
#[cfg(feature = "postgres")]
#[test]
fn postgres_renders_the_companion_as_its_own_column() {
  let terms = terms::<sqlx::Postgres>(BY_TAGS);
  let resumed = Cursor::at(
    &terms,
    [
      Some(ReelValue::Tags(crate::collection_sort_key(&[
        "a".to_owned()
      ]))),
      Some(ReelValue::Id(4)),
    ],
  );

  assert_eq!(
    paged::<sqlx::Postgres>(BY_TAGS, Some(&resumed), Walk::Forward),
    r#"SELECT "id", "title", "__ig_tags_sort__" AS "__ig_ord0__" FROM "reel" WHERE ("__ig_tags_sort__" > $1 OR ("__ig_tags_sort__" = $2 AND ("id" > $3))) ORDER BY "__ig_tags_sort__" ASC, "id" ASC LIMIT $4"#
  );
}

/// **MySQL renders it too, and pays a SCAN for it.** Its `BLOB` carries the binary collation, so the
/// ORDER is the frame's and the page is exact — and `SORT_KEY_INDEX` is `false` there, a blob key
/// needing a length (`ERROR 1170`), so the resume predicate has no index to seek with. That is a
/// COST and not a refusal: the rows come back in the pinned sequence either way, which is why this
/// dialect serves the page rather than being turned away from it.
#[cfg(feature = "mysql")]
#[test]
fn mysql_renders_the_companion_and_the_index_it_has_not_got_changes_nothing() {
  let terms = terms::<sqlx::MySql>(BY_TAGS);
  let resumed = Cursor::at(
    &terms,
    [
      Some(ReelValue::Tags(crate::collection_sort_key(&[
        "a".to_owned()
      ]))),
      Some(ReelValue::Id(4)),
    ],
  );

  assert_eq!(
    paged::<sqlx::MySql>(BY_TAGS, Some(&resumed), Walk::Forward),
    r"SELECT `id`, `title`, `__ig_tags_sort__` AS `__ig_ord0__` FROM `reel` WHERE (`__ig_tags_sort__` > ? OR (`__ig_tags_sort__` = ? AND (`id` > ?))) ORDER BY `__ig_tags_sort__` ASC, `id` ASC LIMIT ?"
  );
}

/// **The ordered SCAN projects NOTHING**, which is the split `SortValues` exists for: it mints no
/// cursor, so a companion read onto every row would be one more column per row that nothing reads.
/// The `ORDER BY` is unchanged — that is the `sortable` word's own shipped deliverable, untouched.
#[cfg(feature = "sqlite")]
#[test]
fn the_ordered_scan_carries_the_order_and_projects_no_boundary() {
  let scan = scanned::<sqlx::Sqlite>(BY_TAGS);

  assert_eq!(
    scan,
    r#"SELECT "id", "title" FROM "reel" ORDER BY "__ig_tags_sort__" ASC, "id" ASC"#
  );
  assert!(
    !scan.contains("__ig_ord0__"),
    "no cursor is minted, so no boundary is read"
  );
}

/// **The FIRST page projects the companion too**, so the walk's every page reads its boundary the
/// same way — a first page that skipped the projection would mint a cursor from a column that was
/// never selected.
#[cfg(feature = "sqlite")]
#[test]
fn the_first_page_of_a_walk_projects_the_boundary_as_every_page_does() {
  assert!(
    paged::<sqlx::Sqlite>(BY_TAGS, None, Walk::Forward)
      .contains(r#""__ig_tags_sort__" AS "__ig_ord0__""#)
  );
}

/// **A cursor minted under ANOTHER order is refused before anything renders** — the existing family,
/// reaching a companion term unchanged, because a signature is over the terms' identities and a
/// companion's identity is the field's.
#[cfg(feature = "sqlite")]
#[test]
fn a_cursor_minted_under_another_order_is_refused() {
  let by_title: &[ReelOrder] = &[ReelOrder::Title(OrderDirection::Asc)];
  let elsewhere = Cursor::at(
    &terms::<sqlx::Sqlite>(by_title),
    [
      Some(ReelValue::Title("a".to_owned())),
      Some(ReelValue::Id(4)),
    ],
  );

  let terms = terms::<sqlx::Sqlite>(BY_TAGS);
  let order = SqlOrder::<sqlx::Sqlite>::new(&terms).expect("a renderable order");
  assert!(matches!(
    SqlKeyset::resume_with(order, &elsewhere, Walk::Forward, &TermColumns),
    Err(crate::CursorError::Order { .. })
  ));
}

/// **A MALFORMED boundary is refused by the existing family**, and no new refusal was minted for
/// one: a companion's slot is an ordinary blob, so what can be wrong with it is what can be wrong
/// with any slot.
///
/// The sharpest one is the ABSENT companion. A collection has no null state — the empty collection
/// is a value and its key is one byte — so the term is `NOT NULL` and a cursor holding nothing there
/// is refused BY THE TERM's own name, before a statement is rendered. The other is the frame itself:
/// a string a client shortened does not decode at all.
#[cfg(feature = "sqlite")]
#[test]
fn a_malformed_boundary_is_refused_by_the_existing_family() {
  let terms = terms::<sqlx::Sqlite>(BY_TAGS);
  let absent = Cursor::at(&terms, [None, Some(ReelValue::Id(4))]);
  let order = SqlOrder::<sqlx::Sqlite>::new(&terms).expect("a renderable order");

  assert_eq!(
    SqlKeyset::resume_with(order, &absent, Walk::Forward, &TermColumns).err(),
    Some(crate::CursorError::Null(TermName::new("tags"))),
    "a companion has no absence to mean, so the slot cannot be empty"
  );

  let minted = boundary(&["a"], 4, BY_TAGS).encode();
  assert!(
    Cursor::<ReelValue>::decode(&minted[..minted.len() - 3]).is_err(),
    "and a frame a client shortened is refused rather than read as the nearest slot"
  );
}

/// THE ENGINE'S OWN ANSWER — the claims no rendered statement can make.
#[cfg(feature = "sqlite")]
mod live {
  use sqlx::{Connection as _, Sqlite};

  use super::{BY_TAGS, Reel, ReelOrder, ReelRow, ReelValue, boundary};
  use crate::{
    Cursor, OrderDirection, collection_sort_key,
    query::{compare_collections, sql::Find},
  };

  /// The corpus, in an order that is NOT the answer — `query::sql::ddl`'s own shadow corpus, whose
  /// load-bearing pair is `["a", "b"]` against `["ab"]`: a joined encoding with no element boundary
  /// writes `ab` for both.
  ///
  /// Row 9 is this suite's own, and it is the FROZEN-BOUNDARY probe: its companion column holds the
  /// key of `["a", "a"]` while its edge rows hold `["z"]`. Nothing a declaration can produce looks
  /// like this — the write plan fills both from one collection — and that is the point: it makes the
  /// two readings of *this row's order* distinguishable, which they are not in any honest row.
  fn corpus() -> Vec<(i64, Vec<String>, Vec<String>)> {
    let owned =
      |tags: &[&str]| -> Vec<String> { tags.iter().map(|tag| (*tag).to_owned()).collect() };
    let reel = |id: i64, tags: &[&str]| (id, owned(tags), owned(tags));
    vec![
      reel(1, &["b"]),
      reel(2, &[]),
      reel(3, &["a", "b"]),
      reel(4, &["a"]),
      reel(5, &["a", "a", "a"]),
      reel(6, &["10"]),
      reel(7, &["2"]),
      reel(8, &["ab"]),
      // (ordered as) ["a", "a"]  ·  (elements) ["z"]
      (9, owned(&["a", "a"]), owned(&["z"])),
    ]
  }

  /// The schema and the corpus, written for real — the collection into the edge table, its ORDER
  /// into the companion column beside it.
  async fn written() -> sqlx::sqlite::SqliteConnection {
    let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
      .await
      .expect("an in-memory database");
    for ddl in [
      r#"CREATE TABLE "reel" ("id" INTEGER PRIMARY KEY, "title" TEXT NOT NULL,
         "__ig_tags_sort__" BLOB NOT NULL)"#,
      r#"CREATE TABLE "reel_tags" ("id" INTEGER NOT NULL, "tags_ordinal" INTEGER NOT NULL,
         "tags" TEXT NOT NULL, PRIMARY KEY ("id", "tags_ordinal"))"#,
    ] {
      sqlx::query(ddl).execute(&mut db).await.expect("a table");
    }
    for (id, ordered_as, elements) in corpus() {
      sqlx::query(r#"INSERT INTO "reel" VALUES (?, ?, ?)"#)
        .bind(id)
        .bind(format!("reel {id}"))
        .bind(collection_sort_key(&ordered_as))
        .execute(&mut db)
        .await
        .expect("a reel");
      for (ordinal, tag) in elements.iter().enumerate() {
        sqlx::query(r#"INSERT INTO "reel_tags" VALUES (?, ?, ?)"#)
          .bind(id)
          .bind(i64::try_from(ordinal).expect("a small corpus"))
          .bind(tag)
          .execute(&mut db)
          .await
          .expect("a tag");
      }
    }
    db
  }

  /// The ids the ORDERED SCAN returns — the sequence every page below is held against, taken from
  /// the framework's own lane rather than from a string this test wrote.
  async fn scan(db: &mut sqlx::sqlite::SqliteConnection) -> Vec<i64> {
    Find::<ReelRow, Sqlite, _>::new(&mut *db, false)
      .order(BY_TAGS)
      .fetch()
      .await
      .expect("the ordered scan")
      .into_iter()
      .map(|reel: Reel| reel.id)
      .collect()
  }

  /// The ids the PIN puts the same corpus in, reading each row's ORDER from the collection its
  /// companion was written from.
  fn pinned() -> Vec<i64> {
    let mut rows = corpus();
    rows.sort_by(|(left_id, left, _), (right_id, right, _)| {
      compare_collections(left, right).then(left_id.cmp(right_id))
    });
    rows.into_iter().map(|(id, _, _)| id).collect()
  }

  /// Every page of `BY_TAGS`, `size` at a time, each cursor round-tripped through its base64 STRING
  /// as a client's would be — forwards.
  async fn forwards(db: &mut sqlx::sqlite::SqliteConnection, size: u32) -> Vec<i64> {
    let mut ids = Vec::new();
    let mut resume: Option<String> = None;
    loop {
      let page = match &resume {
        None => Find::<ReelRow, Sqlite, _>::new(&mut *db, false)
          .order(BY_TAGS)
          .first(size)
          .fetch()
          .await
          .expect("the first page"),
        Some(encoded) => {
          let cursor = Cursor::<ReelValue>::decode(encoded).expect("a cursor this engine minted");
          Find::<ReelRow, Sqlite, _>::new(&mut *db, false)
            .order(BY_TAGS)
            .first(size)
            .after(&cursor)
            .fetch()
            .await
            .expect("the next page")
        }
      };
      let more = page.has_next_page();
      let last = page.edges().last().map(|edge| edge.cursor().encode());
      ids.extend(
        page
          .into_edges()
          .into_iter()
          .map(|edge| edge.into_parts().0.id),
      );
      if !more {
        break;
      }
      resume = last;
    }
    ids
  }

  /// The same walk from the far end — `last` and `before` — with each page's rows prepended, so the
  /// answer is in the scan's own display order.
  async fn backwards(db: &mut sqlx::sqlite::SqliteConnection, size: u32) -> Vec<i64> {
    let mut ids: Vec<i64> = Vec::new();
    let mut resume: Option<String> = None;
    loop {
      let page = match &resume {
        None => Find::<ReelRow, Sqlite, _>::new(&mut *db, false)
          .order(BY_TAGS)
          .last(size)
          .fetch()
          .await
          .expect("the last page"),
        Some(encoded) => {
          let cursor = Cursor::<ReelValue>::decode(encoded).expect("a cursor this engine minted");
          Find::<ReelRow, Sqlite, _>::new(&mut *db, false)
            .order(BY_TAGS)
            .last(size)
            .before(&cursor)
            .fetch()
            .await
            .expect("the page before it")
        }
      };
      let more = page.has_previous_page();
      let first = page.edges().first().map(|edge| edge.cursor().encode());
      let mut head: Vec<i64> = page
        .into_edges()
        .into_iter()
        .map(|edge| edge.into_parts().0.id)
        .collect();
      head.append(&mut ids);
      ids = head;
      if !more {
        break;
      }
      resume = first;
    }
    ids
  }

  /// **THE PARITY PIN, AGAINST A LIVE ENGINE.** SQLite ordering the companion column returns the
  /// corpus in exactly the order [`compare_collections`] does — including row 9, whose companion is
  /// the order it is placed by.
  #[tokio::test]
  async fn the_scan_is_the_pin() {
    let mut db = written().await;

    assert_eq!(scan(&mut db).await, pinned());
  }

  /// **THE WALK, live: no row lost and none doubled across any seam.** Every page size the corpus
  /// has a seam at, each cursor round-tripped through its string, held against the ordered scan.
  #[tokio::test]
  async fn a_page_over_a_companion_walks_the_scan_exactly() {
    let mut db = written().await;
    let expected = scan(&mut db).await;

    for size in 1..=4 {
      assert_eq!(
        forwards(&mut db, size).await,
        expected,
        "the forward walk at size {size}"
      );
      assert_eq!(
        backwards(&mut db, size).await,
        expected,
        "the backward walk at size {size}"
      );
    }
  }

  /// **THE FROZEN BOUNDARY, MADE OBSERVABLE.** Row 9's companion says `["a", "a"]` and its edge rows
  /// say `["z"]`, so the two readings of *where this row sits* are far apart — and the page resumes
  /// at the one the `ORDER BY` used.
  ///
  /// A boundary rebuilt from the hydrated collection would put row 9's position at the very END of
  /// the sequence, and the page after it would come back EMPTY with rows still to serve. The
  /// statement is identical either way, which is why this is measured here and not read off a
  /// golden.
  #[tokio::test]
  async fn the_boundary_is_the_companions_bytes_and_not_the_collections() {
    let mut db = written().await;
    let expected = scan(&mut db).await;
    let at = expected
      .iter()
      .position(|id| *id == 9)
      .expect("row 9 is in the scan");

    let page = Find::<ReelRow, Sqlite, _>::new(&mut db, false)
      .order(BY_TAGS)
      .first(u32::try_from(at + 1).expect("a small corpus"))
      .fetch()
      .await
      .expect("the page ending at row 9");
    let edge = page.edges().last().expect("a non-empty page");
    assert_eq!(edge.node().id, 9, "the page stops at row 9");
    assert_eq!(
      edge.node().tags,
      ["z"],
      "and it is holding the collection its edge table gave it"
    );
    assert_eq!(
      *edge.cursor().values(),
      *boundary(&["a", "a"], 9, BY_TAGS).values(),
      "while the boundary it hands back is the COMPANION's bytes"
    );

    let resumed = Cursor::<ReelValue>::decode(&edge.cursor().encode()).expect("its own cursor");
    let after: Vec<i64> = Find::<ReelRow, Sqlite, _>::new(&mut db, false)
      .order(BY_TAGS)
      .first(16)
      .after(&resumed)
      .fetch()
      .await
      .expect("the page after row 9")
      .into_edges()
      .into_iter()
      .map(|edge| edge.into_parts().0.id)
      .collect();

    assert_eq!(
      after,
      expected[at + 1..],
      "every row after it, and no other — where a rebuilt boundary would have served none"
    );
  }

  /// **A page ordered the other way round walks the same rows in reverse**, which is the property a
  /// backward walk rests on and the one a companion has to keep for the two `Walk`s to be one order.
  #[tokio::test]
  async fn the_descending_order_is_the_exact_reverse() {
    let mut db = written().await;
    let ascending = scan(&mut db).await;

    let descending: Vec<i64> = Find::<ReelRow, Sqlite, _>::new(&mut db, false)
      .order(&[
        ReelOrder::Tags(OrderDirection::Desc),
        ReelOrder::Id(OrderDirection::Desc),
      ])
      .fetch()
      .await
      .expect("the descending scan")
      .into_iter()
      .map(|reel: Reel| reel.id)
      .collect();

    let mut reversed = ascending;
    reversed.reverse();
    assert_eq!(descending, reversed);
  }
}