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
//! The storage side of a [`LanguageId`] query, behind the `sqlx` feature: the comparison a
//! [`LanguageIdFilter`] crosses into, and the crossing that gets it there.
//!
//! ```text
//! LanguageIdFilter                       SqlLanguageIdComparison<Db>
//!   eq: "de-DE"              ──►           language: eq de    ──►  WHERE "l" = ?
//!                                          script:   IS NULL   AND "s" IS NULL
//!                                          region:   eq DE     AND "r" = ?
//!                                          rest:     IS NULL   AND "t" IS NULL
//!
//!   language: { eq: "zh" }   ──►           language: eq zh    ──►  AND "l" = ?
//!   script: { isNull: true } ──►           script:   IS NULL   AND "s" IS NULL
//!
//!   in: ["de", "zh-Hans"]    ──►           members            ──►  AND (( … ) OR ( … ))
//!   ne / notIn               ──►           excluded           ──►  AND NOT (( … ) OR ( … ))
//! ```
//!
//! # `eq` DECOMPOSES and the memberships do not, which is the nullability's doing
//!
//! Equality is the one operator that decomposes conjunctively — `(a, b, c, d) = (…)` IS the
//! conjunction — so a whole-identity `eq` lands in the four column comparisons and needs no
//! spelling of its own. That is what every multi-column comparison does with equality.
//!
//! What is NOT shared is the MEMBERSHIP. A multi-column comparison whose columns are all `NOT NULL`
//! reaches for a ROW VALUE — `("num", "den") IN ((?, ?), …)` — and a row value cannot serve here,
//! because three of these four columns are nullable and SQL compares `NULL` to `NULL` as UNKNOWN
//! rather than as true. A row value would silently drop every tag with no script, which is most of
//! them.
//!
//! So a membership is a DISJUNCTION OF CONJUNCTIONS, written out: one bracket per operand, four
//! predicates inside it, `IS NULL` wherever the operand has no subtag for that seat. It is still ONE
//! conjunct of the surrounding `AND` chain, because the whole disjunction is bracketed — the shape a
//! lowering into an accumulator requires.
//!
//! **The trap this shape exists to make unwritable is the one that LOOKS like it decomposes.**
//! `"language" IN ('de', 'zh') AND "script" IN (NULL, 'Hans')` is the CARTESIAN PRODUCT, so
//! `in: ["de", "zh-Hans"]` spelled that way also returns `zh` and `de-Hans` — rows nobody asked for,
//! in valid SQL of the right shape with the right bind count. Nothing in the rendered text separates
//! the two.
//!
//! `ne` and `not_in` are ONE slot for the timebase's reason: `NOT (x OR y)` is `NOT x AND NOT y`, so
//! excluding one identity and excluding a set is excluding their union.
//!
//! **An empty membership renders `1 = 0`, and the negation of that is `NOT (1 = 0)`** — which is
//! every row, and is the right answer to *exclude nothing*. One spelling serves both directions.
//!
//! # THREE-VALUED LOGIC, and the guard the negation could not do without
//!
//! **A FILLED SEAT IS COMPARED NULL-GUARDED**: `("script" IS NOT NULL AND "script" = ?)` rather than
//! `"script" = ?`. That looks like belt and braces and is not — it is what keeps the NEGATION from
//! dropping rows that plainly satisfy it, and the bug it closes was found by an engine rather than
//! by reading.
//!
//! Unguarded, `"script" = 'Hans'` over a row whose script column is `NULL` is UNKNOWN rather than
//! false. The conjunction inherits it, the disjunction inherits it from the conjunction, and `NOT
//! UNKNOWN` is UNKNOWN — so `notIn: ["zh-Hans"]` silently drops every `zh` row, which is the exact
//! opposite of what it asks for. The guard makes each conjunct two-valued, so the whole predicate is
//! two-valued and `NOT` means what it says.
//!
//! It costs the POSITIVE direction nothing, and that is why it is rendered in both: for a plain `in`
//! an UNKNOWN conjunct and a FALSE one select the same rows, so the guard is provably a no-op there
//! and does not have to be reasoned about per direction.
//!
//! **The LANGUAGE column is NOT guarded**, and that difference carries a meaning. It is `NOT NULL`
//! for any row that has an identity at all, so the only rows it can be null on are the ones where
//! the whole field is absent — and leaving those to SQL's own rule is what keeps `ne` here answering
//! as this crate's scalar kind answers for a nullable column: a row with NO identity is not
//! selected by `ne`, because it has nothing to be unequal with. The way to ask about those rows is the null
//! test the framework's [`Nullable`](crate::Nullable) wrapper publishes one level up, which is a
//! different question with a word of its own.
//!
//! # What is REFUSED, and it is only the doubled equality
//!
//! A whole-identity `eq` fills each column's own equality, and a column has one. So naming both
//! `eq: "de-DE"` and `language: { eq: "de" }` is either a restatement or a contradiction, and
//! assigning over the top would silently keep whichever was written last. Three variants, one per
//! column that can be named twice — the tail has no component slot, so it cannot be.
//!
//! Nothing else refuses. There is no ceiling to refuse against either, and that is worth saying
//! because a membership here binds up to four values per operand: a wide `in` list is a wide `IN`
//! list in any spelling, and the operand count is the client's to choose.
//!
//! # One generic impl, and it was measured
//!
//! Every column's storage type is `String`, which is a native `TEXT` carrier in SQLite, PostgreSQL
//! and MySQL alike; the membership renders `=`, `IS NULL`, `AND`, `OR` and `NOT`, which are the same
//! five words in all three. What differs is the placeholder `sqlx::QueryBuilder` itself writes, which
//! is below the carrier. So there is nothing per-dialect to hold, and no `id/{sqlite,postgres,mysql}`
//! leaf.
//!
//! [`LanguageIdFilter`]: super::LanguageIdFilter

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

use crate::{
  At, Backend, Carrier, ComplexComparison, CompositeComparison, Nullable, ScalarFilter,
  ToDatabaseComparison, TryFromFilter,
  comparison::sql::{SqlConjunction, SqlNullable, SqlScalarComparison, render_column},
};

use super::{
  LanguageId, LanguageIdFilter,
  storage::{LANGUAGE, REGION, REST, SCRIPT, SEGMENTS},
};

// THE DIALECT GATE, and it is the house rule for a test that names one: every assertion below
// crosses a filter into `SqlLanguageIdComparison<Sqlite>`, and `sqlx::Sqlite` is a type the
// `sqlite` feature compiles. The CROSSING itself has no `Db` bound — which is exactly what the
// dialect-parity test in there asserts — so what the gate costs a lane without a driver is the
// checking of it and nothing else.
#[cfg(all(test, feature = "sqlite"))]
mod tests;

/// One column's comparison as this type holds it: the scalar operators, plus the null test the
/// three optional seats need.
type Column<Db> = SqlNullable<SqlScalarComparison<String, Db>, String>;

/// [`LanguageIdFilter`]'s storage-side twin: the four columns an identity occupies, and the two
/// whole-identity sets that cannot decompose onto them.
///
/// Generic over the BACKEND and not one type per backend — see the module docs, where the
/// uniformity is measured rather than assumed. There is no carrier newtype for any column: a carrier
/// owns an ENCODING a column must hold, and a canonical subtag is text.
pub struct SqlLanguageIdComparison<Db> {
  language: SqlScalarComparison<String, Db>,
  script: Column<Db>,
  region: Column<Db>,
  rest: Column<Db>,
  members: Option<Box<[Stored]>>,
  excluded: Option<Box<[Stored]>>,
}

/// One identity as its four stored columns — what a membership binds, and the only place this
/// module holds a value rather than a comparison.
///
/// `String` rather than the seats' own types, because what goes into the statement is the column's
/// text and a bind wants no second conversion at render time.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Stored {
  language: String,
  script: Option<String>,
  region: Option<String>,
  rest: Option<String>,
}

impl Stored {
  /// One domain identity as its columns.
  fn of(id: &LanguageId) -> Self {
    Self {
      language: String::from(id.language().as_str()),
      script: id.script().map(|script| String::from(script.as_str())),
      region: id.region().map(|region| String::from(region.as_str())),
      rest: id.rest().map(|rest| String::from(rest.as_str())),
    }
  }
}

impl<Db> SqlLanguageIdComparison<Db> {
  /// The empty comparison — no operator set on any part.
  #[inline]
  pub const fn new() -> Self {
    Self {
      language: SqlScalarComparison::new(),
      script: SqlNullable::new(SqlScalarComparison::new()),
      region: SqlNullable::new(SqlScalarComparison::new()),
      rest: SqlNullable::new(SqlScalarComparison::new()),
      members: None,
      excluded: None,
    }
  }

  /// The operators over the language column.
  ///
  /// Projected: the wrapped kind, never the field, so what a caller reads is
  /// `comparison.language().eq()` — the operand in the type the COLUMN holds, which is the `String`
  /// beneath the [`Language`](super::Language) a client sent.
  #[inline]
  pub const fn language(&self) -> &SqlScalarComparison<String, Db> {
    &self.language
  }

  /// The operators over the script column, with its null test.
  #[inline]
  pub const fn script(&self) -> &Column<Db> {
    &self.script
  }

  /// The operators over the region column, with its null test.
  #[inline]
  pub const fn region(&self) -> &Column<Db> {
    &self.region
  }

  /// The operators over the tail column, with its null test.
  ///
  /// Filled ONLY by the identity axis — the filter has no tail slot, so nothing a client writes
  /// reaches this directly. It exists because a whole-identity equality has to constrain all four
  /// seats or it is not an equality.
  #[inline]
  pub const fn rest(&self) -> &Column<Db> {
    &self.rest
  }

  /// How many whole identities the membership holds, or [`None`] where `in` was not asked.
  ///
  /// A COUNT rather than the operands, because the operands are this module's storage shape and
  /// publishing them would publish a type a caller has no use for. What a caller wants to know is
  /// whether the facet is set and how wide it is.
  #[inline]
  pub fn members(&self) -> Option<usize> {
    self.members.as_ref().map(|members| members.len())
  }

  /// How many whole identities the exclusion holds — `ne` and `not_in` merged, De Morgan having
  /// made them one question.
  #[inline]
  pub fn excluded(&self) -> Option<usize> {
    self.excluded.as_ref().map(|excluded| excluded.len())
  }
}

/// The lowering.
///
/// # The bound is the SQL family's, plus one seat of this type's own
///
/// Every column lowers through this crate's own kinds, which is what `String: Carrier<Db>` and the
/// backend row buy. The two membership slots render text of their own, so they add what that
/// costs: a buffer a rendered column name can be pushed out of, and a BORROWED `str` that binds.
///
/// The text seat is `&str` rather than `String: Carrier<Db>` for the reason every rendered text
/// seat takes one: the [`String`] carrier row IS `push_bind(self.as_str())`, so naming the owned type
/// would buy nothing the borrowed one does not, and the borrowed seat is the wider one.
impl<Db> ComplexComparison<Db> for SqlLanguageIdComparison<Db>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
  String: Carrier<Db>,
  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
{
  /// The four columns' own counts, then one per membership set.
  ///
  /// EXACT, and the columns report their own rather than this type keeping a number: a nullable
  /// column's count is its operators plus its null test, which is the framework's arithmetic and not
  /// one restated here. Each membership is exactly ONE — a bracketed disjunction is one predicate
  /// however many operands it holds, and a negation is one bracket around one.
  fn conjuncts(&self) -> usize {
    ComplexComparison::<Db>::conjuncts(&self.language)
      + ComplexComparison::<Db>::conjuncts(&self.script)
      + ComplexComparison::<Db>::conjuncts(&self.region)
      + ComplexComparison::<Db>::conjuncts(&self.rest)
      + usize::from(self.members.is_some())
      + usize::from(self.excluded.is_some())
  }

  /// The four columns, then the memberships, into the one accumulator all of them are handed.
  ///
  /// Each column is applied one segment below `at`, and those four segments are the whole of what
  /// this layer contributes: the seats belong to an identity's SHAPE rather than to a table, and
  /// where the four sit 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.
  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: Db::Builder<'q>,
  ) -> Result<Db::Builder<'q>, Db::Error> {
    let language = at.frame(LANGUAGE);
    let builder = self.language.apply(language.at(), builder)?;
    let script = at.frame(SCRIPT);
    let builder = self.script.apply(script.at(), builder)?;
    let region = at.frame(REGION);
    let builder = self.region.apply(region.at(), builder)?;
    let rest = at.frame(REST);
    let mut builder = self.rest.apply(rest.at(), builder)?;

    if let Some(members) = &self.members {
      set::<Db>(members, at, &mut builder, false);
    }
    if let Some(excluded) = &self.excluded {
      set::<Db>(excluded, at, &mut builder, true);
    }

    Ok(builder)
  }
}

/// One whole-identity set as a bracketed disjunction of four-way conjunctions, optionally negated.
///
/// The four column names are rendered ONCE and reused across every operand, which is what keeps a
/// wide `in` list from re-deriving the same four strings per row of it.
///
/// An EMPTY set renders `1 = 0`. Bare, that is *no rows*, which is what an empty `in` asks for;
/// negated it is `NOT (1 = 0)`, which is *every row*, and that is what an empty exclusion asks for.
/// One spelling, both directions.
fn set<'q, Db>(
  identities: &'q [Stored],
  at: At<'_>,
  builder: &mut SqlConjunction<'q, Db>,
  negated: bool,
) where
  Db: sqlx::Database + Backend<Buffer: Display>,
  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
{
  let language = at.frame(LANGUAGE);
  let language = render_column::<Db>(language.at());
  let script = at.frame(SCRIPT);
  let script = render_column::<Db>(script.at());
  let region = at.frame(REGION);
  let region = render_column::<Db>(region.at());
  let rest = at.frame(REST);
  let rest = render_column::<Db>(rest.at());

  let qb = builder.open();
  if negated {
    qb.push("NOT ");
  }
  qb.push("(");

  if identities.is_empty() {
    qb.push("1 = 0");
  }

  for (nth, identity) in identities.iter().enumerate() {
    if nth > 0 {
      qb.push(" OR ");
    }

    qb.push("(");
    qb.push(&language);
    qb.push(" = ");
    qb.push_bind(identity.language.as_str());

    for (column, held) in [
      (&script, &identity.script),
      (&region, &identity.region),
      (&rest, &identity.rest),
    ] {
      qb.push(" AND ");
      match held {
        // NULL-GUARDED, and the guard is what makes the NEGATION correct — see the module docs.
        // Without it, `"script" = 'Hans'` over a row whose script is NULL is UNKNOWN rather than
        // false, the disjunction inherits the UNKNOWN, and `NOT` leaves it UNKNOWN: a `zh` row
        // would be dropped by `notIn: ["zh-Hans"]`, which is a row that plainly satisfies it.
        Some(held) => {
          qb.push("(");
          qb.push(column);
          qb.push(" IS NOT NULL AND ");
          qb.push(column);
          qb.push(" = ");
          qb.push_bind(held.as_str());
          qb.push(")");
        }
        // `IS NULL` and never `= NULL`, which is the whole reason a row value could not serve here.
        None => {
          qb.push(column);
          qb.push(" IS NULL");
        }
      }
    }
    qb.push(")");
  }

  qb.push(")");
}

/// The one place all four column lists an identity spans are stated, read by the predicate and by
/// whatever emits the DDL.
impl<Db> CompositeComparison<Db> for SqlLanguageIdComparison<Db>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
  String: Carrier<Db>,
  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
{
  const SEGMENTS: &'static [crate::ColumnShape] = SEGMENTS;
}

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

/// Written out rather than derived, for the reason this crate'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 SqlLanguageIdComparison<Db> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("SqlLanguageIdComparison")
      .field("language", &self.language)
      .field("script", &self.script)
      .field("region", &self.region)
      .field("rest", &self.rest)
      .field("members", &self.members)
      .field("excluded", &self.excluded)
      .finish()
  }
}

impl<Db> Clone for SqlLanguageIdComparison<Db> {
  fn clone(&self) -> Self {
    Self {
      language: self.language.clone(),
      script: self.script.clone(),
      region: self.region.clone(),
      rest: self.rest.clone(),
      members: self.members.clone(),
      excluded: self.excluded.clone(),
    }
  }
}

impl<Db> PartialEq for SqlLanguageIdComparison<Db> {
  fn eq(&self, other: &Self) -> bool {
    self.language == other.language
      && self.script == other.script
      && self.region == other.region
      && self.rest == other.rest
      && self.members == other.members
      && self.excluded == other.excluded
  }
}

/// Every SQL dialect takes the identity filter to the identity comparison, and the storage type is
/// `String` rather than a parameter: all four columns hold text by construction, so a declaration
/// naming any other column type gets no impl and does not compile.
///
/// The `Db: sqlx::Database` bound is what leaves room beside this for a `MongoLanguageIdComparison`
/// — nothing may implement `sqlx::Database` for a future local `Mongo` marker, so the two impls
/// cannot overlap.
impl<Db> ToDatabaseComparison<String, Db> for LanguageIdFilter
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
  String: Carrier<Db>,
  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
{
  type Comparison = SqlLanguageIdComparison<Db>;
}

/// The crossing, and the only route into a [`SqlLanguageIdComparison`].
///
/// [`TryFromFilter`] rather than [`FromFilter`](crate::FromFilter), because the doubled-equality
/// refusal is real — see the module docs.
///
/// # 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 `String: Carrier<Db>`.
impl<Db> TryFromFilter<LanguageIdFilter> for SqlLanguageIdComparison<Db> {
  type Error = LanguageIdCrossingError;

  fn try_from_filter(filter: LanguageIdFilter) -> 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<[…]>` a membership list already allocated. Naming each
    // field is what makes a field added tomorrow an `E0027` rather than a facet silently not
    // crossing.
    let LanguageIdFilter {
      eq,
      ne,
      in_,
      not_in,
      language,
      script,
      region,
    } = filter;

    // A component slot is OPTIONAL on the wire, and an absent one asks nothing — which is the empty
    // filter.
    let mut language = language.unwrap_or_default();
    let mut script = script.unwrap_or_default();
    let mut region = region.unwrap_or_default();
    // The tail's seat is a `String` where the other three are their own newtypes, and the reason is
    // that it HAS no newtype: the seat is verbatim text, so what a whole-identity equality binds is
    // the column's own value with no domain type in front of it.
    let mut rest = Nullable::<ScalarFilter<String>>::default();

    if let Some(whole) = eq {
      // A whole-identity equality lands in each column's OWN equality, and a column has one. 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 language.eq().is_some() {
        return Err(LanguageIdCrossingError::LanguageConflict);
      }
      if script.inner().eq().is_some() || script.null().is_some() {
        return Err(LanguageIdCrossingError::ScriptConflict);
      }
      if region.inner().eq().is_some() || region.null().is_some() {
        return Err(LanguageIdCrossingError::RegionConflict);
      }

      language = language.with_eq(whole.language().clone());
      script = seat(script, whole.script().cloned());
      region = seat(region, whole.region().cloned());
      rest = seat(rest, whole.rest().map(|rest| String::from(rest.as_str())));
    }

    let members = in_.map(|list| stored(&list));

    // De Morgan: excluding one identity AND excluding a set is excluding their union, so the two
    // slots are one set. An `ne` with no `not_in` is the one-operand case of the same predicate.
    let excluded = match (ne, not_in) {
      (None, None) => None,
      (single, list) => {
        let mut identities = stored(list.as_deref().unwrap_or_default()).into_vec();
        if let Some(single) = single {
          identities.push(Stored::of(&single));
        }
        Some(identities.into_boxed_slice())
      }
    };

    Ok(Self {
      language: infallible(SqlScalarComparison::try_from_filter(language)),
      script: infallible(SqlNullable::try_from_filter(script)),
      region: infallible(SqlNullable::try_from_filter(region)),
      rest: infallible(SqlNullable::try_from_filter(rest)),
      members,
      excluded,
    })
  }
}

/// One optional seat of a whole-identity equality as the column filter that expresses it: an
/// equality where the seat is filled, and a NULL TEST where it is not.
///
/// The `None` arm is the half a `= NULL` would get wrong. An identity with no script is one whose
/// script COLUMN is null, so the predicate that finds it is `IS NULL` — and the framework's nullable
/// wrapper is what spells that, which is why the seat is expressed as a filter here rather than as a
/// comparison.
fn seat<T, I>(
  filter: Nullable<ScalarFilter<T, I>>,
  value: Option<T>,
) -> Nullable<ScalarFilter<T, I>> {
  match value {
    // `try_map` is the one route that hands the INNER filter out by value: `Nullable` publishes
    // `inner()` as a borrow and no owning accessor, so a wrapper cannot otherwise be rebuilt around
    // a modified inside. The closure cannot fail, hence the `Infallible` matched out below.
    Some(value) => {
      match filter.try_map(|inner| Ok::<_, core::convert::Infallible>(inner.with_eq(value))) {
        Ok(filter) => filter,
        Err(never) => match never {},
      }
    }
    None => filter.with_null(true),
  }
}

/// A list of domain identities as the columns each occupies.
fn stored(identities: &[LanguageId]) -> Box<[Stored]> {
  identities.iter().map(Stored::of).collect()
}

/// The three column crossings are `Error = Infallible` — `String: TryFrom<Language>` and its two
/// siblings through those newtypes' own `From`, and `String: TryFrom<Utf8Bytes>` likewise. 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 [`LanguageIdFilter`] did not reach the four columns, and this says which part of it did not.
///
/// Three variants, one per column a client can name twice. The tail is absent because it has no
/// component slot — the identity axis is the only thing that fills it, and one filter holds one
/// `eq`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LanguageIdCrossingError {
  /// `eq` and `language`'s own `eq` both name the language column's equality, and a column has one.
  LanguageConflict,
  /// `eq` and `script`'s own `eq` — or its `isNull` — both name what the script column must be.
  ScriptConflict,
  /// `eq` and `region`'s own `eq` — or its `isNull` — both name what the region column must be.
  RegionConflict,
}

impl fmt::Display for LanguageIdCrossingError {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    let doubled = match self {
      Self::LanguageConflict => "language",
      Self::ScriptConflict => "script",
      Self::RegionConflict => "region",
    };

    write!(f, "the {doubled} column's value is named twice")
  }
}

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