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 CROSSING — where a filter's domain operands become four columns' storage values, and where
//! the one refusal this comparison has is made.
//!
//! What is asserted here is the shape a filter crosses INTO. What that shape renders, and what an
//! engine returns for it, is `tests/language_id_citizen.rs`: a conjunct count is exactly what a
//! wrong lowering keeps while writing the wrong text.

use crate::{ComplexComparison, Nullable, ScalarFilter, TryFromFilter};
use sqlx::Sqlite;

use super::{LanguageIdCrossingError, SqlLanguageIdComparison};
use crate::primitives::lang::{Language, LanguageId, LanguageIdFilter, Region, ScriptSubtag};

/// The comparison a filter crosses into, for the one dialect this crate compiles a driver for.
type Crossed = SqlLanguageIdComparison<Sqlite>;

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

/// One filter through the crossing, unwrapped.
fn crossed(filter: LanguageIdFilter) -> Crossed {
  Crossed::try_from_filter(filter).expect("the crossing")
}

/// **AN EMPTY FILTER OPENS NO CONJUNCT**, so a lowering emits nothing at all for the field.
#[test]
fn an_empty_filter_crosses_to_an_empty_comparison() {
  let empty = LanguageIdFilter::new();
  assert!(empty.is_empty());

  let comparison = crossed(empty);
  assert_eq!(ComplexComparison::<Sqlite>::conjuncts(&comparison), 0);
  assert_eq!(comparison.members(), None);
  assert_eq!(comparison.excluded(), None);
}

/// **A WHOLE-IDENTITY `eq` DECOMPOSES ONTO ALL FOUR COLUMNS**, and the absent seats become NULL
/// TESTS rather than equalities against `NULL`.
///
/// The pin for the module's central claim. `de` constrains four columns: one equality and three
/// `IS NULL`s — because an identity with no script is one whose script COLUMN is null, and a row
/// that only checked the language would also match `de-DE`.
#[test]
fn a_whole_equality_reaches_every_seat_including_the_absent_ones() {
  let comparison = crossed(LanguageIdFilter::new().with_eq(tag("de")));

  assert_eq!(comparison.language().eq().map(String::as_str), Some("de"));
  assert_eq!(comparison.script().null(), Some(true));
  assert_eq!(comparison.region().null(), Some(true));
  assert_eq!(comparison.rest().null(), Some(true));
  assert_eq!(ComplexComparison::<Sqlite>::conjuncts(&comparison), 4);

  // …and a filled seat is an EQUALITY rather than a null test, on the same four columns.
  let comparison = crossed(LanguageIdFilter::new().with_eq(tag("zh-Hans-CN")));
  assert_eq!(comparison.language().eq().map(String::as_str), Some("zh"));
  assert_eq!(
    comparison.script().inner().eq().map(String::as_str),
    Some("Hans")
  );
  assert_eq!(
    comparison.region().inner().eq().map(String::as_str),
    Some("CN")
  );
  assert_eq!(comparison.script().null(), None);
  assert_eq!(comparison.rest().null(), Some(true));
  assert_eq!(ComplexComparison::<Sqlite>::conjuncts(&comparison), 4);
}

/// **THE TAIL IS CONSTRAINED BY THE IDENTITY AXIS AND BY NOTHING ELSE.**
///
/// The filter has no tail slot, so this column is filled only here — and it has to be, or a
/// whole-identity equality would not be an equality: `en-US` would match `en-US-x-Foo`.
#[test]
fn the_identity_axis_is_what_fills_the_tail_column() {
  let bare = crossed(LanguageIdFilter::new().with_eq(tag("en-US")));
  assert_eq!(bare.rest().null(), Some(true));

  let tailed = crossed(LanguageIdFilter::new().with_eq(tag("en-US-x-Foo")));
  assert_eq!(tailed.rest().null(), None);
  assert_eq!(
    tailed.rest().inner().eq().map(String::as_str),
    Some("x-Foo"),
    "verbatim, case included"
  );
}

/// **THE COMPONENT FACETS LOWER PER COLUMN**, which is what makes *all Chinese* one predicate over
/// one column.
#[test]
fn a_component_filter_reaches_its_own_column_and_no_other() {
  let chinese = LanguageIdFilter::new()
    .with_language(ScalarFilter::new().with_eq(Language::new("zh").expect("a language")));
  let comparison = crossed(chinese);

  assert_eq!(comparison.language().eq().map(String::as_str), Some("zh"));
  assert_eq!(ComplexComparison::<Sqlite>::conjuncts(&comparison), 1);
  assert_eq!(
    comparison.script().null(),
    None,
    "nothing was said about it"
  );
  assert_eq!(comparison.rest().null(), None);

  // The script's NULL TEST is the *no script was declared* question, and it is one conjunct.
  let undeclared =
    LanguageIdFilter::new().with_script(Nullable::new(ScalarFilter::new()).with_null(true));
  let comparison = crossed(undeclared);
  assert_eq!(comparison.script().null(), Some(true));
  assert_eq!(ComplexComparison::<Sqlite>::conjuncts(&comparison), 1);

  // …and the two AND together, as every pair of slots on a filter does.
  let both = LanguageIdFilter::new()
    .with_language(ScalarFilter::new().with_eq(Language::new("zh").expect("a language")))
    .with_script(Nullable::new(ScalarFilter::new()).with_null(true));
  assert_eq!(ComplexComparison::<Sqlite>::conjuncts(&crossed(both)), 2);
}

/// **A MEMBERSHIP IS ONE CONJUNCT** however many identities it holds, because the whole disjunction
/// is bracketed.
#[test]
fn a_membership_is_one_conjunct_whatever_its_width() {
  for width in [0usize, 1, 2, 8] {
    let operands: Vec<LanguageId> = ["de", "zh-Hans", "en-US", "fr", "ja", "ko", "it", "pt"]
      .iter()
      .take(width)
      .map(|sent| tag(sent))
      .collect();

    let comparison = crossed(LanguageIdFilter::new().with_in_(operands));
    assert_eq!(comparison.members(), Some(width));
    assert_eq!(
      ComplexComparison::<Sqlite>::conjuncts(&comparison),
      1,
      "width {width}"
    );
  }
}

/// **`ne` AND `notIn` ARE ONE SET**, De Morgan having made them one question.
#[test]
fn the_two_exclusions_merge_into_one_predicate() {
  let single = crossed(LanguageIdFilter::new().with_ne(tag("de")));
  assert_eq!(single.excluded(), Some(1));
  assert_eq!(ComplexComparison::<Sqlite>::conjuncts(&single), 1);

  let list = crossed(LanguageIdFilter::new().with_not_in(vec![tag("de"), tag("fr")]));
  assert_eq!(list.excluded(), Some(2));

  let both = crossed(
    LanguageIdFilter::new()
      .with_ne(tag("ja"))
      .with_not_in(vec![tag("de"), tag("fr")]),
  );
  assert_eq!(both.excluded(), Some(3), "the union, in one predicate");
  assert_eq!(ComplexComparison::<Sqlite>::conjuncts(&both), 1);
}

/// **AN INCLUSION AND AN EXCLUSION ARE TWO CONJUNCTS**, so they narrow one another rather than
/// merging.
#[test]
fn an_inclusion_and_an_exclusion_are_separate_conjuncts() {
  let comparison = crossed(
    LanguageIdFilter::new()
      .with_in_(vec![tag("de"), tag("fr")])
      .with_not_in(vec![tag("fr")]),
  );

  assert_eq!(comparison.members(), Some(2));
  assert_eq!(comparison.excluded(), Some(1));
  assert_eq!(ComplexComparison::<Sqlite>::conjuncts(&comparison), 2);
}

/// **THE ONE REFUSAL IS THE DOUBLED EQUALITY**, once per column that can be named twice.
///
/// A whole-identity `eq` fills each column's own equality, and a column has one. Assigning over the
/// top would silently keep whichever was written last, which is the failure with no error and no
/// wrong value to look at.
#[test]
fn naming_one_columns_value_twice_is_refused_by_name() {
  let language = LanguageIdFilter::new()
    .with_eq(tag("de-DE"))
    .with_language(ScalarFilter::new().with_eq(Language::new("de").expect("a language")));
  assert_eq!(
    Crossed::try_from_filter(language),
    Err(LanguageIdCrossingError::LanguageConflict)
  );

  let script = LanguageIdFilter::new()
    .with_eq(tag("zh-Hans"))
    .with_script(Nullable::new(
      ScalarFilter::new().with_eq(ScriptSubtag::new("Hans").expect("a script")),
    ));
  assert_eq!(
    Crossed::try_from_filter(script),
    Err(LanguageIdCrossingError::ScriptConflict)
  );

  // The NULL TEST is a value too — *the script column is null* is what a whole `eq` with no script
  // already says — so naming both is the same doubling.
  let null = LanguageIdFilter::new()
    .with_eq(tag("de"))
    .with_script(Nullable::new(ScalarFilter::new()).with_null(true));
  assert_eq!(
    Crossed::try_from_filter(null),
    Err(LanguageIdCrossingError::ScriptConflict)
  );

  let region = LanguageIdFilter::new()
    .with_eq(tag("de-DE"))
    .with_region(Nullable::new(
      ScalarFilter::new().with_eq(Region::new("DE").expect("a region")),
    ));
  assert_eq!(
    Crossed::try_from_filter(region),
    Err(LanguageIdCrossingError::RegionConflict)
  );
}

/// **A COMPONENT OPERATOR THAT IS NOT AN EQUALITY IS NOT A CONFLICT**, which is what keeps the
/// refusal narrow.
///
/// `eq: de-DE` beside `language: { in: [de, fr] }` is a conjunction a client can reasonably write —
/// two predicates over one column, both satisfiable — and only the doubled EQUALITY is the pair that
/// could silently lose one.
#[test]
fn a_membership_beside_a_whole_equality_is_allowed() {
  let filter =
    LanguageIdFilter::new()
      .with_eq(tag("de-DE"))
      .with_language(ScalarFilter::new().with_in_(vec![
        Language::new("de").expect("a language"),
        Language::new("fr").expect("a language"),
      ]));

  let comparison = crossed(filter);
  assert_eq!(comparison.language().eq().map(String::as_str), Some("de"));
  assert_eq!(comparison.language().in_().map(<[String]>::len), Some(2));
  assert_eq!(
    ComplexComparison::<Sqlite>::conjuncts(&comparison),
    5,
    "two on the language column, one on each of the other three"
  );
}

/// The crossing has no `Db` bound, so a comparison for one dialect and a comparison for another are
/// built by the same code — the dialect is selected at the LOWERING.
///
/// The SECOND dialect is what this one test needs beyond the module's own gate: a parity assertion
/// wants two drivers compiled, and `sqlx::Postgres` is `postgres`'s. Every other test here reads the
/// one dialect.
#[cfg(feature = "postgres")]
#[test]
fn the_crossing_is_the_same_for_every_dialect() {
  let filter = LanguageIdFilter::new().with_eq(tag("zh-Hans"));

  let sqlite = SqlLanguageIdComparison::<Sqlite>::try_from_filter(filter.clone()).expect("crossed");
  let postgres =
    SqlLanguageIdComparison::<sqlx::Postgres>::try_from_filter(filter).expect("crossed");

  assert_eq!(
    sqlite.language().eq().map(String::as_str),
    postgres.language().eq().map(String::as_str)
  );
  assert_eq!(sqlite.script().null(), postgres.script().null());
}