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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
//! What a stored [`LocalTimestamp`] occupies, binds and reads back — and the DERIVED column the
//! ordering questions are actually answered on.
//!
//! ```text
//!   at_local            TIMESTAMP   the wall clock, as the file wrote it
//!   at_offset_seconds   i32         the displacement east of UTC — 0 where none was stated
//!   at_offset_stated    bool        whether one was stated at all
//!   at_utc_nanos        i64?        the instant, DERIVED and NULLABLE
//! ```
//!
//! # Three columns are the VALUE and one is an INDEX
//!
//! The first three are what a row HOLDS; `utc_nanos` is what a row is ORDERED BY. The split is the
//! only way both questions can be answered exactly:
//!
//! - **The value has to survive.** A wall clock with no offset is a real, complete value — the
//!   commonest one — and a column holding only an instant could neither tell it apart from a zoned
//!   one nor hand either back.
//! - **The order cannot be answered by the value.** Two wall clocks in different zones are not
//!   comparable through `local` at all: `16:45+09:00` is EARLIER than `10:00+00:00`, and a sort
//!   leading with the clock face would put them the other way round. There is exactly ONE quantity
//!   every stored instant shares, and [`LocalTimestamp::to_utc_nanos`] is the crossing into it.
//!
//! The decode reads the VALUE and never the index — a derived column that could redefine the value
//! it was derived from is a second authority, and the whole point of deriving it is that there is
//! one.
//!
//! # The two-leaf offset, and the arrangement the decode REFUSES
//!
//! `offset_seconds` and `offset_stated` are ONE `Option<Offset>` spelled in two `NOT NULL` columns,
//! for the reason the module note states: the shape vocabulary has no word for a value leaf that may
//! be `NULL`, and giving one a `NULL` poisons the row-value equality that finds the row again.
//!
//! Two columns admit one arrangement the type does not — an unstated offset beside a non-zero
//! displacement — and [`Assemble`](crate::Assemble) REFUSES it rather than reading the seconds and
//! ignoring the flag, or reading the flag and ignoring the seconds. It is
//! [`Timestamp::from_parts`](crate::Timestamp::from_parts)'s posture applied one type over: a stored
//! pair nothing here wrote is a decode error at the row that holds it, never a value silently
//! rounded into one that could have been written.
//!
//! # The overflow posture, stated
//!
//! [`LocalTimestamp::to_utc_nanos`] declines for two reasons — no stated zone, and past the ±292-year
//! `i64` ceiling — and the three places that refusal can land each take it differently:
//!
//! | where | posture |
//! |---|---|
//! | the WRITE | the value columns are exact whatever the value; the derived column binds `NULL` |
//! | the READ | unaffected — the decode rebuilds from the three value columns, which never decline |
//! | the QUERY | an OPERAND is a `Timestamp`, which already HAS a position, so nothing is refused at the crossing |
//!
//! The third row is where this house differs from the media instant's, and the difference is the
//! operand: a semantic operand here is a UTC instant rather than a value of this type, so it goes
//! through no derivation and has nothing to fail at. What CANNOT be asked semantically is a value
//! with no zone — and that is answered by there being no row for it in the index, rather than by a
//! refusal.

use crate::{
  ColumnKind, ColumnName, ColumnShape, CursorValue, FieldName, OrderLevel, column::column_eq,
};
use jiff::{civil, tz};

use super::LocalTimestamp;

#[cfg(test)]
mod tests;

/// The wall clock's segment.
pub(super) const LOCAL: &FieldName = FieldName::new("local");

/// The displacement's segment, in seconds east of UTC.
pub(super) const OFFSET_SECONDS: &FieldName = FieldName::new("offset_seconds");

/// The presence bit's segment — whether a zone was stated at all.
pub(super) const OFFSET_STATED: &FieldName = FieldName::new("offset_stated");

/// The derived sort key's segment.
pub(super) const UTC_NANOS: &FieldName = FieldName::new("utc_nanos");

/// **The columns a capture time spans**, and the one authority the width, the bind, the decode and
/// every lowering read.
///
/// **The last entry is [`Nullable`](ColumnShape::Nullable)**, which is this module's posture spelled
/// where a renderer can read it: the derived column binds `NULL` for a value with no stated zone and
/// for one past the nanosecond ceiling, and the bit being the LEAF's is what lets a REQUIRED
/// `at: LocalTimestamp` declare `at_utc_nanos` nullable while its three value columns stay
/// `NOT NULL`. Under a nullability that was the FIELD's, the write would bind the `NULL` the DDL
/// forbade and the engine would refuse the very row the write path promised to store.
///
/// **The three before it are all [`Plain`](ColumnShape::Plain)**, including the two the offset is
/// spelled in — see the module note, where the missing fourth corner of the shape vocabulary is
/// what makes the presence bit a column rather than a `NULL`.
pub(super) const SEGMENTS: &[ColumnShape] = &[
  ColumnShape::Plain(ColumnName::of(LOCAL)),
  ColumnShape::Plain(ColumnName::of(OFFSET_SECONDS)),
  ColumnShape::Plain(ColumnName::of(OFFSET_STATED)),
  ColumnShape::Nullable(ColumnName::of(UTC_NANOS)),
];

/// **The order those four columns MEAN**, which is not the order they are written in.
///
/// The leaves are numbered as [`width`](crate::width) counts them — `local` is `0`,
/// `offset_seconds` is `1`, `offset_stated` is `2` and the derived `utc_nanos` is `3` — so this
/// sequence is *utc_nanos, local, offset_seconds, offset_stated*.
///
/// # Why the derived leaf LEADS
///
/// A wall clock is a reading on a face whose zone the row itself declares, so two rows in different
/// zones are not comparable through it: `2021-08-14T16:45+09:00` is eight hours BEFORE
/// `2021-08-14T16:45+01:00`, and a sort leading with `local` would call them equal. The one quantity
/// every stored instant shares is the derived nanosecond position, so the SEMANTIC order leads with
/// it and the value leaves follow as the tie-break that gives two rows at one instant — or two rows
/// with no instant at all — a stable total order.
///
/// # The NULL partition is where the unzoned values live, and it is a partition rather than a gap
///
/// Every value with no stated zone has `utc_nanos IS NULL`, so the whole unzoned half of a table is
/// ONE partition at one end of this level, ordered among itself by the three levels below —
/// `local`, then the offset pair. A keyset page therefore walks the zoned rows in instant order,
/// crosses the partition boundary once, and walks the unzoned rows in wall-clock order, resuming
/// exactly in both. That walk is what `ingraph/tests/local_timestamp_optional.rs` runs.
///
/// # It is the 2026-08-29 law's SEMANTIC half
///
/// *A derived leaf serves the semantic order only; every structural judgment walks value leaves
/// only.* The structural half is the keyset's null test and row-value equality, both of which read
/// [`value_width`](crate::value_width) and therefore never see this column. Ordering by it is the
/// lawful side of that discipline rather than an exception to it: participation in the ORDER is
/// exactly what the leaf is computed for.
pub(super) const ORDER: &[OrderLevel] = &[
  OrderLevel::new(3),
  OrderLevel::new(0),
  OrderLevel::new(1),
  OrderLevel::new(2),
];

impl ColumnKind for LocalTimestamp {
  const SEGMENTS: &'static [ColumnShape] = SEGMENTS;
  const ORDER: &'static [OrderLevel] = ORDER;
}

// A capture time is one column value when its wall clock and its stated zone both are — the
// derived instant plays no part, being an index rather than a value leaf, and this type's own
// `PartialEq` already reads exactly those two fields.
column_eq! { LocalTimestamp }

/// **The VALUE one of those four levels compares** — the per-leaf vocabulary the citizen publishes
/// beside its sequence, and the type an emitted cursor's slot is minted with for a column of this
/// type.
///
/// One member per leaf, each carrying that leaf's own STORAGE type, in the segment numbering. The
/// wall clock's member holds jiff's [`civil::DateTime`] rather than the `time` type its column binds
/// as, because a leaf is a VALUE first and its bind is a projection: the crossing is the same
/// [`TemporalStorage`](crate::TemporalStorage) row the whole value's bind spends, applied at one
/// leaf.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LocalTimestampLeaf {
  /// Leaf `0` — the wall clock the source wrote.
  Local(civil::DateTime),
  /// Leaf `1` — the displacement east of UTC, in seconds; `0` where none was stated.
  OffsetSeconds(i32),
  /// Leaf `2` — whether a zone was stated at all.
  OffsetStated(bool),
  /// Leaf `3` — the DERIVED instant in nanoseconds, recomputed rather than carried.
  UtcNanos(i64),
}

// One leaf is the same as another leaf when it is the SAME leaf holding the same bytes — the tag
// and the value both, which is what this enum's own derived `PartialEq` already gives.
column_eq! { LocalTimestampLeaf }

/// **The four leaves, and the derived one RECOMPUTED at the call.**
///
/// `utc_nanos` is a function of the value leaves and is stored by nobody — not by the decode, not by
/// the whole value's own [`CursorValue`] row. A level over it asks
/// [`LocalTimestamp::to_utc_nanos`], which is the same computation the write binds, so a boundary is
/// the value the statement sorted by. Where that declines it answers [`None`], which is the same
/// `NULL` the write writes and becomes the cursor slot's own absence — and the keyset's `NULL` arms
/// then place the row where the `ORDER BY` put it.
impl crate::OrderLeaves for LocalTimestamp {
  type Leaf = LocalTimestampLeaf;

  fn leaf(&self, at: usize) -> Option<LocalTimestampLeaf> {
    match at {
      0 => Some(LocalTimestampLeaf::Local(self.local())),
      1 => Some(LocalTimestampLeaf::OffsetSeconds(
        self.offset().map_or(0, |offset| offset.seconds()),
      )),
      2 => Some(LocalTimestampLeaf::OffsetStated(self.is_zoned())),
      3 => self.to_utc_nanos().ok().map(LocalTimestampLeaf::UtcNanos),
      _ => None,
    }
  }
}

/// **The KEYSET position of ONE leaf**: which leaf, then that leaf's own bytes.
///
/// The tag is what makes the read total. A slot is length-delimited by the cursor and holds nothing
/// else, so a sum has to say which member it is — the bytes are a CLIENT's, so a byte naming no leaf
/// is refused rather than read as the nearest one.
impl CursorValue for LocalTimestampLeaf {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    match self {
      Self::Local(local) => {
        out.push(0);
        write_civil(local, out);
      }
      Self::OffsetSeconds(seconds) => {
        out.push(1);
        CursorValue::write_cursor(seconds, out);
      }
      Self::OffsetStated(stated) => {
        out.push(2);
        CursorValue::write_cursor(stated, out);
      }
      Self::UtcNanos(nanos) => {
        out.push(3);
        CursorValue::write_cursor(nanos, out);
      }
    }
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let (tag, value) = bytes.split_first()?;
    match tag {
      0 => read_civil(value).map(Self::Local),
      1 => <i32 as CursorValue>::read_cursor(value).map(Self::OffsetSeconds),
      2 => <bool as CursorValue>::read_cursor(value).map(Self::OffsetStated),
      3 => <i64 as CursorValue>::read_cursor(value).map(Self::UtcNanos),
      _ => None,
    }
  }
}

/// A civil datetime's eleven cursor bytes: `i16` year, then five `i8` clock fields, then the `i32`
/// subsecond, each big-endian.
///
/// FIXED WIDTH, so a client's ten or twelve are refused rather than zero-extended into a plausible
/// datetime — the discipline every integer row in [`CursorValue`] follows, applied to a value of
/// seven of them.
///
/// It is the FIELDS rather than a count of nanoseconds, and that is the weaker assumption: a count
/// would need an epoch and a range this type does not otherwise have, where the fields are what the
/// value already is on both sides.
const CIVIL_WIDTH: usize = size_of::<i16>() + 5 + size_of::<i32>();

fn write_civil(local: &civil::DateTime, out: &mut Vec<u8>) {
  out.extend_from_slice(&local.year().to_be_bytes());
  out.push(local.month() as u8);
  out.push(local.day() as u8);
  out.push(local.hour() as u8);
  out.push(local.minute() as u8);
  out.push(local.second() as u8);
  out.extend_from_slice(&local.subsec_nanosecond().to_be_bytes());
}

/// The inverse, and jiff is the one that says which byte strings are datetimes: a month of `13` or a
/// day of `31` in February is [`None`] here because [`civil::DateTime::new`] refuses it, rather than
/// because of a bound restated in this file.
fn read_civil(bytes: &[u8]) -> Option<civil::DateTime> {
  if bytes.len() != CIVIL_WIDTH {
    return None;
  }
  let year = i16::from_be_bytes(bytes[0..2].try_into().ok()?);
  let subsec = i32::from_be_bytes(bytes[7..11].try_into().ok()?);
  civil::DateTime::new(
    year,
    bytes[2] as i8,
    bytes[3] as i8,
    bytes[4] as i8,
    bytes[5] as i8,
    bytes[6] as i8,
    subsec,
  )
  .ok()
}

/// **ONE BIND OUT**, through the row the leaf's own type already had.
///
/// A level names one column, so its operand is one placeholder — and which row answers is the
/// member's. The wall clock crosses through [`TemporalStorage`](crate::TemporalStorage) on the way,
/// which is the same crossing the whole value's bind makes, so a boundary and a stored row are
/// written by one function.
/// [`push_value_bind`](crate::Carrier::push_value_bind) takes its default: a leaf has no derived
/// leaf inside it to leave out.
#[cfg(all(feature = "sqlx", feature = "time"))]
impl<Db> crate::Carrier<Db> for LocalTimestampLeaf
where
  Db: sqlx::Database,
  bool: crate::Carrier<Db>,
  i32: crate::Carrier<Db>,
  i64: crate::Carrier<Db>,
  crate::Temporal<time::PrimitiveDateTime>: crate::Carrier<Db>,
{
  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    match self {
      Self::Local(local) => {
        <crate::Temporal<time::PrimitiveDateTime> as crate::Carrier<Db>>::push_bind(
          &crate::Temporal::from(*local),
          qb,
        );
      }
      Self::OffsetSeconds(value) => <i32 as crate::Carrier<Db>>::push_bind(value, qb),
      Self::OffsetStated(value) => <bool as crate::Carrier<Db>>::push_bind(value, qb),
      Self::UtcNanos(value) => <i64 as crate::Carrier<Db>>::push_bind(value, qb),
    }
  }
}

/// **The DECLARED half — FOUR words**, each read off the leaf type's own row so that a dialect
/// changing its word for a wall clock, an integer or a boolean moves this declaration and there is
/// no second list to drift from.
#[cfg(feature = "time")]
impl<Db> crate::StoredAs<Db> for LocalTimestamp
where
  bool: crate::StoredAs<Db>,
  i32: crate::StoredAs<Db>,
  i64: crate::StoredAs<Db>,
  time::PrimitiveDateTime: crate::StoredAs<Db>,
{
  const WORDS: &'static [&'static str] = &[
    <time::PrimitiveDateTime as crate::StoredAs<Db>>::WORDS[0],
    <i32 as crate::StoredAs<Db>>::WORDS[0],
    <bool as crate::StoredAs<Db>>::WORDS[0],
    <i64 as crate::StoredAs<Db>>::WORDS[0],
  ];
}

/// **THE ADMISSION.** A capture time is a clock reading and the zone it was read on; it carries no
/// collection, so it is one element of one.
impl crate::CollectionElement for LocalTimestamp {}

/// **The KEYSET position**: the VALUE leaves, big-endian — the wall clock, then the offset pair.
///
/// The derived key is deliberately absent. A page resumes by comparing a boundary against what it
/// was cut at, and a value with no stated zone would have no boundary to be cut at; the three value
/// leaves always have one. It also keeps the cursor exactly as wide as the value it names.
impl CursorValue for LocalTimestamp {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    write_civil(&self.local(), out);
    CursorValue::write_cursor(&self.offset().map_or(0, |offset| offset.seconds()), out);
    CursorValue::write_cursor(&self.is_zoned(), out);
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let (local, rest) = bytes.split_at_checked(CIVIL_WIDTH)?;
    let (seconds, stated) = rest.split_at_checked(size_of::<i32>())?;

    let local = read_civil(local)?;
    let seconds = <i32 as CursorValue>::read_cursor(seconds)?;
    let stated = <bool as CursorValue>::read_cursor(stated)?;

    // The SAME refusal the decode makes, and for the same reason: a pair naming an unstated zone
    // beside a displacement is not a value this type writes, so reading one back would be inventing
    // a boundary out of bytes nothing here produced.
    offset_of(seconds, stated)
      .ok()
      .map(|offset| Self::new(local, offset))
  }
}

/// **FOUR BINDS OUT** — three that carry the value and one that carries its position.
///
/// The derived one is written as `NULL` rather than bound when the value has no instant, which is
/// the shape `ingraph`'s own nullable carrier takes and for its reason: a `None` has no value to
/// hand sqlx, and the column's type is decided by the DDL rather than by a placeholder.
///
/// **AND THREE FOR A STRUCTURAL JUDGMENT.** The `NULL` above is exactly why the value-leaf bind
/// exists: an equality that spent it would compare `NULL = NULL`, which is UNKNOWN, so an unzoned
/// capture time could never be matched by the very tuple that wrote it — ingraph #455's bug, one
/// citizen over. The narrow bind is the WRITE's own first three pushes, and its width is
/// `value_width(SEGMENTS)`.
#[cfg(all(feature = "sqlx", feature = "time"))]
impl<Db> crate::Carrier<Db> for LocalTimestamp
where
  Db: sqlx::Database,
  bool: crate::Carrier<Db>,
  i32: crate::Carrier<Db>,
  i64: crate::Carrier<Db>,
  crate::Temporal<time::PrimitiveDateTime>: crate::Carrier<Db>,
{
  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    self.push_value_bind(qb);
    qb.push(", ");
    match self.to_utc_nanos() {
      Ok(nanos) => <i64 as crate::Carrier<Db>>::push_bind(&nanos, qb),
      Err(_) => {
        qb.push("NULL");
      }
    }
  }

  fn push_value_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    <crate::Temporal<time::PrimitiveDateTime> as crate::Carrier<Db>>::push_bind(
      &crate::Temporal::from(self.local()),
      qb,
    );
    qb.push(", ");
    <i32 as crate::Carrier<Db>>::push_bind(&self.offset().map_or(0, |offset| offset.seconds()), qb);
    qb.push(", ");
    <bool as crate::Carrier<Db>>::push_bind(&self.is_zoned(), qb);
  }
}

/// **AND THE VALUE BACK IN** — the wall clock and the offset pair, by name, and never the derived
/// key.
///
/// Reading the key would give a row two ways to say what value it holds, and a derived column exists
/// precisely so that there is one. It also means a row whose key is `NULL` decodes exactly like any
/// other, which is what keeps the posture above a fact about ORDERING alone.
///
/// Two refusals, both of a STORED value rather than of a caller's arithmetic: the wall clock's
/// components must be a datetime jiff admits, and the offset pair must be one this type writes.
#[cfg(all(feature = "sqlx", feature = "time"))]
impl<'a, R: sqlx::Row> crate::Assemble<'a, R> for LocalTimestamp
where
  bool: crate::Assemble<'a, R>,
  i32: crate::Assemble<'a, R>,
  time::PrimitiveDateTime: crate::Assemble<'a, R>,
{
  fn assemble(row: &'a R, under: Option<&crate::Path<'_>>) -> sqlx::Result<Self> {
    let local: time::PrimitiveDateTime = crate::assembled(row, LOCAL, under)?;
    let seconds: i32 = crate::assembled(row, OFFSET_SECONDS, under)?;
    let stated: bool = crate::assembled(row, OFFSET_STATED, under)?;

    let local = civil_of(local).map_err(|refused| sqlx::Error::ColumnDecode {
      index: LOCAL.as_str().to_owned(),
      source: Box::new(refused),
    })?;
    let offset = offset_of(seconds, stated).map_err(|refused| sqlx::Error::ColumnDecode {
      index: OFFSET_SECONDS.as_str().to_owned(),
      source: Box::new(refused),
    })?;

    Ok(Self::new(local, offset))
  }
}

/// The REVERSE crossing, which [`TemporalStorage`](crate::TemporalStorage) does not state: a stored
/// `time::PrimitiveDateTime` back into the wall clock it was written from.
///
/// # It is fallible, and the fallibility is a FEATURE UNIFICATION rather than a range mismatch
///
/// `time`'s default civil span is `±9999`, which is jiff's exactly — so on this crate's own
/// dependency row the crossing cannot fail. `time`'s `large-dates` feature widens its year to
/// `±999_999`, and a downstream that turns it on gets that widened type here through cargo's feature
/// unification without this crate ever asking for it. So the year is CHECKED rather than cast: a
/// column holding `+123456-01-01` is a decode error naming the column, not a wall clock silently
/// wrapped into a different millennium.
pub(super) fn civil_of(
  stored: time::PrimitiveDateTime,
) -> Result<civil::DateTime, LocalTimestampPartsError> {
  let year = i16::try_from(stored.year()).map_err(|_| LocalTimestampPartsError::Year {
    year: stored.year(),
  })?;

  civil::DateTime::new(
    year,
    u8::from(stored.month()) as i8,
    stored.day() as i8,
    stored.hour() as i8,
    stored.minute() as i8,
    stored.second() as i8,
    stored.nanosecond() as i32,
  )
  .map_err(LocalTimestampPartsError::Local)
}

/// The offset PAIR back into the `Option` it spells, and the one arrangement it refuses.
///
/// `stated = false` beside a non-zero displacement is not a value this type writes: it is a pair
/// whose two halves disagree, and reading it would mean choosing which half to believe. Refused,
/// carrying the seconds, exactly as [`Timestamp::from_parts`](crate::Timestamp::from_parts) refuses
/// a sign-crossing pair and carries both numbers.
pub(super) fn offset_of(
  seconds: i32,
  stated: bool,
) -> Result<Option<tz::Offset>, LocalTimestampPartsError> {
  if !stated {
    return if seconds == 0 {
      Ok(None)
    } else {
      Err(LocalTimestampPartsError::Unstated { seconds })
    };
  }

  tz::Offset::from_seconds(seconds)
    .map(Some)
    .map_err(LocalTimestampPartsError::Offset)
}

/// Why a stored `(local, offset_seconds, offset_stated)` triple is not a capture time.
///
/// Every variant is a REFUSAL of a stored value rather than of a caller's arithmetic, which is what
/// puts them on a decode path: [`Assemble`](crate::Assemble) turns one into
/// [`sqlx::Error::ColumnDecode`] naming the column that carried it, and the MongoDB family turns one
/// into [`MongoTypeError::Range`](crate::query::mongo::MongoTypeError).
///
/// No [`PartialEq`], deliberately: [`jiff::Error`] has none, so an equality here would either compare
/// rendered text — which is jiff's to change — or ignore the half that carries the reason. A test
/// asserts on the VARIANT and on the numbers, which is what a caller can act on.
#[derive(Debug, Clone)]
pub enum LocalTimestampPartsError {
  /// The stored year does not fit jiff's `i16`, which is reachable only where `time`'s
  /// `large-dates` feature is on somewhere in the build — see [`civil_of`].
  Year {
    /// The year the column held.
    year: i32,
  },
  /// jiff refused the stored clock fields outright.
  ///
  /// Carries jiff's own error, which names what it refused and why.
  Local(jiff::Error),
  /// jiff refused the stored displacement: a value outside `±25:59:59`.
  Offset(jiff::Error),
  /// The pair says no zone was stated and then states one.
  ///
  /// Carries the displacement that was stored, because the number together with the flag is the fact
  /// a reader needs — either alone is unremarkable.
  Unstated {
    /// The `offset_seconds` column's value.
    seconds: i32,
  },
}

impl core::fmt::Display for LocalTimestampPartsError {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self {
      Self::Year { year } => write!(
        f,
        "the stored year {year} is outside the -9999..=9999 span a wall clock is written in"
      ),
      Self::Local(cause) => write!(f, "the stored fields are not a wall clock: {cause}"),
      Self::Offset(cause) => write!(f, "the stored seconds are not a zone offset: {cause}"),
      Self::Unstated { seconds } => write!(
        f,
        "the stored pair says no zone was stated and then states {seconds} seconds of one, which \
         is not a spelling a capture time is written as"
      ),
    }
  }
}

impl core::error::Error for LocalTimestampPartsError {
  fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
    match self {
      Self::Local(cause) | Self::Offset(cause) => Some(cause),
      Self::Year { .. } | Self::Unstated { .. } => None,
    }
  }
}

/// **THE BSON FORM: one sub-document, four keys, written in the ORDER the levels mean.**
///
/// ```text
///   { "utc_nanos": 1628926509000000000, "local": "2021-08-14T16:45:09",
///     "offset_seconds": 32400, "offset_stated": true }
/// ```
///
/// It NESTS where the table flattens, which is the asymmetry [`MongoCarrier`](crate::MongoCarrier)'s
/// own instant row already states: SQL's namespace is flat and BSON's is not. **The SEGMENTS are the
/// same segments** — the four leaves a table joins with `_` are the four a document reaches as
/// `at.local`.
///
/// The derived key is written FIRST and `null` where there is none, so that BSON's own field-by-field
/// document comparison agrees with [`ORDER`]: the instant, then the wall clock, then the offset pair.
/// The wall clock is its ISO 8601 text, which is the form BSON can both hold and compare — there is
/// no BSON type for a datetime without a zone, and `UtcDateTime` would invent the one fact this value
/// does not have.
#[cfg(feature = "mongo")]
impl crate::MongoCarrier for LocalTimestamp {
  fn to_bson(&self) -> bson::Bson {
    let mut held = bson::Document::new();
    held.insert(
      UTC_NANOS.as_str(),
      match self.to_utc_nanos() {
        Ok(nanos) => bson::Bson::Int64(nanos),
        Err(_) => bson::Bson::Null,
      },
    );
    held.insert(LOCAL.as_str(), self.local().to_string());
    held.insert(
      OFFSET_SECONDS.as_str(),
      self.offset().map_or(0, |offset| offset.seconds()),
    );
    held.insert(OFFSET_STATED.as_str(), self.is_zoned());
    bson::Bson::Document(held)
  }
}

/// **THE READ: three keys back into a capture time** — [`MongoCarrier`](crate::MongoCarrier)'s
/// mirror, and the derived key is not among them for the reason the SQL decode leaves it out.
///
/// Both refusals are the SQL decode's own, through [`offset_of`] and jiff's parser, so one document
/// and one row cannot disagree about which triples are capture times.
#[cfg(feature = "mongo")]
impl crate::query::mongo::MongoExtract for LocalTimestamp {
  const BSON: &'static str = "object";

  fn extract(value: Option<&bson::Bson>) -> Result<Self, crate::query::mongo::MongoTypeError> {
    use crate::query::mongo::MongoTypeError;

    /// A fixed sentence, which is what [`MongoTypeError::Range`] holds: that variant carries a
    /// `&'static str`, so the values that failed cannot travel with it. The SQL decode keeps them,
    /// and the difference between the two families is the vocabulary rather than the check.
    const REFUSED: &str = "this field holds a `local`, `offset_seconds` and `offset_stated` triple \
                           that is not a capture time";

    let held = match value {
      Some(bson::Bson::Document(held)) => held,
      Some(other) => {
        return Err(MongoTypeError::wrong_type(
          Self::BSON,
          crate::query::mongo::alias(other),
        ));
      }
      None => return Err(MongoTypeError::Absent),
    };

    let local = match held.get(LOCAL.as_str()) {
      Some(bson::Bson::String(text)) => text
        .parse::<civil::DateTime>()
        .map_err(|_| MongoTypeError::Range(REFUSED))?,
      Some(other) => {
        return Err(MongoTypeError::wrong_type(
          "string",
          crate::query::mongo::alias(other),
        ));
      }
      None => return Err(MongoTypeError::Absent),
    };
    let seconds = i32::extract(held.get(OFFSET_SECONDS.as_str()))?;
    let stated = bool::extract(held.get(OFFSET_STATED.as_str()))?;

    offset_of(seconds, stated)
      .map(|offset| Self::new(local, offset))
      .map_err(|_| MongoTypeError::Range(REFUSED))
  }
}