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
#[cfg(feature = "sqlite")]
mod sqlite {
  use crate::{
    At, FieldName, Timestamp,
    comparison::sql::{
      SqlCompositeEdgeComparison, SqlConjunction, SqlCountComparison, SqlLoweringError,
      SqlScalarComparison,
      tests::{ROW, render, render_at},
    },
  };

  /// The framework's own instant is the shipped COMPOSITE element, so it is what these render.
  type Element = SqlScalarComparison<i64, sqlx::Sqlite>;
  type Edge = SqlCompositeEdgeComparison<Timestamp, Element, sqlx::Sqlite>;

  /// The derived table every form below selects from — spelled once, so each assertion reads as the
  /// operator it is about rather than as the projection it shares.
  const SCOPE: &str = "EXISTS (SELECT 1 FROM ( SELECT \"p_stamps\".\"stamps_secs\" AS \
                       \"value_secs\", \"p_stamps\".\"stamps_nanos\" AS \"value_nanos\" FROM \
                       \"p_stamps\" WHERE \"p_stamps\".\"id\" = \"p\".\"id\" ) AS \
                       \"__ig_element_0__\"";

  fn at(second: i64, nanosecond: i32) -> Timestamp {
    Timestamp::from_parts(second, nanosecond).unwrap()
  }

  fn empty() -> Edge {
    Edge::new()
  }

  /// **The element's equality decomposes CONJUNCTIVELY**, and the row value is that spelling.
  ///
  /// `(a, b) = (1, 10)` IS `a = 1 AND b = 10`, so one predicate names both segments and binds both
  /// operands — where a lowering that compared only the leading segment would render valid SQL,
  /// bind one parameter, and admit every element sharing a second.
  #[test]
  fn an_element_equality_names_every_segment() {
    let mut comparison = empty();
    comparison.has_element = Some(at(7, 250));

    let (sql, binds) = render::<sqlx::Sqlite, _>("stamps", &comparison);

    assert_eq!(
      sql,
      format!("{SCOPE} WHERE (\"value_secs\", \"value_nanos\") = (?, ?))")
    );
    assert_eq!(binds, 2);
  }

  /// **The cartesian trap, pinned NEGATIVELY.**
  ///
  /// A membership over two elements renders the row-value list, which admits exactly those two. The
  /// spelling that looks as though it decomposes — `"value_secs" IN (?, ?) AND "value_nanos" IN (?,
  /// ?)` — is well-formed SQL, binds the same four operands, and admits the two CROSS pairs as well.
  /// Nothing in a bind count separates them, so what is asserted here is the TEXT: the row value is
  /// present and the per-column form is absent by name.
  #[test]
  fn an_element_membership_is_the_pairs_and_not_their_product() {
    let mut comparison = empty();
    comparison.has_any_of = Some(Box::new([at(7, 250), at(9, 100)]));

    let (sql, binds) = render::<sqlx::Sqlite, _>("stamps", &comparison);

    assert_eq!(
      sql,
      format!("{SCOPE} WHERE (\"value_secs\", \"value_nanos\") IN ((?, ?), (?, ?)))")
    );
    assert_eq!(binds, 4);
    // The product's own spelling, which would answer a different question under the same operator.
    assert!(!sql.contains("\"value_secs\" IN ("));
    assert!(!sql.contains(" AND \"value_nanos\" IN ("));
  }

  /// An EMPTY membership means MATCH NOTHING, where an absent one asks for every row — the
  /// asymmetry the flat family already draws, arriving through the same renderer.
  #[test]
  fn an_empty_membership_matches_nothing() {
    let mut comparison = empty();
    comparison.has_any_of = Some(Box::new([]));

    let (sql, binds) = render::<sqlx::Sqlite, _>("stamps", &comparison);

    assert_eq!(sql, format!("{SCOPE} WHERE 1 = 0)"));
    assert_eq!(binds, 0);
  }

  /// The element's OWN comparison renders inside the scope, against the PROJECTED names.
  ///
  /// This is what makes a composite element first-class: the filter a declaration writes over one
  /// segment is the element type's own emitted comparison, and it lowers here exactly as it lowers
  /// over a column of the row.
  #[test]
  fn the_element_scope_carries_the_elements_own_comparison() {
    let mut element = SqlScalarComparison::<i64, sqlx::Sqlite>::new();
    element.gt = Some(1_700_000_000);
    let mut comparison = empty();
    comparison.any = Some(element);

    let (sql, binds) = render::<sqlx::Sqlite, _>("stamps", &comparison);

    assert_eq!(sql, format!("{SCOPE} WHERE \"value\" > ?)"));
    assert_eq!(binds, 1);
  }

  /// An empty element comparison writes no `WHERE`, which is the QUANTIFIER asking whether the
  /// collection has an element at all.
  #[test]
  fn an_empty_element_scope_asks_whether_any_element_exists() {
    let mut comparison = empty();
    comparison.any = Some(SqlScalarComparison::<i64, sqlx::Sqlite>::new());

    let (sql, binds) = render::<sqlx::Sqlite, _>("stamps", &comparison);

    assert_eq!(sql, format!("{SCOPE})"));
    assert_eq!(binds, 0);
  }

  /// The cardinality is the correlated `COUNT(*)` this strategy already builds, and it reads the
  /// SHARED scope — so a composite element answers `count` without naming a segment.
  #[test]
  fn the_cardinality_reads_the_shared_scope() {
    let mut count = SqlCountComparison::<i64, sqlx::Sqlite>::new();
    count.eq = Some(2);
    let mut comparison = empty();
    comparison.count = Some(count);

    let (sql, binds) = render::<sqlx::Sqlite, _>("stamps", &comparison);

    assert_eq!(
      sql,
      "(SELECT COUNT(*) FROM \"p_stamps\" WHERE \"p_stamps\".\"id\" = \"p\".\"id\") = ?"
    );
    assert_eq!(binds, 1);
  }

  /// Several operators thread ONE accumulator, and each is its own conjunct.
  #[test]
  fn every_operator_is_one_conjunct() {
    let mut comparison = empty();
    comparison.has_element = Some(at(7, 250));
    comparison.has_any_of = Some(Box::new([at(9, 100)]));

    assert_eq!(comparison.conjuncts(), 2);
    let (sql, binds) = render::<sqlx::Sqlite, _>("stamps", &comparison);
    assert!(sql.contains(") = (?, ?)) AND EXISTS ("));
    assert_eq!(binds, 4);
  }

  /// The TOP LEVEL names no field, so there is no edge table to correlate to — the correlated
  /// family's own refusal, reached before any conjunct opens.
  #[test]
  fn the_top_level_has_no_edge_table() {
    let mut comparison = empty();
    comparison.has_element = Some(at(7, 250));

    let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
    let refused = {
      let out = SqlConjunction::with_lead(&mut qb, "");
      crate::ComplexComparison::apply(&comparison, At::new(&ROW), out).err()
    };

    assert_eq!(qb.sql(), "");
    assert_eq!(
      refused,
      Some(SqlLoweringError::EdgeWithoutField(FieldName::new("p")))
    );
  }

  /// **The ceiling is `elements × segments`**, and past it the refusal names the three numbers a
  /// caller batches by — the `SqlKeyIn` posture, for `SqlKeyIn`'s reason: the second number is the
  /// ELEMENT TYPE's rather than the call's, so a caller under any single-column budget can be over
  /// this one with nothing in its own arithmetic saying so.
  #[test]
  fn a_membership_past_the_ceiling_is_refused_by_name() {
    // SQLite takes 32766 bound parameters and an instant is two columns wide, so 16384 elements are
    // one over.
    let elements = (0..16_384).map(|n| at(n, 0)).collect::<Vec<_>>();
    let mut comparison = empty();
    comparison.has_any_of = Some(elements.into_boxed_slice());

    let frame = At::new(&ROW).frame(FieldName::new("stamps"));
    let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
    let refused = {
      let out = SqlConjunction::with_lead(&mut qb, "");
      crate::ComplexComparison::apply(&comparison, frame.at(), out).err()
    };

    // A refusal leaves the accumulator exactly as it was found — the ordering `SqlKeyIn` keeps.
    assert_eq!(qb.sql(), "");
    let Some(SqlLoweringError::BindCeiling(error)) = refused else {
      panic!("a membership past the ceiling is refused by the bind count");
    };
    assert_eq!(error.keys(), 16_384);
    assert_eq!(error.columns(), 2);
    assert_eq!(error.ceiling(), 32_766);
  }

  /// One element under the ceiling renders, so the fence is at the number it names rather than near
  /// it.
  #[test]
  fn a_membership_at_the_ceiling_renders() {
    let elements = (0..16_383).map(|n| at(n, 0)).collect::<Vec<_>>();
    let mut comparison = empty();
    comparison.has_any_of = Some(elements.into_boxed_slice());

    let frame = At::new(&ROW).frame(FieldName::new("stamps"));
    let (_, binds) = render_at::<sqlx::Sqlite, _>(frame.at(), &comparison);

    assert_eq!(binds, 32_766);
  }
}

/// **AN ELEMENT WHOSE OWN PARTS ARE COMPOSITE**, which is the widening: the edge table writes the
/// FLATTENED leaves, exactly as the direct table already writes them for the same element.
#[cfg(feature = "sqlite")]
mod nested {
  use crate::{
    Carrier, CollectionElement, ColumnKind, ColumnName, ColumnShape, FieldName,
    comparison::sql::{
      SqlCompositeEdgeComparison, SqlScalarComparison,
      tests::{ROW, render},
    },
    flattened, leaf_names, shape,
  };

  /// A half-open span — two columns, and the part a cue SPLICES.
  #[derive(Debug, Clone, Copy)]
  struct Span {
    start: i64,
    end: i64,
  }

  impl ColumnKind for Span {
    const SEGMENTS: &'static [ColumnShape] = &[
      ColumnShape::Plain(ColumnName::new("start")),
      ColumnShape::Plain(ColumnName::new("end")),
    ];
  }

  /// A cue: a span that lends NO name, then a weight — THREE leaf columns under two parts, which is
  /// the shape `DetectedLanguage` has at five.
  #[derive(Debug, Clone, Copy)]
  struct Cue {
    span: Span,
    weight: i64,
  }

  impl ColumnKind for Cue {
    const SEGMENTS: &'static [ColumnShape] = &[
      flattened::<Span>(),
      ColumnShape::Plain(ColumnName::new("weight")),
    ];
  }

  impl CollectionElement for Cue {}

  impl<Db> Carrier<Db> for Cue
  where
    Db: sqlx::Database,
    i64: Carrier<Db>,
  {
    fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
      self.span.start.push_bind(qb);
      qb.push(", ");
      self.span.end.push_bind(qb);
      qb.push(", ");
      self.weight.push_bind(qb);
    }
  }

  /// A part that LENDS its name, so its leaves take a prefix INSIDE the element — the other half of
  /// the walk, and the one a flattened part cannot show.
  #[derive(Debug, Clone, Copy)]
  struct Cadence {
    num: i64,
    den: i64,
  }

  impl ColumnKind for Cadence {
    const SEGMENTS: &'static [ColumnShape] = &[
      ColumnShape::Plain(ColumnName::new("num")),
      ColumnShape::Plain(ColumnName::new("den")),
    ];
  }

  #[derive(Debug, Clone, Copy)]
  struct Mark {
    rate: Cadence,
  }

  impl ColumnKind for Mark {
    const SEGMENTS: &'static [ColumnShape] = &[shape::<Cadence>(ColumnName::new("rate"))];
  }

  impl CollectionElement for Mark {}

  impl<Db> Carrier<Db> for Mark
  where
    Db: sqlx::Database,
    i64: Carrier<Db>,
  {
    fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
      self.rate.num.push_bind(qb);
      qb.push(", ");
      self.rate.den.push_bind(qb);
    }
  }

  type Element = SqlScalarComparison<i64, sqlx::Sqlite>;
  type Cues = SqlCompositeEdgeComparison<Cue, Element, sqlx::Sqlite>;
  type Marks = SqlCompositeEdgeComparison<Mark, Element, sqlx::Sqlite>;

  /// **THE WIDTH IS THE LEAVES**, which is what the descriptor and the bind arithmetic both spend.
  #[test]
  fn a_nested_element_is_as_wide_as_its_leaves() {
    assert_eq!(crate::width(<Cue as ColumnKind>::SEGMENTS), 3);
    assert_eq!(<Cue as ColumnKind>::SEGMENTS.len(), 2);
    assert_eq!(crate::width(<Mark as ColumnKind>::SEGMENTS), 2);
    assert_eq!(<Mark as ColumnKind>::SEGMENTS.len(), 1);
  }

  /// **THE `const` AUDIT KNOWS THE JOIN**, so a descriptor's flat restatement is checked against the
  /// element's own tree rather than trusted beside it.
  const _: () = assert!(leaf_names(
    <Cue as ColumnKind>::SEGMENTS,
    &[
      FieldName::new("start"),
      FieldName::new("end"),
      FieldName::new("weight"),
    ]
  ));
  const _: () = assert!(leaf_names(
    <Mark as ColumnKind>::SEGMENTS,
    &[FieldName::new("rate_num"), FieldName::new("rate_den")]
  ));

  /// **THE PROJECTION AND THE PREDICATE ARE ONE WALK.** A flattened part splices its leaves into the
  /// element's own namespace on BOTH sides of the `AS`, so the predicate names no column the derived
  /// table did not write.
  #[test]
  fn a_flattened_part_splices_its_leaves_into_both_sides() {
    let mut comparison = Cues::new();
    comparison.has_element = Some(Cue {
      span: Span { start: 7, end: 9 },
      weight: 3,
    });

    let (sql, binds) = render::<sqlx::Sqlite, _>("cues", &comparison);

    assert_eq!(
      sql,
      "EXISTS (SELECT 1 FROM ( SELECT \"p_cues\".\"cues_start\" AS \"value_start\", \
       \"p_cues\".\"cues_end\" AS \"value_end\", \"p_cues\".\"cues_weight\" AS \"value_weight\" \
       FROM \"p_cues\" WHERE \"p_cues\".\"id\" = \"p\".\"id\" ) AS \"__ig_element_0__\" WHERE \
       (\"value_start\", \"value_end\", \"value_weight\") = (?, ?, ?))"
    );
    assert_eq!(binds, 3);
    // The doubled word a NAMED part would have produced, absent — it is what lending the part its
    // name would have written, and the whole reason the direct form flattens.
    assert!(!sql.contains("cues_span_start"));
  }

  /// **A PART THAT LENDS ITS NAME PREFIXES ITS LEAVES**, on both sides and by the same walk.
  #[test]
  fn a_named_part_prefixes_its_leaves_on_both_sides() {
    let mut comparison = Marks::new();
    comparison.has_any_of = Some(Box::new([
      Mark {
        rate: Cadence { num: 24, den: 1 },
      },
      Mark {
        rate: Cadence {
          num: 24_000,
          den: 1_001,
        },
      },
    ]));

    let (sql, binds) = render::<sqlx::Sqlite, _>("marks", &comparison);

    assert_eq!(
      sql,
      "EXISTS (SELECT 1 FROM ( SELECT \"p_marks\".\"marks_rate_num\" AS \"value_rate_num\", \
       \"p_marks\".\"marks_rate_den\" AS \"value_rate_den\" FROM \"p_marks\" WHERE \
       \"p_marks\".\"id\" = \"p\".\"id\" ) AS \"__ig_element_0__\" WHERE (\"value_rate_num\", \
       \"value_rate_den\") IN ((?, ?), (?, ?)))"
    );
    assert_eq!(binds, 4);
  }

  /// **THE CEILING MULTIPLIES BY THE LEAVES**, not by the parts — the number a caller batches by is
  /// the columns one element spends.
  #[test]
  fn the_ceiling_counts_leaves_rather_than_parts() {
    let elements = (0..11_000)
      .map(|n| Cue {
        span: Span { start: n, end: n },
        weight: n,
      })
      .collect::<Vec<_>>();
    let mut comparison = Cues::new();
    comparison.has_any_of = Some(elements.into_boxed_slice());

    let frame = crate::At::new(&ROW).frame(FieldName::new("cues"));
    let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
    let refused = {
      let out = crate::comparison::sql::SqlConjunction::with_lead(&mut qb, "");
      crate::ComplexComparison::apply(&comparison, frame.at(), out).err()
    };

    let Some(crate::comparison::sql::SqlLoweringError::BindCeiling(error)) = refused else {
      panic!("a membership past the ceiling is refused by the bind count");
    };
    // Three, which is the LEAF count — a refusal reading `2` would have counted the parts.
    assert_eq!(error.columns(), 3);
    assert_eq!(error.keys(), 11_000);
  }

  /// **THE QUANTIFIED CROSSING REACHES THE COMPOSITE KIND**, and the element's own filter rides
  /// `any` whole — the wide face, narrowed only where the element's own crossing narrows.
  #[test]
  fn a_quantified_crossing_carries_the_elements_own_filter() {
    use crate::{QuantifiedFilter, ScalarFilter, TryFromFilter};

    let filter = QuantifiedFilter::<Cue, ScalarFilter<i64>>::new()
      .with_any(ScalarFilter::new().with_gt(2i64))
      .with_count(ScalarFilter::new().with_gte(1usize));

    let crossed = Cues::try_from_filter(filter).expect("the crossing");

    // The two slots this face has, and the two it structurally has not.
    assert!(crossed.any().is_some());
    assert!(crossed.count().is_some());
    assert!(crossed.has_element().is_none());
    assert!(crossed.has_any_of().is_none());

    let (sql, binds) = render::<sqlx::Sqlite, _>("cues", &crossed);

    assert!(
      sql.contains("\"p_cues\".\"cues_start\" AS \"value_start\""),
      "{sql}"
    );
    assert!(sql.contains(" WHERE \"value\" > ?)"), "{sql}");
    assert!(
      sql.contains("(SELECT COUNT(*) FROM \"p_cues\" WHERE \"p_cues\".\"id\" = \"p\".\"id\") >= ?"),
      "{sql}"
    );
    assert_eq!(binds, 2);
  }

  /// **A `count` PAST THE FAMILY'S INTEGER IS REFUSED BY NAME**, through the same arm the two scalar
  /// narrow crossings take.
  #[test]
  fn a_cardinality_past_the_integer_is_refused_by_name() {
    use crate::{
      QuantifiedFilter, ScalarFilter, TryFromFilter, comparison::sql::ListCrossingError,
    };

    let filter = QuantifiedFilter::<Cue, ScalarFilter<i64>>::new()
      .with_count(ScalarFilter::new().with_eq(usize::MAX));

    assert!(matches!(
      Cues::try_from_filter(filter),
      Err(ListCrossingError::Cardinality(_))
    ));
  }
}

/// **AN ELEMENT CARRYING A DERIVED LEAF** — ingraph #455, and the law that repairs it.
///
/// The shape is `MediaTimestamp`'s: a count, the unit it is counted in, and a DERIVED position
/// beside them that binds `NULL` for a value past a ceiling. Written by hand rather than imported,
/// for the two modules above's reason — this lane carries no citizen vocabulary, and the rendering
/// has to be total over the shapes a person can declare.
///
/// What the suite pins is that an element's structural identity is what it HOLDS: the row value
/// names the value columns, the operand binds exactly those, and the PROJECTION keeps every one, so
/// the element's own comparison can still ask about the index leaf.
#[cfg(feature = "sqlite")]
mod derived_leaf {
  use crate::{
    Carrier, CollectionElement, ColumnKind, ColumnName, ColumnShape,
    comparison::sql::{
      SqlCompositeEdgeComparison, SqlScalarComparison,
      tests::{ROW, render},
    },
  };

  /// A tick: a declared count, the rate it is counted at, and the position it lands on — which the
  /// last one cannot always hold.
  #[derive(Debug, Clone, Copy)]
  struct Tick {
    pts: i64,
    hz: i64,
  }

  impl Tick {
    /// Past this many ticks the position has no place to go, which is this fixture's ±292 years.
    const CEILING: i64 = 1_000;

    /// [`None`] past the ceiling — the honest answer for an index rather than a failure to store
    /// one, exactly as `MediaTimestamp::to_nanos` refuses rather than saturating.
    const fn nanos(self) -> Option<i64> {
      if self.pts > Self::CEILING || self.pts < -Self::CEILING {
        return None;
      }
      Some(self.pts * 1_000_000_000 / self.hz)
    }
  }

  impl ColumnKind for Tick {
    const SEGMENTS: &'static [ColumnShape] = &[
      ColumnShape::Plain(ColumnName::new("pts")),
      ColumnShape::Plain(ColumnName::new("hz")),
      ColumnShape::Nullable(ColumnName::new("nanos")),
    ];
  }

  impl CollectionElement for Tick {}

  /// **THREE BINDS FOR A WRITE AND TWO FOR AN IDENTITY**, which is the pairing the law asks of every
  /// type that declares an index leaf.
  impl<Db> Carrier<Db> for Tick
  where
    Db: sqlx::Database,
    i64: Carrier<Db>,
  {
    fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
      self.push_value_bind(qb);
      qb.push(", ");
      match self.nanos() {
        Some(nanos) => nanos.push_bind(qb),
        None => {
          qb.push("NULL");
        }
      }
    }

    fn push_value_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
      self.pts.push_bind(qb);
      qb.push(", ");
      self.hz.push_bind(qb);
    }
  }

  type Ticks =
    SqlCompositeEdgeComparison<Tick, SqlScalarComparison<i64, sqlx::Sqlite>, sqlx::Sqlite>;

  /// The derived table every form selects from — THREE projected columns, the index leaf included.
  const SCOPE: &str = "EXISTS (SELECT 1 FROM ( SELECT \"p_ticks\".\"ticks_pts\" AS \"value_pts\", \
                       \"p_ticks\".\"ticks_hz\" AS \"value_hz\", \"p_ticks\".\"ticks_nanos\" AS \
                       \"value_nanos\" FROM \"p_ticks\" WHERE \"p_ticks\".\"id\" = \"p\".\"id\" ) \
                       AS \"__ig_element_0__\"";

  /// A tick whose position has no representation — the row the defect could never find.
  const fn unplaceable() -> Tick {
    Tick {
      pts: 10_000,
      hz: 90_000,
    }
  }

  /// **`has_element` NAMES THE VALUE COLUMNS AND BINDS EXACTLY THOSE — ingraph #455.**
  ///
  /// With the index leaf in the tuple this is `(…, "value_nanos") = (?, ?, NULL)`, which is UNKNOWN
  /// for every row: an element past its ceiling could not be found by the very pair that wrote it,
  /// while the collection held it and the decode read it back. The bind count is asserted beside the
  /// text because the two failures look different — a third placeholder is the operand still
  /// spending its index leaf, where a third column name is the left-hand side still asking for one.
  #[test]
  fn an_element_equality_is_the_value_columns_alone() {
    let mut comparison = Ticks::new();
    comparison.has_element = Some(unplaceable());

    let (sql, binds) = render::<sqlx::Sqlite, _>("ticks", &comparison);

    assert_eq!(
      sql,
      format!("{SCOPE} WHERE (\"value_pts\", \"value_hz\") = (?, ?))")
    );
    assert_eq!(binds, 2, "the index leaf is not an operand of an identity");
    assert!(
      !sql.contains("NULL"),
      "and the `NULL` it would have bound is nowhere in the statement: {sql}"
    );
  }

  /// The same at the membership half, where the `NULL` would have been bound once per element.
  #[test]
  fn a_membership_is_the_value_columns_alone() {
    let mut comparison = Ticks::new();
    comparison.has_any_of = Some(Box::new([unplaceable(), Tick { pts: 9, hz: 90_000 }]));

    let (sql, binds) = render::<sqlx::Sqlite, _>("ticks", &comparison);

    assert_eq!(
      sql,
      format!("{SCOPE} WHERE (\"value_pts\", \"value_hz\") IN ((?, ?), (?, ?)))")
    );
    assert_eq!(binds, 4, "two elements at two value columns each");
  }

  /// **THE PROJECTION IS NOT NARROWED WITH THE PREDICATE**, and that is deliberate rather than
  /// missed: the element's own comparison reaching `any` may ask about the index leaf, which is
  /// exactly the question an index leaf exists to answer. So the derived table keeps every column
  /// and only the IDENTITY forms leave one out.
  #[test]
  fn the_element_scope_still_projects_the_derived_column() {
    let mut element = SqlScalarComparison::<i64, sqlx::Sqlite>::new();
    element.gt = Some(0);
    let mut comparison = Ticks::new();
    comparison.any = Some(element);

    let (sql, binds) = render::<sqlx::Sqlite, _>("ticks", &comparison);

    assert_eq!(sql, format!("{SCOPE} WHERE \"value\" > ?)"));
    assert_eq!(binds, 1);
    assert!(sql.contains("AS \"value_nanos\""));
  }

  /// **THE CEILING COUNTS VALUE COLUMNS**, which is what a caller's batch arithmetic has to match:
  /// an element that costs two placeholders and occupies three columns is refused by the two.
  #[test]
  fn the_bind_ceiling_counts_what_the_statement_spends() {
    use crate::{At, ComplexComparison, FieldName, comparison::sql::SqlLoweringError};

    // SQLite takes 32766 parameters and a tick spends TWO of them, so 16384 elements are one over —
    // where a ceiling counting the type's three columns would have refused 10923 of them.
    let elements = (0..16_384)
      .map(|pts| Tick { pts, hz: 90_000 })
      .collect::<Vec<_>>();
    let mut comparison = Ticks::new();
    comparison.has_any_of = Some(elements.into_boxed_slice());

    let frame = At::new(&ROW).frame(FieldName::new("ticks"));
    let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
    let refused = {
      let out = crate::comparison::sql::SqlConjunction::with_lead(&mut qb, "");
      comparison.apply(frame.at(), out).err()
    };

    assert_eq!(
      qb.sql(),
      "",
      "a refusal leaves the accumulator as it found it"
    );
    let Some(SqlLoweringError::BindCeiling(error)) = refused else {
      panic!("a membership past the ceiling is refused by the bind count");
    };
    assert_eq!(error.keys(), 16_384);
    assert_eq!(
      error.columns(),
      2,
      "the VALUE columns, which are what it spends"
    );
    assert_eq!(error.ceiling(), 32_766);
  }
}