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 flags comparison: [`SqlFlagsComparison`].

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

use super::{
  At, Carrier, SqlConjunction, not_wrapped, push_cmp, push_column, push_in, push_subject_cmp,
};
use crate::{
  FlagsFilter, TryMapFilter,
  comparison::{Backend, ComplexComparison, ToDatabaseComparison, TryFromFilter},
};

comparison_kind! {
  /// A [`FlagsFilter`]'s storage-side twin: the whole value compared or enumerated, and three
  /// questions about its BITS, over the integer this database stores the column as.
  ///
  /// SEVEN operators and no sugar. `isEmpty`, `isAll` and the per-flag boolean fan are folded into
  /// four of these at the wire, so what reaches here is the same seven whatever a document wrote —
  /// which is what makes this the single authority on what any flags question MEANS in SQL.
  ///
  /// No ordering, for the reason the enum kind has none: a bit set has no magnitude, and the order
  /// the underlying integer imposes is an artefact of which bit a declaration numbered first.
  SqlFlagsComparison {
    one { eq, ne, has_all, has_any, has_none }
    many { in_, not_in }
  }
}

impl<V, Db> SqlFlagsComparison<V, Db> {
  /// Cross a [`FlagsFilter`] into this comparison, converting each operand with `f`.
  ///
  /// The entry point a DECLARED converter uses. A declared flags type usually needs none — its
  /// emitted [`Carrier`] binds the bit pattern directly — so the identity crossing below is the
  /// common case and this is the escape for a column whose stored width is somebody's own.
  pub fn try_from_filter_with<D, E, F, X>(filter: X, f: F) -> Result<Self, E>
  where
    X: TryMapFilter<D, V, Mapped = FlagsFilter<V>>,
    F: FnMut(D) -> Result<V, E>,
  {
    let stored = filter.try_map_filter(f)?;
    Ok(Self {
      eq: stored.eq,
      ne: stored.ne,
      in_: stored.in_,
      not_in: stored.not_in,
      has_all: stored.has_all,
      has_any: stored.has_any,
      has_none: stored.has_none,
      db: PhantomData,
    })
  }
}

/// The bounds are the LOWERING's, restated — see
/// [`SqlEnumComparison`](super::SqlEnumComparison)'s row.
impl<D, V, Db> ToDatabaseComparison<V, Db> for FlagsFilter<D>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
  V: Carrier<Db>,
{
  type Comparison = SqlFlagsComparison<V, Db>;
}

/// The crossing with no declared converter — see
/// [`SqlScalarComparison`](super::SqlScalarComparison)'s for what the identity case buys.
impl<D, V, Db> TryFromFilter<FlagsFilter<D>> for SqlFlagsComparison<V, Db>
where
  V: TryFrom<D>,
{
  type Error = V::Error;

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

/// The flags kind answers, and answers NARROWLY: only a lone `eq` or `in` names one stored value.
///
/// A mask word does not, and that is a fact about the question rather than about the operand: a
/// column satisfying `(key & m) = m` is a SET of stored keys, so the rewrite
/// `fk IN (SELECT key FROM child WHERE …)` → `fk = v` has no `v` to be. Every mask slot is therefore
/// checked empty, where the enum kind — which has none — checks only the negated pair.
impl<V, Db: crate::comparison::Backend> crate::comparison::ReferentialComparison<Db>
  for SqlFlagsComparison<V, Db>
{
  #[inline]
  fn is_referential(&self) -> bool {
    Self::conjuncts(self) == 1 && (self.eq.is_some() || self.in_.is_some())
  }
}

/// `(col & ?)` — the SUBJECT the three mask words compare, and the one place this family spells a
/// bitwise operator.
///
/// ONE spelling for three dialects, and that is measured rather than assumed: `&` is the bitwise AND
/// of SQLite, PostgreSQL and MySQL alike, over every integer type this framework's carrier table
/// binds a flags column at. What differs per dialect is the column's WIDTH — Postgres has no
/// unsigned types, so a `u32` set is stored and bound as `i8`-wide `BIGINT` — and that is answered
/// one layer down, at the [`Carrier`] row, exactly where a Postgres `ENUM` cast is answered for the
/// vocabulary kind.
///
/// The parenthesis is not decoration. SQL's operator precedence puts `&` below `=` in MySQL and
/// above it in PostgreSQL, so `col & ? = ?` is two different questions in two dialects and this is
/// the one question in all three.
fn push_masked<Db, V>(qb: &mut sqlx::QueryBuilder<Db>, at: At<'_>, mask: &V)
where
  Db: sqlx::Database + Backend<Buffer: Display>,
  V: Carrier<Db>,
{
  qb.push("(");
  push_column(qb, at);
  qb.push(" & ");
  mask.push_bind(qb);
  qb.push(")");
}

/// `(col & ?) = 0`, wrapped in this family's ONE spelling of negation where the question is
/// `hasAny`.
///
/// The zero is a LITERAL and not a bind, and it is the only literal this family writes: it is a
/// constant of the language rather than an operand, so there is nothing for a bind to carry and no
/// value of `V` this function would have to mint one from.
///
/// Both vacuous cases fall out rather than being special-cased, and they agree with `bitflags`' own
/// reading: `hasNone(∅)` is `(col & 0) = 0`, true of every row, and `hasAny(∅)` is its negation,
/// true of none — which is `contains(∅)` and `intersects(∅)` exactly.
fn push_clear<Db, V>(qb: &mut sqlx::QueryBuilder<Db>, at: At<'_>, mask: &V, negated: bool)
where
  Db: sqlx::Database + Backend<Buffer: Display>,
  V: Carrier<Db>,
{
  not_wrapped(qb, negated, |qb| {
    push_masked(qb, at, mask);
    qb.push(" = 0");
  });
}

/// ONE impl for every dialect — [`SqlEnumComparison`](super::SqlEnumComparison)'s finding over a
/// larger operator set, and true for the same two reasons.
///
/// - **The SQL is identical.** Equality, membership and `&` read the same in SQLite, PostgreSQL and
///   MySQL, and the one place they could have diverged — operator precedence around `&` — is closed
///   by [`push_masked`]'s parenthesis rather than by three impls.
/// - **The bounds are identical, and admit the same types.** `V: Carrier<Db>`, and nothing else.
///
/// The three mask words are lowered as ONE shape each and never as a rewrite of another: `hasAll` is
/// `(col & m) = m`, `hasAny` is `NOT ( (col & m) = 0 )` and `hasNone` is `(col & m) = 0`. `hasAll`
/// is not spelled as a pair of the other two, and the reason is the vacuous case — at `m = ∅` the
/// three answer TRUE, FALSE and TRUE, which no single rewrite reproduces.
impl<V, Db> ComplexComparison<Db> for SqlFlagsComparison<V, Db>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
  V: Carrier<Db>,
{
  #[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> {
    if let Some(value) = &self.eq {
      push_cmp(builder.open(), at, " = ", value, false);
    }
    if let Some(value) = &self.ne {
      push_cmp(builder.open(), at, " = ", value, true);
    }
    if let Some(values) = &self.in_ {
      push_in(builder.open(), at, values, false);
    }
    if let Some(values) = &self.not_in {
      push_in(builder.open(), at, values, true);
    }
    if let Some(mask) = &self.has_all {
      push_subject_cmp(
        builder.open(),
        |qb| push_masked(qb, at, mask),
        " = ",
        mask,
        false,
      );
    }
    if let Some(mask) = &self.has_any {
      push_clear(builder.open(), at, mask, true);
    }
    if let Some(mask) = &self.has_none {
      push_clear(builder.open(), at, mask, false);
    }
    Ok(builder)
  }
}

#[cfg(test)]
mod tests;