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 each row stores, and the one row whose obvious spelling would have been wrong.

use bson::Bson;

use super::MongoCarrier;
use crate::{BeI128, BeU64, BeU128, Count, Score};

/// Every row's BSON arm, written out — the table in the module note, as a compilation rather than
/// as prose. The widths that share an arm are the assertion: BSON has one 32-bit integer, one
/// 64-bit integer and one float, so eight Rust widths land on three arms.
#[test]
fn each_width_carries_the_arm_the_table_names() {
  assert_eq!(true.to_bson(), Bson::Boolean(true));
  assert_eq!((-1_i8).to_bson(), Bson::Int32(-1));
  assert_eq!((-1_i16).to_bson(), Bson::Int32(-1));
  assert_eq!((-1_i32).to_bson(), Bson::Int32(-1));
  assert_eq!((-1_i64).to_bson(), Bson::Int64(-1));
  assert_eq!(1_u8.to_bson(), Bson::Int32(1));
  assert_eq!(1_u16.to_bson(), Bson::Int32(1));
  assert_eq!(0.5_f32.to_bson(), Bson::Double(0.5));
  assert_eq!(0.5_f64.to_bson(), Bson::Double(0.5));
  assert_eq!(String::from("v").to_bson(), Bson::String(String::from("v")));
  assert_eq!(Score::ONE.to_bson(), Bson::Double(1.0));
}

/// **The row that had to be measured.** bson's serde serializer writes every `u32` as `Int64`,
/// while `impl From<u32> for Bson` NARROWS to `Int32` when the value fits — so `Bson::from(*self)`
/// would give a small `u32` one BSON type in the filter and another in the stored document, which
/// the filter cannot show and an index scan can.
///
/// The second assertion is the mutation pin: it holds only while this row writes the arm rather
/// than delegating.
#[test]
fn a_small_u32_carries_as_int64_and_not_as_the_from_impl_would() {
  assert_eq!(1_u32.to_bson(), Bson::Int64(1));
  assert_ne!(1_u32.to_bson(), Bson::from(1_u32));
}

/// **THE CARDINALITY IS AN `Int64`, THROUGH THE TYPE'S OWN CODEC** — the same
/// [`Count::to_signed`](crate::Count::to_signed) the SQL family's SQLite and PostgreSQL rows call,
/// so one function produces the value whichever backend a filter is lowered for.
///
/// The saturating arm is read here too, and it is the same unreachable one: a cardinality counts
/// rows that EXIST, so nothing that this framework folds can reach it. What the assertion pins is
/// that the row SATURATES rather than wrapping into a negative `Int64` — which is exactly the
/// failure `legacy/ingraph`'s own `u64` row had, and which the module note records as the divergence
/// a missing row moved to the declaration.
#[test]
fn a_cardinality_carries_as_int64_through_its_own_codec() {
  assert_eq!(Count::new(0).to_bson(), Bson::Int64(0));
  assert_eq!(Count::new(42).to_bson(), Bson::Int64(42));
  assert_eq!(
    Count::new(i64::MAX.unsigned_abs()).to_bson(),
    Bson::Int64(i64::MAX)
  );
  assert_eq!(Count::new(u64::MAX).to_bson(), Bson::Int64(i64::MAX));
}

/// A blob is a GENERIC binary — subtype 0 — rather than any of BSON's special subtypes, which name
/// things a `Vec<u8>` field is not.
#[test]
fn a_blob_carries_as_generic_binary() {
  let Bson::Binary(binary) = vec![1_u8, 2, 3].to_bson() else {
    panic!("a blob carries as binary");
  };
  assert_eq!(binary.subtype, bson::spec::BinarySubtype::Generic);
  assert_eq!(binary.bytes, [1, 2, 3]);
}

/// **A UUID IS THE ONE ROW THAT IS NOT SUBTYPE 0** — BSON named this case, and the row writes the
/// name rather than falling in with the blobs beside it.
///
/// Three claims, and the last is the load-bearing one. The SUBTYPE is `Uuid` (4); the BYTES are the
/// value's own sixteen, in its own order and never the hyphenated rendering; and the ORDER over two
/// of them is `Uuid`'s own `Ord`, which is what makes a cursor page over a uuid column correct here
/// as well as on the three SQL dialects. BSON ranks `BinData` by length, then subtype, then bytes —
/// every uuid shares the first two, so the comparison reduces to the bytewise one, and that is the
/// same reduction the big-endian rows below rely on.
#[test]
fn a_uuid_carries_as_bindata_subtype_four() {
  fn binary(value: Bson) -> bson::Binary {
    let Bson::Binary(binary) = value else {
      panic!("a uuid carries as binary");
    };
    binary
  }

  let low = uuid::Uuid::from_bytes([0x01; 16]);
  let high = uuid::Uuid::from_bytes([0x02; 16]);

  assert_eq!(
    binary(low.to_bson()).subtype,
    bson::spec::BinarySubtype::Uuid
  );
  assert_ne!(
    binary(low.to_bson()).subtype,
    bson::spec::BinarySubtype::Generic,
    "a uuid is not a nameless blob"
  );
  assert_eq!(binary(low.to_bson()).bytes, low.as_bytes());
  assert_eq!(
    binary(low.to_bson()).bytes.len(),
    16,
    "and never the 36 text"
  );

  assert!(low < high, "the Rust order");
  assert!(
    binary(low.to_bson()).bytes < binary(high.to_bson()).bytes,
    "and the stored order, which is the same order"
  );
}

/// The three widths BSON has no integer for reach a column as the carrier's own blob, and the
/// assertion is the BYTES rather than the arm: a row that had spelled its own `to_be_bytes` renders
/// the same `Binary` and is what this exists to catch.
///
/// The right-hand sides are the single encoding authority, which is the same call the SQL family's
/// `Encode` row makes — so a `BeU64` column holds the same eight bytes whichever backend wrote it,
/// by construction and not by two tests agreeing.
#[test]
fn a_wide_integer_carries_the_bytes_its_carrier_encodes() {
  fn bytes(value: Bson) -> Vec<u8> {
    let Bson::Binary(binary) = value else {
      panic!("a big-endian carrier carries as binary");
    };
    assert_eq!(binary.subtype, bson::spec::BinarySubtype::Generic);
    binary.bytes
  }

  assert_eq!(bytes(BeU64(1).to_bson()), BeU64(1).to_blob());
  assert_eq!(bytes(BeU128(1).to_bson()), BeU128(1).to_blob());
  assert_eq!(bytes(BeI128(-1).to_bson()), BeI128(-1).to_blob());

  // The stored order is BIG-endian, which is the whole reason these types exist: the little-endian
  // spelling renders an equally well-formed `BinData` that an index ranks wrongly, and MongoDB
  // compares equal-length equal-subtype blobs bytewise.
  assert_eq!(bytes(BeU64(1).to_bson()), [0, 0, 0, 0, 0, 0, 0, 1]);
  assert!(bytes(BeU64(1).to_bson()) < bytes(BeU64(256).to_bson()));
}

/// A borrowed operand carries exactly as the owned one does, which is what makes a comparison over
/// `&V` a real type rather than an aspiration.
///
/// The BOUND is the assertion and the generic is what discharges it: `owned.to_bson()` through an
/// `&i64` resolves by auto-deref whether or not the blanket exists, so a call at the method syntax
/// would prove nothing.
#[test]
fn a_borrowed_operand_carries_as_its_referent() {
  fn carried<V: MongoCarrier>(value: V) -> Bson {
    value.to_bson()
  }

  let owned = 7_i64;
  let borrowed: &i64 = &owned;
  assert_eq!(carried(borrowed), carried(owned));
}

/// **The framework's own instant, as the two flat integers the licence sentence admits.**
///
/// A sub-document of `secs` and `nanos`, and the assertion is the BSON ARMS as much as the values:
/// `Int64` for the seconds and `Int32` for the fraction, which is what "no BSON date type is
/// involved" means concretely. `UtcDateTime` — the arm `Temporal<time::OffsetDateTime>` would have
/// taken — carries milliseconds, and that is the row this table deliberately does not have.
#[test]
fn an_instant_carries_as_two_flat_integers() {
  use crate::Timestamp;

  let at: Timestamp = "2026-08-09T21:14:03.123456789Z".parse().unwrap();
  let Bson::Document(carried) = at.to_bson() else {
    panic!("an instant carries as a sub-document");
  };

  assert_eq!(carried.get("secs"), Some(&Bson::Int64(1_786_310_043)));
  assert_eq!(carried.get("nanos"), Some(&Bson::Int32(123_456_789)));
  assert_eq!(carried.len(), 2, "and nothing else is in it");

  // The nine digits SURVIVE, which is the whole of the licence: the millisecond truncation that
  // refuses the temporal wrapper has nothing to truncate here.
  assert_ne!(carried.get("nanos"), Some(&Bson::Int32(123_000_000)));

  // A pre-epoch instant carries BOTH halves negative — jiff's own pairing, kept rather than
  // rebased, so the sub-document's field order is the instant's own order.
  let before: Timestamp = "1969-12-31T23:59:58.5Z".parse().unwrap();
  let Bson::Document(carried) = before.to_bson() else {
    panic!("an instant carries as a sub-document");
  };
  assert_eq!(carried.get("secs"), Some(&Bson::Int64(-1)));
  assert_eq!(carried.get("nanos"), Some(&Bson::Int32(-500_000_000)));
}

/// **A PATTERN CARRIES AS A `String` AND NEVER AS BSON'S OWN `RegularExpression`** — the row's
/// refusal, asserted rather than only argued.
///
/// The arm matters because the wrong one is the plausible one: a `Bson::RegularExpression` would
/// make MongoDB MATCH stored text against the value, where every other backend compares the pattern
/// AS text. Pinned so that a later hand cannot "improve" the row into the type BSON happens to have.
///
/// The absent case rides beside it because a watch's pattern is an `Option`, and the optional row's
/// own rule — write the key, carrying `Null` — is what makes a `Some` that became a `None` come back
/// holding `null` rather than come back missing.
#[cfg(feature = "regex")]
#[test]
fn a_pattern_carries_as_its_text_and_not_as_a_bson_regex() {
  let pattern = regex::Regex::new("^[a-z]+(?:-[0-9]+)?$").expect("a pattern");
  assert_eq!(
    pattern.to_bson(),
    Bson::String(String::from("^[a-z]+(?:-[0-9]+)?$"))
  );
  assert!(
    !matches!(pattern.to_bson(), Bson::RegularExpression(_)),
    "the operator arm is refused: this column holds a pattern as a VALUE"
  );

  assert_eq!(
    Some(pattern).to_bson(),
    Bson::String(String::from("^[a-z]+(?:-[0-9]+)?$"))
  );
  assert_eq!(None::<regex::Regex>.to_bson(), Bson::Null);
}