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
//! The storage side of a [`Timebase`] query, behind the `sqlx` feature: the comparison a
//! [`TimebaseFilter`] crosses into, and the crossing that gets it there.
//!
//! ```text
//! TimebaseFilter                          SqlTimebaseComparison<Db>
//!   eq: "2/180000"              ──►         num: eq 1        ──► WHERE "tb_num" = ?
//!   (any of the three shapes)               den: eq 90000          AND "tb_den" = ?
//!
//!   in: ["1/90000", "1/1000"]   ──►         members          ──► AND ("tb_num", "tb_den")
//!                                                                    IN ((?, ?), (?, ?))
//!
//!   ne / notIn                  ──►         excluded         ──► AND NOT (( … ) IN (( … )))
//!
//!   contains: "/90000"          ──►         contains         ──► AND CONCAT("tb_num", '/',
//!                                                                    "tb_den") LIKE ?
//!
//!   numerator: { gt: 1 }        ──►         num: gt 1        ──► AND "tb_num" > ?
//! ```
//!
//! # Both sides reduce, through one function
//!
//! [`Timebase::reduced`] is that function, and it is public so that the WRITE path uses the same
//! one — see [`storage`](super::storage), where the bind calls it. Reducing on one side only is a
//! SILENT MISS: `eq: "2/180000"` would fail to match a row written from `1/90000`, with no error and
//! no wrong value to look at, just rows that never come back. It is the failure shape an index-side
//! and query-side tokenizer disagreeing has, and it earns the same guard — a test asserting that the
//! pair a write would store and the pair a query binds are the same pair.
//!
//! What reduction buys is that storage equality IS value equality: a reduced pair is unique, so an
//! index on `(num, den)` answers `eq` exactly. What it costs is the declared spelling, which
//! [`Display`](core::fmt::Display) keeps and storage does not — and the RENDER facet is the one
//! place a client can see that cost, since what it matches against is the stored pair's rendering.
//!
//! # Every facet crosses, and the row value is why three of them can
//!
//! An earlier shape of this comparison refused `ne`, `in` and `not_in` outright, on the ground that
//! a comparison lowers into an AND accumulator and only `eq` decomposes into one. That ground was
//! real and the conclusion was too strong: what does not decompose into SEVERAL conjuncts still fits
//! in ONE, and the ROW VALUE is the spelling that puts it there.
//!
//! | facet slot | lowering | why that spelling |
//! |---|---|---|
//! | `eq` | `num = ? AND den = ?` | `(a, b) = (1, 10)` IS the conjunction — equality is the one operator that decomposes |
//! | `in` | `("num", "den") IN ((?, ?), …)` | the disjunction of conjunctions, FLAT — [`SqlKeyIn`]'s own measured spelling |
//! | `ne`, `not_in` | `NOT (( … ) IN (( … )))` | De Morgan, and it is why the two share ONE slot |
//! | `starts_with` … | `CONCAT(num, '/', den) LIKE ?` | the stored pair's rendering, built in SQL |
//! | `numerator`, `denominator` | `num > ?` | one column, one predicate — unchanged |
//!
//! **`ne` and `not_in` are ONE slot because excluding is conjunctive where including is not.**
//! `NOT (x OR y)` is `NOT x AND NOT y`, so excluding one value and excluding a set is excluding
//! their union — and the union is one `NOT IN`. That is not a shortcut: two separate `NOT IN`
//! conjuncts would render the same rows, and merging them means the ceiling below is counted once
//! against the sum rather than twice against the halves.
//!
//! The trap this shape exists to make unwritable is the one that LOOKS like it decomposes:
//! `num IN (1, 2) AND den IN (90000, 1000)` is the CARTESIAN PRODUCT, so `in: ["1/90000", "2/1000"]`
//! spelled that way also returns `1/1000` and `2/90000` — rows nobody asked for, in valid SQL of the
//! right shape with the right bind count. Nothing in the rendered text separates the two. The row
//! value is a type here rather than a rule someone follows, because [`SqlKeyIn`] is what holds the
//! operands and it has no other spelling.
//!
//! What is still refused is the ORDERING of a whole timebase, and it is refused STRUCTURALLY — no
//! slot on the filter takes one. Rational order is `num₁ · den₂` against `num₂ · den₁`, which is an
//! expression rather than a column and costs the index, and it is a different order from the stored
//! pair's lexicographic one: `1/1000` is the larger rational and the lower pair. A filter that
//! cannot express the question needs no error to refuse it with.
//!
//! # The RENDER facet builds its subject in SQL, and the alphabet is what makes that portable
//!
//! `CONCAT(num, '/', den)` is the stored pair as text, and `LIKE` over it answers the three affix
//! questions. Two properties make that one rendering rather than one per dialect:
//!
//! - **`CONCAT` is the spelling all three share.** `||` is the SQL-standard concatenation operator
//!   and is what SQLite and PostgreSQL use — and in MySQL it is LOGICAL OR unless `PIPES_AS_CONCAT`
//!   is set, so a `||` rendering would silently mean something else there. `CONCAT` is a function in
//!   all three, and coerces its integer arguments in all three.
//! - **`LIKE`'s dialect differences cannot be observed on this subject.** SQLite folds ASCII case in
//!   `LIKE` and MySQL folds by collation, which is exactly why `ingraph`'s own text kind renders
//!   three concrete lowerings and reaches for `instr` on SQLite. The subject here is two decimal
//!   integers and a slash — a string with no letters in it — so there is no case to fold and the
//!   three dialects answer alike.
//!
//! **The operand's alphabet is checked at this crossing**, and that is what removes the `ESCAPE`
//! clause the two `LIKE` dialects would otherwise need: `%`, `_` and `\` are refused before a
//! pattern is built, so no metacharacter can reach one. The refusal is not a narrowing — a rendering
//! made of `[0-9/]` cannot CONTAIN those characters, so an operand holding one names no row either
//! way. What the refusal buys over silently matching nothing is that a client hears why, and what it
//! buys over escaping is that the `ESCAPE` literal — `'\'` on Postgres, `'\\'` on MySQL, one of the
//! few places their text is genuinely not one text — never has to be spelled here.
//!
//! # ONE address arrives, and each half pushes its own segment
//!
//! [`ComplexComparison::apply`] takes an [`At`], and a timebase occupies two columns — which is not
//! the contradiction it reads as. An address carries a PATH rather than a name, so each half pushes
//! one segment onto whatever it was handed: an address at `timebase` reaches `timebase_num` and
//! `timebase_den`, and the SAME comparison applied at the TOP LEVEL reaches `num` and `den`, because
//! the top level is the EMPTY path and a segment pushed onto nothing is the whole column name. A
//! composite handed a NAME cannot render that second case at all — there is no name that produces a
//! bare `num` — which is why the address is a path and not a prefix.
//!
//! Nothing here invents a spelling rule, because nothing here spells an identifier. The segments go
//! to [`Backend::write_column`], which runs them together and brackets the result as its own family
//! does, so both the `_` and the quoting are the backend's — and whatever emits the DDL is the party
//! that has to agree with them. The segment names themselves are [`SEGMENTS`](super::storage), read
//! by the width, the bind, the decode and every lowering below.
//!
//! What the shape closes is a defect rather than a difference of taste. A lowering handed one name
//! PER column takes two parameters of one type, which can be passed in the wrong order; both orders
//! render valid SQL of the same shape, so no assertion over the rendered text can see it.
//!
//! # Why the two component slots WRAP `SqlScalarComparison` instead of restating it
//!
//! Each is eight operators over one `i32`, which is exactly what [`SqlScalarComparison<i32,
//! Db>`](SqlScalarComparison) already is. Wrapping takes `ingraph`'s rendering with it — the
//! `NOT ( … )` spelling of a negation, the `1 = 0` an empty `in` degenerates to — where a struct
//! with its own sixteen slots would have to reproduce both conventions and could drift from them. It
//! is also the only route in: the kind's slots are `pub(crate)` to `ingraph` and its constructors are
//! `new` and the crossing, so a comparison is BUILT by crossing a filter and in no other way.
//!
//! [`TimebaseFilter`]: super::TimebaseFilter

use core::fmt::{self, Display};

use smol_bytes::Utf8Bytes;

use crate::{
  At, Backend, BindCeiling, Carrier, ComplexComparison, CompositeComparison, ToDatabaseComparison,
  TryFromFilter,
  comparison::sql::{
    SqlConjunction, SqlKeyIn, SqlLoweringError, SqlScalarComparison, render_column,
  },
};

use super::{
  super::rational::Affix,
  Timebase, TimebaseFilter,
  storage::{DEN, NUM, SEGMENTS},
};

// The DIALECT this house's crossing tests render against is Postgres — its NUMBERED placeholders are
// what say which operand reached which column, where a `?` dialect can only say how many there were —
// so the module names `sqlx::Postgres` and needs that driver rather than the family root alone.
//
// The source crate carried a bare `#[cfg(test)]` here and never felt it, its own `sqlx` word arriving
// with a dialect behind it. In this crate `sqlx` is the family ROOT and a dialect is a word of its
// own, so the gate has to name the one it spells. It is the divergence the language family recorded
// on the same move — per-dialect gates replacing a single `sqlx` word — read one dialect over.
#[cfg(all(test, feature = "postgres"))]
mod tests;

/// The two column names a key set names, in the order [`SEGMENTS`](super::storage) lists them.
///
/// [`SqlKeyIn`] takes its parts as strings rather than as `FieldName`s, so this is the one place the
/// two segments are spelled in a second vocabulary — and it reads them off the shared constants
/// rather than repeating the literals, so a rename still has one home.
const PARTS: [&str; 2] = [NUM.as_str(), DEN.as_str()];

/// [`TimebaseFilter`]'s storage-side twin: the two columns a reduced timebase occupies, the
/// whole-value memberships over the pair, and the affix questions over its rendering.
///
/// Generic over the BACKEND and not one type per backend. Nothing a timebase adds is
/// dialect-specific — both halves store as `i32`, which every SQL dialect carries natively, and `Db`
/// selects that carrier at the lowering — and the render facet's own portability is argued in the
/// module docs rather than assumed. There is no carrier newtype here for the same reason: a carrier
/// owns an ENCODING a column must hold, and a reduced `i32` needs none.
pub struct SqlTimebaseComparison<Db> {
  numerator: SqlScalarComparison<i32, Db>,
  denominator: SqlScalarComparison<i32, Db>,
  members: Option<SqlKeyIn<i32, Db, 2>>,
  excluded: Option<SqlKeyIn<i32, Db, 2>>,
  starts_with: Option<Utf8Bytes>,
  ends_with: Option<Utf8Bytes>,
  contains: Option<Utf8Bytes>,
}

impl<Db> SqlTimebaseComparison<Db> {
  /// The empty comparison — no operator set on any facet.
  #[inline]
  pub const fn new() -> Self {
    Self {
      numerator: SqlScalarComparison::new(),
      denominator: SqlScalarComparison::new(),
      members: None,
      excluded: None,
      starts_with: None,
      ends_with: None,
      contains: None,
    }
  }

  /// The operators over the numerator column.
  ///
  /// Projected: the wrapped kind, never the field, so what a caller reads is
  /// `comparison.numerator().eq()` — the storage operand, in the type the column holds and REDUCED,
  /// which is not always the numerator the client spelled.
  #[inline]
  pub const fn numerator(&self) -> &SqlScalarComparison<i32, Db> {
    &self.numerator
  }

  /// The operators over the denominator column, reduced alongside the numerator.
  #[inline]
  pub const fn denominator(&self) -> &SqlScalarComparison<i32, Db> {
    &self.denominator
  }

  /// The reduced pairs this column must be one of, or [`None`] where `in` was not asked.
  #[inline]
  pub const fn members(&self) -> Option<&SqlKeyIn<i32, Db, 2>> {
    self.members.as_ref()
  }

  /// The reduced pairs this column must be NONE of — `ne` and `not_in` merged, De Morgan having made
  /// them one question.
  #[inline]
  pub const fn excluded(&self) -> Option<&SqlKeyIn<i32, Db, 2>> {
    self.excluded.as_ref()
  }

  /// The `LIKE` pattern the rendering must match as a prefix — the operand with its wildcard already
  /// on, since that is the form the bind takes.
  ///
  /// A [`Utf8Bytes`] rather than a `String`, matching the slot it came from: a pattern here is at
  /// most an operand plus two `%`, so every one this crate can build fits the inline
  /// representation and touches no heap. It derefs to `str`, so a reader wanting the text pays
  /// nothing for the choice.
  #[inline]
  pub const fn starts_with(&self) -> Option<&Utf8Bytes> {
    self.starts_with.as_ref()
  }

  /// The `LIKE` pattern the rendering must match as a suffix.
  #[inline]
  pub const fn ends_with(&self) -> Option<&Utf8Bytes> {
    self.ends_with.as_ref()
  }

  /// The `LIKE` pattern the rendering must hold.
  #[inline]
  pub const fn contains(&self) -> Option<&Utf8Bytes> {
    self.contains.as_ref()
  }

  /// True while NO operator slot is set anywhere, so a lowering would emit nothing at all.
  #[inline]
  pub const fn is_empty(&self) -> bool {
    self.numerator.is_empty()
      && self.denominator.is_empty()
      && self.members.is_none()
      && self.excluded.is_none()
      && self.starts_with.is_none()
      && self.ends_with.is_none()
      && self.contains.is_none()
  }

  /// How many conjuncts this comparison lowers to.
  ///
  /// EXACT, and the two column halves report their own rather than this type keeping a number: what
  /// the lowering opens is what each half opens, so there is no arithmetic here that could describe a
  /// different rendering than the one that happens. Each whole-value and affix slot is exactly ONE —
  /// a row-value membership is one predicate however many keys it holds, and a negation is one
  /// bracket around one.
  #[inline]
  pub const fn conjuncts(&self) -> usize {
    self.numerator.conjuncts()
      + self.denominator.conjuncts()
      + self.members.is_some() as usize
      + self.excluded.is_some() as usize
      + self.starts_with.is_some() as usize
      + self.ends_with.is_some() as usize
      + self.contains.is_some() as usize
  }
}

/// The lowering.
///
/// # The bound grew when the row value arrived, and it grew to the SQL family's own
///
/// An earlier shape asked only that a HALF lowers, because both halves did all of the writing. The
/// membership slots render text of their own through [`SqlKeyIn`], and the affix slots render a
/// `CONCAT` — so this type now needs what those need: a bind ceiling to refuse past, the family's own
/// lowering error to refuse WITH, and a buffer a rendered column name can be pushed out of.
///
/// It is [`SqlKeyIn`]'s own bound list, which is the SQL family's, plus one seat of this type's own:
/// a BORROWED `str` binds. The narrowing costs nothing a caller has — a declaration reaching this
/// comparison holds one of the three dialects, and each satisfies every row of it.
///
/// # The text seat is `&str` rather than `String: Carrier<Db>`, and it is the same capability
///
/// `ingraph`'s `String` row IS `qb.push_bind(self.as_str())` — the family binds a borrowed string
/// and owns one only because the row is keyed on the owned type. There is no `Carrier` row for
/// `str` or for [`Utf8Bytes`], so naming the owned one would have meant HOLDING a `String` in the
/// slots above purely to satisfy a bound, which is the allocation those slots exist not to make.
/// Naming what the bind actually spends is also the wider seat: a dialect able to bind a borrowed
/// string qualifies whether or not the framework has written it an owned row.
impl<Db> ComplexComparison<Db> for SqlTimebaseComparison<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>,
{
  #[inline]
  fn conjuncts(&self) -> usize {
    Self::conjuncts(self)
  }

  /// The component halves, then the memberships, then the affixes — into the one accumulator all of
  /// them are handed.
  ///
  /// Each half is applied one segment below `at`, and those two segments are the whole of what this
  /// layer contributes: `num` and `den` belong to a timebase's SHAPE rather than to a table, and
  /// where the pair sits is whatever the caller addressed. A frame is bound to a local first because
  /// the child address BORROWS its path from it, so the link has to outlive the `apply` it is handed
  /// to.
  ///
  /// The accumulator passes through every slot in turn, which is what keeps the groups in one
  /// clause: each opens its conjuncts through the same counter the last one did, so the ` AND `
  /// between them is the accumulator's and no slot's.
  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: Db::Builder<'q>,
  ) -> Result<Db::Builder<'q>, Db::Error> {
    let num = at.frame(NUM);
    let builder = self.numerator.apply(num.at(), builder)?;
    let den = at.frame(DEN);
    let builder = self.denominator.apply(den.at(), builder)?;

    // The key set pushes ITS OWN frames, from `PARTS` — the same two names, reached the way that
    // kind reaches them — so it is handed the address unchanged.
    let mut builder = match &self.members {
      Some(members) => members.apply(at, builder)?,
      None => builder,
    };

    if let Some(excluded) = &self.excluded {
      builder = negated(excluded, at, builder)?;
    }

    // Rendered ONCE for the three slots that each name both columns twice over.
    let rendering =
      self.starts_with.is_some() || self.ends_with.is_some() || self.contains.is_some();
    if rendering {
      let num = render_column::<Db>(at.frame(NUM).at());
      let den = render_column::<Db>(at.frame(DEN).at());

      for pattern in [&self.starts_with, &self.ends_with, &self.contains]
        .into_iter()
        .flatten()
      {
        let qb = builder.open();
        qb.push("CONCAT(");
        qb.push(&num);
        qb.push(", '/', ");
        qb.push(&den);
        qb.push(") LIKE ");
        // Bound as a BORROWED `str`, which is what `ingraph`'s own `String` carrier row spends
        // (`qb.push_bind(self.as_str())`) — reached directly here because the family has no
        // `Carrier` row for a borrowed string or for `Utf8Bytes`, and going through the row it does
        // have would mean owning a `String` this slot deliberately does not hold.
        qb.push_bind(pattern.as_str());
      }
    }

    Ok(builder)
  }
}

/// `NOT ( … )` around a key set's own rendering.
///
/// The nested accumulator leads with `""` rather than ` WHERE ` or ` AND `, which is exactly what
/// that constructor is for: what goes inside the bracket is a bare PREDICATE and not a clause. The
/// outer conjunct is opened here, so the negation is an ordinary member of the surrounding `AND`
/// chain and neither this function nor the key set has to know whether it is the first.
fn negated<'q, Db>(
  keys: &'q SqlKeyIn<i32, Db, 2>,
  at: At<'_>,
  mut builder: SqlConjunction<'q, Db>,
) -> Result<SqlConjunction<'q, Db>, SqlLoweringError>
where
  Db: sqlx::Database
    + BindCeiling
    + for<'a> Backend<Builder<'a> = SqlConjunction<'a, Db>, Error = SqlLoweringError, Buffer: Display>,
  i32: Carrier<Db>,
{
  let qb = builder.open();
  qb.push("NOT (");
  // REBORROWED, so the nested accumulator's borrow ends with the statement and the bracket below is
  // closed through the same buffer it opened. Its own return value is that borrow and is dropped
  // here for exactly that reason.
  let _ = keys.apply(at, SqlConjunction::with_lead(&mut *qb, ""))?;
  qb.push(")");

  Ok(builder)
}

/// The one place both column lists a timebase spans are stated, read by the predicate and by
/// whatever emits the DDL.
///
/// The entries are [`ColumnShape`](crate::ColumnShape)s rather than words, and each is its own
/// PART's type answering — so a timebase whose parts were themselves composite would describe itself
/// here without this declaration changing shape.
impl<Db> CompositeComparison<Db> for SqlTimebaseComparison<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>,
{
  const SEGMENTS: &'static [crate::ColumnShape] = SEGMENTS;
}

impl<Db> Default for SqlTimebaseComparison<Db> {
  #[inline]
  fn default() -> Self {
    Self::new()
  }
}

/// Written out rather than derived, for the reason `ingraph`'s own comparison kinds write theirs
/// out: a derive would bound `Db`, which is a marker no dialect type implements anything for.
impl<Db> fmt::Debug for SqlTimebaseComparison<Db> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("SqlTimebaseComparison")
      .field("numerator", &self.numerator)
      .field("denominator", &self.denominator)
      .field("members", &self.members)
      .field("excluded", &self.excluded)
      .field("starts_with", &self.starts_with)
      .field("ends_with", &self.ends_with)
      .field("contains", &self.contains)
      .finish()
  }
}

impl<Db> Clone for SqlTimebaseComparison<Db> {
  fn clone(&self) -> Self {
    Self {
      numerator: self.numerator.clone(),
      denominator: self.denominator.clone(),
      members: self.members.clone(),
      excluded: self.excluded.clone(),
      starts_with: self.starts_with.clone(),
      ends_with: self.ends_with.clone(),
      contains: self.contains.clone(),
    }
  }
}

impl<Db> PartialEq for SqlTimebaseComparison<Db> {
  fn eq(&self, other: &Self) -> bool {
    self.numerator == other.numerator
      && self.denominator == other.denominator
      && self.members == other.members
      && self.excluded == other.excluded
      && self.starts_with == other.starts_with
      && self.ends_with == other.ends_with
      && self.contains == other.contains
  }
}

/// Every SQL dialect takes the timebase filter to the timebase comparison, and the storage type is
/// `i32` rather than a parameter: both halves of a timebase are `i32` by construction, so a
/// declaration naming any other column type gets no impl and does not compile. One `V` covers two
/// columns without compromise here, because the two hold the same type.
///
/// The `Db: sqlx::Database` bound is what leaves room beside this for a `MongoTimebaseComparison` —
/// nothing may implement `sqlx::Database` for a future local `Mongo` marker, so the two impls cannot
/// overlap.
///
/// # The rest of the bounds are the LOWERING's, restated
///
/// [`ToDatabaseComparison::Comparison`] promises [`ComplexComparison`], so this row has to PROVE it
/// rather than assume it — and what proves it is the impl above, whose list this is. Stated as the
/// DIALECT's capabilities rather than as `SqlTimebaseComparison<Db>: ComplexComparison<Db>` because
/// this is the row a generated where-struct resolves a projection through: a bound naming a
/// comparison type would make this the one column whose crossing a caller cannot satisfy by knowing
/// which database it has.
impl<Db> ToDatabaseComparison<i32, Db> for TimebaseFilter
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>,
{
  type Comparison = SqlTimebaseComparison<Db>;
}

/// **The same comparison, keyed by the CITIZEN rather than by the column type its halves land in** —
/// the row that lets `#[ingraph::record]` take a field declared `Timebase` where an author
/// previously had to hand-flatten it into a `num`/`den` pair.
///
/// The row above answers for `i32`, which is what a HAND-FLATTENED declaration names: an author who
/// writes `timebase_num: i32` and hangs this filter on it is asking about one column, and the map
/// keyed by that column's type is what serves them. A field declared at the citizen's OWN type asks
/// the identical question of the identical columns — [`ColumnKind::SEGMENTS`](crate::ColumnKind)
/// spans the same two and the lowering descends into them by PATH — so the projection is the SAME
/// comparison, and this row adds a KEY rather than a behaviour. Nothing about the rendered SQL moves.
///
/// **The two rows cannot overlap**, which is what makes holding both sound: `V` is the map's first
/// parameter, and [`Timebase`] is a local newtype that is not `i32`. A declaration reaches exactly
/// one of them, decided by the type its author wrote.
impl<Db> ToDatabaseComparison<Timebase, Db> for TimebaseFilter
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>,
{
  type Comparison = SqlTimebaseComparison<Db>;
}

/// The crossing, and the only route into a [`SqlTimebaseComparison`].
///
/// [`TryFromFilter`] and never [`FromFilter`](crate::FromFilter): the render facet's alphabet is
/// checked here, so the crossing can fail, and an infallible half would in any case collide with the
/// blanket that lifts one into the other.
///
/// # No `Db` bound
///
/// The crossing turns domain values into storage values, and which dialect eventually binds them
/// takes no part in that — the dialect is selected at the LOWERING, by `i32: Carrier<Db>`. So this
/// impl holds for every `Db`, including one that is not a database at all.
impl<Db> TryFromFilter<TimebaseFilter> for SqlTimebaseComparison<Db> {
  type Error = TimebaseCrossingError;

  fn try_from_filter(filter: TimebaseFilter) -> Result<Self, Self::Error> {
    // Destructured rather than read through the getters: every operand is moved into the crossing
    // whole, so nothing here copies a `Box<[…]>` that a membership list already allocated.
    let TimebaseFilter {
      eq,
      ne,
      in_,
      not_in,
      starts_with,
      ends_with,
      contains,
      numerator,
      denominator,
    } = filter;

    // A component slot is OPTIONAL on the wire, and an absent one asks nothing — which is the empty
    // filter, exactly what the hand-written parse this replaced wrote for a key a client omitted.
    let mut numerator = numerator.unwrap_or_default();
    let mut denominator = denominator.unwrap_or_default();

    if let Some(whole) = eq {
      // A whole-value equality lands in the halves' OWN equality slots, and a slot holds one
      // operand. Two equalities over one column are either a restatement or a contradiction, and
      // assigning over the top would silently keep whichever was written last.
      if numerator.eq().is_some() {
        return Err(TimebaseCrossingError::NumeratorConflict);
      }
      if denominator.eq().is_some() {
        return Err(TimebaseCrossingError::DenominatorConflict);
      }

      let (num, den) = whole.reduced();
      numerator = numerator.with_eq(num);
      denominator = denominator.with_eq(den);
    }

    let members = in_.map(|list| SqlKeyIn::new(PARTS, keys(&list)));

    // De Morgan: excluding one value AND excluding a set is excluding their union, so the two slots
    // are one key set. An `ne` with no `not_in` is the one-key case of the same predicate.
    let excluded = match (ne, not_in) {
      (None, None) => None,
      (single, list) => {
        let mut keys = keys(list.as_deref().unwrap_or_default());
        if let Some(single) = single {
          let (num, den) = single.reduced();
          keys.push([num, den.get()]);
        }
        Some(SqlKeyIn::new(PARTS, keys))
      }
    };

    Ok(Self {
      numerator: infallible(SqlScalarComparison::try_from_filter(numerator)),
      denominator: infallible(SqlScalarComparison::try_from_filter(denominator)),
      members,
      excluded,
      starts_with: affix(starts_with.as_deref(), Affix::Prefix)?,
      ends_with: affix(ends_with.as_deref(), Affix::Suffix)?,
      contains: affix(contains.as_deref(), Affix::Contains)?,
    })
  }
}

/// The reduced pairs a membership list becomes, in the order the operands were sent.
///
/// A `Vec` rather than a boxed slice, because the exclusion path appends `ne`'s own key to it. The
/// list is NOT de-duplicated: two operands that reduce to one pair are one row of the `IN` list
/// either way, and removing them would cost a sort or a set to save a bind on an input nobody sends.
fn keys(operands: &[Timebase]) -> Vec<[i32; 2]> {
  operands
    .iter()
    .map(|operand| {
      let (num, den) = operand.reduced();
      [num, den.get()]
    })
    .collect()
}

/// One affix operand as a pattern, with the shared gate's refusal wearing THIS citizen's error.
///
/// The alphabet rule and the builder are [`rational::pattern`](super::super::rational), which the
/// rate citizen spends too — one place for the property that no `LIKE` metacharacter can reach a
/// pattern. What stays here is the sentence a client filtering TIMEBASES is told.
fn affix(operand: Option<&str>, affix: Affix) -> Result<Option<Utf8Bytes>, TimebaseCrossingError> {
  super::super::rational::pattern(operand, affix).map_err(TimebaseCrossingError::RenderAlphabet)
}

/// The two halves cross with `Error = Infallible` — `i32: TryFrom<i32>` through std's reflexive
/// blanket, `i32: TryFrom<NonZeroI32>` through that type's `From`. Matched out rather than
/// unwrapped, so the impossibility stays the compiler's and never becomes a panic that cannot fire.
fn infallible<T>(crossed: Result<T, core::convert::Infallible>) -> T {
  match crossed {
    Ok(crossed) => crossed,
    Err(never) => match never {},
  }
}

/// A [`TimebaseFilter`] did not reach the two columns, and this says which part of it did not.
///
/// One variant per way a facet can refuse, rather than one opaque error: the filter came from a
/// client, and which part was unanswerable is the only half of the answer that tells the client what
/// to ask instead.
///
/// It is three variants where it was seven, and the four that went are the measure of what the row
/// value bought: `ne`, `in` and `not_in` are answered rather than refused, and the affix operators
/// are answered over a rendering rather than refused for want of one. What is left is the two ways
/// of naming one column's equality twice, and the one operand a rendering cannot contain.
///
/// [`TimebaseFilter`]: super::TimebaseFilter
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TimebaseCrossingError {
  /// `eq` and `numerator`'s own `eq` both name the numerator's equality, and the column has one.
  NumeratorConflict,
  /// `eq` and `denominator`'s own `eq` both name the denominator's equality, and the column has one.
  DenominatorConflict,
  /// An affix operand holds a character a `num/den` rendering cannot — carrying the first one found.
  RenderAlphabet(char),
}

impl fmt::Display for TimebaseCrossingError {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      Self::NumeratorConflict => f.write_str("the numerator's equality is named twice"),
      Self::DenominatorConflict => f.write_str("the denominator's equality is named twice"),
      Self::RenderAlphabet(outside) => write!(
        f,
        "a timebase renders as digits and a slash, so `{outside}` matches no stored value"
      ),
    }
  }
}

impl core::error::Error for TimebaseCrossingError {}