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 family's two halves: how an address becomes a BSON key, and what the accumulator does with
//! a second conjunct.

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

use super::{Mongo, MongoConjunction, MongoLoweringError, MongoOperator};
use crate::{At, Backend, FieldName, RecordAddress};

/// The row every address below names. Nothing here is correlated, so no test reads it.
const ROW: RecordAddress = RecordAddress::new(FieldName::new("media"), &[FieldName::new("id")]);

/// The key `at` renders to, through the backend row rather than through the free function — so
/// every assertion below is about what a comparison would actually be handed.
fn key(at: At<'_>) -> String {
  let mut rendered = String::new();
  <Mongo as Backend>::write_column(at, &mut rendered);
  rendered
}

#[test]
fn one_segment_is_the_bare_field_name() {
  let frame = At::new(&ROW).frame(FieldName::new("title"));
  assert_eq!(key(frame.at()), "title");
}

/// A composite occupies a SUBDOCUMENT here, where SQL gives it sibling columns — so the segments a
/// layer pushes are joined by the addressing character rather than run together inside one name.
#[test]
fn segments_join_with_dots_at_every_depth() {
  let outer = At::new(&ROW).frame(FieldName::new("timebase"));
  let inner = outer.at().frame(FieldName::new("num"));
  assert_eq!(key(inner.at()), "timebase.num");

  let deepest = inner.at().frame(FieldName::new("scale"));
  assert_eq!(key(deepest.at()), "timebase.num.scale");
}

/// The top level names no field, and what stands in for one has to be REFUSED rather than resolved.
/// Writing nothing — the SQL answer — would leave `{"": …}`, a legal filter about a field called
/// `""`; a top-level `$` is read as an operator and the server has none by that name.
#[test]
fn the_empty_path_writes_a_key_the_server_refuses() {
  assert_eq!(key(At::new(&ROW)), "$");
}

/// The two families are handed the same segments and answer differently, which is the whole of what
/// [`Backend::write_column`] was split out for: SQL runs them together inside one bracketed
/// identifier, MongoDB nests them along a real path and brackets nothing.
///
/// The two now render into different BUFFERS as well — `Utf8BytesMut` here and `String` there — and
/// this stays ONE generic function over both, which is the part worth keeping. Two explicit
/// renderings would assert the same two strings while proving something weaker: what is under test
/// is that the seam itself carries no family's rule, and only a caller that cannot see which
/// backend it has can show that. `B::buffer` supplies the buffer and `AsRef<str>` reads it back,
/// which is exactly as much as such a caller may assume.
#[cfg(feature = "sqlite")]
#[test]
fn the_two_families_join_the_same_segments_differently() {
  fn rendered<B: Backend>(at: At<'_>) -> String
  where
    B::Buffer: AsRef<str>,
  {
    let mut out = B::buffer();
    B::write_column(at, &mut out);
    out.as_ref().to_owned()
  }

  let outer = At::new(&ROW).frame(FieldName::new("timebase"));
  let inner = outer.at().frame(FieldName::new("num"));

  assert_eq!(rendered::<sqlx::Sqlite>(inner.at()), "\"timebase_num\"");
  assert_eq!(rendered::<Mongo>(inner.at()), "timebase.num");
}

/// An accumulator nothing wrote to is `{}`, which MATCHES EVERY DOCUMENT — the same answer the SQL
/// accumulator gives by pushing no clause keyword, arrived at without arranging anything.
#[test]
fn an_untouched_accumulator_is_the_filter_that_matches_everything() {
  assert!(MongoConjunction::new().into_document().is_empty());
}

/// **The case this backend exists to test.** SQL renders two operators on one column as two
/// conjuncts; a BSON document has unique keys, so the second has to join the operator document the
/// first opened.
#[test]
fn two_operators_on_one_field_share_one_key() {
  let mut accumulator = MongoConjunction::new();
  accumulator.merge("a", MongoOperator::Gt, Bson::Int32(1));
  accumulator.merge("a", MongoOperator::Lt, Bson::Int32(5));

  assert_eq!(
    accumulator.into_document(),
    doc! { "a": { "$gt": 1, "$lt": 5 } }
  );
}

/// Two FIELDS are two keys, and the document ANDs them with nothing written between: there is no
/// separator here for an accumulator to hold the way the SQL one holds ` AND `.
#[test]
fn two_fields_are_two_keys_and_nothing_joins_them() {
  let mut accumulator = MongoConjunction::new();
  accumulator.merge("a", MongoOperator::Eq, Bson::Int32(1));
  accumulator.merge("b", MongoOperator::Eq, Bson::Int32(2));

  assert_eq!(
    accumulator.into_document(),
    doc! { "a": { "$eq": 1 }, "b": { "$eq": 2 } }
  );
}

/// Where merging runs out: one field, one operator, twice. A document key cannot hold both, so the
/// second becomes an `$and` branch beside the merged keys instead of overwriting the first — which
/// is MongoDB's own answer to the question, and the only one that loses nothing.
#[test]
fn a_repeated_operator_overflows_into_and() {
  let mut accumulator = MongoConjunction::new();
  accumulator.merge("a", MongoOperator::Eq, Bson::Int32(1));
  accumulator.merge("a", MongoOperator::Eq, Bson::Int32(2));
  accumulator.merge("b", MongoOperator::Gt, Bson::Int32(3));

  assert_eq!(
    accumulator.into_document(),
    doc! {
      "a": { "$eq": 1 },
      "b": { "$gt": 3 },
      "$and": [ { "a": { "$eq": 2 } } ],
    }
  );
}

/// Every operator is written under its `$`-prefixed key, and the exhaustive `match` is the
/// assertion: a row added without a spelling stops compiling, where a row added with the `$`
/// dropped would leave a filter that matches a SUBDOCUMENT of that shape without complaint.
#[test]
fn every_operator_carries_its_sigil() {
  for op in [
    MongoOperator::Eq,
    MongoOperator::Ne,
    MongoOperator::Gt,
    MongoOperator::Gte,
    MongoOperator::Lt,
    MongoOperator::Lte,
    MongoOperator::In,
    MongoOperator::Nin,
    MongoOperator::Regex,
    MongoOperator::Not,
    MongoOperator::All,
    MongoOperator::ElemMatch,
    MongoOperator::Type,
    MongoOperator::Exists,
    MongoOperator::BitsAllSet,
    MongoOperator::BitsAnySet,
    MongoOperator::BitsAllClear,
  ] {
    let spelled = match op {
      MongoOperator::Eq => "$eq",
      MongoOperator::Ne => "$ne",
      MongoOperator::Gt => "$gt",
      MongoOperator::Gte => "$gte",
      MongoOperator::Lt => "$lt",
      MongoOperator::Lte => "$lte",
      MongoOperator::In => "$in",
      MongoOperator::Nin => "$nin",
      MongoOperator::Regex => "$regex",
      MongoOperator::Not => "$not",
      MongoOperator::All => "$all",
      MongoOperator::ElemMatch => "$elemMatch",
      MongoOperator::Type => "$type",
      MongoOperator::Exists => "$exists",
      MongoOperator::BitsAllSet => "$bitsAllSet",
      MongoOperator::BitsAnySet => "$bitsAnySet",
      MongoOperator::BitsAllClear => "$bitsAllClear",
    };
    assert_eq!(op.as_str(), spelled);
    assert!(op.as_str().starts_with('$'));
  }
}

/// The one row `$elemMatch`'s value form does not answer, and it is the row that says no by matching
/// NOTHING — measured on 8.2.12 against `[[1, 2], [8]]`, where `{$elemMatch: {$all: [1]}}` returns
/// no document and raises nothing. Every other row answers there.
#[test]
fn only_all_is_refused_the_element_scope() {
  assert!(!MongoOperator::All.in_element_scope());
  for op in [
    MongoOperator::Eq,
    MongoOperator::Ne,
    MongoOperator::Gt,
    MongoOperator::Gte,
    MongoOperator::Lt,
    MongoOperator::Lte,
    MongoOperator::In,
    MongoOperator::Nin,
    MongoOperator::Regex,
    MongoOperator::Not,
    MongoOperator::ElemMatch,
    MongoOperator::Type,
    MongoOperator::Exists,
  ] {
    assert!(op.in_element_scope(), "{op:?}");
  }
}

/// **The element scope's value form.** The member is the EMPTY path, so its operators are the scope
/// document's own keys — `{$gt: 1, $lt: 6}` rather than the `{"$": …}` the same address renders at
/// the top of a filter.
#[test]
fn operators_at_the_member_become_the_scope_documents_own_keys() {
  let mut accumulator = MongoConjunction::element();
  accumulator.merge("$", MongoOperator::Gt, Bson::Int32(1));
  accumulator.merge("$", MongoOperator::Lt, Bson::Int32(6));

  assert_eq!(
    accumulator.into_element_document(),
    Ok(doc! { "$gt": 1, "$lt": 6 })
  );
}

/// The QUERY form is what a composite element renders into, and it keeps the fold: `$and` inside
/// `$elemMatch` is legal where its branches are field documents, which is exactly what an overflow
/// branch is.
#[test]
fn a_field_below_the_member_keeps_the_and_fold() {
  let mut accumulator = MongoConjunction::element();
  accumulator.merge("price", MongoOperator::Gt, Bson::Int32(1));
  accumulator.merge("price", MongoOperator::Gt, Bson::Int32(2));

  assert_eq!(
    accumulator.into_element_document(),
    Ok(doc! { "price": { "$gt": 1 }, "$and": [ { "price": { "$gt": 2 } } ] })
  );
}

/// The value form hosts no `$and`, so the fold every other position uses has no spelling and the
/// second conjunct is refused rather than written into a document the server would reject.
#[test]
fn a_repeated_operator_at_the_member_is_refused() {
  let mut accumulator = MongoConjunction::element();
  accumulator.merge("$", MongoOperator::Gt, Bson::Int32(1));
  accumulator.merge("$", MongoOperator::Gt, Bson::Int32(2));

  assert_eq!(
    accumulator.into_element_document(),
    Err(MongoLoweringError::ElementConjunction)
  );
}

/// The two forms do not MIX — `{$elemMatch: {$gt: 1, p: 2}}` is *unknown operator: p* — so a
/// comparison writing at the member and at a field below it is the same refusal under a second
/// cause.
#[test]
fn a_bare_operator_beside_a_field_name_is_refused() {
  let mut accumulator = MongoConjunction::element();
  accumulator.merge("$", MongoOperator::Gt, Bson::Int32(1));
  accumulator.merge("p", MongoOperator::Eq, Bson::Int32(2));

  assert_eq!(
    accumulator.into_element_document(),
    Err(MongoLoweringError::ElementConjunction)
  );
}

/// `$all` at the member is the dangerous one: it is not refused by the server, it matches nothing.
/// The refusal names the operator, and it survives being asked FIRST — a later cause is a
/// consequence of a comparison that already had no rendering.
#[test]
fn an_operator_the_value_form_ignores_is_refused_by_name() {
  let mut accumulator = MongoConjunction::element();
  accumulator.merge("$", MongoOperator::All, Bson::Array(vec![Bson::Int32(1)]));
  accumulator.merge("$", MongoOperator::All, Bson::Array(vec![Bson::Int32(2)]));

  assert_eq!(
    accumulator.into_element_document(),
    Err(MongoLoweringError::ElementOperator(MongoOperator::All))
  );
}

/// A top-level operator is refused in BOTH forms — the server is explicit that `$expr` may only be
/// applied to the top-level document — so it is caught by where it came from rather than by what
/// else was written.
#[test]
fn a_top_level_operator_has_no_element_scope() {
  let mut accumulator = MongoConjunction::element();
  accumulator.and(doc! { "$expr": { "$gt": [ 1, 0 ] } });

  assert_eq!(
    accumulator.into_element_document(),
    Err(MongoLoweringError::ElementDocument)
  );
}

/// At the TOP of a filter the same document is an ordinary conjunct, ANDed beside the merged keys
/// through the fold the overflow already had.
#[test]
fn a_top_level_operator_folds_beside_the_merged_keys() {
  let mut accumulator = MongoConjunction::new();
  accumulator.merge("a", MongoOperator::Eq, Bson::Int32(1));
  accumulator.and(doc! { "$expr": { "$gt": [ 1, 0 ] } });

  assert_eq!(
    accumulator.into_document(),
    doc! { "a": { "$eq": 1 }, "$and": [ { "$expr": { "$gt": [ 1, 0 ] } } ] }
  );
}

/// An element scope nothing wrote to is `{}`, which is NOT the empty predicate MongoDB reads it as:
/// measured, an empty scope document matches only members that are documents. Substituting the
/// tautology is the collection kind's job rather than the accumulator's, and this pins the accumulator
/// half — that it hands back what was written and adds nothing.
#[test]
fn an_untouched_element_scope_is_the_empty_document() {
  assert_eq!(
    MongoConjunction::element().into_element_document(),
    Ok(Document::new())
  );
}