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 bytes comparison: [`SqlBytesComparison`], one concrete lowering per dialect, and the crossing
//! that stopped having a refusal to own.

use core::marker::PhantomData;

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

// Gated with their only user, the shared slot walk below — which is itself gated with the
// per-dialect impls that call it. An import carries the cfg its consumer carries, and the run
// that catches a mismatch is the one where the family root is on and every dialect is off.
#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
use super::{Carrier, SqlConjunction, push_cmp, push_in};
#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
use crate::comparison::At;
use crate::{
  BytesFilter, FixedBytesFilter, TryMapFilter,
  comparison::{Backend, ComplexComparison, ToDatabaseComparison, TryFromFilter},
  graphql::filter::ByteSlots,
};

comparison_kind! {
  /// The byte kinds' storage-side twin: ten operator slots, over the type this database stores the
  /// column as.
  ///
  /// # BOTH byte kinds reach it, and it reads no width
  ///
  /// [`BytesFilter`] fills all ten and [`FixedBytesFilter`] fills eight, its substring pair being a
  /// field it does not have. Nothing downstream of the crossing asks which arrived: the SQL a slot
  /// renders is the same either way, and a slot no filter could set is a slot no walk visits.
  ///
  /// This kind carried the WIDTH as a third parameter — `SqlBytesComparison<V, K, Db>` — for one
  /// reason, and the reason retired with the shape axis: its crossing was an INHERENT method reading
  /// `K::SUBSTRING`, and an inherent method may only name its own type's parameters. The refusal is
  /// gone, so the parameter that carried the fact it read is gone with it.
  ///
  /// # The dialects do not agree, and the difference is the argument order
  ///
  /// A byte-substring match is `instr(col, ?) > 0` on SQLite, `position(? in col) > 0` on Postgres
  /// and `LOCATE(?, col) > 0` on MySQL — the operand comes SECOND in one and FIRST in the other two,
  /// which is the kind of difference that renders plausible SQL and matches the wrong rows rather
  /// than failing. So the lowering is three concrete impls.
  ///
  /// Their BOUNDS agree — `V: Carrier<Db>`, since nothing here derives a value from the operand the
  /// way a `LIKE` pattern does — and the SQL does not, which is why this kind is split where
  /// `scalar` is not. Both halves of the test have to hold for one impl to be right.
  SqlBytesComparison {
    one { eq, ne, gt, gte, lt, lte, contains, not_contains }
    many { in_, not_in }
  }
}

impl<V, Db> SqlBytesComparison<V, Db> {
  /// Cross a byte filter into this comparison, converting each operand with `f`.
  ///
  /// The entry point a DECLARED converter uses (`<db>(into = …)`), and it is a PURE MAP —
  /// every operator either kind can express has an answer in this family.
  ///
  /// # The refusal this used to own, and where it went
  ///
  /// `legacy/ingraph` refused a fixed-width substring match while RENDERING, which is what made its
  /// whole `apply` return a `Result`; this crate moved the refusal to the crossing and read it off
  /// `K::SUBSTRING`, a monomorphized const on a shape marker. Both arrangements published a schema
  /// field — `contains` on a `BINARY(32)` column — whose every use was an error.
  ///
  /// [`FixedBytesFilter`] does not have the field. So there is no operand to refuse, no const to
  /// read, and no `BytesCrossingError` to name: a request writing `contains` on a fixed-width column
  /// is answered by the wire's own unknown-field validation, before any of this crate's code runs.
  ///
  /// # The parameter is a BOUND rather than a spelling
  ///
  /// `X` is anything that maps its operands into `V` and lands on a byte filter — which is the two
  /// framework kinds and any MINTED element filter over either, the row `ingraph-codegen`'s element
  /// door emits. Naming one filter type here is what used to make a minted filter `E0308` at an
  /// expansion its author cannot edit.
  ///
  /// # Errors
  ///
  /// Whatever `f` refuses an operand with, and nothing of this crossing's own.
  // SEALED, deliberately: `ByteSlots` is `pub(crate)`, so a caller in any crate may SATISFY this
  // bound — with either byte kind, or with a minted filter over one — and no crate may add an
  // implementor. What a declaring crate extends is `BytesWire` (its own operand's wire face) and
  // `TryMapFilter` (its minted filter's operand map); the gather between a filter and this family's
  // comparison is not a seam anything outside answers.
  #[allow(private_bounds)]
  pub fn try_from_filter_with<D, E, F, X>(filter: X, f: F) -> Result<Self, E>
  where
    X: TryMapFilter<D, V, Mapped: ByteSlots<V>>,
    F: FnMut(D) -> Result<V, E>,
  {
    let stored = filter.try_map_filter(f)?.byte_operands();
    Ok(Self {
      eq: stored.eq,
      ne: stored.ne,
      gt: stored.gt,
      gte: stored.gte,
      lt: stored.lt,
      lte: stored.lte,
      contains: stored.contains,
      not_contains: stored.not_contains,
      in_: stored.in_,
      not_in: stored.not_in,
      db: PhantomData,
    })
  }
}

/// The lowering promise is stated as the COMPARISON's own bound, for the reason
/// [`SqlTextComparison`](super::SqlTextComparison)'s row gives: this kind lowers through three
/// concrete per-dialect impls, so there is no generic bound list to restate — only the fact that
/// the dialect in hand has one of them.
impl<D, V, I, Db> ToDatabaseComparison<V, Db> for BytesFilter<D, I>
where
  Db: sqlx::Database + Backend,
  SqlBytesComparison<V, Db>: ComplexComparison<Db>,
{
  type Comparison = SqlBytesComparison<V, Db>;
}

/// The fixed kind's row, and it lands on the SAME comparison — a storage side reads no width.
impl<D, V, const N: usize, I, Db> ToDatabaseComparison<V, Db> for FixedBytesFilter<D, N, I>
where
  Db: sqlx::Database + Backend,
  SqlBytesComparison<V, Db>: ComplexComparison<Db>,
{
  type Comparison = SqlBytesComparison<V, Db>;
}

/// The crossing with no declared converter: the storage type's own [`TryFrom`].
///
/// Its error is the CONVERTER's, like every other kind's in this family. It was
/// `BytesCrossingError<V::Error>` while a fixed column's substring refusal lived here — an error
/// with a second inhabited variant even at [`Infallible`](core::convert::Infallible), which meant
/// the identity crossing over a blob genuinely could not fail and the type would not say so. It says
/// so now, for both kinds, because there is nothing left to refuse.
impl<D, V, I, Db> TryFromFilter<BytesFilter<D, I>> for SqlBytesComparison<V, Db>
where
  V: TryFrom<D>,
{
  type Error = V::Error;

  fn try_from_filter(filter: BytesFilter<D, I>) -> Result<Self, Self::Error> {
    Self::try_from_filter_with(filter, V::try_from)
  }
}

/// The fixed kind's identity crossing — the same two lines, over eight slots.
impl<D, V, const N: usize, I, Db> TryFromFilter<FixedBytesFilter<D, N, I>>
  for SqlBytesComparison<V, Db>
where
  V: TryFrom<D>,
{
  type Error = V::Error;

  fn try_from_filter(filter: FixedBytesFilter<D, N, I>) -> Result<Self, Self::Error> {
    Self::try_from_filter_with(filter, V::try_from)
  }
}

/// The bytes kind answers, and it is the SAFEST family in the crate to collapse: a byte `eq` is
/// BITWISE on every dialect here — no collation, no case fold, nothing a schema can configure — so
/// the one assumption the collapse makes about the two columns it moves a predicate between is the
/// assumption a byte column cannot get wrong. [`SqlTextComparison`](super::SqlTextComparison)'s row
/// records that same question as live for MySQL's default collations; there is no version of it
/// here.
///
/// The absence this row fills was a LEGACY-WIRE ARTIFACT rather than a judgement. `legacy/ingraph`
/// answered the question for text and not for bytes, which had the order backwards, and the omission
/// travelled across with the wire it was written on. A byte-keyed declaration is a full
/// relation-filter citizen with this row, where before it was refused at the position that wanted the
/// collapse.
///
/// It reads no WIDTH, and there is nothing for one to decide: both kinds hold `eq` and `in_`, and
/// the operators the width DOES decide — the substring pair — are not a field a fixed-width filter
/// has. Either way the count is what declines.
impl<V, Db: crate::comparison::Backend> crate::comparison::ReferentialComparison<Db>
  for SqlBytesComparison<V, Db>
{
  #[inline]
  fn is_referential(&self) -> bool {
    Self::conjuncts(self) == 1 && (self.eq.is_some() || self.in_.is_some())
  }
}

/// The slot walk the three concrete impls share: the six comparison operators, the byte match
/// through `leaf` with its negated twin, then the two membership lists — in the order the struct
/// declares them.
///
/// The walk does NOT ask which byte kind filled the comparison, and it has nothing to ask: a
/// substring operand on a fixed-width column cannot reach a slot here, the filter having no field to
/// set one from. What used to be a refusal the crossing owned and this walk deliberately did not
/// re-check is now an absence neither of them has to know about.
///
/// No affix family and no case fold: a byte string has no characters to take a prefix of and no case
/// to ignore, so the byte match is one operator with a negated twin — which is also why `leaf` takes
/// four arguments where the text kind's takes six.
// Gated with its only callers, the per-dialect impls below: with the family root on and no
// dialect there is no lowering, so there is no walk to share.
#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
fn push_slots<V, Db, L>(
  comparison: &SqlBytesComparison<V, Db>,
  at: At<'_>,
  out: &mut SqlConjunction<'_, Db>,
  leaf: L,
) where
  Db: sqlx::Database + Backend<Buffer: Display>,
  V: Carrier<Db>,
  L: Fn(&mut sqlx::QueryBuilder<Db>, At<'_>, &V, bool),
{
  if let Some(value) = &comparison.eq {
    push_cmp(out.open(), at, " = ", value, false);
  }
  if let Some(value) = &comparison.ne {
    push_cmp(out.open(), at, " = ", value, true);
  }
  if let Some(value) = &comparison.gt {
    push_cmp(out.open(), at, " > ", value, false);
  }
  if let Some(value) = &comparison.gte {
    push_cmp(out.open(), at, " >= ", value, false);
  }
  if let Some(value) = &comparison.lt {
    push_cmp(out.open(), at, " < ", value, false);
  }
  if let Some(value) = &comparison.lte {
    push_cmp(out.open(), at, " <= ", value, false);
  }
  if let Some(value) = &comparison.contains {
    leaf(out.open(), at, value, false);
  }
  if let Some(value) = &comparison.not_contains {
    leaf(out.open(), at, value, true);
  }
  if let Some(values) = &comparison.in_ {
    push_in(out.open(), at, values, false);
  }
  if let Some(values) = &comparison.not_in {
    push_in(out.open(), at, values, true);
  }
}

/// A binary column matches with `LOCATE`, which is byte-exact and — like Postgres's `position` and
/// unlike SQLite's `instr` — takes the operand first.
#[cfg(feature = "mysql")]
mod mysql;

/// `BYTEA` has only `position` — byte-substring, case-blind, and with the operand FIRST, which is
/// the reverse of `instr`'s argument order.
#[cfg(feature = "postgres")]
mod postgres;

/// SQLite's `instr` is blob-aware, so the byte form and the text form are the same function — and
/// the operand comes SECOND.
#[cfg(feature = "sqlite")]
mod sqlite;

#[cfg(test)]
mod tests;