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
//! The temporal crossing: [`TemporalStorage`], and the six rows that give jiff's registered types
//! a storage form.
//!
//! A `jiff::Timestamp` field has had a filter since the vocabulary landed and no way to reach a
//! column: sqlx 0.9 ships no jiff integration, so the type had to become an integer through a
//! declared converter and a timestamp column stopped being temporal. This module is the map from
//! each jiff type to the `time` type that carries it, and nothing else — no arithmetic, no
//! formatting, no zone lookup.
//!
//! # Why a local trait rather than named converter functions
//!
//! `impl TryFrom<jiff::Timestamp> for time::OffsetDateTime` is `E0117` here: both types are foreign,
//! so the conversion cannot be spelled with std's vocabulary from this crate. The conclusion that
//! the conversion must therefore be a FUNCTION a declaration points at does not follow — `E0117`
//! fires because [`TryFrom`] is foreign, and a **local** trait implemented for a foreign type is
//! ordinary and legal. That is what this trait is.
//!
//! The difference is not ergonomic. A named converter is a magic string at a boundary the type
//! system already knows the answer for: the field says `at: Timestamp` and there is exactly one
//! storage form it wants. `<db>(into = …)` stays available for a field that wants a different
//! one, as the escape rather than as the mandatory path.
//!
//! # Why `time` and not `chrono`
//!
//! Both ship for all three dialects in sqlx 0.9, SQLite included, so availability decides nothing.
//! What decides it is that this is a CONVERSION CARRIER and not a date library:
//!
//! - time's four types map 1:1 onto the five jiff types that reach a `time` column, with
//!   `Timestamp` and `Zoned` sharing one. The sixth registered type, `tz::Offset`, reaches an `i32`
//!   instead, for the reason its own row states.
//! - chrono's zone-aware path pulls a SECOND timezone database (`iana-time-zone`, for `Local`) into
//!   a binary that already carries jiff's — two tzdbs that can disagree, for a capability this
//!   layer never uses.
//! - time is no-std-capable, which matters to a crate whose `--no-default-features` lane is a
//!   first-class build.
//!
//! The choice is also low-stakes, because [`Carrier`](crate::Carrier) is open: a downstream that
//! would rather bind `chrono::DateTime<Utc>` writes one row and joins the same comparison
//! vocabulary. What ships built-in is being chosen here, not what anyone is allowed to use.
//!
//! # All six crossings are TOTAL, and that is measured
//!
//! | source | range | target | range | fallible |
//! |---|---|---|---|---|
//! | `jiff::Timestamp` | `-9999-01-02T01:59:59Z` ..= `9999-12-30T22:00:00.999999999Z` | [`time::OffsetDateTime`] | `-9999-01-01T00:00:00Z` ..= `9999-12-31T23:59:59.999999999Z` | no |
//! | `jiff::Zoned` | its `timestamp()`, so the row above | [`time::OffsetDateTime`] | as above | no |
//! | `jiff::civil::Date` | `-9999-01-01` ..= `9999-12-31` | [`time::Date`] | `-9999-01-01` ..= `9999-12-31` | no |
//! | `jiff::civil::Time` | `00:00:00` ..= `23:59:59.999999999` | [`time::Time`] | `00:00:00` ..= `23:59:59.999999999` | no |
//! | `jiff::civil::DateTime` | the two civil rows, paired | [`time::PrimitiveDateTime`] | the two civil rows, paired | no |
//! | `jiff::tz::Offset` | `-25:59:59` ..= `25:59:59`, so `-93_599 ..= 93_599` seconds | `i32` | `-2_147_483_648 ..= 2_147_483_647` | no |
//!
//! The civil rows are the SAME span on both sides, and the DATETIME row is that fact read at the
//! pair: it is built out of the two beneath it rather than out of a third arithmetic, so there is no
//! range it could fail on that they do not already answer for. The OFFSET row is the one crossing
//! whose target is not a `time` type — see its own note, where sqlx's missing row is the reason and
//! the `i32` is measured against jiff's own bounds. The instant row has `25:59:59` of headroom
//! at each end, and that is not luck: jiff picks `Timestamp::MIN`/`MAX` so that either combined with
//! any legal offset still lands inside `-9999-01-01 ..= 9999-12-31`, and `±25:59:59` is
//! `jiff::tz::Offset`'s own range. time's default civil span is that same `±9999`.
//!
//! So [`to_storage`](TemporalStorage::to_storage) returns the VALUE. A `Result` that can never be
//! `Err` is noise every caller pays for, and the alternative — a trait split into fallible and
//! infallible halves — would put the same noise in the type system instead.
//!
//! **What would have made it fallible is an `i64`-nanosecond intermediate**, which tops out at about
//! ±292 years and is three orders of magnitude short. This design does not go through one:
//! `jiff::Timestamp::as_nanosecond` is an `i128` and
//! [`time::OffsetDateTime::from_unix_timestamp_nanos`] takes an `i128`. The intermediate was the
//! fallibility, not the crossing.
//!
//! # Precision survives the crossing, and not every bind
//!
//! The five `time` rows carry NANOSECONDS — an offset has no subsecond component to carry — and the
//! tests pin it at both extremes and on both sides of the epoch — jiff reports `subsec_nanosecond()` with the sign of the timestamp,
//! so the negative half is its own case rather than a symmetry.
//!
//! What happens one layer down is sqlx's and differs per dialect, measured against 0.9:
//!
//! | dialect | column | sub-microsecond operand |
//! |---|---|---|
//! | SQLite | RFC 3339 text | preserved — but a year outside `0000..=9999` is an ERROR at the bind, because RFC 3339 has no spelling for one |
//! | Postgres | `TIMESTAMPTZ`, `TIMESTAMP`, `DATE`, `TIME` | **silently truncated** — the encoder takes `whole_microseconds()` |
//! | MySQL | `TIMESTAMP`, `DATETIME`, `DATE`, `TIME` | **silently truncated** — the encoder takes `nanosecond() / 1000` |
//!
//! That is the same shape `MySqlTime::try_from(Duration)` has, and this crate refuses it for a
//! duration through [`MySqlDuration`](crate::MySqlDuration). It is NOT refused here, and the reason
//! is that the refusal would have to be per-dialect while this crossing is not: SQLite holds the
//! nanoseconds, so a check at the crossing would reject a value one of the three dialects stores
//! exactly. A dialect-scoped carrier that refuses is the shape that would fit, and it is not built
//! because nothing has asked for one — the fact is recorded here so that the asking is informed.

use jiff::{Timestamp, Zoned, civil};

/// The storage form of a temporal value, keyed on the value's own type.
///
/// One trait, six rows, no method to name from a declaration: the field's type IS the answer, and
/// the framework reads it. Public and open — a downstream temporal type joins by implementing this
/// and supplying a [`Carrier`](crate::Carrier) row for whatever it names as `Storage`.
///
/// # Total, so no `Result`
///
/// Every built-in row is a range measurement, not a hope; see the module's table. A crossing added
/// downstream that CANNOT be total belongs in `<db>(try_into = …)`, where a refusal has
/// somewhere to go — this trait's shape is the claim that the conversion has nothing to refuse.
pub trait TemporalStorage {
  /// The type a column holds this value as.
  type Storage;

  /// Convert into the storage form.
  fn to_storage(&self) -> Self::Storage;
}

impl TemporalStorage for Timestamp {
  type Storage = time::OffsetDateTime;

  fn to_storage(&self) -> Self::Storage {
    // `as_nanosecond` is an `i128` and so is the parameter, so the whole instant crosses in one
    // piece. Splitting it into `(as_second, subsec_nanosecond)` would ALSO be lossless and is the
    // trap it looks like the safer route: jiff gives the subsecond part the sign of the timestamp,
    // so `-1ns` arrives as `(0, -1)` and any constructor expecting an unsigned remainder is wrong
    // by a second for every value before the epoch.
    time::OffsetDateTime::from_unix_timestamp_nanos(self.as_nanosecond())
      .expect("jiff's instant range sits inside time's with 25:59:59 to spare at each end")
  }
}

/// A [`Zoned`] stores its INSTANT, normalized to UTC. The zone is dropped, and three measurements
/// agree that dropping it loses nothing this layer could have used:
///
/// - `Zoned`'s [`Ord`], [`Eq`] and [`Hash`] all delegate to `timestamp()`, so no operator the
///   comparison layer renders can read the zone.
/// - sqlx's Postgres and MySQL encoders both call `to_offset(UTC)` before binding, so a preserved
///   offset would be normalized away one layer down regardless.
/// - sqlx's SQLite encoder formats RFC 3339 WITH the offset — so SQLite is the one dialect where a
///   preserved offset would survive, as text that sorts against a UTC column wrongly. The dialect
///   that could keep it is the dialect where keeping it breaks the comparison.
impl TemporalStorage for Zoned {
  type Storage = time::OffsetDateTime;

  #[inline]
  fn to_storage(&self) -> Self::Storage {
    self.timestamp().to_storage()
  }
}

/// Crossed through (year, month, day) rather than through the ordinal day, because that is the
/// weaker assumption about the two calendars: both are proleptic Gregorian, and a civil date is the
/// place they could differ only if one of them numbered years or months differently. The negative
/// leap day `-4000-02-29` is in the tests for exactly that reason.
impl TemporalStorage for civil::Date {
  type Storage = time::Date;

  fn to_storage(&self) -> Self::Storage {
    // jiff's month is 1..=12 and its day 1..=31, both `i8`; its year is `-9999..=9999`, an `i16`
    // that widens into time's `i32` with room to spare. `Month::try_from` and `from_calendar_date`
    // report the same error type, so the two steps compose into one refusal that cannot happen.
    time::Month::try_from(self.month() as u8)
      .and_then(|month| {
        time::Date::from_calendar_date(i32::from(self.year()), month, self.day() as u8)
      })
      .expect("jiff's date range and time's are the same span, -9999-01-01 ..= 9999-12-31")
  }
}

impl TemporalStorage for civil::Time {
  type Storage = time::Time;

  fn to_storage(&self) -> Self::Storage {
    // Hour, minute and second are `i8` in `0..=23`, `0..=59`, `0..=59`; the subsecond is an `i32` in
    // `0..=999_999_999` — a civil time has no negative half, unlike an instant's.
    time::Time::from_hms_nano(
      self.hour() as u8,
      self.minute() as u8,
      self.second() as u8,
      self.subsec_nanosecond() as u32,
    )
    .expect("jiff's civil-time range and time's are the same span, 00:00:00 ..= 23:59:59.999999999")
  }
}

/// Crossed as its two HALVES rather than through a third arithmetic, and that is the whole of the
/// row: a civil datetime IS a civil date beside a civil time, on both sides of the crossing, so this
/// spends the two rows above and adds nothing either of them does not already promise.
///
/// [`time::PrimitiveDateTime`] is the one `time` type with no zone and no offset, which is what makes
/// it the carrier: a wall clock that crossed into [`time::OffsetDateTime`] would arrive carrying an
/// offset nobody wrote, and the whole point of the type is that it names none.
impl TemporalStorage for civil::DateTime {
  type Storage = time::PrimitiveDateTime;

  #[inline]
  fn to_storage(&self) -> Self::Storage {
    time::PrimitiveDateTime::new(self.date().to_storage(), self.time().to_storage())
  }
}

/// A zone offset stores as its SECONDS, and the row is the one place in this trait where the storage
/// form is not a `time` type.
///
/// # Why not [`time::UtcOffset`]
///
/// sqlx 0.9 has no row for it — its `time` module encodes `OffsetDateTime`, `PrimitiveDateTime`,
/// `Date` and `Time` and stops there — so a crossing into it would name a type no dialect can bind,
/// and the missing row would be discovered as an unsatisfied `Carrier` bound rather than here. The
/// wrapper is what makes the integer legal to cross into at all: `impl TryFrom<jiff::tz::Offset> for
/// i32` is `E0117`, both foreign, which is the same wall the module note opens on.
///
/// # It is TOTAL, and the range is jiff's own
///
/// [`Offset::MIN`](jiff::tz::Offset::MIN) is `-25:59:59` and [`MAX`](jiff::tz::Offset::MAX) is
/// `25:59:59`, so the whole domain is `-93_599 ..= 93_599` seconds — four orders of magnitude inside
/// `i32`, and the reason [`seconds`](jiff::tz::Offset::seconds) already answers in one. Nothing here
/// can refuse.
///
/// **The seconds are the WHOLE value.** jiff's offsets have second resolution and no sub-second
/// component, so the integer is not a projection of the offset — it is the offset, spelled in the one
/// unit it has.
impl TemporalStorage for jiff::tz::Offset {
  type Storage = i32;

  #[inline]
  fn to_storage(&self) -> Self::Storage {
    self.seconds()
  }
}

#[cfg(test)]
mod tests;