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 nullable wrapper: [`MongoNullable`].

use bson::Bson;

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

/// A NULLABLE column's comparison: `C`'s operators, plus the null test — which exists here and in no
/// other comparison type.
///
/// One wrapper rather than a nullable twin per kind, mirroring [`Nullable`] exactly, and it is that
/// mirroring that carries the guarantee across: a `NOT NULL` column's filter has no null test, so
/// its comparison has nowhere to put one, so asking a `NOT NULL` column whether it is null is a
/// query that does not typecheck rather than one that matches nothing.
///
/// # The null test is TWO states, and MongoDB's own convention is what makes it two
///
/// A BSON document is the set of fields that were written, so a field can be missing in a way a
/// table row's column cannot. That does not make the question three-valued, because the server
/// reads the two the same way: `{v: null}` matches the document holding an explicit null AND the
/// document with no `v` at all, and the query vocabulary follows that reading throughout. Missing
/// IS null here, by the store's own convention rather than by this crate's arrangement.
///
/// The SQL family conflates the same pair from the other side, which is why one filter means one
/// thing across both backends: `ALTER TABLE … ADD COLUMN` backfills NULL, so a row written before
/// the column existed is indistinguishable from a row that stored NULL into it. Neither family can
/// tell a caller which of the two happened, and neither is asked to.
///
/// What IS three-way is the input face — not asked, asked for null, asked for a value — and
/// [`Nullable`] already carries it as `Option<bool>`, where `None` is *not asked*. That is a fact
/// about the query rather than about the cell, and it is the layer above this one.
///
/// # What each state renders
///
/// | `null` | key | matches |
/// |---|---|---|
/// | `Some(true)` | `{$eq: null}` | the field is null, or there is no such field |
/// | `Some(false)` | `{$ne: null}` | the field is there and is not null |
/// | `None` | *(nothing)* | the question was not asked |
///
/// Both are the server's own spellings, and neither takes an `$exists` beside it. Measured on
/// MongoDB 8.2.12 over the nine-document corpus in this module's tests, `{v: {$ne: null}}` and
/// `{v: {$exists: true, $ne: null}}` return the same five documents — so the presence test is
/// redundant rather than load-bearing, and writing it would state a distinction the convention above
/// says this layer does not draw.
///
/// The two keys PARTITION the corpus: every one of the nine documents answers exactly one of them.
/// That is the property a two-state question is supposed to have, and it is what the tests check
/// rather than assume.
///
/// # An ARRAY holding a null MEMBER answers the null test
///
/// MongoDB applies a field operator to an array's members as well as to the array itself, so a cell
/// holding `[1, null, 3]` is returned by `{$eq: null}` and excluded by `{$ne: null}` — measured,
/// both of the corpus' arrays with a null member answer that way, where each cell plainly holds a
/// value.
///
/// That is the engine's reading of a stored array rather than anything this wrapper chooses, and
/// nothing this crate declares reaches it. A stored array is a COLLECTION column; a collection's
/// element type needs a [`DefaultVecMarker`](crate::DefaultVecMarker) row to be a `Vec`'s default
/// reading and `Option<T>` has none; and no shipped [`MongoCarrier`](super::MongoCarrier) row
/// produces `Bson::Null` or `Bson::Array` at all — the widest is `Vec<u8>`, which is `BinData`. A
/// downstream row that stored one would put its column's null test under this reading — the same
/// standing the array-of-arrays contamination [`MongoListComparison`](super::MongoListComparison)
/// records has, and the same standing the `$`-in-a-field-name hazard has: stated, and the row
/// author's.
#[derive(Debug, Clone, PartialEq)]
pub struct MongoNullable<C> {
  pub(crate) inner: C,
  pub(crate) null: Option<bool>,
}

impl<C> MongoNullable<C> {
  /// `inner`'s operators, with the null test unset.
  #[inline]
  pub const fn new(inner: C) -> Self {
    Self { inner, null: None }
  }

  /// The wrapped comparison — its own operators only. The null test belongs to this type.
  #[inline]
  pub const fn inner(&self) -> &C {
    &self.inner
  }

  /// The null test, when the column was asked about it.
  #[inline]
  pub const fn null(&self) -> Option<bool> {
    self.null
  }

  /// Cross a [`Nullable`] filter into this comparison, converting each OPERAND with `f` — the SQL
  /// family's own entry point, and the same one for the same reason.
  ///
  /// See [`SqlNullable::try_from_filter_with`](crate::comparison::sql::SqlNullable::try_from_filter_with)
  /// for the composition and for what a declared converter is handed. One vocabulary across the two
  /// families: a declaration writes one operand leg, and which store compiled decides nothing about
  /// what that leg is given.
  ///
  /// # Errors
  ///
  /// [`MongoNullableCrossingError::Operand`] when `f` refuses an operand and
  /// [`MongoNullableCrossingError::Inner`] when the wrapped kind's own crossing refuses — and this
  /// family has the second in a way the SQL one barely does: `MongoBytesComparison` declines the
  /// substring operators outright, whatever the operands were.
  pub fn try_from_filter_with<F, D, V, E>(
    filter: Nullable<F>,
    f: impl FnMut(D) -> Result<V, E>,
  ) -> Result<Self, MongoNullableCrossingError<E, <C as TryFromFilter<F::Mapped>>::Error>>
  where
    F: TryMapFilter<D, V>,
    C: TryFromFilter<F::Mapped>,
  {
    let stored = filter
      .try_map_filter(f)
      .map_err(MongoNullableCrossingError::Operand)?;
    Self::try_from_filter_with_inner(stored, C::try_from_filter)
      .map_err(MongoNullableCrossingError::Inner)
  }

  /// Cross a [`Nullable`] filter into this comparison, building the inner comparison with `f`.
  ///
  /// `f` takes the whole wrapped FILTER rather than an operand, and the name says which: the null
  /// test has no operand to convert, and the inner kind's crossing is the thing that knows how to
  /// convert its own. It is the entry [`try_from_filter_with`](Self::try_from_filter_with) composes.
  ///
  /// # Errors
  ///
  /// Whatever `f` refuses the wrapped filter with, and nothing of this wrapper's own — the null test
  /// has both of its states spelled here, so there is nothing left for the crossing to decline.
  pub fn try_from_filter_with_inner<F, E>(
    filter: Nullable<F>,
    f: impl FnOnce(F) -> Result<C, E>,
  ) -> Result<Self, E> {
    Ok(Self {
      inner: f(filter.inner)?,
      null: filter.null,
    })
  }
}

/// Why a [`Nullable`] filter's operands did not become MongoDB values.
///
/// [`NullableCrossingError`](crate::comparison::sql::NullableCrossingError)'s twin, kept apart for
/// the reason every crossing error in this family is: which refusals a store can raise is that
/// store's answer, and one type spanning both would publish the union to callers of each.
///
/// `X` DEFAULTS to `E`, as the SQL twin's does.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MongoNullableCrossingError<E, X = E> {
  /// An operand did not convert into the column's storage type — the converter's own error.
  Operand(E),
  /// The WRAPPED filter did not cross into its own comparison — that crossing's own error.
  Inner(X),
}

impl<E: core::fmt::Display, X: core::fmt::Display> core::fmt::Display
  for MongoNullableCrossingError<E, X>
{
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self {
      Self::Operand(error) => error.fmt(f),
      Self::Inner(error) => error.fmt(f),
    }
  }
}

impl<E, X> std::error::Error for MongoNullableCrossingError<E, X>
where
  E: std::error::Error + 'static,
  X: std::error::Error + 'static,
{
  fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
    match self {
      Self::Operand(error) => Some(error),
      Self::Inner(error) => Some(error),
    }
  }
}

/// The nullable filter crosses into the nullable comparison over whatever its inner kind crosses
/// into — one impl for every kind, present and future.
///
/// The `Option` lands HERE and nowhere below it, for the reason
/// [`SqlNullable`](crate::comparison::sql::SqlNullable)'s own row gives at length: the storage type
/// this impl is asked for is the COLUMN's, so a nullable column names `Option<V>` and `V` is what
/// the inner comparison is built over. Without it, `eq: Some(None)` and `null: Some(true)` would be
/// two spellings of one question — and here the first of them is the wrong one twice over, since
/// `{field: {$eq: null}}` is this wrapper's key rather than an operand's.
///
/// It does not overlap the SQL family's row for the same self type, for the coherence reason
/// [`MongoScalarComparison`](super::MongoScalarComparison)'s row records: that one is keyed on
/// `Db: sqlx::Database`, which is FOREIGN, and [`Mongo`] is local and has no such impl. This row
/// naming [`Mongo`] concretely is the whole of what keeps the two apart.
impl<F, V> ToDatabaseComparison<Option<V>, Mongo> for Nullable<F>
where
  F: ToDatabaseComparison<V, Mongo>,
{
  type Comparison = MongoNullable<F::Comparison>;
}

/// The empty comparison of an empty inner one — bounded on `C`, unlike the flat kinds' unbounded
/// [`Default`], because this wrapper OWNS an inner comparison and has no all-`None` state to build
/// without one. [`Nullable`] carries the same bound on the filter side for the same reason.
impl<C: Default> Default for MongoNullable<C> {
  #[inline]
  fn default() -> Self {
    Self::new(C::default())
  }
}

/// The crossing composes through `C`'s, and the error is `C`'s too — a null test never fails, so the
/// wrapper adds no way for the crossing to.
impl<F, C> TryFromFilter<Nullable<F>> for MongoNullable<C>
where
  C: TryFromFilter<F>,
{
  type Error = C::Error;

  fn try_from_filter(filter: Nullable<F>) -> Result<Self, Self::Error> {
    Self::try_from_filter_with_inner(filter, C::try_from_filter)
  }
}

/// The inner comparison's keys, then the null test's — merged into the same field's operator
/// document, which is what keeps the wrapper from opening a second key for a field that already has
/// one.
///
/// # The two keys are SHARED with the kinds, and the fold is what keeps them apart
///
/// `$eq` and `$ne` are the two most-written keys in this family: the scalar kind spells its own `eq`
/// and `ne` with them, and a collection kind writes `$eq` for `has_element` and for a
/// whole-collection equality. A comparison asking one of those AND the null test is one key twice,
/// and [`MongoConjunction::merge`] folds the second into a top-level `$and` rather than over the
/// first.
///
/// The fold is an INTERSECTION rather than a last-writer-wins, and the corpus separates the three
/// possible readings: a nullable list asking `has_element: 1` with `null: true` renders
/// `{v: {$eq: 1}, $and: [{v: {$eq: null}}]}`, which returns ONE document — where keeping only the
/// first key returns two and keeping only the second returns four.
///
/// [`MongoConjunction::merge`]: super::MongoConjunction::merge
///
/// # The null test composes with non-emptiness rather than colliding with it
///
/// A collection's `any` slot with no operator set renders `{$elemMatch: {$exists: true}}` — *this
/// field is a non-empty array* — and the null test renders beside it under its own key. `$exists` is
/// written INSIDE the element scope and never at the field, so the two documents have nothing to
/// fold. Measured, the pair a nullable list renders for `null: false` returns exactly the one
/// non-empty array whose members are all values.
///
/// # The whole address passes DOWN untouched
///
/// No frame is pushed, because this wrapper is the same field of the same document as its inner —
/// the two conjuncts name one key and the merge is what renders it once.
impl<C: ComplexComparison<Mongo>> ComplexComparison<Mongo> for MongoNullable<C> {
  /// The whole SUBTREE's count — `C`'s conjuncts plus this wrapper's null test — because the
  /// question a caller asks with it is whether anything at all will be rendered.
  #[inline]
  fn conjuncts(&self) -> usize {
    self.inner.conjuncts() + usize::from(self.null.is_some())
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: <Mongo as Backend>::Builder<'q>,
  ) -> Result<<Mongo as Backend>::Builder<'q>, <Mongo as Backend>::Error> {
    let mut builder = self.inner.apply(at, builder)?;
    if let Some(null) = self.null {
      let op = if null {
        MongoOperator::Eq
      } else {
        MongoOperator::Ne
      };
      builder.merge(&field_path(at), op, Bson::Null);
    }
    Ok(builder)
  }
}

#[cfg(test)]
mod tests;