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 four columns, read as the three facts a stored composite states: the WIDTH, the DECODE and
//! the CURSOR.
//!
//! The SQL BIND is the fourth and it is not here — a bind renders SQL, so what proves it is an engine
//! taking the statement, which `tests/language_id_citizen.rs` is. What can be asserted without one
//! is that the width and the decode agree with each other and with the type's own door.
//!
//! The DOCUMENT form is the fifth and it IS here, and the difference is that a BSON value is a value:
//! it needs no engine to be looked at, so the shape the register decided is asserted where it was
//! decided.
//!
//! # Each assertion rides the gate its SUBJECT rides, and three of them ride `sqlx`
//!
//! The decode's own function is `#[cfg(feature = "sqlx")]` — a build with no SQL family has no row to
//! decode, which its module note argues — so the four tests that call it carry the same word. Without
//! it they were an `E0432` on the import in every build that declares the family and declines the SQL
//! one, which `--no-default-features --features derive` is and the matrix runs.
//!
//! The width, the cursor and the document form name no dialect and carry no gate, which is the half
//! worth keeping: they are checked in every lane that compiles this crate at all.

use crate::{ColumnKind, ColumnShape, CursorValue, width};

#[cfg(feature = "sqlx")]
use super::assembled;
use super::{LANGUAGE, REGION, REST, SCRIPT, SEGMENTS};
use crate::primitives::lang::LanguageId;

/// One tag the door must take, unwrapped.
fn admitted(sent: &str) -> LanguageId {
  LanguageId::new(sent).unwrap_or_else(|refused| panic!("`{sent}` is a language tag: {refused}"))
}

/// **FOUR columns, in the seats' own order**, and the width the holder's `INSERT` list reads.
#[test]
fn the_width_is_four_plain_columns_named_for_the_seats() {
  assert_eq!(SEGMENTS.len(), 4);
  assert_eq!(<LanguageId as ColumnKind>::SEGMENTS, SEGMENTS);
  assert_eq!(width(SEGMENTS), 4);

  let names: Vec<&str> = SEGMENTS
    .iter()
    .map(|segment| {
      segment
        .field()
        .expect("a plain column names its field")
        .stored()
        .as_str()
    })
    .collect();

  assert_eq!(names, ["language", "script", "region", "rest"]);

  // Plain, not composite: no seat is itself a multi-column type, so nothing nests.
  assert!(
    SEGMENTS
      .iter()
      .all(|segment| matches!(segment, ColumnShape::Plain(_))),
  );

  // The constants the comparison addresses by are the same four, read from here rather than
  // respelled — a rename moves the width, the bind, the decode and every predicate together.
  assert_eq!(LANGUAGE.as_str(), "language");
  assert_eq!(SCRIPT.as_str(), "script");
  assert_eq!(REGION.as_str(), "region");
  assert_eq!(REST.as_str(), "rest");
}

/// **THE DECODE GOES BACK THROUGH THE DOOR**, so four columns become an identity by the same rules
/// a tag does.
#[cfg(feature = "sqlx")]
#[test]
fn four_columns_assemble_into_the_identity_they_came_from() {
  for tag in [
    "de",
    "de-DE",
    "zh-Hans",
    "sr-Cyrl-RS",
    "en-US-x-Foo",
    "zh-yue-Hant-HK",
  ] {
    let held = admitted(tag);

    let round_tripped = assembled(
      held.language().as_str(),
      held.script().map(|script| script.as_str()),
      held.region().map(|region| region.as_str()),
      held.rest().map(|rest| rest.as_str()),
    )
    .expect("the columns a write path produced");

    assert_eq!(round_tripped, held, "`{tag}`");
  }
}

/// **THE DECODE CANONICALISES**, which is what a row written by something that is not this crate
/// needs.
///
/// A muxer's `GER` in the language column and a `Latn` in the script column read back as `de` with
/// no script at all — the alpha-3 fold and the suppression, applied on the way IN rather than
/// trusted to have happened on the way out.
#[cfg(feature = "sqlx")]
#[test]
fn columns_written_by_somebody_else_read_back_canonical() {
  let foreign = assembled("GER", Some("latn"), Some("de"), None).expect("a decode");

  assert_eq!(foreign, admitted("de-DE"));
  assert_eq!(
    foreign.script(),
    None,
    "the suppression fired at the decode"
  );
}

/// **A COLUMN THAT DOES NOT NAME ITS SUBTAG IS A DECODE ERROR**, rather than a value whose type says
/// it cannot exist.
#[cfg(feature = "sqlx")]
#[test]
fn a_column_holding_something_else_refuses_to_decode() {
  assert!(assembled("!!", None, None, None).is_err());
  assert!(assembled("", None, None, None).is_err());
  assert!(assembled("de", Some("Latin"), None, None).is_err());
  assert!(assembled("de", None, Some("DEU"), None).is_err());
  assert!(assembled("de", None, None, Some("x-!!")).is_err());

  // …and a script column holding something the SUPPRESSION would remove is not an error at all: it
  // is the same value the write path would have produced, arrived at from the other direction.
  assert_eq!(
    assembled("en", Some("Latn"), None, None).expect("a decode"),
    admitted("en")
  );
}

/// **A COLUMN'S SEAT IS THE COLUMN'S**, which is what reading each one through its OWN door buys and
/// what a rebuilt tag would have thrown away.
///
/// The tag parser is POSITIONAL — it reads a subtag's seat off its shape — so spelling four columns
/// back into a tag and re-reading it would let a garbage column land in a seat it did not come from.
/// Both rows below are that failure, measured:
///
/// * a `script` column holding `US` rebuilds as `de-US`, which a tag parser reads as a REGION;
/// * a `script` column holding `Latin` rebuilds as `de-Latin`, five alphanumeric characters, which
///   rides the TAIL.
///
/// Neither reaches a value here. The first is refused because `US` is not four letters, and the
/// second because `Latin` is not either.
#[cfg(feature = "sqlx")]
#[test]
fn a_garbage_column_cannot_land_in_a_seat_it_did_not_come_from() {
  assert!(
    assembled("de", Some("US"), None, None).is_err(),
    "a rebuilt tag would have read this as a region"
  );
  assert!(
    assembled("de", Some("Latin"), None, None).is_err(),
    "a rebuilt tag would have carried this as a variant"
  );

  // The seat a value DID come from is kept, which is the same property from the other side: a
  // region column holding `US` is a region, whatever the script column holds.
  let held = assembled("de", Some("Latn"), Some("US"), None).expect("a decode");
  assert_eq!(held.region().map(|region| region.as_str()), Some("US"));
  assert_eq!(held.script(), None, "German implies Latin");
}

/// **THE CURSOR IS THE CANONICAL TAG**, self-delimiting because the grammar has separators — which
/// is what lets four variable-width columns share one cursor slot with no framing of this row's own.
#[test]
fn the_keyset_position_round_trips_and_refuses_a_forgery() {
  for tag in ["de", "zh-Hans-CN", "en-US-x-Foo", "sr-Cyrl-RS"] {
    let held = admitted(tag);
    let mut position = Vec::new();
    held.write_cursor(&mut position);

    assert_eq!(position, tag.as_bytes(), "`{tag}`");
    assert_eq!(LanguageId::read_cursor(&position), Some(held), "`{tag}`");
  }

  // The CANONICAL tag and not the one that was sent, which is what keeps a page's boundary
  // comparable with the columns it is bound against.
  let folded = admitted("GER-latn-de");
  let mut position = Vec::new();
  folded.write_cursor(&mut position);
  assert_eq!(position, b"de-DE");

  assert_eq!(
    LanguageId::read_cursor(b"en--US"),
    None,
    "a forged position"
  );
  assert_eq!(LanguageId::read_cursor(b""), None);
  assert_eq!(LanguageId::read_cursor(&[0xff]), None, "not even UTF-8");
}

/// **THE DOCUMENT IS A SUB-DOCUMENT OF THE FOUR SEGMENTS, WITH EVERY KEY WRITTEN** — the shape the
/// carrier's own note decides, asserted as a compilation rather than as prose.
///
/// Three claims, and the last is the one that would be silent if it broke:
///
/// * the KEYS are the four `SEGMENTS` names, in that order, and there is nothing else in the
///   document;
/// * a filled seat holds the CANONICAL text, so an mkv's `GER-latn-de` reaches the same document a
///   `de-DE` tag does;
/// * an absent seat holds `Null` and is NOT left out — which is what makes a whole-identity document
///   comparison well defined, since BSON compares two documents by their keys in the order written.
#[cfg(feature = "mongo")]
#[test]
fn an_identity_carries_as_a_sub_document_of_its_four_seats() {
  use crate::MongoCarrier;
  use bson::Bson;

  let bson::Bson::Document(carried) = admitted("zh-Hans-CN").to_bson() else {
    panic!("an identity carries as a sub-document");
  };

  let keys: Vec<&str> = carried.keys().map(String::as_str).collect();
  assert_eq!(
    keys,
    [
      LANGUAGE.as_str(),
      SCRIPT.as_str(),
      REGION.as_str(),
      REST.as_str()
    ],
    "the four segments, in the seats' own order and nothing beside them",
  );
  assert_eq!(carried.get(LANGUAGE.as_str()), Some(&Bson::from("zh")));
  assert_eq!(carried.get(SCRIPT.as_str()), Some(&Bson::from("Hans")));
  assert_eq!(carried.get(REGION.as_str()), Some(&Bson::from("CN")));
  assert_eq!(carried.get(REST.as_str()), Some(&Bson::Null));

  // The FOLD reaches the document, exactly as it reaches the columns and the cursor: an mkv's
  // spelling and an mp4's are one value before either is written anywhere.
  assert_eq!(
    admitted("GER-latn-de").to_bson(),
    admitted("de-DE").to_bson()
  );

  // An identity with THREE empty seats still writes four keys. A carrier that left them out would
  // render a document a whole-identity `$eq` could not match against one that did not, and nothing
  // in either filter would show the difference.
  let bson::Bson::Document(bare) = admitted("de").to_bson() else {
    panic!("an identity carries as a sub-document");
  };
  assert_eq!(bare.len(), 4, "four keys, however few seats are filled");
  for absent in [SCRIPT, REGION, REST] {
    let absent = absent.as_str();
    assert_eq!(bare.get(absent), Some(&Bson::Null), "{absent}");
  }

  // The TAIL is carried verbatim, as it is everywhere else this value is written: a private-use
  // sequence's case is the private party's and this row does not fold it.
  let bson::Bson::Document(tailed) = admitted("en-US-x-Foo").to_bson() else {
    panic!("an identity carries as a sub-document");
  };
  assert_eq!(tailed.get(REST.as_str()), Some(&Bson::from("x-Foo")));
}

/// **THE READ IS THE WRITE'S MIRROR** — an identity written as a sub-document reads back as the
/// value that wrote it, seat by seat, through EACH seat's own door rather than a rebuilt tag.
#[cfg(feature = "mongo")]
#[test]
fn an_identity_reads_back_the_document_it_carried_as() {
  use crate::{MongoCarrier, query::mongo::MongoExtract};

  for tag in [
    "de",
    "de-DE",
    "zh-Hans",
    "zh-Hans-CN",
    "sr-Cyrl-RS",
    "en-US-x-Foo",
    "zh-yue-Hant-HK",
  ] {
    let held = admitted(tag);
    let written = held.to_bson();
    assert_eq!(LanguageId::extract(Some(&written)), Ok(held), "`{tag}`");
  }
}

/// **THE LANGUAGE KEY: MISSING OR `null` IS ONE REFUSAL**, mirroring
/// [`LanguageIdColumnError::NoLanguage`] — the seat that has no `Option` in its own type, so a
/// document that does not fill it is refused rather than read as an absent identity.
///
/// The `Option<LanguageId>` blanket is the field's own absence — a track nobody tagged. This is the
/// narrower question: a document that IS present, at the right BSON type, and still does not name a
/// language.
#[cfg(feature = "mongo")]
#[test]
fn a_missing_or_null_language_key_is_one_named_refusal() {
  use crate::query::mongo::{MongoExtract, MongoTypeError};
  use bson::doc;

  let missing = doc! { "script": "Hans", "region": "CN", "rest": bson::Bson::Null };
  let null = doc! {
    "language": bson::Bson::Null, "script": "Hans", "region": "CN", "rest": bson::Bson::Null
  };

  let refusal = LanguageId::extract(Some(&missing.into()));
  assert!(
    matches!(refusal, Err(MongoTypeError::Range(_))),
    "a missing language key: {refusal:?}"
  );
  assert_eq!(
    refusal,
    LanguageId::extract(Some(&null.into())),
    "a missing key and an explicit null name the SAME refusal for this seat",
  );
}

/// **THE THREE OPTIONAL SEATS: MISSING OR `null` IS ONE ANSWER, `None`** — the general law this
/// vocabulary reads every optional field under, applied here through `Option<T>`'s own blanket
/// rather than a rule of this composite's.
#[cfg(feature = "mongo")]
#[test]
fn a_missing_optional_seat_and_an_explicit_null_both_read_as_absent() {
  use crate::query::mongo::MongoExtract;
  use bson::doc;

  let missing_script =
    doc! { "language": "de", "region": bson::Bson::Null, "rest": bson::Bson::Null };
  let null_script = doc! {
    "language": "de", "script": bson::Bson::Null, "region": bson::Bson::Null,
    "rest": bson::Bson::Null
  };

  let from_missing = LanguageId::extract(Some(&missing_script.into())).expect("a bare `de`");
  let from_null = LanguageId::extract(Some(&null_script.into())).expect("a bare `de`");

  assert_eq!(from_missing, admitted("de"));
  assert_eq!(
    from_missing, from_null,
    "a missing key and an explicit null are one answer"
  );
  assert_eq!(from_missing.script(), None);
}

/// **A WRONG BSON TYPE AT A SEAT IS A REFUSAL NAMING WHAT WAS FOUND** — the alias
/// [`document_seats`] reaches through the widened `query::mongo::alias`, so a `script` key holding
/// an `int` is named as one rather than folded into a generic "not a string".
#[cfg(feature = "mongo")]
#[test]
fn a_wrong_bson_type_at_a_seat_is_named() {
  use crate::query::mongo::{MongoExtract, MongoTypeError};
  use bson::doc;

  let document = doc! {
    "language": "de", "script": 4i32, "region": bson::Bson::Null, "rest": bson::Bson::Null
  };

  assert_eq!(
    LanguageId::extract(Some(&document.into())),
    Err(MongoTypeError::wrong_type("string", "int"))
  );

  // The whole field, at the wrong BSON type entirely — the outer presence-and-type check
  // `document_seats` does not itself make.
  assert_eq!(
    LanguageId::extract(Some(&bson::Bson::String(String::from("de")))),
    Err(MongoTypeError::wrong_type("object", "string"))
  );
  assert_eq!(LanguageId::extract(None), Err(MongoTypeError::Absent));
}

/// **A HAND-WRITTEN DOCUMENT FOLDS AT THE READ DOOR**, mirroring
/// `columns_written_by_somebody_else_read_back_canonical`'s SQL claim on the other backend: each
/// seat re-validates through its own type, so the suppression still fires and a muxer's alpha-3
/// spelling reads back canonical.
#[cfg(feature = "mongo")]
#[test]
fn a_hand_written_document_folds_at_the_read_door_too() {
  use crate::query::mongo::MongoExtract;
  use bson::doc;

  let foreign = doc! {
    "language": "GER", "script": "latn", "region": "de", "rest": bson::Bson::Null
  };

  let read = LanguageId::extract(Some(&foreign.into())).expect("a decode");
  assert_eq!(read, admitted("de-DE"));
  assert_eq!(read.script(), None, "the suppression fired at the read");
}

/// **A TAIL SUBTAG THAT DOES NOT FIT THE ENVELOPE IS REFUSED**, mirroring
/// `a_garbage_column_cannot_land_in_a_seat_it_did_not_come_from`'s SQL claim: the tail is held
/// VERBATIM and still re-validated against its own loose grammar on the way in.
#[cfg(feature = "mongo")]
#[test]
fn a_malformed_tail_is_refused_rather_than_carried() {
  use crate::query::mongo::{MongoExtract, MongoTypeError};
  use bson::doc;

  let document = doc! {
    "language": "en", "script": bson::Bson::Null, "region": bson::Bson::Null, "rest": "x-!!"
  };

  assert!(matches!(
    LanguageId::extract(Some(&document.into())),
    Err(MongoTypeError::Range(_))
  ));
}