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
use core::convert::Infallible;

use super::SqlScalarComparison;
use crate::{ScalarFilter, Score, comparison::TryFromFilter};

/// A `Score` stored as PERMILLE: the crossing that changes the value rather than only its type, so a
/// pass-through mutation is visible in the operand and not only in the SQL.
fn permille(score: Score) -> Result<i32, Infallible> {
  Ok((score.get() * 1000.0) as i32)
}

/// The crossing carries DOMAIN values in and leaves STORAGE values behind — the one property the
/// whole layer exists for.
#[test]
fn a_crossing_replaces_the_operand_with_its_stored_form() {
  let filter = ScalarFilter::<Score>::new()
    .with_eq(Score::new(0.75).unwrap())
    .with_in_([Score::ZERO, Score::ONE]);

  let crossed = SqlScalarComparison::<i32, ()>::try_from_filter_with(filter, permille).unwrap();

  assert_eq!(crossed.eq(), Some(&750));
  assert_eq!(crossed.in_(), Some(&[0, 1000][..]));
}

/// The list slot converts element by element, and the FIRST failure is the answer — the operands
/// already crossed go with it rather than being reported half-done.
#[test]
fn a_list_crossing_stops_at_the_first_refusal() {
  let filter = ScalarFilter::<i64>::new().with_in_([1i64, 300, 2]);
  let crossed = SqlScalarComparison::<u8, ()>::try_from_filter(filter);
  assert!(crossed.is_err());

  let all_fit = ScalarFilter::<i64>::new().with_in_([1i64, 2, 3]);
  let crossed = SqlScalarComparison::<u8, ()>::try_from_filter(all_fit).unwrap();
  assert_eq!(crossed.in_(), Some(&[1u8, 2, 3][..]));
}

/// An empty membership list crosses to an empty membership list. Collapsing it to `None` would turn
/// "match no rows" into "match every row" in silence.
#[test]
fn an_empty_membership_list_stays_present() {
  let filter = ScalarFilter::<i64>::new().with_in_(Vec::<i64>::new());
  let crossed = SqlScalarComparison::<i64, ()>::try_from_filter(filter).unwrap();
  assert_eq!(crossed.in_(), Some(&[][..]));
  assert!(!crossed.is_empty());
  assert_eq!(crossed.conjuncts(), 1);
}

/// The identity crossing keeps its promise in the TYPE: assigning the error to `Infallible` is the
/// assertion, and it stops compiling the moment the crossing acquires a way to fail.
#[test]
fn the_identity_crossing_cannot_fail() {
  let filter = ScalarFilter::<i64>::new().with_eq(1i64);
  let crossed: Result<SqlScalarComparison<i64, ()>, Infallible> =
    SqlScalarComparison::try_from_filter(filter);
  assert_eq!(crossed.unwrap().eq(), Some(&1));
}

/// `eq()` and `ne()` shadow [`PartialEq`]'s methods for call syntax, and `==` is unaffected because
/// the operator reaches the trait directly.
#[test]
fn the_operators_still_compare_whole_comparisons() {
  let one =
    SqlScalarComparison::<i64, ()>::try_from_filter(ScalarFilter::<i64>::new().with_eq(1i64))
      .unwrap();
  let same =
    SqlScalarComparison::<i64, ()>::try_from_filter(ScalarFilter::<i64>::new().with_eq(1i64))
      .unwrap();
  let other =
    SqlScalarComparison::<i64, ()>::try_from_filter(ScalarFilter::<i64>::new().with_eq(2i64))
      .unwrap();

  assert_eq!(one, same);
  assert!(one == same);
  assert!(one != other);
  // The inherent getter is what a bare `eq` call resolves to now.
  assert_eq!(one.eq(), Some(&1));
}

#[cfg(feature = "sqlite")]
mod sqlite {
  use core::cell::RefCell;

  use super::{SqlScalarComparison, permille};
  use crate::{
    At, BeU64, ComplexComparison, FieldName, ScalarFilter, Score,
    comparison::{
      TryFromFilter,
      sql::{
        QueryBuilder, SelectClause, SqlConjunction,
        tests::{Probe, ROW, render, threaded},
      },
    },
  };

  /// The whole point of threading the accumulator: `apply` writes its conjuncts into the one it was
  /// handed and gives it back, so the comparison after it joins with ` AND ` and neither of them
  /// opens a clause.
  #[test]
  fn a_threaded_comparison_hands_the_accumulator_back_for_the_next_one() {
    let cmp = SqlScalarComparison::<i64, sqlx::Sqlite>::try_from_filter(
      ScalarFilter::<i64>::new().with_eq(1i64).with_gt(3i64),
    )
    .unwrap();

    let mut builder = QueryBuilder::<SelectClause, sqlx::Sqlite>::select()
      .push_field("\"id\"")
      .from("\"t\"")
      .begin_where();
    {
      let accumulator = SqlConjunction::new(builder.inner_mut());
      let accumulator = cmp
        .apply(At::new(&ROW).frame(FieldName::new("n")).at(), accumulator)
        .unwrap();
      cmp
        .apply(At::new(&ROW).frame(FieldName::new("m")).at(), accumulator)
        .unwrap();
    }

    assert_eq!(
      builder.finalize().into_string(),
      "SELECT \"id\" FROM \"t\" WHERE \"n\" = ? AND \"n\" > ? AND \"m\" = ? AND \"m\" > ?"
    );
  }

  fn probed<'a>(
    filter: ScalarFilter<i64>,
    bound: &'a RefCell<Vec<i64>>,
  ) -> SqlScalarComparison<Probe<'a>, sqlx::Sqlite> {
    SqlScalarComparison::try_from_filter_with(filter, |value| {
      Ok::<_, core::convert::Infallible>(Probe { value, bound })
    })
    .unwrap()
  }

  fn apply_probed(comparison: &SqlScalarComparison<Probe<'_>, sqlx::Sqlite>) -> String {
    threaded::<sqlx::Sqlite, _>("n", comparison)
  }

  /// Every operand the comparison holds reaches the builder, in slot order.
  #[test]
  fn every_operand_the_comparison_holds_is_bound() {
    let bound = RefCell::new(Vec::new());
    let cmp = probed(ScalarFilter::new().with_eq(1i64).with_gt(3i64), &bound);

    apply_probed(&cmp);

    assert_eq!(*bound.borrow(), [1, 3]);
  }

  /// The probe is not a longer way of reading the SQL: these two comparisons render the SAME text
  /// and bind the same number of times, and differ only in the operands — which is exactly the
  /// class of defect a string assertion cannot see.
  #[test]
  fn two_comparisons_render_alike_and_bind_differently() {
    let ascending = RefCell::new(Vec::new());
    let descending = RefCell::new(Vec::new());

    let sql = apply_probed(&probed(
      ScalarFilter::new().with_eq(1i64).with_gt(3i64),
      &ascending,
    ));
    let same_sql = apply_probed(&probed(
      ScalarFilter::new().with_eq(3i64).with_gt(1i64),
      &descending,
    ));

    assert_eq!(sql, same_sql);
    assert_eq!(*ascending.borrow(), [1, 3]);
    assert_eq!(*descending.borrow(), [3, 1]);
  }

  #[test]
  fn every_operator_renders_its_own_conjunct() {
    let filter = ScalarFilter::<i64>::new()
      .with_eq(1i64)
      .with_ne(2i64)
      .with_gt(3i64)
      .with_gte(4i64)
      .with_lt(5i64)
      .with_lte(6i64)
      .with_in_([7i64, 8])
      .with_not_in([9i64]);
    let crossed = SqlScalarComparison::<i64, sqlx::Sqlite>::try_from_filter(filter).unwrap();

    assert_eq!(crossed.conjuncts(), 8);
    assert_eq!(
      render::<sqlx::Sqlite, _>("n", &crossed),
      (
        "\"n\" = ? AND NOT ( \"n\" = ? ) AND \"n\" > ? AND \"n\" >= ? AND \"n\" < ? AND \
         \"n\" <= ? AND \"n\" IN (?, ?) AND NOT ( \"n\" IN (?) )"
          .to_owned(),
        9
      )
    );
  }

  /// The physical encoding never reaches the SQL: a `u64` bound as an order-preserving blob and an
  /// `i64` bound natively render the SAME text. The bind count is the only thing the text can show,
  /// which is why the crossing has to be asserted on the operand instead.
  #[test]
  fn the_carrier_is_invisible_in_the_sql() {
    let native = SqlScalarComparison::<i64, sqlx::Sqlite>::try_from_filter(
      ScalarFilter::<i64>::new().with_eq(1i64),
    )
    .unwrap();
    let blob = SqlScalarComparison::<BeU64, sqlx::Sqlite>::try_from_filter(
      ScalarFilter::<u64>::new().with_eq(1u64),
    )
    .unwrap();

    assert_eq!(blob.eq(), Some(&BeU64(1)));
    assert_eq!(
      render::<sqlx::Sqlite, _>("n", &native),
      render::<sqlx::Sqlite, _>("n", &blob)
    );
  }

  /// An empty `in_` matches no rows and an empty `not_in` matches every row — the two are not each
  /// other's negation by accident, they are `1 = 0` inside and outside the wrap.
  #[test]
  fn an_empty_membership_list_renders_a_contradiction() {
    let in_ = SqlScalarComparison::<i64, sqlx::Sqlite>::try_from_filter(
      ScalarFilter::<i64>::new().with_in_(Vec::<i64>::new()),
    )
    .unwrap();
    let not_in = SqlScalarComparison::<i64, sqlx::Sqlite>::try_from_filter(
      ScalarFilter::<i64>::new().with_not_in(Vec::<i64>::new()),
    )
    .unwrap();

    assert_eq!(
      render::<sqlx::Sqlite, _>("n", &in_),
      ("1 = 0".to_owned(), 0)
    );
    assert_eq!(
      render::<sqlx::Sqlite, _>("n", &not_in),
      ("NOT ( 1 = 0 )".to_owned(), 0)
    );
  }

  /// A borrowed operand is the same struct with a different `V`, and it lowers identically —
  /// `&V: Carrier<Db>` wherever `V: Carrier<Db>`.
  #[test]
  fn a_borrowed_operand_lowers_as_the_owned_one_does() {
    let owned = SqlScalarComparison::<i64, sqlx::Sqlite>::try_from_filter(
      ScalarFilter::<i64>::new().with_eq(1i64),
    )
    .unwrap();
    let value = 1i64;
    let borrowed = SqlScalarComparison::<&i64, sqlx::Sqlite>::try_from_filter(
      ScalarFilter::<&i64>::new().with_eq(&value),
    )
    .unwrap();

    assert_eq!(
      render::<sqlx::Sqlite, _>("n", &owned),
      render::<sqlx::Sqlite, _>("n", &borrowed)
    );
  }

  /// The declared-converter path and the trait path reach the same builder — one is the other with
  /// the storage type's own `TryFrom` supplied.
  #[test]
  fn a_declared_converter_renders_what_the_trait_path_does() {
    let declared = SqlScalarComparison::<i32, sqlx::Sqlite>::try_from_filter_with(
      ScalarFilter::<Score>::new().with_eq(Score::new(0.75).unwrap()),
      permille,
    )
    .unwrap();
    let plain = SqlScalarComparison::<i32, sqlx::Sqlite>::try_from_filter(
      ScalarFilter::<i32>::new().with_eq(750i32),
    )
    .unwrap();

    assert_eq!(declared, plain);
    assert_eq!(
      render::<sqlx::Sqlite, _>("s", &declared),
      ("\"s\" = ?".to_owned(), 1)
    );
  }
}

/// **The COMPOSITE lowering**, against the framework's own two-column citizen.
///
/// A `Timestamp` operand pushes two placeholders — the comma is its carrier row's — so a left-hand
/// side naming ONE column renders `"at" = ?, ?`, which no engine parses. What these pin is the row
/// value that replaces it, and the ONE spelling all eight operators take.
#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
mod composite {
  use super::SqlScalarComparison;
  use crate::{ScalarFilter, Timestamp, comparison::TryFromFilter};

  /// The fixture instant: a full nine digits, so nothing here can pass by dropping a fraction.
  fn at() -> Timestamp {
    "2026-08-09T21:14:03.123456789Z"
      .parse()
      .expect("the fixture parses")
  }

  /// The pre-epoch instant whose two halves are BOTH negative — the pairing the storage slice
  /// records, carried into the predicate so an operand that straddles the epoch is one of the
  /// fixtures rather than an afterthought.
  fn before_epoch() -> Timestamp {
    "1969-12-31T23:59:58.5Z"
      .parse()
      .expect("the fixture parses")
  }

  /// The comparison for one filter, in whichever dialect the caller names.
  fn crossed<Db>(filter: ScalarFilter<Timestamp>) -> SqlScalarComparison<Timestamp, Db> {
    SqlScalarComparison::try_from_filter(filter).expect("the identity crossing cannot fail")
  }

  /// **Every operator is the row value, and `eq` is not the exception.**
  ///
  /// `(a, b) = (?, ?)` IS `a = ? AND b = ?` — SQL's own definition of row-value equality — so the
  /// conjunctive reading is what this already means, and equality shares the spelling rather than
  /// decomposing while seven operators cannot. The ordering operators are LEXICOGRAPHIC here, which
  /// is what makes them the instant's own order: `as_second` truncates towards zero, so the two
  /// halves never disagree in sign and comparing the pair left to right is comparing the moment.
  #[cfg(feature = "sqlite")]
  #[test]
  fn every_operator_of_an_instant_is_a_row_value() {
    use crate::comparison::sql::tests::render;

    let filter = ScalarFilter::new()
      .with_eq(at())
      .with_ne(before_epoch())
      .with_gt(at())
      .with_gte(at())
      .with_lt(at())
      .with_lte(at())
      .with_in_([at(), before_epoch()])
      .with_not_in([before_epoch()]);
    let comparison = crossed::<sqlx::Sqlite>(filter);

    assert_eq!(comparison.conjuncts(), 8);
    assert_eq!(
      render::<sqlx::Sqlite, _>("at", &comparison),
      (
        "(\"at_secs\", \"at_nanos\") = (?, ?) AND \
         NOT ( (\"at_secs\", \"at_nanos\") = (?, ?) ) AND \
         (\"at_secs\", \"at_nanos\") > (?, ?) AND \
         (\"at_secs\", \"at_nanos\") >= (?, ?) AND \
         (\"at_secs\", \"at_nanos\") < (?, ?) AND \
         (\"at_secs\", \"at_nanos\") <= (?, ?) AND \
         (\"at_secs\", \"at_nanos\") IN ((?, ?), (?, ?)) AND \
         NOT ( (\"at_secs\", \"at_nanos\") IN ((?, ?)) )"
          .to_owned(),
        // TWO binds per operand, and nine operands: the count is the half the text cannot show.
        18
      )
    );
  }

  /// **The membership does NOT decompose**, which is the wrongness `SqlKeyIn` names one kind over:
  /// `"at_secs" IN (?, ?) AND "at_nanos" IN (?, ?)` binds the same four operands, renders without an
  /// error, and admits the two pairs nobody asked for. The row-value list is what asks the question
  /// that was written.
  #[cfg(feature = "sqlite")]
  #[test]
  fn an_instants_membership_is_the_pairs_and_not_their_product() {
    use crate::comparison::sql::tests::render;

    let (sql, binds) = render::<sqlx::Sqlite, _>(
      "at",
      &crossed::<sqlx::Sqlite>(ScalarFilter::new().with_in_([at(), before_epoch()])),
    );

    assert_eq!(sql, "(\"at_secs\", \"at_nanos\") IN ((?, ?), (?, ?))");
    assert_eq!(binds, 4);
    assert!(
      !sql.contains(" AND "),
      "a membership that decomposed would show the conjunction here: {sql}"
    );
  }

  /// An EMPTY membership keeps [`push_subject_in`](crate::comparison::sql)'s asymmetry: `in_: []`
  /// matches no row and `not_in: []` matches every one, and neither renders a column.
  #[cfg(feature = "sqlite")]
  #[test]
  fn an_empty_instant_membership_degenerates_as_a_scalars_does() {
    use crate::comparison::sql::tests::render;

    assert_eq!(
      render::<sqlx::Sqlite, _>(
        "at",
        &crossed::<sqlx::Sqlite>(ScalarFilter::new().with_in_(Vec::<Timestamp>::new()))
      ),
      ("1 = 0".to_owned(), 0)
    );
    assert_eq!(
      render::<sqlx::Sqlite, _>(
        "at",
        &crossed::<sqlx::Sqlite>(ScalarFilter::new().with_not_in(Vec::<Timestamp>::new()))
      ),
      ("NOT ( 1 = 0 )".to_owned(), 0)
    );
  }

  /// A SCALAR is untouched by the branch: its width is the default, so it lands on the plain form
  /// and renders the bytes it always did. Beside the composite above, this is what makes the
  /// selection the TYPE's rather than a mode somebody sets.
  #[cfg(feature = "sqlite")]
  #[test]
  fn a_scalar_operand_still_names_one_column() {
    use crate::comparison::sql::tests::render;

    let comparison = SqlScalarComparison::<i64, sqlx::Sqlite>::try_from_filter(
      ScalarFilter::<i64>::new().with_lt(7i64),
    )
    .unwrap();
    assert_eq!(
      render::<sqlx::Sqlite, _>("n", &comparison),
      ("\"n\" < ?".to_owned(), 1)
    );
  }

  /// Postgres numbers its placeholders, so the row value is `($1, $2)` — and the bind count beside
  /// the text is the half that shows the pair was bound twice rather than once.
  #[cfg(feature = "postgres")]
  #[test]
  fn the_postgres_row_value_numbers_both_placeholders() {
    use crate::comparison::sql::tests::render;

    assert_eq!(
      render::<sqlx::Postgres, _>(
        "at",
        &crossed::<sqlx::Postgres>(ScalarFilter::new().with_gte(at()).with_lt(before_epoch()))
      ),
      (
        "(\"at_secs\", \"at_nanos\") >= ($1, $2) AND (\"at_secs\", \"at_nanos\") < ($3, $4)"
          .to_owned(),
        4
      )
    );
  }

  /// MySQL brackets with backticks and spells `?`, and the row value composes inside both — the same
  /// uniformity `SqlKeyIn` measured for its own list.
  #[cfg(feature = "mysql")]
  #[test]
  fn the_mysql_row_value_brackets_with_backticks() {
    use crate::comparison::sql::tests::render;

    assert_eq!(
      render::<sqlx::MySql, _>(
        "at",
        &crossed::<sqlx::MySql>(ScalarFilter::new().with_gte(at()).with_lt(before_epoch()))
      ),
      (
        "(`at_secs`, `at_nanos`) >= (?, ?) AND (`at_secs`, `at_nanos`) < (?, ?)".to_owned(),
        4
      )
    );
  }
}

/// **THE COMPOSITE LOWERING WHERE THE COMPOSITE CARRIES A DERIVED LEAF** — ingraph #455 at the FLAT
/// shape, which is the half of the repair no test held.
///
/// The module above renders a two-column citizen whose every column is value, so the identity forms
/// and the bound forms come out the same text and nothing there can tell them apart. This one
/// renders `MediaTimestamp`, where they differ: three value columns and a derived fourth that binds
/// `NULL` for an instant past the ±292-year ceiling.
///
/// # What these pin, and why the collection lane does not already pin it
///
/// The law — *a derived leaf serves the semantic order only; every structural judgment walks value
/// leaves only* — is rendered at TWO call sites. `SqlCompositeEdgeComparison` is one, and its
/// `derived_leaf` suite holds it. `SqlScalarComparison` is the other, and it was unheld: with this
/// kind's `eq`/`ne` pointed back at [`push_operand_cmp`](crate::comparison::sql::push_operand_cmp)
/// the whole crate still passed — 2464 unit tests and every media-time integration lane — so the
/// flat half of the repair could be reverted in silence. These are the tests that go red for it.
///
/// The real citizen is used rather than a hand-written shape, this lane being the one where it is
/// available: `at: { eq: … }` over a `MediaTimestamp` is what a client actually writes, and the
/// goldens below are that statement's text on all three engines.
#[cfg(all(
  feature = "mediatime",
  any(feature = "sqlite", feature = "postgres", feature = "mysql")
))]
mod derived_leaf {
  use core::num::NonZeroI32;

  use super::SqlScalarComparison;
  use crate::MediaTimestamp;

  /// The value columns of an instant at `at`, in the order the segments name them — the left-hand
  /// side every IDENTITY judgment writes.
  const VALUE: &str = "(\"at_pts\", \"at_timebase_num\", \"at_timebase_den\")";

  /// And the whole width, which is the left-hand side the four BOUND operators keep.
  const WHOLE: &str = "(\"at_pts\", \"at_timebase_num\", \"at_timebase_den\", \"at_nanos\")";

  /// An instant whose derived position exists: `90000` ticks at `1/90000` is one second in.
  fn placeable() -> MediaTimestamp {
    instant(90_000, 1, 90_000)
  }

  /// A second placeable instant, so a membership list has two distinct members.
  fn later() -> MediaTimestamp {
    instant(180_000, 1, 90_000)
  }

  /// **The instant the defect could not find.** `i64::MAX` ticks at one per second is about 292
  /// billion years, and the nanosecond product leaves `i64` long before — so the three value columns
  /// are stored exactly and the derived one holds `NULL`.
  fn unplaceable() -> MediaTimestamp {
    let extreme = instant(i64::MAX, 1, 1);
    assert!(
      extreme.to_nanos().is_err(),
      "the fixture is only a fixture while its position has nowhere to land"
    );
    extreme
  }

  fn instant(pts: i64, num: i32, den: i32) -> MediaTimestamp {
    MediaTimestamp::new(mediatime::Timestamp::new(
      pts,
      mediatime::Timebase::new(
        num,
        NonZeroI32::new(den).expect("a denominator is never zero"),
      ),
    ))
  }

  /// The comparison for one operand in a named slot, in whichever dialect the caller names.
  fn eq_of<Db>(value: MediaTimestamp) -> SqlScalarComparison<MediaTimestamp, Db> {
    let mut comparison = SqlScalarComparison::new();
    comparison.eq = Some(value);
    comparison
  }

  /// **THE SPLIT, IN ONE TEXT**: four identity operators over three columns and four bound operators
  /// over four, from one comparison so the two widths are read side by side rather than a paragraph
  /// apart.
  ///
  /// `eq`/`ne`/`in`/`notIn` ask WHICH VALUE a row holds and a derived leaf is not part of one;
  /// `gt`/`gte`/`lt`/`lte` ask where a row SITS, which is the question the derived leaf exists to
  /// answer. Both halves are asserted because the law can fail in either direction — narrowing the
  /// bound operators would put the four columns of the `ORDER BY` out of step with the predicate
  /// that resumes it.
  #[cfg(feature = "sqlite")]
  #[test]
  fn the_identity_operators_name_the_value_columns_and_the_bound_ones_name_them_all() {
    use crate::comparison::sql::tests::render;

    let mut comparison = SqlScalarComparison::<MediaTimestamp, sqlx::Sqlite>::new();
    comparison.eq = Some(placeable());
    comparison.ne = Some(later());
    comparison.gt = Some(placeable());
    comparison.gte = Some(placeable());
    comparison.lt = Some(later());
    comparison.lte = Some(later());
    comparison.in_ = Some(Box::new([placeable(), later()]));
    comparison.not_in = Some(Box::new([later()]));

    assert_eq!(comparison.conjuncts(), 8);
    assert_eq!(
      render::<sqlx::Sqlite, _>("at", &comparison),
      (
        format!(
          "{VALUE} = (?, ?, ?) AND \
           NOT ( {VALUE} = (?, ?, ?) ) AND \
           {WHOLE} > (?, ?, ?, ?) AND \
           {WHOLE} >= (?, ?, ?, ?) AND \
           {WHOLE} < (?, ?, ?, ?) AND \
           {WHOLE} <= (?, ?, ?, ?) AND \
           {VALUE} IN ((?, ?, ?), (?, ?, ?)) AND \
           NOT ( {VALUE} IN ((?, ?, ?)) )"
        ),
        // Three binds per identity operand and four per bound one: 3 + 3 + 4 × 4 + 6 + 3.
        31
      )
    );
  }

  /// **AN INSTANT PAST THE CEILING IS MATCHED BY THE VERY PAIR THAT WROTE IT — ingraph #455.**
  ///
  /// With the derived leaf in the tuple this is `(…, "at_nanos") = (?, ?, ?, NULL)`, and `NULL = NULL`
  /// is UNKNOWN rather than true — so the row is not returned by an equality against its own stored
  /// value. The bind count is asserted beside the text because the two failures look different: a
  /// fourth placeholder is the operand still spending its derived leaf, where a fourth column name is
  /// the left-hand side still asking for one.
  #[cfg(feature = "sqlite")]
  #[test]
  fn an_instant_past_the_ceiling_is_matched_by_the_pair_that_wrote_it() {
    use crate::comparison::sql::tests::render;

    let (sql, binds) = render::<sqlx::Sqlite, _>("at", &eq_of::<sqlx::Sqlite>(unplaceable()));

    assert_eq!(sql, format!("{VALUE} = (?, ?, ?)"));
    assert_eq!(
      binds, 3,
      "the derived leaf is not an operand of an identity"
    );
    assert!(
      !sql.contains("at_nanos"),
      "the derived column is absent by NAME, which is the claim the column list could satisfy by \
       accident: {sql}"
    );
    assert!(
      !sql.contains("NULL"),
      "and the `NULL` it would have bound is nowhere in the statement: {sql}"
    );
  }

  /// **THE NEGATION IS THE HALF THAT MAKES THE DEFECT LOOK LIKE MISSING DATA**, so it is pinned
  /// rather than left to follow from `eq`.
  ///
  /// `NOT ( UNKNOWN )` is UNKNOWN, not true. With the derived leaf in the tuple an unplaceable
  /// instant fails its own `eq` AND fails `ne` against anything at all — the row is in neither
  /// answer, which reads as a row that was never stored rather than as a predicate that is wrong.
  /// Over the value columns both questions are two-valued again and the row is in exactly one.
  #[cfg(feature = "sqlite")]
  #[test]
  fn a_negated_identity_over_an_unplaceable_instant_is_the_value_columns_alone() {
    use crate::comparison::sql::tests::render;

    let mut comparison = SqlScalarComparison::<MediaTimestamp, sqlx::Sqlite>::new();
    comparison.ne = Some(unplaceable());
    comparison.not_in = Some(Box::new([unplaceable(), placeable()]));

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

    assert_eq!(
      sql,
      format!("NOT ( {VALUE} = (?, ?, ?) ) AND NOT ( {VALUE} IN ((?, ?, ?), (?, ?, ?)) )")
    );
    assert_eq!(binds, 9, "three operands at three value columns each");
    assert!(!sql.contains("NULL"), "{sql}");
  }

  /// A membership list holding an unplaceable member spends the VALUE width per element, which is
  /// what the collection family's bind ceiling counts and what this family's list has to match.
  #[cfg(feature = "sqlite")]
  #[test]
  fn a_membership_holding_an_unplaceable_instant_binds_only_value_columns() {
    use crate::comparison::sql::tests::render;

    let mut comparison = SqlScalarComparison::<MediaTimestamp, sqlx::Sqlite>::new();
    comparison.in_ = Some(Box::new([unplaceable(), placeable(), later()]));

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

    assert_eq!(sql, format!("{VALUE} IN ((?, ?, ?), (?, ?, ?), (?, ?, ?))"));
    assert_eq!(binds, 9, "three elements at three value columns each");
  }

  /// **AND THE BOUND OPERATORS STILL WRITE THE KEYWORD**, which is not a leak but the semantic half
  /// of the law seen from the same fixture.
  ///
  /// A bound over an unplaceable instant is UNKNOWN and the row is outside every one of them — that
  /// is what having no position MEANS, and it is the honest answer rather than the defect. The
  /// `NULL` is WRITTEN rather than bound, which is why this spends three placeholders across four
  /// columns; asserting it here is what keeps the two arms of `MediaTimestamp`'s carrier from
  /// drifting into one.
  #[cfg(feature = "sqlite")]
  #[test]
  fn a_bound_over_an_unplaceable_instant_keeps_the_whole_width_and_writes_the_keyword() {
    use crate::comparison::sql::tests::render;

    let mut comparison = SqlScalarComparison::<MediaTimestamp, sqlx::Sqlite>::new();
    comparison.gt = Some(unplaceable());

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

    assert_eq!(sql, format!("{WHOLE} > (?, ?, ?, NULL)"));
    assert_eq!(binds, 3, "the keyword is written, not bound");
  }

  /// Postgres numbers its placeholders, and the numbering is what shows the narrowing in a form a
  /// bracket count cannot fake: three per identity operand and four per bound one, running on.
  #[cfg(feature = "postgres")]
  #[test]
  fn the_postgres_row_value_numbers_only_the_value_columns() {
    use crate::comparison::sql::tests::render;

    let mut comparison = SqlScalarComparison::<MediaTimestamp, sqlx::Postgres>::new();
    comparison.eq = Some(unplaceable());
    comparison.gt = Some(placeable());
    comparison.in_ = Some(Box::new([placeable(), later()]));

    assert_eq!(
      render::<sqlx::Postgres, _>("at", &comparison),
      (
        format!(
          "{VALUE} = ($1, $2, $3) AND \
           {WHOLE} > ($4, $5, $6, $7) AND \
           {VALUE} IN (($8, $9, $10), ($11, $12, $13))"
        ),
        13
      )
    );
  }

  /// MySQL brackets with backticks, and the row value composes inside them at the narrower width the
  /// same way — the uniformity the composite module above measures for a citizen with no derived
  /// leaf, restated for one that has.
  #[cfg(feature = "mysql")]
  #[test]
  fn the_mysql_row_value_backticks_only_the_value_columns() {
    use crate::comparison::sql::tests::render;

    let mut comparison = SqlScalarComparison::<MediaTimestamp, sqlx::MySql>::new();
    comparison.eq = Some(unplaceable());
    comparison.in_ = Some(Box::new([placeable(), later()]));

    assert_eq!(
      render::<sqlx::MySql, _>("at", &comparison),
      (
        "(`at_pts`, `at_timebase_num`, `at_timebase_den`) = (?, ?, ?) AND \
         (`at_pts`, `at_timebase_num`, `at_timebase_den`) IN ((?, ?, ?), (?, ?, ?))"
          .to_owned(),
        9
      )
    );
  }

  /// **A SCALAR IS BYTE-IDENTICAL THROUGH BOTH FORMS**, which is the claim that lets the whole
  /// roster move without a golden anywhere else in the crate changing.
  ///
  /// A scalar's `SEGMENTS` are empty, so both functions take the same early return to the plain
  /// `"col" <op> ?` spelling and neither reaches a row value at all. Asserted by rendering the two
  /// against one operand and comparing the strings, rather than by writing the expected text twice —
  /// a golden pinned in two places can be edited in two places.
  #[cfg(feature = "sqlite")]
  #[test]
  fn a_scalar_renders_byte_identically_through_both_forms() {
    use crate::{
      At, FieldName,
      comparison::sql::{push_operand_cmp, push_value_operand_cmp, tests::ROW},
    };

    let frame = At::new(&ROW).frame(FieldName::new("id"));
    let rendered = |whole: bool| {
      let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
      if whole {
        push_operand_cmp(&mut qb, frame.at(), " = ", &7i64, false);
      } else {
        push_value_operand_cmp(&mut qb, frame.at(), " = ", &7i64, false);
      }
      qb.sql().to_owned()
    };

    assert_eq!(rendered(false), rendered(true));
    assert_eq!(rendered(false), "\"id\" = ?");
  }
}

/// **THE CONFIDENCE KIND'S LOWERING, PER CARRIER** — one widthless filter, crossed into three
/// storage types, each rendering the threshold at its OWN precision.
///
/// This is the seam the ConfidenceFilter reshape put the width on. A client writes `gte: 0.1` once
/// and the column decides what that means: `0.1_f32` here, `0.1_f64` there, and the exact base-ten
/// tenth at the width that has one. The three answers are three different values, which is why the
/// assertion is written at three widths rather than at the one a fixture would reach for.
#[test]
fn one_threshold_crosses_into_each_width_at_that_widths_precision() {
  use crate::{Confidence, ConfidenceFilter, ConfidenceOperand};

  let filter = || {
    ConfidenceFilter::new()
      .with_gte(ConfidenceOperand::decimal("0.1").expect("a confidence"))
      .with_lt(ConfidenceOperand::number(1.0).expect("a confidence"))
  };

  let narrow: SqlScalarComparison<Confidence<f32>, ()> =
    TryFromFilter::try_from_filter(filter()).expect("f32 holds both");
  assert_eq!(narrow.gte(), Confidence::<f32>::new(0.1).as_ref());
  assert_eq!(narrow.lt(), Some(&Confidence::<f32>::ONE));

  let wide: SqlScalarComparison<Confidence<f64>, ()> =
    TryFromFilter::try_from_filter(filter()).expect("f64 holds both");
  assert_eq!(wide.gte(), Confidence::<f64>::new(0.1).as_ref());

  // The two widths hold two different numbers for one threshold, which is the whole point of
  // resolving the width at the COLUMN rather than at the operand.
  assert_ne!(f64::from(narrow.gte().expect("set").get()), 0.1_f64);
  assert_eq!(wide.gte().expect("set").get(), 0.1_f64);

  // The membership slots come out EMPTY, this kind having no slot for either — so a confidence
  // column's comparison is the ordinary scalar one with two conjuncts and no `IN`.
  assert_eq!(narrow.in_(), None);
  assert_eq!(narrow.not_in(), None);
  assert_eq!(narrow.conjuncts(), 2);
}

/// The EXACT width is the one that can refuse a threshold, and the refusal reaches the crossing's
/// own error rather than being rounded away inside it.
#[cfg(feature = "rust_decimal")]
#[test]
fn an_inexpressible_threshold_refuses_at_the_crossing() {
  use crate::{Confidence, ConfidenceFilter, ConfidenceOperand};

  let filter = ConfidenceFilter::new()
    .with_gte(ConfidenceOperand::decimal("0.1000000000000000000000000000001").expect("in range"));

  let refused: Result<SqlScalarComparison<Confidence<rust_decimal::Decimal>, ()>, _> =
    TryFromFilter::try_from_filter(filter);
  let why = refused.expect_err("the scale cannot carry it");
  assert_eq!(why.width(), "f128");
}