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
//! What the scalar kind renders, and the case the whole backend was written to check: two
//! operators on one field.

use bson::{Document, doc};

use super::MongoScalarComparison;
use crate::{
  At, ComplexComparison, FieldName, Mongo, RecordAddress, ScalarFilter, ToDatabaseComparison,
  TryFromFilter, comparison::mongo::MongoConjunction,
};

/// 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")]);

/// Lower one comparison at one column of [`ROW`] and finish the filter.
fn rendered<C: ComplexComparison<Mongo>>(comparison: &C, column: &str) -> Document {
  let frame = At::new(&ROW).frame(FieldName::new(column));
  comparison
    .apply(frame.at(), MongoConjunction::new())
    .expect("a MongoDB lowering cannot refuse")
    .into_document()
}

/// **The case this backend exists to check, through `apply` rather than through the accumulator.**
///
/// The same filter renders `"a" > ? AND "a" < ?` in SQL — two conjuncts appended — where a BSON
/// document has unique keys and both operators have to arrive under ONE.
#[test]
fn two_operators_on_one_field_share_one_key() {
  let comparison =
    MongoScalarComparison::<i64>::try_from_filter(ScalarFilter::<i32>::new().with_gt(1).with_lt(5))
      .expect("the identity crossing cannot fail");

  assert_eq!(comparison.conjuncts(), 2);
  assert_eq!(
    rendered(&comparison, "a"),
    doc! { "a": { "$gt": 1_i64, "$lt": 5_i64 } }
  );
}

/// All eight operators, all under one key — and the mapping onto `$eq`, `$ne`, `$gt`, `$gte`,
/// `$lt`, `$lte`, `$in` and `$nin` is one-to-one, which is a result rather than a coincidence: the
/// operator vocabulary was chosen against SQL.
#[test]
fn every_operator_maps_one_to_one_and_merges() {
  let comparison = MongoScalarComparison::<i64>::try_from_filter(
    ScalarFilter::<i64>::new()
      .with_eq(1)
      .with_ne(2)
      .with_gt(3)
      .with_gte(4)
      .with_lt(5)
      .with_lte(6)
      .with_in_(vec![7_i64, 8])
      .with_not_in(vec![9_i64]),
  )
  .expect("the identity crossing cannot fail");

  assert_eq!(comparison.conjuncts(), 8);
  assert_eq!(
    rendered(&comparison, "a"),
    doc! {
      "a": {
        "$eq": 1_i64,
        "$ne": 2_i64,
        "$gt": 3_i64,
        "$gte": 4_i64,
        "$lt": 5_i64,
        "$lte": 6_i64,
        "$in": [7_i64, 8_i64],
        "$nin": [9_i64],
      }
    }
  );
}

/// A composite occupies a SUBDOCUMENT here, which is what the `.` join means: the same frames that
/// give SQL a `timebase_num` column give MongoDB a field of a nested document.
#[test]
fn a_frame_below_a_frame_addresses_a_subdocument() {
  let comparison =
    MongoScalarComparison::<i64>::try_from_filter(ScalarFilter::<i32>::new().with_eq(3))
      .expect("the identity crossing cannot fail");

  let outer = At::new(&ROW).frame(FieldName::new("timebase"));
  let inner = outer.at().frame(FieldName::new("num"));
  let filter = comparison
    .apply(inner.at(), MongoConjunction::new())
    .expect("a MongoDB lowering cannot refuse")
    .into_document();

  assert_eq!(filter, doc! { "timebase.num": { "$eq": 3_i64 } });
}

/// A PRESENT membership operator with an empty list asks for no documents, and an ABSENT one asks
/// for every document — the same truth table the SQL family reaches through `1 = 0` and its
/// negation wrap, arrived at here with no degenerate case to write.
#[test]
fn an_empty_membership_list_is_the_operator_present() {
  let empty = MongoScalarComparison::<i64>::try_from_filter(
    ScalarFilter::<i64>::new().with_in_(Vec::<i64>::new()),
  )
  .expect("the identity crossing cannot fail");
  assert_eq!(empty.conjuncts(), 1);
  assert_eq!(rendered(&empty, "a"), doc! { "a": { "$in": [] } });

  let absent = MongoScalarComparison::<i64>::new();
  assert!(absent.is_empty());
  assert!(rendered(&absent, "a").is_empty());
}

/// Two comparisons threaded through ONE accumulator at one path, both setting `eq`. A document key
/// cannot hold two `$eq`s, so the second becomes an `$and` branch — where SQL simply appends a
/// second conjunct and where an overwrite would answer a different question in silence.
#[test]
fn two_comparisons_at_one_path_overflow_rather_than_overwrite() {
  let first = MongoScalarComparison::<i64>::try_from_filter(ScalarFilter::<i32>::new().with_eq(1))
    .expect("the identity crossing cannot fail");
  let second = MongoScalarComparison::<i64>::try_from_filter(ScalarFilter::<i32>::new().with_eq(2))
    .expect("the identity crossing cannot fail");

  let frame = At::new(&ROW).frame(FieldName::new("a"));
  let mut accumulator = MongoConjunction::new();
  accumulator = first
    .apply(frame.at(), accumulator)
    .expect("a MongoDB lowering cannot refuse");
  accumulator = second
    .apply(frame.at(), accumulator)
    .expect("a MongoDB lowering cannot refuse");

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

/// A comparison over a COLUMN applied at the TOP LEVEL addresses none, and what stands in has to be
/// refused by the engine rather than resolved by it — `{"": …}` would be a legal filter about a
/// field called `""`.
#[test]
fn a_column_comparison_at_the_top_level_writes_the_key_the_server_refuses() {
  let comparison =
    MongoScalarComparison::<i64>::try_from_filter(ScalarFilter::<i32>::new().with_eq(1))
      .expect("the identity crossing cannot fail");

  let filter = comparison
    .apply(At::new(&ROW), MongoConjunction::new())
    .expect("a MongoDB lowering cannot refuse")
    .into_document();

  assert_eq!(filter, doc! { "$": { "$eq": 1_i64 } });
}

/// The projection an expansion writes for a scalar field, resolved — and the ANNOTATION is the
/// assertion: the crossing must land on this kind, and the kind must be the one that lowers for
/// this backend.
#[test]
fn the_codegen_projection_resolves_for_a_scalar_field() {
  type Crossed = <ScalarFilter<i64> as ToDatabaseComparison<i64, Mongo>>::Comparison;

  let comparison: Crossed = MongoScalarComparison::<i64>::new();
  assert!(comparison.is_empty());
}

/// The identity crossing is provably unable to fail rather than merely always succeeding, and the
/// `match` with NO arms is what proves it: an error type with an inhabitant stops compiling here.
#[test]
fn the_identity_crossing_cannot_fail() {
  fn unreachable_reason(
    error: <MongoScalarComparison<i64> as TryFromFilter<ScalarFilter<i64>>>::Error,
  ) -> ! {
    match error {}
  }

  match MongoScalarComparison::<i64>::try_from_filter(ScalarFilter::<i32>::new().with_eq(1)) {
    Ok(comparison) => assert_eq!(comparison.conjuncts(), 1),
    Err(error) => unreachable_reason(error),
  }
}

/// A comparison over a FIELD's own operators refuses nothing, and that is the whole of what this
/// backend's refusal is not about.
///
/// This was a `match` with NO arms, and it stopped compiling exactly when its own note said it
/// would: the element scope gave [`Mongo`] a way to fail and that failure took a name. What survives
/// is the half worth asserting — every refusal this family has belongs to the position INSIDE an
/// `$elemMatch`, so a kind writing a field's operators has no path to one whatever it is handed.
#[test]
fn a_field_operator_lowering_refuses_nothing() {
  let comparison = MongoScalarComparison::<i64>::try_from_filter(
    ScalarFilter::<i32>::new().with_gt(1).with_not_in([2, 3]),
  )
  .expect("the identity crossing");
  let frame = At::new(&ROW).frame(FieldName::new("a"));

  assert!(
    comparison
      .apply(frame.at(), MongoConjunction::new())
      .is_ok()
  );

  // The same comparison at the MEMBER's address, finished as a scope document: eight distinct
  // operators are eight distinct keys, so nothing here overflows and nothing here is a row the value
  // form declines.
  let scope = comparison
    .apply(At::new(&ROW), MongoConjunction::element())
    .expect("apply itself never refuses")
    .into_element_document();
  assert_eq!(scope, Ok(doc! { "$gt": 1i64, "$nin": [ 2i64, 3i64 ] }));
}

/// **A `u64` field is declarable on a build with this backend and no other**, which is the whole of
/// what the storage split bought and the thing that was impossible before it.
///
/// BSON has no unsigned 64-bit integer, so `u64` has no row and never will — the same answer SQLite
/// and Postgres give. What changed is the ESCAPE: `BeU64` used to live inside `comparison::sql`
/// behind the `sqlx` feature, so this declaration could not be spelled here at all, for a reason
/// that had nothing to do with MongoDB. Every name below now comes from the crate root.
///
/// It runs under `--all-features` too, where it proves less. `ci/test-matrix.sh`'s
/// `--features mongo` lane is the one where the SQL family is absent and the declaration has
/// nothing to borrow.
#[test]
fn a_wide_integer_field_declares_the_big_endian_carrier() {
  use bson::{Binary, spec::BinarySubtype};

  use crate::BeU64;

  /// The stored blob, spelled from the carrier's own codec rather than from a literal — so this
  /// asserts the ROW reaches that codec and not that two byte lists were typed alike.
  fn blob(value: BeU64) -> Binary {
    Binary {
      subtype: BinarySubtype::Generic,
      bytes: value.to_blob().to_vec(),
    }
  }

  let comparison = MongoScalarComparison::<BeU64>::try_from_filter(
    ScalarFilter::<u64>::new().with_eq(1_u64).with_lt(9_u64),
  )
  .expect("the crossing into a blob carrier is total");

  assert_eq!(comparison.eq(), Some(&BeU64(1)));
  assert_eq!(
    rendered(&comparison, "checksum"),
    doc! {
      "checksum": {
        "$eq": blob(BeU64(1)),
        "$lt": blob(BeU64(9)),
      }
    }
  );
}

/// **The framework's own COMPOSITE, on the backend where a composite needs no lowering of its own.**
///
/// The SQL family had to grow a row value for an instant — one left-hand side naming two columns —
/// because a table FLATTENS a composite. A document NESTS it, so the operand is one sub-document
/// under one key and `$eq` and the ordering operators are already the right questions. This is that
/// claim checked rather than taken on faith, and what it checks is the two halves it rests on:
///
/// - the operand reaches ONE key, whole, so nothing here compares a column that does not exist;
/// - the sub-document's fields are written `secs` THEN `nanos`, which is what MongoDB's documented
///   BSON order reads — a document is compared field by field in the order it holds them, so the
///   pair sorts by seconds and breaks ties on the fraction. The lexicographic step from there to the
///   instant's own order is pinned once, on the type: see
///   `primitives::timestamp::tests::the_pairs_lexicographic_order_is_the_instants`.
#[test]
fn an_instant_compares_whole_under_one_key() {
  use crate::Timestamp;

  let at: Timestamp = "2026-08-09T21:14:03.123456789Z".parse().unwrap();
  let before: Timestamp = "1969-12-31T23:59:58.5Z".parse().unwrap();
  let comparison = MongoScalarComparison::<Timestamp>::try_from_filter(
    ScalarFilter::<Timestamp>::new()
      .with_gte(before)
      .with_lt(at),
  )
  .expect("the identity crossing cannot fail");

  let rendered = rendered(&comparison, "at");
  assert_eq!(
    rendered,
    doc! {
      "at": {
        "$gte": { "secs": -1_i64, "nanos": -500_000_000_i32 },
        "$lt": { "secs": 1_786_310_043_i64, "nanos": 123_456_789_i32 },
      }
    }
  );

  // The KEY ORDER inside the operand, which the assertion above cannot see: `doc!` compares by
  // content and BSON compares by position, so the sequence is read out rather than matched.
  let Some(bson::Bson::Document(operators)) = rendered.get("at") else {
    panic!("the instant's operators share one key");
  };
  let Some(bson::Bson::Document(operand)) = operators.get("$lt") else {
    panic!("the operand is a sub-document");
  };
  assert_eq!(
    operand.keys().collect::<Vec<_>>(),
    ["secs", "nanos"],
    "BSON compares a document field by field in this order, so seconds have to come first"
  );
}

/// **THE CONFIDENCE KIND LOWERS HERE TOO**, and it renders through the ordinary scalar path — one
/// widthless threshold, the column's own width, and `$gte` where every other scalar column has one.
///
/// The SQL family's twin test is where the per-width argument is written out; what this one adds is
/// that the second backend joined by the same road, through a row bounded on
/// [`ScoreKind`](crate::ScoreKind) rather than on four widths.
#[test]
fn a_confidence_threshold_renders_at_the_columns_width() {
  use crate::{Confidence, ConfidenceFilter, ConfidenceOperand};

  let filter = ConfidenceFilter::new().with_gte(ConfidenceOperand::number(0.5).expect("in range"));
  let crossed: MongoScalarComparison<Confidence<f32>> =
    TryFromFilter::try_from_filter(filter).expect("f32 holds a half");

  assert_eq!(crossed.gte(), Confidence::<f32>::new(0.5).as_ref());
  assert_eq!(
    rendered(&crossed, "score"),
    doc! { "score": { "$gte": 0.5 } }
  );
}