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 text comparison: [`SqlTextComparison`], and one concrete lowering per dialect.

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, TextMatch};
use crate::{
  TextFilter, TryMapFilter,
  comparison::{Backend, ComplexComparison, ToDatabaseComparison, TryFromFilter},
};

comparison_kind! {
  /// A [`TextFilter`]'s storage-side twin: the same twenty operators, over the type this database
  /// stores the column as.
  ///
  /// # The twelve affix slots read as a table, not as twelve renderings
  ///
  /// `contains` / `starts_with` / `ends_with`, each with a negated and a case-insensitive variant,
  /// are (kind × negated × nocase) triples over one [`TextMatch`] leaf. So the slot walk is a
  /// twelve-row table and a loop, shared by every dialect, and what a dialect supplies is the leaf
  /// the loop calls.
  ///
  /// # The dialects do NOT agree here, in either of the two ways that matter
  ///
  /// A substring match is `instr(col, ?) > 0` on SQLite, `col LIKE ? ESCAPE '\'` on Postgres and
  /// `LOCATE`-free `LIKE` with a doubled escape literal on MySQL — different SQL. And the
  /// difference reaches the BOUNDS: `LIKE`'s right-hand side is a PATTERN derived from the operand
  /// (its `\`, `%` and `_` escaped, a wildcard wrapped around it), and deriving one means reading
  /// the text, so the two `LIKE` dialects need `V: AsRef<str>` where SQLite needs only its carrier.
  ///
  /// One impl over all three could carry only the UNION of those bounds, which made `AsRef<str>` a
  /// requirement of SQLite's lowering that SQLite's lowering never used. Three concrete impls state
  /// each dialect's real requirement, and the SQLite one admits every text carrier — including a
  /// stored form that is not a Rust string.
  SqlTextComparison {
    one {
      eq,
      ne,
      gt,
      gte,
      lt,
      lte,
      contains,
      contains_nocase,
      not_contains,
      not_contains_nocase,
      starts_with,
      starts_with_nocase,
      not_starts_with,
      not_starts_with_nocase,
      ends_with,
      ends_with_nocase,
      not_ends_with,
      not_ends_with_nocase,
    }
    many { in_, not_in }
  }
}

/// The text kind answers for its two PLAIN operators alone, which is what makes the count the right
/// question here rather than a list: the kind carries twenty, seventeen of them matching shapes that
/// name no single child row, and any of them set raises the count past one.
///
/// # ONE impl over every dialect, where the LOWERING has three — and the open reading
///
/// The lowering is per-dialect because `LIKE` is: two of the three build a pattern and need
/// `V: AsRef<str>` for it. Nothing here renders, so this is the wire's own answer asked at the other
/// end and it holds wherever the wire's does.
///
/// What the dialect split WOULD be for, if it is ever wanted: the collapse moves a predicate off the
/// target's key column and onto the source's reference column, so it assumes the two compare text
/// alike. Under a schema whose two columns carry different collations they do not — MySQL's defaults
/// are the case to measure — and a dialect that wanted to decline would simply not have this row.
/// The framework's own DDL declares both columns from one type, so within a framework-emitted schema
/// they agree by construction; a hand-declared physical layout is where the question is live. It is
/// RECORDED rather than decided: the wire has answered `true` for every dialect since
/// `legacy/ingraph`, and narrowing it here would be a compile error for a declaration that works
/// today rather than a slower query.
impl<V, Db: crate::comparison::Backend> crate::comparison::ReferentialComparison<Db>
  for SqlTextComparison<V, Db>
{
  #[inline]
  fn is_referential(&self) -> bool {
    Self::conjuncts(self) == 1 && (self.eq.is_some() || self.in_.is_some())
  }
}

impl<V, Db> SqlTextComparison<V, Db> {
  /// Cross a [`TextFilter`] into this comparison, converting each operand with `f`.
  ///
  /// The entry point a DECLARED converter uses (`<db>(into = …)`), and the same call the trait
  /// crossing below makes with the storage type's own [`TryFrom`] supplied.
  ///
  /// Generic over the database where the LOWERING is not, and that is the honest split rather than
  /// an inconsistency: converting an operand is the same act in every dialect and cannot fail for a
  /// dialect's reason, where rendering one differs in both its SQL and its bounds.
  ///
  /// All twenty operands cross through the one converter, substring operands included. A stored form
  /// that is not a substring of another stored form where the domain values were — a compressed or
  /// re-encoded text — therefore changes what `contains` MEANS, and that is a property of the
  /// declared conversion rather than something this layer can check.
  ///
  /// The filter is a BOUND rather than a spelling — see
  /// [`SqlScalarComparison::try_from_filter_with`](super::SqlScalarComparison::try_from_filter_with),
  /// where the wall that closes is written up.
  pub fn try_from_filter_with<D, I, E, F, X>(filter: X, f: F) -> Result<Self, E>
  where
    X: TryMapFilter<D, V, Mapped = TextFilter<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,
      contains: stored.contains,
      contains_nocase: stored.contains_nocase,
      not_contains: stored.not_contains,
      not_contains_nocase: stored.not_contains_nocase,
      starts_with: stored.starts_with,
      starts_with_nocase: stored.starts_with_nocase,
      not_starts_with: stored.not_starts_with,
      not_starts_with_nocase: stored.not_starts_with_nocase,
      ends_with: stored.ends_with,
      ends_with_nocase: stored.ends_with_nocase,
      not_ends_with: stored.not_ends_with,
      not_ends_with_nocase: stored.not_ends_with_nocase,
      in_: stored.in_,
      not_in: stored.not_in,
      db: PhantomData,
    })
  }
}

/// The lowering promise is stated as the COMPARISON's own bound, because this kind has no other
/// spelling for it.
///
/// [`ToDatabaseComparison::Comparison`](crate::ToDatabaseComparison::Comparison) promises
/// [`ComplexComparison`], so a row proves it. The three kinds whose lowering is ONE generic impl
/// prove it by restating that impl's bound list; this kind's lowering is three CONCRETE impls whose
/// bounds disagree — SQLite asks `V: Carrier<Sqlite>` and the two `LIKE` dialects add
/// `V: AsRef<str>` to build a pattern — so there is no bound list to restate. What is true of all
/// three at once is exactly `SqlTextComparison<V, Db>: ComplexComparison<Db>`, and at a dialect
/// that resolves to whichever impl the dialect has.
///
/// `Db: sqlx::Database` is kept for the coherence reason
/// [`SqlScalarComparison`](super::SqlScalarComparison)'s row records, and `Db: Backend` because
/// naming [`ComplexComparison`] needs it and it is not elaborated from the crossing.
///
/// The READING parameter is carried but never read: what a crossing spends is the OPERANDS, and the
/// wire form they arrived under is spent by the time one is built. Generic over it so a declarer's
/// own text type — whose filter names a marker that crate owns — reaches storage exactly as
/// `TextFilter<String>` does.
impl<D, I, V, Db> ToDatabaseComparison<V, Db> for TextFilter<D, I>
where
  Db: sqlx::Database + Backend,
  SqlTextComparison<V, Db>: ComplexComparison<Db>,
{
  type Comparison = SqlTextComparison<V, Db>;
}

/// The crossing with no declared converter — see [`SqlScalarComparison`](super::SqlScalarComparison)'s
/// for what the identity case buys. A `String` column stored as `String` is the common one, and it
/// reaches its comparison with an [`Infallible`](core::convert::Infallible) error.
impl<D, I, V, Db> TryFromFilter<TextFilter<D, I>> for SqlTextComparison<V, Db>
where
  V: TryFrom<D>,
{
  type Error = V::Error;

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

/// The slot walk the three concrete impls share: the six comparison operators, the twelve affix
/// slots through `leaf`, then the two membership lists — in the order the struct declares them.
///
/// This is where the dialects genuinely agree, and it is shared for exactly that reason. `= ?`,
/// `> ?` and `IN (?, …)` reduce to a placeholder in every dialect and go through
/// [`Carrier`] and one `push_cmp` / `push_in`; the affixes do not, and `leaf` is the whole of what
/// the three impls differ by. A dialect answers a row of the table by READING its three components
/// as three arguments, which is what keeps a dialect at one leaf rather than at twelve.
///
/// `leaf` is taken as a type parameter rather than as a function POINTER so each impl monomorphizes
/// its own walk — and so the leaf's own bounds stay the leaf's, which is what lets SQLite's take
/// `V: Carrier<Sqlite>` while Postgres's takes `V: Carrier<Postgres> + AsRef<str>`.
// 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: &SqlTextComparison<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<'_>, TextMatch, &V, bool, 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);
  }
  // The twelve affix slots, in the order the struct declares them: three kinds, each plain,
  // case-insensitive, negated, and both.
  let matches: [(&Option<V>, TextMatch, bool, bool); 12] = [
    (&comparison.contains, TextMatch::Contains, false, false),
    (
      &comparison.contains_nocase,
      TextMatch::Contains,
      false,
      true,
    ),
    (&comparison.not_contains, TextMatch::Contains, true, false),
    (
      &comparison.not_contains_nocase,
      TextMatch::Contains,
      true,
      true,
    ),
    (&comparison.starts_with, TextMatch::Prefix, false, false),
    (
      &comparison.starts_with_nocase,
      TextMatch::Prefix,
      false,
      true,
    ),
    (&comparison.not_starts_with, TextMatch::Prefix, true, false),
    (
      &comparison.not_starts_with_nocase,
      TextMatch::Prefix,
      true,
      true,
    ),
    (&comparison.ends_with, TextMatch::Suffix, false, false),
    (&comparison.ends_with_nocase, TextMatch::Suffix, false, true),
    (&comparison.not_ends_with, TextMatch::Suffix, true, false),
    (
      &comparison.not_ends_with_nocase,
      TextMatch::Suffix,
      true,
      true,
    ),
  ];
  for (slot, kind, negated, nocase) in matches {
    if let Some(value) = slot {
      leaf(out.open(), at, kind, value, negated, nocase);
    }
  }
  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);
  }
}

/// MySQL matches with `LIKE` too, and folds case by wrapping BOTH sides in `LOWER` rather than with
/// a second operator — collation-independent, which is what a `utf8mb4_bin` column needs.
///
/// It carries the same `V: AsRef<str>` Postgres's does, for the same reason and through the same
/// shared builder; the divergence between the two is one lexing rule, spelled at the leaf.
#[cfg(feature = "mysql")]
mod mysql;

/// Postgres matches with `LIKE` / `ILIKE`, which is why its three affixes render BYTE-IDENTICAL SQL
/// and differ only in the bound pattern: a differential over the rendered text cannot tell
/// `starts_with` from `ends_with` here, and `dialect::tests` asserts the pattern instead.
///
/// `V: AsRef<str>` is what the pattern costs, and it is real: [`like_pattern`](super::like_pattern)
/// reads the operand's characters to escape them, and a carrier that binds an opaque encoding has no
/// characters to read. The same carrier SQLite lowers therefore has no lowering here, and the
/// omission is a bound naming the missing trait rather than a query that binds something plausible:
///
/// ```compile_fail,E0599
/// use ingraph::{
///   At, Carrier, ComplexComparison, FieldName, RecordAddress, TextFilter, TryFromFilter,
///   comparison::sql::{SqlConjunction, SqlTextComparison},
/// };
///
/// struct Opaque(String);
///
/// impl From<String> for Opaque {
///   fn from(text: String) -> Self {
///     Self(text)
///   }
/// }
///
/// impl Carrier<sqlx::Postgres> for Opaque {
///   fn push_bind(&self, qb: &mut sqlx::QueryBuilder<sqlx::Postgres>) {
///     qb.push_bind(self.0.as_str());
///   }
/// }
///
/// let c = SqlTextComparison::<Opaque, sqlx::Postgres>::try_from_filter(
///   TextFilter::<String>::new().with_contains("cam".to_owned()),
/// )
/// .unwrap();
/// let mut qb = sqlx::QueryBuilder::<sqlx::Postgres>::default();
/// const ROW: RecordAddress = RecordAddress::new(FieldName::new("t"), &[FieldName::new("id")]);
/// let out = SqlConjunction::with_lead(&mut qb, "");
/// let frame = At::new(&ROW).frame(FieldName::new("n"));
/// c.apply(frame.at(), out).unwrap();
/// ```
///
/// 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 has to be positive:
///
/// ```
/// use ingraph::{
///   At, ComplexComparison, FieldName, RecordAddress, TextFilter, TryFromFilter,
///   comparison::sql::{SqlConjunction, SqlTextComparison},
/// };
///
/// let c = SqlTextComparison::<String, sqlx::Postgres>::try_from_filter(
///   TextFilter::<String>::new().with_contains("cam".to_owned()),
/// )
/// .unwrap();
/// let mut qb = sqlx::QueryBuilder::<sqlx::Postgres>::default();
/// const ROW: RecordAddress = RecordAddress::new(FieldName::new("t"), &[FieldName::new("id")]);
/// let out = SqlConjunction::with_lead(&mut qb, "");
/// let frame = At::new(&ROW).frame(FieldName::new("n"));
/// c.apply(frame.at(), out).unwrap();
/// assert_eq!(qb.sql(), "\"n\" LIKE $1 ESCAPE '\\'");
/// ```
#[cfg(feature = "postgres")]
mod postgres;

/// SQLite matches with `instr`/`substr` and folds case with `lower`, so it renders every shape the
/// vocabulary declares and needs no pattern at all.
///
/// That is why its impl carries ONE bound where the two `LIKE` dialects carry two: nothing here
/// derives a value from the operand's text, so the operand binds through its own [`Carrier`] row and
/// `V: AsRef<str>` is never asked for. A stored text form that is not a Rust string — a newtype with
/// no `AsRef<str>`, a compact rope — is filterable with `contains` on this dialect and on neither
/// other, and that difference is what one impl over three dialects could not say.
///
/// The claim, from outside the crate, where a downstream storage type actually lives:
///
/// ```
/// use ingraph::{
///   At, Carrier, ComplexComparison, FieldName, RecordAddress, TextFilter, TryFromFilter,
///   comparison::sql::{SqlConjunction, SqlTextComparison},
/// };
///
/// /// A stored text form with no `AsRef<str>` — an interned handle, a compact rope.
/// struct Opaque(String);
///
/// impl From<String> for Opaque {
///   fn from(text: String) -> Self {
///     Self(text)
///   }
/// }
///
/// impl Carrier<sqlx::Sqlite> for Opaque {
///   fn push_bind(&self, qb: &mut sqlx::QueryBuilder<sqlx::Sqlite>) {
///     qb.push_bind(self.0.as_str());
///   }
/// }
///
/// let c = SqlTextComparison::<Opaque, sqlx::Sqlite>::try_from_filter(
///   TextFilter::<String>::new().with_contains("cam".to_owned()),
/// )
/// .unwrap();
/// let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
/// const ROW: RecordAddress = RecordAddress::new(FieldName::new("t"), &[FieldName::new("id")]);
/// let out = SqlConjunction::with_lead(&mut qb, "");
/// let frame = At::new(&ROW).frame(FieldName::new("n"));
/// c.apply(frame.at(), out).unwrap();
/// assert_eq!(qb.sql(), "instr(\"n\", ?) > 0");
/// ```
#[cfg(feature = "sqlite")]
mod sqlite;

#[cfg(test)]
mod tests;