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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
//! The two relation kinds' rendering, their refusals, and the collapse.
//!
//! Text is the instrument here more than it is for a leaf, and the reason is the subquery seam's
//! own: what a relation gets wrong renders perfectly well. A correlation joining the child table to
//! itself, a semi-join projecting the wrong column, an `all` whose negation sits outside the
//! `EXISTS` — each is valid SQL of the right shape that admits a different row set. So the pins are
//! byte-exact and each names the mutation it would catch.
#![cfg(feature = "sqlite")]

use super::{SqlDerivedComparison, SqlRefComparison};
use crate::{
  At, FieldName, RecordAddress, ScalarFilter, TextFilter,
  comparison::{
    CollapsibleComparison, ComplexComparison, TryFromFilter,
    sql::{
      RelatedRow, RelationDepthError, RelationWidthError, SqlConjunction, SqlCountComparison,
      SqlLoweringError, SqlScalarComparison, SqlTextComparison, tests::render_at,
    },
  },
};

/// The row every predicate here constrains: a `shot`, keyed by `id`, carrying a `cover_id` that
/// points at a keyframe.
const SHOT: RecordAddress = RecordAddress::new(FieldName::new("shot"), &[FieldName::new("id")]);
/// The row a `cover_id` points AT, and — read the other way — the row whose `shot_id` points back.
const KEYFRAME: RelatedRow = RelatedRow::new(
  RecordAddress::new(FieldName::new("keyframe"), &[FieldName::new("id")]),
  &[
    "__ig_keyframe_0__",
    "__ig_keyframe_1__",
    "__ig_keyframe_2__",
  ],
);
/// A row addressed by two columns — what neither kind has a second name for.
const SPLICE: RelatedRow = RelatedRow::new(
  RecordAddress::new(
    FieldName::new("splice"),
    &[FieldName::new("media_id"), FieldName::new("splice_id")],
  ),
  &["__ig_splice_0__", "__ig_splice_1__"],
);
/// A record that refers to its OWN kind — the shape whose correlation used to compare a column to
/// itself. Two aliases past depth zero, which is what the two-level pin needs.
const SCENE: RelatedRow = RelatedRow::new(
  RecordAddress::new(FieldName::new("scene"), &[FieldName::new("id")]),
  &["__ig_scene_0__", "__ig_scene_1__", "__ig_scene_2__"],
);
/// The same row with ONE alias minted, so depth one is already past the ceiling — what the refusal
/// is exercised against without nesting eight levels of fixture.
const SHALLOW: RelatedRow = RelatedRow::new(
  RecordAddress::new(FieldName::new("scene"), &[FieldName::new("id")]),
  &["__ig_scene_0__"],
);
/// A row whose declaration named `alias(depth = 10)` — TEN names, two past what the default mints.
const DEEP: RelatedRow = RelatedRow::new(
  RecordAddress::new(FieldName::new("deep"), &[FieldName::new("id")]),
  &[
    "__ig_deep_0__",
    "__ig_deep_1__",
    "__ig_deep_2__",
    "__ig_deep_3__",
    "__ig_deep_4__",
    "__ig_deep_5__",
    "__ig_deep_6__",
    "__ig_deep_7__",
    "__ig_deep_8__",
    "__ig_deep_9__",
  ],
);
/// Its twin at the DEFAULT depth — eight names, exactly what `DEPTH_CEILING` mints for a declaration
/// that named none. Spelled out rather than derived from the constant, so the fixture is what a
/// reader can count.
const DEFAULTED: RelatedRow = RelatedRow::new(
  RecordAddress::new(FieldName::new("scene"), &[FieldName::new("id")]),
  &[
    "__ig_scene_0__",
    "__ig_scene_1__",
    "__ig_scene_2__",
    "__ig_scene_3__",
    "__ig_scene_4__",
    "__ig_scene_5__",
    "__ig_scene_6__",
    "__ig_scene_7__",
  ],
);
/// The `scene` column carrying its parent's id.
const PARENT_ID: &FieldName = FieldName::new("parent_id");
/// The `keyframe` column carrying a shot's id, which is what a reverse position correlates on.
const SHOT_ID: &FieldName = FieldName::new("shot_id");
/// The correlated scope every reverse quantifier opens, spelled once so the tests below read as the
/// quantifier they are about.
const SCOPE: &str = "SELECT 1 FROM \"keyframe\" \"__ig_keyframe_1__\" \
                    WHERE \"__ig_keyframe_1__\".\"shot_id\" = \"shot\".\"id\"";
/// The same scope's cardinality.
const CARDINALITY: &str = "(SELECT COUNT(*) FROM \"keyframe\" \"__ig_keyframe_1__\" \
                           WHERE \"__ig_keyframe_1__\".\"shot_id\" = \"shot\".\"id\")";

type Scalar = SqlScalarComparison<i64, sqlx::Sqlite>;
type Text = SqlTextComparison<String, sqlx::Sqlite>;
type Ref = SqlRefComparison<Keyframe, sqlx::Sqlite>;
type Derived = SqlDerivedComparison<Keyframe, sqlx::Sqlite>;

/// A stand-in for a generated ENTITY comparison: two columns walked at frames below whatever row it
/// is applied at, plus the id projection a relation collapses through.
///
/// Written by hand because the emission that would write one is blocked — see the parent module's
/// note — and because the two things a relation asks of a target comparison are exactly these: render
/// at an address, and say whether the id is all it constrains.
#[derive(Debug, Clone, PartialEq)]
struct Keyframe {
  id: Scalar,
  title: Text,
  /// Whether the id's operators SURVIVE the collapse — the second half of
  /// [`CollapsibleComparison`]'s law, which a generated comparison answers from the operators it set
  /// and this fixture answers from a field.
  referential: bool,
}

impl Keyframe {
  fn new() -> Self {
    Self {
      id: Scalar::new(),
      title: Text::new(),
      referential: true,
    }
  }

  fn with_id(mut self, id: i64) -> Self {
    self.id = Scalar::try_from_filter(ScalarFilter::<i64>::new().with_eq(id)).unwrap();
    self
  }

  fn with_title(mut self, title: &str) -> Self {
    self.title =
      Text::try_from_filter(TextFilter::<String>::new().with_eq(title.to_owned())).unwrap();
    self
  }

  /// The id is constrained and the shape does NOT survive a dangling reference, so the target
  /// declines the collapse and the relation pays for its subquery.
  const fn unreferential(mut self) -> Self {
    self.referential = false;
    self
  }
}

impl ComplexComparison<sqlx::Sqlite> for Keyframe {
  fn conjuncts(&self) -> usize {
    self.id.conjuncts() + self.title.conjuncts()
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: SqlConjunction<'q, sqlx::Sqlite>,
  ) -> Result<SqlConjunction<'q, sqlx::Sqlite>, SqlLoweringError> {
    let id = at.frame(FieldName::new("id"));
    let builder = self.id.apply(id.at(), builder)?;
    let title = at.frame(FieldName::new("title"));
    self.title.apply(title.at(), builder)
  }
}

impl CollapsibleComparison<sqlx::Sqlite> for Keyframe {
  type Id = Scalar;

  fn only_id(&self) -> Option<&Scalar> {
    (self.referential && self.title.is_empty()).then_some(&self.id)
  }
}

/// Render one comparison of [`SHOT`] at `column` and return `(sql, bind count)`.
///
/// The family harness's `render` frames a row of its own, and both kinds here need this one — the
/// forward kind because the foreign key is a column of it, the reverse kind because the correlation
/// compares against its id.
fn render(column: &str, comparison: &impl ComplexComparison<sqlx::Sqlite>) -> (String, usize) {
  let frame = At::new(&SHOT).frame(FieldName::new(column));
  render_at::<sqlx::Sqlite, _>(frame.at(), comparison)
}

/// What a lowering answered with at `at` — the SQL it rendered, or the refusal instead.
fn lowered(
  at: At<'_>,
  comparison: &impl ComplexComparison<sqlx::Sqlite>,
) -> Result<String, SqlLoweringError> {
  let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
  {
    let out = SqlConjunction::with_lead(&mut qb, "");
    comparison.apply(at, out)?;
  }
  Ok(qb.into_string())
}

/// **The forward reference is a semi-join through the foreign key**, and every name in it comes from
/// a different party: the fk from the address it was applied at, the projected id and the table from
/// the target this comparison holds.
///
/// The mutations this catches both parse — projecting the target's table where its id belongs, and
/// selecting FROM the parent.
#[test]
fn a_forward_reference_renders_a_semi_join_through_the_foreign_key() {
  let cover = Ref::new(KEYFRAME, Keyframe::new().with_title("Autumn"));

  assert_eq!(
    render("cover_id", &cover),
    (
      "\"cover_id\" IN ( SELECT \"__ig_keyframe_1__\".\"id\" FROM \"keyframe\" \"__ig_keyframe_1__\" WHERE \"title\" = ? )".into(),
      1
    )
  );
  assert_eq!(ComplexComparison::conjuncts(&cover), 1);
}

/// **The subquery is BARE — no `ORDER BY`, no `LIMIT`.**
///
/// A `LIMIT` inside would bound it globally rather than per parent, which changes the ANSWER by
/// dropping parents that qualify; per-parent top-N is a lateral join or a window function and a
/// different feature. The outer PAGE's ceiling is the page's own, which is why the statement here
/// carries one and the assertion reads only what is inside the brackets.
#[test]
fn the_relation_subquery_carries_no_order_and_no_limit() {
  use crate::comparison::sql::{QueryBuilder, SelectClause};

  let cover = Ref::new(KEYFRAME, Keyframe::new().with_title("Autumn"));
  let mut statement = QueryBuilder::<SelectClause, sqlx::Sqlite>::select()
    .push_field("\"id\"")
    .from("\"shot\"")
    .begin_where();
  {
    let frame = At::new(&SHOT).frame(FieldName::new("cover_id"));
    let accumulator = SqlConjunction::new(statement.inner_mut());
    cover.apply(frame.at(), accumulator).unwrap();
  }
  let sql = statement
    .order_by(FieldName::new("slate"), false)
    .limit(10)
    .finalize()
    .into_string();

  let (_, tail) = sql.split_once(" IN ( ").expect("a semi-join");
  let (subquery, _) = tail.split_once(" )").expect("a closed subquery");
  assert!(
    !subquery.contains("ORDER BY") && !subquery.contains("LIMIT"),
    "the relation subquery is bare: {subquery}"
  );
  // The page's ceiling is unaffected — the law is about what is INSIDE the brackets.
  assert!(sql.ends_with(" ORDER BY \"slate\" ASC LIMIT ?"), "{sql}");
}

/// **A predicate naming only the target's id renders NO subquery**, and it renders the id's own
/// operators at the foreign key's address.
///
/// The two twins below are what make this an optimisation rather than a coincidence: the same
/// relation and the same id, once with a target that declines the substitution and once with a
/// second column set, each paying for one subquery.
#[test]
fn a_predicate_on_the_targets_id_alone_collapses_onto_the_foreign_key() {
  let collapsing = Ref::new(KEYFRAME, Keyframe::new().with_id(10));
  let (sql, binds) = render("cover_id", &collapsing);
  assert_eq!((sql.as_str(), binds), ("\"cover_id\" = ?", 1));
  assert!(!sql.contains("SELECT"), "the collapse renders no subquery");
  assert_eq!(ComplexComparison::conjuncts(&collapsing), 1);

  let declining = Ref::new(KEYFRAME, Keyframe::new().with_id(10).unreferential());
  assert_eq!(
    render("cover_id", &declining),
    (
      "\"cover_id\" IN ( SELECT \"__ig_keyframe_1__\".\"id\" FROM \"keyframe\" \"__ig_keyframe_1__\" WHERE \"id\" = ? )".into(),
      1
    )
  );

  let narrowed = Ref::new(KEYFRAME, Keyframe::new().with_id(10).with_title("Autumn"));
  assert_eq!(
    render("cover_id", &narrowed),
    (
      "\"cover_id\" IN ( SELECT \"__ig_keyframe_1__\".\"id\" FROM \"keyframe\" \"__ig_keyframe_1__\" WHERE \"id\" = ? AND \"title\" = ? )"
        .into(),
      2
    )
  );
}

/// An EMPTY nested predicate lowers to nothing — no degenerate `IN ( SELECT id FROM target )`, which
/// would be *this reference is live* rather than *nothing*.
#[test]
fn an_empty_nested_predicate_opens_no_conjunct() {
  let empty = Ref::new(KEYFRAME, Keyframe::new());
  assert_eq!(ComplexComparison::conjuncts(&empty), 0);
  assert_eq!(render("cover_id", &empty), (String::new(), 0));
}

/// **A wide address is refused before anything is written**, so the accumulator is left as it was
/// found — and the refusal is a property of the RELATION, so the collapsing predicate is refused
/// too.
///
/// Both directions: the forward kind refuses its TARGET, whose id it would project, and the reverse
/// kind refuses the PARENT, whose id it would compare against.
#[test]
fn a_relation_whose_address_is_wide_is_refused_and_writes_nothing() {
  let frame = At::new(&SHOT).frame(FieldName::new("splice_id"));
  let wide_target =
    SqlRefComparison::<_, sqlx::Sqlite>::new(SPLICE, Keyframe::new().with_title("Autumn"));
  assert_eq!(
    lowered(frame.at(), &wide_target),
    Err(SqlLoweringError::RelationWidth(RelationWidthError::new(
      FieldName::new("splice"),
      2
    )))
  );

  let collapsing = SqlRefComparison::<_, sqlx::Sqlite>::new(SPLICE, Keyframe::new().with_id(10));
  assert!(lowered(frame.at(), &collapsing).is_err());

  let reverse = Derived::new(KEYFRAME, SHOT_ID).with_any(Keyframe::new());
  assert_eq!(
    lowered(At::new(SPLICE.address()), &reverse),
    Err(SqlLoweringError::RelationWidth(RelationWidthError::new(
      FieldName::new("splice"),
      2
    )))
  );
}

/// **Each quantifier opens its own correlated scope**, and the four render in the order the
/// vocabulary declares them.
///
/// The rendering to watch is `all`'s: the negation sits INSIDE the `EXISTS`, around the nested
/// predicate alone. Moved outside — `NOT ( EXISTS ( … AND … ) )` — it becomes `none` under another
/// name, which is well-formed and answers a different question.
#[test]
fn every_quantifier_opens_a_correlated_scope_of_its_own() {
  let any = Derived::new(KEYFRAME, SHOT_ID).with_any(Keyframe::new().with_title("Autumn"));
  assert_eq!(
    render("covers", &any),
    (format!("EXISTS ({SCOPE} AND \"title\" = ?)"), 1)
  );

  let none = Derived::new(KEYFRAME, SHOT_ID).with_none(Keyframe::new().with_title("Autumn"));
  assert_eq!(
    render("covers", &none),
    (format!("NOT EXISTS ({SCOPE} AND \"title\" = ?)"), 1)
  );

  let all = Derived::new(KEYFRAME, SHOT_ID).with_all(Keyframe::new().with_title("Autumn"));
  assert_eq!(
    render("covers", &all),
    (format!("NOT EXISTS ({SCOPE} AND NOT ( \"title\" = ? ))"), 1)
  );

  let count = Derived::new(KEYFRAME, SHOT_ID).with_count(
    SqlCountComparison::try_from_filter(ScalarFilter::<usize>::new().with_gt(2)).unwrap(),
  );
  assert_eq!(render("covers", &count), (format!("{CARDINALITY} > ?"), 1));

  let every = Derived::new(KEYFRAME, SHOT_ID)
    .with_any(Keyframe::new())
    .with_all(Keyframe::new().with_title("Autumn"))
    .with_none(Keyframe::new())
    .with_count(
      SqlCountComparison::try_from_filter(ScalarFilter::<usize>::new().with_gt(2)).unwrap(),
    );
  assert_eq!(every.conjuncts(), 4);
  assert_eq!(
    render("covers", &every),
    (
      format!(
        "EXISTS ({SCOPE}) AND NOT EXISTS ({SCOPE} AND NOT ( \"title\" = ? )) AND \
         NOT EXISTS ({SCOPE}) AND {CARDINALITY} > ?"
      ),
      2
    )
  );
}

/// **`all` over an EMPTY predicate is vacuously true**, and it renders the constant rather than a
/// `NOT ( )` no dialect parses.
///
/// The other two quantifiers need no such case: an empty predicate leaves the accumulator's ` AND `
/// lead unpushed, so `any` becomes *this row has one* and `none` becomes *this row has none*.
#[test]
fn an_empty_predicate_is_vacuous_under_all_and_a_presence_test_under_the_others() {
  let all = Derived::new(KEYFRAME, SHOT_ID).with_all(Keyframe::new());
  assert_eq!(all.conjuncts(), 1);
  assert_eq!(render("covers", &all), ("1 = 1".into(), 0));

  let any = Derived::new(KEYFRAME, SHOT_ID).with_any(Keyframe::new());
  assert_eq!(render("covers", &any), (format!("EXISTS ({SCOPE})"), 0));

  let none = Derived::new(KEYFRAME, SHOT_ID).with_none(Keyframe::new());
  assert_eq!(
    render("covers", &none),
    (format!("NOT EXISTS ({SCOPE})"), 0)
  );
}

/// **The correlation names the source and the parent apart**, which is the assertion the reverse
/// kind rests on: both tables carry an `id`, and SQL resolves an unqualified name to the innermost
/// scope — so an unqualified correlation would compare the child's column to itself, hold for every
/// row of the child table, and turn every quantifier into a question about the WHOLE table.
///
/// The source side is its ALIAS rather than its table, which is the half that makes the shape hold
/// for a record referring to its own kind — see the self-relation pins below.
#[test]
fn the_correlation_qualifies_both_sides() {
  let any = Derived::new(KEYFRAME, SHOT_ID).with_any(Keyframe::new());
  let (sql, _) = render("covers", &any);
  assert!(
    sql.contains("\"__ig_keyframe_1__\".\"shot_id\" = \"shot\".\"id\""),
    "both sides are qualified: {sql}"
  );
}

/// **A SELF-RELATION names its two sides apart**, which is the whole defect the aliasing closes.
///
/// Before it, the source and the parent were each qualified by their TABLE — correct exactly while
/// the two tables differ. A `scene` whose `parent_id` names a `scene` rendered
/// `"scene"."parent_id" = "scene"."id"`, both halves resolving to the inner scope, so every
/// quantifier answered *is any row its own parent*. It parses, it binds, and it returns the wrong
/// rows; `live::a_self_relation_correlates_to_the_outer_row` is the same fact against an engine.
#[test]
fn a_self_relation_aliases_the_inner_scope() {
  let any = Derived::new(SCENE, PARENT_ID).with_any(Keyframe::new());

  assert_eq!(
    lowered(At::new(SCENE.address()), &any).unwrap(),
    "EXISTS (SELECT 1 FROM \"scene\" \"__ig_scene_1__\" \
     WHERE \"__ig_scene_1__\".\"parent_id\" = \"scene\".\"id\")"
  );
}

/// **Two levels of one table take two different aliases**, and the inner correlation names the
/// OUTER one — which is what a single alias, or an alternating pair, would get wrong at the third
/// level while passing every one-level test.
///
/// The forward kind is the outer hop and the reverse kind the inner, so this also pins that the two
/// kinds agree about what depth they are at.
#[test]
fn two_levels_of_one_table_take_two_aliases() {
  let inner = Derived::new(SCENE, PARENT_ID).with_any(Keyframe::new());
  let outer = SqlRefComparison::<_, sqlx::Sqlite>::new(SCENE, Nesting(inner));
  let frame = At::new(SCENE.address()).frame(PARENT_ID);

  assert_eq!(
    lowered(frame.at(), &outer).unwrap(),
    "\"parent_id\" IN ( SELECT \"__ig_scene_1__\".\"id\" FROM \"scene\" \"__ig_scene_1__\" \
     WHERE EXISTS (SELECT 1 FROM \"scene\" \"__ig_scene_2__\" \
     WHERE \"__ig_scene_2__\".\"parent_id\" = \"__ig_scene_1__\".\"id\") )"
  );
}

/// **Past the last minted alias the lowering REFUSES**, naming the row, the depth and the ceiling.
///
/// Reusing a name is the alternative, and it is the silent one: SQL resolves a reference to the
/// innermost scope that has a match, so a repeated alias correlates the wrong two rows and the
/// statement still answers. The fixture mints ONE alias so the ceiling is reached at the first hop
/// rather than the ninth.
#[test]
fn a_relation_deeper_than_its_aliases_is_refused() {
  let any = Derived::new(SHALLOW, PARENT_ID).with_any(Keyframe::new());

  assert_eq!(
    lowered(At::new(SHALLOW.address()), &any),
    Err(SqlLoweringError::RelationDepth(RelationDepthError::new(
      FieldName::new("scene"),
      1,
      1
    )))
  );

  // The FORWARD kind refuses on the same ground, and refuses before it writes: a ceiling reached is
  // a fact about the relation rather than about the predicate inside it.
  let forward = SqlRefComparison::<_, sqlx::Sqlite>::new(SHALLOW, Keyframe::new().with_title("x"));
  let frame = At::new(SHALLOW.address()).frame(PARENT_ID);
  assert_eq!(
    lowered(frame.at(), &forward),
    Err(SqlLoweringError::RelationDepth(RelationDepthError::new(
      FieldName::new("scene"),
      1,
      1
    )))
  );
}

/// **A row minted PAST the default depth renders past it**, and one minted at the default refuses
/// there — which is the whole of what makes eight a default rather than a wall.
///
/// The two fixtures differ in nothing but the length of their alias tables: ten names against the
/// eight `DEPTH_CEILING` mints for a declaration that named no depth. Nine hops over the first
/// renders, and the ninth scope wears the tenth name; nine hops over the second answers
/// `RelationDepth` at eight, saying eight — *the array's own length*, which is the sentence
/// `RelationDepthError` carries and the reason a deeper record needed no engine to be taught
/// anything.
///
/// The mutation this catches is a `scope` that compared against `DEPTH_CEILING` instead of
/// `aliases.len()`: the deep chain would refuse at nine with the constant in the message, and every
/// existing pin — all of them at or under eight — would still pass.
#[test]
fn the_depth_a_row_refuses_at_is_its_own() {
  let deep = hops(DEEP, 9);
  let rendered = lowered(At::new(DEEP.address()).frame(PARENT_ID).at(), &deep)
    .expect("ten names carry nine scopes");

  assert!(
    rendered.contains("\"deep\" \"__ig_deep_9__\""),
    "{rendered}"
  );
  assert!(
    rendered.contains("\"deep\" \"__ig_deep_1__\""),
    "{rendered}"
  );

  let defaulted = hops(DEFAULTED, 9);
  assert_eq!(
    lowered(
      At::new(DEFAULTED.address()).frame(PARENT_ID).at(),
      &defaulted
    ),
    Err(SqlLoweringError::RelationDepth(RelationDepthError::new(
      FieldName::new("scene"),
      8,
      8
    ))),
    "the default depth refuses at the default, by name",
  );
}

/// A self-reference nested `hops` deep, built OUTERMOST-LAST so the whole chain is one owned value.
///
/// Owned rather than assembled inside a lowering, because [`ComplexComparison::apply`] borrows the
/// nested predicate for the statement's lifetime — a hop built on the way down would be a temporary
/// the builder outlives.
fn hops(row: RelatedRow, hops: usize) -> Chain {
  let mut built = Chain::Leaf(Box::new(Keyframe::new().with_title("x")));
  for _ in 0..hops {
    built = Chain::Hop(Box::new(SqlRefComparison::new(row, built)));
  }
  built
}

/// One link of [`hops`]: a forward reference over the same row, or the leaf predicate under the
/// deepest of them.
///
/// Both variants are boxed. The hop must be — it holds a `Chain` — and the leaf follows it so the
/// enum is a pointer either way rather than as wide as a whole comparison at every link.
#[derive(Debug, Clone, PartialEq)]
enum Chain {
  /// The innermost predicate, over the target row's own columns.
  Leaf(Box<Keyframe>),
  /// One more forward hop over the same row, carrying everything below it.
  Hop(Box<SqlRefComparison<Chain, sqlx::Sqlite>>),
}

impl ComplexComparison<sqlx::Sqlite> for Chain {
  fn conjuncts(&self) -> usize {
    match self {
      Self::Leaf(leaf) => ComplexComparison::conjuncts(leaf.as_ref()),
      Self::Hop(hop) => ComplexComparison::conjuncts(hop.as_ref()),
    }
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: SqlConjunction<'q, sqlx::Sqlite>,
  ) -> Result<SqlConjunction<'q, sqlx::Sqlite>, SqlLoweringError> {
    match self {
      Self::Leaf(leaf) => leaf.apply(at, builder),
      Self::Hop(hop) => hop.apply(at, builder),
    }
  }
}

impl CollapsibleComparison<sqlx::Sqlite> for Chain {
  type Id = Scalar;

  /// Never, for [`Nesting`]'s reason: a relation inside a relation is not a constraint on the outer
  /// target's id, and answering `Some` would drop every link below this one.
  fn only_id(&self) -> Option<&Scalar> {
    None
  }
}

/// A comparison whose whole content is ONE nested relation, so a forward hop can carry a reverse one
/// and the depths compose.
///
/// It renders the nested predicate at the address it is handed and nothing else — which is what
/// makes the alias in the assertion above the ENGINE's rather than the fixture's.
#[derive(Debug, Clone, PartialEq)]
struct Nesting(Derived);

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

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: SqlConjunction<'q, sqlx::Sqlite>,
  ) -> Result<SqlConjunction<'q, sqlx::Sqlite>, SqlLoweringError> {
    self.0.apply(at, builder)
  }
}

impl CollapsibleComparison<sqlx::Sqlite> for Nesting {
  type Id = Scalar;

  /// Never — a relation inside a relation is not a constraint on the outer target's id, so the
  /// collapse must not swallow it. Answering `Some` here would drop the whole inner predicate.
  fn only_id(&self) -> Option<&Scalar> {
    None
  }
}

/// The reverse kind reads the ROW and not the column, so the same comparison renders identically at
/// the top level, at one frame and at two.
///
/// It is the opposite of the correlated COLLECTION kinds, which derive their edge table FROM the
/// path and refuse the empty one — and it is why a derived position, which is stored nowhere, needs
/// no column of its own to be applied at.
#[test]
fn a_derived_position_reads_the_row_and_leaves_the_path_unread() {
  let any = Derived::new(KEYFRAME, SHOT_ID).with_any(Keyframe::new().with_title("Autumn"));
  let outer = At::new(&SHOT).frame(FieldName::new("covers"));
  let inner = outer.at().frame(FieldName::new("deeper"));

  let top = lowered(At::new(&SHOT), &any).unwrap();
  assert_eq!(top, render("covers", &any).0);
  assert_eq!(top, lowered(inner.at(), &any).unwrap());
}

/// The nested predicate is applied at the TARGET's own top level, so its columns are the target's
/// and the parent's path does not reach them.
///
/// Extended by the parent's path instead, this would render `"cover_id_title"` — a column that does
/// not exist, which the engine refuses only after the whole statement is built.
#[test]
fn the_nested_predicate_is_addressed_at_the_targets_own_top_level() {
  let cover = Ref::new(KEYFRAME, Keyframe::new().with_id(10).unreferential());
  let outer = At::new(&SHOT).frame(FieldName::new("cover"));
  let inner = outer.at().frame(FieldName::new("id"));

  assert_eq!(
    render_at::<sqlx::Sqlite, _>(inner.at(), &cover),
    (
      "\"cover_id\" IN ( SELECT \"__ig_keyframe_1__\".\"id\" FROM \"keyframe\" \"__ig_keyframe_1__\" WHERE \"id\" = ? )".into(),
      1
    )
  );
}

/// The bind list is the half the rendered text cannot show: three `?` read the same whatever went
/// into them, so a walk that rendered its scopes in the right order while binding out of order would
/// satisfy every assertion above.
#[test]
fn the_quantifiers_bind_in_the_order_they_render() {
  let bound = core::cell::RefCell::new(Vec::new());
  let position = SqlDerivedComparison::<Probed<'_>, sqlx::Sqlite>::new(KEYFRAME, SHOT_ID)
    .with_any(Probed {
      value: 1,
      bound: &bound,
    })
    .with_all(Probed {
      value: 2,
      bound: &bound,
    })
    .with_none(Probed {
      value: 3,
      bound: &bound,
    });

  lowered(At::new(&SHOT), &position).unwrap();
  assert_eq!(*bound.borrow(), [1, 2, 3]);
}

/// A comparison whose one conjunct binds a RECORDED operand — the family's own probe, wrapped in the
/// smallest comparison that can hold one.
struct Probed<'a> {
  value: i64,
  bound: &'a core::cell::RefCell<Vec<i64>>,
}

impl ComplexComparison<sqlx::Sqlite> for Probed<'_> {
  fn conjuncts(&self) -> usize {
    1
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    mut builder: SqlConjunction<'q, sqlx::Sqlite>,
  ) -> Result<SqlConjunction<'q, sqlx::Sqlite>, SqlLoweringError> {
    use crate::{Carrier, comparison::sql::tests::Probe};

    let qb = builder.open();
    crate::comparison::sql::push_column(qb, at);
    qb.push(" = ");
    Probe {
      value: self.value,
      bound: self.bound,
    }
    .push_bind(qb);
    Ok(builder)
  }
}

/// The same predicates against a REAL engine, over a corpus whose answers are all different.
///
/// Every form above renders plausible SQL when it is wrong, which is the defect class this whole
/// layer keeps finding: the text reads correctly, the bind count matches, and the row set differs.
/// So the pins above are byte-exact and these are about the ANSWER — computed by hand from the
/// corpus, and each chosen so that a quantifier confused with its neighbour gives a different set.
mod live {
  use sqlx::{Connection as _, Executor as _, Row as _, sqlite::SqliteConnection};

  use super::{
    Derived, KEYFRAME, Keyframe, PARENT_ID, Ref, SCENE, SHOT, SHOT_ID, SqlRefComparison,
  };
  use crate::{
    At, FieldName, ScalarFilter,
    comparison::{
      ComplexComparison, TryFromFilter,
      sql::{QueryBuilder, SelectClause, SqlConjunction, SqlCountComparison, quote_ident},
    },
  };

  /// Five shots over five keyframes, arranged so that no two quantifiers admit the same rows.
  ///
  /// ```text
  /// shot  slate    cover → title    keyframes (title)          any    none   all    count>1
  ///  1    alpha     10   → Autumn    10 Autumn, 11 Meadow       yes     .      .      yes
  ///  2    bravo     11   → Meadow    12 Zebra                    .     yes     .       .
  ///  3    delta    NULL  → NULL      (none)                      .     yes    yes      .
  ///  4    echo      12   → Zebra     13 Autumn                  yes     .     yes      .
  ///  5    foxtrot  NULL  → NULL      14 Autumn, 15 NULL         yes     .     yes     yes
  /// ```
  ///
  /// Shot 3 is the VACUOUS case — no children, so `all` holds and `any` does not. Shot 5 is the
  /// third-truth-value case: its `NULL` title is neither a match nor a counterexample, so it passes
  /// `all` while failing `any` on its own.
  async fn corpus() -> SqliteConnection {
    let mut db = SqliteConnection::connect("sqlite::memory:")
      .await
      .expect("an in-memory database");
    for ddl in [
      r#"CREATE TABLE "shot" ("id" INTEGER PRIMARY KEY, "slate" TEXT NOT NULL,
         "cover_id" INTEGER)"#,
      r#"CREATE TABLE "keyframe" ("id" INTEGER PRIMARY KEY, "title" TEXT, "shot_id" INTEGER)"#,
    ] {
      db.execute(ddl).await.expect("a table");
    }
    for (id, slate, cover) in [
      (1i64, "alpha", Some(10i64)),
      (2, "bravo", Some(11)),
      (3, "delta", None),
      (4, "echo", Some(12)),
      (5, "foxtrot", None),
    ] {
      sqlx::query(r#"INSERT INTO "shot" VALUES (?, ?, ?)"#)
        .bind(id)
        .bind(slate)
        .bind(cover)
        .execute(&mut db)
        .await
        .expect("a shot");
    }
    for (id, title, shot) in [
      (10i64, Some("Autumn"), 1i64),
      (11, Some("Meadow"), 1),
      (12, Some("Zebra"), 2),
      (13, Some("Autumn"), 4),
      (14, Some("Autumn"), 5),
      (15, None, 5),
    ] {
      sqlx::query(r#"INSERT INTO "keyframe" VALUES (?, ?, ?)"#)
        .bind(id)
        .bind(title)
        .bind(shot)
        .execute(&mut db)
        .await
        .expect("a keyframe");
    }
    db
  }

  /// The shots this predicate admits, in id order — the whole statement built the way a caller
  /// builds one, so the accumulator's clause keyword is under test beside the predicate.
  async fn shots(
    db: &mut SqliteConnection,
    at: At<'_>,
    comparison: &impl ComplexComparison<sqlx::Sqlite>,
  ) -> Vec<i64> {
    let mut statement = QueryBuilder::<SelectClause, sqlx::Sqlite>::select()
      .push_field("\"id\"")
      .from("\"shot\"")
      .begin_where();
    {
      let accumulator = SqlConjunction::new(statement.inner_mut());
      comparison
        .apply(at, accumulator)
        .expect("a rendered predicate");
    }
    let mut built = statement.order_by(FieldName::new("id"), false).finalize();
    built
      .build()
      .fetch_all(db)
      .await
      .expect("the engine answers")
      .iter()
      .map(|row| row.get::<i64, _>(0))
      .collect()
  }

  /// **A SELF-RELATION correlates to the OUTER row**, live — the defect the aliasing closes, pinned
  /// against a real engine because the wrong version answered without complaining.
  ///
  /// ```text
  /// scene  title    parent   children (title)
  ///   1    root      —        2 Autumn
  ///   2    Autumn    1        —
  ///   3    other     1        4 Autumn
  ///   4    Autumn    3        —
  /// ```
  ///
  /// *The scenes with an `Autumn` child* is `[1, 3]`. Before the alias the correlation rendered
  /// `"scene"."parent_id" = "scene"."id"` — both halves resolving to the INNER scope, since SQL
  /// resolves an unqualified-by-scope reference to the innermost match — so the predicate asked
  /// whether any scene is its own parent and admitted `[]`. Measured: it parsed, it bound, it ran.
  ///
  /// The corpus is chosen so that the broken reading and the right one differ: no scene here IS its
  /// own parent, so the old form answers the empty set rather than something that happens to
  /// overlap.
  #[tokio::test]
  async fn a_self_relation_correlates_to_the_outer_row() {
    let mut db = scenes().await;

    let children = Derived::new(SCENE, PARENT_ID).with_any(Keyframe::new().with_title("Autumn"));
    assert_eq!(
      rows(&mut db, At::new(SCENE.address()), &children).await,
      [1, 3]
    );

    // The neighbouring quantifiers are answered by the same corpus, and no two agree — which is what
    // keeps this from passing under a correlation that is merely differently wrong.
    let none = Derived::new(SCENE, PARENT_ID).with_none(Keyframe::new().with_title("Autumn"));
    assert_eq!(rows(&mut db, At::new(SCENE.address()), &none).await, [2, 4]);

    let childless = Derived::new(SCENE, PARENT_ID).with_any(Keyframe::new());
    assert_eq!(
      rows(&mut db, At::new(SCENE.address()), &childless).await,
      [1, 3]
    );
  }

  /// **Two levels of one table answer through two aliases**, live.
  ///
  /// *The scenes whose PARENT has an `Autumn` child*: scenes 2 and 3 hang off scene 1, whose
  /// children are `Autumn` and `other`; scene 4 hangs off scene 3, whose one child is `Autumn`. So
  /// `[2, 3, 4]`, and scene 1 is excluded by having no parent at all rather than by the predicate.
  ///
  /// It is the assertion a single alias cannot pass: the inner correlation names the OUTER hop's
  /// row, so with one name in play the inner scope would shadow it and the question would collapse
  /// into the level above — which on this corpus is a different set.
  #[tokio::test]
  async fn two_levels_of_one_table_answer_through_two_aliases() {
    let mut db = scenes().await;

    let inner = Derived::new(SCENE, PARENT_ID).with_any(Keyframe::new().with_title("Autumn"));
    let through = SqlRefComparison::<_, sqlx::Sqlite>::new(SCENE, super::Nesting(inner));
    let frame = At::new(SCENE.address()).frame(PARENT_ID);

    assert_eq!(rows(&mut db, frame.at(), &through).await, [2, 3, 4]);

    // The one-level question over the same corpus is a DIFFERENT set, which is what makes the two
    // levels legible as two: this one is *scenes that have an `Autumn` child*.
    let one_level = Derived::new(SCENE, PARENT_ID).with_any(Keyframe::new().with_title("Autumn"));
    assert_eq!(
      rows(&mut db, At::new(SCENE.address()), &one_level).await,
      [1, 3]
    );
  }

  /// A `scene` whose `parent_id` names a `scene` — the shape whose correlation used to compare a
  /// column to itself.
  async fn scenes() -> SqliteConnection {
    let mut db = SqliteConnection::connect("sqlite::memory:")
      .await
      .expect("an in-memory database");
    db.execute(
      r#"CREATE TABLE "scene" ("id" INTEGER PRIMARY KEY, "title" TEXT, "parent_id" INTEGER)"#,
    )
    .await
    .expect("a table");
    for (id, title, parent) in [
      (1i64, "root", None::<i64>),
      (2, "Autumn", Some(1)),
      (3, "other", Some(1)),
      (4, "Autumn", Some(3)),
    ] {
      sqlx::query(r#"INSERT INTO "scene" VALUES (?, ?, ?)"#)
        .bind(id)
        .bind(title)
        .bind(parent)
        .execute(&mut db)
        .await
        .expect("a scene");
    }
    db
  }

  /// [`shots`] over any table: the ids this predicate admits, in id order.
  async fn rows(
    db: &mut SqliteConnection,
    at: At<'_>,
    comparison: &impl ComplexComparison<sqlx::Sqlite>,
  ) -> Vec<i64> {
    let table = quote_ident::<sqlx::Sqlite>(at.record().table());
    let mut statement = QueryBuilder::<SelectClause, sqlx::Sqlite>::select()
      .push_field("\"id\"")
      .from(table.as_str())
      .begin_where();
    {
      let accumulator = SqlConjunction::new(statement.inner_mut());
      comparison
        .apply(at, accumulator)
        .expect("a rendered predicate");
    }
    let mut built = statement.order_by(FieldName::new("id"), false).finalize();
    built
      .build()
      .fetch_all(db)
      .await
      .expect("the engine answers")
      .iter()
      .map(|row| row.get::<i64, _>(0))
      .collect()
  }

  /// The forward semi-join admits the shots whose COVER matches — not the shots that have a
  /// matching keyframe, which is the neighbouring question and a different set.
  #[tokio::test]
  async fn the_semi_join_answers_about_the_referenced_row() {
    let mut db = corpus().await;
    let cover = Ref::new(KEYFRAME, Keyframe::new().with_title("Autumn"));
    let frame = At::new(&SHOT).frame(FieldName::new("cover_id"));

    assert_eq!(shots(&mut db, frame.at(), &cover).await, [1]);

    // The reverse position over the same predicate is the other question, and answers three rows.
    let any = Derived::new(KEYFRAME, SHOT_ID).with_any(Keyframe::new().with_title("Autumn"));
    assert_eq!(shots(&mut db, At::new(&SHOT), &any).await, [1, 4, 5]);
  }

  /// **The collapse and the subquery admit the SAME rows**, which is the whole claim the
  /// optimisation makes — and the one a rendering test cannot check.
  #[tokio::test]
  async fn the_collapsed_form_answers_exactly_as_its_subquery_would() {
    let mut db = corpus().await;
    let frame = At::new(&SHOT).frame(FieldName::new("cover_id"));

    let collapsing = Ref::new(KEYFRAME, Keyframe::new().with_id(11));
    let declining = Ref::new(KEYFRAME, Keyframe::new().with_id(11).unreferential());

    let collapsed = shots(&mut db, frame.at(), &collapsing).await;
    assert_eq!(collapsed, [2]);
    assert_eq!(collapsed, shots(&mut db, frame.at(), &declining).await);
  }

  /// Each quantifier admits its own set, and no two of them agree on this corpus.
  #[tokio::test]
  async fn every_quantifier_answers_its_own_question() {
    let mut db = corpus().await;
    let top = At::new(&SHOT);
    let autumn = || Keyframe::new().with_title("Autumn");

    let any = Derived::new(KEYFRAME, SHOT_ID).with_any(autumn());
    let all = Derived::new(KEYFRAME, SHOT_ID).with_all(autumn());
    let none = Derived::new(KEYFRAME, SHOT_ID).with_none(autumn());
    let count = Derived::new(KEYFRAME, SHOT_ID).with_count(
      SqlCountComparison::try_from_filter(ScalarFilter::<usize>::new().with_gt(1)).unwrap(),
    );

    assert_eq!(shots(&mut db, top, &any).await, [1, 4, 5]);
    assert_eq!(shots(&mut db, top, &all).await, [3, 4, 5]);
    assert_eq!(shots(&mut db, top, &none).await, [2, 3]);
    assert_eq!(shots(&mut db, top, &count).await, [1, 5]);
  }

  /// **`all` over a row with NO children is TRUE**, and `any` over the same row is false — the
  /// decision, live.
  ///
  /// Shot 3 is the row: it has no keyframes at all, so there is no counterexample for `NOT EXISTS`
  /// to find and no witness for `EXISTS`. A reading of `all` as *some child, and every one of them*
  /// would have excluded it, which is the one mutation the two assertions together catch.
  #[tokio::test]
  async fn all_over_a_row_with_no_children_is_vacuously_true() {
    let mut db = corpus().await;
    let top = At::new(&SHOT);

    let all = Derived::new(KEYFRAME, SHOT_ID).with_all(Keyframe::new().with_title("Autumn"));
    let any = Derived::new(KEYFRAME, SHOT_ID).with_any(Keyframe::new().with_title("Autumn"));
    assert!(shots(&mut db, top, &all).await.contains(&3));
    assert!(!shots(&mut db, top, &any).await.contains(&3));

    // The empty predicate is the same reading one step further: EVERY row passes, childless or not.
    let vacuous = Derived::new(KEYFRAME, SHOT_ID).with_all(Keyframe::new());
    assert_eq!(shots(&mut db, top, &vacuous).await, [1, 2, 3, 4, 5]);

    // And its neighbours are not vacuous — `any` with no predicate is *this row has a child*.
    let has_one = Derived::new(KEYFRAME, SHOT_ID).with_any(Keyframe::new());
    assert_eq!(shots(&mut db, top, &has_one).await, [1, 2, 4, 5]);
  }
}