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 family-level harness every kind's tests render through, and the fold itself.

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

// Every name here is reached only from the harnesses and the dialect-gated tests below, so the
// imports carry the gate their users carry.
#[cfg(feature = "sqlite")]
use super::Carrier;
#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
use super::{QueryBuilder, SelectClause, SqlConjunction};
#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
use crate::{
  FieldName,
  comparison::{At, Backend, ComplexComparison, RecordAddress},
};

/// The row every rendering here constrains unless a test names another: a `p` row keyed by `id`.
///
/// One address for the whole family, wrapped once by the harnesses rather than written at each of
/// their hundred-odd callers. Eight of the nine kinds never read it — a leaf's predicate is about
/// its column alone — so for them it is a parameter that goes past. The one that reads it is
/// [`SqlEdgeComparison`](super::SqlEdgeComparison), and its tests are written against this row:
/// its `tags` column's elements are kept in `p_tags` and correlate on `"p"."id"`.
#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
pub(crate) const ROW: RecordAddress =
  RecordAddress::new(FieldName::new("p"), &[FieldName::new("id")]);

/// Render one column's comparison of [`ROW`] and return `(sql, bind count)`.
///
/// The bind count is half the assertion: the SQL text shows a `?` and says nothing about what was
/// bound, and the whole point of a carrier is that two different encodings render the same text.
///
/// Gated with its callers — every one of them names a dialect, because a rendering is a thing a
/// dialect does. With the family root on and no dialect there is nothing to render into.
///
/// `column` is a `&str` and both the [`FieldName`] wrap and the FRAME are made HERE, once, rather
/// than at each of the harness's callers. The parameter is a name by construction — it is the only
/// thing this function takes that could be one — so the type has nothing left to distinguish, and
/// pushing the wrap outward would put it in every assertion without adding a question the compiler
/// answers.
///
/// What the frame adds is the thing a kind's own tests are not about: one column of [`ROW`] is one
/// segment below the top level, and rendering it means holding the frame across the call.
#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
pub(crate) fn render<Db, C>(column: &str, comparison: &C) -> (String, usize)
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
  <Db as Backend>::Error: core::fmt::Debug,
  C: ComplexComparison<Db>,
  <Db as sqlx::Database>::Arguments: sqlx::IntoArguments<Db>,
{
  let frame = At::new(&ROW).frame(FieldName::new(column));
  render_at(frame.at(), comparison)
}

/// [`render`] against an address the caller names, for the one kind whose SQL depends on the row.
#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
pub(crate) fn render_at<Db, C>(at: At<'_>, comparison: &C) -> (String, usize)
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
  <Db as Backend>::Error: core::fmt::Debug,
  C: ComplexComparison<Db>,
  <Db as sqlx::Database>::Arguments: sqlx::IntoArguments<Db>,
{
  use sqlx::Execute;

  let mut qb = sqlx::QueryBuilder::<Db>::default();
  {
    // A FRAGMENT rather than a clause: what this harness reports is one column's predicate, so the
    // accumulator opens with nothing. `threaded` below is the counterpart that renders a statement.
    let out = SqlConjunction::with_lead(&mut qb, "");
    if comparison.apply(at, out).unwrap().written() == 0 {
      return (String::new(), 0);
    }
  }
  let mut built = qb.build();
  let binds = match built.take_arguments() {
    Ok(Some(args)) => sqlx::Arguments::len(&args),
    Ok(None) | Err(_) => 0,
  };
  (built.sql().as_str().to_owned(), binds)
}

/// Thread one comparison a statement's predicate list and return the whole SQL.
///
/// The counterpart of [`render`] for the lowering that passes the accumulator through, and it holds
/// the CALLER's whole half of the contract: enter the clause, build one accumulator, thread every
/// comparison through it, and drop it. The keyword and every separator are the accumulator's, which
/// is why a comparison that renders nothing leaves a statement with no `WHERE` in it.
///
/// It returns the whole statement rather than the predicate alone, because the join between the
/// keyword and the first conjunct is exactly what a predicate-only assertion cannot see.
#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
pub(super) fn threaded<Db, C>(field: &str, comparison: &C) -> String
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
  <Db as Backend>::Error: core::fmt::Debug,
  C: ComplexComparison<Db>,
{
  let mut builder = QueryBuilder::<SelectClause, Db>::select()
    .push_field("\"id\"")
    .from("\"t\"")
    .begin_where();
  {
    let frame = At::new(&ROW).frame(FieldName::new(field));
    let accumulator = SqlConjunction::new(builder.inner_mut());
    comparison.apply(frame.at(), accumulator).unwrap();
  }
  builder.finalize().into_string()
}

/// A storage type that records the operand it BOUND, in bind order.
///
/// The operand a comparison holds is not observable from the rendered SQL — a `?` says nothing about
/// what went into it — so a lowering that drops, reorders or substitutes an operand can render a
/// string that still looks right, byte for byte. This is what sees it, and every kind's mutation
/// check goes through it for that reason.
///
/// One dialect is enough: what a probe watches is the SLOT WALK, which is the generic impl's and the
/// same code in every dialect.
#[cfg(feature = "sqlite")]
pub(super) struct Probe<'a> {
  pub(super) value: i64,
  pub(super) bound: &'a core::cell::RefCell<Vec<i64>>,
}

#[cfg(feature = "sqlite")]
impl Carrier<sqlx::Sqlite> for Probe<'_> {
  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<sqlx::Sqlite>) {
    self.bound.borrow_mut().push(self.value);
    qb.push_bind(self.value);
  }
}

/// ONE column, the default body — the claim the bind above has to agree with: it pushes one
/// placeholder, so the lowering names one column.
#[cfg(feature = "sqlite")]
impl crate::ColumnKind for Probe<'_> {}

#[cfg(feature = "sqlite")]
#[test]
fn the_accumulator_separates_only_between_conjuncts() {
  use crate::{ScalarFilter, comparison::TryFromFilter};

  // A plain name, as every column reaching a comparison is: the bracketing below is the LEAF's.
  const COLUMN: &str = "n";

  let empty =
    <super::SqlScalarComparison<i64, sqlx::Sqlite>>::try_from_filter(ScalarFilter::<i64>::new())
      .unwrap();
  assert_eq!(
    render::<sqlx::Sqlite, _>(COLUMN, &empty),
    (String::new(), 0)
  );

  let one = <super::SqlScalarComparison<i64, sqlx::Sqlite>>::try_from_filter(
    ScalarFilter::<i64>::new().with_eq(1i64),
  )
  .unwrap();
  assert_eq!(
    render::<sqlx::Sqlite, _>(COLUMN, &one),
    ("\"n\" = ?".into(), 1)
  );

  // Declaration order, not insertion order: the slots are walked in the order they are declared.
  let two = <super::SqlScalarComparison<i64, sqlx::Sqlite>>::try_from_filter(
    ScalarFilter::<i64>::new().with_gt(0i64).with_eq(1i64),
  )
  .unwrap();
  assert_eq!(
    render::<sqlx::Sqlite, _>(COLUMN, &two),
    ("\"n\" = ? AND \"n\" > ?".into(), 2)
  );
}

/// The column reaches the statement bracketed, and it is the LOWERING that brackets it — every path
/// a name can take out of this family: the shared `push_cmp`, the shared `push_in`, the null test
/// [`SqlNullable`](super::SqlNullable) pushes itself, and a per-dialect leaf.
///
/// Text is the right instrument here and only here. What an operand BINDS is invisible in the SQL,
/// which is why every other assertion in this family goes through a probe — but quoting IS the text,
/// and a name that closes its own identifier is visible in nothing else.
///
/// The escape is the half that matters: unescaped, `n" = 1 OR "x` would end the identifier and leave
/// ` = 1 OR ` standing as SQL. Escaped, the whole name is one identifier — a column that does not
/// exist, which the engine refuses.
#[cfg(feature = "sqlite")]
#[test]
fn the_lowering_brackets_the_column_and_escapes_a_bracket_inside_it() {
  use crate::{
    Nullable, ScalarFilter, TextFilter,
    comparison::{
      TryFromFilter,
      sql::{SqlNullable, SqlScalarComparison, SqlTextComparison},
    },
  };

  const INJECTED: &str = "n\" = 1 OR \"x";

  let scalar = <SqlScalarComparison<i64, sqlx::Sqlite>>::try_from_filter(
    ScalarFilter::<i64>::new().with_eq(1i64),
  )
  .unwrap();
  assert_eq!(
    render::<sqlx::Sqlite, _>(INJECTED, &scalar),
    ("\"n\"\" = 1 OR \"\"x\" = ?".into(), 1)
  );

  let membership = <SqlScalarComparison<i64, sqlx::Sqlite>>::try_from_filter(
    ScalarFilter::<i64>::new().with_in_([1i64]),
  )
  .unwrap();
  assert_eq!(
    render::<sqlx::Sqlite, _>(INJECTED, &membership),
    ("\"n\"\" = 1 OR \"\"x\" IN (?)".into(), 1)
  );

  let nullable = <SqlNullable<SqlScalarComparison<i64, sqlx::Sqlite>, i64>>::try_from_filter(
    Nullable::<ScalarFilter<i64>>::new(ScalarFilter::new()).with_null(true),
  )
  .unwrap();
  assert_eq!(
    render::<sqlx::Sqlite, _>(INJECTED, &nullable),
    ("\"n\"\" = 1 OR \"\"x\" IS NULL".into(), 0)
  );

  // A per-dialect leaf, which pushes the column itself rather than through the shared helpers.
  let text = <SqlTextComparison<String, sqlx::Sqlite>>::try_from_filter(
    TextFilter::<String>::new().with_contains("cam".to_owned()),
  )
  .unwrap();
  assert_eq!(
    render::<sqlx::Sqlite, _>(INJECTED, &text),
    ("instr(\"n\"\" = 1 OR \"\"x\", ?) > 0".into(), 1)
  );
}

/// The bracket is the DIALECT's, so the same name is two different identifiers — and a name carrying
/// one dialect's bracket is an ordinary character to the other, which is why each dialect escapes
/// its own and only its own.
///
/// MySQL is the lane that says it: `"n"` is a string LITERAL there unless `ANSI_QUOTES` is set, so
/// the wrong bracket compares a constant against the operand and the predicate is false for every
/// row — a wrong answer rather than an error.
#[cfg(feature = "mysql")]
#[test]
fn the_bracket_a_column_gets_is_the_dialects_own() {
  use crate::{
    ScalarFilter,
    comparison::{TryFromFilter, sql::SqlScalarComparison},
  };

  let crossed = <SqlScalarComparison<i64, sqlx::MySql>>::try_from_filter(
    ScalarFilter::<i64>::new().with_eq(1i64),
  )
  .unwrap();

  assert_eq!(
    render::<sqlx::MySql, _>("n", &crossed),
    ("`n` = ?".into(), 1)
  );
  assert_eq!(
    render::<sqlx::MySql, _>("a`b", &crossed),
    ("`a``b` = ?".into(), 1)
  );
  assert_eq!(
    render::<sqlx::MySql, _>("a\"b", &crossed),
    ("`a\"b` = ?".into(), 1)
  );
}

/// The bracket that wraps two or more conjuncts belongs to the CALLER, not to this accumulator —
/// a comparison does not know whether it is the whole where-clause or one column of it.
#[cfg(feature = "sqlite")]
#[test]
fn the_accumulator_counts_what_it_opened() {
  let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
  // The accumulator's exclusive borrow of the builder ends with this scope, which is the only way
  // to read the builder back — two live accumulators over one builder is what the borrow forbids.
  {
    let mut out = SqlConjunction::with_lead(&mut qb, "");
    assert_eq!(out.written(), 0);
    out.open().push("a");
    out.open().push("b");
    assert_eq!(out.written(), 2);
  }
  assert_eq!(qb.sql().as_str(), "a AND b");
}

/// The lead is pushed by the FIRST conjunct and by no later one, and an accumulator that opens none
/// pushes nothing at all — which is what keeps a statement with no predicate from carrying a keyword
/// with nothing after it.
#[cfg(feature = "sqlite")]
#[test]
fn the_lead_belongs_to_the_first_conjunct_and_an_unopened_accumulator_writes_none() {
  let mut none = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
  {
    let unopened = SqlConjunction::new(&mut none);
    assert_eq!(unopened.written(), 0);
  }
  assert_eq!(none.sql().as_str(), "");

  let mut one = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
  {
    let mut out = SqlConjunction::new(&mut one);
    out.open().push("a");
    out.open().push("b");
  }
  assert_eq!(one.sql().as_str(), " WHERE a AND b");

  // Any lead, because the clause the accumulator opens is the caller's — this is the seam a
  // ` HAVING ` enters through, and the one a bare fragment leaves empty.
  let mut continued = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
  {
    let mut out = SqlConjunction::with_lead(&mut continued, " AND ");
    out.open().push("a");
    out.open().push("b");
  }
  assert_eq!(continued.sql().as_str(), " AND a AND b");
}