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
#[cfg(feature = "sqlite")]
mod sqlite {
  use core::convert::Infallible;

  use crate::{
    At, FieldName, ListFilter, QuantifiedFilter, RecordAddress, SetFilter, TextFilter,
    comparison::{
      TryFromFilter,
      sql::{
        SqlEdgeComparison, SqlEdgeSetComparison, SqlLoweringError, SqlScalarComparison,
        SqlTextComparison,
        tests::{ROW, render, render_at, threaded},
      },
    },
  };

  /// The element comparison an `i64` member crosses into — supplied at each of this module's
  /// spellings, because these tests assert the collection's own operators rather than the element's.
  type Element<V> = SqlScalarComparison<V, sqlx::Sqlite>;
  type Edge = SqlEdgeComparison<i64, Element<i64>, sqlx::Sqlite>;
  type EdgeSet = SqlEdgeSetComparison<i64, Element<i64>, sqlx::Sqlite>;
  /// A `String` member is read as TEXT, so the one crossing here whose domain is `String` names the
  /// text comparison for its element rather than the scalar one.
  type TextEdgeSet = SqlEdgeSetComparison<i64, SqlTextComparison<i64, sqlx::Sqlite>, sqlx::Sqlite>;

  /// The correlated `EXISTS` every containment form is built from, spelled once here so the tests
  /// below read as the operator they are about.
  const SCOPE: &str = "SELECT 1 FROM \"p_tags\" WHERE \"p_tags\".\"id\" = \"p\".\"id\"";

  /// A tag column stored as its element LENGTHS — a crossing that changes the value rather than only
  /// its type, so a pass-through mutation shows in the operand and not only in the SQL.
  fn length(tag: String) -> Result<i64, Infallible> {
    Ok(tag.len() as i64)
  }

  /// One converter, every slot.
  #[test]
  fn one_element_converter_serves_every_slot() {
    let filter = SetFilter::<String>::new()
      .with_encloses(["hdr".to_owned(), "sdr".to_owned()])
      .with_has_element("stereo".to_owned());

    let crossed = TextEdgeSet::try_from_filter_with(filter, length).unwrap();

    assert_eq!(crossed.encloses(), Some(&[3i64, 3][..]));
    assert_eq!(crossed.has_element(), Some(&6i64));
    assert_eq!(crossed.conjuncts(), 2);
  }

  /// **The one converter reaches the NESTED filter's operands too**, which is the whole of what
  /// filling both slots from one declaration means.
  ///
  /// The `any` slot holds a whole element FILTER, and its operands are made of the same elements the
  /// collection's own slots hold — so a converter that stopped at the top level would leave a
  /// question about `"hdr"` where the column stores `3`. The two assertions are the two levels, and
  /// the numbers differ so that a converter reaching one and not the other cannot pass.
  #[test]
  fn the_one_converter_reaches_the_nested_element_filter() {
    let filter = SetFilter::<String, TextFilter<String>>::new()
      .with_has_element("stereo".to_owned())
      .with_any(TextFilter::<String>::new().with_eq("hdr".to_owned()));

    let crossed = TextEdgeSet::try_from_filter_with(filter, length).unwrap();

    assert_eq!(crossed.has_element(), Some(&6i64));
    assert_eq!(
      crossed.any().expect("the element question").eq(),
      Some(&3i64),
      "the nested operand crossed through the same converter, one level down"
    );
  }

  /// **A column no other conversion can reach**, which is what makes a declared converter LOAD-
  /// BEARING rather than a convenience: `u64` and [`BeU64`](crate::BeU64) have no [`TryFrom`]
  /// between them — the storage form is a byte layout rather than a numeric widening — so this
  /// crossing exists through the declaration or not at all, at BOTH levels.
  ///
  /// A function rather than an assertion, because what is pinned is that it COMPILES. The day the
  /// nested filter stops going through the declared converter, this is `E0277` naming
  /// `BeU64: TryFrom<u64>` — the same refusal the interface corpus's scalar column already carries,
  /// one level down.
  fn _a_pinned_collection_crosses_through_the_declaration_at_both_levels(
    filter: ListFilter<u64, crate::ScalarFilter<u64>>,
  ) -> SqlEdgeComparison<crate::BeU64, SqlScalarComparison<crate::BeU64, sqlx::Sqlite>, sqlx::Sqlite>
  {
    fn store(mark: u64) -> Result<crate::BeU64, Infallible> {
      Ok(crate::BeU64(mark))
    }

    SqlEdgeComparison::try_from_filter_with(filter, store).expect("an infallible crossing")
  }

  /// **The correlation qualifies BOTH sides**, and this is the assertion the whole strategy rests
  /// on: the parent and the edge table carry the same key column names, and SQL resolves an
  /// unqualified name to the innermost scope — so an unqualified correlation would compare the edge
  /// table's key to itself, hold for every row of it, and turn every operator into a question about
  /// the WHOLE table rather than about this parent's collection. It renders, it binds the same
  /// operands, and it returns rows nobody asked for.
  #[test]
  fn the_correlation_names_the_parent_and_the_edge_table_apart() {
    let crossed = Edge::try_from_filter(ListFilter::<i64>::new().with_has_element(6i64)).unwrap();

    let (sql, _) = render::<sqlx::Sqlite, _>("tags", &crossed);
    assert!(
      sql.contains("\"p_tags\".\"id\" = \"p\".\"id\""),
      "both sides are qualified: {sql}"
    );
  }

  /// A compound key correlates on every column, in the order the row names them — and the same
  /// comparison the tests above apply against `p` is applied against this row instead, which is
  /// what "the address is not in the comparison" means at the value level.
  #[test]
  fn a_compound_key_correlates_on_every_column() {
    const SEGMENT: RecordAddress = RecordAddress::new(
      FieldName::new("segment"),
      &[FieldName::new("media_id"), FieldName::new("segment_id")],
    );

    let crossed = Edge::try_from_filter(ListFilter::<i64>::new().with_has_element(6i64)).unwrap();

    assert_eq!(
      render_at::<sqlx::Sqlite, _>(
        At::new(&SEGMENT).frame(FieldName::new("speakers")).at(),
        &crossed
      )
      .0,
      "EXISTS (SELECT 1 FROM \"segment_speakers\" WHERE \
       \"segment_speakers\".\"media_id\" = \"segment\".\"media_id\" AND \
       \"segment_speakers\".\"segment_id\" = \"segment\".\"segment_id\" AND \
       \"segment_speakers\".\"speakers\" = ?)"
    );
  }

  /// Membership IS containment of the singleton, so it renders the `encloses` form over a
  /// one-element operand rather than a form of its own — and it is the same form on both kinds,
  /// which is why the sequence answers it without reading its ordinal.
  #[test]
  fn membership_is_containment_of_the_singleton_on_both_kinds() {
    let member = EdgeSet::try_from_filter(SetFilter::<i64>::new().with_has_element(6i64)).unwrap();
    let singleton =
      EdgeSet::try_from_filter(SetFilter::<i64>::new().with_encloses([6i64])).unwrap();
    let sequence = Edge::try_from_filter(ListFilter::<i64>::new().with_has_element(6i64)).unwrap();

    assert_eq!(
      render::<sqlx::Sqlite, _>("tags", &member),
      render::<sqlx::Sqlite, _>("tags", &singleton)
    );
    assert_eq!(
      render::<sqlx::Sqlite, _>("tags", &sequence),
      render::<sqlx::Sqlite, _>("tags", &member)
    );
  }

  /// This strategy's element scope is a correlated DERIVED TABLE, and the projection is what makes
  /// the element's address an ordinary [`At`]: every other form here names the value column
  /// QUALIFIED, which an element comparison cannot render.
  ///
  /// Both kinds reach it, and both reach it on every dialect — there is no refusal here, where a
  /// MySQL `JSON` column has one. Measured on SQLite 3.51.0, PostgreSQL 14.23 and MySQL 8.4.11: each
  /// admits exactly the rows with a matching element, including where the PARENT carries its own
  /// `value` column.
  #[test]
  fn an_element_question_opens_a_correlated_derived_table() {
    let crossed = EdgeSet::try_from_filter(
      SetFilter::<i64>::new().with_any(crate::ScalarFilter::new().with_gt(2)),
    )
    .unwrap();

    assert_eq!(
      render::<sqlx::Sqlite, _>("tags", &crossed),
      (
        "EXISTS (SELECT 1 FROM ( SELECT \"p_tags\".\"tags\" AS \"value\" FROM \"p_tags\" WHERE \
         \"p_tags\".\"id\" = \"p\".\"id\" ) AS \"__ig_element_0__\" WHERE \"value\" > ?)"
          .to_owned(),
        1
      )
    );
    assert_eq!(crossed.conjuncts(), 1);
  }

  /// The cardinality is the correlated `COUNT(*)` this strategy already builds, so a `count`
  /// operator and the length half of a sequence ordering read the same number by construction.
  ///
  /// It needs no care about the empty collection: `COUNT(*)` over no matching rows is `0`, where a
  /// Postgres array's `array_length` would be `NULL`. Both kinds answer it, and the set kind takes
  /// the `i64: Carrier<Db>` bound for it — the sequence kind already had one for its ordinals.
  #[test]
  fn a_cardinality_is_the_correlated_count() {
    let set = EdgeSet::try_from_filter(
      SetFilter::<i64>::new().with_count(crate::ScalarFilter::new().with_eq(0)),
    )
    .unwrap();
    let sequence = Edge::try_from_filter(
      ListFilter::<i64>::new().with_count(crate::ScalarFilter::new().with_eq(0)),
    )
    .unwrap();

    let expected = (
      "(SELECT COUNT(*) FROM \"p_tags\" WHERE \"p_tags\".\"id\" = \"p\".\"id\") = ?".to_owned(),
      1,
    );
    assert_eq!(render::<sqlx::Sqlite, _>("tags", &set), expected);
    assert_eq!(render::<sqlx::Sqlite, _>("tags", &sequence), expected);
  }

  /// **THE NARROW KIND REACHES THE EDGE TABLE**, which is the strategy the two JSON dialects keep
  /// every collection in — so this is the crossing a quantified column actually takes on SQLite, and
  /// what it renders is what the wide filter renders with its other seven slots unset.
  ///
  /// The equality between the two crossings is the claim; the SQL beside it is what they render, so
  /// the pair says both. A second implementation of the two arms could pass the second assertion and
  /// not the first.
  #[test]
  fn a_quantified_crossing_reaches_the_edge_table_through_the_wide_kinds_arms() {
    let narrow = Edge::try_from_filter(
      QuantifiedFilter::<i64>::new()
        .with_any(crate::ScalarFilter::new().with_gt(2))
        .with_count(crate::ScalarFilter::new().with_eq(0)),
    )
    .unwrap();
    let wide = Edge::try_from_filter(
      ListFilter::<i64>::new()
        .with_any(crate::ScalarFilter::new().with_gt(2))
        .with_count(crate::ScalarFilter::new().with_eq(0)),
    )
    .unwrap();

    assert_eq!(narrow, wide);
    assert_eq!(narrow.conjuncts(), wide.conjuncts());
    assert_eq!(
      render::<sqlx::Sqlite, _>("tags", &narrow),
      render::<sqlx::Sqlite, _>("tags", &wide)
    );
    assert_eq!(
      render::<sqlx::Sqlite, _>("tags", &narrow),
      (
        "EXISTS (SELECT 1 FROM ( SELECT \"p_tags\".\"tags\" AS \"value\" FROM \"p_tags\" WHERE \
         \"p_tags\".\"id\" = \"p\".\"id\" ) AS \"__ig_element_0__\" WHERE \"value\" > ?) AND \
         (SELECT COUNT(*) FROM \"p_tags\" WHERE \"p_tags\".\"id\" = \"p\".\"id\") = ?"
          .to_owned(),
        2
      )
    );
  }

  /// The two nested slots answer the empty case oppositely, and the reason is the quantifier: an
  /// element scope with no predicate asks whether the collection HAS an element, while a cardinality
  /// with no operator asks nothing at all.
  #[test]
  fn an_empty_element_scope_is_a_predicate_and_an_empty_cardinality_is_not() {
    let any =
      EdgeSet::try_from_filter(SetFilter::<i64>::new().with_any(crate::ScalarFilter::new()))
        .unwrap();
    let count =
      EdgeSet::try_from_filter(SetFilter::<i64>::new().with_count(crate::ScalarFilter::new()))
        .unwrap();

    assert_eq!(
      render::<sqlx::Sqlite, _>("tags", &any),
      (
        "EXISTS (SELECT 1 FROM ( SELECT \"p_tags\".\"tags\" AS \"value\" FROM \"p_tags\" WHERE \
         \"p_tags\".\"id\" = \"p\".\"id\" ) AS \"__ig_element_0__\")"
          .to_owned(),
        0
      )
    );
    assert!(!any.is_empty());

    assert_eq!(
      render::<sqlx::Sqlite, _>("tags", &count),
      (String::new(), 0)
    );
    assert!(count.is_empty());
  }

  /// Every sequence operator, in the order the filter declares them — including the four an edge
  /// table makes answerable for the first time on this dialect.
  #[test]
  fn every_sequence_operator_renders_its_own_conjunct() {
    let filter = ListFilter::<i64>::new()
      .with_eq([1i64])
      .with_ne([2i64])
      .with_gt([3i64])
      .with_gte([4i64])
      .with_lt([5i64])
      .with_lte([6i64])
      .with_has_element(7i64);
    let crossed = Edge::try_from_filter(filter).unwrap();

    assert_eq!(crossed.conjuncts(), 7);
    let (sql, binds) = render::<sqlx::Sqlite, _>("tags", &crossed);
    // `eq` and `ne` bind an (ordinal, value) pair and a length each; the four orderings do the same;
    // `has_element` binds one element.
    assert_eq!(binds, 19);
    assert!(sql.contains("COALESCE("), "{sql}");
    assert!(sql.contains("\"p_tags\".\"tags_ordinal\""), "{sql}");
    assert!(sql.contains("NOT ( ( NOT EXISTS ("), "the `ne` wrap: {sql}");
  }

  /// Every set operator, likewise — and none of them names an ordinal.
  #[test]
  fn every_set_operator_renders_its_own_conjunct() {
    let filter = SetFilter::<i64>::new()
      .with_eq([1i64])
      .with_ne([2i64])
      .with_encloses([3i64])
      .with_enclosed_by([4i64])
      .with_overlaps([5i64])
      .with_has_element(6i64);
    let crossed = EdgeSet::try_from_filter(filter).unwrap();

    assert_eq!(crossed.conjuncts(), 6);
    let (sql, binds) = render::<sqlx::Sqlite, _>("tags", &crossed);
    // `eq` and `ne` bind their operand once per containment direction; the other four bind one
    // element apiece.
    assert_eq!(binds, 8);
    assert!(!sql.contains("ordinal"), "{sql}");
  }

  /// The four set operators, each on its own, so the shape of the SQL is readable rather than
  /// inferred from one long conjunction.
  #[test]
  fn the_set_operators_render_indexed_existence_tests() {
    for (filter, expected) in [
      (
        SetFilter::<i64>::new().with_encloses([7i64]),
        format!("EXISTS ({SCOPE} AND \"p_tags\".\"tags\" = ?)"),
      ),
      (
        SetFilter::<i64>::new().with_encloses([7i64, 8]),
        format!(
          "( EXISTS ({SCOPE} AND \"p_tags\".\"tags\" = ?) AND \
           EXISTS ({SCOPE} AND \"p_tags\".\"tags\" = ?) )"
        ),
      ),
      (
        SetFilter::<i64>::new().with_enclosed_by([8i64]),
        format!("NOT EXISTS ({SCOPE} AND \"p_tags\".\"tags\" NOT IN (?))"),
      ),
      (
        SetFilter::<i64>::new().with_overlaps([9i64, 10]),
        format!("EXISTS ({SCOPE} AND \"p_tags\".\"tags\" IN (?, ?))"),
      ),
    ] {
      let crossed = EdgeSet::try_from_filter(filter).unwrap();
      assert_eq!(render::<sqlx::Sqlite, _>("tags", &crossed).0, expected);
    }
  }

  /// The KIND decides what equality MEANS, and under an edge table it decides which COLUMNS the
  /// question reads: a sequence compares position by position and reads the ordinal, a set compares
  /// as sets and never names it.
  #[test]
  fn the_kind_splits_equality_and_only_the_sequence_reads_the_ordinal() {
    let sequence = Edge::try_from_filter(ListFilter::<i64>::new().with_eq([1i64, 2])).unwrap();
    let set = EdgeSet::try_from_filter(SetFilter::<i64>::new().with_eq([1i64, 2])).unwrap();

    assert_eq!(
      render::<sqlx::Sqlite, _>("tags", &sequence).0,
      format!(
        "( NOT EXISTS ({SCOPE} AND (\"p_tags\".\"tags_ordinal\", \"p_tags\".\"tags\") \
         NOT IN ((?, ?), (?, ?))) AND (SELECT COUNT(*) FROM \"p_tags\" WHERE \
         \"p_tags\".\"id\" = \"p\".\"id\") = ? )"
      )
    );
    assert_eq!(
      render::<sqlx::Sqlite, _>("tags", &set).0,
      format!(
        "( ( EXISTS ({SCOPE} AND \"p_tags\".\"tags\" = ?) AND \
         EXISTS ({SCOPE} AND \"p_tags\".\"tags\" = ?) ) AND \
         NOT EXISTS ({SCOPE} AND \"p_tags\".\"tags\" NOT IN (?, ?)) )"
      )
    );
  }

  /// No set rendering names the ordinal column, on ANY operator the kind can carry — which is the
  /// storage half of the split: a set's edge table has no such column, so a lowering that named it
  /// would be SQL against a schema nobody emitted. The type is what makes that unwritable: the set
  /// path builds a `Scope`, which has no ordinal to hand out.
  #[test]
  fn no_set_rendering_names_the_ordinal_column() {
    let filter = SetFilter::<i64>::new()
      .with_eq([1i64])
      .with_ne([2i64])
      .with_encloses([3i64])
      .with_enclosed_by([4i64])
      .with_overlaps([5i64])
      .with_has_element(6i64);
    let crossed = EdgeSet::try_from_filter(filter).unwrap();

    let (sql, _) = render::<sqlx::Sqlite, _>("tags", &crossed);
    assert!(!sql.contains("ordinal"), "{sql}");
  }

  /// The ordering family, which on this dialect had no answer at all before an ordinal column
  /// existed: the first differing position decides it, and equal-on-the-overlap falls through to
  /// the lengths.
  #[test]
  fn an_ordering_reads_the_first_differing_ordinal_then_the_lengths() {
    let crossed = Edge::try_from_filter(ListFilter::<i64>::new().with_gte([3i64, 4])).unwrap();

    assert_eq!(
      render::<sqlx::Sqlite, _>("tags", &crossed).0,
      "COALESCE((SELECT \"p_tags\".\"tags\" > \"__ig_operand_0__\".\"value\" FROM \"p_tags\" JOIN \
       ( SELECT ? AS \"ordinal\", ? AS \"value\" UNION ALL SELECT ?, ? ) AS \"__ig_operand_0__\" \
       ON \"__ig_operand_0__\".\"ordinal\" = \"p_tags\".\"tags_ordinal\" \
       WHERE \"p_tags\".\"id\" = \"p\".\"id\" AND \"p_tags\".\"tags\" <> \"__ig_operand_0__\".\"value\" \
       ORDER BY \"p_tags\".\"tags_ordinal\" LIMIT 1), \
       (SELECT COUNT(*) FROM \"p_tags\" WHERE \"p_tags\".\"id\" = \"p\".\"id\") >= ?)"
    );

    // The strictness reaches the LENGTH test and nothing else — a position where the two differ
    // decides the comparison outright, so `gt` and `gte` ask the same question there.
    let strict = Edge::try_from_filter(ListFilter::<i64>::new().with_gt([3i64, 4])).unwrap();
    let (strict, _) = render::<sqlx::Sqlite, _>("tags", &strict);
    let (loose, _) = render::<sqlx::Sqlite, _>("tags", &crossed);
    assert_eq!(strict.replace(") > ?)", ") >= ?)"), loose);
  }

  /// An empty operand is an OPERAND, not an absence, and each operator degenerates to what it means
  /// against the empty collection.
  #[test]
  fn an_empty_operand_degenerates_per_operator() {
    for (filter, expected) in [
      (
        ListFilter::<i64>::new().with_eq([]),
        format!("NOT EXISTS ({SCOPE})"),
      ),
      (
        ListFilter::<i64>::new().with_gt([]),
        format!("EXISTS ({SCOPE})"),
      ),
      (ListFilter::<i64>::new().with_gte([]), "1 = 1".to_owned()),
      (ListFilter::<i64>::new().with_lt([]), "1 = 0".to_owned()),
      (
        ListFilter::<i64>::new().with_lte([]),
        format!("NOT EXISTS ({SCOPE})"),
      ),
    ] {
      let crossed = Edge::try_from_filter(filter).unwrap();
      assert_eq!(render::<sqlx::Sqlite, _>("tags", &crossed).0, expected);
    }

    for (filter, expected) in [
      (
        // Every collection encloses the empty one.
        SetFilter::<i64>::new().with_encloses([]),
        "1 = 1".to_owned(),
      ),
      (
        // None overlaps it.
        SetFilter::<i64>::new().with_overlaps([]),
        "1 = 0".to_owned(),
      ),
      (
        // Only the empty collection is enclosed by it.
        SetFilter::<i64>::new().with_enclosed_by([]),
        format!("NOT EXISTS ({SCOPE})"),
      ),
      (
        // …and only the empty collection equals it, which is the one predicate the two kinds share.
        SetFilter::<i64>::new().with_eq([]),
        format!("NOT EXISTS ({SCOPE})"),
      ),
    ] {
      let crossed = EdgeSet::try_from_filter(filter).unwrap();
      assert_eq!(render::<sqlx::Sqlite, _>("tags", &crossed).0, expected);
    }
  }

  /// **The bind count DOES follow the operand's length here**, which is the trade this strategy
  /// makes against the column-stored kinds' one-bind operand — and it is the arithmetic `push_in`
  /// has, so it takes no ceiling.
  #[test]
  fn the_bind_count_follows_the_operand_length() {
    for len in [0usize, 1, 3, 1000] {
      let operand: Vec<i64> = (0..len as i64).collect();
      let crossed =
        EdgeSet::try_from_filter(SetFilter::<i64>::new().with_encloses(operand)).unwrap();

      let (_, binds) = render::<sqlx::Sqlite, _>("tags", &crossed);
      assert_eq!(binds, len, "a {len}-element operand");
    }
  }

  /// The operands reach the bind list in the order the walk declares, and each one exactly once.
  ///
  /// A `?` says nothing about what went into it, so a walk that dropped, reordered or duplicated an
  /// operand would render text that still looks right. This is the party that was there.
  #[test]
  fn every_operand_is_bound_once_and_in_order() {
    use core::cell::RefCell;

    use crate::comparison::{
      ComplexComparison,
      sql::{SqlConjunction, tests::Probe},
    };

    let bound = RefCell::new(Vec::new());
    let crossed = SqlEdgeSetComparison::<
      Probe<'_>,
      SqlScalarComparison<Probe<'_>, sqlx::Sqlite>,
      sqlx::Sqlite,
    >::try_from_filter_with_element(
      SetFilter::<i64>::new()
        .with_encloses([7i64, 8])
        .with_overlaps([9i64])
        .with_has_element(10i64),
      |value| {
        Ok::<_, Infallible>(Probe {
          value,
          bound: &bound,
        })
      },
      // The element slot is unset here, so this crossing never runs; it is still the argument that
      // says WHICH comparison one member would be asked.
      |any: crate::ScalarFilter<i64>| {
        SqlScalarComparison::try_from_filter(any.try_map(|value| {
          Ok::<_, Infallible>(Probe {
            value,
            bound: &bound,
          })
        })?)
      },
    )
    .unwrap();

    let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
    {
      let out = SqlConjunction::with_lead(&mut qb, "");
      let frame = At::new(&ROW).frame(FieldName::new("tags"));
      crossed.apply(frame.at(), out).unwrap();
    }
    assert_eq!(*bound.borrow(), [7, 8, 9, 10]);
  }

  /// The threaded lowering — the accumulator's lead, and a predicate that nests a whole subquery
  /// inside one conjunct.
  #[test]
  fn the_threaded_lowering_opens_one_clause() {
    let crossed = EdgeSet::try_from_filter(
      SetFilter::<i64>::new()
        .with_encloses([3i64])
        .with_overlaps([5i64]),
    )
    .unwrap();

    assert_eq!(
      threaded::<sqlx::Sqlite, _>("tags", &crossed),
      format!(
        "SELECT \"id\" FROM \"t\" WHERE EXISTS ({SCOPE} AND \"p_tags\".\"tags\" = ?) AND \
         EXISTS ({SCOPE} AND \"p_tags\".\"tags\" IN (?))"
      )
    );
  }

  /// **The crossing takes a filter and nothing else**, which is the whole point of this kind's
  /// redesign: a generated comparison composes its fields' crossings, so a collection field that
  /// could not cross refused the entire entity rather than only itself.
  ///
  /// Reached through the TRAIT — fully qualified, so an inherent method of the same name could not
  /// stand in for it. That is the half a call on the type alone would not pin.
  #[test]
  fn a_filter_alone_crosses_into_an_edge_comparison() {
    let crossed = <Edge as TryFromFilter<ListFilter<i64>>>::try_from_filter(
      ListFilter::<i64>::new().with_has_element(6i64),
    )
    .unwrap();

    assert_eq!(crossed.has_element(), Some(&6i64));
    assert_eq!(
      render::<sqlx::Sqlite, _>("tags", &crossed).0,
      format!("EXISTS ({SCOPE} AND \"p_tags\".\"tags\" = ?)")
    );
  }

  /// …and it is applied against a row the CALLER names, so one comparison answers the same question
  /// of two different rows.
  ///
  /// This is what replaces the property the old shape had. The address was held in the comparison,
  /// so it was fixed at construction; now it is not in the comparison at all, and the two renderings
  /// below differ in every name a correlation uses while the operand and the operator stay put.
  #[test]
  fn one_comparison_is_applied_against_whatever_row_the_caller_names() {
    const SEGMENT: RecordAddress =
      RecordAddress::new(FieldName::new("segment"), &[FieldName::new("media_id")]);

    let crossed = Edge::try_from_filter(ListFilter::<i64>::new().with_has_element(6i64)).unwrap();

    assert_eq!(
      render::<sqlx::Sqlite, _>("tags", &crossed).0,
      format!("EXISTS ({SCOPE} AND \"p_tags\".\"tags\" = ?)")
    );
    assert_eq!(
      render_at::<sqlx::Sqlite, _>(
        At::new(&SEGMENT).frame(FieldName::new("tags")).at(),
        &crossed
      )
      .0,
      "EXISTS (SELECT 1 FROM \"segment_tags\" WHERE \
       \"segment_tags\".\"media_id\" = \"segment\".\"media_id\" AND \
       \"segment_tags\".\"tags\" = ?)"
    );
  }

  /// The edge table is the ROW's table extended by the column's path — `edge_table`'s own join,
  /// which is not the column renderer's — so two collection columns of one row are two tables and
  /// the ordinal column of each is its own.
  #[test]
  fn the_edge_table_is_the_rows_table_extended_by_the_field() {
    let crossed = Edge::try_from_filter(ListFilter::<i64>::new().with_eq([1i64])).unwrap();

    let (tags, _) = render::<sqlx::Sqlite, _>("tags", &crossed);
    let (speakers, _) = render::<sqlx::Sqlite, _>("speakers", &crossed);

    assert!(tags.contains("FROM \"p_tags\""), "{tags}");
    assert!(tags.contains("\"p_tags\".\"tags_ordinal\""), "{tags}");
    assert!(speakers.contains("FROM \"p_speakers\""), "{speakers}");
    assert!(
      speakers.contains("\"p_speakers\".\"speakers_ordinal\""),
      "{speakers}"
    );
  }

  /// **The well-formed always-false predicate is gone.** An edge table holds a FIELD's elements, so
  /// at the top level — which names none — the join would hand back the row's own table and the
  /// forms below would correlate the row to itself.
  ///
  /// The value column is what made the other forms safe: the top level names none, the backend
  /// writes nothing for it, and the predicate around it does not parse. The forms listed here touch
  /// no value column, so nothing stopped them — `NOT EXISTS (SELECT 1 FROM "p" WHERE "p"."id" =
  /// "p"."id")` parses and is false for every row, and its `EXISTS` twin is true for every row.
  ///
  /// So the assertion is on the SQL as well as on the refusal: an `Err` alone would still hold if
  /// the walk had run and written the predicate first.
  #[test]
  fn an_edge_comparison_at_the_top_level_is_refused_rather_than_correlating_the_row_to_itself() {
    use crate::comparison::{ComplexComparison, sql::SqlConjunction};

    /// The self-correlation the top level rendered — with `NOT` in front of it for some of the
    /// operands below and bare for the others.
    const SELF_CORRELATION: &str = "EXISTS (SELECT 1 FROM \"p\" WHERE \"p\".\"id\" = \"p\".\"id\")";

    fn refuse_at_the_top_level<C: ComplexComparison<sqlx::Sqlite>>(comparison: &C) {
      let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
      // The REFUSAL is read last, so a lowering that renders and then returns `Ok` fails on what it
      // wrote rather than on the type of what it returned.
      let refused = {
        let out = SqlConjunction::with_lead(&mut qb, "");
        comparison.apply(At::new(&ROW), out).err()
      };
      let sql = qb.sql();
      let sql = sql.as_str();

      assert!(
        !sql.contains(SELF_CORRELATION),
        "the top level rendered: {sql}"
      );
      assert_eq!(sql, "");
      assert_eq!(
        refused,
        Some(SqlLoweringError::EdgeWithoutField(FieldName::new("p")))
      );
    }

    for filter in [
      ListFilter::<i64>::new().with_eq([]),
      ListFilter::<i64>::new().with_ne([]),
      ListFilter::<i64>::new().with_gt([]),
      ListFilter::<i64>::new().with_lte([]),
    ] {
      refuse_at_the_top_level(&Edge::try_from_filter(filter).unwrap());
    }

    for filter in [
      SetFilter::<i64>::new().with_eq([]),
      SetFilter::<i64>::new().with_ne([]),
      SetFilter::<i64>::new().with_enclosed_by([]),
    ] {
      refuse_at_the_top_level(&EdgeSet::try_from_filter(filter).unwrap());
    }

    // The address is refused whatever the comparison holds — including one holding nothing, which
    // renders no predicate anywhere. A refusal that waited for a slot to be set would be back to
    // depending on the operand, which is the shape that let this through in the first place.
    refuse_at_the_top_level(&Edge::new());
    refuse_at_the_top_level(&EdgeSet::new());
  }

  /// An edge table is the row's table extended by a FIELD's path, so it is never the row's own —
  /// which is the naming half of the refusal above, at the operation that derives the name.
  #[test]
  fn an_edge_table_is_never_the_rows_own_table() {
    use crate::comparison::sql::edge_table;

    assert_eq!(
      edge_table(At::new(&ROW)),
      Err(SqlLoweringError::EdgeWithoutField(FieldName::new("p")))
    );
    assert_eq!(
      edge_table(At::new(&ROW).frame(FieldName::new("tags")).at()).unwrap(),
      "p_tags"
    );
  }

  /// The refusal names the ROW it was applied to, and its text says what that address was missing —
  /// which is what a caller reads when a refusal reaches a log rather than a match arm.
  #[test]
  fn the_refusal_names_the_row_it_was_applied_to() {
    assert_eq!(
      SqlLoweringError::EdgeWithoutField(FieldName::new("p")).to_string(),
      "the top level of `p` names no field, so it has no edge table to correlate to"
    );
  }

  /// A comparison with no operator set renders nothing, so a statement built around it has no
  /// clause — the property the accumulator holds for every kind.
  #[test]
  fn an_empty_comparison_renders_nothing() {
    let crossed = Edge::new();

    assert!(crossed.is_empty());
    assert_eq!(crossed.conjuncts(), 0);
    // The same value the derive on a generated where struct would reach for, now that the kind
    // holds no addressing it would have to invent.
    assert_eq!(crossed, Edge::default());
    assert_eq!(
      render::<sqlx::Sqlite, _>("tags", &crossed),
      (String::new(), 0)
    );
  }
}

/// **The one converter against a real engine**, because the difference between reaching one level
/// and reaching two is a ROW SET rather than a text: both readings render well-formed SQL, bind the
/// same number of parameters, and admit different clips.
///
/// The column stores TENTHS of a second where a client writes SECONDS, so the converter changes the
/// VALUE and not only its type — which is what makes an unconverted operand visible instead of
/// merely differently typed. `i64::try_from` is a conversion that also exists between the two, so
/// dropping the declaration compiles and answers, and answers WRONGLY: that is the mutation this
/// corpus is shaped to catch.
///
/// ```text
/// clip  slate    marks (stored tenths)   has_element 1s → 10   any ≥ 9s → 90
///  1    alpha    10, 90                        yes                 yes
///  2    bravo    10, 20                        yes                  .
///  3    delta    (none)                         .                   .
///  4    echo     400                            .                  yes
/// ```
///
/// So the filter admits `[1]` — and each way of losing the converter admits something else: at the
/// top level `has_element` asks for a stored `1` and admits `[]`, at the nested level `any` asks for
/// `≥ 9` and admits `[1, 2]`.
#[cfg(feature = "sqlite")]
mod live {
  use core::num::TryFromIntError;

  use sqlx::{Connection as _, Executor as _, Row as _, sqlite::SqliteConnection};

  use crate::{
    At, FieldName, ListFilter, RecordAddress, ScalarFilter,
    comparison::{
      ComplexComparison,
      sql::{QueryBuilder, SelectClause, SqlConjunction, SqlEdgeComparison, SqlScalarComparison},
    },
  };

  /// The parent this corpus's collection hangs off — one key column, which is what the edge table
  /// correlates on.
  const CLIP: RecordAddress = RecordAddress::new(FieldName::new("clip"), &[FieldName::new("id")]);

  /// A mark column stored at a finer unit than the one a client writes it in.
  fn tenths(seconds: u64) -> Result<i64, TryFromIntError> {
    i64::try_from(seconds).map(|seconds| seconds * 10)
  }

  /// The two tables the edge strategy names, and four clips whose collections differ in the ways
  /// the filter below distinguishes.
  async fn corpus() -> SqliteConnection {
    let mut db = SqliteConnection::connect("sqlite::memory:")
      .await
      .expect("an in-memory database");
    for ddl in [
      r#"CREATE TABLE "clip" ("id" INTEGER PRIMARY KEY, "slate" TEXT NOT NULL)"#,
      r#"CREATE TABLE "clip_marks" ("id" INTEGER, "marks_ordinal" INTEGER, "marks" INTEGER,
         PRIMARY KEY ("id", "marks_ordinal"))"#,
    ] {
      db.execute(ddl).await.expect("a table");
    }
    for (id, slate) in [(1i64, "alpha"), (2, "bravo"), (3, "delta"), (4, "echo")] {
      sqlx::query(r#"INSERT INTO "clip" VALUES (?, ?)"#)
        .bind(id)
        .bind(slate)
        .execute(&mut db)
        .await
        .expect("a clip");
    }
    for (clip, ordinal, mark) in [
      (1i64, 0i64, 10i64),
      (1, 1, 90),
      (2, 0, 10),
      (2, 1, 20),
      (4, 0, 400),
    ] {
      sqlx::query(r#"INSERT INTO "clip_marks" VALUES (?, ?, ?)"#)
        .bind(clip)
        .bind(ordinal)
        .bind(mark)
        .execute(&mut db)
        .await
        .expect("a mark");
    }
    db
  }

  /// The clips this predicate admits, in id order.
  async fn clips(
    db: &mut SqliteConnection,
    comparison: &impl ComplexComparison<sqlx::Sqlite>,
  ) -> Vec<i64> {
    let frame = At::new(&CLIP).frame(FieldName::new("marks"));
    let mut statement = QueryBuilder::<SelectClause, sqlx::Sqlite>::select()
      .push_field("\"id\"")
      .from("\"clip\"")
      .begin_where();
    {
      let accumulator = SqlConjunction::new(statement.inner_mut());
      comparison
        .apply(frame.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()
  }

  /// One declaration, both levels, one engine.
  #[tokio::test]
  async fn one_declared_converter_carries_both_levels_of_a_live_collection() {
    let mut db = corpus().await;

    let written = ListFilter::<u64, ScalarFilter<u64>>::new()
      .with_has_element(1u64)
      .with_any(ScalarFilter::new().with_gte(9u64));
    let crossed =
      SqlEdgeComparison::<i64, SqlScalarComparison<i64, sqlx::Sqlite>, sqlx::Sqlite>::try_from_filter_with(
        written, tenths,
      )
      .expect("every mark fits the column's integer");

    assert_eq!(
      clips(&mut db, &crossed).await,
      [1],
      "the clip with a one-second mark AND a mark of nine seconds or more"
    );
  }
}

/// The crossing MAP, which is where the two strategies are actually chosen between: one filter
/// reaches a column-stored comparison on Postgres and the edge-table one on the two dialects with no
/// array type — and each shape reads its own half of the row.
///
/// It is a type-level assertion, because the map is a type-level trait — a value-level test could
/// only observe the choice after something had already made it.
#[cfg(all(feature = "sqlite", feature = "postgres", feature = "mysql"))]
#[test]
fn the_map_chooses_a_strategy_per_dialect() {
  use crate::{
    ListFilter, SetFilter,
    comparison::{
      ToDatabaseComparison,
      sql::{
        SqlEdgeComparison, SqlEdgeSetComparison, SqlListComparison, SqlScalarComparison,
        SqlSetComparison,
      },
    },
  };

  fn same<T>(_: core::marker::PhantomData<T>, _: core::marker::PhantomData<T>) {}

  /// The element comparison an `i64` member crosses into on each dialect — the answer the map's own
  /// element half gives, which every one of the six equations below carries.
  type Element<Db> = SqlScalarComparison<i64, Db>;

  type Sequence<Db> = <ListFilter<i64> as ToDatabaseComparison<i64, Db>>::Comparison;
  type Set<Db> = <SetFilter<i64> as ToDatabaseComparison<i64, Db>>::Comparison;

  same(
    core::marker::PhantomData::<Sequence<sqlx::Postgres>>,
    core::marker::PhantomData::<SqlListComparison<i64, Element<sqlx::Postgres>, sqlx::Postgres>>,
  );
  same(
    core::marker::PhantomData::<Set<sqlx::Postgres>>,
    core::marker::PhantomData::<SqlSetComparison<i64, Element<sqlx::Postgres>, sqlx::Postgres>>,
  );
  same(
    core::marker::PhantomData::<Sequence<sqlx::Sqlite>>,
    core::marker::PhantomData::<SqlEdgeComparison<i64, Element<sqlx::Sqlite>, sqlx::Sqlite>>,
  );
  same(
    core::marker::PhantomData::<Set<sqlx::Sqlite>>,
    core::marker::PhantomData::<SqlEdgeSetComparison<i64, Element<sqlx::Sqlite>, sqlx::Sqlite>>,
  );
  same(
    core::marker::PhantomData::<Sequence<sqlx::MySql>>,
    core::marker::PhantomData::<SqlEdgeComparison<i64, Element<sqlx::MySql>, sqlx::MySql>>,
  );
  same(
    core::marker::PhantomData::<Set<sqlx::MySql>>,
    core::marker::PhantomData::<SqlEdgeSetComparison<i64, Element<sqlx::MySql>, sqlx::MySql>>,
  );
}