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
use core::{fmt::Display, num::NonZeroI32};

use crate::{
  At, Backend, BindCeiling, Carrier, ComplexComparison, FieldName, RecordAddress, ScalarFilter,
  ToDatabaseComparison, TryFromFilter,
  comparison::sql::{SqlConjunction, SqlLoweringError},
};
use smol_bytes::Utf8Bytes;

use super::{RateCrossingError, SqlRateComparison};
use crate::primitives::mediatime::{RateFilter, tests::rate};

const ROW: RecordAddress = RecordAddress::new(FieldName::new("streams"), &[FieldName::new("id")]);

/// The dialect the LOWERING renders against — Postgres, whose NUMBERED placeholders say which
/// operand reached which column. What it cannot say is whether an engine accepts the text;
/// `tests/rate_citizen.rs` is where a real one answers.
type Dialect = sqlx::Postgres;

/// Nothing on the crossing is dialect-specific, so an uninhabited marker stands for every dialect.
enum AnyDialect {}

/// The crossing row, DISCHARGED rather than assumed — a bound the impl needs and this list forgets
/// is `E0277` at the signature.
#[expect(
  dead_code,
  reason = "the signature is the assertion; instantiating it would name one dialect"
)]
fn assert_the_filter_maps_to_the_comparison<Db>()
where
  Db: sqlx::Database
    + BindCeiling
    + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
  i32: Carrier<Db>,
  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
{
  fn crosses<Db: Backend, C>()
  where
    RateFilter: ToDatabaseComparison<i32, Db, Comparison = C>,
  {
  }

  crosses::<Db, SqlRateComparison<Db>>();
}

fn denominator(value: i32) -> NonZeroI32 {
  NonZeroI32::new(value).expect("a denominator is never zero")
}

fn cross(filter: RateFilter) -> Result<SqlRateComparison<AnyDialect>, RateCrossingError> {
  SqlRateComparison::try_from_filter(filter)
}

fn lower(filter: RateFilter) -> SqlRateComparison<Dialect> {
  SqlRateComparison::try_from_filter(filter).expect("the filter is crossable")
}

fn render(comparison: &SqlRateComparison<Dialect>, field: &str) -> (String, usize) {
  let mut qb = sqlx::QueryBuilder::<Dialect>::default();
  let column = At::new(&ROW).frame(FieldName::new(field));
  let written = {
    let out = SqlConjunction::with_lead(&mut qb, "");
    comparison
      .apply(column.at(), out)
      .expect("the operands are few and meet no ceiling")
      .written()
  };

  (qb.sql().as_str().to_owned(), written)
}

/// **The crossing DECOMPOSES and REDUCES.** `60000/2002` reaches the comparison as `num = 30000` and
/// `den = 1001` — and the numerator is the RATE's, not the reciprocal's.
#[test]
fn the_crossing_decomposes_and_reduces_a_whole_value_operand() {
  let comparison = cross(RateFilter::new().with_eq(rate(60_000, 2002))).expect("a rate");

  assert_eq!(comparison.numerator().eq(), Some(&30_000));
  assert_eq!(comparison.denominator().eq(), Some(&1001));
  assert_eq!(comparison.conjuncts(), 2);

  // The pair a crossing that reciprocated would hold instead — the one confusion this citizen has
  // to be able to rule out.
  assert_ne!(comparison.numerator().eq(), Some(&1001));
}

/// The pair a WRITE would store and the pair a QUERY binds come out of one reduction, so the two
/// cannot drift apart. Every case declares a spelling its stored pair differs from.
#[test]
fn the_stored_pair_and_the_bound_pair_come_from_one_reduction() {
  for (num, den) in [(60_000, 2002), (2, 4), (0, 90_000), (48_000, 2)] {
    let declared = rate(num, den);
    let (stored_num, stored_den) = declared.reduced();

    let bound = cross(RateFilter::new().with_eq(declared)).expect("a rate crosses");

    assert_eq!(bound.numerator().eq(), Some(&stored_num), "{num}/{den}");
    assert_eq!(
      bound.denominator().eq(),
      Some(&stored_den.get()),
      "{num}/{den}"
    );
    assert_ne!(
      (stored_num, stored_den.get()),
      (num, den),
      "{num}/{den} must not already be in lowest terms, or the case proves nothing"
    );
  }
}

/// Two equalities over one column are refused BY NAME rather than one overwriting the other, and the
/// sentences are this citizen's own.
#[test]
fn a_whole_value_equality_and_a_component_equality_conflict() {
  assert_eq!(
    cross(
      RateFilter::new()
        .with_eq(rate(30, 1))
        .with_numerator(ScalarFilter::new().with_eq(30))
    )
    .unwrap_err(),
    RateCrossingError::NumeratorConflict
  );
  assert_eq!(
    cross(
      RateFilter::new()
        .with_eq(rate(30, 1))
        .with_denominator(ScalarFilter::new().with_eq(denominator(1)))
    )
    .unwrap_err(),
    RateCrossingError::DenominatorConflict
  );

  assert_eq!(
    RateCrossingError::NumeratorConflict.to_string(),
    "the rate's numerator equality is named twice"
  );
  assert_eq!(
    RateCrossingError::RenderAlphabet('%').to_string(),
    "a rate renders as digits and a slash, so `%` matches no stored value"
  );
}

/// **`in` is a ROW VALUE and never two column lists** — the cartesian-product trap, closed by the
/// type that holds the operands.
#[test]
fn a_membership_list_lowers_as_one_row_value() {
  let comparison = lower(RateFilter::new().with_in_(vec![rate(60_000, 2002), rate(24, 1)]));
  let (sql, written) = render(&comparison, "fps");

  assert_eq!(sql, r#"("fps_num", "fps_den") IN (($1, $2), ($3, $4))"#);
  assert_eq!(written, 1, "a membership is ONE conjunct however many keys");
  assert_eq!(
    comparison.members().expect("in was asked").keys(),
    [[30_000, 1001], [24, 1]],
    "the keys are the reduced pairs, in the order they were sent"
  );
}

/// `ne` and `notIn` merge into ONE negated row value — De Morgan, spelled as a merge.
#[test]
fn a_negation_and_an_exclusion_merge_into_one_predicate() {
  let comparison = lower(
    RateFilter::new()
      .with_ne(rate(24, 1))
      .with_not_in(vec![rate(60_000, 2002)]),
  );
  let (sql, written) = render(&comparison, "fps");

  assert_eq!(
    sql,
    r#"NOT (("fps_num", "fps_den") IN (($1, $2), ($3, $4)))"#
  );
  assert_eq!(written, 1);
  assert_eq!(
    comparison.excluded().expect("ne was asked").keys(),
    [[30_000, 1001], [24, 1]]
  );
}

/// An EMPTY membership keeps its direction: `in: []` asks for no rows, `notIn: []` excludes nothing.
#[test]
fn an_empty_membership_list_keeps_its_direction() {
  assert_eq!(
    render(&lower(RateFilter::new().with_in_(Vec::new())), "fps").0,
    "1 = 0"
  );
  assert_eq!(
    render(&lower(RateFilter::new().with_not_in(Vec::new())), "fps").0,
    "NOT (1 = 0)"
  );
}

/// **The render facet builds its subject in SQL**, and the pattern binds rather than being spelled
/// into the text.
#[test]
fn the_render_facet_matches_against_the_stored_spelling() {
  let comparison = lower(
    RateFilter::new()
      .with_starts_with(Utf8Bytes::from("30"))
      .with_ends_with(Utf8Bytes::from("1001"))
      .with_contains(Utf8Bytes::from("/")),
  );
  let (sql, written) = render(&comparison, "fps");

  assert_eq!(
    sql,
    concat!(
      r#"CONCAT("fps_num", '/', "fps_den") LIKE $1"#,
      r#" AND CONCAT("fps_num", '/', "fps_den") LIKE $2"#,
      r#" AND CONCAT("fps_num", '/', "fps_den") LIKE $3"#
    )
  );
  assert_eq!(written, 3);
  assert_eq!(comparison.starts_with(), Some(&Utf8Bytes::from("30%")));
  assert_eq!(comparison.ends_with(), Some(&Utf8Bytes::from("%1001")));
  assert_eq!(comparison.contains(), Some(&Utf8Bytes::from("%/%")));
}

/// The shared alphabet gate wears THIS citizen's error — the property that no `LIKE` metacharacter
/// reaches a pattern, reported in the vocabulary the client asked in.
#[test]
fn an_operand_outside_the_rendered_alphabet_is_refused() {
  for outside in ['%', '_', '\\', 'f', '.'] {
    let operand = Utf8Bytes::from(format!("30{outside}"));

    assert_eq!(
      cross(RateFilter::new().with_contains(operand.clone())).unwrap_err(),
      RateCrossingError::RenderAlphabet(outside)
    );
    assert_eq!(
      cross(RateFilter::new().with_starts_with(operand.clone())).unwrap_err(),
      RateCrossingError::RenderAlphabet(outside)
    );
    assert_eq!(
      cross(RateFilter::new().with_ends_with(operand)).unwrap_err(),
      RateCrossingError::RenderAlphabet(outside)
    );
  }

  for inside in ["30000/1001", "/", "1001", "0/1"] {
    assert!(cross(RateFilter::new().with_contains(Utf8Bytes::from(inside))).is_ok());
  }
}

/// **ONE address reaches the lowering and TWO columns come out of it**, and at the TOP LEVEL both
/// render bare.
#[test]
fn the_lowering_derives_both_columns_from_one_address() {
  let comparison = lower(RateFilter::new().with_eq(rate(60_000, 2002)));

  assert_eq!(
    render(&comparison, "fps").0,
    r#""fps_num" = $1 AND "fps_den" = $2"#
  );

  let mut qb = sqlx::QueryBuilder::<Dialect>::default();
  {
    let out = SqlConjunction::with_lead(&mut qb, "");
    comparison.apply(At::new(&ROW), out).unwrap();
  }
  assert_eq!(qb.sql(), r#""num" = $1 AND "den" = $2"#);
}

/// The path is the CALLER's and the segments are the type's — asserted with a different operator per
/// half, which is what makes a swap visible.
#[test]
fn each_half_renders_under_its_own_derived_name() {
  let comparison = lower(
    RateFilter::new()
      .with_numerator(ScalarFilter::new().with_gte(24))
      .with_denominator(ScalarFilter::new().with_lt(denominator(1002))),
  );

  assert_eq!(
    render(&comparison, "frame_rate").0,
    r#""frame_rate_num" >= $1 AND "frame_rate_den" < $2"#
  );
}

/// The empty filter crosses to the empty comparison, and `Default` is `new()`.
#[test]
fn the_empty_filter_crosses_to_the_empty_comparison() {
  let comparison = cross(RateFilter::new()).expect("an empty filter is crossable");

  assert!(comparison.is_empty());
  assert_eq!(comparison.conjuncts(), 0);
  assert_eq!(comparison, SqlRateComparison::new());
  assert_eq!(
    SqlRateComparison::<AnyDialect>::default(),
    SqlRateComparison::new()
  );
}

/// **The conjunct count is what the accumulator opened**, with every facet set at once.
#[test]
fn the_conjunct_count_is_what_the_lowering_opens() {
  let comparison = lower(
    RateFilter::new()
      .with_numerator(ScalarFilter::new().with_gt(0).with_lte(100_000))
      .with_denominator(ScalarFilter::new().with_ne(denominator(7)))
      .with_in_(vec![rate(30, 1)])
      .with_ne(rate(24, 1))
      .with_starts_with(Utf8Bytes::from("3"))
      .with_ends_with(Utf8Bytes::from("1"))
      .with_contains(Utf8Bytes::from("/")),
  );
  let (sql, written) = render(&comparison, "fps");

  // 2 + 1 + 1 + 1 + 3
  assert_eq!(comparison.conjuncts(), 8, "{sql}");
  assert_eq!(written, 8, "{sql}");
  assert_eq!(sql.matches(" AND ").count(), 7, "{sql}");
}