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
//! Why a query did not answer, and why a write did not land: [`SqlQueryError`] and
//! [`SqlWriteError`].

use super::CrossingError;
use crate::{CursorError, comparison::sql::SqlLoweringError, query::PagingOrderError};

/// The ceiling a `skip` is refused past.
///
/// `LIMIT` and `OFFSET` bind a SIGNED 64-bit integer in every dialect this crate ships, so the
/// honest range is the same number three times rather than a per-dialect constant — measured
/// against sqlx 0.9's own binds, which is where the width is fixed.
const SKIP_CEILING: u64 = i64::MAX as u64;

/// Why a query did not answer.
///
/// # A lowering refusal is carried VERBATIM
///
/// The query layer never absorbs one. A dialect that refuses a filter — a key set past its bind
/// ceiling, a scope it has no working spelling of — has said something specific about the query
/// being asked, and a page that reported *the query failed* would be throwing away the only
/// sentence a caller can act on.
///
/// # The refusals that are NOT here
///
/// A page without a written order, and a cursor position given beside an offset. Both are missing
/// methods on the builder rather than variants here: the first is what the ordered state exists
/// for, and the second is what consuming into [`Positioned`](super::Positioned) closes. A refusal
/// that cannot be spelled needs no variant to report it.
#[derive(Debug)]
pub enum SqlQueryError {
  /// The driver refused, or the statement did.
  Sql(sqlx::Error),
  /// A comparison would not lower for this dialect — carried as the dialect stated it.
  Lowering(SqlLoweringError),
  /// The written order cannot be rendered for this dialect.
  Order(crate::comparison::sql::SqlOrderError),
  /// A PAGE was asked for over an order no page can resume at.
  ///
  /// Separate from [`Order`](Self::Order) because the two questions are: that one is what a
  /// STATEMENT cannot carry, and this is what a BOUNDARY cannot be taken at. A dialect that orders
  /// by the term perfectly well still raises this where a cursor has no slot to hold the value —
  /// which is every collection, on every backend.
  ///
  /// `PageOrder` and not `Paging`, because [`Paging`](super::Paging) is the lane type one module
  /// over: a variant sharing that name makes the type's own path ambiguous to rustc's diagnostics,
  /// which is measured rather than feared — the `query_lanes` fixture's pinned text moved the day
  /// the two collided.
  PageOrder(PagingOrderError),
  /// The cursor is not this query's — see [`CursorError`] for which of the seven ways.
  Cursor(CursorError),
  /// A `skip` past what the dialect's `OFFSET` can hold.
  ///
  /// A typed refusal rather than a panic, which is the wound this variant is the scar of: polarsync
  /// narrowed the same number with `i64::try_from(…).unwrap()`, so a client's oversized offset took
  /// the process down. It is also not silently clamped — an offset saturated to the ceiling would
  /// answer a different question with no way to tell.
  ///
  /// Carries what was asked for.
  Skip(u64),
  /// A stored row is not a record, or an address is not this database's columns.
  Crossing(CrossingError),
}

impl From<sqlx::Error> for SqlQueryError {
  #[inline]
  fn from(error: sqlx::Error) -> Self {
    Self::Sql(error)
  }
}

impl From<SqlLoweringError> for SqlQueryError {
  #[inline]
  fn from(error: SqlLoweringError) -> Self {
    Self::Lowering(error)
  }
}

impl From<crate::comparison::sql::SqlOrderError> for SqlQueryError {
  #[inline]
  fn from(error: crate::comparison::sql::SqlOrderError) -> Self {
    Self::Order(error)
  }
}

impl From<PagingOrderError> for SqlQueryError {
  #[inline]
  fn from(error: PagingOrderError) -> Self {
    Self::PageOrder(error)
  }
}

impl From<CursorError> for SqlQueryError {
  #[inline]
  fn from(error: CursorError) -> Self {
    Self::Cursor(error)
  }
}

impl From<CrossingError> for SqlQueryError {
  #[inline]
  fn from(error: CrossingError) -> Self {
    Self::Crossing(error)
  }
}

impl core::fmt::Display for SqlQueryError {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self {
      Self::Sql(error) => write!(f, "this query did not run: {error}"),
      Self::Lowering(error) => write!(f, "this query's predicate does not lower here: {error}"),
      Self::Order(error) => write!(f, "this query's order cannot be rendered here: {error}"),
      Self::PageOrder(error) => write!(f, "this query's order cannot be paged: {error}"),
      Self::Cursor(error) => write!(f, "this query cannot resume there: {error}"),
      Self::Skip(skip) => write!(
        f,
        "a skip of {skip} is past the {SKIP_CEILING} this dialect's OFFSET holds"
      ),
      Self::Crossing(error) => write!(f, "this row and its record do not cross: {error}"),
    }
  }
}

impl core::error::Error for SqlQueryError {
  fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
    match self {
      Self::Sql(error) => Some(error),
      Self::Lowering(error) => Some(error),
      Self::Order(error) => Some(error),
      Self::PageOrder(error) => Some(error),
      Self::Cursor(error) => Some(error),
      Self::Skip(_) => None,
      Self::Crossing(error) => Some(&**error),
    }
  }
}

/// **The engine lane's wire words** — one per arm, because the seven refuse seven different things
/// and a client acts on them differently: rewrite the predicate, drop an order term, drop the
/// cursor, ask for a smaller skip, or stop asking and retry later.
///
/// Every word is named after WHAT was refused and never after WHO refused it, which is
/// [`ErrorCode`]'s own derivation rule: `STORE_REFUSED` rather than `SQLX_ERROR`, so a deployment
/// that changes database keeps the contract. `UNUSABLE_CURSOR` is SHARED with
/// [`PageError::Cursor`](crate::PageError::Cursor) for the same rule's other clause — the wire door
/// refuses a cursor whose frame will not read, this lane refuses one that does not belong to the
/// order it is replayed against, and a client's fix is the same either way.
///
/// A method on the refusal rather than a table beside it, so an arm added here cannot leave a
/// mapping somewhere else out of date — see [`ToErrorCode`] for why the fact belongs to the type
/// that has it.
impl crate::ToErrorCode for SqlQueryError {
  fn error_code(&self) -> crate::ErrorCode {
    match self {
      Self::Sql(_) => crate::ErrorCode::StoreRefused,
      Self::Lowering(_) => crate::ErrorCode::UnsupportedFilter,
      Self::Order(_) => crate::ErrorCode::UnrenderableOrder,
      Self::PageOrder(_) => crate::ErrorCode::UnpageableOrder,
      Self::Cursor(_) => crate::ErrorCode::UnusableCursor,
      Self::Crossing(_) => crate::ErrorCode::UnreadableRow,
      Self::Skip(_) => crate::ErrorCode::OversizedSkip,
    }
  }
}

/// Why a write did not land.
///
/// # THREE of a query's six are missing, and the three that are missing are the point
///
/// A write names no cursor, writes no order and takes no offset, so [`SqlQueryError`]'s
/// [`Cursor`](SqlQueryError::Cursor), [`Order`](SqlQueryError::Order) and
/// [`Skip`](SqlQueryError::Skip) have nothing here to report — and a refusal that cannot be spelled
/// needs no variant, which is the rule that module's own note already states one type over. Sharing
/// the query's type would have given a caller three arms to handle that no write can reach.
///
/// # A lowering refusal is carried VERBATIM, exactly as a query's is
///
/// The one this lane can raise is the BIND CEILING: a collection's elements are one bound parameter
/// each, so an edge insert wide enough to pass the dialect's limit is refused with the three numbers
/// [`BindCeilingError`](crate::comparison::sql::BindCeilingError) carries rather than chunked into
/// several statements. That is [`SqlKeyIn`](crate::comparison::sql::SqlKeyIn)'s refuse-don't-chunk
/// doctrine on the write side, and it is the same reason: a caller that splits a batch knows what
/// the pieces mean, and a lane that split one silently would report success for a record it stored
/// in parts.
///
/// # The FOURTH variant is the DELETE lane's, and it exists because a TYPE could not close it
///
/// [`Unscoped`](Self::Unscoped) is what a filter that lowers to no predicate at all is answered
/// with. Making the filter a REQUIRED parameter — which it is, where a read's is an
/// [`Option`] — closes the case a caller never wrote one, and that is where the other refusals of
/// this family stop: an unspellable state needs no variant. It does NOT close the case a caller
/// BUILT a comparison and set nothing on it, because an all-absent comparison is an ordinary value
/// whose lowering renders zero conjuncts — [`ComplexComparison::is_empty`](crate::ComplexComparison)
/// is the one place that is visible. The statement it would produce is `DELETE FROM "clip"` with no
/// `WHERE` at all, which empties the table and reports success.
#[derive(Debug)]
pub enum SqlWriteError {
  /// The driver refused, or the statement did — a constraint violation among them, which is what a
  /// plain `insert` onto an address that is already taken answers with, and what a `unique` field
  /// answers with the same way: [`insert`](super::insert)'s own note argues why that is carried
  /// here whole rather than narrowed into a variant of this crate's own.
  ///
  /// A caller that means to act on WHICH constraint fired reads the driver's own answer: sqlx
  /// already names the kind through `sqlx::Error::as_database_error()`, and
  /// `DatabaseError::is_unique_violation()` on what that returns is `true` for every constraint
  /// this variant carries from either source — the address's own or a declared `unique` field's.
  /// Nothing in `ingraph` re-derives that judgment, which is the same posture as the constraint
  /// itself: the ENGINE decided, and this variant is the deciding answer surfaced rather than read.
  Sql(sqlx::Error),
  /// The statement will not render for this dialect — carried as the dialect stated it.
  Lowering(SqlLoweringError),
  /// A record is not this database's row: whatever the declaration's own write conversion refused
  /// with.
  Crossing(CrossingError),
  /// A DELETE was handed a filter naming no row at all — see the type's own note. Carries the table
  /// the statement would have emptied, which is the sentence a caller needs: *which* table was
  /// about to go.
  Unscoped(&'static crate::FieldName),
}

impl From<sqlx::Error> for SqlWriteError {
  #[inline]
  fn from(error: sqlx::Error) -> Self {
    Self::Sql(error)
  }
}

impl From<SqlLoweringError> for SqlWriteError {
  #[inline]
  fn from(error: SqlLoweringError) -> Self {
    Self::Lowering(error)
  }
}

impl From<CrossingError> for SqlWriteError {
  #[inline]
  fn from(error: CrossingError) -> Self {
    Self::Crossing(error)
  }
}

impl core::fmt::Display for SqlWriteError {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self {
      Self::Sql(error) => write!(f, "this write did not run: {error}"),
      Self::Lowering(error) => write!(f, "this write's statement does not render here: {error}"),
      Self::Crossing(error) => write!(f, "this record and its row do not cross: {error}"),
      // `as_str` rather than the name itself: this family of borrowed names carries no `Display`,
      // by design — see [`borrowed_name`](crate::name), whose whole content is that a name is a
      // borrow with a role rather than a thing that prints.
      Self::Unscoped(table) => write!(
        f,
        "this delete names no row, so it would empty `{}` — a filter that lowers to no predicate is \
         refused rather than run",
        table.as_str()
      ),
    }
  }
}

impl core::error::Error for SqlWriteError {
  fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
    match self {
      Self::Sql(error) => Some(error),
      Self::Lowering(error) => Some(error),
      Self::Crossing(error) => Some(&**error),
      // No source: the refusal is this lane's own finding about a value it was handed rather than
      // anything a driver or a dialect said.
      Self::Unscoped(_) => None,
    }
  }
}

/// `skip` as the signed offset a dialect binds, or the refusal.
///
/// # Errors
///
/// [`SqlQueryError::Skip`] where the value is past [`i64::MAX`].
pub(super) fn offset(skip: u64) -> Result<u64, SqlQueryError> {
  if skip > SKIP_CEILING {
    return Err(SqlQueryError::Skip(skip));
  }
  Ok(skip)
}

#[cfg(test)]
mod tests;