Skip to main content

ingraph/comparison/mongo/
duration.rs

1//! The duration comparison: [`MongoDurationComparison`], the nanosecond integer a duration column
2//! holds, and the range the crossing refuses past.
3
4use jiff::SignedDuration;
5
6use super::{Mongo, MongoCarrier, MongoOperator, field_path, membership};
7use crate::{
8  DurationFilter, DurationOutOfRange,
9  comparison::{At, Backend, ComplexComparison, ToDatabaseComparison, TryFromFilter},
10  graphql::filter::{map_operand, map_operands},
11};
12
13mongo_comparison_kind! {
14  /// A [`DurationFilter`]'s storage-side twin: the same eight operators, over the type this database
15  /// stores the field as.
16  ///
17  /// # BSON has no span, so a duration column is an INTEGER — and the SQL family refused that
18  ///
19  /// MongoDB's only temporal type is `UtcDateTime`, an `i64` of milliseconds since the epoch. It is
20  /// an INSTANT rather than a span, so it is the wrong kind before the resolution is even reached;
21  /// `carrier` records the resolution half of that finding for the four `jiff` types, which have the
22  /// right kind and the wrong precision. There is no third candidate: BSON's remaining types are
23  /// numbers, strings, binary and containers.
24  ///
25  /// [`SqlDurationComparison`](crate::comparison::sql::SqlDurationComparison) meets the same absence
26  /// on SQLite and answers it the other way — no lowering at all, and a field that needs a duration
27  /// there declares `i64` nanoseconds with [`ScalarFilter<i64>`](crate::ScalarFilter) in the open,
28  /// rather than storing an integer the crate dressed up as temporal.
29  ///
30  /// What makes the same absence get the opposite answer is that SQLite is one dialect OF THREE.
31  /// Refusing there costs a declarer a dialect and keeps the kind: the column moves to Postgres or
32  /// MySQL, both of which hold a duration natively, and the GraphQL face every backend shares is
33  /// untouched. MongoDB is one backend. Refusing here would not move a column anywhere — it would
34  /// mean [`DurationFilter`] has no MongoDB answer at all, so an entity that asks a duration
35  /// question could not be stored on this backend without changing the FIELD, which changes the
36  /// input object every other backend serves too.
37  ///
38  /// The cost is the one SQLite's row names and it is paid, not avoided: an `Int64` is a number to
39  /// every consumer outside this crate, and nothing in the document says which unit it counts.
40  ///
41  /// # NANOSECONDS, fixed by this crate rather than declared
42  ///
43  /// It is the unit that loses nothing. [`SignedDuration`] IS a nanosecond value, so the conversion
44  /// is exact for every operand it accepts and the ones it cannot hold are refused rather than
45  /// rounded — where a Postgres `INTERVAL` and a MySQL `TIME` are microsecond types and this crate
46  /// refuses a nanosecond operand on both.
47  ///
48  /// A per-column unit would be worse than a fixed one: the same filter would mean different spans
49  /// at two columns, and the stored document carries nothing that says which.
50  ///
51  /// # `V` is a parameter although the filter has none
52  ///
53  /// [`DurationFilter`] guards exactly one Rust type, so it needs no parameter — the shape
54  /// [`BooleanFilter`](crate::BooleanFilter) has, and the reason this kind has no operand-level
55  /// `try_map` on the filter side: mapping a [`SignedDuration`] to some `V` has no [`DurationFilter`] to
56  /// land in, and this type IS the landing place. So the crossing has one entry point,
57  /// [`try_from_filter_with`](Self::try_from_filter_with).
58  ///
59  /// What a column STORES stays a declaration here as everywhere else — `V` is what a declared
60  /// converter names, and `i64` is what the crate answers when nothing is declared.
61  MongoDurationComparison {
62    one { eq, ne, gt, gte, lt, lte }
63    many { in_, not_in }
64  }
65}
66
67impl<V> MongoDurationComparison<V> {
68  /// Cross a [`DurationFilter`] into this comparison, converting each operand with `f`.
69  ///
70  /// The entry point a DECLARED converter uses (`mongo(into = …)`), and — see the type's
71  /// own note — the only place a duration's operands can be mapped at all. The trait crossing below
72  /// is this same call with [`DurationFilter::operand_nanos`] in place of `f`.
73  ///
74  /// # Errors
75  ///
76  /// Whatever `f` reports, at the first operand it refuses.
77  pub fn try_from_filter_with<E, F>(filter: DurationFilter, mut f: F) -> Result<Self, E>
78  where
79    F: FnMut(SignedDuration) -> Result<V, E>,
80  {
81    Ok(Self {
82      eq: map_operand(filter.eq, &mut f)?,
83      ne: map_operand(filter.ne, &mut f)?,
84      gt: map_operand(filter.gt, &mut f)?,
85      gte: map_operand(filter.gte, &mut f)?,
86      lt: map_operand(filter.lt, &mut f)?,
87      lte: map_operand(filter.lte, &mut f)?,
88      in_: map_operands(filter.in_, &mut f)?,
89      not_in: map_operands(filter.not_in, &mut f)?,
90    })
91  }
92}
93
94/// One backend, so one row — and the header is concrete for the coherence reason
95/// [`MongoScalarComparison`](super::MongoScalarComparison)'s records.
96///
97/// `V` is open here and the CROSSING below is not, which is the split
98/// [`ToDatabaseComparison`]'s own note describes: a storage form is a declaration rather than a law,
99/// so a column that declares its own converter reaches any carrier this backend has, while a column
100/// that declares none reaches the one this crate answers with.
101impl<V: MongoCarrier> ToDatabaseComparison<V, Mongo> for DurationFilter {
102  type Comparison = MongoDurationComparison<V>;
103}
104
105/// The crossing with no declared converter, and the ONE storage type it lands on.
106///
107/// # It names `i64` where every other kind in this family is generic over `V: TryFrom<D>`
108///
109/// That generic row would be empty here, and it is measured rather than argued: with it in place of
110/// this one, `MongoDurationComparison::<i64>::try_from_filter` is `E0599` — *its trait bounds were
111/// not satisfied* — because `i64: TryFrom<SignedDuration>` does not hold and no crate but `jiff` may
112/// write it. Two types DO satisfy the bound — [`SignedDuration`] reflexively, and
113/// [`core::time::Duration`] through jiff's own conversion — and BSON has nothing for either of them
114/// to carry as, so neither has a [`MongoCarrier`] row. The generic spelling would compile and be
115/// reachable by nothing this backend stores.
116///
117/// The two spellings also cannot both exist: with the generic one present, a concrete `i64` row is
118///
119/// ```text
120/// error[E0119]: conflicting implementations of trait `TryFromFilter<DurationFilter>`
121///               for type `MongoDurationComparison<i64>`
122///   = note: upstream crates may add a new impl of trait
123///           `std::convert::TryFrom<jiff::SignedDuration>` for type `i64` in future versions
124/// ```
125///
126/// So naming the type is what lets the undeclared crossing reach a CHECKED converter at all.
127///
128/// # The refusal, and where it is not
129///
130/// [`DurationFilter::operand_nanos`] is that converter, and its [`DurationOutOfRange`] is this
131/// crossing's error rather than a MongoDB-local restatement of it: one refusal has one name, and it
132/// is the same one a declared `i64` column gets on Postgres.
133///
134/// It reads *duration is outside ±`i64` nanoseconds*, which is about 292 years either way — where
135/// [`SignedDuration`] reaches about 292 billion. Truncating instead would turn an out-of-range
136/// operand into a plausible in-range one and match the wrong documents with nothing to notice; with
137/// a SIGNED operand it would also flip the sign, so `292 years + 1ns` becomes a large NEGATIVE
138/// count. A MongoDB lowering has no later place to say no either: [`Backend::Error`] for [`Mongo`]
139/// is [`Infallible`](core::convert::Infallible), so the crossing is the last position that can
140/// refuse.
141///
142/// ALL EIGHT slots are guarded at BOTH ENDS, `in_` and `not_in` included. One out-of-range element
143/// refuses the whole filter rather than being dropped, because a dropped element silently NARROWS
144/// `in_` and silently WIDENS `not_in`.
145impl TryFromFilter<DurationFilter> for MongoDurationComparison<i64> {
146  type Error = DurationOutOfRange;
147
148  fn try_from_filter(filter: DurationFilter) -> Result<Self, Self::Error> {
149    Self::try_from_filter_with(filter, DurationFilter::operand_nanos)
150  }
151}
152
153/// The eight operators map one-to-one onto `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`, `$in` and
154/// `$nin`, and the walk is the scalar kind's — see it for the two places that mapping is not the
155/// identity it looks like, and for why the field path is rendered once.
156///
157/// # The order `$gt` answers in is the numeric one, and what that rests on is the TYPE
158///
159/// MongoDB's comparison order puts *Numbers (ints, longs, doubles, decimals)* in ONE bracket, and
160/// all numeric types are equivalent within it — so an `Int64` operand is compared by value and the
161/// four ordering operators mean what the filter means. The order itself carries no qualification,
162/// where the byte kind's does: `BinData` is compared by LENGTH before its bytes, so only a
163/// fixed-width column's `$lt` is the bytewise one and a variable-width column's four ordering
164/// operators are refused. This kind therefore needs no width and no gate.
165///
166/// What IS conditional is the bracket itself: MongoDB documents that a comparison operator *only
167/// performs comparisons on fields where the BSON type matches the query value's type*, with limited
168/// cross-type comparison through type bracketing. So the operand and the stored field have to reach
169/// BSON as the same arm — the agreement `carrier`'s module note is about, and the one it had to
170/// measure for `u32`, where the serializer widens and [`From`] narrows.
171///
172/// For `i64` the two routes agree: bson 3.1's `Serializer::serialize_i64` and `impl From<i64> for
173/// Bson` are both `Bson::Int64`, with no narrowing arm between them. `carrier`'s row writes that arm
174/// directly, so a duration operand and the document field it is compared against are one BSON type.
175///
176/// Read from MongoDB's documented comparison order rather than measured against a live server, which
177/// is the standing the `BinData` rule already has here.
178impl<V: MongoCarrier> ComplexComparison<Mongo> for MongoDurationComparison<V> {
179  #[inline]
180  fn conjuncts(&self) -> usize {
181    Self::conjuncts(self)
182  }
183
184  fn apply<'q>(
185    &'q self,
186    at: At<'_>,
187    mut builder: <Mongo as Backend>::Builder<'q>,
188  ) -> Result<<Mongo as Backend>::Builder<'q>, <Mongo as Backend>::Error> {
189    let field = field_path(at);
190    for (slot, op) in [
191      (&self.eq, MongoOperator::Eq),
192      (&self.ne, MongoOperator::Ne),
193      (&self.gt, MongoOperator::Gt),
194      (&self.gte, MongoOperator::Gte),
195      (&self.lt, MongoOperator::Lt),
196      (&self.lte, MongoOperator::Lte),
197    ] {
198      if let Some(value) = slot {
199        builder.merge(&field, op, value.to_bson());
200      }
201    }
202    for (slot, op) in [
203      (&self.in_, MongoOperator::In),
204      (&self.not_in, MongoOperator::Nin),
205    ] {
206      if let Some(values) = slot {
207        builder.merge(&field, op, membership(values));
208      }
209    }
210    Ok(builder)
211  }
212}
213
214#[cfg(test)]
215mod tests;