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 scalar comparison: [`SqlScalarComparison`].

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

use super::{
  Carrier, SqlConjunction, push_operand_cmp, push_value_operand_cmp, push_value_operand_in,
};
use crate::{
  ColumnKind, ScalarFilter, TryMapFilter,
  comparison::{At, Backend, ComplexComparison, ToDatabaseComparison, TryFromFilter},
};

comparison_kind! {
  /// A [`ScalarFilter`]'s storage-side twin: the same eight operators, over the type this database
  /// stores the column as.
  ///
  /// `V` is the STORAGE type, never the field's. A `u64` column on SQLite crosses into
  /// `SqlScalarComparison<BeU64, Sqlite>`, and the conversion happened once, at the crossing.
  ///
  /// # Borrowing rides in `V`
  ///
  /// `SqlScalarComparison<&'a i64, Postgres>` is the same struct with a different `V` — there is no
  /// lifetime on the type and no parallel borrowed family, because
  /// [`Carrier`] is implemented for `&T` wherever it is for `T`. That matters most for the identity
  /// crossing, which otherwise rebuilds a whole `Box<[V]>` to change nothing.
  SqlScalarComparison {
    one { eq, ne, gt, gte, lt, lte }
    many { in_, not_in }
  }
}

impl<V, Db> SqlScalarComparison<V, Db> {
  /// Cross a [`ScalarFilter`] into this comparison, converting each operand with `f`.
  ///
  /// The entry point a DECLARED converter uses (`<db>(into = …)`). The trait crossing below is
  /// this same call with the storage type's own [`TryFrom`] in place of `f`, which is why a
  /// declaration that names a converter and one that does not reach the database the same way.
  ///
  /// # The filter is a BOUND rather than a spelling
  ///
  /// `X` is anything whose operands map into `V` and land on this kind — the framework's filter, and
  /// any MINTED element filter over it, the row `ingraph-codegen`'s element door emits. Naming
  /// `ScalarFilter<D, I>` here is what used to make a minted filter `E0308` at a span its author
  /// cannot edit: `emit::cross` writes ONE call for a column whatever kind it is, off a projection
  /// that is deliberately type-blind, so the second party to that call cannot be told apart by a
  /// spelling. See `ingraph/tests/flat_crossings.rs`, which is the vantage that has the wall.
  pub fn try_from_filter_with<D, I, E, F, X>(filter: X, f: F) -> Result<Self, E>
  where
    X: TryMapFilter<D, V, Mapped = ScalarFilter<V, I>>,
    F: FnMut(D) -> Result<V, E>,
  {
    let stored = filter.try_map_filter(f)?;
    Ok(Self {
      eq: stored.eq,
      ne: stored.ne,
      gt: stored.gt,
      gte: stored.gte,
      lt: stored.lt,
      lte: stored.lte,
      in_: stored.in_,
      not_in: stored.not_in,
      db: PhantomData,
    })
  }
}

/// Every SQL dialect takes the scalar filter to the scalar comparison; only the storage type and the
/// dialect vary, and both are parameters. The MongoDB family joins beside this over the same trait
/// — measured, not assumed: `impl<…, Db: sqlx::Database>` here and `impl<…> …<Mongo>` there do NOT
/// overlap, because `Mongo` would be local and nothing may implement `sqlx::Database` for it.
///
/// # The rest of the bounds are the LOWERING's, restated
///
/// [`ToDatabaseComparison::Comparison`](crate::ToDatabaseComparison::Comparison) promises
/// [`ComplexComparison`], so this row has to PROVE it rather than assume it, and what proves it is
/// the bound list the lowering below already carries — including [`ColumnKind`], which is the
/// operand's WIDTH and is what the lowering reads to know whether it is naming one column or
/// several. `Db: sqlx::Database` stays at the head of that list for the coherence reason above,
/// which the added bounds do not replace: `Backend` is a trait this crate declares, so a local
/// `Mongo` may implement it and the overlap argument would be gone if that were all the header said.
impl<D, I, V, Db> ToDatabaseComparison<V, Db> for ScalarFilter<D, I>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
  V: Carrier<Db> + ColumnKind,
{
  type Comparison = SqlScalarComparison<V, Db>;
}

/// The scalar kind answers, and it is the kind an id column most often crosses into: an integer key
/// compared under `eq` is exactly the shape a relation collapses onto the foreign key.
///
/// ONE impl for every dialect, for [`ComplexComparison`]'s reason one layer simpler — nothing here
/// renders, so there is no dialect-varying SQL for the answer to depend on.
impl<V, Db: Backend> crate::comparison::ReferentialComparison<Db> for SqlScalarComparison<V, Db> {
  #[inline]
  fn is_referential(&self) -> bool {
    Self::conjuncts(self) == 1 && (self.eq.is_some() || self.in_.is_some())
  }
}

/// A scalar comparison re-stated over a different element is that comparison: the dialect keeps and
/// only the operand's storage type moves.
///
/// It is here because a COLLECTION re-states its element comparison through the same trait — see
/// [`StrategyOver`](super::StrategyOver) — and a scalar is the element kind every collection this
/// crate ships a wrapper row for holds. An element kind with no row here has no re-stated
/// collection, which is the same honest answer an element with no storage row gets.
impl<V, Db, W> super::StrategyOver<W> for SqlScalarComparison<V, Db> {
  type Comparison = SqlScalarComparison<W, Db>;
}

/// The crossing with no declared converter: the storage type's own [`TryFrom`].
///
/// When the storage type IS the field's, `V: TryFrom<V>` resolves through std's reflexive
/// `From`/`Into` blankets and the error is [`Infallible`](core::convert::Infallible) — so the
/// identity crossing is provably unable to fail rather than merely always succeeding.
impl<D, I, V, Db> TryFromFilter<ScalarFilter<D, I>> for SqlScalarComparison<V, Db>
where
  V: TryFrom<D>,
{
  type Error = V::Error;

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

/// **THE CONFIDENCE KIND LOWERS ONTO THIS COMPARISON**, which is what a widthless operand costs and
/// what it buys.
///
/// [`ConfidenceFilter`] is one input object over every width a confidence measures in, so its
/// operands carry no width — and the width has to come from somewhere. It comes from HERE: `V` is
/// the column's own storage type, and `V: ScoreKind` is the row that says what one threshold means
/// AT that type. A `Confidence<f32>` column narrows the operand to binary32, a
/// `Confidence<rust_decimal::Decimal>` column reads its exact literal, and the client wrote one
/// threshold either way.
///
/// **The comparison is the ordinary scalar one**, and that is the deliverable rather than an
/// economy: the confidence needed a filter KIND because its OPERAND is different, and it needed no
/// comparison kind because its OPERATORS are not — six of the eight, over a total order, rendered by
/// the same `push_operand_cmp` every other scalar column renders through. `in`/`not_in` come out of
/// the crossing empty, this filter having no slot for either.
///
/// The bound is [`ScoreKind`] rather than the four widths written out, which is the FRAMEWORK-OPEN
/// posture stated as a where clause: a builtin that comes to serve as a score gets this lowering by
/// implementing that one trait, and no row here changes.
impl<V: crate::ScoreKind, Db> TryFromFilter<crate::ConfidenceFilter>
  for SqlScalarComparison<V, Db>
{
  type Error = V::Error;

  fn try_from_filter(filter: crate::ConfidenceFilter) -> Result<Self, Self::Error> {
    Self::try_from_filter_with(filter, |operand| V::from_operand(&operand))
  }
}

/// The confidence kind's storage-side answer, and it is [`ScalarFilter`]'s row above with one
/// parameter fewer: there is no `D` to carry, the operand being the same widthless
/// [`ConfidenceOperand`](crate::ConfidenceOperand) at every column.
///
/// Every bound is the row above's, unchanged, and for the same reasons — including `Db:
/// sqlx::Database` at the head, which is what keeps this from overlapping the MongoDB family's.
impl<V, Db> ToDatabaseComparison<V, Db> for crate::ConfidenceFilter
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
  V: Carrier<Db> + ColumnKind,
{
  type Comparison = SqlScalarComparison<V, Db>;
}

/// ONE impl for every dialect, and that is a POSITIVE finding rather than the absence of one.
///
/// The test this kind passes is not "no difference was found" — it is that the dialects agree on
/// both of the things a lowering can differ in:
///
/// - **The SQL is identical.** `"col" = ?`, `"col" > ?`, `"col" IN (?, …)`, the `1 = 0` an empty
///   list degenerates to, and the `NOT ( … )` wrap are one spelling in SQLite, Postgres and MySQL
///   alike. The placeholder is the only token that varies and it is
///   [`sqlx::QueryBuilder`]'s to vary, not this crate's — no string pushed on this path reads
///   differently in any dialect.
/// - **The bounds are identical, and so is the set of types they admit.** `V: Carrier<Db>` is the
///   whole requirement in every dialect. Nothing here needs a capability one engine has and another
///   does not — contrast [`SqlTextComparison`](super::SqlTextComparison), whose two `LIKE` dialects
///   need `V: AsRef<str>` to build a pattern and whose SQLite impl does not, and
///   [`SqlListComparison`](super::SqlListComparison), whose Postgres impl needs
///   [`PgHasArrayType`](sqlx::postgres::PgHasArrayType) and has no counterpart elsewhere.
///
/// What DOES vary per dialect is WHICH types have a [`Carrier`] row — `u64` has one on MySQL and not
/// on SQLite. That variation is the carrier table's, keyed on (storage type × dialect), and it
/// travels through this impl's bound rather than being flattened by it.
///
/// A fourth dialect is checked against those two statements. One whose equality, ordering or
/// membership differed in either respect would need a concrete impl of its own, exactly as the four
/// kinds that do have theirs.
///
/// # The bound that ties the dialect to its builder
///
/// `Db: for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>>` is what lets this body open a
/// conjunct at all: [`Backend::Builder`] is an associated type, so without the equality the builder
/// is opaque and the only thing an impl could do with it is give it back. Stating it as a bound
/// rather than writing one impl per dialect keeps the uniform kind uniform — a dialect that came to
/// need its own builder would simply not satisfy it, and would get a concrete impl.
///
/// # The buffer is a BOUND where the builder is an equality, and the difference is what each is for
///
/// This body hands its rendered names to [`sqlx::QueryBuilder::push`], which takes `impl Display`
/// and nothing more, so `Buffer: Display` is the whole of what the column path costs here — where
/// the builder has to be THE accumulator this family threads, because the body opens conjuncts on
/// it. Pinning the buffer to a type as well would close a question this impl never asks, and would
/// close it for every hand-written comparison generic over the dialect: such a comparison restates
/// this list to prove [`ComplexComparison`], so an equality here becomes an equality downstream.
///
/// Those two are the whole of what this impl asks of `Db`. The identifier is not spelled the same in
/// every dialect either, but this body never spells one: it hands the address to
/// [`push_column`](super::push_column), and which character brackets a column is the
/// [`Backend`]'s answer rather than a further bound here.
///
/// # `V: ColumnKind` is what makes a COMPOSITE operand nameable, and it is the third claim of a
/// storable type rather than a new one
///
/// A storage type already states three facts — its width ([`ColumnKind`]), its bind
/// ([`Carrier`]) and its read ([`Assemble`](crate::Assemble)) — and this impl reads the first two
/// TOGETHER, because a predicate is where they have to agree: an operand whose bind pushes two
/// placeholders under a left-hand side naming one column renders `"at" = ?, ?`, which no engine
/// parses. The width is a `const`, so the branch is resolved at compile time and the scalar path is
/// the same code and the same bytes it was before the bound existed — see
/// [`push_operand_cmp`](super::push_operand_cmp).
///
/// What it costs a DOWNSTREAM scalar is nothing it had not already paid: `impl ColumnKind for MyScalar
/// {}` is the whole row, the body being the default, and every storage type this crate ships has one.
impl<V, Db> ComplexComparison<Db> for SqlScalarComparison<V, Db>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
  V: Carrier<Db> + ColumnKind,
{
  #[inline]
  fn conjuncts(&self) -> usize {
    Self::conjuncts(self)
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    mut builder: Db::Builder<'q>,
  ) -> Result<Db::Builder<'q>, Db::Error> {
    // The four IDENTITY slots take the VALUE columns and the four BOUND slots take the whole
    // width, which is the law's own line drawn where both sides of it are rendered: an equality
    // asks WHICH VALUE a row holds and an index leaf is not part of one, where a bound asks where
    // the row SITS, which is the question an index leaf exists to answer. For every type with no
    // index leaf the two forms render the same text, so nothing but the two media-time citizens
    // can tell them apart.
    if let Some(value) = &self.eq {
      push_value_operand_cmp(builder.open(), at, " = ", value, false);
    }
    if let Some(value) = &self.ne {
      push_value_operand_cmp(builder.open(), at, " = ", value, true);
    }
    if let Some(value) = &self.gt {
      push_operand_cmp(builder.open(), at, " > ", value, false);
    }
    if let Some(value) = &self.gte {
      push_operand_cmp(builder.open(), at, " >= ", value, false);
    }
    if let Some(value) = &self.lt {
      push_operand_cmp(builder.open(), at, " < ", value, false);
    }
    if let Some(value) = &self.lte {
      push_operand_cmp(builder.open(), at, " <= ", value, false);
    }
    if let Some(values) = &self.in_ {
      push_value_operand_in(builder.open(), at, values, false);
    }
    if let Some(values) = &self.not_in {
      push_value_operand_in(builder.open(), at, values, true);
    }
    Ok(builder)
  }
}

#[cfg(test)]
mod tests;