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 cardinality comparison: [`SqlCountComparison`], and the walk each collection strategy renders
//! it through.

use core::marker::PhantomData;

use super::{Carrier, SqlConjunction, push_subject_cmp, push_subject_in};
use crate::{ScalarFilter, comparison::TryFromFilter};

comparison_kind! {
  /// How many elements a collection holds, asked through the eight operators a number is asked —
  /// [`ScalarFilter`]'s, over the integer this family compares a cardinality as.
  ///
  /// # It is a KIND rather than a [`SqlScalarComparison`](super::SqlScalarComparison)
  ///
  /// The operators are the same eight and the operands are the same shape, so the difference is not
  /// what it holds. It is what it is compared AGAINST: every other comparison in this family names a
  /// COLUMN, and this one names an EXPRESSION over a column — `json_array_length("tags")`,
  /// `cardinality("tags")`, a correlated `COUNT(*)` — which the collection strategy holding it
  /// supplies.
  ///
  /// So it implements no [`ComplexComparison`](crate::ComplexComparison), and the absence is the
  /// point rather than an omission: `apply` takes an [`At`](crate::At) and would render `"tags" = ?`,
  /// which is a well-formed predicate asking the wrong question. A scalar comparison in this slot
  /// could be applied that way by anyone holding it; this one cannot be applied at all, and reaches a
  /// statement only through [`push_count_slots`], which has no spelling without a cardinality.
  ///
  /// # `V` is the integer the CARDINALITY is compared as, not the element's
  ///
  /// A collection of any element type counts the same way, so this parameter never follows the
  /// element. Every collection kind names `i64` for it — the one integer all three dialects have a
  /// [`Carrier`] row for, and the one the sequence kind already binds its ordinals through — and the
  /// parameter is what leaves a dialect whose cardinality is some other integer a type to name.
  SqlCountComparison {
    one { eq, ne, gt, gte, lt, lte }
    many { in_, not_in }
  }
}

impl<V, Db> SqlCountComparison<V, Db> {
  /// Cross a [`ScalarFilter`] over a cardinality into this comparison, converting each operand with
  /// `f`.
  ///
  /// The entry point the collection crossings reach, and the trait crossing below is this same call
  /// with the storage type's own [`TryFrom`] supplied — the arrangement
  /// [`SqlScalarComparison::try_from_filter_with`](super::SqlScalarComparison::try_from_filter_with)
  /// has, for the same reason.
  ///
  /// # Errors
  ///
  /// Whatever `f` refuses an operand with.
  pub fn try_from_filter_with<D, I, E, F>(filter: ScalarFilter<D, I>, f: F) -> Result<Self, E>
  where
    F: FnMut(D) -> Result<V, E>,
  {
    let stored = filter.try_map(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,
    })
  }
}

/// The crossing with no declared converter: the storage type's own [`TryFrom`].
///
/// A cardinality filter's operands are `usize` — a collection's length is one — and this family
/// compares a cardinality as `i64`, so the crossing every collection makes is `i64: TryFrom<usize>`
/// and its error is [`TryFromIntError`](core::num::TryFromIntError). It REFUSES rather than
/// saturating, unlike [`edge`](super::edge)'s ordinal, and the difference is whose number it is: an
/// ordinal is a slice index this crate produced, where a `count` operand is a client's and a
/// substituted operand is a wrong result set reported as a right one.
impl<D, I, V, Db> TryFromFilter<ScalarFilter<D, I>> for SqlCountComparison<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)
  }
}

/// Walk the eight slots against `cardinality`, opening one conjunct per set operator.
///
/// `cardinality` writes the LEFT-HAND SIDE — the expression yielding this collection's length — and
/// it is a writer rather than a rendered string because each strategy spells one differently and two
/// of them name the collection's column inside it. Everything to the right of it is shared, which is
/// what makes `count` one question with four spellings of its cardinality rather than four questions.
///
/// The operator set and its ORDER are [`SqlScalarComparison`](super::SqlScalarComparison)'s own, so a
/// cardinality is asked in the order a number is asked anywhere in this crate.
///
/// # An EMPTY comparison opens no conjunct, and nothing here checks for one
///
/// Every slot is guarded by its own `if let`, so a comparison with no operator set walks all eight
/// and writes nothing — which is the honest reading of the empty case, since a cardinality is not
/// quantified and asking nothing about it excludes no row. That is [`Nullable`](crate::Nullable)'s
/// fold-in rather than the element scope's `EXISTS`, and it is why
/// [`conjuncts`](SqlCountComparison::conjuncts) is what the collection kinds add rather than one.
///
/// Not gated on a dialect: two of its four callers are the correlated kinds, whose lowering is
/// generic over the database, so a build with the family root and no dialect still reaches it.
pub(super) fn push_count_slots<V, Db>(
  comparison: &SqlCountComparison<V, Db>,
  out: &mut SqlConjunction<'_, Db>,
  cardinality: impl Fn(&mut sqlx::QueryBuilder<Db>),
) where
  Db: sqlx::Database,
  V: Carrier<Db>,
{
  for (value, op, negated) in [
    (&comparison.eq, " = ", false),
    (&comparison.ne, " = ", true),
    (&comparison.gt, " > ", false),
    (&comparison.gte, " >= ", false),
    (&comparison.lt, " < ", false),
    (&comparison.lte, " <= ", false),
  ] {
    if let Some(value) = value {
      push_subject_cmp(out.open(), &cardinality, op, value, negated);
    }
  }
  for (values, negated) in [(&comparison.in_, false), (&comparison.not_in, true)] {
    if let Some(values) = values {
      push_subject_in(out.open(), &cardinality, values, negated);
    }
  }
}

#[cfg(test)]
mod tests;