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 three facts a STORED composite states about itself, and the one authority all of them read:
//! how many columns a [`Timebase`] spans, how those columns are bound out, and how they are read
//! back in.
//!
//! ```text
//!   SEGMENTS   num, den          the width — what a holder's INSERT list and DDL name
//!   Carrier    ?, ?              the bind — one placeholder per segment, the comma between them ours
//!   Assemble   num → i32 ← den   the decode — read by NAME, so a transposition cannot typecheck away
//!   CursorValue  8 bytes         the keyset position, big-endian, exactly as the columns hold it
//! ```
//!
//! # ONE list, read four ways
//!
//! [`SEGMENTS`] is the whole of what makes those four agree. The comparison pushes a frame per
//! entry, the row puts a column per entry, the bind pushes a placeholder per entry and the decode
//! reads one per entry — so a rename here moves `WHERE tb_num = ?`, `SELECT tb_num`, the `VALUES`
//! width and the read together. Nothing counts the columns; the list is the count.
//!
//! # What is gated and what is not
//!
//! The width and the cursor position are UNGATED, because neither names a database: a composite
//! spans two columns wherever it is stored, and a keyset position is bytes. The bind and the decode
//! ride the `sqlx` feature, because both are written against sqlx's own types — a `QueryBuilder` and
//! a `Row` — and a build with no SQL family has neither.
//!
//! # The bind writes the REDUCED pair, and it is the same reduction the crossing binds
//!
//! [`Timebase::reduced`] is THE authority, and it is public so that this path and the query path can
//! call the same one rather than each dividing correctly. Reducing on one side only is a SILENT
//! MISS: a row written from `2/180000` and a filter binding `1/90000` simply never meet, with no
//! error and no wrong value to look at.
//!
//! What that costs is the pair the stream DECLARED, which storage does not keep — see
//! [`Timebase`]'s [`Display`](core::fmt::Display), which does.

use core::{fmt, num::NonZeroI32};

use crate::{ColumnKind, ColumnName, ColumnShape, CursorValue, FieldName, column::column_eq};
use mediatime as mt;

use super::Timebase;

#[cfg(test)]
mod tests;

/// The numerator's segment — the name a frame pushes and a column carries.
///
/// `pub(crate)` rather than `pub(super)`, because the citizens that NEST this one address these
/// columns directly: a timestamp's `exact` facet binds the timebase halves beside the `pts`, and it
/// reads the names from here rather than respelling them — one authority, at every depth.
pub(crate) const NUM: &FieldName = FieldName::new("num");

/// The denominator's segment.
pub(crate) const DEN: &FieldName = FieldName::new("den");

/// **The two columns a timebase spans**, and the one authority every half of the crossing reads.
///
/// `num` and `den` rather than the wire's `numerator`/`denominator`, and the difference is which
/// side of the crossing each vocabulary belongs to: a column name is DDL a database already holds,
/// where a field name is a schema commitment to a client. The wire took the longer spelling because
/// `mediatime`'s own serde face publishes those two names; the columns keep the short ones because
/// renaming a column is a migration and this cut is not one.
pub(super) const SEGMENTS: &[ColumnShape] = &[
  ColumnShape::Plain(ColumnName::of(NUM)),
  ColumnShape::Plain(ColumnName::of(DEN)),
];

/// **The STORAGE half of the width** — what a holder's row reads to know this field is two columns
/// and not one. It names no dialect, because a width has none.
impl ColumnKind for Timebase {
  const SEGMENTS: &'static [ColumnShape] = SEGMENTS;
}

/// **One leaf, and it is the value.** A timebase means numerator then denominator, which is the sequence it is written in — the
/// citizen that NESTS this one is the one with a sequence to state, and it states its own.
impl crate::DeclaredLeaves for Timebase {}

// Two timebases are one column value when they are the same rational — `mediatime`'s own
// `PartialEq` cross-multiplies rather than comparing the pair as written, so `2/180000` and
// `1/90000` already answer equal here exactly as `reduced()` makes them one row.
column_eq! { Timebase }

/// **The DECLARED half of the same two columns** — the words a `CREATE TABLE` spells them with, one
/// per segment above.
///
/// Both halves are `i32`, so the words are that width's own in whichever dialect is asked rather
/// than a spelling written here: the numerator and a non-zero denominator are what the
/// [`Carrier`](crate::Carrier) row binds, and a dialect that stores an `i32` differently moves this
/// row with it. Generic over the dialect for the reason the carrier row is — nothing in the
/// delegation is per-dialect, and the arity is fixed at two.
impl<Db> crate::StoredAs<Db> for Timebase
where
  i32: crate::StoredAs<Db>,
{
  const WORDS: &'static [&'static str] = &[
    <i32 as crate::StoredAs<Db>>::WORDS[0],
    <i32 as crate::StoredAs<Db>>::WORDS[0],
  ];
}

/// A pair of columns does not hold a timebase, and this says which invariant they broke.
///
/// The two are the constructor's two, met on the way IN from a database rather than on the way in
/// from a client: `mediatime` refuses a negative half and [`NonZeroI32`] refuses a zero denominator,
/// and a column is an `INTEGER` that can hold either. So a decode has to test what the type
/// guarantees, and the alternative — trusting the column — is a `Timebase` whose invariants are a
/// hope about someone else's DDL.
///
/// It is a decode error rather than a parse error, and it is a separate type from
/// [`ParseTimebaseError`](super::ParseTimebaseError) for that reason: nothing here was spelled, so
/// there is no separator to be missing and no half that failed to be an integer. What is left is
/// exactly the two domain rules.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TimebaseColumnError {
  /// The denominator column holds zero, which [`NonZeroI32`] forbids.
  ZeroDenominator,
  /// A column holds a negative value, which `mediatime`'s constructor refuses.
  NegativeHalf,
}

impl fmt::Display for TimebaseColumnError {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    let reason = match self {
      Self::ZeroDenominator => "the stored denominator must not be zero",
      Self::NegativeHalf => "neither stored half may be negative",
    };

    f.write_str(reason)
  }
}

impl core::error::Error for TimebaseColumnError {}

/// The two columns as one value, or the invariant they broke.
///
/// Shared by the two readers below — the row decode and the cursor — so that a timebase arriving
/// from a database and one arriving from a client's page token are admitted by the same rule.
fn assembled(num: i32, den: i32) -> Result<Timebase, TimebaseColumnError> {
  let den = NonZeroI32::new(den).ok_or(TimebaseColumnError::ZeroDenominator)?;

  mt::Timebase::try_new(num, den)
    .map(Timebase::new)
    .ok_or(TimebaseColumnError::NegativeHalf)
}

/// **The KEYSET position**: eight bytes, two big-endian `i32`s, in the order [`SEGMENTS`] names.
///
/// A page resumes by binding the last row's values back, so what is written here is what the COLUMNS
/// hold — the reduced pair — and not the declared one. A cursor carrying `2/180000` where the row
/// holds `1/90000` would compare against a value no column has.
///
/// FIXED WIDTH, which is what makes the read total, and the DOMAIN is checked on top of the width: a
/// cursor is a string a CLIENT hands back, so seven bytes are refused rather than zero-extended, and
/// a forged `den` of zero is refused rather than turned into a `Timebase` whose type says it cannot
/// exist.
impl CursorValue for Timebase {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    let (num, den) = self.reduced();
    CursorValue::write_cursor(&num, out);
    CursorValue::write_cursor(&den.get(), out);
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let (num, den) = bytes.split_at_checked(size_of::<i32>())?;
    let num = <i32 as CursorValue>::read_cursor(num)?;
    let den = <i32 as CursorValue>::read_cursor(den)?;

    assembled(num, den).ok()
  }
}

/// **N BINDS OUT.** The engine's `VALUES` loop writes the comma between FIELDS; the comma between a
/// field's own columns is this one, because the count is this type's — so a holder's `INSERT` names
/// `tb_num, tb_den` and binds `?, ?` with neither list told the number.
///
/// Generic over the dialect where the fixture that models this names one concretely, and the
/// difference is coherence rather than taste: that fixture also serves MongoDB, whose marker is
/// foreign to it, so its two headers would overlap. This crate ships one family, so one header
/// serves it — and `i32: Carrier<Db>` is the whole requirement, both halves being `i32` by
/// construction.
#[cfg(feature = "sqlx")]
impl<Db> crate::Carrier<Db> for Timebase
where
  Db: sqlx::Database,
  i32: crate::Carrier<Db>,
{
  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    let (num, den) = self.reduced();
    <i32 as crate::Carrier<Db>>::push_bind(&num, qb);
    qb.push(", ");
    <i32 as crate::Carrier<Db>>::push_bind(&den.get(), qb);
  }
}

/// **AND N COLUMNS BACK IN** — the bind above read the other way, and the third fact a stored
/// composite states.
///
/// Generic over the ROW where the bind is generic over the DIALECT, and the asymmetry is the two
/// traits' parameters rather than a choice made here: a bind is a dialect's fact, while a read is
/// [`sqlx::Row`]'s method.
///
/// `under` arrives carrying the holder's own segment for a field that lends its name, and carrying
/// nothing extra for one marked `flatten` — so this one body serves both without knowing which it is
/// reading. By NAME in both cases, which is what a transposition cannot survive: both columns are
/// integers, so `num` and `den` read positionally would swap without a type error anywhere.
#[cfg(feature = "sqlx")]
impl<'a, R: sqlx::Row> crate::Assemble<'a, R> for Timebase
where
  i32: crate::Assemble<'a, R>,
{
  fn assemble(row: &'a R, under: Option<&crate::Path<'_>>) -> sqlx::Result<Self> {
    let num: i32 = crate::assembled(row, NUM, under)?;
    let den: i32 = crate::assembled(row, DEN, under)?;

    assembled(num, den).map_err(|refused| sqlx::Error::Decode(Box::new(refused)))
  }
}