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: [`MongoScalarComparison`].

use super::{Mongo, MongoCarrier, MongoOperator, field_path, membership};
use crate::{
  ScalarFilter, TryMapFilter,
  comparison::{At, Backend, ComplexComparison, ToDatabaseComparison, TryFromFilter},
};

mongo_comparison_kind! {
  /// A [`ScalarFilter`]'s storage-side twin: the same eight operators, over the type this database
  /// stores the field as.
  ///
  /// `V` is the STORAGE type, never the field's, and it is the only parameter — there is no `Db` to
  /// carry, because MongoDB is one backend rather than a family of dialects. That is the whole of
  /// what makes this type's [`Debug`], [`Clone`] and [`PartialEq`] derives rather than the
  /// hand-written impls its SQL twin needs.
  ///
  /// # Borrowing rides in `V`
  ///
  /// `MongoScalarComparison<&'a i64>` is the same struct with a different `V`, because
  /// [`MongoCarrier`] is implemented for `&T` wherever it is for `T` — the property that matters
  /// most to the identity crossing, which otherwise rebuilds a whole `Box<[V]>` to change nothing.
  MongoScalarComparison {
    one { eq, ne, gt, gte, lt, lte }
    many { in_, not_in }
  }
}

impl<V> MongoScalarComparison<V> {
  /// Cross a [`ScalarFilter`] into this comparison, converting each operand with `f`.
  ///
  /// The entry point a DECLARED converter uses (`mongo(into = …)`). The trait crossing
  /// below is this same call with the storage type's own [`TryFrom`] in place of `f`.
  ///
  /// The filter is a BOUND rather than a spelling — see
  /// [`SqlScalarComparison::try_from_filter_with`](crate::comparison::sql::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 = 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,
    })
  }
}

/// The scalar filter crosses into the scalar comparison for the one backend this family has, and
/// the header naming [`Mongo`] concretely is what keeps it from overlapping the SQL row.
///
/// Coherence permits it because [`Mongo`] is LOCAL and `sqlx::Database` is foreign: only this crate
/// could write `impl sqlx::Database for Mongo`, and it has not, so `Db = Mongo` cannot unify with a
/// header demanding one. Measured rather than assumed — the SQL row's own note predicted this and
/// this is the compilation that checks it.
impl<D, I, V: MongoCarrier> ToDatabaseComparison<V, Mongo> for ScalarFilter<D, I> {
  type Comparison = MongoScalarComparison<V>;
}

/// 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: TryFrom<D>> TryFromFilter<ScalarFilter<D, I>> for MongoScalarComparison<V> {
  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's two rows, and they are the SQL family's word for word with the dialect
/// parameter gone — see
/// [`SqlScalarComparison`](crate::comparison::sql::SqlScalarComparison)'s pair, where the whole
/// argument is: a widthless operand gets its width from the COLUMN's storage type, and `V: ScoreKind`
/// is the row that supplies it.
impl<V: MongoCarrier> ToDatabaseComparison<V, Mongo> for crate::ConfidenceFilter {
  type Comparison = MongoScalarComparison<V>;
}

impl<V: crate::ScoreKind> TryFromFilter<crate::ConfidenceFilter> for MongoScalarComparison<V> {
  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 scalar kind answers here for the reason it does in the SQL family: an `$eq` or an `$in` on
/// the target's own key is a constraint the source's reference field can carry instead.
impl<V> crate::comparison::ReferentialComparison<Mongo> for MongoScalarComparison<V> {
  #[inline]
  fn is_referential(&self) -> bool {
    Self::conjuncts(self) == 1 && (self.eq.is_some() || self.in_.is_some())
  }
}

/// ONE impl, and the eight operators map ONE-TO-ONE onto `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`,
/// `$in` and `$nin`. That is a result rather than a coincidence: the operator vocabulary was chosen
/// against SQL and it turned out not to be SQL-shaped.
///
/// # Two ways the mapping is not the identity it looks like
///
/// **`ne` is `$ne` and not a negated `$eq`.** The SQL family renders every negation as
/// `NOT ( … )`, one spelling shared by a negated operator and its positive twin, because a dialect
/// writing its own `NOT` could put it inside a function call where three-valued logic makes it a
/// different question. MongoDB's `$ne` is the operator, and `{$not: {$eq: v}}` is the same
/// question here, so the direct spelling is taken.
///
/// **`$ne` matches a document whose field is NULL OR ABSENT**, where SQL's `NOT (col = ?)` on a
/// NULL column is UNKNOWN and matches nothing. That is not a defect in this row — it is MongoDB
/// matching where SQL's three-valued logic declines to — and closing the difference is
/// [`MongoNullable`](super::MongoNullable)'s question rather than the scalar kind's. Recorded here
/// because the operator table is where it is invisible: a caller that wants those cells excluded
/// asks the column's null test, and the wrapper writes `{$ne: null}` beside this key.
///
/// # The field path is rendered ONCE
///
/// A SQL leaf renders its column per conjunct, because each conjunct spells it. A BSON key is a
/// string that every operator of this comparison is merged under, so the rendering happens once at
/// the top of the body and the merge does the rest.
impl<V: MongoCarrier> ComplexComparison<Mongo> for MongoScalarComparison<V> {
  #[inline]
  fn conjuncts(&self) -> usize {
    Self::conjuncts(self)
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    mut builder: <Mongo as Backend>::Builder<'q>,
  ) -> Result<<Mongo as Backend>::Builder<'q>, <Mongo as Backend>::Error> {
    let field = field_path(at);
    for (slot, op) in [
      (&self.eq, MongoOperator::Eq),
      (&self.ne, MongoOperator::Ne),
      (&self.gt, MongoOperator::Gt),
      (&self.gte, MongoOperator::Gte),
      (&self.lt, MongoOperator::Lt),
      (&self.lte, MongoOperator::Lte),
    ] {
      if let Some(value) = slot {
        builder.merge(&field, op, value.to_bson());
      }
    }
    for (slot, op) in [
      (&self.in_, MongoOperator::In),
      (&self.not_in, MongoOperator::Nin),
    ] {
      if let Some(values) = slot {
        builder.merge(&field, op, membership(values));
      }
    }
    Ok(builder)
  }
}

#[cfg(test)]
mod tests;