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 a binary column renders, and the two questions this backend answers with a refusal.
//!
//! The load-bearing test here is the first one, and it is DIFFERENTIAL: the ordering refusal rests
//! on a claim about two comparison rules rather than on anything visible in a filter document. A
//! `$gt` over a blob renders, is well-formed, and carries one BSON value — the defect it would
//! cover is entirely in which documents come back, and only the two orders side by side show it.

use core::{cmp::Ordering, convert::Infallible};

use bson::{Binary, Document, doc, spec::BinarySubtype};

use super::{MongoBytesComparison, MongoBytesCrossingError};
use crate::{
  At, BytesFilter, ComplexComparison, FieldName, FixedBytesFilter, Mongo, RecordAddress,
  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 `BinData` a `Vec<u8>` operand carries as, spelled through the same subtype the carrier
/// writes — so an assertion below is about the ROW reaching that subtype and not about two byte
/// lists having been typed alike.
fn blob(bytes: &[u8]) -> Binary {
  Binary {
    subtype: BinarySubtype::Generic,
    bytes: bytes.to_vec(),
  }
}

/// A blob column kept as lowercase hex TEXT — a crossing that changes the operand rather than only
/// its type, so a pass-through mutation shows in the operand and not only in the document.
fn hex(bytes: Vec<u8>) -> Result<String, Infallible> {
  Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
}

/// **The measurement the ordering refusal rests on**, written as the two rules side by side.
///
/// MongoDB compares `BinData` by length, then subtype, then bytes; every dialect in the SQL family
/// compares bytes and settles a prefix by length last. The subtype term is absent from the
/// reconstruction below because every blob this family writes carries the generic one — `carrier`
/// decides that once, for exactly this reason.
#[test]
fn the_two_binary_orders_agree_only_at_equal_length() {
  fn bytewise(a: &[u8], b: &[u8]) -> Ordering {
    a.cmp(b)
  }

  fn length_first(a: &[u8], b: &[u8]) -> Ordering {
    a.len().cmp(&b.len()).then_with(|| a.cmp(b))
  }

  // The pair the refusal is for: the shorter operand is the larger one bytewise, and the two rules
  // answer opposite ways about it.
  assert_eq!(bytewise(&[0xff], &[0x00, 0x00]), Ordering::Greater);
  assert_eq!(length_first(&[0xff], &[0x00, 0x00]), Ordering::Less);

  // At EQUAL width the length term separates nothing, so what is left is the bytewise comparison
  // itself — which is the whole of what a fixed-width column buys, over every pair of one-byte and
  // two-byte values there is.
  for a in 0..=u8::MAX {
    for b in 0..=u8::MAX {
      assert_eq!(bytewise(&[a], &[b]), length_first(&[a], &[b]));
      assert_eq!(bytewise(&[a, b], &[b, a]), length_first(&[a, b], &[b, a]));
    }
  }

  // At UNEQUAL width the length term decides alone, whatever the bytes say — so no choice of
  // operand recovers the agreement on a blob.
  for a in 0..=u8::MAX {
    assert_eq!(length_first(&[a], &[0x00, 0x00]), Ordering::Less);
  }
}

/// A FIXED-width column answers the four ordering operators, and the operands reach the document as
/// generic-subtype `BinData`.
#[test]
fn a_fixed_column_orders_over_the_bytes_it_was_given() {
  let comparison = MongoBytesComparison::<Vec<u8>>::try_from_filter(
    FixedBytesFilter::<[u8; 4], 4>::new()
      .with_gte([0x00, 0x00, 0x00, 0x01])
      .with_lt([0xff, 0xff, 0xff, 0xff]),
  )
  .expect("a fixed-width column answers the ordering operators");

  assert_eq!(comparison.conjuncts(), 2);
  assert_eq!(
    rendered(&comparison, "digest"),
    doc! {
      "digest": {
        "$gte": blob(&[0x00, 0x00, 0x00, 0x01]),
        "$lt": blob(&[0xff, 0xff, 0xff, 0xff]),
      }
    }
  );
}

/// A VARIABLE-width column keeps equality and membership, and both merge under one key exactly as
/// the scalar kind's do.
#[test]
fn a_variable_column_compares_and_enumerates() {
  let comparison = MongoBytesComparison::<Vec<u8>>::try_from_filter(
    BytesFilter::<Vec<u8>>::new()
      .with_eq(vec![0x89, 0x50])
      .with_ne(vec![0x00])
      .with_in_([vec![0xff], vec![0x00, 0x01]])
      .with_not_in([Vec::new()]),
  )
  .expect("a blob column answers equality and membership");

  assert_eq!(comparison.conjuncts(), 4);
  assert_eq!(
    rendered(&comparison, "payload"),
    doc! {
      "payload": {
        "$eq": blob(&[0x89, 0x50]),
        "$ne": blob(&[0x00]),
        "$in": [blob(&[0xff]), blob(&[0x00, 0x01])],
        "$nin": [blob(&[])],
      }
    }
  );
}

/// Each of the four ordering operators is refused on a blob, and the refusal names the one it
/// declined — so a filter setting several does not report the wrong operator.
#[test]
fn a_variable_column_refuses_every_ordering_operator() {
  let refused = [
    (BytesFilter::<Vec<u8>>::new().with_gt(vec![0x01]), "gt"),
    (BytesFilter::<Vec<u8>>::new().with_gte(vec![0x01]), "gte"),
    (BytesFilter::<Vec<u8>>::new().with_lt(vec![0x01]), "lt"),
    (BytesFilter::<Vec<u8>>::new().with_lte(vec![0x01]), "lte"),
  ];

  for (filter, operator) in refused {
    assert_eq!(
      MongoBytesComparison::<Vec<u8>>::try_from_filter(filter).unwrap_err(),
      MongoBytesCrossingError::VariableOrdering(operator)
    );
  }
}

/// The substring pair is refused wherever it can be WRITTEN, and after the byte kinds split there
/// is one such place: a blob.
///
/// That is where this family parts from the SQL one twice over. There, a blob answers `contains` and
/// a hash has no such field; here nothing answers it at any width, because MongoDB has no binary
/// substring form — so the refusal survives the split on the one kind that can still ask.
///
/// The fixed kind's half of this test is gone rather than passing: `with_contains` is not a method
/// on [`FixedBytesFilter`], so the state it asserted about is unconstructible (`E0599`) and the
/// assertion moved to the type.
#[test]
fn a_blob_is_refused_a_byte_substring() {
  assert_eq!(
    MongoBytesComparison::<Vec<u8>>::try_from_filter(
      BytesFilter::<Vec<u8>>::new().with_contains(vec![0x0d])
    )
    .unwrap_err(),
    MongoBytesCrossingError::Substring("contains")
  );
  assert_eq!(
    MongoBytesComparison::<Vec<u8>>::try_from_filter(
      BytesFilter::<Vec<u8>>::new().with_not_contains(vec![0x0d])
    )
    .unwrap_err(),
    MongoBytesCrossingError::Substring("not_contains")
  );
}

/// A crossing with a DECLARED converter replaces the operand with its stored form, and the storage
/// type carries as whatever its own row says — here a `String`, not `BinData`.
#[test]
fn a_crossing_replaces_the_operand_with_its_stored_form() {
  let comparison = MongoBytesComparison::<String>::try_from_filter_with(
    BytesFilter::<Vec<u8>>::new()
      .with_eq(vec![0x89, 0x50])
      .with_in_([vec![0xff], vec![0x00]]),
    hex,
  )
  .expect("the crossing into a hex column is total for equality and membership");

  assert_eq!(comparison.eq().map(String::as_str), Some("8950"));
  assert_eq!(
    rendered(&comparison, "payload"),
    doc! { "payload": { "$eq": "8950", "$in": ["ff", "00"] } }
  );
}

/// Both refusals are checked BEFORE the operands convert, so the error names the operator with no
/// answer rather than the conversion that would also have failed.
#[test]
fn the_refusals_are_checked_before_the_operands_convert() {
  /// A converter that refuses everything, so reaching it at all is visible in the error.
  fn refuse(_: Vec<u8>) -> Result<String, &'static str> {
    Err("the converter ran")
  }

  assert_eq!(
    MongoBytesComparison::<String>::try_from_filter_with(
      BytesFilter::<Vec<u8>>::new().with_contains(vec![0x0d]),
      refuse,
    )
    .unwrap_err(),
    MongoBytesCrossingError::Substring("contains")
  );
  assert_eq!(
    MongoBytesComparison::<String>::try_from_filter_with(
      BytesFilter::<Vec<u8>>::new().with_gt(vec![0x0d]),
      refuse,
    )
    .unwrap_err(),
    MongoBytesCrossingError::VariableOrdering("gt")
  );

  // And an operand the converter really does refuse reports the converter's own error, so the two
  // halves are told apart rather than collapsed.
  assert_eq!(
    MongoBytesComparison::<String>::try_from_filter_with(
      BytesFilter::<Vec<u8>>::new().with_eq(vec![0x0d]),
      refuse,
    )
    .unwrap_err(),
    MongoBytesCrossingError::Operand("the converter ran")
  );
}

/// **THE TWO KINDS' IDENTITY CROSSINGS HAVE DIFFERENT ERROR TYPES, AND THE ANNOTATIONS ARE THE
/// ASSERTION.**
///
/// A blob's is `MongoBytesCrossingError<Infallible>`, which still has inhabited variants because
/// neither refusal has anything to do with converting. A fixed-width column's is the CONVERTER's
/// error bare — at `Infallible` a crossing that provably cannot fail, which is the honesty the SQL
/// family gained for both kinds and this one gains for the fixed kind alone.
#[test]
fn the_blob_keeps_a_refusal_and_the_fixed_kind_has_none_left() {
  let variable: Result<MongoBytesComparison<Vec<u8>>, MongoBytesCrossingError<Infallible>> =
    MongoBytesComparison::try_from_filter(BytesFilter::<Vec<u8>>::new().with_lte(vec![0x0d]));
  assert_eq!(
    variable.unwrap_err(),
    MongoBytesCrossingError::VariableOrdering("lte")
  );

  let fixed: Result<MongoBytesComparison<Vec<u8>>, Infallible> =
    MongoBytesComparison::try_from_filter(
      FixedBytesFilter::<[u8; 4], 4>::new().with_lte([0x0d, 0x0a, 0x0d, 0x0a]),
    );
  assert_eq!(fixed.unwrap().conjuncts(), 1);
}

/// The projection an expansion writes for a blob 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.
///
/// Both KINDS reach the SAME comparison type, which is the width's absence from a storage side
/// stated as a property rather than as a note: nothing downstream of a crossing reads one.
#[test]
fn the_codegen_projection_resolves_for_a_bytes_field_of_either_shape() {
  type Blob = <BytesFilter<Vec<u8>> as ToDatabaseComparison<Vec<u8>, Mongo>>::Comparison;
  type Hash = <FixedBytesFilter<[u8; 4], 4> as ToDatabaseComparison<Vec<u8>, Mongo>>::Comparison;

  let blob: Blob = MongoBytesComparison::<Vec<u8>>::new();
  let hash: Hash = MongoBytesComparison::<Vec<u8>>::new();
  assert!(blob.is_empty());
  assert_eq!(blob, hash);
}