Skip to main content

ingraph/comparison/sql/
carrier.rs

1//! The per-(storage type × dialect) binding: [`Carrier`], and the sqlx rows this dialect family
2//! reaches a column through.
3//!
4//! # Two layers, not one conflict
5//!
6//! ```text
7//! postgres(type = "BeU64")     the DECLARATION: what this field is stored as
8//! <BeU64 as Carrier<Postgres>>       the FRAMEWORK:   how that stored type binds in this dialect
9//! ```
10//!
11//! The framework does not choose the first, and it is not this module's at all: the storage FORMS a
12//! declaration spells — [`BeU64`](crate::BeU64) and its neighbours — carry no dialect and are
13//! declared in the crate's `storage` module under no backend's feature. What is here is the second
14//! layer, which is per-dialect by construction, and an omission in it is an unsatisfied `Carrier`
15//! bound naming the field's type and its dialect rather than a query that binds something plausible.
16//!
17//! [`SqlScalarComparison<V, Db>`](super::SqlScalarComparison) requires that second layer to exist:
18//! without a type-level carrier the `Db` parameter has nothing to select.
19//!
20//! # The table
21//!
22//! A row exists where the stored bytes are something the dialect can hold; where they are not, the
23//! type has NO row and the declaration has to name a storage type that does.
24//!
25//! | storage type | SQLite | Postgres | MySQL |
26//! |---|---|---|---|
27//! | `bool`, `i16`, `i32`, `i64`, `f32`, `f64` | native | native | native |
28//! | `i8` | native | widened `i16` | native |
29//! | `u8` | native | widened `i16` | native |
30//! | `u16` | native | widened `i32` | native |
31//! | `u32` | native | widened `i64` | native |
32//! | `u64` | — | — | native `BIGINT UNSIGNED` |
33//! | `u128`, `i128` | — | — | — |
34//! | `String` | native `TEXT` | native `TEXT` | native `TEXT` |
35//! | [`smol_bytes::Utf8Bytes`] | native `TEXT` | native `TEXT` | native `TEXT` |
36//! | `Vec<u8>` | native `BLOB` | native `BYTEA` | native `VARBINARY` |
37//! | [`Score`] | native `f32` | native `f32` | native `f32` |
38//! | [`Confidence<f64>`] | native `f64` | native `f64` | native `f64` |
39//! | [`Duration`] | — | native `INTERVAL` | — |
40//! | [`PgInterval`] | — | native `INTERVAL` | — |
41//! | [`PgDuration`] | — | native `INTERVAL` | — |
42//! | [`MySqlDuration`] | — | — | native `TIME` |
43//! | [`BeU64`] | blob | blob | (not needed) |
44//! | [`BeU128`], [`BeI128`] | blob | blob | blob |
45//! | [`uuid::Uuid`] | native `BLOB` | native `UUID` | native `BINARY(16)` |
46//! | `regex::Regex` (behind `regex`) | the PATTERN as native `TEXT` | the same | the same |
47//! | [`Count`] | narrowed `i64` | narrowed `i64` | native `BIGINT UNSIGNED` |
48//! | [`time::OffsetDateTime`], [`time::PrimitiveDateTime`], [`time::Date`], [`time::Time`] | native | native | native |
49//! | [`Temporal<T>`] | as its `T` | as its `T` | as its `T` |
50//! | [`TypedId<I, E>`] | as its `I` | as its `I` | as its `I` |
51//! | `NonZero*` (ten widths) | as its underlying integer | as its underlying integer | as its underlying integer |
52//! | [`Timestamp`] | **two** columns: `i64` + `i32` | the same two | the same two |
53//! | `Vec<E>` for `E` in `bool`, `i16`, `i32`, `i64`, `f32`, `f64`, `String`, `Vec<u8>` | — | ONE `E[]` | — |
54//!
55//! The [`Timestamp`] row is the only one in the table that is not one column, and it is the
56//! framework's own instant — see its [`Carrier`] row for the comma between the two binds, and
57//! [`ColumnKind`](crate::ColumnKind) for the width the two claims have to agree about.
58//!
59//! Postgres has no unsigned types and sqlx maps `i8` to `"char"`, which is why four widths widen
60//! there and nowhere else. The widened primitive IS the carrier — sqlx already ships all three of
61//! its traits — so the widening needs no newtype, only a row that says which integer it becomes.
62//!
63//! The last row is the COLLECTION boundary a page over a collection column resumes at, and it is
64//! Postgres's alone because a native array is: the other two dialects keep every collection in an
65//! edge table, so there is no column of the row for a boundary to be a value of. See
66//! `pg_array_carriers!` for why it is one bind and never an element expansion.
67//!
68//! # THE UUID ROW IS NATIVE THREE TIMES OVER, and the three natives are three different columns
69//!
70//! It is the only row in the table where `native` means a different physical form per dialect rather
71//! than one form under three names, and that is the 2026-08-29 ruling: **each backend stores a uuid
72//! in its own best form.** Censused off sqlx 0.9's `sqlx-postgres`, `sqlx-mysql` and `sqlx-sqlite`
73//! (`src/types/uuid.rs` in each), all three behind that crate's own `uuid` feature, which this
74//! crate's `sqlx` feature turns on:
75//!
76//! | dialect | `Type::type_info` | what `Encode` writes |
77//! |---|---|---|
78//! | PostgreSQL | `PgTypeInfo::UUID` | the sixteen bytes, no wrapper |
79//! | MySQL | `<&[u8]>::type_info()` | the sixteen bytes, length-encoded |
80//! | SQLite | `DataType::Blob` | `SqliteArgumentValue::Blob` of the sixteen bytes |
81//!
82//! **Not one of the three is the canonical text**, which is the fact the row is here to make
83//! unmissable — sqlx's MySQL decode says so in its own refusal (*`Uuid` uses binary format for
84//! MySQL/MariaDB; for text-formatted UUIDs use `uuid::fmt::Hyphenated`*), and this crate binds
85//! `Uuid` rather than either `fmt` wrapper for exactly that reason. The declared words those three
86//! forms are spelled with — `uuid`, `binary(16)`, `BLOB` — are `column::stored`'s, where the live
87//! catalogue readings and the ORDERING argument that ties all four backends to one byte order are
88//! recorded.
89//!
90//! The row rides `native_carriers!` on all three, `Uuid` being [`Copy`], so no borrowed view is
91//! wanted and no blob newtype is in the way: the value binds as itself.
92//!
93//! # A duration is native on two dialects, absent on the third, and MICROSECONDS on both
94//!
95//! Measured against sqlx 0.9:
96//!
97//! | dialect | column | sqlx's bridge | sub-microsecond operand |
98//! |---|---|---|---|
99//! | Postgres | `INTERVAL` | `Type` + `Encode` + `PgHasArrayType` for [`Duration`]; [`PgInterval`] direct | REFUSED — `PgInterval::try_from` rejects a nanosecond count that is not a multiple of 1000 |
100//! | MySQL | `TIME` | `MySqlTime`: `Type`, `Encode`, `Decode` — and `Type` for [`Duration`] with NO `Encode` | **silently truncated** — `MySqlTime::try_from(Duration)` takes `subsec_micros()`, which divides by 1000 |
101//! | SQLite | — | none, and SQLite has no temporal type at all | — |
102//!
103//! Both live dialects stop at MICROSECONDS. The filter's operand — a
104//! [`SignedDuration`](jiff::SignedDuration) — carries nanoseconds, so the gap is real, and the two
105//! engines disagree about what to do with it: Postgres refuses and MySQL rounds. This crate refuses
106//! on both — [`MySqlDuration`] is the carrier a MySQL duration column declares, and its [`TryFrom`]
107//! makes the check sqlx's own does not, so a nanosecond operand is a typed error at the CROSSING
108//! rather than a value quietly rounded inside a bind. Rounding is invisible in the rendered SQL,
109//! which is the property that makes it the worse failure.
110//!
111//! # …and both are SIGNED columns, which only one of these carriers is
112//!
113//! `INTERVAL` and `TIME` both hold a negative span, and the filter's operand can now spell one. What
114//! stands between them is the CARRIER, and the three differ:
115//!
116//! | carrier | dialect | negative operand |
117//! |---|---|---|
118//! | [`PgDuration`] | Postgres | STORED — pure microseconds, sign and all |
119//! | [`MySqlDuration`] | MySQL | STORED — the conversion splits magnitude from sign and puts the sign on the `MySqlTime` |
120//! | [`Duration`] | Postgres | REFUSED at the crossing — jiff's `TryFrom<SignedDuration> for Duration` has no unsigned value to become |
121//! | [`PgInterval`] | Postgres | STORED, and only through a DECLARED converter |
122//!
123//! The first two rows are this crate's own newtypes and are what an undeclared column reaches on
124//! each dialect. They exist for one reason: sqlx 0.9 ships no jiff integration, so neither
125//! `MySqlTime` nor `PgInterval` has a conversion from the operand, and `impl TryFrom<SignedDuration>`
126//! for either is `E0117` from here — foreign trait, foreign type, and neither sqlx nor jiff depends
127//! on the other to write it. A newtype this crate owns is the door through that wall, and it carries
128//! the CHECK as well as the conversion.
129//!
130//! The last two rows are what a DECLARED converter can still reach, and each remains useful for a
131//! reason of its own: [`Duration`] refuses a sub-microsecond operand at the BIND rather than at the
132//! crossing, and [`PgInterval`] is the only way to write a MIXED-FIELD interval, which a column
133//! sharing a schema with something else may need.
134//!
135//! MySQL's `TIME` also has a CEILING: `±838:59:59`, about 35 days, in each direction. Comfortable
136//! for a media duration and not for an accumulated total, and a column that needs more declares
137//! `i64` nanoseconds through
138//! [`DurationFilter::operand_nanos`](crate::DurationFilter::operand_nanos) — which is checked at
139//! both ends, and which is the reason that converter still exists now that neither dialect stores an
140//! integer by default.
141//!
142//! The [`Duration`] and [`PgInterval`] rows are ungated by `jiff`, because both are types a build
143//! without it can still name and bind. [`MySqlDuration`]'s row is not: that type exists to convert
144//! FROM the filter's operand, so without the feature it has no source type and no reason to be.
145//!
146//! `u64` has no SQLite or Postgres row because sqlx-sqlite 0.9 ships `Type` and `Decode` for it and
147//! no `Encode`, and sqlx-postgres ships none of the three. A `u64` field on either declares
148//! [`BeU64`] and crosses into it; on MySQL it needs no declaration at all.
149//!
150//! # …and [`Count`] HAS a row on all three, which is not that ruling reversed
151//!
152//! The absence above is about an ARBITRARY 64-bit magnitude — a hash, an offset, an id minted
153//! elsewhere — whose top half is ordinary traffic, so narrowing one into an `i64` loses a value
154//! nobody agreed to lose. A [`Count`] is not arbitrary: it counts rows that EXIST, so it is bounded
155//! by the physical store, and its narrowing crosses no information at all. The type carries that
156//! invariant and the row above spends it; a bare `u64` states nothing, so its row stays absent and
157//! [`BeU64`] stays the escape a `u64` column declares.
158//!
159//! The two directions are not symmetric, and the honesty is in the second. The ENCODE saturates at
160//! `i64::MAX` over an arm no count reaches. The DECODE refuses a NEGATIVE column by name — see
161//! `narrowed_count!` — because nothing this framework writes could have produced one, so it is a
162//! corrupt row rather than a wide count.
163//!
164//! # A CONFIDENCE carries natively at both widths that have a column, and jiff's four INSTANT types
165//! carry through [`Temporal`]
166//!
167//! [`Score`] is `Confidence<f32>`, whose constructor already excludes `NaN`, the infinities and
168//! everything outside `[0.0, 1.0]`. Nothing about that invariant is a STORAGE fact, so there is no
169//! encoding to own and no newtype to add: the row binds the wrapped float in all three dialects, the
170//! crossing from a `ScalarFilter<Score>` is the identity, and a `Score` column therefore needs no
171//! declaration. [`Confidence<f64>`] is the same row one width up.
172//!
173//! **Two widths and not four.** A confidence also measures in `half::f16` and
174//! `rust_decimal::Decimal`, and neither has a row here — because neither BARE width has one either.
175//! A confidence is a citizen of exactly the faces the width it measures in is a citizen of, so those
176//! two reach a schema and stop: they are wire scalars with no `ColumnKind`, which is a fact about
177//! what this framework has admitted as a column type rather than about confidences.
178//!
179//! **sqlx 0.9 ships no `jiff` integration** — its temporal type modules are `chrono` and `time` —
180//! so jiff's four instant and civil types reach a column through `time`'s three, which sqlx DOES encode for
181//! all three dialects, SQLite included. What this crate supplies is the crossing that reaches them,
182//! and it is [`TemporalStorage`](crate::TemporalStorage) rather than a declared converter: the field
183//! says `at: Timestamp` and the framework reads the type. [`Temporal<T>`] is what makes that
184//! crossing spellable at all — see its own note for the two `E0119`s that make it a coherence result
185//! — and it is a storage form rather than a dialect surface, so it lives beside the big-endian
186//! carriers and not here.
187//!
188//! What IS here is the four rows the wrapper needs to reach a sqlx column: its [`Carrier`] row and
189//! sqlx's own three. `time`'s three types keep rows of their own beside it, so a column declared as
190//! one directly still binds. Those are gated on `time` alone; the wrapper's need `jiff` too, since
191//! without it nothing implements [`TemporalStorage`](crate::TemporalStorage) and there is no
192//! `Temporal` to write a row for.
193//!
194//! jiff's FIFTH registered type, `SignedDuration`, is not among them and reaches no `Temporal`: it
195//! is an elapsed span rather than an instant, so its storage is the duration section above.
196//!
197//! [`Duration`]: core::time::Duration
198//! [`PgDuration`]: crate::PgDuration
199//! [`PgInterval`]: sqlx::postgres::types::PgInterval
200//! [`Count`]: crate::Count
201//! [`Score`]: crate::Score
202//! [`Confidence<f64>`]: crate::Confidence
203//! [`Temporal`]: crate::Temporal
204//! [`Temporal<T>`]: crate::Temporal
205//! [`Timestamp`]: crate::Timestamp
206//! [`TypedId<I, E>`]: crate::TypedId
207
208// The temporal storage form this module writes four rows for. It is the crate's rather than this
209// family's — see the note above — and the import carries the gate those rows carry. The big-endian
210// carriers are imported by the per-dialect modules instead, since that is the only depth their rows
211// are written at.
212#[cfg(all(feature = "jiff", feature = "time"))]
213use crate::Temporal;
214
215/// One storage type's physical binding in one SQL dialect.
216///
217/// Public, and deliberately so: this is the surface a downstream scalar or enum joins the
218/// comparison vocabulary through. A downstream type with a row here needs nothing else from this
219/// crate to be filtered on — the comparison kinds are already generic over it.
220///
221/// # Why a push rather than an associated bind type
222///
223/// The method form lets a row render more than a placeholder where a dialect needs one — a cast, a
224/// function call — without the trait changing shape. An associated type could carry only the value.
225///
226/// # The unimplemented note names BOTH exits, because a missing row means one of two things
227///
228/// The storability audit is where a declaration meets this trait: `impl Record<Db>` names a concrete
229/// backend, so every stored column's crossing is checked at the declaration rather than deferred to
230/// a call site. What the refusal cannot say for itself is WHICH kind of missing row it is, and the
231/// two have opposite answers. A type ONE dialect cannot hold — `u64` on SQLite, which has no
232/// unsigned 64-bit column — names the form it is stored as. A type NO dialect can hold is
233/// ENGINE-RESIDENT: an [`Embedding`](crate::Embedding) lives in a vector index, and #112's ruling on
234/// it is the user's own — *vectors do not belong in record-kind databases* — so the field wears
235/// `#[ingraph(skip)]` and the record keeps its rows, its filter, its order and its pages.
236#[diagnostic::on_unimplemented(
237  message = "`{Self}` has no carrier in `{Db}`: no column of that dialect can hold one",
238  label = "this declaration stores a column of `{Self}`",
239  note = "a type ONE dialect cannot hold names the form it is stored AS, with the conversions that \
240          reach it: `<db>(type = \"…\", from = \"…\", into = \"…\")`",
241  note = "a type NO dialect can hold is ENGINE-RESIDENT — an `Embedding` lives in its vector engine \
242          rather than in a row — and an engine-resident field wears `#[ingraph(skip)]`, which mints \
243          no column and fills the field on the way back"
244)]
245pub trait Carrier<Db: sqlx::Database> {
246  /// Push this value's placeholder and bound argument onto `qb`.
247  ///
248  /// A lone bind: an `IN` list's caller pushes its own separators.
249  ///
250  /// # A COMPOSITE pushes SEVERAL, and the separators between them are ITS
251  ///
252  /// A caller writing a `VALUES` list counts FIELDS and puts a comma between them, because a field
253  /// is what it can see. How many columns a field spans is the type's own answer —
254  /// [`ColumnKind::SEGMENTS`](crate::ColumnKind), read at compile time — so a type spanning two
255  /// pushes two placeholders with its own comma between them, and the `INSERT` list and the
256  /// `VALUES` list come out the same width with neither side told the number.
257  ///
258  /// The two claims are stated on two traits and have to agree: a row whose shape says two columns
259  /// and whose bind pushes one renders a statement the engine refuses to parse, which is the loud
260  /// failure rather than the silent one.
261  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>);
262
263  /// Push this value's placeholders and bound arguments for its VALUE columns alone — the DERIVED
264  /// leaves left out.
265  ///
266  /// # It is the bind side of the law, and [`ColumnShape::holds_value`] is the other side
267  ///
268  /// *A derived leaf serves the semantic order only; every structural judgment walks value leaves
269  /// only* — see [`ColumnShape`](crate::ColumnShape), where the law and its readers are written out.
270  /// Row-value EQUALITY and MEMBERSHIP are structural judgments, so their left-hand side names the
271  /// value leaves and their right-hand side has to bind exactly those. This is that right-hand side.
272  ///
273  /// It exists because a derived leaf can bind `NULL` for a value that IS there:
274  /// [`MediaTimestamp`](crate::MediaTimestamp) past the ±292-year ceiling stores its three value
275  /// columns exactly and writes `NULL` into `at_nanos`. A whole-width equality against such an
276  /// element is `(…, NULL) = (…, NULL)`, which is UNKNOWN rather than true, so `has_element` could
277  /// never match it — ingraph #455, repaired by this method rather than by a special case at the
278  /// operator.
279  ///
280  /// The `NULL` is what made that failure VISIBLE and it is not the reason for the method.
281  /// [`BoundingBox`](crate::BoundingBox)'s `area` is [`Derived`](crate::ColumnShape::Derived) — never
282  /// `NULL`, `NOT NULL` in the DDL — and is left out here all the same: a whole-width equality would
283  /// compare a column no caller ever supplied, which is the same poisoning without the three-valued
284  /// logic to announce it.
285  ///
286  /// # The DEFAULT is the answer for every type whose columns are all value
287  ///
288  /// Which is every type with no DERIVED leaf of its own, under either of that word's spellings. A
289  /// scalar has one column and it is the value; a composite whose segments are all
290  /// [`Plain`](crate::ColumnShape::Plain), directly or through its own composites, binds the same
291  /// list either way. So the default delegates to [`push_bind`](Self::push_bind) and a type states
292  /// nothing here unless it has an index leaf to leave out.
293  ///
294  /// [`ColumnShape::holds_value`]: crate::ColumnShape::holds_value
295  ///
296  /// # The pairing is the same one [`push_bind`](Self::push_bind) states, one column list over
297  ///
298  /// This bind's width has to be [`value_width`](crate::value_width) of the same `SEGMENTS` its
299  /// sibling's width is [`width`](crate::width) of. A type that declares an index leaf and forgets
300  /// this method binds one placeholder too many under a left-hand side naming one column fewer,
301  /// which is a statement the engine refuses to parse — the loud failure, exactly as it is for the
302  /// pairing above.
303  fn push_value_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
304    self.push_bind(qb);
305  }
306}
307
308/// **A NULLABLE column binds its value where it has one, and `NULL` where it has not.**
309///
310/// The row a nullable column of ANY type was missing, and the WRITE lane is where its absence
311/// showed: an emitted `bind` reaches `<Option<Channel> as Carrier<Db>>::push_bind`, so a record with
312/// a nullable column could be declared, filtered, ordered and read back, and not INSERTED. Nothing
313/// in the workspace had ever written one, which is how the gap outlived the columns that need it.
314///
315/// # `NULL` is WRITTEN rather than bound, and the reason is this trait's own shape
316///
317/// A `None` has no value to hand sqlx, and this trait carries no type a null could be bound AS —
318/// [`push_bind`](Carrier::push_bind) is a method on a VALUE, which is what lets a row render a cast
319/// or a call rather than a placeholder. Binding `None::<some type>` would pick a type the column may
320/// not have: PostgreSQL infers a parameter's type from its bind and refuses a `BOOL` null written
321/// into a `TEXT` column. The keyword has no type at all, so the engine takes the column's — and it
322/// is a CONSTANT, so nothing a caller supplies reaches the statement.
323///
324/// # As many `NULL`s as the type is WIDE
325///
326/// A composite occupies several columns and pushes one placeholder each with its own comma between
327/// them — the arrangement [`push_bind`](Carrier::push_bind) documents — so an absent composite has
328/// to render the same width, or the `INSERT` list and the `VALUES` list come out different lengths.
329/// The count is [`ColumnKind`](crate::ColumnKind)'s, which is the same authority the row's `COLUMNS`
330/// is built from, so the two cannot disagree: that trait's own `Option<T>` row already says an
331/// optional field is as wide as its value.
332///
333/// # Nothing else pushes an `Option`
334///
335/// A filter's operands are never optional — [`Nullable`](crate::Nullable) carries the null test and
336/// renders `IS NULL`, and the values inside it are the inner filter's — and a cursor slot holds what
337/// the column HOLDS rather than the `Option` holding it, the frame spelling absence itself. So this
338/// row is reached from the write lane and from nowhere a keyword would be the wrong shape.
339impl<T, Db> Carrier<Db> for Option<T>
340where
341  T: Carrier<Db> + crate::ColumnKind,
342  Db: sqlx::Database,
343{
344  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
345    let Some(value) = self else {
346      push_nulls(qb, widths(T::SEGMENTS).0);
347      return;
348    };
349    value.push_bind(qb);
350  }
351
352  /// The same arrangement at the narrower width: an absent composite renders as many `NULL`s as it
353  /// has VALUE columns, which is what keeps it the same shape as the row value it is compared
354  /// against.
355  fn push_value_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
356    let Some(value) = self else {
357      push_nulls(qb, widths(T::SEGMENTS).1);
358      return;
359    };
360    value.push_value_bind(qb);
361  }
362}
363
364/// `(width, value_width)` of a field of the type whose segments these are — with a SCALAR's empty
365/// list answering `(1, 1)`, which is the one column it occupies and the one that holds its value.
366const fn widths(segments: &[crate::ColumnShape]) -> (usize, usize) {
367  if segments.is_empty() {
368    return (1, 1);
369  }
370  (
371    crate::column::width(segments),
372    crate::column::value_width(segments),
373  )
374}
375
376/// `NULL, NULL, …` — `count` of them, with this family's own separator between.
377fn push_nulls<Db: sqlx::Database>(qb: &mut sqlx::QueryBuilder<Db>, count: usize) {
378  for at in 0..count {
379    if at > 0 {
380      qb.push(", ");
381    }
382    qb.push("NULL");
383  }
384}
385
386/// A borrowed operand carries exactly as the owned one does, which is what makes
387/// `SqlScalarComparison<&'a V, Db>` a real type rather than an aspiration: the borrowed comparison
388/// is the same struct with a different `V`, and it needs no lifetime of its own and no parallel
389/// family.
390///
391/// sqlx supplies the other half — `impl<'q, T, DB: Database> Encode<'q, DB> for &'_ T` and
392/// `impl<T: ?Sized + Type<DB>, DB: Database> Type<DB> for &'_ T` — so a reference binds wherever its
393/// referent does, with no copy.
394impl<T, Db> Carrier<Db> for &T
395where
396  T: Carrier<Db>,
397  Db: sqlx::Database,
398{
399  #[inline]
400  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
401    T::push_bind(self, qb);
402  }
403
404  /// Forwarded rather than left to the default, which would be the BORROW's own `push_bind` and
405  /// therefore the whole width — a borrowed composite would bind its index leaf where the owned one
406  /// leaves it out, and the borrowed operand family would not render what the owned one does.
407  #[inline]
408  fn push_value_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
409    T::push_value_bind(self, qb);
410  }
411}
412
413/// One row for the typed id, delegating to the id it holds — so the table gains ONE entry rather
414/// than one per entity: a [`TypedId`](crate::TypedId) binds wherever its `I` does, in whatever
415/// dialect `I` has a row for, and the entity marker reaches no column.
416///
417/// Generic over `Db` for the reason the wrapper below is: nothing in the delegation is per-dialect.
418impl<I, E, Db> Carrier<Db> for crate::TypedId<I, E>
419where
420  I: Carrier<Db>,
421  Db: sqlx::Database,
422{
423  #[inline]
424  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
425    self.id_ref().push_bind(qb);
426  }
427
428  #[inline]
429  fn push_value_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
430    self.id_ref().push_value_bind(qb);
431  }
432}
433
434/// **TWO BINDS OUT, and the comma between them is this row's.**
435///
436/// The framework's own instant occupies two columns — see
437/// [`ColumnKind`](crate::ColumnKind)'s row for the width, which is the claim this one has to agree
438/// with. A caller writing a `VALUES` list counts FIELDS and puts a comma between them; the comma
439/// inside a field is here, because the count is the type's.
440///
441/// # Generic over the dialect, where a DOWNSTREAM composite names one
442///
443/// The derive corpus's `Timebase` writes three rows, one per dialect, and its own note says why: a
444/// generic header from outside this crate would overlap the framework's rows for a backend that is
445/// not an `sqlx::Database`, and rustc cannot see from out there that none will arrive. From INSIDE
446/// there is nothing to overlap — this is the only row for this self type — so the header states the
447/// two parts' own requirements and every dialect that carries an `i64` and an `i32` gets the
448/// instant for free. All three do.
449///
450/// The parts bind through their OWN rows rather than through `push_bind` directly, which is what
451/// keeps a dialect's decision about an integer the dialect's: Postgres widens four integer widths
452/// here, and a composite that reached past those rows would be a second binding path for the same
453/// value.
454impl<Db> Carrier<Db> for crate::Timestamp
455where
456  Db: sqlx::Database,
457  i64: Carrier<Db>,
458  i32: Carrier<Db>,
459{
460  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
461    self.as_second().push_bind(qb);
462    qb.push(", ");
463    self.subsec_nanosecond().push_bind(qb);
464  }
465}
466
467/// One row for the wrapper, delegating to whatever its `T` already has — so the (type × dialect)
468/// table gains three entries rather than nine, and a downstream storage form joins by supplying its
469/// own [`Carrier`] row and nothing more.
470#[cfg(all(feature = "jiff", feature = "time"))]
471impl<T, Db> Carrier<Db> for Temporal<T>
472where
473  T: Carrier<Db>,
474  Db: sqlx::Database,
475{
476  #[inline]
477  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
478    self.get().push_bind(qb);
479  }
480
481  #[inline]
482  fn push_value_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
483    self.get().push_value_bind(qb);
484  }
485}
486
487/// sqlx's own [`Type`](sqlx::Type), delegating as the [`Carrier`] row above does — the wrapper
488/// declares whatever column its `T` declares, in whatever dialect `T` declares one for.
489///
490/// # A carrier row is not enough for a COLLECTION
491///
492/// [`Carrier::push_bind`] is how a scalar operand reaches a query here, and a `Temporal<T>` that had
493/// only that could be compared but not held in a Postgres `ARRAY`: the collection lowering binds
494/// `&[V]` as ONE parameter, and sqlx routes a slice through the element's own `Type`, `Encode` and
495/// [`PgHasArrayType`](sqlx::postgres::PgHasArrayType) rather than through anything this crate
496/// declares. Without those three the wrapper had no array type to name, so a `Vec<jiff::Timestamp>`
497/// reached an edge table where a `Vec<time::OffsetDateTime>` reached an array column — the same
498/// logical column in two physical shapes, chosen by which temporal crate the declaration named.
499///
500/// # Generic over `Db`, and over `T`
501///
502/// One impl rather than one per (storage type × dialect): nothing in the delegation is per-dialect,
503/// and `#[repr(transparent)]` is not what makes it sound — the inner value is FORWARDED, never
504/// reinterpreted, so the impl would be equally correct for a wrapper with any layout.
505///
506/// # The two bind paths cannot disagree here
507///
508/// Both end at `T`: the carrier row calls `<T as Carrier<Db>>::push_bind` and these call
509/// `<T as Encode<Db>>`, and every storage form this crate ships — `time`'s three — carries through
510/// `native_carriers!`, whose body IS `push_bind` and therefore sqlx's `Encode`. A `T` that binds
511/// through something else CAN differ: `i8` on Postgres widens to `smallint` here while sqlx types it
512/// `"char"`. So these three are not on their own a licence to put any `Temporal<T>` in an array
513/// column, and [`PgCollectionStorage`](super::PgCollectionStorage) does not read them as one: the
514/// wrapper's strategy is `T`'s DECLARED row, and `i8` declares the edge table.
515#[cfg(all(feature = "jiff", feature = "time"))]
516impl<T, Db> sqlx::Type<Db> for Temporal<T>
517where
518  T: sqlx::Type<Db>,
519  Db: sqlx::Database,
520{
521  #[inline]
522  fn type_info() -> <Db as sqlx::Database>::TypeInfo {
523    <T as sqlx::Type<Db>>::type_info()
524  }
525
526  #[inline]
527  fn compatible(ty: &<Db as sqlx::Database>::TypeInfo) -> bool {
528    <T as sqlx::Type<Db>>::compatible(ty)
529  }
530}
531
532/// The bytes, delegated whole: all four methods, so a `T` that overrides one is not silently given
533/// the trait's default through the wrapper.
534///
535/// [`produces`](sqlx::Encode::produces) is the one that would matter quietly — it is the per-VALUE
536/// type override, consulted ahead of [`Type::type_info`](sqlx::Type::type_info), and a default
537/// `None` here would discard a `T`'s answer.
538#[cfg(all(feature = "jiff", feature = "time"))]
539impl<'q, T, Db> sqlx::Encode<'q, Db> for Temporal<T>
540where
541  T: sqlx::Encode<'q, Db>,
542  Db: sqlx::Database,
543{
544  #[inline]
545  fn encode(
546    self,
547    buf: &mut <Db as sqlx::Database>::ArgumentBuffer,
548  ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
549    <T as sqlx::Encode<'q, Db>>::encode(self.0, buf)
550  }
551
552  #[inline]
553  fn encode_by_ref(
554    &self,
555    buf: &mut <Db as sqlx::Database>::ArgumentBuffer,
556  ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
557    <T as sqlx::Encode<'q, Db>>::encode_by_ref(&self.0, buf)
558  }
559
560  #[inline]
561  fn produces(&self) -> Option<<Db as sqlx::Database>::TypeInfo> {
562    <T as sqlx::Encode<'q, Db>>::produces(&self.0)
563  }
564
565  #[inline]
566  fn size_hint(&self) -> usize {
567    <T as sqlx::Encode<'q, Db>>::size_hint(&self.0)
568  }
569}
570
571/// The third of the three, and the one with a dialect in its name: sqlx declares it for Postgres
572/// alone, so this row is gated where the other two are not.
573///
574/// It is what makes `&[Temporal<T>]` type as `T[]` — the array OF the column the two impls above
575/// name, which is the whole point of delegating rather than inventing one.
576#[cfg(all(feature = "postgres", feature = "jiff", feature = "time"))]
577impl<T> sqlx::postgres::PgHasArrayType for Temporal<T>
578where
579  T: sqlx::postgres::PgHasArrayType,
580{
581  #[inline]
582  fn array_type_info() -> sqlx::postgres::PgTypeInfo {
583    <T as sqlx::postgres::PgHasArrayType>::array_type_info()
584  }
585
586  #[inline]
587  fn array_compatible(ty: &sqlx::postgres::PgTypeInfo) -> bool {
588    <T as sqlx::postgres::PgHasArrayType>::array_compatible(ty)
589  }
590}
591
592/// A [`SignedDuration`](jiff::SignedDuration) stored as MySQL's native `TIME` — the carrier a MySQL
593/// duration column declares, and the CHECK sqlx's own conversion does not make.
594///
595/// # Why a newtype where Postgres needs none
596///
597/// `MySqlTime` already binds: it has `Type`, `Encode` and `Decode`. What it does not have is a
598/// faithful conversion from the filter's operand. It has none from a [`SignedDuration`] at all —
599/// sqlx 0.9 ships no jiff integration — and the one it has from a [`Duration`](core::time::Duration)
600/// reads `value.subsec_micros()`, whose own comment is *"Simply divides by 1000"*, so a `1500ns`
601/// operand becomes `1µs` and the query matches rows the caller did not ask for. Nothing in the
602/// rendered SQL shows it.
603///
604/// Declaring `MySqlTime` directly would put that conversion on the undeclared crossing, which is the
605/// path a column with no declared converter takes. This newtype is what makes the checked conversion
606/// the only one reachable from here: `MySqlTime` has no [`Carrier`] row of its own, so a duration
607/// column on MySQL stores as this type or does not compile.
608///
609/// # The SIGN, which sqlx's conversion cannot carry and this one must
610///
611/// `TIME` is a SIGNED type — `±838:59:59` — and `MySqlTime` models that with a
612/// [`MySqlTimeSign`](sqlx::mysql::types::MySqlTimeSign) beside a magnitude. sqlx's
613/// `TryFrom<Duration>` hard-codes `Positive`, and correctly so: its source type has no other value.
614/// A [`SignedDuration`] does, so this conversion splits the operand into magnitude and sign and puts
615/// the sign back.
616///
617/// The magnitude comes from [`SignedDuration::unsigned_abs`], which is total — it is
618/// `Duration::new(secs.unsigned_abs(), nanos.unsigned_abs())` and so has no `i64::MIN` panic that a
619/// negation would.
620///
621/// Nothing here reads `MySqlTime::is_negative`. Its body in sqlx 0.9.0 is `self.sign.is_positive()`,
622/// which is the inverted answer; `sign()` is the accessor that reports what was set.
623///
624/// # What it refuses
625///
626/// [`MySqlDurationError::Nanoseconds`] for sub-microsecond precision `TIME` cannot hold, and
627/// [`MySqlDurationError::Ceiling`] past `838:59:59` — about 35 days, which is `TIME`'s whole range
628/// in EACH direction. A duration column that must exceed the ceiling stores `i64` nanoseconds
629/// instead, through [`DurationFilter::operand_nanos`](crate::DurationFilter::operand_nanos).
630///
631/// [`SignedDuration`]: jiff::SignedDuration
632#[cfg(all(feature = "mysql", feature = "jiff"))]
633#[derive(Debug, Clone, Copy, PartialEq, Eq)]
634pub struct MySqlDuration(sqlx::mysql::types::MySqlTime);
635
636#[cfg(all(feature = "mysql", feature = "jiff"))]
637impl MySqlDuration {
638  /// The stored `TIME` value.
639  #[inline]
640  pub const fn get(self) -> sqlx::mysql::types::MySqlTime {
641    self.0
642  }
643}
644
645/// The CHECKED conversion, and the whole reason the newtype exists — see its own note for what
646/// sqlx's does instead, and for why the sign is applied here rather than left where sqlx puts it.
647///
648/// # Errors
649///
650/// [`MySqlDurationError::Nanoseconds`] when `value` carries sub-microsecond precision;
651/// [`MySqlDurationError::Ceiling`] when its magnitude exceeds `TIME`'s `838:59:59`.
652#[cfg(all(feature = "mysql", feature = "jiff"))]
653impl TryFrom<jiff::SignedDuration> for MySqlDuration {
654  type Error = MySqlDurationError;
655
656  fn try_from(value: jiff::SignedDuration) -> Result<Self, Self::Error> {
657    let magnitude = value.unsigned_abs();
658    let remainder = magnitude.subsec_nanos() % 1_000;
659    if remainder != 0 {
660      return Err(MySqlDurationError::Nanoseconds(remainder));
661    }
662    // Every remaining refusal is the ceiling: `MySqlTime::new` reports `FieldRange` past 838 hours
663    // and `SubsecondExcess` for the sliver between `838:59:59.0` and `839:00:00.0`, and both say the
664    // same thing to a caller. The sub-microsecond case is already gone, so nothing else can arrive.
665    let time = sqlx::mysql::types::MySqlTime::try_from(magnitude)
666      .map_err(|_| MySqlDurationError::Ceiling)?;
667    // `with_sign(Negative)` on a zero magnitude would build the `NegativeZero` value `MySqlTime::new`
668    // refuses, and `is_negative` is false for a zero `SignedDuration`, so the guard is the same test
669    // that decides the sign.
670    Ok(Self(if value.is_negative() {
671      time.with_sign(sqlx::mysql::types::MySqlTimeSign::Negative)
672    } else {
673      time
674    }))
675  }
676}
677
678#[cfg(all(feature = "mysql", feature = "jiff"))]
679impl From<MySqlDuration> for sqlx::mysql::types::MySqlTime {
680  #[inline]
681  fn from(value: MySqlDuration) -> Self {
682    value.0
683  }
684}
685
686/// Why a [`SignedDuration`](jiff::SignedDuration) did not become a MySQL `TIME`.
687#[cfg(all(feature = "mysql", feature = "jiff"))]
688#[derive(Debug, Clone, Copy, PartialEq, Eq)]
689pub enum MySqlDurationError {
690  /// The operand carries sub-microsecond precision, carried here as the remainder in nanoseconds.
691  ///
692  /// The remainder is taken off the MAGNITUDE and so is unsigned: `-1500ns` and `1500ns` are the
693  /// same refusal, because it is the precision that `TIME` cannot hold and not the direction.
694  ///
695  /// `TIME` stores microseconds. Rounding would answer a question the caller did not ask and leave
696  /// no trace in the SQL, so the operand is refused instead.
697  Nanoseconds(u32),
698  /// The operand's magnitude exceeds `TIME`'s `838:59:59` — about 35 days, the whole range of the
699  /// type in either direction.
700  Ceiling,
701}
702
703#[cfg(all(feature = "mysql", feature = "jiff"))]
704impl core::fmt::Display for MySqlDurationError {
705  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
706    match self {
707      Self::Nanoseconds(remainder) => write!(
708        f,
709        "duration carries {remainder}ns below a microsecond and MySQL `TIME` stores microseconds"
710      ),
711      Self::Ceiling => f.write_str("duration exceeds MySQL `TIME`'s ±838:59:59 (about 35 days)"),
712    }
713  }
714}
715
716#[cfg(all(feature = "mysql", feature = "jiff"))]
717impl std::error::Error for MySqlDurationError {}
718
719/// A [`SignedDuration`](jiff::SignedDuration) stored as PostgreSQL's native `INTERVAL` — the carrier
720/// a Postgres duration column declares, and the door through a wall the orphan rule builds.
721///
722/// # Why a newtype where sqlx already ships the type
723///
724/// [`PgInterval`](sqlx::postgres::types::PgInterval) binds: it has `Type`, `Encode`, `Decode` and
725/// `PgHasArrayType`. What it does not have, and cannot be given from here, is a conversion from the
726/// filter's operand. sqlx 0.9 ships no jiff integration, so `TryFrom<SignedDuration> for PgInterval`
727/// would be a foreign trait on a foreign type — `E0117` from this crate, and neither sqlx nor jiff
728/// depends on the other to write it. The newtype is a type this crate owns, which is the whole of
729/// what the impl needs.
730///
731/// Before it, an undeclared Postgres duration column reached `core::time::Duration` through jiff's
732/// own conversion, and that type is UNSIGNED: a negative operand was refused at the crossing on a
733/// dialect whose column holds one perfectly well. This carrier is what closes that gap, and it makes
734/// the three backends answer alike — MongoDB stores a signed integer, MySQL a signed `TIME`, and
735/// Postgres a signed `INTERVAL`.
736///
737/// # PURE MICROSECONDS, and the comparison that makes it exact
738///
739/// The interval is built as `months: 0, days: 0, microseconds: n`. An `INTERVAL` has three
740/// independent fields and the same span has many spellings, so the question is whether an operand
741/// written in one of them compares correctly against a column written in another.
742///
743/// It does, and it is measured rather than assumed. PostgreSQL compares two intervals by
744/// normalising BOTH through one convention — a month counts as 30 days and a day as 24 hours — so
745/// the field split never reaches the comparison. On PostgreSQL 17.10:
746///
747/// ```text
748/// INTERVAL '1 month' = INTERVAL '30 days' = INTERVAL '720 hours'   -- all true
749/// INTERVAL '1 day'   = INTERVAL '24 hours'                         -- true
750/// INTERVAL '719 hours' < INTERVAL '1 month' < INTERVAL '721 hours' -- true
751/// ```
752///
753/// and a pure-microseconds operand of `2592000s` selects the rows stored as `1 mon` AND as
754/// `30 days`, with `>=` also reaching `1 mon 1 day`. Negative operands normalise identically.
755///
756/// So a pure-microseconds operand is exactly as correct as any other spelling, and it is the only
757/// one this crate can build honestly: the operand is an elapsed span with no calendar fields in it,
758/// and filling `months` or `days` would be inventing a calendar reading the caller never wrote.
759///
760/// What that inherits — rather than introduces — is the CONVENTION. A column holding `INTERVAL
761/// '1 mon'` answers `eq` for an operand of exactly 30 days, because that is what Postgres means by
762/// equality here, not because anything was lost on the way in. A schema that needs calendar
763/// identity rather than elapsed-span equality wants a different column type, and that is true of
764/// every spelling of the operand.
765///
766/// A column that must hold a mixed-field interval for some other reason still has the escape it
767/// always had: [`PgInterval`](sqlx::postgres::types::PgInterval) keeps its own [`Carrier`] row, and
768/// a declared converter reaches it.
769///
770/// # What it refuses
771///
772/// [`PgDurationError::Nanoseconds`] for sub-microsecond precision `INTERVAL` cannot hold — the same
773/// refusal [`MySqlDuration`] makes, because both columns are microsecond types and the filter is a
774/// nanosecond one — and [`PgDurationError::Range`] when the microsecond count leaves `i64`, which is
775/// the width of the interval's own field.
776///
777/// [`SignedDuration`]: jiff::SignedDuration
778#[cfg(all(feature = "postgres", feature = "jiff"))]
779#[derive(Debug, Clone, Copy, PartialEq, Eq)]
780pub struct PgDuration(sqlx::postgres::types::PgInterval);
781
782#[cfg(all(feature = "postgres", feature = "jiff"))]
783impl PgDuration {
784  /// The stored `INTERVAL` value.
785  #[inline]
786  pub const fn get(self) -> sqlx::postgres::types::PgInterval {
787    self.0
788  }
789}
790
791/// The CHECKED conversion, and the whole reason the newtype exists.
792///
793/// # Errors
794///
795/// [`PgDurationError::Nanoseconds`] when `value` carries sub-microsecond precision;
796/// [`PgDurationError::Range`] when its microsecond count does not fit the interval's `i64` field.
797#[cfg(all(feature = "postgres", feature = "jiff"))]
798impl TryFrom<jiff::SignedDuration> for PgDuration {
799  type Error = PgDurationError;
800
801  fn try_from(value: jiff::SignedDuration) -> Result<Self, Self::Error> {
802    let nanos = value.as_nanos();
803    // The remainder is reported UNSIGNED, so `-1500ns` and `1500ns` are the same refusal: what
804    // `INTERVAL` cannot hold is the precision, not the direction. `%` in Rust takes the sign of the
805    // dividend, hence the `unsigned_abs`; the cast cannot truncate, the value being below 1000.
806    let remainder = (nanos % 1_000).unsigned_abs() as u32;
807    if remainder != 0 {
808      return Err(PgDurationError::Nanoseconds(remainder));
809    }
810    // The division is exact now that the remainder is gone, so truncation toward zero is not a
811    // rounding decision — there is nothing left to round.
812    let microseconds = i64::try_from(nanos / 1_000).map_err(|_| PgDurationError::Range)?;
813    Ok(Self(sqlx::postgres::types::PgInterval {
814      months: 0,
815      days: 0,
816      microseconds,
817    }))
818  }
819}
820
821#[cfg(all(feature = "postgres", feature = "jiff"))]
822impl From<PgDuration> for sqlx::postgres::types::PgInterval {
823  #[inline]
824  fn from(value: PgDuration) -> Self {
825    value.0
826  }
827}
828
829/// Why a [`SignedDuration`](jiff::SignedDuration) did not become a PostgreSQL `INTERVAL`.
830#[cfg(all(feature = "postgres", feature = "jiff"))]
831#[derive(Debug, Clone, Copy, PartialEq, Eq)]
832pub enum PgDurationError {
833  /// The operand carries sub-microsecond precision, carried here as the remainder in nanoseconds.
834  ///
835  /// Unsigned, for the reason [`MySqlDurationError::Nanoseconds`] is: `-1500ns` and `1500ns` are one
836  /// refusal about precision rather than two about direction.
837  ///
838  /// `INTERVAL` stores microseconds. Rounding would answer a question the caller did not ask and
839  /// leave no trace in the SQL, so the operand is refused instead.
840  Nanoseconds(u32),
841  /// The operand's microsecond count does not fit the interval's `i64` field — about ±292_471 years.
842  ///
843  /// `Range` rather than `Ceiling`, which is the name [`MySqlDurationError`] uses, because the two
844  /// bounds are not the same shape: MySQL's is a ceiling on the MAGNITUDE (`±838:59:59` either way),
845  /// where this one is the two-sided and slightly asymmetric span of an `i64`.
846  Range,
847}
848
849#[cfg(all(feature = "postgres", feature = "jiff"))]
850impl core::fmt::Display for PgDurationError {
851  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
852    match self {
853      Self::Nanoseconds(remainder) => write!(
854        f,
855        "duration carries {remainder}ns below a microsecond and PostgreSQL `INTERVAL` stores \
856         microseconds"
857      ),
858      Self::Range => f.write_str(
859        "duration is outside PostgreSQL `INTERVAL`'s i64 microseconds (about ±292471 years)",
860      ),
861    }
862  }
863}
864
865#[cfg(all(feature = "postgres", feature = "jiff"))]
866impl std::error::Error for PgDurationError {}
867
868/// Implement the three sqlx traits for one blob carrier against one database, delegating the type
869/// info and the raw bytes to `Vec<u8>` — whichever binary column that database maps it to.
870///
871/// [`Decode`](sqlx::Decode) is here because a carrier that can only write is a bind helper rather
872/// than a carrier: the encoding has ONE authority and an authority names both directions. It is also
873/// what makes the encoding testable as a round trip.
874///
875/// That authority is the storage form's own `to_blob` / `from_blob`, which is what makes this row a
876/// BINDING rather than a second encoding. A dialect writing `to_be_bytes` here would agree with the
877/// carrier today and be free to stop; the other family's rows call the same two methods, so a
878/// `BeU64` column holds the same bytes whichever backend wrote it.
879#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
880macro_rules! blob_carrier {
881  ($name:ident, $db:ty) => {
882    impl sqlx::Type<$db> for $name {
883      #[inline]
884      fn type_info() -> <$db as sqlx::Database>::TypeInfo {
885        <Vec<u8> as sqlx::Type<$db>>::type_info()
886      }
887
888      #[inline]
889      fn compatible(ty: &<$db as sqlx::Database>::TypeInfo) -> bool {
890        <Vec<u8> as sqlx::Type<$db>>::compatible(ty)
891      }
892    }
893
894    impl sqlx::Encode<'_, $db> for $name {
895      fn encode_by_ref(
896        &self,
897        buf: &mut <$db as sqlx::Database>::ArgumentBuffer,
898      ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
899        <Vec<u8> as sqlx::Encode<'_, $db>>::encode(self.to_blob().to_vec(), buf)
900      }
901    }
902
903    impl<'r> sqlx::Decode<'r, $db> for $name {
904      fn decode(
905        value: <$db as sqlx::Database>::ValueRef<'r>,
906      ) -> Result<Self, sqlx::error::BoxDynError> {
907        let bytes = <Vec<u8> as sqlx::Decode<'r, $db>>::decode(value)?;
908        <$name>::from_blob(&bytes).ok_or_else(|| {
909          sqlx::error::BoxDynError::from(concat!(
910            stringify!($name),
911            ": stored blob is not the expected width"
912          ))
913        })
914      }
915    }
916
917    impl Carrier<$db> for $name {
918      #[inline]
919      fn push_bind(&self, qb: &mut sqlx::QueryBuilder<$db>) {
920        qb.push_bind(*self);
921      }
922    }
923  };
924}
925
926/// **THE CARDINALITY, ON A DIALECT WITH NO UNSIGNED 64-BIT COLUMN** — the three sqlx rows and the
927/// [`Carrier`] row a [`Count`](crate::Count) column crosses through on SQLite and PostgreSQL.
928///
929/// It is `blob_carrier!`'s shape one type over, and it is that shape because the same law applies:
930/// the ENCODING has one authority and the authority names both directions.
931/// [`Count::to_signed`](crate::Count::to_signed) and
932/// [`Count::from_signed`](crate::Count::from_signed) are it — the MongoDB family's row calls the
933/// same method, so a `Count` column holds the same value whichever backend wrote it.
934///
935/// # What the two directions each spend, and why they are not symmetric
936///
937/// The ENCODE saturates at [`i64::MAX`] over an arm no count reaches: a cardinality counts rows that
938/// exist, so it is bounded by the physical store, and that bound is the whole reason this type is
939/// carriable where a bare `u64` is not — see [`Count`](crate::Count) for the ruling.
940///
941/// The DECODE has no such licence. A negative column is a value no write of this framework's could
942/// have produced, so it is a corrupt row rather than a wide count, and it is refused BY NAME as
943/// [`NegativeCount`](crate::NegativeCount) wrapped in sqlx's own
944/// [`ColumnDecode`](sqlx::Error::ColumnDecode) — never clamped to zero, which would answer a
945/// question nobody asked and leave no trace anywhere.
946#[cfg(any(feature = "sqlite", feature = "postgres"))]
947macro_rules! narrowed_count {
948  ($db:ty) => {
949    impl sqlx::Type<$db> for crate::Count {
950      #[inline]
951      fn type_info() -> <$db as sqlx::Database>::TypeInfo {
952        <i64 as sqlx::Type<$db>>::type_info()
953      }
954
955      #[inline]
956      fn compatible(ty: &<$db as sqlx::Database>::TypeInfo) -> bool {
957        <i64 as sqlx::Type<$db>>::compatible(ty)
958      }
959    }
960
961    impl sqlx::Encode<'_, $db> for crate::Count {
962      fn encode_by_ref(
963        &self,
964        buf: &mut <$db as sqlx::Database>::ArgumentBuffer,
965      ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
966        <i64 as sqlx::Encode<'_, $db>>::encode(self.to_signed(), buf)
967      }
968    }
969
970    impl<'r> sqlx::Decode<'r, $db> for crate::Count {
971      fn decode(
972        value: <$db as sqlx::Database>::ValueRef<'r>,
973      ) -> Result<Self, sqlx::error::BoxDynError> {
974        let stored = <i64 as sqlx::Decode<'r, $db>>::decode(value)?;
975        crate::Count::from_signed(stored).map_err(sqlx::error::BoxDynError::from)
976      }
977    }
978
979    impl Carrier<$db> for crate::Count {
980      #[inline]
981      fn push_bind(&self, qb: &mut sqlx::QueryBuilder<$db>) {
982        qb.push_bind(*self);
983      }
984    }
985  };
986}
987
988/// The rows sqlx already encodes the way this crate stores them: a plain `push_bind`.
989#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
990macro_rules! native_carriers {
991  ($db:ty { $( $ty:ty ),+ $(,)? }) => {
992    $(
993      impl Carrier<$db> for $ty {
994        #[inline]
995        fn push_bind(&self, qb: &mut sqlx::QueryBuilder<$db>) {
996          qb.push_bind(*self);
997        }
998      }
999    )+
1000  };
1001}
1002
1003/// The rows sqlx encodes as this crate stores them but which are NOT [`Copy`], so the bind names
1004/// the borrowed view instead of a copy of the value.
1005///
1006/// `push_bind<'t, T: Encode<'t, DB>>` takes `'t` as a free lifetime and `QueryBuilder<DB>` carries
1007/// none, so a `&'a str` whose referent outlives the call binds with no allocation — a clone here
1008/// would copy every text operand in every query for nothing.
1009#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
1010macro_rules! borrowed_carriers {
1011  ($db:ty { $( $ty:ty => $view:ident ),+ $(,)? }) => {
1012    $(
1013      impl Carrier<$db> for $ty {
1014        #[inline]
1015        fn push_bind(&self, qb: &mut sqlx::QueryBuilder<$db>) {
1016          qb.push_bind(self.$view());
1017        }
1018      }
1019    )+
1020  };
1021}
1022
1023/// A whole COLLECTION as ONE array parameter — the boundary a page over a collection column resumes
1024/// at.
1025///
1026/// # One bind, and never an element expansion
1027///
1028/// `push_bind` on a slice is a single `$n` typed `E[]`, whatever the list holds, which is what the
1029/// collection comparisons above already do (`push_array_op`, `push_mutual_containment`) and what
1030/// this row joins them in. The alternative — one placeholder per element — would put a ROW's stored
1031/// value against the dialect's [`BindCeiling`](crate::BindCeiling), so a page over a long list would
1032/// refuse to render for a reason that has nothing to do with the page. There is no such interaction
1033/// here, and a bind-count assertion beside the keyset is what keeps it that way.
1034///
1035/// The bind names the borrowed view rather than a copy, exactly as `borrowed_carriers!` does and for
1036/// its reason: cloning a boundary list at every arm of the keyset expansion would copy it three
1037/// times per term for nothing.
1038///
1039/// # It is the CURSOR's row, and it is not a licence to compare a collection as a scalar
1040///
1041/// What asks for it is [`SqlKeyset`](super::SqlKeyset), whose boundary values bind through
1042/// [`Carrier`]. A `ListFilter` still crosses into [`SqlListComparison`](super::SqlListComparison)
1043/// or an edge kind — the strategy is
1044/// [`PgCollectionStorage`](super::PgCollectionStorage)'s answer and not this row's, and the two
1045/// cannot disagree because this table is a strict subset of that one's array rows.
1046///
1047/// # The elements, and why exactly these
1048///
1049/// The array-stored rows of that same table, intersected with the ones
1050/// [`CursorValue`](crate::CursorValue) encodes — a boundary needs both halves, since
1051/// [`SqlOrdering::Value`](crate::query::sql::SqlOrdering::Value) is `Carrier<Db> + CursorValue`. So
1052/// `Duration`, `PgInterval` and `time`'s three are absent: they ride the array perfectly well and
1053/// have no cursor codec, which is the same missing row a SCALAR of one already has.
1054#[cfg(feature = "postgres")]
1055macro_rules! pg_array_carriers {
1056  ($( $ty:ty ),+ $(,)?) => {
1057    $(
1058      impl Carrier<sqlx::Postgres> for Vec<$ty> {
1059        #[inline]
1060        fn push_bind(&self, qb: &mut sqlx::QueryBuilder<sqlx::Postgres>) {
1061          qb.push_bind(self.as_slice());
1062        }
1063      }
1064    )+
1065  };
1066}
1067
1068/// The rows whose stored bytes are a WIDER native integer. Only Postgres widens, so the macro is
1069/// gated with its one user rather than left defined-and-unused in a build without it.
1070#[cfg(feature = "postgres")]
1071macro_rules! widened_carriers {
1072  ($db:ty { $( $ty:ty => $wide:ty ),+ $(,)? }) => {
1073    $(
1074      impl Carrier<$db> for $ty {
1075        #[inline]
1076        fn push_bind(&self, qb: &mut sqlx::QueryBuilder<$db>) {
1077          qb.push_bind(<$wide>::from(*self));
1078        }
1079      }
1080    )+
1081  };
1082}
1083
1084/// This crate's own primitive, at each width that has a column. It binds the WRAPPED value and
1085/// nothing else: the `[0.0, 1.0]` invariant is a fact about the DOMAIN, maintained by the
1086/// constructor, and a column has no way to carry it.
1087///
1088/// Two widths and not four. `half::f16` and `rust_decimal::Decimal` reach a schema and stop there —
1089/// neither is a `ColumnKind`, so neither is a width a declaration can name as a column — and a
1090/// confidence is a citizen of exactly the faces the width it measures in is a citizen of. Binding a
1091/// `f16` confidence as a `f32` here would have minted a storage decision for a width the framework
1092/// has not admitted, in the one place nobody would look for it.
1093impl<Db: sqlx::Database, S: crate::ConfidenceCarrier + Carrier<Db>> Carrier<Db>
1094  for crate::Confidence<S>
1095{
1096  #[inline]
1097  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
1098    self.get().push_bind(qb);
1099  }
1100}
1101
1102/// **A `NonZero*` COLUMN BINDS ITS UNDERLYING INTEGER, THROUGH [`NonZero::get`](core::num::NonZero::get).**
1103///
1104/// One generic row per width rather than one per (width × dialect) — the same shape
1105/// [`Temporal<T>`](Temporal)'s row takes, one paragraph up in this file's history, and
1106/// [`Confidence<S>`]'s just above. The wrapped integer is what a column HOLDS, so whichever dialect
1107/// carries that width carries this row for free: `NonZeroU64` binds wherever `u64` does (MySQL
1108/// alone, by the table above), and `NonZeroU128`/`NonZeroI128` bind nowhere, because `u128`/`i128`
1109/// do not either. There is nothing to enumerate per dialect — the bound says it once.
1110///
1111/// # Why `.get()` and not a second encoding
1112///
1113/// The `NonZero` invariant is a fact about the RUST type, maintained by the constructor, exactly as
1114/// [`Confidence`](crate::Confidence)'s `[0.0, 1.0]` one is — a column has no way to carry it and does
1115/// not need to: the STORED width is the plain integer (see [`ColumnKind`](crate::ColumnKind)'s row,
1116/// which answers the scalar default), so the write side hands the underlying value to the width's
1117/// OWN row rather than inventing a second bind path for the same bytes.
1118macro_rules! nonzero_carriers {
1119  ($( $ty:ty => $inner:ty ),+ $(,)?) => {
1120    $(
1121      impl<Db: sqlx::Database> Carrier<Db> for $ty
1122      where
1123        $inner: Carrier<Db>,
1124      {
1125        #[inline]
1126        fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
1127          self.get().push_bind(qb);
1128        }
1129      }
1130    )+
1131  };
1132}
1133
1134nonzero_carriers! {
1135  core::num::NonZeroI8 => i8,
1136  core::num::NonZeroI16 => i16,
1137  core::num::NonZeroI32 => i32,
1138  core::num::NonZeroI64 => i64,
1139  core::num::NonZeroI128 => i128,
1140  core::num::NonZeroU8 => u8,
1141  core::num::NonZeroU16 => u16,
1142  core::num::NonZeroU32 => u32,
1143  core::num::NonZeroU64 => u64,
1144  core::num::NonZeroU128 => u128,
1145}
1146
1147/// # Nothing silently works, and the compiler is where that is said
1148///
1149/// A `u64` column declared as a `u64` on SQLite has no row, so its comparison has no lowering. The
1150/// omission is a bound naming the type and the dialect, not a query that binds something plausible:
1151///
1152/// ```compile_fail,E0599
1153/// use ingraph::{
1154///   At, ComplexComparison, FieldName, RecordAddress, ScalarFilter, TryFromFilter,
1155///   comparison::sql::SqlScalarComparison,
1156/// };
1157///
1158/// let c = SqlScalarComparison::<u64, sqlx::Sqlite>::try_from_filter(
1159///   ScalarFilter::<u64>::new().with_eq(1u64),
1160/// )
1161/// .unwrap();
1162/// let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
1163/// const ROW: RecordAddress = RecordAddress::new(FieldName::new("t"), &[FieldName::new("id")]);
1164/// let out = ingraph::comparison::sql::SqlConjunction::with_lead(&mut qb, "");
1165/// let frame = At::new(&ROW).frame(FieldName::new("n"));
1166/// c.apply(frame.at(), out).unwrap();
1167/// ```
1168///
1169/// Declaring the storage type the dialect can hold is what makes it compile, and the twin below is
1170/// what keeps the negative one honest — stable rustdoc runs a `compile_fail` block just far enough
1171/// to see it fail and never checks why, so the pair shares its imports and its call shape and one
1172/// half must COMPILE:
1173///
1174/// ```
1175/// use ingraph::{
1176///   At, BeU64, ComplexComparison, FieldName, RecordAddress, ScalarFilter, TryFromFilter,
1177///   comparison::sql::SqlScalarComparison,
1178/// };
1179///
1180/// let c = SqlScalarComparison::<BeU64, sqlx::Sqlite>::try_from_filter(
1181///   ScalarFilter::<u64>::new().with_eq(1u64),
1182/// )
1183/// .unwrap();
1184/// let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
1185/// const ROW: RecordAddress = RecordAddress::new(FieldName::new("t"), &[FieldName::new("id")]);
1186/// let out = ingraph::comparison::sql::SqlConjunction::with_lead(&mut qb, "");
1187/// let frame = At::new(&ROW).frame(FieldName::new("n"));
1188/// c.apply(frame.at(), out).unwrap();
1189/// assert_eq!(qb.sql(), "\"n\" = ?");
1190/// ```
1191#[cfg(feature = "sqlite")]
1192mod sqlite {
1193  use super::Carrier;
1194  use crate::{BeI128, BeU64, BeU128};
1195
1196  native_carriers!(sqlx::Sqlite {
1197    bool,
1198    i8,
1199    i16,
1200    i32,
1201    i64,
1202    u8,
1203    u16,
1204    u32,
1205    f32,
1206    f64,
1207    // Sixteen bytes into a `BLOB`, through sqlx's own `Encode` — see this module's uuid note.
1208    uuid::Uuid
1209  });
1210  borrowed_carriers!(sqlx::Sqlite {
1211    String => as_str,
1212    Vec<u8> => as_slice,
1213    smol_bytes::Utf8Bytes => as_str,
1214  });
1215  // THE PATTERN, bound as its own text through the borrowed arm — `as_str` hands back the very
1216  // `&str` `Regex::new` was given, so the bind is a text bind and the automaton reaches no
1217  // placeholder. Borrowed and not native for `Utf8Bytes`' reason: a `Regex` is not `Copy`, and there
1218  // is no need to clone one to name its pattern.
1219  #[cfg(feature = "regex")]
1220  borrowed_carriers!(sqlx::Sqlite { regex::Regex => as_str });
1221
1222  blob_carrier!(BeU64, sqlx::Sqlite);
1223  blob_carrier!(BeU128, sqlx::Sqlite);
1224  blob_carrier!(BeI128, sqlx::Sqlite);
1225  narrowed_count!(sqlx::Sqlite);
1226
1227  #[cfg(feature = "time")]
1228  native_carriers!(sqlx::Sqlite { time::OffsetDateTime, time::PrimitiveDateTime, time::Date, time::Time });
1229}
1230
1231#[cfg(feature = "postgres")]
1232mod postgres {
1233  use super::Carrier;
1234  use crate::{BeI128, BeU64, BeU128};
1235
1236  native_carriers!(sqlx::Postgres {
1237    bool,
1238    i16,
1239    i32,
1240    i64,
1241    f32,
1242    f64,
1243    ::core::time::Duration,
1244    sqlx::postgres::types::PgInterval,
1245    // The native `uuid` parameter — `PgTypeInfo::UUID`, sixteen raw bytes on the binary protocol —
1246    // so a `= $1` against a `uuid` column needs no cast. See this module's uuid note.
1247    uuid::Uuid
1248  });
1249  widened_carriers!(sqlx::Postgres { i8 => i16, u8 => i16, u16 => i32, u32 => i64 });
1250  borrowed_carriers!(sqlx::Postgres {
1251    String => as_str,
1252    Vec<u8> => as_slice,
1253    smol_bytes::Utf8Bytes => as_str,
1254  });
1255  // THE PATTERN, bound as its own text through the borrowed arm — `as_str` hands back the very
1256  // `&str` `Regex::new` was given, so the bind is a text bind and the automaton reaches no
1257  // placeholder. Borrowed and not native for `Utf8Bytes`' reason: a `Regex` is not `Copy`, and there
1258  // is no need to clone one to name its pattern.
1259  #[cfg(feature = "regex")]
1260  borrowed_carriers!(sqlx::Postgres { regex::Regex => as_str });
1261
1262  // The COLLECTION boundaries, one array parameter each — see `pg_array_carriers!` for the element
1263  // list and for why an element expansion is the thing this row exists not to be. `Vec<Vec<u8>>` is
1264  // the list of byte strings that `BYTEA[]` is; the `Vec<u8>` above it is one `BYTEA`.
1265  pg_array_carriers!(bool, i16, i32, i64, f32, f64, String, Vec<u8>);
1266  blob_carrier!(BeU64, sqlx::Postgres);
1267  blob_carrier!(BeU128, sqlx::Postgres);
1268  blob_carrier!(BeI128, sqlx::Postgres);
1269  narrowed_count!(sqlx::Postgres);
1270
1271  /// The `INTERVAL` row, binding the checked newtype's wrapped value — written out rather than
1272  /// listed above because the bind names `get()` and not the value itself, which is
1273  /// [`MySqlDuration`](super::MySqlDuration)'s arrangement for the same reason.
1274  ///
1275  /// It rides `jiff` with the type it binds: [`PgDuration`](super::PgDuration) exists to carry the
1276  /// duration filter's operand, and without that feature there is no operand to convert from.
1277  #[cfg(feature = "jiff")]
1278  impl Carrier<sqlx::Postgres> for super::PgDuration {
1279    #[inline]
1280    fn push_bind(&self, qb: &mut sqlx::QueryBuilder<sqlx::Postgres>) {
1281      qb.push_bind(self.get());
1282    }
1283  }
1284
1285  #[cfg(feature = "time")]
1286  native_carriers!(sqlx::Postgres { time::OffsetDateTime, time::PrimitiveDateTime, time::Date, time::Time });
1287}
1288
1289#[cfg(feature = "mysql")]
1290mod mysql {
1291  use super::Carrier;
1292  use crate::{BeI128, BeU128, Count};
1293
1294  native_carriers!(sqlx::MySql {
1295    bool,
1296    i8,
1297    i16,
1298    i32,
1299    i64,
1300    u8,
1301    u16,
1302    u32,
1303    u64,
1304    f32,
1305    f64,
1306    // Sixteen bytes into a `binary(16)`, through sqlx's own `Encode`, which writes them
1307    // length-encoded and never the hyphenated text — see this module's uuid note.
1308    uuid::Uuid
1309  });
1310
1311  /// The `TIME` row, binding the checked newtype's wrapped value — the `Score` arrangement, where
1312  /// the invariant belongs to the Rust type and the column carries none of it.
1313  ///
1314  /// It rides `jiff` with the type it binds: [`MySqlDuration`](super::MySqlDuration) exists to carry
1315  /// the duration filter's operand, and without that feature there is no operand to convert from.
1316  #[cfg(feature = "jiff")]
1317  impl Carrier<sqlx::MySql> for super::MySqlDuration {
1318    #[inline]
1319    fn push_bind(&self, qb: &mut sqlx::QueryBuilder<sqlx::MySql>) {
1320      qb.push_bind(self.get());
1321    }
1322  }
1323  borrowed_carriers!(sqlx::MySql {
1324    String => as_str,
1325    Vec<u8> => as_slice,
1326    smol_bytes::Utf8Bytes => as_str,
1327  });
1328  // THE PATTERN, bound as its own text through the borrowed arm — `as_str` hands back the very
1329  // `&str` `Regex::new` was given, so the bind is a text bind and the automaton reaches no
1330  // placeholder. Borrowed and not native for `Utf8Bytes`' reason: a `Regex` is not `Copy`, and there
1331  // is no need to clone one to name its pattern.
1332  #[cfg(feature = "regex")]
1333  borrowed_carriers!(sqlx::MySql { regex::Regex => as_str });
1334
1335  blob_carrier!(BeU128, sqlx::MySql);
1336  blob_carrier!(BeI128, sqlx::MySql);
1337
1338  /// **THE CARDINALITY, ON THE ONE DIALECT WHOSE COLUMN HOLDS IT WHOLE** — `BIGINT UNSIGNED`, so
1339  /// the three rows delegate to `u64` and the crossing is the IDENTITY.
1340  ///
1341  /// Written out rather than reached through `narrowed_count!`, and the asymmetry IS the fact: the
1342  /// other two dialects spend [`Count`](crate::Count)'s bound to get into an `i64` and this one
1343  /// spends nothing, so a row that shared the macro would have hidden the one difference between
1344  /// the three carriers behind a parameter.
1345  ///
1346  /// The decode has nothing to refuse for the same reason. Every `u64` is a cardinality — what the
1347  /// newtype states is where a value CAME FROM, not which values it admits — so
1348  /// [`NegativeCount`](crate::NegativeCount) has no arm here and cannot: the column holds no
1349  /// negative value to be one.
1350  impl sqlx::Type<sqlx::MySql> for Count {
1351    #[inline]
1352    fn type_info() -> <sqlx::MySql as sqlx::Database>::TypeInfo {
1353      <u64 as sqlx::Type<sqlx::MySql>>::type_info()
1354    }
1355
1356    #[inline]
1357    fn compatible(ty: &<sqlx::MySql as sqlx::Database>::TypeInfo) -> bool {
1358      <u64 as sqlx::Type<sqlx::MySql>>::compatible(ty)
1359    }
1360  }
1361
1362  impl sqlx::Encode<'_, sqlx::MySql> for Count {
1363    fn encode_by_ref(
1364      &self,
1365      buf: &mut <sqlx::MySql as sqlx::Database>::ArgumentBuffer,
1366    ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
1367      <u64 as sqlx::Encode<'_, sqlx::MySql>>::encode(self.get(), buf)
1368    }
1369  }
1370
1371  impl<'r> sqlx::Decode<'r, sqlx::MySql> for Count {
1372    fn decode(
1373      value: <sqlx::MySql as sqlx::Database>::ValueRef<'r>,
1374    ) -> Result<Self, sqlx::error::BoxDynError> {
1375      <u64 as sqlx::Decode<'r, sqlx::MySql>>::decode(value).map(Count::new)
1376    }
1377  }
1378
1379  native_carriers!(sqlx::MySql { Count });
1380
1381  #[cfg(feature = "time")]
1382  native_carriers!(sqlx::MySql { time::OffsetDateTime, time::PrimitiveDateTime, time::Date, time::Time });
1383}
1384
1385#[cfg(test)]
1386mod tests;