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
//! What a record ANSWERS and what STORES it: `get` by address, `find` over a filter and the three
//! lanes a plural query can be asked in, beside the verbs a record is written and REMOVED with.
//!
//! ```text
//! Media::find_sqlite(&pool).fetch()                     unordered, unlimited — NO `ORDER BY`
//! Media::find_sqlite(&pool).limit(100).fetch()          unordered, any N     — NO `ORDER BY`
//! Media::find_sqlite(&pool).order(&terms).first(100)
//!                          .after(&cursor).fetch()      the PAGE lane        — a written order
//!
//! Media::insert_sqlite(&pool, media).await             a NEW row; a taken address refuses
//! Media::upsert_sqlite(&pool, media).await             the KEYED REPLACE on that address
//!
//! Media::delete_sqlite(&pool, &id).await               that row and its own; `false` for a miss
//! Media::delete_sqlite_where(&pool, &filter).await     every row the filter names — the COUNT
//! ```
//!
//! The read half is a BUILDER and the write half is a call, and the asymmetry is the questions': a
//! query has lanes to choose between and a write has a record and a verb. What the two share is the
//! ROW — the read raises one into its record and the write crosses a record into one, through the
//! same declared conversions read in two directions — so both live here rather than in two modules
//! that would each have to know what a row is.
//!
//! # The REMOVAL half mirrors the read's two addresses rather than the store's one
//!
//! A store verb is handed a record, so it has one address to write at and no way to need a second.
//! A removal has to be told which rows it means, and there are exactly two ways a caller ever knows:
//! it holds the id, or it holds the predicate the rows are under. So the two doors mirror `get` and
//! `find` — the by-id one answers `bool` where `get` answers an [`Option`], the by-filter one
//! answers a COUNT where `find` answers a [`Vec`], and one law is behind both narrowings, the id
//! being `UNIQUE`. What the FILTER road is for is the re-index: a source that produced fourteen rows
//! and now produces nine leaves five behind, and *what it used to produce* is a set nobody holds.
//! See [`sql::delete`] and [`sql::delete_where`], where the walk and its two refusals are written.
//!
//! # There is no default order, and a page cannot be asked for without one
//!
//! A query that writes no ordering term gets no `ORDER BY` at all: SQL's own unordered semantics is
//! the honest answer, and a sort nobody asked for is work every row pays for. What that costs is
//! that *any N rows* has to be its own lane rather than a page with the cursors ignored — which is
//! the second line above, and which is why the clause machine has a `FROM → LIMIT` edge.
//!
//! A PAGE is the case that cannot be spelled that way. A cursor is a position in an order, so a page
//! over an unordered set compares its values against columns nobody named, and the rows it returns
//! skip and repeat with no error anywhere. Here it is a MISSING METHOD: `first`, `last`, `after`,
//! `before` and `skip` exist on the ordered builder state and nowhere else, so the wrong query does
//! not compile. **That is this lane's rule and it stands.**
//!
//! The WIRE answers the same question differently, and the difference is the caller's. A Rust query
//! reaching the page lane has already written `.order(…)`, because a compiler told it to; a client
//! writing a document has no such conversation, so an absent `orderBy` there is the record's KEY
//! ASCENDING — a documented default over a unique column, which makes the order total and the page
//! correct. See [`crate::graphql::connection`] for the whole of it. What the wire still refuses is
//! the pair `Paging<Forward>` and `Paging<Backward>` have no method in common for, and
//! [`PageError`](crate::PageError) is where those arrows are written out as sentences. `skip` is the
//! one position with no wire argument at all, there being no OFFSET lane there.
//!
//! # What is here, and what is per backend
//!
//! This module holds what a page IS, which names no database: the [`Page`], its [`Edge`]s, the two
//! ceilings every backend's builder clamps to, how deep a reference is followed, and the frame that
//! says which of a written order's terms a given backend's ordering statement can carry. The
//! ENGINE — the statement, the executor seam, the typestate builder — is per backend and lives in a
//! module of its own beside them, as the comparison family's rendering does: [`sql`] is the SQL
//! family's, [`mongo`] the document family's.
//!
//! The ordering frame is here for the reason [`DEPTH_CEILING`] is: its whole content is that the
//! verdict is PER BACKEND: [`OrderCapability`] is a row each family answers, and [`partition`] is
//! the one party that reads them.
//!
//! The WRITE lane is the SQL family's alone today, and that is demand rather than design: the
//! MongoDB execution lane renders and runs a `find`, and no ruling has asked it for a verb that
//! stores. Its own module gets one when something does.

mod order;
mod page;

pub use order::{
  CollectionBoundary, CollectionOrdering, NullPlacement, OrderCapability, OrderPartition,
  PagingOrderError, ShadowBoundary, ShadowOrdering, TermRepetition, Unpushable,
  compare_collections, partition,
};
pub use page::{Edge, Page};

#[cfg(feature = "mongo")]
pub mod mongo;
#[cfg(feature = "sqlx")]
pub mod sql;

/// What a record ⇄ row crossing refuses with.
///
/// The emitted conversions' OWN error type, carried rather than re-wrapped: a row's columns may each
/// fail differently and there is no type that names all of them, which is the reasoning
/// `ingraph-codegen`'s row conversions already wrote this box for. A generated per-row error enum is
/// the better long-term answer and belongs with the trait layer that would define it.
///
/// # It is the QUERY layer's rather than one engine's, and the second backend is what moved it
///
/// It sat in [`sql`] while there was one engine, and every word of it is about the CROSSING rather
/// than about SQL: a declared conversion refuses the same way whichever database the row came out
/// of, and a second copy under [`mongo`] would be two names for one box that a caller would have to
/// convert between. `query::sql::CrossingError` still resolves — the family re-exports it — so the
/// move costs a reader nothing.
pub type CrossingError = Box<dyn core::error::Error + Send + Sync>;

/// A request that named a column THIS DEPLOYMENT's database does not store.
///
/// # The schema states the DECLARATION's truth, and this is the other half of that
///
/// A record may narrow a column out of one of its databases — `sqlite(skip(default = "…"))`, or a
/// bare presence list that leaves SQLite out — and the column keeps its filter word and its
/// order-by word in the emitted schema all the same. *A client must never see a schema that varies
/// with a deployment's storage choice* forbids the schema varying BY deployment; it does not
/// command shrinking it TO the intersection, and a word that came and went with whichever database
/// a service was pointed at would be exactly the varying schema the law forbids.
///
/// So the word is constant and the ANSWER is where the deployment speaks. A predicate or an order
/// over a column this database has not got is refused here, by name, before a statement is
/// rendered — never as a bare *no such column* out of the driver, which names a physical column and
/// not the client's own term.
///
/// # The author owns the combination, and the refusal is what makes it legible
///
/// Narrowing the column, publishing the word and deploying that database are three of the
/// declaration author's own decisions. The framework's job is a sentence naming both halves — which
/// column, and which dialect has not got it — rather than hiding the word or scolding at
/// declaration time. What IS refused at declaration time is the ADDRESS: identity is unskippable,
/// so a narrowed address step is a compile-time named refusal and never reaches this type.
///
/// # Two seats answer with it, and they are the two vocabularies the ruling names
///
/// The PREDICATE crossing (`TryFromFilter` for the database's own comparison), where a filter
/// carrying an operand for a narrowed column refuses instead of crossing; and the ORDERING, where a
/// term minted for a dialect that has not got the column carries
/// [`TermSubject::Absent`](crate::TermSubject::Absent) and is refused by
/// [`SqlOrder::new`](crate::comparison::sql::SqlOrder::new) or
/// [`MongoOrder::new`](mongo::MongoOrder::new) before a row is read.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ColumnNotStored {
  column: &'static crate::TermName,
  database: &'static str,
}

impl ColumnNotStored {
  /// The refusal for `column` at `database`.
  ///
  /// `column` is the RENAME-PROOF identity — the record field's own name, which is what a client
  /// wrote and what the schema published — rather than whatever the databases that DO store it call
  /// their column. A sentence naming a physical column of a table this deployment has not got would
  /// name the one thing nobody can look at.
  #[inline]
  #[must_use]
  pub const fn new(column: &'static crate::TermName, database: &'static str) -> Self {
    Self { column, database }
  }

  /// The column the request named.
  #[inline]
  #[must_use]
  pub const fn column(&self) -> &'static crate::TermName {
    self.column
  }

  /// The dialect this deployment's database speaks — the half of the sentence that is the
  /// deployment's rather than the declaration's.
  #[inline]
  #[must_use]
  pub const fn database(&self) -> &'static str {
    self.database
  }
}

impl core::fmt::Display for ColumnNotStored {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    let Self { column, database } = self;
    let column: &str = column;
    write!(
      f,
      "`{column}` is not stored in this deployment's database: the declaration narrowed the column \
       out of `{database}` and keeps it in this record's other databases, so there is no column \
       here to compare or to order by"
    )
  }
}

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

/// The page size a query gets when it asks for a page and names no size.
///
/// polarsync's own default, and one of the few things its connection layer got right. A client that
/// says `after: <cursor>` and nothing else is asking to continue, not to be handed the rest of the
/// table.
pub const DEFAULT_PAGE_SIZE: u32 = 100;

/// The widest page this framework will assemble, whatever a client asks for.
///
/// # It CLAMPS rather than refusing, and that is the graph-node guard's own behaviour
///
/// A ceiling that refuses turns a client's optimism into an error page; one that clamps answers the
/// question with fewer rows and lets the cursor carry the client on. The relay contract already
/// allows a server to return fewer edges than asked for, so the clamped answer is a legal one and
/// needs no second channel to explain itself.
///
/// The number is the graph-node guard's 1000, and it is a FRAMEWORK default rather than a law: a
/// per-record widening is a declaration option for the era whose grammar can carry one. polarsync
/// shipped this cap and then dropped it, which is the wound this constant is the scar of — an
/// unbounded page is a table scan a client can ask for by accident.
///
/// [`u32`] is the width, and it is what makes the OTHER overflow unspellable: `LIMIT` binds a
/// signed 64-bit integer in every dialect here, so a page size that could not fit one would have to
/// be built out of a wider type than the ceiling admits. A `skip` is not so bounded and refuses on
/// its own, at the engine that binds it.
pub const MAX_PAGE_SIZE: u32 = 1000;

/// The default has to fit under the ceiling that clamps it, or a client naming no size gets a
/// narrower page than one naming the default — which would make the two constants disagree about
/// what *no size given* means. A `const` rather than a test, so the disagreement is a build that
/// does not finish.
const _: () = assert!(
  DEFAULT_PAGE_SIZE <= MAX_PAGE_SIZE,
  "the default page size must fit under the ceiling"
);

/// The depth a record's relation aliases are minted to where the declaration names no number —
/// and, since a reference is followed only as far as an alias carries it, how deep an engine
/// follows before refusing.
///
/// # A DEFAULT rather than a wall, and the array is what the refusal reads
///
/// `SqlQuery::ALIASES` and `MongoQuery::ALIASES` are SLICES, so their length is a fact about one
/// (record, database) pair rather than part of a trait item's type — and the refusal past the last
/// entry reports `aliases.len()`, never this number. A declaration that nests deeper says so, once,
/// on the database whose statements do it: `<db>(alias(depth = 16))`. What this constant
/// governs is the record that names nothing.
///
/// Eight is chosen against what a relation predicate actually nests: each level is a scope inside a
/// scope over one query, and a filter written by hand or crossed from a wire query reaches two or
/// three. The unused tail costs eight `&'static str` per row type, which is read-only data and
/// nothing at runtime — which is also why the default is generous rather than tight: raising it
/// later cannot help a deployment already compiled, and the knob is what a deeper one reaches for.
///
/// # A relation PREDICATE is not the only thing that spends it
///
/// A MongoDB nested ORDERING follows references too, and it spends the same names for the same
/// reason: each hop is a `$lookup` whose `as` is a FIELD of the document being joined onto, so it
/// takes that name from the target's own `MongoQuery::ALIASES` and refuses past the last one with
/// [`MongoLoweringError::RelationDepth`](crate::comparison::mongo::MongoLoweringError::RelationDepth)
/// — the same refusal, naming the same collection, as a relation nested that deep.
///
/// The SQL nested ordering spends none of it, and the asymmetry is a fact about SCOPES rather than a
/// policy: a correlated subselect may call its row source by the real table name, because nothing
/// outside it can see that name, while every stage of a pipeline writes into one document. What the
/// two families share is the NUMBER, for the reason below.
///
/// # It is the QUERY layer's rather than one engine's, and the second backend is what moved it
///
/// It sat in [`sql`] while there was one engine, and nothing about the number is SQL's. A default
/// that differed per backend would make a filter answerable on one deployment's storage choice and
/// refused on another's, which is the same argument
/// [`MongoDerivedComparison`](crate::comparison::mongo::MongoDerivedComparison) makes about the
/// quantifier vocabulary. `query::sql::DEPTH_CEILING` still resolves — the family re-exports it — so
/// the move costs a reader nothing.
///
/// Its twin is `ingraph-codegen`'s `alias::DEPTH_CEILING`, which is what MINTS that many for a
/// record that named no depth; the dependency runs one way, so the two are separate constants and
/// `ingraph-derive`'s `emitted_aliases_fill_the_ceiling` is what keeps them one number.
pub const DEPTH_CEILING: usize = 8;