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 MongoDB side of a range query, behind the `mongo` feature: the comparisons a
//! [`TimeRangeFilter`] and a [`TimeRangedFilter`] cross into on the one backend that is not a family
//! of dialects.
//!
//! ```text
//! TimeRangeFilter                       MongoTimeRangeComparison
//!   overlaps: { … }        ──►            { "span.start": { "$lt": <the operand's END> },
//!                                           "span.end":   { "$gt": <the operand's START> } }
//! ```
//!
//! # The SEAT is compared WHOLE, and BSON's own document order is what makes that an instant
//! comparison
//!
//! A SQL conjunct names two columns and compares them as a row value; a BSON key names ONE field,
//! and that field holds the instant's whole sub-document — `{"secs": …, "nanos": …}`. So `$lte`
//! against another such document is a DOCUMENT comparison, and
//! [`MongoCarrier`](crate::MongoCarrier)'s own instant row already records what that means: BSON
//! compares two sub-documents field by field in written order, so a pair written by that row
//! compares by seconds and then by nanoseconds, which IS the instant's order. The two documents
//! carry the same two keys in the same order, so the comparison reduces to the values; jiff's signs
//! are matched between the halves, so the lexicographic reading is the chronological one.
//!
//! Nothing new is claimed here. This row SPENDS the ordering that row states, which is the first
//! time anything in this crate does — that note ends *nothing spends it today*.
//!
//! # The STRICTNESS is the half-openness, and it is the SQL twin's table in this family's operators
//!
//! | word | operand | `start` key | `end` key |
//! |---|---|---|---|
//! | `contains` | an instant `t` | `$lte: t` | `$gt: t` |
//! | `contains` | a span `[a, b)` | `$lte: a` | `$gte: b` |
//! | `overlaps` | a span `[a, b)` | `$lt: b` | `$gt: a` |
//! | `within` | a span `[a, b)` | `$gte: a` | `$lte: b` |
//!
//! Every cell is derived where the SQL twin derives it — see that module, and `mediagraph`'s own
//! table behind both. Nothing about MongoDB changes which comparison is strict: openness is a
//! property of the INTERVAL, and the backend only decides how a comparison is spelled.
//!
//! # A REPEATED operator lands in the overflow, and that is the accumulator's own answer
//!
//! Two interval words can ask the same operator of the same seat: `overlaps` and `contains` both
//! write `$lte` at `start`. One BSON key cannot hold two `$lte`s, and
//! [`merge`](crate::comparison::mongo::MongoFilter::merge) is where that is decided — a repeated
//! operator becomes a conjunct of its own beside the merged keys, which is the same `AND` the SQL
//! family gets from opening two conjuncts. So the three words compose here exactly as they compose
//! there, and this file writes no rule about it.
//!
//! [`TimeRangeFilter`]: super::TimeRangeFilter
//! [`TimeRangedFilter`]: super::TimeRangedFilter

use crate::{
  At, Backend, ColumnKind, ComplexComparison, CompositeComparison, MongoCarrier, Timestamp,
  ToDatabaseComparison, TryFromFilter,
  comparison::mongo::{Mongo, MongoOperator, MongoScalarComparison, field_path},
};

use super::{
  Contained, TimeRange, TimeRangeFilter, TimeRanged, TimeRangedFilter,
  storage::{DATA, END, SEGMENTS, START},
};

#[cfg(test)]
mod tests;

/// [`TimeRangeFilter`](super::TimeRangeFilter)'s storage-side twin on MongoDB: the three interval
/// words, and the two ends.
///
/// No backend parameter, which is the whole of what makes [`Debug`], [`Clone`] and [`PartialEq`]
/// derives here where the SQL twin writes them out: MongoDB is one backend rather than a family of
/// dialects, so there is no `Db` marker to carry.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct MongoTimeRangeComparison {
  overlaps: Option<TimeRange>,
  contains: Option<Contained>,
  within: Option<TimeRange>,
  start: MongoScalarComparison<Timestamp>,
  end: MongoScalarComparison<Timestamp>,
}

impl MongoTimeRangeComparison {
  /// The empty comparison — no operator set on any facet.
  #[inline]
  #[must_use]
  pub fn new() -> Self {
    Self::default()
  }

  /// The stretch the field must MEET, where one was asked for.
  #[inline]
  #[must_use]
  pub const fn overlaps(&self) -> Option<&TimeRange> {
    self.overlaps.as_ref()
  }

  /// The position or stretch the field must HOLD, where one was asked for.
  #[inline]
  #[must_use]
  pub const fn contains(&self) -> Option<&Contained> {
    self.contains.as_ref()
  }

  /// The stretch the field must be INSIDE, where one was asked for.
  #[inline]
  #[must_use]
  pub const fn within(&self) -> Option<&TimeRange> {
    self.within.as_ref()
  }

  /// The operators over the first instant's sub-document.
  #[inline]
  #[must_use]
  pub const fn start(&self) -> &MongoScalarComparison<Timestamp> {
    &self.start
  }

  /// The operators over the last instant's sub-document.
  #[inline]
  #[must_use]
  pub const fn end(&self) -> &MongoScalarComparison<Timestamp> {
    &self.end
  }
}

/// The lowering: the three words' six possible operators at the two seats, then each end's own
/// comparison beneath its own key.
impl ComplexComparison<Mongo> for MongoTimeRangeComparison {
  #[inline]
  fn conjuncts(&self) -> usize {
    2 * (usize::from(self.overlaps.is_some())
      + usize::from(self.contains.is_some())
      + usize::from(self.within.is_some()))
      + ComplexComparison::<Mongo>::conjuncts(&self.start)
      + ComplexComparison::<Mongo>::conjuncts(&self.end)
  }

  /// Each seat's key is rendered ONCE and every operator merged under it — the arrangement
  /// [`MongoScalarComparison`]'s own body takes, and the reason a BSON leaf differs from a SQL one.
  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 start = at.frame(START);
    let end = at.frame(END);
    let start_key = field_path(start.at());
    let end_key = field_path(end.at());

    // The two SPAN words, each two operators. `crossed` is what makes `overlaps` the CROSSED pair:
    // it compares each seat against the OTHER end of the operand, where `within` compares each seat
    // against its own. The OPERATORS carry the strictness, and `overlaps` is the only strict row —
    // see this module's table.
    for (operand, crossed, at_start, at_end) in [
      (&self.overlaps, true, MongoOperator::Lt, MongoOperator::Gt),
      (&self.within, false, MongoOperator::Gte, MongoOperator::Lte),
    ] {
      let Some(range) = operand else { continue };
      let (against_start, against_end) = if crossed {
        (range.end(), range.start())
      } else {
        (range.start(), range.end())
      };

      builder.merge(&start_key, at_start, against_start.to_bson());
      builder.merge(&end_key, at_end, against_end.to_bson());
    }

    // `contains` is the word with TWO SHAPES, and the shapes differ in the END key's operator: an
    // instant is MEMBERSHIP of a half-open set and refuses `t == end`, where a span compares like
    // boundaries and admits `b == end`.
    match &self.contains {
      Some(Contained::Instant(at)) => {
        builder.merge(&start_key, MongoOperator::Lte, at.to_bson());
        builder.merge(&end_key, MongoOperator::Gt, at.to_bson());
      }
      Some(Contained::Span(span)) => {
        builder.merge(&start_key, MongoOperator::Lte, span.start().to_bson());
        builder.merge(&end_key, MongoOperator::Gte, span.end().to_bson());
      }
      None => {}
    }

    let builder = self.start.apply(start.at(), builder)?;

    self.end.apply(end.at(), builder)
  }
}

/// The one place the fields a stretch spans are stated — the storage module's own `SEGMENTS`, which
/// this family joins with `.` where the SQL one joins with `_`.
impl CompositeComparison<Mongo> for MongoTimeRangeComparison {
  const SEGMENTS: &'static [crate::ColumnShape] = SEGMENTS;
}

/// The range filter crosses into the range comparison for the one backend this family has, and the
/// header naming [`Mongo`] concretely is what keeps it from overlapping the SQL row — see
/// [`MongoScalarComparison`]'s own note, where the coherence argument is made.
impl ToDatabaseComparison<Timestamp, Mongo> for TimeRangeFilter {
  type Comparison = MongoTimeRangeComparison;
}

/// The crossing, and the only route into a [`MongoTimeRangeComparison`].
///
/// [`Infallible`](core::convert::Infallible) for the SQL twin's reason, which is a PROOF rather than
/// an optimism: an interval operand has already been through [`TimeRange::new`], and each component
/// filter crosses through `Timestamp: TryFrom<Timestamp>` — std's reflexive blanket, whose error IS
/// `Infallible`.
impl TryFromFilter<TimeRangeFilter> for MongoTimeRangeComparison {
  type Error = core::convert::Infallible;

  fn try_from_filter(filter: TimeRangeFilter) -> Result<Self, Self::Error> {
    // Destructured rather than read through the getters, so a slot added to the filter tomorrow is
    // an `E0027` here instead of a facet silently not crossing.
    let TimeRangeFilter {
      overlaps,
      contains,
      within,
      start,
      end,
    } = filter;

    Ok(Self {
      overlaps: overlaps.map(Into::into),
      contains: contains.map(Into::into),
      within: within.map(Into::into),
      start: MongoScalarComparison::try_from_filter(start.unwrap_or_default())?,
      end: MongoScalarComparison::try_from_filter(end.unwrap_or_default())?,
    })
  }
}

/// [`TimeRangedFilter`](super::TimeRangedFilter)'s storage-side twin on MongoDB: the stretch's whole
/// comparison, and the payload's own beside it.
///
/// `P` is carried for the SQL twin's reason — a composite comparison states the columns it spans and
/// a width is the DOMAIN type's — and it is the only parameter this type has beyond the payload's
/// comparison, there being no dialect.
#[derive(Debug, Clone, PartialEq)]
pub struct MongoTimeRangedComparison<P, C> {
  range: MongoTimeRangeComparison,
  data: C,
  // `fn() -> P` so the payload contributes no auto-trait or variance obligation.
  payload: core::marker::PhantomData<fn() -> P>,
}

impl<P, C> MongoTimeRangedComparison<P, C> {
  /// The empty comparison — no operator set on either half.
  #[inline]
  #[must_use]
  pub fn new() -> Self
  where
    C: Default,
  {
    Self {
      range: MongoTimeRangeComparison::new(),
      data: C::default(),
      payload: core::marker::PhantomData,
    }
  }

  /// The stretch's whole comparison.
  #[inline]
  #[must_use]
  pub const fn range(&self) -> &MongoTimeRangeComparison {
    &self.range
  }

  /// The payload's own comparison.
  #[inline]
  #[must_use]
  pub const fn data(&self) -> &C {
    &self.data
  }
}

impl<P, C: Default> Default for MongoTimeRangedComparison<P, C> {
  #[inline]
  fn default() -> Self {
    Self::new()
  }
}

/// The lowering: the stretch at the address it was given, then the payload one key below.
///
/// The stretch's keys splice into the holder's own document path because its entry in `SEGMENTS`
/// lends no name — the same flattening the SQL side spells with a shorter prefix, in this family's
/// dotted spelling.
impl<P, C: ComplexComparison<Mongo>> ComplexComparison<Mongo> for MongoTimeRangedComparison<P, C> {
  #[inline]
  fn conjuncts(&self) -> usize {
    ComplexComparison::<Mongo>::conjuncts(&self.range)
      + ComplexComparison::<Mongo>::conjuncts(&self.data)
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: <Mongo as Backend>::Builder<'q>,
  ) -> Result<<Mongo as Backend>::Builder<'q>, <Mongo as Backend>::Error> {
    let builder = self.range.apply(at, builder)?;
    let data = at.frame(DATA);

    self.data.apply(data.at(), builder)
  }
}

/// The width, from [`TimeRanged<P>`](super::TimeRanged)'s own row — read rather than restated, which
/// is what the `P` parameter is for.
impl<P: ColumnKind, C: ComplexComparison<Mongo>> CompositeComparison<Mongo>
  for MongoTimeRangedComparison<P, C>
{
  const SEGMENTS: &'static [crate::ColumnShape] = <TimeRanged<P> as ColumnKind>::SEGMENTS;
}

/// **THE ROUTING ROW**, and it reaches every payload whose filter routes on its own type — the SQL
/// twin's shape and its argument, which is that a width is the domain type's.
impl<TF, P> ToDatabaseComparison<TimeRanged<P>, Mongo> for TimeRangedFilter<TF>
where
  TF: ToDatabaseComparison<P, Mongo>,
  P: ColumnKind,
{
  type Comparison = MongoTimeRangedComparison<P, TF::Comparison>;
}

/// The crossing, and the error is the PAYLOAD's — the stretch half is provably infallible, so every
/// refusal this crossing can produce is one the payload family already names.
impl<P, TF: Default, C: TryFromFilter<TF>> TryFromFilter<TimeRangedFilter<TF>>
  for MongoTimeRangedComparison<P, C>
{
  type Error = C::Error;

  fn try_from_filter(filter: TimeRangedFilter<TF>) -> Result<Self, Self::Error> {
    let TimeRangedFilter { range, data } = filter;

    let range = MongoTimeRangeComparison::try_from_filter(range.unwrap_or_default())
      .unwrap_or_else(|infallible| match infallible {});

    Ok(Self {
      range,
      data: C::try_from_filter(data.unwrap_or_default())?,
      payload: core::marker::PhantomData,
    })
  }
}