ingraph/comparison/sql/nullable.rs
1//! The nullable wrapper: [`SqlNullable`].
2
3use core::{fmt::Display, marker::PhantomData};
4
5use super::{SqlConjunction, fold_value_leaves, push_column};
6use crate::{
7 ColumnKind, Nullable, TryMapFilter,
8 comparison::{
9 At, Backend, ComplexComparison, CompositeComparison, ToDatabaseComparison, TryFromFilter,
10 },
11};
12
13/// A NULLABLE column's comparison: `C`'s operators, plus the null test — which exists here and in no
14/// other comparison type.
15///
16/// One wrapper rather than a nullable twin per kind, mirroring [`Nullable`] exactly, and it is that
17/// mirroring that carries the guarantee across: a `NOT NULL` column's filter has no null test, so
18/// its comparison has nowhere to put one, so `IS NULL` against a `NOT NULL` column is a query that
19/// does not typecheck rather than one that matches nothing.
20///
21/// # Composition pins the dialect, so there is nothing to disambiguate
22///
23/// Emptiness and conjunct counts come through `C`, which already carries its `Db` in its own type.
24/// That is the whole reason neither lowering trait below has a backend-neutral counterpart: where a
25/// FILTER is ambiguous across two compiled backends, a comparison names exactly one.
26///
27/// # `C` is [`Sized`], and that is structural
28///
29/// The wrapper OWNS its inner comparison, so relaxing the bound to `?Sized` is `E0277` at the impl:
30/// *the size for values of type `C` cannot be known at compilation time*. A `?Sized` comparison
31/// bound would only be reachable through indirection this type does not have, and this type has
32/// none because a comparison is a value the caller already holds.
33///
34/// # `V` IS THE COLUMN'S VALUE TYPE, and it is here so the null test knows how wide it is
35///
36/// `IS NULL` is a question about a COLUMN, and a composite field is not one: `at: MediaTimestamp`
37/// occupies `at_pts`, `at_timebase_num`, `at_timebase_den` and `at_nanos`, and no engine has ever
38/// had a column called `at`. Without the value type this wrapper rendered the field's own name and
39/// produced a predicate the database refuses — reachable the moment an optional composite became
40/// declarable, which is what makes the parameter part of this type rather than a refinement.
41///
42/// **It is the STORAGE type and not the comparison**, and the difference is which authority answers.
43/// `V::SEGMENTS` is the one `const` the row's `COLUMNS`, its `CREATE TABLE`, its binds and its
44/// decode all read; a comparison restating them would be a second list, and a null test rendered
45/// from a second list is exactly the drift the first list exists to prevent.
46///
47/// A SCALAR `V` states no segments, so the test is the one column at the address — unchanged, and
48/// the same shape it always had.
49#[derive(Debug, Clone, PartialEq)]
50pub struct SqlNullable<C, V: ?Sized> {
51 pub(crate) inner: C,
52 pub(crate) null: Option<bool>,
53 /// The value type, carried for its [`SEGMENTS`](ColumnKind::SEGMENTS) alone.
54 ///
55 /// `fn() -> V` rather than `V`: the wrapper holds no value of it, so an owning marker would
56 /// borrow-check and auto-trait as though it did — and a `?Sized` `V` could not be a field at all.
57 pub(crate) value: PhantomData<fn() -> V>,
58}
59
60impl<C, V: ?Sized> SqlNullable<C, V> {
61 /// `inner`'s operators, with the null test unset.
62 #[inline]
63 pub const fn new(inner: C) -> Self {
64 Self {
65 inner,
66 null: None,
67 value: PhantomData,
68 }
69 }
70
71 /// The wrapped comparison — its own operators only. The null test belongs to this type.
72 #[inline]
73 pub const fn inner(&self) -> &C {
74 &self.inner
75 }
76
77 /// The null test, when the column was asked about it.
78 #[inline]
79 pub const fn null(&self) -> Option<bool> {
80 self.null
81 }
82
83 /// Cross a [`Nullable`] filter into this comparison, converting each OPERAND with `f`.
84 ///
85 /// The entry point a DECLARED converter uses, and it means here exactly what it means on every
86 /// FLAT kind — `SqlEnumComparison`'s, `SqlScalarComparison`'s and the rest all take one operand
87 /// and answer with the stored form. That uniformity is not a courtesy: a record's crossing spells
88 /// ONE call whatever kind a column is, so a wrapper reading this argument as something else makes
89 /// the declaration that reaches it fail inside its own expansion.
90 ///
91 /// # The composition, and the two levels it joins
92 ///
93 /// `f` converts an OPERAND, and the null test is not one — `IS NULL` is a question about the
94 /// COLUMN rather than about a value, so it crosses untouched and no converter is ever asked about
95 /// it. What `f` does reach is the wrapped filter's operands, through that kind's own
96 /// [`TryMapFilter`] row; the mapped filter is then already in storage form, so the inner crossing
97 /// that builds `C` is the identity one.
98 ///
99 /// This is [`SqlEdgeComparison::try_from_filter_with`](super::SqlEdgeComparison::try_from_filter_with)'s
100 /// shape one container over. A collection's row conversion is `Vec<Domain> -> Vec<Stored>` over an
101 /// element leg of `Domain -> Stored`; a nullable column's is `Option<Domain> -> Option<Stored>`
102 /// over an operand leg of `Domain -> Stored`. One declaration, two levels, and the container is
103 /// what decides which leg sees the `Option`.
104 ///
105 /// A caller whose two hops really are two functions — or one holding an inner comparison it built
106 /// itself — asks [`try_from_filter_with_inner`](Self::try_from_filter_with_inner), which is what
107 /// this composes.
108 ///
109 /// # Errors
110 ///
111 /// [`NullableCrossingError::Operand`] when `f` refuses an operand and
112 /// [`NullableCrossingError::Inner`] when the wrapped kind's own crossing refuses. The two are
113 /// independent — a kind may decline an OPERATOR this dialect cannot answer whatever the operands
114 /// were — so they are two arms rather than one error the caller has to disambiguate by eye.
115 pub fn try_from_filter_with<F, D, S, E>(
116 filter: Nullable<F>,
117 f: impl FnMut(D) -> Result<S, E>,
118 ) -> Result<Self, NullableCrossingError<E, <C as TryFromFilter<F::Mapped>>::Error>>
119 where
120 F: TryMapFilter<D, S>,
121 C: TryFromFilter<F::Mapped>,
122 {
123 let stored = filter
124 .try_map_filter(f)
125 .map_err(NullableCrossingError::Operand)?;
126 Self::try_from_filter_with_inner(stored, C::try_from_filter)
127 .map_err(NullableCrossingError::Inner)
128 }
129
130 /// Cross a [`Nullable`] filter into this comparison, building the inner comparison with `f`.
131 ///
132 /// `f` takes the whole wrapped FILTER rather than an operand, and the name says which: the null
133 /// test has no operand to convert, and the inner kind's crossing is the thing that knows how to
134 /// convert its own. It is the entry [`try_from_filter_with`](Self::try_from_filter_with) composes
135 /// and the one a caller holding two separate hops reaches directly — the same split the collection
136 /// kinds publish under `try_from_filter_with` / `try_from_filter_with_element`.
137 ///
138 /// # Errors
139 ///
140 /// Whatever `f` refuses the wrapped filter with, and nothing of this wrapper's own.
141 pub fn try_from_filter_with_inner<F, E>(
142 filter: Nullable<F>,
143 f: impl FnOnce(F) -> Result<C, E>,
144 ) -> Result<Self, E> {
145 Ok(Self {
146 inner: f(filter.inner)?,
147 null: filter.null,
148 value: PhantomData,
149 })
150 }
151}
152
153/// Why a [`Nullable`] filter's operands did not become storage values.
154///
155/// The family's fourth crossing error, and it carries
156/// [`ListCrossingError`](super::ListCrossingError)'s shape minus the arms a collection has and a
157/// nullable column does not: there is no cardinality to narrow and no element order for a dialect to
158/// decline, so what is left is the two independent hops the single-converter crossing joins.
159///
160/// # The null test raises none of them
161///
162/// `IS NULL` and `IS NOT NULL` are ANSI, they take no operand, and both states are spelled by the
163/// wrapper itself — so the wrapper contributes no arm here. Every refusal this type carries comes
164/// from something below it.
165///
166/// `X` DEFAULTS to `E`, for the reason [`ListCrossingError`](super::ListCrossingError)'s does: the
167/// value kinds cross with exactly their storage type's own conversion error, so
168/// `NullableCrossingError<Infallible>` still spells the identity crossing over such a column.
169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170pub enum NullableCrossingError<E, X = E> {
171 /// An operand did not convert into the column's storage type — the converter's own error.
172 Operand(E),
173 /// The WRAPPED filter did not cross into its own comparison — that crossing's own error.
174 ///
175 /// Reachable without any operand failing: a kind may decline an OPERATOR the vocabulary can
176 /// express and this dialect cannot answer, whatever the operands were.
177 Inner(X),
178}
179
180impl<E: Display, X: Display> Display for NullableCrossingError<E, X> {
181 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
182 match self {
183 Self::Operand(error) => error.fmt(f),
184 Self::Inner(error) => error.fmt(f),
185 }
186 }
187}
188
189impl<E, X> std::error::Error for NullableCrossingError<E, X>
190where
191 E: std::error::Error + 'static,
192 X: std::error::Error + 'static,
193{
194 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
195 match self {
196 Self::Operand(error) => Some(error),
197 Self::Inner(error) => Some(error),
198 }
199 }
200}
201
202/// The nullable filter crosses into the nullable comparison over whatever its inner kind crosses
203/// into — one impl for every kind, present and future.
204///
205/// # The `Option` lands HERE and nowhere below it
206///
207/// The storage type this impl is asked for is the COLUMN's, so a nullable column names
208/// `Option<V>` — and `V` is what the inner comparison is built over. That is the whole content of
209/// the `Option<V>` in the header, and without it the wrapper passed the column's storage type
210/// straight down: `Option<Uuid7>` crossed into `SqlNullable<SqlScalarComparison<Option<Uuid7>, Db>>`,
211/// where `eq: Some(None)` and `null: Some(true)` are two spellings of is-null. One of them is the
212/// operator this wrapper exists to be the only home of; the other is an operand whose `None` no
213/// lowering reads as anything but a bind of SQL `NULL`, which `=` never matches.
214///
215/// After it, `eq: Some(None)` is not a question with a bad answer. The slot is an `Option` of the
216/// OPERAND — presence, which every slot carries — and the operand is now `Uuid7`, so the inner
217/// `None` has no type to be. The second spelling is UNSPELLABLE rather than unused, which is the
218/// same standard [`Nullable`] holds the filter side to: a `NOT NULL` column has no `with_null` to
219/// call.
220///
221/// Nothing overlaps it. `Nullable<F>` is this crate's only self type on this trait that is a
222/// wrapper — the flat kinds impl for `BooleanFilter`, `ScalarFilter<D>`, `TextFilter<D>`,
223/// `BytesFilter<D, K>`, `EnumFilter<D>`, `ListFilter<D>`, `SetFilter<D>` and `DurationFilter`,
224/// each a distinct type — so narrowing this header from `V` to `Option<V>` removes crossings and adds no ambiguity.
225/// What it removes is exactly the ones that were wrong: a nullable column whose declared storage
226/// type is NOT an `Option` no longer crosses at all, where before it crossed into a comparison that
227/// could not express the column's own null test as anything but a value.
228///
229/// # A nullable column that OVERRIDES its storage type spells the `Option`
230///
231/// `ingraph-codegen` writes a column's stored type verbatim — the `type = "…"` override when there
232/// is one, the domain type otherwise (`PersistColumn::ty`). So a nullable column with no override
233/// crosses as `Option<Uuid7>` and lands here, while `#[ingraph(optional, sqlite(type =
234/// "i64"))]` asks for `ToDatabaseComparison<i64, Sqlite>` and no longer resolves. The spelling that
235/// does is `type = "Option<i64>"`, which is also what the column IS: nullable, stored as `i64`.
236///
237/// That is a refusal replacing a wrong answer rather than a capability lost. The bare override used
238/// to resolve, and what it resolved to was the two-spellings shape this impl exists to remove.
239/// Nothing in this repository declares the combination today, and rustc names the fix on its own —
240/// *the trait `ToDatabaseComparison<i64, Sqlite>` is not implemented for
241/// `Nullable<ScalarFilter<u64>>` but trait `ToDatabaseComparison<Option<_>, Sqlite>` is implemented
242/// for it*.
243///
244/// # The two spellings, as the compiler sees them
245///
246/// A nullable column's operands are the column's storage type with the `Option` taken off. Both
247/// blocks name a dialect where they used to name `()`, and both are gated on one: the crossing's
248/// item bound promises the comparison LOWERS, `ComplexComparison` is keyed on a [`Backend`], and the
249/// only backends there are, are dialects. The kind and its comparison are still declared outside the
250/// crate, which is the case this pair is about.
251///
252#[cfg_attr(feature = "sqlite", doc = "```")]
253#[cfg_attr(not(feature = "sqlite"), doc = "```ignore")]
254/// use ingraph::{
255/// At, Backend, ComplexComparison, Nullable,
256/// comparison::{
257/// ToDatabaseComparison,
258/// sql::{Carrier, SqlConjunction, SqlLoweringError, SqlNullable, push_column},
259/// },
260/// };
261///
262/// // A filter kind and a comparison declared OUTSIDE this crate, which is the case the wrapper
263/// // composes over.
264/// struct KeyFilter;
265/// struct KeyComparison<V>(Option<V>);
266///
267/// impl<V: Carrier<sqlx::Sqlite>, Db: Backend> ToDatabaseComparison<V, Db> for KeyFilter
268/// where
269/// KeyComparison<V>: ComplexComparison<Db>,
270/// {
271/// type Comparison = KeyComparison<V>;
272/// }
273///
274/// impl<V: Carrier<sqlx::Sqlite>> ComplexComparison<sqlx::Sqlite> for KeyComparison<V> {
275/// fn conjuncts(&self) -> usize {
276/// usize::from(self.0.is_some())
277/// }
278///
279/// fn apply<'q>(
280/// &'q self,
281/// at: At<'_>,
282/// mut builder: SqlConjunction<'q, sqlx::Sqlite>,
283/// ) -> Result<SqlConjunction<'q, sqlx::Sqlite>, SqlLoweringError> {
284/// if let Some(value) = &self.0 {
285/// let qb = builder.open();
286/// push_column(qb, at);
287/// qb.push(" = ");
288/// value.push_bind(qb);
289/// }
290/// Ok(builder)
291/// }
292/// }
293///
294/// type Column =
295/// <Nullable<KeyFilter> as ToDatabaseComparison<Option<i64>, sqlx::Sqlite>>::Comparison;
296/// let _: Column = SqlNullable::new(KeyComparison::<i64>(None));
297/// ```
298///
299/// so the is-null-as-an-operand spelling is not a question with a bad answer, it is a type that does
300/// not exist (`E0308`):
301///
302#[cfg_attr(feature = "sqlite", doc = "```compile_fail,E0308")]
303#[cfg_attr(not(feature = "sqlite"), doc = "```ignore")]
304/// use ingraph::{
305/// At, Backend, ComplexComparison, Nullable,
306/// comparison::{
307/// ToDatabaseComparison,
308/// sql::{Carrier, SqlConjunction, SqlLoweringError, SqlNullable, push_column},
309/// },
310/// };
311///
312/// struct KeyFilter;
313/// struct KeyComparison<V>(Option<V>);
314///
315/// impl<V: Carrier<sqlx::Sqlite>, Db: Backend> ToDatabaseComparison<V, Db> for KeyFilter
316/// where
317/// KeyComparison<V>: ComplexComparison<Db>,
318/// {
319/// type Comparison = KeyComparison<V>;
320/// }
321///
322/// impl<V: Carrier<sqlx::Sqlite>> ComplexComparison<sqlx::Sqlite> for KeyComparison<V> {
323/// fn conjuncts(&self) -> usize {
324/// usize::from(self.0.is_some())
325/// }
326///
327/// fn apply<'q>(
328/// &'q self,
329/// at: At<'_>,
330/// mut builder: SqlConjunction<'q, sqlx::Sqlite>,
331/// ) -> Result<SqlConjunction<'q, sqlx::Sqlite>, SqlLoweringError> {
332/// if let Some(value) = &self.0 {
333/// let qb = builder.open();
334/// push_column(qb, at);
335/// qb.push(" = ");
336/// value.push_bind(qb);
337/// }
338/// Ok(builder)
339/// }
340/// }
341///
342/// type Column =
343/// <Nullable<KeyFilter> as ToDatabaseComparison<Option<i64>, sqlx::Sqlite>>::Comparison;
344/// let _: Column = SqlNullable::new(KeyComparison::<Option<i64>>(None));
345/// ```
346///
347/// The two earn their keep only together, and they fail in opposite directions. Widening this
348/// impl's header back to `V` makes `Column` resolve to `SqlNullable<KeyComparison<Option<u128>>>`,
349/// which reds the FIRST block on `E0308` and makes the SECOND compile — and a `compile_fail` block
350/// that compiles is a failing test. Neither block alone would notice.
351///
352/// # The wrapper pays nothing for the crossing's item bound, and that is the composition working
353///
354/// `SqlNullable<C>` lowers when `C` does, and `C` here is `F::Comparison` — which already carries
355/// [`ComplexComparison<Db>`](crate::ComplexComparison) because the inner crossing promised it. So
356/// this row states the DATABASE's half of the lowering bound and nothing at all about the operand,
357/// exactly as the lowering impl below does. Wrapping a kind whose lowering is concrete per dialect
358/// is still the same one line as wrapping a kind whose lowering is generic.
359impl<F, V, Db> ToDatabaseComparison<Option<V>, Db> for Nullable<F>
360where
361 Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
362 F: ToDatabaseComparison<V, Db>,
363 // The column's own width, which the null test spends: a composite is tested at its VALUE columns
364 // and a scalar at the one it is. Every type that can BE an optional column already answers it —
365 // the row's `COLUMNS` is built from the same `const` — so the bound narrows nothing a declaration
366 // can reach and makes the wrapper's rendering provable where it is chosen.
367 V: crate::ColumnKind,
368{
369 type Comparison = SqlNullable<F::Comparison, V>;
370}
371
372/// The empty comparison of an empty inner one — bounded on `C`, unlike the flat kinds' unbounded
373/// [`Default`], because this wrapper OWNS an inner comparison and has no all-`None` state to build
374/// without one. [`Nullable`] carries the same bound on the filter side for the same reason.
375impl<C: Default, V: ?Sized> Default for SqlNullable<C, V> {
376 #[inline]
377 fn default() -> Self {
378 Self::new(C::default())
379 }
380}
381
382/// The crossing composes through `C`'s, and the error is `C`'s too — a null test never fails, so the
383/// wrapper adds no way for the crossing to.
384impl<F, C, V: ?Sized> TryFromFilter<Nullable<F>> for SqlNullable<C, V>
385where
386 C: TryFromFilter<F>,
387{
388 type Error = C::Error;
389
390 fn try_from_filter(filter: Nullable<F>) -> Result<Self, Self::Error> {
391 Self::try_from_filter_with_inner(filter, C::try_from_filter)
392 }
393}
394
395/// The FIRST composite, and the one that proves the recursion: everything above composes over `C`,
396/// and this is where `C` is lowered rather than only crossed.
397///
398/// A nested sub-comparison receives exactly the accumulator its parent was handed, which is why
399/// recursion needs no state of its own and no layer needs to know its own depth. The bound says so
400/// too — `C: ComplexComparison<Db>`, the same trait this impl provides, and nothing else — so a
401/// wrapper around a wrapper is the same one line as a wrapper around a leaf.
402///
403/// ONE impl for every dialect, and the finding is stronger here than for the three flat kinds that
404/// share it, because this wrapper adds ONE token to a lowering it does not otherwise touch:
405///
406/// - **The SQL is identical.** `IS NULL` and `IS NOT NULL` are ANSI and are spelled the same in
407/// SQLite, Postgres and MySQL. That is the entire text this impl contributes.
408/// - **The bounds are identical, and admit the same types.** `C: ComplexComparison<Db>` — the
409/// wrapper requires nothing of the operand at all, because it has none.
410///
411/// Everything that could differ per dialect is INSIDE `C`, which already names its own database in
412/// its own type. So this impl composes over the split rather than flattening it: wrapping a kind
413/// whose lowering is concrete per dialect is the same one line as wrapping a kind whose lowering is
414/// generic, and `SqlNullable<SqlTextComparison<V, Sqlite>>` reaches SQLite's own impl through `C`
415/// without this file knowing there is more than one.
416impl<C, V, Db> ComplexComparison<Db> for SqlNullable<C, V>
417where
418 Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
419 C: ComplexComparison<Db>,
420 V: ColumnKind + ?Sized,
421{
422 /// The whole SUBTREE's count — `C`'s conjuncts plus this wrapper's null test — because the
423 /// question a caller asks with it is whether anything at all will be rendered.
424 #[inline]
425 fn conjuncts(&self) -> usize {
426 self.inner.conjuncts() + usize::from(self.null.is_some())
427 }
428
429 /// The inner comparison's conjuncts, then the null test — appended LAST, so a where-clause reads
430 /// in the order the column's operators were declared and the null question closes it.
431 ///
432 /// Negation is the OPERATOR here (`IS NOT NULL`) rather than a `NOT ( … )` wrap, because SQL's
433 /// three-valued logic makes those two different questions: `NOT ( col IS NULL )` is what
434 /// `IS NOT NULL` means, but `NOT ( col = ? )` is UNKNOWN for a null column rather than true.
435 ///
436 /// The whole address passes DOWN untouched — no frame is pushed — because this wrapper is the
437 /// same column of the same row as its inner: the two conjuncts name one identifier and each
438 /// renders it once.
439 fn apply<'q>(
440 &'q self,
441 at: At<'_>,
442 builder: Db::Builder<'q>,
443 ) -> Result<Db::Builder<'q>, Db::Error> {
444 let mut builder = self.inner.apply(at, builder)?;
445 if let Some(null) = self.null {
446 push_null_test::<Db, V>(builder.open(), at, null);
447 }
448 Ok(builder)
449 }
450}
451
452/// **THE NULL TEST**, at one column for a scalar and over the VALUE columns for a composite.
453///
454/// ```text
455/// scalar "at" IS NULL
456/// composite ("at_pts" IS NULL AND "at_timebase_num" IS NULL AND "at_timebase_den" IS NULL)
457/// ```
458///
459/// # It is the WRITTEN form of the encoding the read already uses, and that is the whole design
460///
461/// An optional composite is absent when every one of its value columns is `NULL` and present when
462/// none of them is — the same sentence
463/// [`Assemble`](crate::Assemble)'s `Option<T>` row is written from. So the predicate is the
464/// conjunction of the per-column tests, in the same direction, and a filter therefore selects
465/// exactly the rows the decode would answer `None` for. Two spellings of one rule, and if they
466/// disagreed a query would return rows it then refused to decode.
467///
468/// **The derived columns are absent from both.** `at_nanos IS NULL` is true for an instant that IS
469/// stored and has no representable position, so including it would make `isNull: true` select rows
470/// holding values — which is the reading the leaf bit exists to prevent.
471///
472/// # `IS NOT NULL` is `AND` and not `OR`, and the asymmetry is the point
473///
474/// The negation of *every value column is `NULL`* is *some value column is not*, which is `OR` — and
475/// that is deliberately NOT what this renders. `isNull: false` asks for the rows that hold a value,
476/// and a row holding one has ALL of its value columns filled; the `OR` form would additionally admit
477/// the half-written rows the decode refuses by name. Both operators therefore describe rows that
478/// decode, and the state between them belongs to neither — which is the same standing
479/// [`PartialCompositeError`](crate::PartialCompositeError) takes on the read side.
480///
481/// # The parentheses are the conjunct boundary
482///
483/// The test is ONE conjunct of the surrounding clause — [`conjuncts`](ComplexComparison::conjuncts)
484/// counts it as one — so a composite's several terms are bracketed to stay one. A scalar renders
485/// bare, exactly as it always has, so no statement a scalar column produces moves.
486fn push_null_test<Db, V>(qb: &mut sqlx::QueryBuilder<Db>, at: At<'_>, null: bool)
487where
488 Db: sqlx::Database + Backend<Buffer: Display>,
489 V: ColumnKind + ?Sized,
490{
491 let test = if null { " IS NULL" } else { " IS NOT NULL" };
492 if V::SEGMENTS.is_empty() {
493 push_column(qb, at);
494 qb.push(test);
495 return;
496 }
497 qb.push("(");
498 let rendered = fold_value_leaves(at, V::SEGMENTS, 0usize, &mut |written, leaf| {
499 if written > 0 {
500 qb.push(" AND ");
501 }
502 push_column(qb, leaf);
503 qb.push(test);
504 written + 1
505 });
506 // A composite with NO value column has nothing that could be absent, which is exactly what
507 // `Assemble`'s own row answers for one: always present, never `None`. So the two directions are
508 // not symmetric here — asking for the absent rows selects none and asking for the present ones
509 // selects all — and the constants say so rather than the term being dropped, which would have
510 // made `isNull: true` mean *every row*. No shipped type reaches this; it is written because the
511 // walk can be handed a shape a person wrote.
512 if rendered == 0 {
513 qb.push(if null { "FALSE" } else { "TRUE" });
514 }
515 qb.push(")");
516}
517
518/// Nullability is orthogonal to how many columns a value occupies, so the wrapper is a composite
519/// exactly when what it wraps is, and pushes exactly what that pushes.
520///
521/// Stated rather than assumed, because it is not the default: nothing makes a wrapper inherit its
522/// inner's traits, and without this row `Option<Timebase>` would be unflattenable while `Timebase` was
523/// not — a difference the column's declaration never asked for.
524///
525/// It composes over `C` the way every other row on this type does, and this one adds no text at all:
526/// the null test renders at the SAME column as the inner comparison's own conjuncts, so the wrapper
527/// pushes no segment and has none of its own to report.
528impl<C, V, Db> CompositeComparison<Db> for SqlNullable<C, V>
529where
530 Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
531 C: CompositeComparison<Db>,
532 V: ColumnKind + ?Sized,
533{
534 const SEGMENTS: &'static [crate::ColumnShape] = C::SEGMENTS;
535}
536
537#[cfg(test)]
538mod tests;