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 WRITE half: the verbs a record is stored and REMOVED with on MongoDB, and the DOCUMENT each
//! of them is.
//!
//! ```text
//! insert         insertOne(<the whole document>)
//!
//! upsert         replaceOne({_id: …}, <the whole document>, {upsert: true})
//!
//! delete         deleteOne({_id: {$eq: …}})
//!
//! delete_where   deleteMany(<the lowered filter>)
//! ```
//!
//! # It is [`query::sql::write`](crate::query::sql)'s grammar, seat for seat
//!
//! Four verbs and the same four meanings: [`insert`](super::insert) is the plain store and a taken
//! address is the SERVER's own refusal; [`upsert`](super::upsert) is the keyed replace at that same
//! address; [`delete`](super::delete) is the removal at an ID and answers a yes-or-no;
//! [`delete_where`](super::delete_where) is the removal over a PREDICATE and answers a count. The
//! removal half mirrors the READ half rather than the store half, for the reason the SQL lane
//! records: a store verb is handed a record and needs no way to say which documents it is about, and
//! a removal does — so it borrows the two shapes a caller already knows one in, `get`'s id and
//! `find`'s filter.
//!
//! # THREE of that lane's paragraphs have nothing to answer here, and the reason is one fact
//!
//! A record is ONE DOCUMENT on this backend. `edge_collections` answers `false` for MongoDB and the
//! front end refuses the `edge` word in a `mongo(…)` block outright — *a document holds its own
//! array, and there is no second table* — so a collection column is a BSON array FIELD of the
//! document itself, in the same document as every scalar beside it. That deletes three whole
//! sections of the SQL register at once:
//!
//! - **No edge statements.** There is no `DELETE FROM <edge>` and no `INSERT INTO <edge>`, no
//!   ordinal to compute and no bind ceiling to be refused past, because there are no element rows.
//! - **No provenance statements.** `SqlWrite::SIDES` has no counterpart: a split-layout ancestry is a
//!   second TABLE, and a document that would hold one holds it inline like everything else.
//! - **No transaction bracket.** The SQL lane opens one because *the SHAPE decides the bracket* and
//!   a record spanning several tables is several statements. Here every verb is ONE command against
//!   ONE collection, and a single command is atomic by the server's own law — so a framework-begun
//!   transaction would be a bracket with nothing to hold together. A caller who wants several
//!   WRITES to see one state passes a `mongodb::ClientSession`, exactly as the read lane's `_in`
//!   twins already take one, and this lane begins nothing and commits nothing.
//!
//! # …and it is what makes `upsert` the cascade
//!
//! The SQL lane's replace is a sequence: the keyed replace on the parent, then every collection's
//! rows removed and rewritten, then every provenance table cleared — several statements, one bracket,
//! and a whole note about what an edge set left un-deleted would silently hold. `replace_one` with
//! `upsert: true` replaces the WHOLE DOCUMENT, and a document's embedded arrays are part of it. So
//! the *collection that arrives shorter comes back shorter* rule is not enforced here; it is the
//! command's own semantics, and there is nothing between the two halves for a failure to land in.
//!
//! What that costs is stated rather than hidden: the replacement is total, so a field a WRITER did
//! not put in the document is a field the stored document no longer has. That is the same reading
//! `upsert` already has one backend over — *the value handed over is the whole of it* — and it is why
//! a PARTIAL document (a `mongo` block that narrows the record's columns) replaces at its own width
//! and never merges into what was stored.
//!
//! # …and what the cascade argument is NOT yet exercised on, which is a gap this half INHERITS
//!
//! A collection column has no storage form on this backend today, and the reason is a table row
//! rather than anything here: [`MongoExtract`](super::MongoExtract) has no `Vec<T>` row and
//! [`MongoCarrier`] has none either — only `Vec<u8>`, which is a `binData` BLOB rather than an array.
//! The comparison layer answers a collection perfectly well (that is
//! [`MongoListComparison`](crate::comparison::mongo::MongoListComparison)'s whole family, over a
//! native BSON array), and a stored one is a document field this write would send and that read would
//! not take back.
//!
//! So the sentence above is the COMMAND's semantics and the storage layout's, both of which hold
//! whatever a column may be: `replace_one` swaps the document, arrays included, and there is no second
//! table for a cascade to reach. What is not yet reachable is a declaration that HAS such a column,
//! and widening those two tables is the read half's change rather than this one's — the write half
//! stores exactly what the read half can give back, which is the gate
//! [`MongoWrite`]'s supertrait already states.
//!
//! # The two layers are the READ half's two layers
//!
//! Everything in this file is a VALUE and runs nothing: [`MongoWrite`] says how a record becomes the
//! document that stores it, and [`stored`], [`replacement`], [`removal`] and [`removal_where`] build
//! exactly the documents the four commands take. It compiles under `mongo` alone, so a caller holding
//! their own `mongodb::Collection` can take any of them and issue the command themselves. The lane
//! that issues it rides `mongodb` — see [`lane`](super::lane), and the module note above it for why
//! the driver is a second feature.
//!
//! # The DOCUMENT is built through the carrier vocabulary, and NOT through serde
//!
//! An emitted document derives `Serialize`, and building the stored document with it was measured and
//! refused — for [`from_document`](super::MongoQuery::from_document)'s reason read the other way.
//! serde and this crate's storage vocabulary DISAGREE about BSON: `Vec<u8>` serializes as an array of
//! integers where [`MongoCarrier`] writes a `binData`, which is exactly what
//! [`MongoExtract`](super::MongoExtract) reads back — so a serde-written document would not survive
//! its own extraction, and the failure would be a typed refusal on the READ of a document the WRITE
//! reported success for.
//!
//! [`MongoCarrier`] is [`MongoExtract`] read backwards, row for row, round-tripped by the tests
//! beside them. So the encode is the decode's twin under the same table, which is the whole of what
//! makes a stored document readable: `from_document` reads field by field under the names this
//! database spells, and [`MongoWrite::document`] writes field by field under those same names.
//!
//! # What is measured here, and what is not
//!
//! The same posture the read lane records, and for the same measured reason: `ci/test-matrix.sh`
//! provisions no service, and there is no mongod in it — so what is tested is the DOCUMENT each verb
//! would send, which is a value and is the whole of what this file decides. The tests beside it
//! implement [`MongoWrite`] by hand through nothing but its public items, which is the discipline the
//! SQL write lane's own fixture keeps: a member only an emitter could have supplied would not compile
//! there.
//!
//! What a live walk still owes is one row, and it is the server's rather than this lane's: that a
//! second `insert` at a stored `_id` is refused with duplicate-key `11000` and that `replace_one`
//! with `upsert: true` at the same address is not. Both are documented server behaviour rather than
//! anything this file chooses, and neither is reachable without a mongod.

use bson::Document;

use super::{CrossingError, MongoQuery, MongoWriteError, package::identity};
use crate::{
  ComplexComparison, Identifiable,
  comparison::{
    At,
    mongo::{Mongo, MongoConjunction},
  },
};

/// One MongoDB document, as the engine WRITES it.
///
/// # A second trait over [`MongoQuery`], which is the split [`SqlWrite`] already makes
///
/// Everything a write shares with a query — the collection, the address, the id's crossing, which
/// record this document stores — is stated once, on the trait that already holds them, so a lane
/// that stores a document and a lane that reads one cannot disagree about which collection or which
/// `_id`. What is here is the two things only a write needs: the crossing INTO the document, and the
/// document itself.
///
/// It is also the answer to a name that would otherwise be ambiguous. `ADDRESS` is a const, and a
/// document carrying two of them — one from a read binding and one from a write binding — makes
/// `Row::ADDRESS` `E0034` at every use site, in an expansion nobody can edit. The supertrait is what
/// makes there be one.
///
/// The supertrait also fixes what a write-only document would be, and the answer today is that there
/// is none: a document that cannot be raised back into its record has no [`MongoQuery`] impl, so it
/// has no write lane either. That is the read half's own gate read one layer down rather than a new
/// one.
///
/// # Every field goes through the DECLARED crossing
///
/// [`row`](Self::row) is the only way in and [`document`](Self::document) reads what it produced, so a
/// declaration's write legs are on the path of every value this lane sends. There is no ad-hoc
/// conversion beside them and nowhere to put one: the engine holds a document and cannot name a
/// record's field.
///
/// [`SqlWrite`]: crate::query::sql::SqlWrite
pub trait MongoWrite: MongoQuery {
  /// The document this record becomes — the DUAL of [`MongoQuery::record`], the same fields and the
  /// same declared conversions read the other way.
  ///
  /// # Errors
  ///
  /// Whatever the declaration's own write conversions refuse with: `mongo(try_from(…))` is on this
  /// path, and the cell beside it is the type its refusal is named by.
  fn row(record: Self::Record) -> Result<Self, CrossingError>;

  /// This document, as the BSON a command stores — every field under the key this database spells
  /// it, which is `_id` for the record's own id.
  ///
  /// The inverse of [`from_document`](MongoQuery::from_document) and its exact twin: one entry per
  /// field, in the same order, under the same names, through [`MongoCarrier`] where that reads
  /// through [`MongoExtract`]. See the module note for why serde does not write it.
  ///
  /// # It cannot fail, and that is the crossing's doing
  ///
  /// [`row`](Self::row) has already spent every declared conversion, so what this walks is storage
  /// values a carrier row exists for — the same argument
  /// [`MongoCarrier::to_bson`](crate::MongoCarrier::to_bson) makes for its own infallibility, and the
  /// same one [`SqlWrite::bind`](crate::query::sql::SqlWrite::bind) makes for taking no `Result`.
  ///
  /// [`MongoCarrier`]: crate::MongoCarrier
  /// [`MongoExtract`]: super::MongoExtract
  fn document(&self) -> Document;
}

/// The document an [`insert`](super::insert) stores: the record, crossed.
///
/// # Errors
///
/// Whatever the declaration's own write conversions refuse with — see [`MongoWrite::row`].
pub fn stored<Row: MongoWrite>(record: Row::Record) -> Result<Document, MongoWriteError> {
  Ok(Row::row(record)?.document())
}

/// The two documents an [`upsert`](super::upsert) sends: the address it replaces AT, and the whole
/// document it replaces it WITH.
///
/// The filter is the same `{_id: {$eq: …}}` a [`get`](super::get) and a [`delete`](super::delete)
/// name a document by — one spelling, minted by [`identity`] — so the three verbs cannot come to
/// disagree about what an address is. The id is read off the RECORD, which is where every other
/// address on this backend is read from and what [`MongoQuery::id`] takes.
///
/// # Errors
///
/// As [`stored`], plus an id that will not cross into this database's stored value.
pub fn replacement<Row: MongoWrite>(
  record: Row::Record,
) -> Result<(Document, Document), MongoWriteError> {
  // BEFORE the crossing, off the record's own `Identifiable` seam — which is the DOMAIN id every
  // other address is named by, and what `MongoQuery::id` takes. Reading it back out of the crossed
  // document instead would need the reverse conversion to run in the middle of a write, so a
  // declaration whose `try_into` leg can refuse would have a store verb failing on the READ half of
  // a crossing it never performs.
  let filter = identity::<Row>(record.id_ref())?;
  Ok((filter, Row::row(record)?.document()))
}

/// The filter a [`delete`](super::delete) removes one document by.
///
/// [`identity`]'s spelling and nothing added: the `_id` is unique by the server's own construction, so
/// the predicate names at most one document by the storage engine's law and the verb answers a
/// yes-or-no rather than a count.
///
/// Bounded by [`MongoQuery`] where the store verbs take [`MongoWrite`], and the narrower bound is the
/// honest one: an address is a READ-side fact — the same one [`address`](super::address) is built
/// from — so nothing here needs a document to know how to be written. The LANE still asks for the
/// write binding, which is where *may this row be stored at all* belongs.
///
/// # Errors
///
/// Whatever the declaration's own id conversion refuses with — see [`MongoQuery::id`].
pub fn removal<Row: MongoQuery>(
  id: &<Row::Record as Identifiable>::Id,
) -> Result<Document, MongoWriteError> {
  Ok(identity::<Row>(id)?)
}

/// The filter a [`delete_where`](super::delete_where) removes documents by — lowered, and refused
/// where it names everything or reaches another collection.
///
/// # The unscoped refusal is TWO tiers, exactly as the SQL lane's is
///
/// The first asks about the VALUE: a comparison with no operator set anywhere answers
/// [`is_empty`](ComplexComparison::is_empty), and it is asked before anything lowers so that the
/// cheapest refusal is also the first — and so that the sentence is about the COLLECTION rather than
/// about whichever stage noticed.
///
/// The second asks about the RENDERING, and it is not the first one repeated. `is_empty` is a count
/// an implementor supplies and the filter document is text an implementor writes; a comparison whose
/// count OVER-reports passes the first tier and is caught only here. What it would otherwise produce
/// is `deleteMany({})` — which is every document in the collection, reported as success. So the second
/// tier is a check on the trait's own contract, and it is where the SQL lane's *rendered zero
/// conjuncts* check sits one backend over.
///
/// # The join refusal is this backend's third, and it is not optional
///
/// See [`MongoWriteError::Joined`]. A predicate that lowered to `$lookup` stages has said something a
/// delete command cannot carry, and sending the `$match` without them would remove a SUPERSET of what
/// the filter named.
///
/// # Errors
///
/// A lowering refusal carried verbatim, [`MongoWriteError::Joined`] for a filter that needs a join,
/// and [`MongoWriteError::Unscoped`] for one that names no document.
pub fn removal_where<Row, P>(filter: &P) -> Result<Document, MongoWriteError>
where
  Row: MongoQuery,
  P: ComplexComparison<Mongo>,
{
  let address = Row::ADDRESS;
  // Ahead of every rendering, so the cheapest refusal is also the first — the SQL lane's own
  // ordering, and for its reason.
  if filter.is_empty() {
    return Err(MongoWriteError::Unscoped(address.table()));
  }
  let predicate = filter
    .apply(At::new(&address), MongoConjunction::new())?
    .into_predicate();
  let (document, joins, _) = predicate.into_parts();
  // BEFORE the empty-document tier, and the order is load-bearing rather than tidy: a filter whose
  // whole predicate is a relation lowers to an EMPTY `$match` with the meaning in the stages after it
  // — `package::tests`' own joined golden renders exactly that — so asking *is the document empty*
  // first would answer `Unscoped`, which is a true sentence about the wrong cause. The caller's filter
  // is not unscoped; it is unrunnable here.
  if !joins.is_empty() {
    return Err(MongoWriteError::Joined(joins.len()));
  }
  if document.is_empty() {
    return Err(MongoWriteError::Unscoped(address.table()));
  }
  Ok(document)
}

#[cfg(test)]
mod tests;