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 compound key's membership: [`SqlKeyIn`].

use core::{fmt::Display, marker::PhantomData};

use super::{
  BindCeiling, BindCeilingError, Carrier, SqlConjunction, SqlLoweringError, push_column,
};
use crate::{
  FieldName,
  comparison::{At, Backend, ComplexComparison},
};

/// A set of COMPOUND KEYS a row's key must be one of, lowered as the row-value `IN` — one predicate
/// naming `N` columns at once.
///
/// ```text
/// ("media_id", "segment_id") IN ((?, ?), (?, ?))
/// ```
///
/// # Only `eq` decomposes into a conjunction
///
/// Every other kind in this family lowers into an AND accumulator and decomposes along its columns,
/// and for equality that is exact: `(a, b) = (1, 10)` IS `a = 1 AND b = 10`. Membership does not
/// decompose, and the spelling that looks as though it does asks a different question:
///
/// ```text
/// -- the key set {(1, 10), (2, 20)}
/// WHERE ("a", "b") IN ((?, ?), (?, ?))     the keys
/// WHERE "a" IN (?, ?) AND "b" IN (?, ?)    the CARTESIAN PRODUCT — also (1, 20) and (2, 10)
/// ```
///
/// The second is well-formed SQL, binds the same four operands, and returns rows nobody asked for.
/// Nothing in the rendered text or the bind count separates the two, which is why this kind exists
/// as a type rather than as a rule someone follows.
///
/// The disjunctive spelling — `("a" = ? AND "b" = ?) OR (…)` — is not an escape. **Measured on
/// SQLite 3.51: it is refused from 999 keys**, because each `OR` is another level of a parse tree
/// whose depth ceiling is 1000. The row-value list is FLAT and parses at twenty thousand.
///
/// # It is CONSTRUCTED, not crossed
///
/// Every other kind in this family is the storage-side twin of a client's filter and arrives through
/// [`TryFromFilter`](crate::TryFromFilter). This one has no filter twin, because a key set is not
/// something a client writes: it is the product of a relation collapse, or the second leg of
/// `search → keys → hydrate`, where a fulltext or vector index returns keys and the `persist` store is
/// filtered by them. So the only way in is [`new`](Self::new), and there is no crossing to declare a
/// converter for.
///
/// # `N` is the key's width, and it is the type's
///
/// A key set is `k` keys of `N` columns, held as `[[V; N]]` — so a key of the wrong width is not a
/// value this type can hold, and there is no arity to check at render time. `N = 0` is refused
/// where it is written: a key names at least one column.
///
/// `N = 1` renders `("k") IN ((?), (?))`, which is the general spelling degenerating rather than a
/// case with its own branch: a one-element parenthesised list is the element in all three dialects,
/// measured, so it means exactly what a plain `IN` would.
///
/// The `N` PART NAMES arrive with the key set and the ADDRESS arrives at
/// [`apply`](ComplexComparison::apply), which is the composite convention exactly: one frame is
/// pushed per column. A key applied at `key` over `["media", "segment"]` addresses `key_media` and
/// `key_segment`, and nothing here invents either half.
///
/// At the TOP LEVEL nothing was pushed above them, so the parts are the whole names — which is what
/// the block above renders and what this kind is actually for: a key set collapsed out of a
/// relation names the ROW's own key columns, not columns beneath a field. Under a single-name
/// address that spelling was unreachable, since every application had to be handed a name and every
/// name prefixed all `N` of them.
///
/// # One `V`, and what that means for a key whose columns are stored differently
///
/// Every column of the key binds through the same [`Carrier`] row, as every other kind in this
/// family binds through one. A key whose columns have DIFFERENT storage types is therefore not
/// expressible here yet; it needs a carrier over a heterogeneous tuple, which is a seam rather than
/// a line — and nothing has asked for one.
///
/// # There is no negated twin
///
/// `NOT IN` over a row value is one expression and would render, but it is not what the collapse
/// this kind serves produces, and its three-valued behaviour over a key column that admits `NULL`
/// is a different question from the positive form's. It arrives when something asks, with its own
/// measurement.
pub struct SqlKeyIn<V, Db, const N: usize> {
  parts: [&'static str; N],
  keys: Box<[[V; N]]>,
  // `fn() -> Db` rather than a bare parameter, so the dialect marker contributes no auto-trait or
  // variance obligation: the comparison is `Send`/`Sync` on `V` alone.
  db: PhantomData<fn() -> Db>,
}

impl<V, Db, const N: usize> SqlKeyIn<V, Db, N> {
  /// The membership of `keys`, whose columns are `parts` of the name this comparison is applied
  /// under.
  ///
  /// `parts` is `&'static str` for the reason every identifier on this path is one: a part name
  /// belongs to the key's SHAPE — which column of the key, not which column of a table — and it
  /// reaches the SQL text rather than the bind list.
  ///
  /// # A key of no columns is refused here
  ///
  /// `() IN ((), ())` is not a predicate in any of the three dialects, and a key that names nothing
  /// is not a key. The refusal is the width being the TYPE's, so it lands where the width is
  /// written rather than in a `Result` every caller with a real key would have to unwrap:
  ///
  /// ```compile_fail,E0080
  /// use ingraph::comparison::sql::SqlKeyIn;
  ///
  /// let key_in = SqlKeyIn::<i64, (), 0>::new([], [[]]);
  /// ```
  ///
  /// Its twin, which must COMPILE — stable rustdoc runs a `compile_fail` block just far enough to
  /// see it fail and never checks why, so the pair shares its call shape and one half is positive:
  ///
  /// ```
  /// use ingraph::comparison::sql::SqlKeyIn;
  ///
  /// let key_in = SqlKeyIn::<i64, (), 1>::new(["media"], [[1i64], [2]]);
  /// assert_eq!(key_in.keys(), [[1], [2]]);
  /// ```
  pub fn new(parts: [&'static str; N], keys: impl Into<Box<[[V; N]]>>) -> Self {
    const { assert!(N > 0, "a key names at least one column") }
    Self {
      parts,
      keys: keys.into(),
      db: PhantomData,
    }
  }

  /// The part names, in the order the key's columns are rendered and bound.
  #[inline]
  pub const fn parts(&self) -> &[&'static str; N] {
    &self.parts
  }

  /// The key set. EMPTY is an operand rather than an absence — it asks for no rows, where an absent
  /// comparison asks for every row — so there is no `is_empty` here that could be read as either.
  #[inline]
  pub fn keys(&self) -> &[[V; N]] {
    &self.keys
  }
}

impl<V: core::fmt::Debug, Db, const N: usize> core::fmt::Debug for SqlKeyIn<V, Db, N> {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("SqlKeyIn")
      .field("parts", &self.parts)
      .field("keys", &self.keys)
      .finish()
  }
}

impl<V: Clone, Db, const N: usize> Clone for SqlKeyIn<V, Db, N> {
  fn clone(&self) -> Self {
    Self {
      parts: self.parts,
      keys: self.keys.clone(),
      db: PhantomData,
    }
  }
}

impl<V: PartialEq, Db, const N: usize> PartialEq for SqlKeyIn<V, Db, N> {
  fn eq(&self, other: &Self) -> bool {
    self.parts == other.parts && self.keys == other.keys
  }
}

/// ONE impl for every dialect, and the row-value `IN` is uniform in both of the ways a lowering can
/// differ — **measured**, on SQLite 3.51.0, PostgreSQL 16.14 and MySQL 8.4.10:
///
/// - **The SQL is identical.** `(a, b) IN ((?, ?), (?, ?))` parses and answers the same question in
///   all three, including with each engine's own placeholder syntax composed inside the nested tuple
///   list — `?` on SQLite and MySQL, `$1, $2, …` on Postgres. SQLite needs neither its `VALUES` form
///   nor a subquery for it.
/// - **The bounds are identical.** `V: Carrier<Db>` is the whole requirement, exactly as it is for
///   [`SqlScalarComparison`](super::SqlScalarComparison).
///
/// What is NOT uniform is the ceiling, and it rides as a bound stating a number rather than as three
/// concrete impls — the arrangement [`QuoteIdent`](super::QuoteIdent) already has one level down,
/// and for the same reason: the spelling is one everywhere and the constant is not.
///
/// # Why this kind has a ceiling where [`push_in`](super::push_in) deliberately has none
///
/// The multiplication. A single column's `IN` costs one bind per element, so the number a caller
/// passes IS the number that reaches the limit; a compound key's costs `k × N`, and `N` is a
/// property of the KEY rather than of the call. A caller under any single-column budget can be five
/// or forty times over this one without anything in its own arithmetic saying so.
///
/// And past the ceiling there is exactly one right answer, which is to SPLIT the key set into
/// batches whose union is the query. That is not something this layer can do quietly: it renders one
/// predicate into one accumulator, and a chunk is a different statement. So the refusal names the
/// three numbers a caller needs to batch by, and batching stays where the rest of the predicate is.
///
/// # What the ceiling is, per dialect
///
/// It is the BIND count, in all three, and it is checked before the conjunct opens so that a refusal
/// leaves the accumulator exactly as it was found.
///
/// | dialect | ceiling | why that one governs |
/// |---|---|---|
/// | SQLite | 32766 | `SQLITE_MAX_VARIABLE_NUMBER`, the default since 3.32 and the value the amalgamation sqlx bundles carries. The parse-depth ceiling of 1000 that stops the disjunctive spelling does NOT reach this one — the row-value list is flat, measured to twenty thousand keys |
/// | Postgres | 65535 | the whole range of the extended protocol's parameter count, which sqlx refuses past rather than truncating |
/// | MySQL | 65535 | the same range, refused by the server as *prepared statement contains too many placeholders* |
///
/// A softer limit sits under Postgres's and is deliberately not encoded here: its parser recurses
/// over the row-value list, so `max_stack_depth` — a server setting, 2MB by default — refuses a
/// two-column key set somewhere between seven and eight thousand keys. It is loud, it is
/// configuration, and a constant here would be this crate guessing at someone's `postgresql.conf`.
impl<V, Db, const N: usize> ComplexComparison<Db> for SqlKeyIn<V, Db, N>
where
  Db: sqlx::Database
    + BindCeiling
    + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
  V: Carrier<Db>,
{
  /// One, whatever the key set holds: an empty one renders `1 = 0` and a full one renders the row
  /// value, and both are a single conjunct.
  #[inline]
  fn conjuncts(&self) -> usize {
    1
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    mut builder: Db::Builder<'q>,
  ) -> Result<Db::Builder<'q>, Db::Error> {
    // `checked_mul` rather than a product: a key set whose bind cost does not fit in a `usize` is
    // over every ceiling there is, and saying so is the same answer.
    let binds = self.keys.len().checked_mul(N);
    if binds.is_none_or(|binds| binds > Db::MAX_BIND_PARAMETERS) {
      return Err(SqlLoweringError::BindCeiling(BindCeilingError::new(
        self.keys.len(),
        N,
        Db::MAX_BIND_PARAMETERS,
      )));
    }

    let qb = builder.open();
    if self.keys.is_empty() {
      // The same degeneracy `push_in` gives an empty list, and for the same reason: a key set that
      // came out empty means MATCH NOTHING, where an absent comparison asks for every row.
      qb.push("1 = 0");
    } else {
      qb.push("(");
      for (i, part) in self.parts.iter().enumerate() {
        if i > 0 {
          qb.push(", ");
        }
        let frame = at.frame(FieldName::new(part));
        push_column(qb, frame.at());
      }
      qb.push(") IN (");
      for (i, key) in self.keys.iter().enumerate() {
        if i > 0 {
          qb.push(", ");
        }
        qb.push("(");
        for (j, value) in key.iter().enumerate() {
          if j > 0 {
            qb.push(", ");
          }
          value.push_bind(qb);
        }
        qb.push(")");
      }
      qb.push(")");
    }
    Ok(builder)
  }
}

#[cfg(test)]
mod tests;