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 storage backend a comparison renders for: [`Backend`], the three sqlx dialects that
//! implement it, and `Mongo` beside them.
//!
//! # What the three SQL rows say
//!
//! Each names the same accumulator — this crate's AND accumulator over its own dialect. A comparison
//! is one or more conjuncts joined by ` AND `, and the accumulator holds the one bit no conjunct's
//! writer holds alone: whether this conjunct is the first. A nested sub-comparison is handed exactly
//! the accumulator its parent held, which is what makes recursion legal by construction.
//!
//! # Why not the clause machine
//!
//! [`QueryBuilder`](super::sql::QueryBuilder) is a `SELECT` under construction, and naming it here
//! would pin its HOLDER to the default — a `sqlx::QueryBuilder` the statement owns. But a statement
//! inside a [`sub_select`](super::sql::QueryBuilder::sub_select) is held by the statement that
//! opened it, so the holder is a different type at every nesting depth, and a comparison could not
//! be applied inside a subquery at all. That is the relation shape: `field IN ( SELECT … )`.
//!
//! The deeper reason it was the wrong parameter is that **a comparison only ever goes `WhereClause`
//! → `WhereClause`. It never transitions.** The typestate polices clause SEQUENCE, which is the
//! statement's concern rather than a conjunct's, and the accumulator holds
//! `&'q mut sqlx::QueryBuilder<Db>` — one type at every depth.
//!
//! The clause machine stays reachable from a comparison and is not the thing threaded through it: a
//! layer that needs a subquery opens a conjunct, takes the `&mut` the accumulator yields, and wraps
//! it with [`select_into`](super::sql::QueryBuilder::select_into).
//!
//! # What the three rows refuse with
//!
//! The same refusal, and it names TWO things: a key set past the dialect's bind ceiling, and a
//! correlated comparison applied at an address naming no field. Every OTHER failure a SQL comparison
//! can have happens at the CROSSING — an operand that will not convert into the type this dialect
//! stores, a width that does not fit — and by the time a comparison exists it holds storage values
//! that binding cannot reject.
//!
//! That is why this row said [`Infallible`](core::convert::Infallible) while every kind lowered one
//! column, and why [`SqlKeyIn`](super::sql::SqlKeyIn) is what ended it: a compound key's membership
//! costs one bound parameter PER COLUMN per key, so the count that meets a sixteen-bit ceiling is
//! not one the caller passed. The `Result` on this path was already being carried for the backends
//! and the nested layers that have a no to give; the SQL family now has noes of its own.
//!
//! The second of them is what [`write_column`](Backend::write_column)'s empty-path answer does not
//! reach: a correlated predicate names a table derived from the column's path rather than the column
//! itself, so writing nothing leaves it well-formed. See
//! [`SqlLoweringError::EdgeWithoutField`](super::sql::SqlLoweringError::EdgeWithoutField).
//!
//! Three rows saying one thing is not an argument for one blanket over `Db: sqlx::Database`. What a
//! backend renders into and what it refuses with are exactly what a dialect might come to disagree
//! about, and a blanket is the shape that cannot express the disagreement. The three rows already
//! disagree about the NUMBER — see [`BindCeiling`](super::sql::BindCeiling) — and agree only about
//! the kind of no.
//!
//! # What the FOURTH row says, and it is not a fourth dialect
//!
//! `Mongo` answers every question differently, which is the point of it being here: the builder is
//! an owned BSON accumulator rather than a borrow into a `sqlx::QueryBuilder`, the refusal is
//! [`Infallible`](core::convert::Infallible), the buffer is a `String` because a rendered path
//! becomes a `bson::Document` key, and the column is a dotted PATH with nothing bracketed rather
//! than one identifier with everything bracketed. None of that needed a change to this trait, and
//! the reason is that each answer is an associated item rather than a shape the trait spells for
//! its implementors.
//!
//! The `Builder` GAT's lifetime is the one place the fit is loose. It was kept for a backend whose
//! builder holds references into the operands, and a document builder was the case named; measured,
//! a document builder holds none, because every BSON value owns its bytes. So the row below
//! resolves the slot to a type with no lifetime at all. The slot costs nothing and stays open — but
//! nothing yet has needed it.

// The rows are per dialect, so the names they use carry the dialects' gate rather than the family
// root's: a build with `sqlx` alone implements this trait for nothing and must not import a type it
// then does not name.
use super::At;
#[cfg(feature = "mongo")]
use super::mongo::{Mongo, MongoConjunction, MongoLoweringError, write_field_path};
#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
use super::sql::{SqlConjunction, SqlLoweringError, quote_column};
#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
use smol_bytes::Utf8BytesMut;

/// One storage backend's rendering surface: the builder its comparisons thread, the buffer a column
/// name is rendered into, and the refusal they can return.
///
/// # Why the builder type is the BACKEND's
///
/// Every comparison rendering for one backend must agree about the builder, because they hand it to
/// each other: a walk leaves one comparison and enters the next, and a nested comparison receives
/// the one its parent held. An associated type on [`ComplexComparison`](crate::ComplexComparison)
/// instead would let two comparisons for one dialect name two different builders, and nothing would
/// compose.
///
/// So the three SQL dialects share one builder — this crate's AND accumulator, parameterised by the
/// dialect — while a backend outside the SQL family brings its own.
pub trait Backend {
  /// The builder a comparison for this backend is handed, renders into, and hands back.
  ///
  /// `'q` is the borrow the BUILDER holds of whatever it renders into — for the sqlx rows, the
  /// accumulator's `&'q mut sqlx::QueryBuilder<Db>` — and
  /// [`ComplexComparison::apply`](crate::ComplexComparison::apply) takes `&'q self` under the same
  /// lifetime, so a comparison outlives the builder it renders into.
  ///
  /// That tie is what keeps this associated type open rather than something the SQL family needs.
  /// sqlx 0.9's builder owns its arguments, so a SQL operand need not outlive the borrow at all;
  /// a backend whose builder assembles REFERENCES to the operands — a document builder that borrows
  /// rather than encodes — is unimplementable WITHOUT it, because nothing in the signature would
  /// let it say the operands are still there.
  type Builder<'q>;

  /// What a lowering for this backend refuses with.
  ///
  /// The backend's type rather than the trait's, because what can be refused is the backend's
  /// question — an operator this engine lacks, an operand form it will not take, a ceiling its wire
  /// protocol imposes. The three SQL rows refuse with the last of those, and the ceiling differs per
  /// dialect while the refusal does not.
  type Error;

  /// The text buffer this backend renders a column name into.
  ///
  /// The backend's rather than the trait's, for the reason [`Builder`](Self::Builder) and
  /// [`Error`](Self::Error) are: what a rendered name IS differs by where it is going. The SQL rows
  /// name [`Utf8BytesMut`], whose inline storage holds a bracketed identifier without touching the
  /// heap; the MongoDB row names [`String`], because a rendered path there becomes a
  /// [`bson::Document`] key and that type is `String` — a buffer of any other kind would be
  /// converted at the one place it is used, which is a cost with nothing on the other side of it.
  ///
  /// Deliberately unbounded. A backend able to render into a pooled buffer, or one holding an arena
  /// handle, is a backend this trait admits; a `Default` or `Write` bound here would decide for it.
  /// What generic code needs instead is a constructor, which is
  /// [`buffer_with_capacity`](Self::buffer_with_capacity).
  type Buffer;

  /// A buffer able to take `capacity` bytes before it grows.
  ///
  /// A constructor rather than a `Default` bound, for the reason [`Buffer`](Self::Buffer) is
  /// unbounded: a pooled buffer or one holding an arena handle has no meaningful `Default`, and a
  /// bound would have decided that for the backend. The CAPACITY one is the primitive because the
  /// other direction cannot be recovered — [`buffer`](Self::buffer) defaults to this, so what "no
  /// stated capacity" means is the backend's answer rather than the trait's guess.
  fn buffer_with_capacity(capacity: usize) -> Self::Buffer;

  /// A buffer at this backend's own default capacity.
  ///
  /// What the SQL family's own renderings ask for, and the measurement is why: `Utf8BytesMut` is
  /// inline up to 62 bytes, so a bracketed name that fits allocates nothing whatever capacity it
  /// was built with, and one that does not saves exactly one allocation by stating a capacity —
  /// measured at 2 allocations against 1 for a 74-byte name, with an ESTIMATED capacity and an
  /// exactly computed one indistinguishable (359 ns against 359). A second walk of the path to
  /// compute a number that is inert below the inline range is not a trade this family makes.
  #[must_use]
  fn buffer() -> Self::Buffer {
    Self::buffer_with_capacity(0)
  }

  /// Write the column `at` names into `out`, joined and bracketed as this backend spells one.
  ///
  /// # Why the JOIN is here and not a separator constant
  ///
  /// [`At::path`](crate::At::path) carries segments, and a backend does two things with them that a
  /// `const SEPARATOR` cannot express together: the SQL family runs them together with `_` and then
  /// brackets the WHOLE as one identifier, where a document family nests them along a `.` and
  /// brackets nothing. A separator alone would leave each comparison kind to bracket the result —
  /// the duplication [`quote_ident`](crate::comparison::sql::quote_ident) exists to prevent — and
  /// would build a joined name before quoting it, which is the allocation per column the path
  /// removes.
  ///
  /// So this subsumes `quote_ident` at the COLUMN position, and only there. A table's name is not a
  /// column path: an edge table's `<table>_<field>` is a different join over a different namespace,
  /// and folding the two means changing a document family's path separator silently renames tables.
  ///
  /// # The EMPTY path
  ///
  /// The top level names no column. What to write for one is this method's decision, and the two
  /// families below answer it differently while agreeing about the standard: the rendering has to
  /// be something the ENGINE refuses, because a caller error resolved is worse than one reported.
  ///
  /// The SQL rows write nothing, which makes the surrounding predicate unparseable. Writing nothing
  /// is not available to a document family — an empty BSON key is legal, so `{"": …}` is a filter
  /// that quietly matches nothing — so the MongoDB row writes a key the server refuses instead. The
  /// standard travels; the rendering does not.
  ///
  /// # It writes rather than returns
  ///
  /// A backend able to write its segments straight into a buffer the caller already holds allocates
  /// nothing at all; one that returns a buffer per column cannot. The caller owns it, so several
  /// names may be accumulated into one and split apart afterwards — which is what the correlated
  /// kinds do, where one edge table's name is written into three of them.
  fn write_column(at: At<'_>, out: &mut Self::Buffer);
}

/// The SQL rows all three name [`Utf8BytesMut`], and a bracketed identifier is why: `INLINE_CAP` is
/// 62 bytes, more than a column path spends in any declaration this crate has seen, so the whole
/// rendering sits inline where a `String` allocates for the first character written. The correlated
/// kinds take the other half of it, splitting several finished names out of one buffer.
#[cfg(feature = "sqlite")]
impl Backend for sqlx::Sqlite {
  type Builder<'q> = SqlConjunction<'q, sqlx::Sqlite>;
  type Error = SqlLoweringError;
  type Buffer = Utf8BytesMut;

  fn buffer_with_capacity(capacity: usize) -> Self::Buffer {
    Utf8BytesMut::with_capacity(capacity)
  }

  fn write_column(at: At<'_>, out: &mut Self::Buffer) {
    quote_column::<Self>(at, out);
  }
}

#[cfg(feature = "postgres")]
impl Backend for sqlx::Postgres {
  type Builder<'q> = SqlConjunction<'q, sqlx::Postgres>;
  type Error = SqlLoweringError;
  type Buffer = Utf8BytesMut;

  fn buffer_with_capacity(capacity: usize) -> Self::Buffer {
    Utf8BytesMut::with_capacity(capacity)
  }

  fn write_column(at: At<'_>, out: &mut Self::Buffer) {
    quote_column::<Self>(at, out);
  }
}

#[cfg(feature = "mysql")]
impl Backend for sqlx::MySql {
  type Builder<'q> = SqlConjunction<'q, sqlx::MySql>;
  type Error = SqlLoweringError;
  type Buffer = Utf8BytesMut;

  fn buffer_with_capacity(capacity: usize) -> Self::Buffer {
    Utf8BytesMut::with_capacity(capacity)
  }

  fn write_column(at: At<'_>, out: &mut Self::Buffer) {
    quote_column::<Self>(at, out);
  }
}

/// The one row that is not a dialect, and the three answers it gives are each different from the
/// three above.
///
/// # The builder is OWNED, and `'q` goes unused
///
/// Every SQL row resolves the GAT to a borrow into the statement's buffer, because a statement is a
/// larger thing a conjunct writes part of. A `find` filter is not part of anything — the document
/// IS the deliverable — and every value in it owns its bytes, so the accumulator owns the whole
/// filter and has nothing to borrow from the operands. `'q` is therefore unmentioned on the right,
/// which is legal and is the measurement the seam was waiting for.
///
/// # The refusal is the ELEMENT SCOPE's, and it arrived exactly as this row said it would
///
/// This said [`Infallible`](core::convert::Infallible) while every kind rendered a field's own
/// operators: a comparison already holds storage values, chosen by the declaration and converted
/// once at the crossing, so nothing being rendered could be looked at and declined. BSON's ceilings
/// are real — sixteen megabytes to a document, a hundred levels of nesting — and they are the
/// analogue of [`BindCeiling`](super::sql::BindCeiling) rather than something a scalar's `$in` list
/// reaches: the SQL family deliberately puts no ceiling on single-column membership either, and
/// refuses only where a COMPOUND key multiplies a count the caller did not choose.
///
/// [`MongoLoweringError`](super::mongo::MongoLoweringError) is what ended it, and the shape is the
/// SQL family's own: `$elemMatch` holds a RESTRICTED sub-language, and what a nested comparison
/// writes into one is knowable only when it writes it. So the refusal belongs to the lowering for
/// the reason
/// [`SqlLoweringError::JsonElementScope`](super::sql::SqlLoweringError::JsonElementScope) does,
/// and this row names it rather than a second uninhabited type.
///
/// # The buffer is a [`String`], where the SQL rows take an inline one
///
/// A rendered path here does not go into a statement's text — it becomes a KEY, and
/// [`bson::Document`]'s keys are `String`. Any other buffer would be converted at the one place its
/// contents are used, so the inline storage the SQL rows gain would be spent again on the copy out
/// of it. The seam is what makes that statable rather than a compromise: the two families disagree
/// about the buffer for the same reason they disagree about `.` and `_`.
#[cfg(feature = "mongo")]
impl Backend for Mongo {
  type Builder<'q> = MongoConjunction;
  type Error = MongoLoweringError;
  type Buffer = String;

  fn buffer_with_capacity(capacity: usize) -> Self::Buffer {
    String::with_capacity(capacity)
  }

  fn write_column(at: At<'_>, out: &mut Self::Buffer) {
    write_field_path(at, out);
  }
}

#[cfg(test)]
mod tests;