ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//! The DECLARED half of a column: [`StoredAs`], the word one dialect's `CREATE TABLE` spells a
//! storage type with.
//!
//! # The fourth face, and what the other three could not answer
//!
//! [`ColumnKind`](crate::ColumnKind) says HOW MANY columns a field is,
//! [`Carrier<Db>`](crate::Carrier) says how its value BINDS in one dialect, and
//! [`Assemble`](crate::Assemble) says how it READS BACK. None of them says what the column is
//! DECLARED AS, so every party that has needed the word so far has written it by hand: a descriptor
//! carries `Column::new(FieldName::new("id"), "BIGINT", false)` with the type as plain text, and the
//! text is a claim about a dialect that nothing checks against the type it stores.
//!
//! This is that word, answered by the TYPE, per dialect. A declaration that reads it cannot spell
//! `TEXT` for a column its carrier binds an `i64` into, because the two are no longer written in two
//! places.
//!
//! # THE SPELLING LAW: the word has TWO READERS, and only one of them accepts synonyms
//!
//! The word is read twice and the readings are not the same reading:
//!
//! - `CREATE TABLE` needs a LEGAL INPUT. Every dialect here accepts several spellings of one type —
//!   PostgreSQL takes `int8` for a `bigint`, `float8` for a `double precision`, `timestamptz` for a
//!   `timestamp with time zone` — and all of them build.
//! - the DRIFT AUDIT needs the CATALOGUE'S OWN ANSWER. `audit_columns` compares the declared word
//!   against what [`AsyncSchemaDialect::stored`](crate::query::sql::AsyncSchemaDialect::stored)
//!   reports, with [`str::eq_ignore_ascii_case`] and nothing else — no synonym table, no
//!   normalisation. A catalogue answers in ONE spelling, and a legal alias is not it.
//!
//! So an alias BUILDS AND THEN FAILS ITS OWN AUDIT, silently, until the first `validate` run. That
//! is not a hazard this module reasons about from documentation — it is measured. Against
//! PostgreSQL 16, a column declared `int8` is reported by `information_schema.columns.data_type` as
//! `bigint`; `float8` as `double precision`; `bool` as `boolean`; `timestamptz` as `timestamp with
//! time zone`. And sqlx's own [`Type::type_info`](sqlx::Type::type_info) names for those very types
//! are `INT8`, `FLOAT8`, `BOOL`, `TIMESTAMPTZ` — every one an alias the catalogue never answers. A
//! row spelled from the driver's vocabulary would have been the wrong vocabulary.
//!
//! **Each row below is written in its dialect catalogue's own reported spelling**, and each was read
//! back off a live server rather than a manual. Which catalogue column that is differs per dialect,
//! and the difference is load-bearing:
//!
//! | dialect | probe | the column the audit compares | what it reports |
//! |---|---|---|---|
//! | SQLite | `pragma_table_info` | `type` | the DECLARED word, echoed verbatim |
//! | PostgreSQL | `information_schema.columns` | `data_type` | the SQL standard's name, lower case |
//! | MySQL | `information_schema.COLUMNS` | `COLUMN_TYPE` | the declared type WITH width and attributes |
//!
//! Three consequences, each of which decides rows below:
//!
//! - **SQLite echoes**, so any legal spelling self-agrees and the audit cannot catch a wrong one.
//!   The rows take the family's existing convention — the storage CLASS SQLite actually holds the
//!   bound value in: `INTEGER`, `REAL`, `TEXT`, `BLOB`. That is the word the hand-written blueprints
//!   in this crate already use, and it is the one that gives the stored value the affinity its
//!   ordering needs.
//! - **PostgreSQL normalises to the standard's name**, so the rows say `bigint`, `double precision`,
//!   `boolean`, `timestamp with time zone` — never the driver's `INT8`, `FLOAT8`, `BOOL`,
//!   `TIMESTAMPTZ`.
//! - **MySQL reports `COLUMN_TYPE` rather than `DATA_TYPE`**, which carries the width and the
//!   attributes. So `bool` is `tinyint(1)` and NOT `boolean` — MySQL's `BOOLEAN` is spelled into a
//!   `TINYINT(1)` and the catalogue answers with what it became; an unsigned integer carries
//!   ` unsigned` in the word itself; and a sub-second temporal column must declare its precision or
//!   lose it. `TIMESTAMP` truncates `22:13:20.123456` to `22:13:20` where `TIMESTAMP(6)` keeps it —
//!   measured against MySQL 8.4 — so the temporal rows carry `(6)`.
//!
//! # THE UUID IS THE FIRST ROW WHERE THE FOUR BACKENDS DISAGREE ABOUT THE FORM, not just the word
//!
//! Every other type above is stored in ONE form and spelled three ways — an `i64` is an integer
//! everywhere and the dialects differ only in what they call one. A uuid is not: it is sixteen bytes
//! that each backend has its OWN best home for, and the 2026-08-29 ruling is that each one uses it
//! rather than a single portable TEXT. The table, censused off sqlx 0.9 and bson 3 and then read
//! back off a live server per dialect:
//!
//! | backend | the form | this crate's word | what the catalogue answered |
//! |---|---|---|---|
//! | PostgreSQL | the native `uuid` type, 16 bytes | `uuid` | `data_type` = `udt_name` = `uuid` (PG 16) |
//! | MySQL | a fixed-width binary column | `binary(16)` | `COLUMN_TYPE` = `binary(16)` (MySQL 8.4) |
//! | SQLite | the BLOB storage class, 16 bytes | `BLOB` | `pragma_table_info.type` echoes it |
//! | MongoDB | `BinData` subtype 4 | — | no DDL word exists; see `comparison::mongo::carrier` |
//!
//! **The canonical 36-character text is what this is NOT**, and the difference is 20 bytes a row
//! plus an index that sorts by ASCII digits rather than by the value. Text remains the road for a
//! type that has only a text form, and it is no longer what a uuid gets for want of anything better
//! — **including under `#[derive(ingraph::Id)]`**, whose wrapper rows read
//! [`IdColumn<Db>`](crate::IdColumn) at the inner and therefore inherit the row above rather than
//! the `TEXT` one. That seam's own note is where the per-member roads are.
//!
//! ## The four forms SORT THE SAME, which is what keeps a cursor page correct
//!
//! All four compare BYTEWISE over the same sixteen bytes in the same order:
//!
//! - PostgreSQL's `uuid` is a 16-byte value compared with `memcmp` (`uuid_cmp`).
//! - MySQL's `binary(16)` compares as a binary string, which is bytewise with no collation involved.
//! - SQLite compares two BLOBs with `memcmp`, and BLOB sorts after every other storage class — which
//!   costs nothing here, a uuid column holding no other class.
//! - BSON orders `BinData` by LENGTH, then SUBTYPE, then bytes. Every uuid shares the first two, so
//!   the order reduces to the bytewise one — the same argument the big-endian carriers already make
//!   in `comparison::mongo::carrier`.
//!
//! And [`uuid::Uuid`]'s own [`Ord`] is that same bytewise order, the type being a `[u8; 16]` under
//! `#[repr(transparent)]`. So the Rust order, the four stored orders and
//! [`CursorValue`](crate::CursorValue)'s sixteen-byte encoding are ONE order, and a keyset page over
//! a uuid column resumes where it left off on every backend rather than on three of them.
//!
//! **For a UUIDv7 that order is TIME order**, since v7 puts a 48-bit big-endian millisecond in the
//! leading six bytes — so `ORDER BY id` on a v7 column is newest-last without a second column, which
//! is the property the whole arrangement exists to preserve. It is not claimed for v4, whose bytes
//! are random and whose order is therefore arbitrary but still TOTAL and still agreed on by all
//! four, which is all a cursor needs.
//!
//! ## What it does NOT get, recorded rather than left silent
//!
//! [`CollectionElement`](crate::CollectionElement) has no uuid row, so `Vec<uuid::Uuid>` is not a
//! declarable column. That is [`smol_bytes::Utf8Bytes`]'s own position — a value citizen that is not
//! an element — and it is a DOOR: an edge table of uuids needs nothing new, while the PostgreSQL
//! ARRAY road wants an `uuid[]` carrier row and a storage-strategy ruling beside the ones
//! `PgCollectionStorage` already makes. Neither is decided here.
//!
//! # What has NO row, and why absence is the answer
//!
//! The standing this module takes is [`Carrier`](crate::Carrier)'s: *absence IS the refusal*. A type
//! with no row in a dialect is a type that dialect cannot declare, and the missing row is an
//! `E0277` naming both.
//!
//! - **A type with no carrier in that dialect.** `u64` has no PostgreSQL or SQLite row because no
//!   column of those dialects holds one, and `i128`/`u128` have none anywhere. A word for a column
//!   nothing can bind into would be a schema promise the write lane cannot keep.
//! - **`str`.** It answers a WIDTH and nothing else — it is not a value a row owns, and it has no
//!   carrier in any dialect — so it has no word either. `&str` follows it, the borrowed row
//!   delegating to its referent.
//! - **[`Vec<T>`], on every dialect, and PostgreSQL is the one that PROVES it cannot have one.** A
//!   collection reaches storage two ways: as an EDGE TABLE, where the field appears in no column
//!   list at all and no word is wanted; or as a PostgreSQL ARRAY, where the two readers want two
//!   DIFFERENT STRINGS and no single word satisfies both. `CREATE TABLE t (x bigint[])` is legal and
//!   `CREATE TABLE t (x ARRAY)` is a syntax error, while `data_type` for that same column reports
//!   `ARRAY` and never `bigint[]` — the element type living in `udt_name` as `_int8`. Both halves
//!   are measured. One `const WORDS` cannot be both strings, so the array column is left without a
//!   row rather than given one that is wrong for whichever reader is not looking, and the split it
//!   would need is the emission's problem to state rather than this trait's to hide.
//!
//! # The GENERIC boundary, which is a property of stable Rust and was measured
//!
//! A row's `WORDS` is a `const`, so its LENGTH is fixed when the impl is written. Two shapes follow
//! from that and the line between them is not a taste:
//!
//! - **A composite of FIXED arity composes freely, ACROSS DIALECTS.** `[A::WORDS[0], B::WORDS[0]]`
//!   has length two whatever `Db` is, so a composite may read its parts' rows through a generic
//!   `Db` and stay one impl. Every composite below does, which is why a dialect that carries an
//!   `i64` and an `i32` gets [`Timestamp`](crate::Timestamp) for free and no primitive here has a
//!   row per dialect.
//! - **A composite whose arity depends on a TYPE PARAMETER cannot have a row at all.**
//!   [`TimeRanged<T>`](crate::TimeRanged) spans the range's four columns plus `T`'s own, so its
//!   `WORDS` would be `TimeRange::WORDS` concatenated with `T::WORDS` — an array whose length is
//!   `4 + <T as StoredAs<Db>>::WORDS.len()`. Stable Rust refuses that twice over: naming the length
//!   as an inner `const` is `E0401` (*can't use generic parameters from outer item*), and naming it
//!   in the array's own length position is *constant expression depends on a generic parameter*.
//!   Both were compiled to confirm. So `TimeRanged<T>` has no row, and the concatenation belongs to
//!   whatever assembles a row's whole column list from its FIELDS — where the lengths are concrete.
//!
//! A generic wrapper that DELEGATES is untouched by this, having no arithmetic to do:
//! [`Option<T>`], `&T`, [`TypedId<I, E>`](crate::TypedId), [`Temporal<T>`](crate::Temporal),
//! [`Confidence<S>`](crate::Confidence) and the `NonZero*` family each hand back the word of the
//! thing they wrap.
//!
//! # The campaign
//!
//! This was T1 of four, and it landed the trait and its rows wired to NOTHING — deliberately, so
//! that the rows could be argued and measured on their own before anything depended on them being
//! right. T2 gave [`Table::shaped`](crate::Table) a constructor taking a field's words, and **T3
//! spends them**: `#[ingraph::record(…)]` emits `impl Describe<Db>` per declared SQL dialect, whose
//! `WORDS` list is one projection through this trait per FIELD, spanned at that field. So a type
//! with no row here is now an `E0277` at a DECLARATION rather than a fact nothing reads — which is
//! what the notes on the trait below are for, and why they name the `<db>(type = "…")` road out.
//!
//! Two absences above became the emission's own boundaries rather than this module's:
//!
//!   * `Vec<T>`'s missing row is why a record whose collection this database keeps in a COLUMN gets
//!     no blueprint at all. It is a documented SKIP on the emitter's roster and not an error, so a
//!     Postgres array column keeps every lane it has; `postgres(edge)` is what lands the schema.
//!   * `TimeRanged<T>`'s missing row is `E0277` at the field, there being no fact about a TYPE a
//!     macro reading tokens can skip on.
//!
//! T4 is the application's own knife: the hand-written `Describe` impls retire, since an emitted one
//! beside a hand-written one is `E0119`.
//!
//! [`Option<T>`]: core::option::Option
//! [`Vec<T>`]: std::vec::Vec

/// The word ONE dialect's DDL declares this storage type with — one per LEAF COLUMN.
///
/// # One word per leaf, and the count is [`ColumnKind`](crate::ColumnKind)'s
///
/// A scalar is one word. A composite is one word per column it spans, in the order
/// [`SEGMENTS`](crate::ColumnKind::SEGMENTS) states them — FLATTENED, because a word is wanted for
/// each column a `CREATE TABLE` writes and a nested shape writes no column of its own. So
/// `WORDS.len()` equals the field's width, and the two `const`s answer the same question from two
/// sides: how many columns, and what each is called.
///
/// The agreement is asserted per row rather than left to a reader — see this module's tests, where
/// every shipped type's width is held against its word count in a `const`.
///
/// # It is OPEN, and that is the [`ColumnKind`](crate::ColumnKind) admission shape
///
/// `Db` carries no bound. A downstream type joins by writing its own row, and a FUTURE DIALECT —
/// one this crate has never heard of, which need not be an [`sqlx::Database`] — joins by writing
/// rows for the types it can hold. Neither needs anything from this crate but the trait.
///
/// # Examples
///
/// A downstream scalar, and the composite that spans two of it:
///
/// ```
/// use ingraph::{ColumnKind, ColumnName, ColumnShape, StoredAs};
///
/// struct Cents(i64);
/// impl ColumnKind for Cents {}
/// impl<Db> StoredAs<Db> for Cents
/// where
///   i64: StoredAs<Db>,
/// {
///   const WORDS: &'static [&'static str] = <i64 as StoredAs<Db>>::WORDS;
/// }
///
/// struct Money { amount: Cents, currency: String }
/// impl ColumnKind for Money {
///   const SEGMENTS: &'static [ColumnShape] = &[
///     ColumnShape::Plain(ColumnName::new("amount")),
///     ColumnShape::Plain(ColumnName::new("currency")),
///   ];
/// }
/// impl<Db> StoredAs<Db> for Money
/// where
///   Cents: StoredAs<Db>,
///   String: StoredAs<Db>,
/// {
///   const WORDS: &'static [&'static str] = &[
///     <Cents as StoredAs<Db>>::WORDS[0],
///     <String as StoredAs<Db>>::WORDS[0],
///   ];
/// }
///
/// # #[cfg(feature = "postgres")] {
/// assert_eq!(<Money as StoredAs<sqlx::Postgres>>::WORDS, ["bigint", "text"]);
/// # }
/// # #[cfg(feature = "mysql")] {
/// assert_eq!(<Money as StoredAs<sqlx::MySql>>::WORDS, ["bigint", "varchar(255)"]);
/// # }
/// ```
#[diagnostic::on_unimplemented(
  message = "`{Self}` has no declared type in `{Db}`: that dialect has no word for this column",
  label = "this declaration stores a column of `{Self}`",
  note = "a type that dialect cannot HOLD has no word by design — see `Carrier`, whose row is \
          missing for the same reason, and name the form it is stored AS instead",
  note = "a COLLECTION has no word: it is an edge table, which appears in no column list, or a \
          PostgreSQL array, whose `CREATE TABLE` spelling and whose catalogue spelling are two \
          different strings",
  note = "a composite whose ARITY depends on a type parameter — `TimeRanged<T>` — can have no row \
          at all: its length would be `4 + <T as StoredAs<Db>>::WORDS.len()`, which stable Rust \
          refuses in both positions a `const` could name it",
  note = "under `#[ingraph::record(…)]` the road out is `<db>(type = \"…\")`, naming a stored form \
          that HAS a row in this dialect, with `from`/`into` beside it"
)]
pub trait StoredAs<Db> {
  /// One word per column this type spans, in [`SEGMENTS`](crate::ColumnKind::SEGMENTS) order,
  /// written in this dialect catalogue's own reported spelling.
  const WORDS: &'static [&'static str];
}

/// Whether a type's word count matches the width its shape claims — the two `const`s held against
/// each other.
///
/// A SCALAR spans one column and states no segments, which is why this is not `WORDS.len() ==
/// width(SEGMENTS)`: that would read `0` for every scalar. It is the same branch
/// [`Carrier`](crate::Carrier)'s `Option` row takes to count the `NULL`s an absent value renders,
/// and it is written once here so both readings cannot drift.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "sqlite")] {
/// use ingraph::{StoredAs, Timestamp, spans};
///
/// const _: () = assert!(spans::<Timestamp, sqlx::Sqlite>());
/// assert_eq!(<Timestamp as StoredAs<sqlx::Sqlite>>::WORDS, ["INTEGER", "INTEGER"]);
/// # }
/// ```
#[must_use]
pub const fn spans<T: crate::ColumnKind + StoredAs<Db> + ?Sized, Db>() -> bool {
  let width = if T::SEGMENTS.is_empty() {
    1
  } else {
    super::width(T::SEGMENTS)
  };
  T::WORDS.len() == width
}

/// The one-word rows of one dialect: a scalar's whole answer is the word, so the table is the
/// impls.
macro_rules! stored_words {
  ($db:ty { $( $ty:ty => $word:literal ),+ $(,)? }) => {
    $(
      impl StoredAs<$db> for $ty {
        const WORDS: &'static [&'static str] = &[$word];
      }
    )+
  };
}

/// A wrapper that is stored EXACTLY as the thing it wraps, and therefore is spelled exactly as it
/// is.
///
/// One generic row per wrapper rather than one per (wrapper × dialect), which is the shape
/// [`Carrier`](crate::Carrier)'s own `NonZero*`, `Confidence` and `Temporal` rows take: the word is
/// the wrapped type's, so whichever dialect has a word for that carries this for free and there is
/// nothing to enumerate.
macro_rules! stored_as_inner {
  ($( $( #[$attr:meta] )* $ty:ty => $inner:ty ),+ $(,)?) => {
    $(
      $( #[$attr] )*
      impl<Db> StoredAs<Db> for $ty
      where
        $inner: StoredAs<Db>,
      {
        const WORDS: &'static [&'static str] = <$inner as StoredAs<Db>>::WORDS;
      }
    )+
  };
}

/// SQLite's words are its STORAGE CLASSES, and the reason is that its catalogue cannot correct one.
///
/// `pragma_table_info` reports the declared word verbatim, so every legal spelling self-agrees and
/// the audit is no check at all here — which makes the choice a matter of what the word is FOR
/// rather than what it must be. It is for the affinity: a declared `INTEGER` gives INTEGER affinity,
/// `TEXT` gives TEXT affinity, and an RFC 3339 instant stored under TEXT affinity orders
/// lexicographically, which is the order it is meant to have.
///
/// So `bool` is `INTEGER` and not `BOOLEAN`, and the three `time` types are `TEXT` and not
/// `DATETIME`/`DATE`/`TIME`: sqlx binds a bool as `0`/`1` and an instant as a string, and the word
/// names what SQLite actually holds. The alternatives are legal, self-agree, and are named here so
/// that a reader finding one in an older schema knows it was not a mistake — only a different
/// convention. This crate's own hand-written blueprints already use these words.
#[cfg(feature = "sqlite")]
mod sqlite {
  use super::StoredAs;

  stored_words!(sqlx::Sqlite {
    bool => "INTEGER",
    i8 => "INTEGER",
    i16 => "INTEGER",
    i32 => "INTEGER",
    i64 => "INTEGER",
    u8 => "INTEGER",
    u16 => "INTEGER",
    u32 => "INTEGER",
    f32 => "REAL",
    f64 => "REAL",
    String => "TEXT",
    smol_bytes::Utf8Bytes => "TEXT",
    Vec<u8> => "BLOB",
    // `BLOB`, because that is the storage class sqlx binds a `Uuid` into: `Type<Sqlite> for Uuid`
    // answers `DataType::Blob` and the encode pushes `SqliteArgumentValue::Blob` of the sixteen raw
    // bytes. The word is the class rather than a decorative `UUID` for this module's own reason —
    // `pragma_table_info` echoes whatever is declared, so the word buys the AFFINITY and nothing
    // else, and BLOB affinity is what makes the stored value compare bytewise.
    uuid::Uuid => "BLOB",
    crate::BeU64 => "BLOB",
    crate::BeU128 => "BLOB",
    crate::BeI128 => "BLOB",
    crate::Count => "INTEGER",
  });

  // THE PATTERN, on `String`'s own word: a row holds the TEXT `Regex::new` was handed, so the
  // affinity it wants is the one text wants and the class is the same class. The automaton is not
  // stored and has no word here — it is rebuilt from this column on the way back.
  #[cfg(feature = "regex")]
  stored_words!(sqlx::Sqlite { regex::Regex => "TEXT" });

  // The three sqlx encodes as strings — see the module note for why the word is the storage class
  // and not `DATETIME`.
  #[cfg(feature = "time")]
  stored_words!(sqlx::Sqlite {
    time::OffsetDateTime => "TEXT",
    time::PrimitiveDateTime => "TEXT",
    time::Date => "TEXT",
    time::Time => "TEXT",
  });
}

/// PostgreSQL's words are the SQL standard's names, because `information_schema.columns.data_type`
/// answers in them and in nothing else.
///
/// The four WIDENED integers are the visible consequence of reading the carrier rather than the Rust
/// type: `i8` and `u8` bind as `i16`, `u16` as `i32`, `u32` as `i64` — PostgreSQL having no
/// one-byte and no unsigned integer — so their words are the words of the columns they are actually
/// stored in. A row that said `smallint` for a `u32` would have described a column the write lane
/// overflows.
#[cfg(feature = "postgres")]
mod postgres {
  use super::StoredAs;

  stored_words!(sqlx::Postgres {
    bool => "boolean",
    i16 => "smallint",
    i32 => "integer",
    i64 => "bigint",
    f32 => "real",
    f64 => "double precision",
    String => "text",
    smol_bytes::Utf8Bytes => "text",
    Vec<u8> => "bytea",
    // **THE ONE DIALECT WITH A TYPE OF ITS OWN FOR THIS VALUE**, so the word is that type and not a
    // byte column: `Type<Postgres> for Uuid` is `PgTypeInfo::UUID`, and `information_schema` reports
    // `data_type` = `udt_name` = `uuid` for a column declared with it — measured against PostgreSQL
    // 16, where `pg_type` also gives it `typlen` 16. A `bytea` row would have been legal, sixteen
    // bytes wide and WRONG: it forfeits the type's own input parsing, its `uuid` index operator
    // class, and the catalogue would then answer `bytea` to an audit expecting the value's own word.
    uuid::Uuid => "uuid",
    crate::BeU64 => "bytea",
    crate::BeU128 => "bytea",
    crate::BeI128 => "bytea",
    crate::Count => "bigint",
    core::time::Duration => "interval",
    sqlx::postgres::types::PgInterval => "interval",
  });

  // The widened four, whose word is the WIDER column's — see the module note.
  stored_words!(sqlx::Postgres {
    i8 => "smallint",
    u8 => "smallint",
    u16 => "integer",
    u32 => "bigint",
  });

  // THE PATTERN, on `text`'s word for the SQLite row's reason. `text` and not `varchar(n)`: a
  // pattern has no width a schema can name, and PostgreSQL's `text` is the same storage as an
  // unbounded `varchar` with no ceiling to be wrong about.
  #[cfg(feature = "regex")]
  stored_words!(sqlx::Postgres { regex::Regex => "text" });

  #[cfg(feature = "jiff")]
  stored_words!(sqlx::Postgres { crate::PgDuration => "interval" });

  // `data_type` spells out what the driver calls `TIMESTAMPTZ` and `TIME`, and both long forms are
  // measured rather than transcribed.
  #[cfg(feature = "time")]
  stored_words!(sqlx::Postgres {
    time::OffsetDateTime => "timestamp with time zone",
    time::PrimitiveDateTime => "timestamp without time zone",
    time::Date => "date",
    time::Time => "time without time zone",
  });
}

/// MySQL's words are `COLUMN_TYPE`'s, which is the declared type WITH its width and its attributes —
/// so three things a `DATA_TYPE` reading would have hidden are visible in the rows.
///
/// **`bool` is `tinyint(1)`.** MySQL has no boolean type: `BOOLEAN` is a spelling of `TINYINT(1)`
/// and the catalogue answers with what the column became. A row that said `boolean` would build and
/// then fail its audit against a column it created correctly, which is the exact failure the
/// spelling law exists to prevent — and it is the one row where the honest word looks least like the
/// Rust type.
///
/// **An unsigned integer carries ` unsigned` in the word**, the attribute being part of
/// `COLUMN_TYPE` rather than a separate column.
///
/// **A temporal column declares its PRECISION or silently loses it.** A plain `TIMESTAMP` stores
/// whole seconds, so `22:13:20.123456` comes back `22:13:20`; `TIMESTAMP(6)` keeps it. sqlx binds
/// microseconds, so `(6)` is the width that matches what the carrier actually sends, and the
/// catalogue reports the precision with the word.
#[cfg(feature = "mysql")]
mod mysql {
  use super::StoredAs;

  stored_words!(sqlx::MySql {
    bool => "tinyint(1)",
    i8 => "tinyint",
    i16 => "smallint",
    i32 => "int",
    i64 => "bigint",
    u8 => "tinyint unsigned",
    u16 => "smallint unsigned",
    u32 => "int unsigned",
    u64 => "bigint unsigned",
    f32 => "float",
    f64 => "double",
    String => "varchar(255)",
    smol_bytes::Utf8Bytes => "varchar(255)",
    Vec<u8> => "blob",
    // **`binary(16)`, and the WIDTH is in the word for `tinyint(1)`'s own reason** — `COLUMN_TYPE`
    // carries it, so a row saying `binary` would build a `binary(1)` and then disagree with its own
    // catalogue. Sixteen is not a choice: `Type<MySql> for Uuid` delegates to `&[u8]`'s type info
    // and the encode writes the sixteen raw bytes, while the DECODE refuses any other length by name
    // — *Expected 16 bytes, got N* — so a narrower or wider column is a read that fails on the row
    // rather than a value that fits badly. `binary` and not `varbinary`: the value is fixed-width,
    // and a fixed-width column spends no length prefix and pads nothing.
    //
    // Measured against MySQL 8.4: `COLUMN_TYPE` for a column created `binary(16)` is `binary(16)`,
    // where `DATA_TYPE` alone would have said `binary` and lost the width this word has to carry.
    uuid::Uuid => "binary(16)",
    crate::BeU128 => "blob",
    crate::BeI128 => "blob",
    crate::Count => "bigint unsigned",
  });

  // THE PATTERN, on the house's own text word — the same `varchar(255)` `String` and
  // `smol_bytes::Utf8Bytes` take two rows up, because a pattern IS text and a second text word for
  // one kind of text is a convention this table does not have.
  //
  // **255 IS A CEILING AND IT IS THE HOUSE'S, NOT THE VALUE'S.** A uuid earns `binary(16)` because
  // sixteen is a fact about uuids; there is no such number for a pattern, so this row inherits the
  // width every text column here inherits and a pattern longer than 255 bytes is refused by MySQL on
  // the way in exactly as a longer `String` is. A declaration whose patterns run longer spells its
  // own word — the same road any oversized text column takes — and nothing about this row is a claim
  // that 255 is enough.
  #[cfg(feature = "regex")]
  stored_words!(sqlx::MySql { regex::Regex => "varchar(255)" });

  #[cfg(feature = "jiff")]
  stored_words!(sqlx::MySql { crate::MySqlDuration => "time(6)" });

  // `(6)` for the reason the module note gives: a plain `TIMESTAMP`/`TIME` truncates what the
  // carrier binds.
  #[cfg(feature = "time")]
  stored_words!(sqlx::MySql {
    time::OffsetDateTime => "timestamp(6)",
    time::PrimitiveDateTime => "datetime(6)",
    time::Date => "date",
    time::Time => "time(6)",
  });
}

/// A borrowed column is declared as what it borrows — the delegation
/// [`Carrier`](crate::Carrier)'s own borrowed row makes, one layer down.
///
/// `?Sized`, so the row is spellable for an unsized referent; `str` still reaches no dialect, having
/// no row of its own, and `&str` inherits exactly that.
impl<T: StoredAs<Db> + ?Sized, Db> StoredAs<Db> for &T {
  const WORDS: &'static [&'static str] = <T as StoredAs<Db>>::WORDS;
}

/// **A NULLABLE column is declared at its VALUE's type.** Nullability decides what a column may
/// HOLD, not what it is — the `NULL` is a property of the column carried beside the word, which is
/// what [`Column::nullable`](crate::Column::nullable) already states — so an optional field's words
/// are its value's, and there are as many of them.
///
/// Without this row a nullable composite would have fewer words than the same type unwrapped, and
/// the `CREATE TABLE` would come out narrower than the `INSERT` that fills it.
impl<T: StoredAs<Db>, Db> StoredAs<Db> for Option<T> {
  const WORDS: &'static [&'static str] = <T as StoredAs<Db>>::WORDS;
}

/// The typed id is declared as the id it holds — one word, whatever entity it addresses, the marker
/// reaching no column. Its carrier row and its width row both say the same.
impl<I: StoredAs<Db>, E, Db> StoredAs<Db> for crate::TypedId<I, E> {
  const WORDS: &'static [&'static str] = <I as StoredAs<Db>>::WORDS;
}

/// **A CONFIDENCE IS DECLARED AT THE WIDTH IT MEASURES IN.** The `[0.0, 1.0]` invariant is a fact
/// about the domain and a column has no way to carry it, so the word is the width's — and the bound
/// carries the ADMISSION with it, exactly as the width row does: a confidence is spellable in a
/// dialect precisely where the float it measures in is.
impl<S: crate::ConfidenceCarrier + StoredAs<Db>, Db> StoredAs<Db> for crate::Confidence<S> {
  const WORDS: &'static [&'static str] = <S as StoredAs<Db>>::WORDS;
}

/// The temporal wrapper is declared as its inner type, delegating as its carrier and its width rows
/// both do — the crossing to a `time` column is the storage form's business and not a second word.
#[cfg(all(feature = "jiff", feature = "time"))]
impl<T: StoredAs<Db>, Db> StoredAs<Db> for crate::Temporal<T> {
  const WORDS: &'static [&'static str] = <T as StoredAs<Db>>::WORDS;
}

stored_as_inner! {
  /// A `NonZero*` column IS its underlying integer — the invariant belongs to the Rust type and the
  /// column carries none of it — so it is declared as that integer, in whichever dialects have a
  /// word for one. `NonZeroU64` is spellable on MySQL alone and `NonZeroI128`/`NonZeroU128`
  /// nowhere, which is exactly where their integers stand.
  core::num::NonZeroI8 => i8,
  core::num::NonZeroI16 => i16,
  core::num::NonZeroI32 => i32,
  core::num::NonZeroI64 => i64,
  core::num::NonZeroI128 => i128,
  core::num::NonZeroU8 => u8,
  core::num::NonZeroU16 => u16,
  core::num::NonZeroU32 => u32,
  core::num::NonZeroU64 => u64,
  core::num::NonZeroU128 => u128,
}

/// **TWO WORDS OUT, and the pair is read off the parts rather than restated.**
///
/// The framework's own instant occupies two columns — an `i64` second and an `i32` subsecond
/// nanosecond, which is what its [`Carrier`](crate::Carrier) row binds — so its declaration is those
/// two types' own words in that order. Nothing here spells `bigint` or `INTEGER`: a dialect that
/// changed its mind about how it stores an `i64` would move this row with it.
///
/// # Generic over the dialect, which is what the FIXED arity buys
///
/// The array has length two whatever `Db` is, so one impl covers every dialect that carries both
/// parts — all three do. This is the shape every composite in this crate takes, and the boundary it
/// stops at is [`TimeRanged<T>`](crate::TimeRanged)'s: see this module's note, where the two
/// compiler refusals are recorded.
impl<Db> StoredAs<Db> for crate::Timestamp
where
  i64: StoredAs<Db>,
  i32: StoredAs<Db>,
{
  const WORDS: &'static [&'static str] = &[
    <i64 as StoredAs<Db>>::WORDS[0],
    <i32 as StoredAs<Db>>::WORDS[0],
  ];
}

#[cfg(test)]
mod tests;