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 duration comparison: [`MongoDurationComparison`], the nanosecond integer a duration column
//! holds, and the range the crossing refuses past.

use jiff::SignedDuration;

use super::{Mongo, MongoCarrier, MongoOperator, field_path, membership};
use crate::{
  DurationFilter, DurationOutOfRange,
  comparison::{At, Backend, ComplexComparison, ToDatabaseComparison, TryFromFilter},
  graphql::filter::{map_operand, map_operands},
};

mongo_comparison_kind! {
  /// A [`DurationFilter`]'s storage-side twin: the same eight operators, over the type this database
  /// stores the field as.
  ///
  /// # BSON has no span, so a duration column is an INTEGER — and the SQL family refused that
  ///
  /// MongoDB's only temporal type is `UtcDateTime`, an `i64` of milliseconds since the epoch. It is
  /// an INSTANT rather than a span, so it is the wrong kind before the resolution is even reached;
  /// `carrier` records the resolution half of that finding for the four `jiff` types, which have the
  /// right kind and the wrong precision. There is no third candidate: BSON's remaining types are
  /// numbers, strings, binary and containers.
  ///
  /// [`SqlDurationComparison`](crate::comparison::sql::SqlDurationComparison) meets the same absence
  /// on SQLite and answers it the other way — no lowering at all, and a field that needs a duration
  /// there declares `i64` nanoseconds with [`ScalarFilter<i64>`](crate::ScalarFilter) in the open,
  /// rather than storing an integer the crate dressed up as temporal.
  ///
  /// What makes the same absence get the opposite answer is that SQLite is one dialect OF THREE.
  /// Refusing there costs a declarer a dialect and keeps the kind: the column moves to Postgres or
  /// MySQL, both of which hold a duration natively, and the GraphQL face every backend shares is
  /// untouched. MongoDB is one backend. Refusing here would not move a column anywhere — it would
  /// mean [`DurationFilter`] has no MongoDB answer at all, so an entity that asks a duration
  /// question could not be stored on this backend without changing the FIELD, which changes the
  /// input object every other backend serves too.
  ///
  /// The cost is the one SQLite's row names and it is paid, not avoided: an `Int64` is a number to
  /// every consumer outside this crate, and nothing in the document says which unit it counts.
  ///
  /// # NANOSECONDS, fixed by this crate rather than declared
  ///
  /// It is the unit that loses nothing. [`SignedDuration`] IS a nanosecond value, so the conversion
  /// is exact for every operand it accepts and the ones it cannot hold are refused rather than
  /// rounded — where a Postgres `INTERVAL` and a MySQL `TIME` are microsecond types and this crate
  /// refuses a nanosecond operand on both.
  ///
  /// A per-column unit would be worse than a fixed one: the same filter would mean different spans
  /// at two columns, and the stored document carries nothing that says which.
  ///
  /// # `V` is a parameter although the filter has none
  ///
  /// [`DurationFilter`] guards exactly one Rust type, so it needs no parameter — the shape
  /// [`BooleanFilter`](crate::BooleanFilter) has, and the reason this kind has no operand-level
  /// `try_map` on the filter side: mapping a [`SignedDuration`] to some `V` has no [`DurationFilter`] to
  /// land in, and this type IS the landing place. So the crossing has one entry point,
  /// [`try_from_filter_with`](Self::try_from_filter_with).
  ///
  /// What a column STORES stays a declaration here as everywhere else — `V` is what a declared
  /// converter names, and `i64` is what the crate answers when nothing is declared.
  MongoDurationComparison {
    one { eq, ne, gt, gte, lt, lte }
    many { in_, not_in }
  }
}

impl<V> MongoDurationComparison<V> {
  /// Cross a [`DurationFilter`] into this comparison, converting each operand with `f`.
  ///
  /// The entry point a DECLARED converter uses (`mongo(into = …)`), and — see the type's
  /// own note — the only place a duration's operands can be mapped at all. The trait crossing below
  /// is this same call with [`DurationFilter::operand_nanos`] in place of `f`.
  ///
  /// # Errors
  ///
  /// Whatever `f` reports, at the first operand it refuses.
  pub fn try_from_filter_with<E, F>(filter: DurationFilter, mut f: F) -> Result<Self, E>
  where
    F: FnMut(SignedDuration) -> Result<V, E>,
  {
    Ok(Self {
      eq: map_operand(filter.eq, &mut f)?,
      ne: map_operand(filter.ne, &mut f)?,
      gt: map_operand(filter.gt, &mut f)?,
      gte: map_operand(filter.gte, &mut f)?,
      lt: map_operand(filter.lt, &mut f)?,
      lte: map_operand(filter.lte, &mut f)?,
      in_: map_operands(filter.in_, &mut f)?,
      not_in: map_operands(filter.not_in, &mut f)?,
    })
  }
}

/// One backend, so one row — and the header is concrete for the coherence reason
/// [`MongoScalarComparison`](super::MongoScalarComparison)'s records.
///
/// `V` is open here and the CROSSING below is not, which is the split
/// [`ToDatabaseComparison`]'s own note describes: a storage form is a declaration rather than a law,
/// so a column that declares its own converter reaches any carrier this backend has, while a column
/// that declares none reaches the one this crate answers with.
impl<V: MongoCarrier> ToDatabaseComparison<V, Mongo> for DurationFilter {
  type Comparison = MongoDurationComparison<V>;
}

/// The crossing with no declared converter, and the ONE storage type it lands on.
///
/// # It names `i64` where every other kind in this family is generic over `V: TryFrom<D>`
///
/// That generic row would be empty here, and it is measured rather than argued: with it in place of
/// this one, `MongoDurationComparison::<i64>::try_from_filter` is `E0599` — *its trait bounds were
/// not satisfied* — because `i64: TryFrom<SignedDuration>` does not hold and no crate but `jiff` may
/// write it. Two types DO satisfy the bound — [`SignedDuration`] reflexively, and
/// [`core::time::Duration`] through jiff's own conversion — and BSON has nothing for either of them
/// to carry as, so neither has a [`MongoCarrier`] row. The generic spelling would compile and be
/// reachable by nothing this backend stores.
///
/// The two spellings also cannot both exist: with the generic one present, a concrete `i64` row is
///
/// ```text
/// error[E0119]: conflicting implementations of trait `TryFromFilter<DurationFilter>`
///               for type `MongoDurationComparison<i64>`
///   = note: upstream crates may add a new impl of trait
///           `std::convert::TryFrom<jiff::SignedDuration>` for type `i64` in future versions
/// ```
///
/// So naming the type is what lets the undeclared crossing reach a CHECKED converter at all.
///
/// # The refusal, and where it is not
///
/// [`DurationFilter::operand_nanos`] is that converter, and its [`DurationOutOfRange`] is this
/// crossing's error rather than a MongoDB-local restatement of it: one refusal has one name, and it
/// is the same one a declared `i64` column gets on Postgres.
///
/// It reads *duration is outside ±`i64` nanoseconds*, which is about 292 years either way — where
/// [`SignedDuration`] reaches about 292 billion. Truncating instead would turn an out-of-range
/// operand into a plausible in-range one and match the wrong documents with nothing to notice; with
/// a SIGNED operand it would also flip the sign, so `292 years + 1ns` becomes a large NEGATIVE
/// count. A MongoDB lowering has no later place to say no either: [`Backend::Error`] for [`Mongo`]
/// is [`Infallible`](core::convert::Infallible), so the crossing is the last position that can
/// refuse.
///
/// ALL EIGHT slots are guarded at BOTH ENDS, `in_` and `not_in` included. One out-of-range element
/// refuses the whole filter rather than being dropped, because a dropped element silently NARROWS
/// `in_` and silently WIDENS `not_in`.
impl TryFromFilter<DurationFilter> for MongoDurationComparison<i64> {
  type Error = DurationOutOfRange;

  fn try_from_filter(filter: DurationFilter) -> Result<Self, Self::Error> {
    Self::try_from_filter_with(filter, DurationFilter::operand_nanos)
  }
}

/// The eight operators map one-to-one onto `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`, `$in` and
/// `$nin`, and the walk is the scalar kind's — see it for the two places that mapping is not the
/// identity it looks like, and for why the field path is rendered once.
///
/// # The order `$gt` answers in is the numeric one, and what that rests on is the TYPE
///
/// MongoDB's comparison order puts *Numbers (ints, longs, doubles, decimals)* in ONE bracket, and
/// all numeric types are equivalent within it — so an `Int64` operand is compared by value and the
/// four ordering operators mean what the filter means. The order itself carries no qualification,
/// where the byte kind's does: `BinData` is compared by LENGTH before its bytes, so only a
/// fixed-width column's `$lt` is the bytewise one and a variable-width column's four ordering
/// operators are refused. This kind therefore needs no width and no gate.
///
/// What IS conditional is the bracket itself: MongoDB documents that a comparison operator *only
/// performs comparisons on fields where the BSON type matches the query value's type*, with limited
/// cross-type comparison through type bracketing. So the operand and the stored field have to reach
/// BSON as the same arm — the agreement `carrier`'s module note is about, and the one it had to
/// measure for `u32`, where the serializer widens and [`From`] narrows.
///
/// For `i64` the two routes agree: bson 3.1's `Serializer::serialize_i64` and `impl From<i64> for
/// Bson` are both `Bson::Int64`, with no narrowing arm between them. `carrier`'s row writes that arm
/// directly, so a duration operand and the document field it is compared against are one BSON type.
///
/// Read from MongoDB's documented comparison order rather than measured against a live server, which
/// is the standing the `BinData` rule already has here.
impl<V: MongoCarrier> ComplexComparison<Mongo> for MongoDurationComparison<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;