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 compound key's membership means, and what the per-column spelling of it means instead.
//!
//! The load-bearing test here is DIFFERENTIAL and evaluates both spellings against the same rows.
//! Nothing about the defect it guards is visible in the SQL: the cartesian spelling is well-formed,
//! binds the same operands, and returns MORE ROWS.
//!
//! The ceiling half names a dialect for its number, which is the one thing about this kind that is
//! not one spelling everywhere.

#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
use core::fmt::Display;

use super::SqlKeyIn;
#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
use crate::{
  At, Backend, BindCeiling, Carrier, ComplexComparison, FieldName, QuoteIdent,
  comparison::sql::{BindCeilingError, SqlConjunction, SqlLoweringError, tests::ROW},
};
#[cfg(feature = "sqlite")]
use crate::{
  ScalarFilter,
  comparison::sql::{SqlScalarComparison, tests::Probe},
};

/// A key set carrying nothing renders a predicate all the same, so the count is one whatever it
/// holds — and the trait's [`is_empty`](ComplexComparison::is_empty) is therefore always false.
///
/// It is checked without a dialect because it is the kind's arithmetic rather than a rendering.
#[test]
fn a_key_in_is_always_exactly_one_conjunct() {
  let keyed = SqlKeyIn::<i64, (), 2>::new(["media", "segment"], [[1, 10], [2, 20]]);
  let empty = SqlKeyIn::<i64, (), 2>::new(["media", "segment"], []);

  assert_eq!(keyed.keys().len(), 2);
  assert!(empty.keys().is_empty());
  assert_eq!(keyed.parts(), &["media", "segment"]);
}

/// One column's predicate as a bare FRAGMENT, with the operands it bound in bind order.
///
/// The operand log is not decoration: a key set that reached the columns transposed renders SQL
/// that is byte-identical to the right answer, and the bind order is the only place it shows.
#[cfg(feature = "sqlite")]
fn rendered<C>(
  field: &str,
  comparison: &C,
  bound: &core::cell::RefCell<Vec<i64>>,
) -> (String, Vec<i64>)
where
  C: ComplexComparison<sqlx::Sqlite>,
{
  let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
  {
    let accumulator = SqlConjunction::with_lead(&mut qb, "");
    let frame = At::new(&ROW).frame(FieldName::new(field));
    comparison.apply(frame.at(), accumulator).unwrap();
  }
  (qb.sql().as_str().to_owned(), bound.take())
}

/// The `eq` operand of one key column, recording what it binds.
#[cfg(feature = "sqlite")]
fn probe(value: i64, bound: &core::cell::RefCell<Vec<i64>>) -> Probe<'_> {
  Probe { value, bound }
}

/// One column's membership, as a comparison lowering into an AND accumulator would reach for it.
#[cfg(feature = "sqlite")]
fn column_in<'a>(
  values: [i64; 2],
  bound: &'a core::cell::RefCell<Vec<i64>>,
) -> SqlScalarComparison<Probe<'a>, sqlx::Sqlite> {
  SqlScalarComparison::try_from_filter_with(
    ScalarFilter::<i64>::new().with_in_(values),
    |value: i64| Ok::<_, core::convert::Infallible>(probe(value, bound)),
  )
  .unwrap()
}

/// The same key set spelled as one membership PER COLUMN — the shape a two-column comparison falls
/// into when it decomposes the way `eq` legitimately does.
///
/// Written out rather than derived from [`SqlKeyIn`], because what the differential asserts is that
/// the two are not the same predicate.
#[cfg(feature = "sqlite")]
struct PerColumn<'a> {
  media: SqlScalarComparison<Probe<'a>, sqlx::Sqlite>,
  segment: SqlScalarComparison<Probe<'a>, sqlx::Sqlite>,
}

#[cfg(feature = "sqlite")]
impl ComplexComparison<sqlx::Sqlite> for PerColumn<'_> {
  fn conjuncts(&self) -> usize {
    self.media.conjuncts() + self.segment.conjuncts()
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: <sqlx::Sqlite as Backend>::Builder<'q>,
  ) -> Result<<sqlx::Sqlite as Backend>::Builder<'q>, SqlLoweringError> {
    let media = at.frame(FieldName::new("media"));
    let builder = self.media.apply(media.at(), builder)?;
    let segment = at.frame(FieldName::new("segment"));
    self.segment.apply(segment.at(), builder)
  }
}

/// The rows the differential asks about: the two the key set names, and the two more that the
/// CARTESIAN PRODUCT of the same columns' projections admits.
#[cfg(feature = "sqlite")]
const CANDIDATES: [(i64, i64); 4] = [(1, 10), (1, 20), (2, 10), (2, 20)];

/// The two key columns, as the leaf brackets them.
#[cfg(feature = "sqlite")]
const COLUMNS: [&str; 2] = ["\"k_media\"", "\"k_segment\""];

/// Whether `row` satisfies the rendered predicate `sql` under `bound`, the operands in bind order.
///
/// # Why the instrument is the predicate's MEANING and not its text
///
/// The defect this file guards emits well-formed SQL, binds the same operands the same number of
/// times, and matches rows the caller did not ask for. A differential over the rendered string
/// reports it as a different spelling, which is the one thing about it that does not matter.
///
/// # The semantics are MEASURED
///
/// Both spellings were put to SQLite 3.51.0, PostgreSQL 16.14 and MySQL 8.4.10 over exactly
/// [`CANDIDATES`] with the key set `{(1,10),(2,20)}`. All three returned those two rows for the
/// row-value `IN` and all four for the per-column conjunction. This reads the two productions that
/// experiment covers — a membership and the `1 = 0` an empty set degenerates to — and refuses
/// anything else rather than guessing at it.
#[cfg(feature = "sqlite")]
fn admits(sql: &str, bound: &[i64], row: (i64, i64)) -> bool {
  let mut rest = bound;
  let mut matched = true;
  for conjunct in sql.split(" AND ") {
    let (operands, remainder) = rest.split_at(conjunct.matches('?').count());
    rest = remainder;
    if conjunct == "1 = 0" {
      matched = false;
      continue;
    }
    let (head, _) = conjunct
      .split_once(" IN (")
      .expect("this evaluator reads a membership or the `1 = 0` an empty set renders");
    matched &= if head.starts_with('(') {
      // A row value: the operands are keys of as many columns as `head` lists.
      operands
        .as_chunks::<2>()
        .0
        .iter()
        .any(|&[media, segment]| (media, segment) == row)
    } else if head == COLUMNS[0] {
      operands.contains(&row.0)
    } else if head == COLUMNS[1] {
      operands.contains(&row.1)
    } else {
      panic!("a membership over a column this evaluator does not know: {head}")
    };
  }
  assert!(rest.is_empty(), "every bound operand belongs to a conjunct");
  matched
}

/// Which of [`CANDIDATES`] a rendered predicate lets through.
#[cfg(feature = "sqlite")]
fn admitted(sql: &str, bound: &[i64]) -> Vec<(i64, i64)> {
  CANDIDATES
    .into_iter()
    .filter(|row| admits(sql, bound, *row))
    .collect()
}

/// A compound key's membership is ONE row-value `IN`, and its columns are the parts of the name
/// that arrived from above.
#[cfg(feature = "sqlite")]
#[test]
fn a_compound_key_lowers_to_one_row_value_in() {
  let bound = core::cell::RefCell::new(Vec::new());
  let key_in = SqlKeyIn::<Probe<'_>, sqlx::Sqlite, 2>::new(
    ["media", "segment"],
    [
      [probe(1, &bound), probe(10, &bound)],
      [probe(2, &bound), probe(20, &bound)],
    ],
  );

  assert_eq!(ComplexComparison::conjuncts(&key_in), 1);
  assert_eq!(
    rendered("k", &key_in, &bound),
    (
      "(\"k_media\", \"k_segment\") IN ((?, ?), (?, ?))".to_owned(),
      vec![1, 10, 2, 20]
    )
  );
}

/// A one-column key takes the SAME spelling, degenerating rather than branching: the brackets around
/// a single column and around a single operand are what SQL calls a parenthesised expression, and
/// SQLite 3.51.0, PostgreSQL 16.14 and MySQL 8.4.10 each answer it exactly as they answer a plain
/// `IN` — measured.
#[cfg(feature = "sqlite")]
#[test]
fn a_one_column_key_is_the_same_spelling_degenerating() {
  let bound = core::cell::RefCell::new(Vec::new());
  let key_in = SqlKeyIn::<Probe<'_>, sqlx::Sqlite, 1>::new(
    ["media"],
    [[probe(1, &bound)], [probe(2, &bound)]],
  );

  assert_eq!(
    rendered("k", &key_in, &bound),
    ("(\"k_media\") IN ((?), (?))".to_owned(), vec![1, 2])
  );
}

/// **The one the kind exists for.** The same key set, spelled two ways, is two different questions:
/// the row-value `IN` asks for the keys, and the per-column conjunction asks for the CARTESIAN
/// PRODUCT of their columns — which is a superset, silently.
///
/// Both spellings render valid SQL and bind the same four operands, so the assertion is over the
/// rows each one admits. `(1, 20)` is the witness: no key names it, and the conjunction lets it
/// through.
#[cfg(feature = "sqlite")]
#[test]
fn a_row_value_in_and_a_per_column_conjunction_do_not_mean_the_same_thing() {
  let bound = core::cell::RefCell::new(Vec::new());
  let key_in = SqlKeyIn::<Probe<'_>, sqlx::Sqlite, 2>::new(
    ["media", "segment"],
    [
      [probe(1, &bound), probe(10, &bound)],
      [probe(2, &bound), probe(20, &bound)],
    ],
  );
  let (key_sql, key_operands) = rendered("k", &key_in, &bound);

  let per_column = PerColumn {
    media: column_in([1, 2], &bound),
    segment: column_in([10, 20], &bound),
  };
  let (column_sql, column_operands) = rendered("k", &per_column, &bound);

  // The same operands reach the statement either way, which is why counting binds cannot see this.
  assert_eq!(key_operands.len(), column_operands.len());

  let by_key = admitted(&key_sql, &key_operands);
  let by_column = admitted(&column_sql, &column_operands);

  assert_eq!(by_key, [(1, 10), (2, 20)]);
  assert_eq!(by_column, [(1, 10), (1, 20), (2, 10), (2, 20)]);
  assert_ne!(by_key, by_column);
}

/// An empty key set asks for NO ROWS, and that is an answer rather than a refusal — the same
/// asymmetry `in_: []` carries against an absent operator, which asks for every row.
#[cfg(feature = "sqlite")]
#[test]
fn an_empty_key_set_matches_no_rows_and_is_not_a_refusal() {
  let bound = core::cell::RefCell::new(Vec::new());
  let empty = SqlKeyIn::<Probe<'_>, sqlx::Sqlite, 2>::new(["media", "segment"], []);

  assert_eq!(ComplexComparison::conjuncts(&empty), 1);
  assert!(!empty.is_empty());

  let (sql, operands) = rendered("k", &empty, &bound);
  assert_eq!((sql.as_str(), operands.as_slice()), ("1 = 0", &[][..]));
  assert_eq!(admitted(&sql, &operands), []);
}

/// The name arrives from above and each column extends it, so a key column may be spelled anything
/// a column may be spelled — the suffix goes on while the name is still a name and the bracketing
/// happens after.
#[cfg(feature = "sqlite")]
#[test]
fn a_key_column_extends_the_name_it_was_given_and_the_leaf_brackets_it() {
  let bound = core::cell::RefCell::new(Vec::new());
  let key_in = SqlKeyIn::<Probe<'_>, sqlx::Sqlite, 2>::new(
    ["media", "segment"],
    [[probe(1, &bound), probe(10, &bound)]],
  );

  assert_eq!(
    rendered("a\"b", &key_in, &bound).0,
    "(\"a\"\"b_media\", \"a\"\"b_segment\") IN ((?, ?))"
  );
}

/// Render `keys` keys of two columns for one dialect, reporting the conjunct count on success.
///
/// The BOUND is half the assertion: a dialect's row must name this family's accumulator AND this
/// family's refusal, which is what one generic impl over three dialects rests on.
#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
fn render_keys<Db>(keys: usize) -> Result<usize, SqlLoweringError>
where
  Db: sqlx::Database
    + QuoteIdent
    + BindCeiling
    + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
  i64: Carrier<Db>,
{
  let key_in = SqlKeyIn::<i64, Db, 2>::new(["media", "segment"], vec![[1i64, 10i64]; keys]);
  let mut qb = sqlx::QueryBuilder::<Db>::default();
  let accumulator = SqlConjunction::with_lead(&mut qb, "");
  let frame = At::new(&ROW).frame(FieldName::new("k"));
  key_in
    .apply(frame.at(), accumulator)
    .map(|out| out.written())
}

/// The ceiling is the DIALECT's, and it is over BINDS rather than over keys: a k-key, n-column
/// membership costs `k × n` of them, so the number a caller can pass depends on the width of its
/// own key.
///
/// Each row is checked at both sides of its own edge, which is what makes this the ceiling rather
/// than a number near it.
#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
#[test]
fn a_key_set_is_refused_at_the_dialect_s_own_bind_ceiling() {
  #[cfg(feature = "sqlite")]
  {
    // 32766 = `SQLITE_MAX_VARIABLE_NUMBER`, and 16383 two-column keys is 32766 binds exactly.
    assert_eq!(render_keys::<sqlx::Sqlite>(16383), Ok(1));
    assert_eq!(
      render_keys::<sqlx::Sqlite>(16384),
      Err(SqlLoweringError::BindCeiling(BindCeilingError::new(
        16384, 2, 32766
      )))
    );
  }
  #[cfg(feature = "postgres")]
  {
    // 65535 is the whole range of the protocol's parameter count, so 32767 keys is the last that
    // fits and 32768 is one row past it rather than one bind past it.
    assert_eq!(render_keys::<sqlx::Postgres>(32767), Ok(1));
    assert_eq!(
      render_keys::<sqlx::Postgres>(32768),
      Err(SqlLoweringError::BindCeiling(BindCeilingError::new(
        32768, 2, 65535
      )))
    );
  }
  #[cfg(feature = "mysql")]
  {
    assert_eq!(render_keys::<sqlx::MySql>(32767), Ok(1));
    assert_eq!(
      render_keys::<sqlx::MySql>(32768),
      Err(SqlLoweringError::BindCeiling(BindCeilingError::new(
        32768, 2, 65535
      )))
    );
  }
}

/// A refusal leaves the accumulator EXACTLY as it was found — no conjunct opened, no separator and
/// no clause keyword pushed.
///
/// The check runs before the conjunct opens for that reason. A caller that renders the statement
/// anyway gets one missing predicate rather than a trailing ` WHERE ` with nothing after it, and
/// the next comparison threaded through still knows it is the first.
#[cfg(feature = "sqlite")]
#[test]
fn a_refused_key_set_leaves_the_accumulator_untouched() {
  let key_in =
    SqlKeyIn::<i64, sqlx::Sqlite, 2>::new(["media", "segment"], vec![[1i64, 10i64]; 16384]);
  let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
  {
    let accumulator = SqlConjunction::new(&mut qb);
    let frame = At::new(&ROW).frame(FieldName::new("k"));
    assert!(key_in.apply(frame.at(), accumulator).is_err());
  }

  assert_eq!(qb.sql(), "");
}

/// The refusal names the three numbers a caller needs to split the key set, and its text says which
/// is which.
#[cfg(feature = "sqlite")]
#[test]
fn the_refusal_names_what_a_caller_has_to_batch_by() {
  let error = SqlLoweringError::BindCeiling(BindCeilingError::new(16384, 2, 32766));

  assert_eq!(
    error.to_string(),
    "16384 keys of 2 columns need 32768 bound parameters and this dialect takes 32766"
  );
}