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
//! The nullable wrapper: [`SqlNullable`].

use core::{fmt::Display, marker::PhantomData};

use super::{SqlConjunction, fold_value_leaves, push_column};
use crate::{
  ColumnKind, Nullable, TryMapFilter,
  comparison::{
    At, Backend, ComplexComparison, CompositeComparison, ToDatabaseComparison, TryFromFilter,
  },
};

/// A NULLABLE column's comparison: `C`'s operators, plus the null test — which exists here and in no
/// other comparison type.
///
/// One wrapper rather than a nullable twin per kind, mirroring [`Nullable`] exactly, and it is that
/// mirroring that carries the guarantee across: a `NOT NULL` column's filter has no null test, so
/// its comparison has nowhere to put one, so `IS NULL` against a `NOT NULL` column is a query that
/// does not typecheck rather than one that matches nothing.
///
/// # Composition pins the dialect, so there is nothing to disambiguate
///
/// Emptiness and conjunct counts come through `C`, which already carries its `Db` in its own type.
/// That is the whole reason neither lowering trait below has a backend-neutral counterpart: where a
/// FILTER is ambiguous across two compiled backends, a comparison names exactly one.
///
/// # `C` is [`Sized`], and that is structural
///
/// The wrapper OWNS its inner comparison, so relaxing the bound to `?Sized` is `E0277` at the impl:
/// *the size for values of type `C` cannot be known at compilation time*. A `?Sized` comparison
/// bound would only be reachable through indirection this type does not have, and this type has
/// none because a comparison is a value the caller already holds.
///
/// # `V` IS THE COLUMN'S VALUE TYPE, and it is here so the null test knows how wide it is
///
/// `IS NULL` is a question about a COLUMN, and a composite field is not one: `at: MediaTimestamp`
/// occupies `at_pts`, `at_timebase_num`, `at_timebase_den` and `at_nanos`, and no engine has ever
/// had a column called `at`. Without the value type this wrapper rendered the field's own name and
/// produced a predicate the database refuses — reachable the moment an optional composite became
/// declarable, which is what makes the parameter part of this type rather than a refinement.
///
/// **It is the STORAGE type and not the comparison**, and the difference is which authority answers.
/// `V::SEGMENTS` is the one `const` the row's `COLUMNS`, its `CREATE TABLE`, its binds and its
/// decode all read; a comparison restating them would be a second list, and a null test rendered
/// from a second list is exactly the drift the first list exists to prevent.
///
/// A SCALAR `V` states no segments, so the test is the one column at the address — unchanged, and
/// the same shape it always had.
#[derive(Debug, Clone, PartialEq)]
pub struct SqlNullable<C, V: ?Sized> {
  pub(crate) inner: C,
  pub(crate) null: Option<bool>,
  /// The value type, carried for its [`SEGMENTS`](ColumnKind::SEGMENTS) alone.
  ///
  /// `fn() -> V` rather than `V`: the wrapper holds no value of it, so an owning marker would
  /// borrow-check and auto-trait as though it did — and a `?Sized` `V` could not be a field at all.
  pub(crate) value: PhantomData<fn() -> V>,
}

impl<C, V: ?Sized> SqlNullable<C, V> {
  /// `inner`'s operators, with the null test unset.
  #[inline]
  pub const fn new(inner: C) -> Self {
    Self {
      inner,
      null: None,
      value: PhantomData,
    }
  }

  /// The wrapped comparison — its own operators only. The null test belongs to this type.
  #[inline]
  pub const fn inner(&self) -> &C {
    &self.inner
  }

  /// The null test, when the column was asked about it.
  #[inline]
  pub const fn null(&self) -> Option<bool> {
    self.null
  }

  /// Cross a [`Nullable`] filter into this comparison, converting each OPERAND with `f`.
  ///
  /// The entry point a DECLARED converter uses, and it means here exactly what it means on every
  /// FLAT kind — `SqlEnumComparison`'s, `SqlScalarComparison`'s and the rest all take one operand
  /// and answer with the stored form. That uniformity is not a courtesy: a record's crossing spells
  /// ONE call whatever kind a column is, so a wrapper reading this argument as something else makes
  /// the declaration that reaches it fail inside its own expansion.
  ///
  /// # The composition, and the two levels it joins
  ///
  /// `f` converts an OPERAND, and the null test is not one — `IS NULL` is a question about the
  /// COLUMN rather than about a value, so it crosses untouched and no converter is ever asked about
  /// it. What `f` does reach is the wrapped filter's operands, through that kind's own
  /// [`TryMapFilter`] row; the mapped filter is then already in storage form, so the inner crossing
  /// that builds `C` is the identity one.
  ///
  /// This is [`SqlEdgeComparison::try_from_filter_with`](super::SqlEdgeComparison::try_from_filter_with)'s
  /// shape one container over. A collection's row conversion is `Vec<Domain> -> Vec<Stored>` over an
  /// element leg of `Domain -> Stored`; a nullable column's is `Option<Domain> -> Option<Stored>`
  /// over an operand leg of `Domain -> Stored`. One declaration, two levels, and the container is
  /// what decides which leg sees the `Option`.
  ///
  /// A caller whose two hops really are two functions — or one holding an inner comparison it built
  /// itself — asks [`try_from_filter_with_inner`](Self::try_from_filter_with_inner), which is what
  /// this composes.
  ///
  /// # Errors
  ///
  /// [`NullableCrossingError::Operand`] when `f` refuses an operand and
  /// [`NullableCrossingError::Inner`] when the wrapped kind's own crossing refuses. The two are
  /// independent — a kind may decline an OPERATOR this dialect cannot answer whatever the operands
  /// were — so they are two arms rather than one error the caller has to disambiguate by eye.
  pub fn try_from_filter_with<F, D, S, E>(
    filter: Nullable<F>,
    f: impl FnMut(D) -> Result<S, E>,
  ) -> Result<Self, NullableCrossingError<E, <C as TryFromFilter<F::Mapped>>::Error>>
  where
    F: TryMapFilter<D, S>,
    C: TryFromFilter<F::Mapped>,
  {
    let stored = filter
      .try_map_filter(f)
      .map_err(NullableCrossingError::Operand)?;
    Self::try_from_filter_with_inner(stored, C::try_from_filter)
      .map_err(NullableCrossingError::Inner)
  }

  /// Cross a [`Nullable`] filter into this comparison, building the inner comparison with `f`.
  ///
  /// `f` takes the whole wrapped FILTER rather than an operand, and the name says which: the null
  /// test has no operand to convert, and the inner kind's crossing is the thing that knows how to
  /// convert its own. It is the entry [`try_from_filter_with`](Self::try_from_filter_with) composes
  /// and the one a caller holding two separate hops reaches directly — the same split the collection
  /// kinds publish under `try_from_filter_with` / `try_from_filter_with_element`.
  ///
  /// # Errors
  ///
  /// Whatever `f` refuses the wrapped filter with, and nothing of this wrapper's own.
  pub fn try_from_filter_with_inner<F, E>(
    filter: Nullable<F>,
    f: impl FnOnce(F) -> Result<C, E>,
  ) -> Result<Self, E> {
    Ok(Self {
      inner: f(filter.inner)?,
      null: filter.null,
      value: PhantomData,
    })
  }
}

/// Why a [`Nullable`] filter's operands did not become storage values.
///
/// The family's fourth crossing error, and it carries
/// [`ListCrossingError`](super::ListCrossingError)'s shape minus the arms a collection has and a
/// nullable column does not: there is no cardinality to narrow and no element order for a dialect to
/// decline, so what is left is the two independent hops the single-converter crossing joins.
///
/// # The null test raises none of them
///
/// `IS NULL` and `IS NOT NULL` are ANSI, they take no operand, and both states are spelled by the
/// wrapper itself — so the wrapper contributes no arm here. Every refusal this type carries comes
/// from something below it.
///
/// `X` DEFAULTS to `E`, for the reason [`ListCrossingError`](super::ListCrossingError)'s does: the
/// value kinds cross with exactly their storage type's own conversion error, so
/// `NullableCrossingError<Infallible>` still spells the identity crossing over such a column.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NullableCrossingError<E, X = E> {
  /// An operand did not convert into the column's storage type — the converter's own error.
  Operand(E),
  /// The WRAPPED filter did not cross into its own comparison — that crossing's own error.
  ///
  /// Reachable without any operand failing: a kind may decline an OPERATOR the vocabulary can
  /// express and this dialect cannot answer, whatever the operands were.
  Inner(X),
}

impl<E: Display, X: Display> Display for NullableCrossingError<E, X> {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self {
      Self::Operand(error) => error.fmt(f),
      Self::Inner(error) => error.fmt(f),
    }
  }
}

impl<E, X> std::error::Error for NullableCrossingError<E, X>
where
  E: std::error::Error + 'static,
  X: std::error::Error + 'static,
{
  fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
    match self {
      Self::Operand(error) => Some(error),
      Self::Inner(error) => Some(error),
    }
  }
}

/// The nullable filter crosses into the nullable comparison over whatever its inner kind crosses
/// into — one impl for every kind, present and future.
///
/// # The `Option` lands HERE and nowhere below it
///
/// The storage type this impl is asked for is the COLUMN's, so a nullable column names
/// `Option<V>` — and `V` is what the inner comparison is built over. That is the whole content of
/// the `Option<V>` in the header, and without it the wrapper passed the column's storage type
/// straight down: `Option<Uuid7>` crossed into `SqlNullable<SqlScalarComparison<Option<Uuid7>, Db>>`,
/// where `eq: Some(None)` and `null: Some(true)` are two spellings of is-null. One of them is the
/// operator this wrapper exists to be the only home of; the other is an operand whose `None` no
/// lowering reads as anything but a bind of SQL `NULL`, which `=` never matches.
///
/// After it, `eq: Some(None)` is not a question with a bad answer. The slot is an `Option` of the
/// OPERAND — presence, which every slot carries — and the operand is now `Uuid7`, so the inner
/// `None` has no type to be. The second spelling is UNSPELLABLE rather than unused, which is the
/// same standard [`Nullable`] holds the filter side to: a `NOT NULL` column has no `with_null` to
/// call.
///
/// Nothing overlaps it. `Nullable<F>` is this crate's only self type on this trait that is a
/// wrapper — the flat kinds impl for `BooleanFilter`, `ScalarFilter<D>`, `TextFilter<D>`,
/// `BytesFilter<D, K>`, `EnumFilter<D>`, `ListFilter<D>`, `SetFilter<D>` and `DurationFilter`,
/// each a distinct type — so narrowing this header from `V` to `Option<V>` removes crossings and adds no ambiguity.
/// What it removes is exactly the ones that were wrong: a nullable column whose declared storage
/// type is NOT an `Option` no longer crosses at all, where before it crossed into a comparison that
/// could not express the column's own null test as anything but a value.
///
/// # A nullable column that OVERRIDES its storage type spells the `Option`
///
/// `ingraph-codegen` writes a column's stored type verbatim — the `type = "…"` override when there
/// is one, the domain type otherwise (`PersistColumn::ty`). So a nullable column with no override
/// crosses as `Option<Uuid7>` and lands here, while `#[ingraph(optional, sqlite(type =
/// "i64"))]` asks for `ToDatabaseComparison<i64, Sqlite>` and no longer resolves. The spelling that
/// does is `type = "Option<i64>"`, which is also what the column IS: nullable, stored as `i64`.
///
/// That is a refusal replacing a wrong answer rather than a capability lost. The bare override used
/// to resolve, and what it resolved to was the two-spellings shape this impl exists to remove.
/// Nothing in this repository declares the combination today, and rustc names the fix on its own —
/// *the trait `ToDatabaseComparison<i64, Sqlite>` is not implemented for
/// `Nullable<ScalarFilter<u64>>` but trait `ToDatabaseComparison<Option<_>, Sqlite>` is implemented
/// for it*.
///
/// # The two spellings, as the compiler sees them
///
/// A nullable column's operands are the column's storage type with the `Option` taken off. Both
/// blocks name a dialect where they used to name `()`, and both are gated on one: the crossing's
/// item bound promises the comparison LOWERS, `ComplexComparison` is keyed on a [`Backend`], and the
/// only backends there are, are dialects. The kind and its comparison are still declared outside the
/// crate, which is the case this pair is about.
///
#[cfg_attr(feature = "sqlite", doc = "```")]
#[cfg_attr(not(feature = "sqlite"), doc = "```ignore")]
/// use ingraph::{
///   At, Backend, ComplexComparison, Nullable,
///   comparison::{
///     ToDatabaseComparison,
///     sql::{Carrier, SqlConjunction, SqlLoweringError, SqlNullable, push_column},
///   },
/// };
///
/// // A filter kind and a comparison declared OUTSIDE this crate, which is the case the wrapper
/// // composes over.
/// struct KeyFilter;
/// struct KeyComparison<V>(Option<V>);
///
/// impl<V: Carrier<sqlx::Sqlite>, Db: Backend> ToDatabaseComparison<V, Db> for KeyFilter
/// where
///   KeyComparison<V>: ComplexComparison<Db>,
/// {
///   type Comparison = KeyComparison<V>;
/// }
///
/// impl<V: Carrier<sqlx::Sqlite>> ComplexComparison<sqlx::Sqlite> for KeyComparison<V> {
///   fn conjuncts(&self) -> usize {
///     usize::from(self.0.is_some())
///   }
///
///   fn apply<'q>(
///     &'q self,
///     at: At<'_>,
///     mut builder: SqlConjunction<'q, sqlx::Sqlite>,
///   ) -> Result<SqlConjunction<'q, sqlx::Sqlite>, SqlLoweringError> {
///     if let Some(value) = &self.0 {
///       let qb = builder.open();
///       push_column(qb, at);
///       qb.push(" = ");
///       value.push_bind(qb);
///     }
///     Ok(builder)
///   }
/// }
///
/// type Column =
///   <Nullable<KeyFilter> as ToDatabaseComparison<Option<i64>, sqlx::Sqlite>>::Comparison;
/// let _: Column = SqlNullable::new(KeyComparison::<i64>(None));
/// ```
///
/// so the is-null-as-an-operand spelling is not a question with a bad answer, it is a type that does
/// not exist (`E0308`):
///
#[cfg_attr(feature = "sqlite", doc = "```compile_fail,E0308")]
#[cfg_attr(not(feature = "sqlite"), doc = "```ignore")]
/// use ingraph::{
///   At, Backend, ComplexComparison, Nullable,
///   comparison::{
///     ToDatabaseComparison,
///     sql::{Carrier, SqlConjunction, SqlLoweringError, SqlNullable, push_column},
///   },
/// };
///
/// struct KeyFilter;
/// struct KeyComparison<V>(Option<V>);
///
/// impl<V: Carrier<sqlx::Sqlite>, Db: Backend> ToDatabaseComparison<V, Db> for KeyFilter
/// where
///   KeyComparison<V>: ComplexComparison<Db>,
/// {
///   type Comparison = KeyComparison<V>;
/// }
///
/// impl<V: Carrier<sqlx::Sqlite>> ComplexComparison<sqlx::Sqlite> for KeyComparison<V> {
///   fn conjuncts(&self) -> usize {
///     usize::from(self.0.is_some())
///   }
///
///   fn apply<'q>(
///     &'q self,
///     at: At<'_>,
///     mut builder: SqlConjunction<'q, sqlx::Sqlite>,
///   ) -> Result<SqlConjunction<'q, sqlx::Sqlite>, SqlLoweringError> {
///     if let Some(value) = &self.0 {
///       let qb = builder.open();
///       push_column(qb, at);
///       qb.push(" = ");
///       value.push_bind(qb);
///     }
///     Ok(builder)
///   }
/// }
///
/// type Column =
///   <Nullable<KeyFilter> as ToDatabaseComparison<Option<i64>, sqlx::Sqlite>>::Comparison;
/// let _: Column = SqlNullable::new(KeyComparison::<Option<i64>>(None));
/// ```
///
/// The two earn their keep only together, and they fail in opposite directions. Widening this
/// impl's header back to `V` makes `Column` resolve to `SqlNullable<KeyComparison<Option<u128>>>`,
/// which reds the FIRST block on `E0308` and makes the SECOND compile — and a `compile_fail` block
/// that compiles is a failing test. Neither block alone would notice.
///
/// # The wrapper pays nothing for the crossing's item bound, and that is the composition working
///
/// `SqlNullable<C>` lowers when `C` does, and `C` here is `F::Comparison` — which already carries
/// [`ComplexComparison<Db>`](crate::ComplexComparison) because the inner crossing promised it. So
/// this row states the DATABASE's half of the lowering bound and nothing at all about the operand,
/// exactly as the lowering impl below does. Wrapping a kind whose lowering is concrete per dialect
/// is still the same one line as wrapping a kind whose lowering is generic.
impl<F, V, Db> ToDatabaseComparison<Option<V>, Db> for Nullable<F>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
  F: ToDatabaseComparison<V, Db>,
  // The column's own width, which the null test spends: a composite is tested at its VALUE columns
  // and a scalar at the one it is. Every type that can BE an optional column already answers it —
  // the row's `COLUMNS` is built from the same `const` — so the bound narrows nothing a declaration
  // can reach and makes the wrapper's rendering provable where it is chosen.
  V: crate::ColumnKind,
{
  type Comparison = SqlNullable<F::Comparison, V>;
}

/// The empty comparison of an empty inner one — bounded on `C`, unlike the flat kinds' unbounded
/// [`Default`], because this wrapper OWNS an inner comparison and has no all-`None` state to build
/// without one. [`Nullable`] carries the same bound on the filter side for the same reason.
impl<C: Default, V: ?Sized> Default for SqlNullable<C, V> {
  #[inline]
  fn default() -> Self {
    Self::new(C::default())
  }
}

/// The crossing composes through `C`'s, and the error is `C`'s too — a null test never fails, so the
/// wrapper adds no way for the crossing to.
impl<F, C, V: ?Sized> TryFromFilter<Nullable<F>> for SqlNullable<C, V>
where
  C: TryFromFilter<F>,
{
  type Error = C::Error;

  fn try_from_filter(filter: Nullable<F>) -> Result<Self, Self::Error> {
    Self::try_from_filter_with_inner(filter, C::try_from_filter)
  }
}

/// The FIRST composite, and the one that proves the recursion: everything above composes over `C`,
/// and this is where `C` is lowered rather than only crossed.
///
/// A nested sub-comparison receives exactly the accumulator its parent was handed, which is why
/// recursion needs no state of its own and no layer needs to know its own depth. The bound says so
/// too — `C: ComplexComparison<Db>`, the same trait this impl provides, and nothing else — so a
/// wrapper around a wrapper is the same one line as a wrapper around a leaf.
///
/// ONE impl for every dialect, and the finding is stronger here than for the three flat kinds that
/// share it, because this wrapper adds ONE token to a lowering it does not otherwise touch:
///
/// - **The SQL is identical.** `IS NULL` and `IS NOT NULL` are ANSI and are spelled the same in
///   SQLite, Postgres and MySQL. That is the entire text this impl contributes.
/// - **The bounds are identical, and admit the same types.** `C: ComplexComparison<Db>` — the
///   wrapper requires nothing of the operand at all, because it has none.
///
/// Everything that could differ per dialect is INSIDE `C`, which already names its own database in
/// its own type. So this impl composes over the split rather than flattening it: wrapping a kind
/// whose lowering is concrete per dialect is the same one line as wrapping a kind whose lowering is
/// generic, and `SqlNullable<SqlTextComparison<V, Sqlite>>` reaches SQLite's own impl through `C`
/// without this file knowing there is more than one.
impl<C, V, Db> ComplexComparison<Db> for SqlNullable<C, V>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
  C: ComplexComparison<Db>,
  V: ColumnKind + ?Sized,
{
  /// The whole SUBTREE's count — `C`'s conjuncts plus this wrapper's null test — because the
  /// question a caller asks with it is whether anything at all will be rendered.
  #[inline]
  fn conjuncts(&self) -> usize {
    self.inner.conjuncts() + usize::from(self.null.is_some())
  }

  /// The inner comparison's conjuncts, then the null test — appended LAST, so a where-clause reads
  /// in the order the column's operators were declared and the null question closes it.
  ///
  /// Negation is the OPERATOR here (`IS NOT NULL`) rather than a `NOT ( … )` wrap, because SQL's
  /// three-valued logic makes those two different questions: `NOT ( col IS NULL )` is what
  /// `IS NOT NULL` means, but `NOT ( col = ? )` is UNKNOWN for a null column rather than true.
  ///
  /// The whole address passes DOWN untouched — no frame is pushed — because this wrapper is the
  /// same column of the same row as its inner: the two conjuncts name one identifier and each
  /// renders it once.
  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: Db::Builder<'q>,
  ) -> Result<Db::Builder<'q>, Db::Error> {
    let mut builder = self.inner.apply(at, builder)?;
    if let Some(null) = self.null {
      push_null_test::<Db, V>(builder.open(), at, null);
    }
    Ok(builder)
  }
}

/// **THE NULL TEST**, at one column for a scalar and over the VALUE columns for a composite.
///
/// ```text
///   scalar     "at"        IS NULL
///   composite  ("at_pts" IS NULL AND "at_timebase_num" IS NULL AND "at_timebase_den" IS NULL)
/// ```
///
/// # It is the WRITTEN form of the encoding the read already uses, and that is the whole design
///
/// An optional composite is absent when every one of its value columns is `NULL` and present when
/// none of them is — the same sentence
/// [`Assemble`](crate::Assemble)'s `Option<T>` row is written from. So the predicate is the
/// conjunction of the per-column tests, in the same direction, and a filter therefore selects
/// exactly the rows the decode would answer `None` for. Two spellings of one rule, and if they
/// disagreed a query would return rows it then refused to decode.
///
/// **The derived columns are absent from both.** `at_nanos IS NULL` is true for an instant that IS
/// stored and has no representable position, so including it would make `isNull: true` select rows
/// holding values — which is the reading the leaf bit exists to prevent.
///
/// # `IS NOT NULL` is `AND` and not `OR`, and the asymmetry is the point
///
/// The negation of *every value column is `NULL`* is *some value column is not*, which is `OR` — and
/// that is deliberately NOT what this renders. `isNull: false` asks for the rows that hold a value,
/// and a row holding one has ALL of its value columns filled; the `OR` form would additionally admit
/// the half-written rows the decode refuses by name. Both operators therefore describe rows that
/// decode, and the state between them belongs to neither — which is the same standing
/// [`PartialCompositeError`](crate::PartialCompositeError) takes on the read side.
///
/// # The parentheses are the conjunct boundary
///
/// The test is ONE conjunct of the surrounding clause — [`conjuncts`](ComplexComparison::conjuncts)
/// counts it as one — so a composite's several terms are bracketed to stay one. A scalar renders
/// bare, exactly as it always has, so no statement a scalar column produces moves.
fn push_null_test<Db, V>(qb: &mut sqlx::QueryBuilder<Db>, at: At<'_>, null: bool)
where
  Db: sqlx::Database + Backend<Buffer: Display>,
  V: ColumnKind + ?Sized,
{
  let test = if null { " IS NULL" } else { " IS NOT NULL" };
  if V::SEGMENTS.is_empty() {
    push_column(qb, at);
    qb.push(test);
    return;
  }
  qb.push("(");
  let rendered = fold_value_leaves(at, V::SEGMENTS, 0usize, &mut |written, leaf| {
    if written > 0 {
      qb.push(" AND ");
    }
    push_column(qb, leaf);
    qb.push(test);
    written + 1
  });
  // A composite with NO value column has nothing that could be absent, which is exactly what
  // `Assemble`'s own row answers for one: always present, never `None`. So the two directions are
  // not symmetric here — asking for the absent rows selects none and asking for the present ones
  // selects all — and the constants say so rather than the term being dropped, which would have
  // made `isNull: true` mean *every row*. No shipped type reaches this; it is written because the
  // walk can be handed a shape a person wrote.
  if rendered == 0 {
    qb.push(if null { "FALSE" } else { "TRUE" });
  }
  qb.push(")");
}

/// Nullability is orthogonal to how many columns a value occupies, so the wrapper is a composite
/// exactly when what it wraps is, and pushes exactly what that pushes.
///
/// Stated rather than assumed, because it is not the default: nothing makes a wrapper inherit its
/// inner's traits, and without this row `Option<Timebase>` would be unflattenable while `Timebase` was
/// not — a difference the column's declaration never asked for.
///
/// It composes over `C` the way every other row on this type does, and this one adds no text at all:
/// the null test renders at the SAME column as the inner comparison's own conjuncts, so the wrapper
/// pushes no segment and has none of its own to report.
impl<C, V, Db> CompositeComparison<Db> for SqlNullable<C, V>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
  C: CompositeComparison<Db>,
  V: ColumnKind + ?Sized,
{
  const SEGMENTS: &'static [crate::ColumnShape] = C::SEGMENTS;
}

#[cfg(test)]
mod tests;