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
//! A written order as MongoDB renders it: [`MongoOrder`], the `$sort` stage it becomes, and what it
//! refuses before rendering anything.
//!
//! # One order drives both halves of a page
//!
//! [`SqlOrder`](crate::comparison::sql::SqlOrder)'s sentence, and it is the same sentence here: the
//! `$sort` the documents come back in and the `$match` that resumes at the cursor's document have to
//! agree about every term's direction, or the page skips or repeats exactly the documents at a
//! boundary. Two call sites reading one list is a convention; ONE value that renders both is a
//! guarantee, and [`MongoKeyset`](super::MongoKeyset) is built from this type rather than from a
//! slice for that reason.
//!
//! # There is no `NullOrder` here, and its absence is a MEASUREMENT rather than an omission
//!
//! The SQL family carries a per-dialect answer for where `NULL` sorts, because the three dialects
//! disagree and one of them needs the position spelled on the term. MongoDB has one answer and it
//! is already the framework's: BSON's total order runs `MinKey < Null < Numbers < String < …`, and
//! a MISSING field sorts exactly where a `null` does — so `NULL` is BELOW every value on an
//! ascending term and above it on a descending one, which is the pin
//! [`pinned_nulls`](crate::comparison::sql::pinned_nulls) states from the other family.
//!
//! So `$sort` states nothing about nulls, and this backend's
//! [`NullPlacement`](crate::query::NullPlacement) row says [`Reachable`] with no knob behind it.
//! What it refuses instead is what the SQL twin does not: a `$sort` is a DOCUMENT, so two terms
//! over one field are one entry.
//!
//! [`Reachable`]: crate::query::NullPlacement::Reachable
//!
//! # The `_id` TAIL is the order's, not this renderer's
//!
//! A completed order already ends with the record's own id — [`MongoOrdering::complete`] is what
//! appends it, and the address is what says which column that is — so this renders the terms it is
//! given and adds nothing. The tail is visible in every golden beside this module as a trailing
//! `_id: 1`, which is what makes an order that lost it a red test rather than a page that silently
//! repeats rows across a tie.
//!
//! [`MongoOrdering::complete`]: super::MongoOrdering::complete

use bson::{Bson, Document};

use super::{MongoFields, MongoSubjects, subject::sort_key};
use crate::{
  OrderTerm, RecordAddress, TermName, Walk,
  comparison::mongo::Mongo,
  query::{ColumnNotStored, Unpushable, partition},
};

/// The `$sort` value an ASCENDING term takes.
const ASC: i32 = 1;

/// The `$sort` value a DESCENDING term takes.
const DESC: i32 = -1;

/// A written order, checked: non-empty, and every term naming a field this document has.
///
/// # It is `Copy`, and a page renders it twice
///
/// One borrowed slice, so the value is the width of what it points at — the argument
/// [`SqlOrder`](crate::comparison::sql::SqlOrder) makes for the same receiver. A page hands it to
/// the `$sort` stage and then to the keyset, and neither takes it away from the other.
///
/// # No backend parameter, where the SQL twin has a dialect
///
/// What that parameter carried there was the CHECKED-NESS of a per-dialect `NULL` answer. There is
/// one MongoDB and one null position, so there is nothing for a type parameter to keep apart.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MongoOrder<'a> {
  // NON-EMPTY, established by `new` and relied on by `push_sort`.
  terms: &'a [OrderTerm],
}

impl<'a> MongoOrder<'a> {
  /// `terms` as an order this backend can render WHOLE, or why it cannot.
  ///
  /// # It reads the capability frame rather than scanning for itself
  ///
  /// What a `$sort` document cannot hold is [`Mongo`](crate::Mongo)'s own
  /// [`OrderCapability`](crate::query::OrderCapability) row, and
  /// [`partition`](crate::query::partition) is the one party that reads a row — so this refuses
  /// exactly the orders that frame leaves a remainder for, and a row that lied would redden here
  /// rather than pass a wrong `$sort` through. The refusal is the BACKSTOP the frame's own note
  /// describes: a lane that means to degrade partitions first and hands over
  /// [`pushable`](crate::query::OrderPartition::pushable), which this then takes whole.
  ///
  /// # Errors
  ///
  /// [`MongoSortError::Empty`] for an order over no terms; [`MongoSortError::NotStored`] for a term
  /// naming a column this deployment's database has not got, which is the declaration-truth
  /// schema's runtime half; [`MongoSortError::Repeated`] where two
  /// terms name one field — which SQL tolerates as a redundant `ORDER BY` entry and a document
  /// cannot hold at all, its keys being unique; [`MongoSortError::Collection`] for a term over a
  /// collection, which this engine sorts by a rule the framework does not mean; and
  /// [`MongoSortError::Semantic`] for a term over a citizen that states a semantic sequence, which
  /// this backend has no expansion for yet.
  pub fn new(terms: &'a [OrderTerm]) -> Result<Self, MongoSortError> {
    if terms.is_empty() {
      return Err(MongoSortError::Empty);
    }
    // A SEMANTIC citizen is refused BY NAME, and before the capability frame is consulted: the frame
    // answers what a `$sort` document CAN hold, and this is about what this backend has not been
    // taught. Asked early for `NotStored`'s reason — it needs no context and its sentence is the
    // narrowest one available.
    if let Some(refused) = terms
      .iter()
      .find(|term| !term.order().is_empty() || term.leaf().is_some())
    {
      return Err(MongoSortError::Semantic(refused.identity()));
    }
    let partition = partition::<Mongo>(terms);
    let Some(refused) = partition.remainder().first() else {
      return Ok(Self { terms });
    };
    let term = refused.identity();
    // The cause is READ rather than assumed, and three of the seven are verdicts this backend's rows
    // cannot give: MongoDB puts a missing value where the framework pins it, so `NullPosition` never
    // arrives, and `CollectionCursor` and `ShadowCursor` are `paging`'s alone. `CollectionShadow`
    // joins the collection sentence: a companion column this backend cannot order bytewise is the
    // same news to a client as an array it cannot order element by element. Mapping them keeps a row
    // that CHANGED from arriving here as the wrong sentence instead of as a red test.
    Err(match partition.cause() {
      // The DEPLOYMENT's own refusal, and the one cause that says nothing about `$sort`: the field
      // is not in this collection's documents at all. The dialect comes off the term's own subject,
      // where the emission put it.
      Some(Unpushable::NotStored) => MongoSortError::NotStored(ColumnNotStored::new(
        term,
        refused
          .subject()
          .absent_from()
          // Total by construction: `NotStored` is the verdict `TermSubject::Absent` alone produces,
          // and the dialect is that subject's own payload.
          .expect("a term refused as unstored names the dialect that has not got it"),
      )),
      Some(
        Unpushable::CollectionSemantics
        | Unpushable::CollectionTable
        | Unpushable::CollectionShadow,
      ) => MongoSortError::Collection(term),
      _ => MongoSortError::Repeated(term),
    })
  }

  /// The terms, in the sequence they run.
  #[inline]
  #[must_use]
  pub const fn terms(&self) -> &'a [OrderTerm] {
    self.terms
  }

  /// This order's `$sort` value, running `walk`'s way, with every term sorting by a field of the
  /// document `at` addresses — which is where the id becomes `_id`.
  ///
  /// A backward walk renders every term INVERTED, which — with the documents re-reversed after they
  /// come back, which is the lane's — is the same order read from the far end.
  #[must_use]
  pub fn sort(&self, at: &RecordAddress, walk: Walk) -> Document {
    self.sort_with(at, walk, &MongoFields)
  }

  /// [`sort`](Self::sort) with what each term SORTS BY written by `subjects` — the `$sort` half of
  /// [`MongoSubjects`], whose other halves are the keyset's and the join stages'.
  ///
  /// The three take ONE value, and that is the whole reason this exists rather than a caller
  /// building its own document: a page is several readings of one order, and a term named one way
  /// in the ordering and another in the resume predicate skips or repeats exactly the documents at
  /// a boundary. [`sort_key`](super::subject::sort_key) is where the name is decided, once.
  #[must_use]
  pub fn sort_with<S: MongoSubjects + ?Sized>(
    &self,
    at: &RecordAddress,
    walk: Walk,
    subjects: &S,
  ) -> Document {
    let mut sort = Document::new();
    for (level, term) in self.terms.iter().enumerate() {
      let direction = walk.direction(term.direction());
      let value = if direction.is_descending() { DESC } else { ASC };
      sort.insert(
        sort_key(at, self.terms, level, subjects),
        Bson::Int32(value),
      );
    }
    sort
  }
}

/// Why a written order cannot be rendered for MongoDB.
///
/// # No refusal here is about a cursor
///
/// An order is refused before any cursor is looked at, which is what keeps
/// [`CursorError`](crate::CursorError) about the string a client handed back and this type about
/// the query being asked. A page over an order this refuses has no cursor to be wrong.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MongoSortError {
  /// A term names a column THIS DEPLOYMENT's database does not store — the declaration narrowed it
  /// out of `mongo` and keeps it in the record's others.
  ///
  /// The schema states the DECLARATION's truth, so the word is offered wherever the service runs;
  /// this is the deployment's own answer, given before a `$sort` is built rather than as a stage
  /// naming a field no document has. See [`ColumnNotStored`], which carries both halves of the
  /// sentence: which column, and which dialect has not got it.
  NotStored(ColumnNotStored),
  /// An order over NO terms.
  ///
  /// There is no default order in this framework, and *an order over nothing has no spelling*: a
  /// query that wrote no term renders no `$sort` stage at all and never reaches this type.
  Empty,
  /// Two terms naming ONE field, which a `$sort` document cannot hold.
  ///
  /// The SQL family has no such refusal, and the difference is the data structure rather than the
  /// engine: `ORDER BY "a" ASC, "a" DESC` is a redundant second term SQL simply ignores, where
  /// `{a: 1, a: -1}` is a document with one key — the second entry REPLACES the first. So a page
  /// would sort by the last direction written and resume against the first, which is the boundary
  /// defect this whole layer exists to prevent, arriving with no error anywhere.
  ///
  /// It cannot be reached through a completed framework order — the derive refuses colliding column
  /// names, and [`complete`](super::MongoOrdering::complete) MOVES a term that already names the id
  /// rather than repeating it — so this is the seam for a hand-written order, checked because the
  /// terms are a caller's slice.
  ///
  /// Carries the repeated term, by the identity a rename does not move.
  Repeated(&'static TermName),
  /// A term over a COLLECTION, which this engine orders by a rule the framework does not mean.
  ///
  /// It is a DISAGREEMENT and not a missing feature, which is why the sentence names the rule.
  /// `$sort` over an array field compares each document's MINIMUM element on an ascending term and
  /// its MAXIMUM on a descending one, so `[9]` sorts after `[1, 99]` ascending, the two directions
  /// are not reverses of one another, and neither is the framework's element-by-element order — see
  /// [`compare_collections`](crate::query::compare_collections), which is what a client's term
  /// means everywhere else.
  ///
  /// Serving it anyway would put the documents in an order no other deployment of the same schema
  /// produces, with no error anywhere. Carries the term, by the identity a rename does not move.
  Collection(&'static TermName),
  /// A term over a citizen that states a SEMANTIC SEQUENCE — [`ColumnKind::ORDER`] — which this
  /// backend has no expansion for.
  ///
  /// # It is refused BY NAME rather than served in the declaration order
  ///
  /// The SQL family expands such a term into one ordinary level per leaf, which works because that
  /// family FLATTENS a composite into columns of the row: a level is a column, and the engine has an
  /// `ORDER BY` entry to give it. A document family NESTS one, so `at` is a sub-document and `$sort`
  /// over it compares the sub-document — a rule that is the field order of the stored BSON rather
  /// than the sequence the citizen means. Serving that would put the documents in an order no SQL
  /// deployment of the same schema produces, with no error anywhere, which is exactly the standing
  /// [`Collection`](Self::Collection) takes for the same kind of disagreement.
  ///
  /// The seat for the answer exists — [`ToDatabaseOrderBy`](crate::ToDatabaseOrderBy) carries the
  /// dialect for this reason, and a document family's sequence over a nested citizen is a genuinely
  /// different answer from a table family's. What is missing is the EMISSION that would spend it:
  /// this backend's `$sort` keys, its keyset and its cursor slots all still read a term as one
  /// field. That is the mongo emission round's work, and until it lands the honest answer is this
  /// one.
  ///
  /// Carries the term, by the identity a rename does not move.
  ///
  /// [`ColumnKind::ORDER`]: crate::ColumnKind::ORDER
  Semantic(&'static TermName),
}

impl core::fmt::Display for MongoSortError {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self {
      Self::Empty => f.write_str("an order over no terms has no spelling"),
      Self::NotStored(why) => write!(f, "{why}"),
      Self::Repeated(term) => {
        let term: &str = term;
        write!(
          f,
          "`{term}` is named twice and a `$sort` document holds one entry per field"
        )
      }
      Self::Collection(term) => {
        let term: &str = term;
        write!(
          f,
          "`{term}` is a collection, and `$sort` orders one by its smallest element ascending and \
           its largest descending rather than element by element"
        )
      }
      Self::Semantic(term) => {
        let term: &str = term;
        write!(
          f,
          "`{term}` states a semantic order over its own columns, and this backend sorts a nested \
           citizen as one sub-document rather than by that sequence"
        )
      }
    }
  }
}

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

#[cfg(test)]
mod tests;