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
use core::{fmt::Display, num::NonZeroI32};

use crate::{
  At, Backend, BindCeiling, Carrier, ComplexComparison, FieldName, RecordAddress, ScalarFilter,
  ToDatabaseComparison, TryFromFilter,
  comparison::sql::{SqlConjunction, SqlLoweringError},
};
use smol_bytes::Utf8Bytes;

use super::{SqlTimebaseComparison, TimebaseCrossingError};
use crate::primitives::mediatime::{Timebase, TimebaseFilter, tests::timebase};

/// The row every lowering here constrains: a `stream` row keyed by `id`.
///
/// Nothing below reads it — a timebase's comparison is not correlated, so it takes the row and
/// ignores it — and it is declared once rather than at each assertion for that reason. A `const` and
/// not a `let`, because [`RecordAddress`]'s key list is `&'static`: a row's address is stated beside
/// the schema that declares it rather than built per query.
const ROW: RecordAddress = RecordAddress::new(FieldName::new("stream"), &[FieldName::new("id")]);

/// The `Db` a crossing test names.
///
/// Nothing on the crossing carries a [`sqlx::Database`] bound — it is where DOMAIN values become
/// STORAGE values, and which dialect will later bind them takes no part in it — so an uninhabited
/// marker instantiates the comparison exactly as a real dialect would, and does it for every
/// dialect at once rather than for a chosen one.
enum AnyDialect {}

/// The dialect the LOWERING tests render against, and the reason it is not [`AnyDialect`].
///
/// A lowering is handed the builder its backend names, and every SQL dialect names
/// `SqlConjunction<'q, Db>` — a type bounded on [`sqlx::Database`], which a marker declared here
/// cannot be: that trait carries a connection, a transaction manager, a row and an argument buffer,
/// none of which rendering a predicate uses and none of which a test can supply.
///
/// So the two halves are asserted differently, and each in the strongest form available to it. The
/// crossing is checked for EVERY dialect, because nothing about it is dialect-specific. The
/// rendering is checked against ONE real dialect, because the alternative is asserting a conjunct
/// count against itself — and a count is exactly what a lowering naming the wrong column, or
/// dropping a half, still reports correctly.
///
/// Postgres is the one, because its placeholders are NUMBERED: `$1` and `$2` say which operand
/// reached which column, where SQLite's `?` renders the same character for both and leaves the
/// pairing invisible. That spelling is the only dialect-specific thing in the text below — the
/// column names, the operators and the joins are one spelling in all three.
///
/// What Postgres CANNOT say is whether an engine accepts the text, and the render facet's `CONCAT`
/// is exactly such a claim. `tests/timebase_citizen.rs` is where a real engine answers it.
type Dialect = sqlx::Postgres;

/// The filter's type-level map to its comparison, checked for EVERY dialect at once rather than for
/// a chosen one.
///
/// Never called, and not callable here: a call needs a concrete dialect, and which one it is, is not
/// what this asserts. The DEFINITION is the assertion — a bound added to the impl, or a projection
/// that stopped resolving, fails to compile at this signature.
///
/// The bound list is the crossing row's own, and it GREW with the row value and the render facet: a
/// membership refuses past a bind ceiling and refuses with the SQL family's own error, and an affix
/// pattern binds as a BORROWED string. Every bound here is about the DATABASE, which is the property
/// worth pinning — a caller resolving this projection knows which dialect it has, and each of the
/// three satisfies all of it.
///
/// The projection is DISCHARGED rather than assumed, which is what makes the list load-bearing: an
/// inner function demands the crossing row and this signature has to prove it from the bounds
/// above, so a bound the impl needs and this list forgets is `E0277` here. Written the other way —
/// with `TimebaseFilter: ToDatabaseComparison<…>` in this clause — the obligation would be an
/// assumption, and a stale list would compile.
#[expect(
  dead_code,
  reason = "the signature is the assertion; instantiating it would name one dialect"
)]
fn assert_the_filter_maps_to_the_comparison<Db>()
where
  Db: sqlx::Database
    + BindCeiling
    + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
  i32: Carrier<Db>,
  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
{
  // `Db: Backend` is the TRAIT's own bound rather than a second demand — `ToDatabaseComparison`
  // carries it — and it is restated here because an inner function names its obligations in full.
  fn crosses<Db: Backend, C>()
  where
    TimebaseFilter: ToDatabaseComparison<i32, Db, Comparison = C>,
  {
  }

  crosses::<Db, SqlTimebaseComparison<Db>>();
}

fn denominator(value: i32) -> NonZeroI32 {
  NonZeroI32::new(value).expect("a denominator is never zero")
}

/// The value facet's equality, over the timebase a stream DECLARED.
fn whole_eq(num: i32, den: i32) -> TimebaseFilter {
  TimebaseFilter::new().with_eq(timebase(num, den))
}

fn cross(
  filter: TimebaseFilter,
) -> Result<SqlTimebaseComparison<AnyDialect>, TimebaseCrossingError> {
  SqlTimebaseComparison::try_from_filter(filter)
}

/// The same crossing at the one dialect that can be rendered, for the tests that go on to render.
fn lower(filter: TimebaseFilter) -> SqlTimebaseComparison<Dialect> {
  SqlTimebaseComparison::try_from_filter(filter).expect("the filter is crossable")
}

/// Render `comparison` at the `field` column of [`ROW`] as a bare predicate fragment: the SQL, and
/// the number of conjuncts the ACCUMULATOR opened.
///
/// The empty lead is what makes the text an assertion about the comparison alone —
/// [`SqlConjunction`] pushes its lead before the first conjunct anything writes, and which clause
/// that opens is pinned on its own below.
///
/// `written` is the second number and the point of returning it: it is kept by the party that
/// pushes the separators, so it is independent of anything the comparison reports about itself.
fn render(comparison: &SqlTimebaseComparison<Dialect>, field: &str) -> (String, usize) {
  let mut qb = sqlx::QueryBuilder::<Dialect>::default();
  let column = At::new(&ROW).frame(FieldName::new(field));
  let written = {
    let out = SqlConjunction::with_lead(&mut qb, "");
    comparison
      .apply(column.at(), out)
      .expect("the operands are few and meet no ceiling")
      .written()
  };

  (qb.sql().as_str().to_owned(), written)
}

/// The same, applied at the TOP LEVEL: the address that names [`ROW`] and no column at all.
fn render_at_top_level(comparison: &SqlTimebaseComparison<Dialect>) -> String {
  let mut qb = sqlx::QueryBuilder::<Dialect>::default();
  {
    let out = SqlConjunction::with_lead(&mut qb, "");
    comparison
      .apply(At::new(&ROW), out)
      .expect("the operands are few and meet no ceiling");
  }

  qb.sql().as_str().to_owned()
}

/// Every scalar operator on both component halves — sixteen conjuncts.
fn every_component_operator() -> TimebaseFilter {
  TimebaseFilter::new()
    .with_numerator(
      ScalarFilter::new()
        .with_eq(1)
        .with_ne(2)
        .with_gt(3)
        .with_gte(4)
        .with_lt(5)
        .with_lte(6)
        .with_in_([7, 8])
        .with_not_in([9]),
    )
    .with_denominator(
      ScalarFilter::new()
        .with_eq(denominator(90_000))
        .with_ne(denominator(1_000))
        .with_gt(denominator(11))
        .with_gte(denominator(12))
        .with_lt(denominator(13))
        .with_lte(denominator(14))
        .with_in_([denominator(15), denominator(16)])
        .with_not_in([denominator(17)]),
    )
}

/// **The crossing DECOMPOSES and REDUCES.** A whole-value `eq` naming `2/180000` reaches the
/// comparison as `num = 1` and `den = 90000` — two operands over two columns, in lowest terms, and
/// no whole-value slot anywhere past the boundary.
///
/// Asserted on the OPERANDS the comparison holds rather than on the SQL it renders, and that is the
/// only place the reduction is visible at all: reduced and unreduced both render
/// `"timebase_num" = $1 AND "timebase_den" = $2`, differing only inside the bound values.
#[test]
fn the_crossing_decomposes_and_reduces_a_whole_value_operand() {
  let comparison = cross(whole_eq(2, 180_000)).expect("2/180000 is a timebase");

  assert_eq!(comparison.numerator().eq(), Some(&1));
  assert_eq!(comparison.denominator().eq(), Some(&90_000));
  assert_eq!(comparison.conjuncts(), 2);

  // The two operands a crossing that skipped the reduction would hold instead.
  assert_ne!(comparison.numerator().eq(), Some(&2));
  assert_ne!(comparison.denominator().eq(), Some(&180_000));
}

/// The pair a WRITE would store and the pair a QUERY binds come out of one function, so the two
/// cannot drift apart.
///
/// This is the guard the silent-miss deserves: reducing on one side only produces no error and no
/// wrong value, just a row and a predicate that never meet. Every case here is a timebase whose
/// declared spelling differs from its stored pair, because a reduced-only fixture would pass
/// against a crossing that reduced nothing.
#[test]
fn the_stored_pair_and_the_bound_pair_come_from_one_reduction() {
  for (num, den) in [(2, 180_000), (2, 4), (0, 90_000), (60_000, 2002), (8, 12)] {
    let declared = timebase(num, den);
    let (stored_num, stored_den) = declared.reduced();

    let bound = cross(TimebaseFilter::new().with_eq(declared)).expect("a timebase crosses");

    assert_eq!(bound.numerator().eq(), Some(&stored_num), "{num}/{den}");
    assert_eq!(
      bound.denominator().eq(),
      Some(&stored_den.get()),
      "{num}/{den}"
    );
    assert_ne!(
      (stored_num, stored_den.get()),
      (num, den),
      "{num}/{den} must not already be in lowest terms, or the case proves nothing"
    );
  }
}

/// Two spellings of one timebase cross to the SAME comparison, which is what makes an index on
/// `(num, den)` answer equality exactly.
#[test]
fn equal_timebases_cross_to_the_same_comparison() {
  let half = cross(whole_eq(1, 2)).expect("a timebase");
  let two_quarters = cross(whole_eq(2, 4)).expect("a timebase");

  assert_eq!(half, two_quarters);
  assert_eq!(half.numerator().eq(), Some(&1));
  assert_eq!(half.denominator().eq(), Some(&2));
}

/// A zero numerator reduces to `0/1` rather than keeping the denominator it was declared with, so
/// every "no rate" timebase is one row.
#[test]
fn a_zero_numerator_reduces_to_a_denominator_of_one() {
  let comparison = cross(whole_eq(0, 90_000)).expect("0/90000 is a timebase");

  assert_eq!(comparison.numerator().eq(), Some(&0));
  assert_eq!(comparison.denominator().eq(), Some(&1));
}

/// Both component halves cross with EVERY scalar operator, because each half is a column of its own.
/// A single column holding both would answer none of these without rewriting the predicate into an
/// expression over the combined value.
#[test]
fn both_halves_cross_with_every_operator() {
  let comparison = cross(every_component_operator()).expect("both halves are plain columns");

  assert_eq!(comparison.numerator().eq(), Some(&1));
  assert_eq!(comparison.numerator().ne(), Some(&2));
  assert_eq!(comparison.numerator().gt(), Some(&3));
  assert_eq!(comparison.numerator().gte(), Some(&4));
  assert_eq!(comparison.numerator().lt(), Some(&5));
  assert_eq!(comparison.numerator().lte(), Some(&6));
  assert_eq!(comparison.numerator().in_(), Some([7, 8].as_slice()));
  assert_eq!(comparison.numerator().not_in(), Some([9].as_slice()));

  assert_eq!(comparison.denominator().eq(), Some(&90_000));
  assert_eq!(comparison.denominator().ne(), Some(&1_000));
  assert_eq!(comparison.denominator().gt(), Some(&11));
  assert_eq!(comparison.denominator().gte(), Some(&12));
  assert_eq!(comparison.denominator().lt(), Some(&13));
  assert_eq!(comparison.denominator().lte(), Some(&14));
  assert_eq!(comparison.denominator().in_(), Some([15, 16].as_slice()));
  assert_eq!(comparison.denominator().not_in(), Some([17].as_slice()));

  assert_eq!(comparison.conjuncts(), 16);
}

/// The whole-value equality lands beside the halves' OTHER operators rather than replacing them, so
/// a filter naming both facets keeps both.
#[test]
fn a_whole_value_equality_composes_with_the_components_other_operators() {
  let comparison = cross(
    whole_eq(2, 180_000)
      .with_numerator(ScalarFilter::new().with_gte(1))
      .with_denominator(ScalarFilter::new().with_not_in([denominator(1)])),
  )
  .expect("no slot is named twice");

  assert_eq!(comparison.numerator().eq(), Some(&1));
  assert_eq!(comparison.numerator().gte(), Some(&1));
  assert_eq!(comparison.denominator().eq(), Some(&90_000));
  assert_eq!(comparison.denominator().not_in(), Some([1].as_slice()));
  assert_eq!(comparison.conjuncts(), 4);
}

/// Two equalities over one column are refused BY NAME rather than one overwriting the other, which
/// would silently keep whichever the crossing happened to write last.
#[test]
fn a_whole_value_equality_and_a_component_equality_conflict() {
  assert_eq!(
    cross(whole_eq(1, 90_000).with_numerator(ScalarFilter::new().with_eq(1))).unwrap_err(),
    TimebaseCrossingError::NumeratorConflict
  );
  assert_eq!(
    cross(whole_eq(1, 90_000).with_denominator(ScalarFilter::new().with_eq(denominator(90_000))))
      .unwrap_err(),
    TimebaseCrossingError::DenominatorConflict
  );

  // The NUMERATOR is tested first, so a filter naming both hears about that one.
  assert_eq!(
    cross(
      whole_eq(1, 90_000)
        .with_numerator(ScalarFilter::new().with_eq(1))
        .with_denominator(ScalarFilter::new().with_eq(denominator(90_000)))
    )
    .unwrap_err(),
    TimebaseCrossingError::NumeratorConflict
  );
}

/// **`in` is a ROW VALUE and never two column lists**, which is the whole reason the membership slot
/// holds a key set rather than reaching for the halves.
///
/// The rendered text is what says so: `("a", "b") IN ((…), (…))` admits exactly the two pairs, where
/// `"a" IN (…) AND "b" IN (…)` — the spelling that looks as though membership decomposes — admits
/// their CARTESIAN PRODUCT, four pairs for these operands, in valid SQL with the same bind count.
///
/// The operands REDUCE on the way in, like every other operand here.
#[test]
fn a_membership_list_lowers_as_one_row_value() {
  let comparison =
    lower(TimebaseFilter::new().with_in_(vec![timebase(2, 180_000), timebase(30_000, 1001)]));
  let (sql, written) = render(&comparison, "timebase");

  assert_eq!(
    sql,
    r#"("timebase_num", "timebase_den") IN (($1, $2), ($3, $4))"#
  );
  assert_eq!(written, 1, "a membership is ONE conjunct however many keys");
  assert_eq!(comparison.conjuncts(), written);
  assert_eq!(
    comparison.members().expect("in was asked").keys(),
    [[1, 90_000], [30_000, 1001]],
    "the keys are the reduced pairs, in the order they were sent"
  );
}

/// **`ne` and `not_in` are ONE negated row value**, because excluding a value AND excluding a set is
/// excluding their union — De Morgan, spelled as a merge rather than as two conjuncts.
#[test]
fn a_negation_and_an_exclusion_merge_into_one_predicate() {
  let comparison = lower(
    TimebaseFilter::new()
      .with_ne(timebase(1, 1000))
      .with_not_in(vec![timebase(2, 180_000)]),
  );
  let (sql, written) = render(&comparison, "timebase");

  assert_eq!(
    sql,
    r#"NOT (("timebase_num", "timebase_den") IN (($1, $2), ($3, $4)))"#
  );
  assert_eq!(written, 1);
  assert_eq!(comparison.conjuncts(), written);
  assert_eq!(
    comparison.excluded().expect("ne was asked").keys(),
    [[1, 90_000], [1, 1000]],
    "the list's keys first, then the single one appended"
  );
}

/// Each of the two negating slots alone reaches the same predicate, so `ne` is the one-key case of
/// the exclusion rather than a shape of its own.
#[test]
fn either_negating_slot_alone_reaches_the_negated_row_value() {
  for filter in [
    TimebaseFilter::new().with_ne(timebase(1, 90_000)),
    TimebaseFilter::new().with_not_in(vec![timebase(1, 90_000)]),
  ] {
    let comparison = lower(filter);

    assert_eq!(
      render(&comparison, "timebase").0,
      r#"NOT (("timebase_num", "timebase_den") IN (($1, $2)))"#
    );
    assert_eq!(
      comparison.excluded().expect("a key set").keys(),
      [[1, 90_000]]
    );
  }
}

/// An EMPTY membership list is an operand rather than an absence, and the two directions mean
/// opposite things — which the degenerate `1 = 0` renders exactly.
///
/// `in: []` asks for NO rows; `notIn: []` excludes nothing and asks for every row. Both fall out of
/// the same rendering with the negation around one of them, so neither needs a case of its own in
/// the lowering.
#[test]
fn an_empty_membership_list_keeps_its_direction() {
  let included = lower(TimebaseFilter::new().with_in_(Vec::new()));
  assert_eq!(render(&included, "timebase").0, "1 = 0");

  let excluded = lower(TimebaseFilter::new().with_not_in(Vec::new()));
  assert_eq!(render(&excluded, "timebase").0, "NOT (1 = 0)");

  assert!(!included.is_empty());
  assert!(!excluded.is_empty());
}

/// **The render facet builds its subject in SQL**, and the pattern binds rather than being spelled
/// into the text — so an operand cannot reach the statement as syntax.
///
/// The three affixes differ only in where the wildcard sits, which is asserted through the bound
/// patterns; the rendered text is one shape for all three, and that is the point of asserting it
/// once per slot.
#[test]
fn the_render_facet_matches_against_the_stored_spelling() {
  let comparison = lower(
    TimebaseFilter::new()
      .with_starts_with(Utf8Bytes::from("1/"))
      .with_ends_with(Utf8Bytes::from("90000"))
      .with_contains(Utf8Bytes::from("/9")),
  );
  let (sql, written) = render(&comparison, "timebase");

  assert_eq!(
    sql,
    concat!(
      r#"CONCAT("timebase_num", '/', "timebase_den") LIKE $1"#,
      r#" AND CONCAT("timebase_num", '/', "timebase_den") LIKE $2"#,
      r#" AND CONCAT("timebase_num", '/', "timebase_den") LIKE $3"#
    )
  );
  assert_eq!(written, 3);
  assert_eq!(comparison.conjuncts(), written);

  assert_eq!(comparison.starts_with(), Some(&Utf8Bytes::from("1/%")));
  assert_eq!(comparison.ends_with(), Some(&Utf8Bytes::from("%90000")));
  assert_eq!(comparison.contains(), Some(&Utf8Bytes::from("%/9%")));
}

/// **A pattern touches no heap**, which is the whole of what carrying [`Utf8Bytes`] instead of a
/// `String` buys — and it is asserted rather than assumed, because the property is a LENGTH one and
/// a build that changed the affix wrapping could quietly cross the inline ceiling.
///
/// The subject is two decimal integers and a slash, so the widest pattern a real timebase produces
/// is `%2147483647/2147483647%` at 23 bytes — exactly the inline capacity, and the reason the
/// ceiling was never a constraint on the alphabet. A `String` at any of these lengths is a heap
/// allocation per operand per query.
#[test]
fn a_render_pattern_stays_inside_the_inline_representation() {
  let widest = format!("{}/{}", i32::MAX, i32::MAX);

  for operand in ["1/", "/90000", "/9", "1001/30000", widest.as_str()] {
    let comparison = cross(TimebaseFilter::new().with_contains(Utf8Bytes::from(operand)))
      .expect("the alphabet is digits and a slash");
    let pattern = comparison.contains().expect("contains was asked");

    assert!(
      pattern.is_inline(),
      "`{pattern}` ({} bytes) spilled to the heap",
      pattern.len()
    );
  }
}

/// **The operand's alphabet is what removes the `ESCAPE` clause**: a character a `num/den` rendering
/// cannot hold is refused at the crossing, so no `LIKE` metacharacter ever reaches a pattern.
///
/// The three wildcards are named individually because they are the ones that would matter — an
/// unescaped `%` turns `contains: "50%"` into a match on everything beginning `50`, which is a wrong
/// result set reported as a right one. The rest of the alphabet is refused by the same rule.
#[test]
fn an_operand_outside_the_rendered_alphabet_is_refused() {
  for outside in ['%', '_', '\\', 'e', ' ', '-'] {
    let operand = Utf8Bytes::from(format!("1{outside}"));

    assert_eq!(
      cross(TimebaseFilter::new().with_contains(operand.clone())).unwrap_err(),
      TimebaseCrossingError::RenderAlphabet(outside),
      "contains: {operand:?}"
    );
    assert_eq!(
      cross(TimebaseFilter::new().with_starts_with(operand.clone())).unwrap_err(),
      TimebaseCrossingError::RenderAlphabet(outside)
    );
    assert_eq!(
      cross(TimebaseFilter::new().with_ends_with(operand)).unwrap_err(),
      TimebaseCrossingError::RenderAlphabet(outside)
    );
  }

  // The alphabet itself crosses, including an operand that is only a separator and one that is only
  // digits — a substring of a rendering need not be a rendering.
  for inside in ["1/90000", "/", "9", "0/1", "//"] {
    assert!(cross(TimebaseFilter::new().with_contains(Utf8Bytes::from(inside))).is_ok());
  }
}

/// The empty filter crosses, and to the empty comparison — a filter with nothing set is not an
/// error, it is a query that narrows nothing.
#[test]
fn the_empty_filter_crosses_to_the_empty_comparison() {
  let comparison = cross(TimebaseFilter::new()).expect("an empty filter is crossable");

  assert!(comparison.is_empty());
  assert_eq!(comparison.conjuncts(), 0);
  assert_eq!(comparison, SqlTimebaseComparison::new());
}

/// A PRESENT but empty membership list survives the crossing on the component half that takes one:
/// `in: []` asks for no rows where an absent `in_` asks for every row, and collapsing the first onto
/// the second is a different query.
#[test]
fn an_empty_component_membership_survives_the_crossing() {
  let comparison =
    cross(TimebaseFilter::new().with_numerator(ScalarFilter::new().with_in_(Vec::new())))
      .expect("an empty list has no operand to refuse");

  assert_eq!(comparison.numerator().in_(), Some([].as_slice()));
  assert!(!comparison.is_empty());
  assert_eq!(comparison.conjuncts(), 1);
}

/// `Default` delegates to `new()` rather than deriving an all-`None` construction of its own, so
/// the two cannot drift apart.
#[test]
fn default_is_the_empty_comparison() {
  assert_eq!(
    SqlTimebaseComparison::<AnyDialect>::default(),
    SqlTimebaseComparison::new()
  );
}

/// Each refusal says which part of the filter was unanswerable, which is the only half of the answer
/// that tells a client what to ask instead.
#[test]
fn each_refusal_names_the_part_it_is_about() {
  assert_eq!(
    TimebaseCrossingError::NumeratorConflict.to_string(),
    "the numerator's equality is named twice"
  );
  assert_eq!(
    TimebaseCrossingError::DenominatorConflict.to_string(),
    "the denominator's equality is named twice"
  );
  assert_eq!(
    TimebaseCrossingError::RenderAlphabet('%').to_string(),
    "a timebase renders as digits and a slash, so `%` matches no stored value"
  );
}

/// **ONE address reaches the lowering and TWO columns come out of it**, joined in the order the
/// halves are declared.
///
/// This is the assertion a lowering taking a name PER column could not make. Two parameters of one
/// type can be passed in either order, both orders render valid SQL of the same shape, and the only
/// difference is which operand was bound in which column — invisible to any assertion over the text.
/// Here there is one address and the two segments are literals in the body, so there is nothing left
/// to pass wrongly.
#[test]
fn the_lowering_derives_both_columns_from_one_address() {
  let comparison = lower(whole_eq(2, 180_000));
  let (sql, written) = render(&comparison, "timebase");

  assert_eq!(sql, r#""timebase_num" = $1 AND "timebase_den" = $2"#);
  assert_eq!(written, 2);
  assert_eq!(comparison.conjuncts(), written);
}

/// **At the TOP LEVEL every facet renders BARE** — `num` and `den`, with nothing in front of them —
/// because the top level is the EMPTY path and a segment pushed onto nothing is the whole column
/// name.
///
/// This is the case a PREFIX has no spelling for, seen from OUTSIDE the crate that owns the address:
/// a composite handed one name puts it in front of every column, so the only way to reach a bare
/// `num` is to pass a name that is not the row's — and a predicate over the row would then disagree
/// with the row's own address about which column identifies it. A [`ROW`] whose own `num` and `den`
/// columns hold its timebase is exactly that application.
///
/// The numbered placeholders carry the rest: `$1` sits at `num` and `$2` at `den`, so which operand
/// reached which column is asserted rather than inferred from the names. Every facet is here rather
/// than the equality alone, because each reaches the address by its own route — the components
/// through their frames, the key set through its own part names, and the rendering through a column
/// rendered twice.
#[test]
fn the_top_level_renders_every_facet_bare() {
  assert_eq!(
    render_at_top_level(&lower(whole_eq(2, 180_000))),
    r#""num" = $1 AND "den" = $2"#
  );
  assert_eq!(
    render_at_top_level(&lower(TimebaseFilter::new().with_in_(vec![timebase(1, 2)]))),
    r#"("num", "den") IN (($1, $2))"#
  );
  assert_eq!(
    render_at_top_level(&lower(
      TimebaseFilter::new().with_contains(Utf8Bytes::from("/9"))
    )),
    r#"CONCAT("num", '/', "den") LIKE $1"#
  );
}

/// The path is the CALLER's and the segments are the type's, so the same comparison renders under
/// whatever name the column was declared with.
///
/// Asserted with a different operator per half, which is what makes a swap visible: with both halves
/// carrying `eq` the text is symmetric and only the binds would differ.
#[test]
fn each_half_renders_under_its_own_derived_name() {
  let comparison = lower(
    TimebaseFilter::new()
      .with_numerator(ScalarFilter::new().with_gte(1))
      .with_denominator(ScalarFilter::new().with_lt(denominator(5))),
  );

  assert_eq!(
    render(&comparison, "pts_timebase").0,
    r#""pts_timebase_num" >= $1 AND "pts_timebase_den" < $2"#
  );
}

/// **[`SqlTimebaseComparison::conjuncts`] is EXACT**, asserted against the number the accumulator
/// actually opened rather than against itself.
///
/// It is what a caller decides separators by, so a wrong count renders wrong SQL — and being a
/// count, it is precisely what a lowering that named one column twice, or dropped a half, would
/// still report correctly. Two independent readings say otherwise here: the accumulator's own
/// `written`, and the joins in the text, which no single conjunct's rendering contains.
///
/// The last case is every facet at once, which is where a count could go wrong by a slot rather than
/// by a shape.
#[test]
fn the_conjunct_count_is_what_the_lowering_opens() {
  let cases = [
    (TimebaseFilter::new(), 0),
    (
      TimebaseFilter::new().with_numerator(ScalarFilter::new().with_eq(1)),
      1,
    ),
    (whole_eq(2, 180_000), 2),
    (
      whole_eq(2, 180_000)
        .with_numerator(ScalarFilter::new().with_gte(1))
        .with_denominator(ScalarFilter::new().with_not_in([denominator(1)])),
      4,
    ),
    (TimebaseFilter::new().with_in_(vec![timebase(1, 2)]), 1),
    (
      TimebaseFilter::new()
        .with_ne(timebase(1, 2))
        .with_not_in(vec![timebase(1, 3)]),
      1,
    ),
    (every_component_operator(), 16),
    (
      every_component_operator()
        .with_in_(vec![timebase(1, 2)])
        .with_ne(timebase(1, 3))
        .with_starts_with(Utf8Bytes::from("1/"))
        .with_ends_with(Utf8Bytes::from("2"))
        .with_contains(Utf8Bytes::from("/")),
      21,
    ),
  ];

  for (filter, expected) in cases {
    let comparison = lower(filter);
    let (sql, written) = render(&comparison, "timebase");

    assert_eq!(comparison.conjuncts(), expected, "{sql}");
    assert_eq!(written, expected, "{sql}");
    assert_eq!(
      sql.matches(" AND ").count(),
      expected.saturating_sub(1),
      "{sql}"
    );
  }
}

/// The clause keyword rides on the FIRST conjunct, so a comparison that renders nothing leaves a
/// statement with no clause rather than an empty one.
///
/// Both halves are needed and neither alone would notice: a lead pushed unconditionally passes the
/// first assertion, and a lowering that never opened a conjunct passes the second.
#[test]
fn the_clause_keyword_rides_on_the_first_conjunct() {
  let column = At::new(&ROW).frame(FieldName::new("timebase"));

  let mut qb = sqlx::QueryBuilder::<Dialect>::default();
  let comparison = lower(whole_eq(1, 90_000));
  {
    let out = SqlConjunction::new(&mut qb);
    comparison.apply(column.at(), out).unwrap();
  }
  assert_eq!(
    qb.sql(),
    r#" WHERE "timebase_num" = $1 AND "timebase_den" = $2"#
  );

  let mut qb = sqlx::QueryBuilder::<Dialect>::default();
  let empty = lower(TimebaseFilter::new());
  let written = {
    let out = SqlConjunction::new(&mut qb);
    empty.apply(column.at(), out).unwrap().written()
  };
  assert!(empty.is_empty());
  assert_eq!(written, 0);
  assert_eq!(qb.sql(), "");
}

/// A negated key set is an ORDINARY conjunct — its bracket opens through the same accumulator every
/// other slot opens through, so it can be the first predicate or a later one and neither it nor the
/// accumulator has to know which.
///
/// The nested rendering is what this pins: the inner accumulator leads with nothing, so no ` AND `
/// or ` WHERE ` appears inside the bracket, and the outer one closes it in the same buffer.
#[test]
fn a_negation_nests_without_leaking_its_lead() {
  let column = At::new(&ROW).frame(FieldName::new("timebase"));
  let comparison = lower(
    TimebaseFilter::new()
      .with_numerator(ScalarFilter::new().with_gt(0))
      .with_ne(timebase(1, 2)),
  );

  let mut qb = sqlx::QueryBuilder::<Dialect>::default();
  {
    let out = SqlConjunction::new(&mut qb);
    comparison.apply(column.at(), out).unwrap();
  }

  assert_eq!(
    qb.sql(),
    concat!(
      r#" WHERE "timebase_num" > $1"#,
      r#" AND NOT (("timebase_num", "timebase_den") IN (($2, $3)))"#
    )
  );
}

/// The value facet holds DOMAIN values, so two spellings of one timebase are one operand before the
/// crossing rather than after it — which is the difference from the text slot this replaced.
#[test]
fn the_value_facet_holds_timebases_rather_than_spellings() {
  let filter = TimebaseFilter::new().with_eq(timebase(2, 4));

  assert_eq!(filter.eq(), Some(&timebase(1, 2)));
  assert_eq!(
    filter.eq().map(Timebase::to_string),
    Some(String::from("2/4")),
    "and the DECLARED pair is still what it renders as"
  );
}