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 INTERFACE's own vocabulary: which member a row came from, what each arm projects, and the
//! refusal a discriminant nobody declared gets.
//!
//! An interface names no table and mints no id, so its query layer reads its MEMBERS' tables — one
//! `SELECT` per member, joined by `UNION ALL`, every arm projecting the shared columns under the
//! interface's own names. Two facts have to travel with that statement and neither is a member's:
//! WHICH member each row came from, and what that member calls each shared column.
//!
//! # The discriminant is a WORD the interface owns, and never a table's name
//!
//! An interface's total order ends `…, kind, id`, so the discriminant is a sort key: the sequence
//! rows come back in depends on how the engine compares two of these strings, and a cursor freezes
//! one. A member's TABLE cannot be that string, for two reasons that are each on their own decisive
//! — it is per DATABASE (`persist(sqlite(table = "…"), postgres(table = "…"))` names two), so one
//! interface's cursor would not be portable between two deployments of one schema; and it is
//! RENAMEABLE, so moving a member's table would silently re-sort every page of every interface it
//! belongs to.
//!
//! So the word is the member's own VARIANT, snake-cased — `video`, `audio` — which the interface's
//! declaration writes and nothing about storage can move. Lower-case ASCII is not decoration
//! either: a discriminant is compared by the ENGINE's collation, and the three shipped dialects'
//! defaults (SQLite `BINARY`, PostgreSQL's `C`/`en_US.utf8`, MySQL's `utf8mb4_0900_ai_ci`) agree on
//! the ordering of lower-case ASCII and do NOT agree on how it sorts against upper case. A word
//! that cannot contain a case distinction cannot be sorted two ways.
//!
//! # `Ord` is deliberately NOT on [`InterfaceKind`]
//!
//! A derived `Ord` over the emitted enum would run in DECLARATION order, and the statement sorts by
//! the projected STRING. Two orderings that agree only while a declaration happens to be written
//! alphabetically is exactly the shape that pages wrongly with no error anywhere, so the comparison
//! every party makes is over [`as_str`](InterfaceKind::as_str) and the enum carries no ordering at
//! all.

use core::fmt;

use smol_bytes::Utf8Bytes;

use crate::FieldName;

/// The alias every arm of a union projects its discriminant under.
///
/// ONE name, shared by the party that WRITES it into the statement and the party that DECODES it
/// off the row — the discipline a sort value's alias and a gathered element's already follow.
///
/// # `__ig_…__` is the SYNTHESIZED-COLUMN law, and it is what makes `kind` an ordinary field name
///
/// A column the framework invents wears `__ig_` at the front and `__` at the end. That shape is
/// inside the fence `ingraph-derive` already refuses a declared column for — *a name with `__` at
/// both ends is reserved* — so a declaration CANNOT spell this name, and an interface promising a
/// shared field called `kind` collides with nothing. A synthesized column named `kind` would have
/// made the framework's own vocabulary compete with the declaration's, which is the one thing the
/// fence exists to prevent.
pub const KIND: &FieldName = FieldName::new("__ig_kind__");

/// The name every arm of a union projects its member's ADDRESS column under.
///
/// A REAL column and therefore an ordinary name: what each arm selects is that member's own address
/// column, which is `id` in one table and `audio_id` in the next, so the union needs one output name
/// for them and `id` is what it is. It is not synthesized — the value is a member's own, where the
/// discriminant beside it is the framework's invention — so it wears no fence, and a shared field
/// called `id` collides with it exactly as two columns of one name collide anywhere.
pub const ID: &FieldName = FieldName::new("id");

/// The name the outer query gives the union it selects from.
///
/// A union is a DERIVED TABLE and a derived table must be named, so this is the name the shared
/// predicate and the `ORDER BY` qualify their columns with. Synthesized, therefore fenced: nothing
/// a declaration can spell, so a member's own table called `union` collides with nothing.
pub const SOURCE: &FieldName = FieldName::new("__ig_union__");

/// Which member a row came from, as the interface's own closed vocabulary.
///
/// A CAPABILITY rather than a member of the query binding, because the answer is one per INTERFACE
/// where the binding is one per (interface, database): the word a row carries is the same word in
/// every database the interface is about, which is the whole of what makes a cursor minted against
/// SQLite replayable against the Postgres deployment of one schema.
///
/// # [`parse`](Self::parse) is DEFAULTED, and there is no second body to write
///
/// It is a scan of [`ALL`](Self::ALL) comparing [`as_str`](Self::as_str), which is the only
/// implementation the two items admit. An emitted vocabulary states the two facts and inherits the
/// crossing; a hand-written one does the same.
pub trait InterfaceKind: Copy + Eq + Sized + 'static {
  /// The interface this vocabulary is about — what a refusal names.
  const INTERFACE: &'static str;

  /// Every member, in DECLARATION order.
  ///
  /// Declaration order rather than sorted order, because it is what the arms render in and an
  /// expansion is diffable exactly while its emission order is the declaration's. Nothing reads it
  /// as an ordering — see the module note on why [`Ord`] is absent.
  const ALL: &'static [Self];

  /// The word this member's arm projects, and the word a cursor freezes.
  fn as_str(self) -> &'static str;

  /// The member `word` names.
  ///
  /// # Errors
  ///
  /// [`UnknownKind`] where no member carries the word — a row whose discriminant this interface
  /// never declared, which is a statement reading a table the union does not join or a cursor
  /// minted against another interface.
  fn parse(word: &str) -> Result<Self, UnknownKind> {
    Self::ALL
      .iter()
      .copied()
      .find(|kind| kind.as_str() == word)
      .ok_or_else(|| UnknownKind::new(Self::INTERFACE, word))
  }
}

/// A discriminant naming no member of the interface that read it.
///
/// It carries the word VERBATIM rather than a summary, because the word is the whole evidence: a
/// row from a table the union does not join and a cursor minted under another interface are told
/// apart by reading it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnknownKind {
  interface: &'static str,
  word: Utf8Bytes,
}

impl UnknownKind {
  /// The refusal `interface` answers `word` with.
  #[inline]
  #[must_use]
  pub fn new(interface: &'static str, word: &str) -> Self {
    Self {
      interface,
      word: Utf8Bytes::from(word.to_owned()),
    }
  }

  /// The interface that has no member of this name.
  #[inline]
  #[must_use]
  pub const fn interface(&self) -> &'static str {
    self.interface
  }

  /// The word the row carried.
  #[inline]
  #[must_use]
  pub fn word(&self) -> &str {
    &self.word
  }
}

impl fmt::Display for UnknownKind {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(
      f,
      "`{interface}` has no member called `{word}`",
      interface = self.interface,
      word = self.word
    )
  }
}

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

/// What HYDRATING an interface's page refuses with: the union answered, and the members' own tables
/// did not.
///
/// # It is the COHERENCE refusal, and it exists because two statements are two moments
///
/// A page is a union over the members' tables and a hydration is one gather per member, so a row the
/// union returned can be gone by the time its member's table is read. Inside one read transaction
/// that cannot happen — which is what [`BeginRead`](crate::query::sql::BeginRead)'s passthrough is
/// for — and outside one it can, so the gap is REPORTED rather than papered over with a shorter
/// list. A page that silently loses rows is a page whose `hasNextPage` is a lie.
///
/// # It carries the WORD and a count, and never an id
///
/// The members need not agree about what an id is, so a refusal naming one would be generic in the
/// member — and this type is what a declared error unifies through, which a generic one could not
/// be. The member's word and how many of its rows went missing is the whole evidence a caller acts
/// on.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HydrationError {
  /// An address of ANOTHER member arrived in this member's batch.
  ///
  /// A caller error rather than a race: the batch is one member's lane, and an address carries which
  /// member it is of. Refused rather than skipped, because a skipped address is a row that silently
  /// leaves the page.
  Foreign {
    /// The interface whose lane was being run.
    interface: &'static str,
    /// The member whose lane it was.
    asked: &'static str,
    /// The member the address was actually of.
    held: &'static str,
  },
  /// The union answered with rows this member's table no longer holds.
  Missing {
    /// The interface the page was over.
    interface: &'static str,
    /// The member whose table was read.
    member: &'static str,
    /// How many of the asked-for rows were not there.
    missing: usize,
  },
}

impl fmt::Display for HydrationError {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      Self::Foreign {
        interface,
        asked,
        held,
      } => write!(
        f,
        "`{interface}`: `{asked}`'s hydration was handed an address of `{held}`"
      ),
      Self::Missing {
        interface,
        member,
        missing,
      } => write!(
        f,
        "`{interface}`: {missing} row(s) the union answered with are no longer in `{member}`'s \
         table — the page and the hydration did not see one state of the database"
      ),
    }
  }
}

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

/// ONE shared column, as one arm of a union projects it.
///
/// TWO names rather than one, and they differ exactly where a member block moved the column: the
/// interface promises `created_at` and `Audio` carries it as `imported_at`, so that arm renders
/// `"imported_at" AS "created_at"` and every other arm renders the name twice over. Which is why
/// the pair is carried rather than an `Option`: the arm that renames and the arm that does not are
/// one rendering, and a branch on absence would be a second one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InterfaceColumn {
  field: &'static FieldName,
  column: &'static FieldName,
}

impl InterfaceColumn {
  /// The column `column` of this member, promised under the interface's own `field`.
  #[inline]
  #[must_use]
  pub const fn new(field: &'static FieldName, column: &'static FieldName) -> Self {
    Self { field, column }
  }

  /// The INTERFACE's name for the column — what the projection aliases to, and what the row decodes
  /// under.
  #[inline]
  #[must_use]
  pub const fn field(&self) -> &'static FieldName {
    self.field
  }

  /// What THIS member calls it — the name the arm selects.
  #[inline]
  #[must_use]
  pub const fn column(&self) -> &'static FieldName {
    self.column
  }
}

/// ONE arm of a union: which member it reads, and how that member's row spells the shared columns.
///
/// The TABLE is not here, and its absence is the point: a member's table is its own declaration's
/// and is reached through the member's query binding rather than restated by the interface —
/// see [`SqlInterface::table`](crate::query::sql::SqlInterface::table), which asks the member's own
/// `ADDRESS` for it. An arm carrying a copy would be a second spelling of a name a
/// `persist(<db>(table = "…"))` can move.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InterfaceArm<K: 'static> {
  kind: K,
  columns: &'static [InterfaceColumn],
}

impl<K: 'static> InterfaceArm<K> {
  /// The arm reading `kind`'s member, whose shared columns are `columns`.
  ///
  /// `const`, because an arm list is an ITEM: an emitted binding states it once beside the
  /// interface it describes, exactly as a row's `ADDRESS` is stated.
  #[inline]
  #[must_use]
  pub const fn new(kind: K, columns: &'static [InterfaceColumn]) -> Self {
    Self { kind, columns }
  }

  /// Which member this arm reads.
  #[inline]
  #[must_use]
  pub const fn kind(&self) -> K
  where
    K: Copy,
  {
    self.kind
  }

  /// The shared columns, in the order the projection renders them — the interface's declaration
  /// order, and the same order at every arm.
  #[inline]
  #[must_use]
  pub const fn columns(&self) -> &'static [InterfaceColumn] {
    self.columns
  }
}

#[cfg(test)]
mod tests;