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 DOCUMENT each write verb sends, WITHOUT a server.
//!
//! # The posture is the read lane's, and it is measured rather than chosen
//!
//! `ci/test-matrix.sh` runs `cargo` lanes and provisions no service — there is no mongod in it, and
//! no in-process fake to stand in for one — so a live test here would be a lane nothing runs. What a
//! write verb DECIDES is the document it sends, which is a value; so that is what is asserted, the
//! same way [`lane`](super::super::lane)'s own tests assert the command a read would issue.
//!
//! Two rows are therefore the SERVER's rather than this lane's, and both are documented behaviour:
//! a second `insertOne` at a stored `_id` is refused with duplicate-key `11000`, and a `replaceOne`
//! with `upsert: true` at that same address is not. Neither is reachable without a mongod, and
//! neither is anything this file chooses.
//!
//! # The binding is written BY HAND, which is the third-party proof as well as the harness
//!
//! [`MongoWrite`](super::MongoWrite) is implemented on the family's own fixture through nothing but
//! its public items — `ingraph-codegen` cannot reach this crate, so a member only an emitter could
//! have supplied would not compile there. That is `query::sql::write`'s own arrangement, one backend
//! over, and the filters below are the FIXTURE's own builders so that a predicate a package golden
//! renders and a predicate a delete removes by are one value.

use bson::{Bson, Document, doc};

use super::{removal, removal_where, replacement, stored};
use crate::{
  ComplexComparison,
  comparison::{At, Backend, mongo::Mongo},
  query::mongo::{
    MongoQuery, MongoWriteError,
    tests::{Shot, ShotFilter, ShotMongo, covering, titled},
  },
};

/// The record every verb below is asked about — one `Some` optional and one `None`, so the
/// null-writing row is on the path of every document rather than of a case.
fn shot() -> Shot {
  Shot {
    media: 7,
    id: 3,
    title: "wide".to_owned(),
    score: Some(0.5),
    cover: None,
  }
}

/// The document that record becomes, spelled out: every field under the key this database spells it,
/// the id under `_id`, and the absent optional under an explicit `null`.
fn stored_shot() -> Document {
  doc! {
    "media": 7i64,
    "_id": 3i64,
    "title": "wide",
    "score": 0.5f64,
    "cover_id": Bson::Null,
  }
}

/// The whole document, and the id under the key MongoDB indexes rather than the one the record
/// wrote — which is the mapping [`field_key`](crate::comparison::mongo::field_key) owns, and this is
/// the write side of it.
#[test]
fn an_insert_sends_the_whole_document_with_the_id_under_underscore_id() {
  let document = stored::<ShotMongo>(shot()).expect("the fixture crosses");

  assert_eq!(document, stored_shot());
}

/// An absent optional is written as `null` rather than left out, and the reason is the REPLACEMENT:
/// `replaceOne` swaps the whole document, so a key omitted is a key the stored document loses.
#[test]
fn an_absent_optional_is_written_as_null_rather_than_omitted() {
  let document = stored::<ShotMongo>(shot()).expect("the fixture crosses");

  assert!(document.contains_key("cover_id"));
  assert_eq!(document.get("cover_id"), Some(&Bson::Null));
}

/// The keyed replace is the SAME document the plain store sends, at the SAME address a `get` and a
/// `delete` name — which is what makes the three verbs one address vocabulary rather than three.
#[test]
fn an_upsert_replaces_the_whole_document_at_the_address_the_other_verbs_name() {
  let (filter, document) = replacement::<ShotMongo>(shot()).expect("the fixture crosses");

  assert_eq!(filter, doc! { "_id": { "$eq": 3i64 } });
  assert_eq!(document, stored_shot());
  assert_eq!(document, stored::<ShotMongo>(shot()).expect("crosses"));
  assert_eq!(filter, removal::<ShotMongo>(&3).expect("the id crosses"));
}

/// **THE CASCADE, as far as a value can carry it.** The replacement is a DOCUMENT and never an update
/// specification: no key of it is an operator, so `replaceOne` swaps the stored document whole rather
/// than merging fields into it. That is what makes an embedded array — the only form a collection
/// column takes on this backend, there being no second table — go with the record it belongs to, in
/// the one command, with nothing between two halves for a failure to land in.
///
/// A `$set`-shaped document would pass every other assertion in this file and would MERGE: a field
/// the new record does not carry would survive under the old record's value, silently. So the shape
/// is asserted rather than assumed.
#[test]
fn the_replacement_is_a_document_and_never_an_update_specification() {
  let (_, document) = replacement::<ShotMongo>(shot()).expect("the fixture crosses");

  assert!(
    document.keys().all(|key| !key.starts_with('$')),
    "a replacement carries fields, and an operator key would make it an update: {document:?}"
  );
  // Every field the document declares and nothing else: a replacement narrower than the row would
  // leave the stored document holding whatever the last writer put there.
  assert_eq!(document.len(), <ShotMongo as MongoQuery>::FIELDS.len());
}

/// **IDEMPOTENCY, as far as a value carries it.** The same record always produces the same pair, so a
/// second `upsert` issues the command the first one issued — byte for byte, filter and replacement
/// both. Nothing in the crossing reads a clock, a counter or anything the caller did not hand over.
///
/// What a server adds beyond this is that `replaceOne(…, upsert: true)` at an address it already
/// filled is not a duplicate-key error, which is the row a live walk owes and this one cannot claim.
#[test]
fn upserting_the_same_record_twice_issues_the_same_command() {
  let once = replacement::<ShotMongo>(shot()).expect("the fixture crosses");
  let twice = replacement::<ShotMongo>(shot()).expect("the fixture crosses");

  assert_eq!(once, twice);
}

/// The removal at an address is the address predicate and nothing else — no `$limit`, because `_id`
/// is unique by the server's own construction.
#[test]
fn a_delete_names_one_document_by_its_id() {
  let filter = removal::<ShotMongo>(&3).expect("the id crosses");

  assert_eq!(filter, doc! { "_id": { "$eq": 3i64 } });
}

/// The filter road lowers the CALLER's own comparison — the same value a `find` would have taken,
/// rendering the same predicate, which is what lets a caller check a re-index's scope with a read
/// before spending it on a delete.
#[test]
fn a_scoped_delete_lowers_the_callers_own_filter() {
  let predicate = removal_where::<ShotMongo, _>(&titled("wide")).expect("a scoped filter lowers");

  assert_eq!(predicate, doc! { "title": { "$eq": "wide" } });
}

/// **TIER ONE of the unscoped refusal** — the VALUE. A comparison with no operator set anywhere is
/// refused before anything lowers, naming the collection that was about to go.
#[test]
fn an_unfilled_comparison_is_refused_before_anything_lowers() {
  let refusal = removal_where::<ShotMongo, _>(&ShotFilter::default())
    .expect_err("an empty comparison names no document");

  match refusal {
    MongoWriteError::Unscoped(collection) => assert_eq!(collection.as_str(), "shot"),
    other => panic!("the empty comparison is refused as unscoped, not as `{other}`"),
  }
}

/// **TIER TWO** — the RENDERING, and it is not tier one repeated. `conjuncts` is a number an
/// implementor supplies and the filter document is what an implementor writes; a comparison that
/// OVER-reports passes the first tier and is caught only here, where what it would otherwise send is
/// `deleteMany({})` — every document in the collection, reported as success.
///
/// The over-reporting comparison is built rather than described: nothing shipped does this, which is
/// exactly why the second tier is a check on the trait's own contract rather than a second reading of
/// the first.
#[test]
fn a_comparison_that_over_reports_its_conjuncts_is_still_refused() {
  let refusal =
    removal_where::<ShotMongo, _>(&Liar).expect_err("a filter that renders `{}` is refused");

  match refusal {
    MongoWriteError::Unscoped(collection) => assert_eq!(collection.as_str(), "shot"),
    other => panic!("the over-reporting comparison is refused as unscoped, not as `{other}`"),
  }
}

/// A filter that lowers to a `$lookup` is refused by name, carrying how many stages had no place to
/// go — because a delete command takes a filter document and has no pipeline.
///
/// # The stakes are the WORST case rather than a narrow one, and the package golden says so
///
/// `a_relation_joins_before_the_sort_and_grows_the_reads`, one module over, renders this same value:
/// its top-level `$match` is **`{}`** and the whole predicate lives in the three stages after it —
/// the `$lookup`, the `$ne: []` that keeps the documents it matched, and the `$project` that drops
/// the join field again. So a lane that sent the `$match` and dropped the rest would send
/// `deleteMany({})`: not a superset, the WHOLE COLLECTION, reported as success.
///
/// The refusal is therefore asked BEFORE the empty-document tier, so the sentence a caller reads
/// names the cause rather than the symptom — this filter is not unscoped, it is unrunnable here.
///
/// The same value is a perfectly good READ, which is what makes this one predicate answering
/// differently to two commands rather than a predicate nobody can write.
#[test]
fn a_filter_that_needs_a_lookup_is_refused_rather_than_run_without_it() {
  let refusal = removal_where::<ShotMongo, _>(&covering("Autumn"))
    .expect_err("a relation predicate has no place in a delete");

  match refusal {
    // The three the golden renders: the join, its keep-predicate, and the projection that undoes it.
    MongoWriteError::Joined(stages) => assert_eq!(stages, 3),
    other => panic!("the joined filter is refused as joined, not as `{other}`"),
  }
}

/// The document a write sends is the document the extraction reads: the same keys, the same values,
/// and a record that comes back equal. It is the one assertion neither direction can make alone, and
/// it is what the two carrier tables being inverses BUYS — a serde-written document would fail here
/// on the first blob-shaped column.
#[test]
fn the_document_a_write_sends_is_the_document_the_read_extracts() {
  let record = shot();
  let document = stored::<ShotMongo>(record.clone()).expect("the fixture crosses");
  let read = ShotMongo::from_document(&document).expect("the write's own document extracts");

  assert_eq!(read.record().expect("the row raises"), record);
}

/// A comparison that says it wrote something and writes nothing — the shape tier two exists for, and
/// the only way to reach it.
#[derive(Debug)]
struct Liar;

impl ComplexComparison<Mongo> for Liar {
  fn conjuncts(&self) -> usize {
    1
  }

  fn apply<'q>(
    &'q self,
    _: At<'_>,
    builder: <Mongo as Backend>::Builder<'q>,
  ) -> Result<<Mongo as Backend>::Builder<'q>, <Mongo as Backend>::Error> {
    Ok(builder)
  }
}