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: [`SqlDurationComparison`], and one concrete lowering per dialect that
//! HAS a duration — which is two of the three.

use core::marker::PhantomData;

#[cfg(any(feature = "postgres", feature = "mysql"))]
use core::fmt::Display;

use jiff::SignedDuration;

// Gated with their only user, the shared slot walk below — which is itself gated with the
// per-dialect impls that call it. SQLite is absent from that list on purpose; see the type's note.
#[cfg(any(feature = "postgres", feature = "mysql"))]
use super::{Carrier, SqlConjunction, push_cmp, push_in};
#[cfg(any(feature = "postgres", feature = "mysql"))]
use crate::comparison::{At, Backend, TryFromFilter};
use crate::{
  DurationFilter,
  graphql::filter::{map_operand, map_operands},
};

comparison_kind! {
  /// A [`DurationFilter`]'s storage-side twin: the same eight operators, over the type this database
  /// stores the column as.
  ///
  /// # SQLite has no duration, and the absence is the design
  ///
  /// SQLite ships no temporal type at all, and sqlx 0.9 ships no bridge to one. There is therefore
  /// no `ComplexComparison<Sqlite>` here and no
  /// [`ToDatabaseComparison<V, Sqlite>`](crate::ToDatabaseComparison) for [`DurationFilter`] — a
  /// duration column on SQLite is refused rather than stored as an integer this crate invented for
  /// it. Inventing one would be the lowest-common-denominator move the rest of this family exists
  /// to undo: the column would stop being temporal, and every consumer outside this crate would see
  /// a number.
  ///
  /// The refusal lands at the comparison's INSTANTIATION rather than at the declaration that asks
  /// for it. An emitted comparison is generic over the database and carries one crossing per column
  /// in its own `where` clause, so a record declaring a duration column beside `sqlite` compiles;
  /// the missing row is reported where that comparison is named at the dialect, as
  /// `DurationFilter: ToDatabaseComparison<SignedDuration, Sqlite>` unsatisfied.
  ///
  /// A duration that must live on SQLite is declared as what it actually is — `i64` nanoseconds with
  /// [`ScalarFilter<i64>`](crate::ScalarFilter) — by the field, in the open.
  ///
  /// # `V` is a parameter although the filter has none, and the two live dialects prove it has to be
  ///
  /// [`DurationFilter`] guards exactly one Rust type, so it needs no parameter — the same shape
  /// [`BooleanFilter`](crate::BooleanFilter) has. What a column STORES is a different question, and
  /// the two dialects that answer it answer differently: Postgres binds
  /// [`Duration`](core::time::Duration) or [`PgInterval`](sqlx::postgres::types::PgInterval) into an
  /// `INTERVAL`, MySQL binds [`MySqlDuration`](super::MySqlDuration) into a `TIME`, and neither type
  /// has a row in the other's carrier column.
  ///
  /// # Both store MICROSECONDS, and they disagree about the nanosecond
  ///
  /// `INTERVAL` and `TIME` are microsecond types where this filter's operand is a nanosecond one.
  /// Postgres REFUSES an operand that is not a whole number of microseconds; sqlx's own
  /// `MySqlTime::try_from(Duration)` ROUNDS one. This crate refuses on both, and
  /// [`MySqlDuration`](super::MySqlDuration) is where MySQL's refusal is made — see its note for why
  /// that needed a carrier of its own rather than a paragraph.
  ///
  /// MySQL's `TIME` additionally stops at `±838:59:59`, about 35 days. Comfortable for a media
  /// duration, not for an accumulated total; a column that needs more declares `i64` nanoseconds
  /// through [`DurationFilter::operand_nanos`], which is checked.
  ///
  /// # Both columns are SIGNED, and both dialects now reach that with no declaration
  ///
  /// `INTERVAL` and `TIME` both hold a negative span, and each dialect has a carrier of this crate's
  /// own that carries one: [`PgDuration`](super::PgDuration) writes pure microseconds into an
  /// `INTERVAL`, [`MySqlDuration`](super::MySqlDuration) puts the sign on a `MySqlTime`. Neither
  /// could have been sqlx's — `impl TryFrom<SignedDuration>` for `PgInterval` or `MySqlTime` is
  /// `E0117` from here — which is why both are newtypes rather than rows. `carrier`'s own note
  /// carries the table, including the two carriers a DECLARED converter can still reach and what
  /// each is still for.
  ///
  /// # There is no read path here, so `INTERVAL`'s calendar fields cannot be met
  ///
  /// A `PgInterval` carries `months` and `days` beside `microseconds`, and a value written by
  /// something else with either non-zero has no [`SignedDuration`] to become — a month has no fixed
  /// length without a reference date, which is the same refusal jiff makes at the PARSER. This layer
  /// only ever BINDS: [`PgDuration`](super::PgDuration) fills `microseconds` alone, so nothing here
  /// can produce such a value and nothing here decodes one. The refusal that case needs belongs to
  /// whatever reads a row back, and no such thing has crossed into this crate.
  ///
  /// COMPARING against one is a different question and is settled: Postgres normalises both sides of
  /// an interval comparison through one convention, so a pure-microseconds operand orders exactly
  /// against a mixed-field column. Measured, and recorded at [`PgDuration`](super::PgDuration).
  ///
  /// # One crossing, a lowering per dialect
  ///
  /// 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) — and it is generic over
  /// the database, because converting an operand is the same act wherever it lands. The LOWERING is
  /// concrete per dialect, because what a dialect can store is not.
  SqlDurationComparison {
    one { eq, ne, gt, gte, lt, lte }
    many { in_, not_in }
  }
}

impl<V, Db> SqlDurationComparison<V, Db> {
  /// Cross a [`DurationFilter`] into this comparison, converting each operand with `f`.
  ///
  /// The entry point a DECLARED converter uses, and — see the type's own note — the only place a
  /// duration's operands can be mapped at all.
  ///
  /// Every converter this crate offers for it is CHECKED, and each refuses a different thing:
  /// `PgDuration::try_from` refuses sub-microsecond precision and a microsecond count past `i64`,
  /// `MySqlDuration::try_from` refuses sub-microsecond precision and MySQL's 35-day ceiling,
  /// `Duration::try_from` refuses a NEGATIVE operand, and [`DurationFilter::operand_nanos`] refuses a
  /// duration outside ±`i64` nanoseconds (about ±292 years). None of them rounds — a substituted
  /// operand is a wrong result set reported as a right one, and the substitution leaves no mark on
  /// the SQL.
  ///
  /// It is also the only route to a raw [`PgInterval`](sqlx::postgres::types::PgInterval), which the
  /// undeclared crossing below cannot reach: sqlx ships no conversion from the operand and no crate
  /// but sqlx or jiff may write one. What that route is FOR is now narrow — a column that must hold
  /// a MIXED-FIELD interval — because the pure-microseconds case has a carrier of its own.
  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)?,
      db: PhantomData,
    })
  }
}

/// The crossing with no declared converter, and it is worth having for both live dialects because
/// each has a default storage type that converts from a [`SignedDuration`] and CHECKS while it does:
/// [`PgDuration`](super::PgDuration) for the Postgres `INTERVAL`,
/// [`MySqlDuration`](super::MySqlDuration) for the MySQL `TIME`.
///
/// That is the whole reason both storage types are newtypes of this crate's rather than sqlx's own:
/// this impl is what an undeclared column reaches, so whatever `TryFrom` it resolves to had better
/// be the checked conversion — and sqlx's types cannot carry one, `impl TryFrom<SignedDuration>` for
/// `PgInterval` or `MySqlTime` being `E0117` from here.
///
/// The bound admits other `V`s and always did: `core::time::Duration` resolves through jiff's own
/// conversion, and a column may name it to move the sub-microsecond refusal to the bind. What no
/// longer has to be declared is the ordinary signed case.
#[cfg(any(feature = "postgres", feature = "mysql"))]
impl<V, Db> TryFromFilter<DurationFilter> for SqlDurationComparison<V, Db>
where
  V: TryFrom<SignedDuration>,
{
  type Error = V::Error;

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

/// The slot walk the two concrete impls share — the eight operators, in the order the struct
/// declares them.
///
/// It is the SCALAR walk with a different struct: every operator this kind carries reduces to
/// `col <op> ?` in both dialects, and the operand goes through [`Carrier`]. What makes the kind
/// concrete-per-dialect is not the SQL but which `V` each dialect admits, and the carrier table is
/// where that is answered — see the type's own note.
// Gated with its only callers, the per-dialect impls below.
#[cfg(any(feature = "postgres", feature = "mysql"))]
fn push_slots<V, Db>(
  comparison: &SqlDurationComparison<V, Db>,
  at: At<'_>,
  out: &mut SqlConjunction<'_, Db>,
) where
  Db: sqlx::Database + Backend<Buffer: Display>,
  V: Carrier<Db>,
{
  if let Some(value) = &comparison.eq {
    push_cmp(out.open(), at, " = ", value, false);
  }
  if let Some(value) = &comparison.ne {
    push_cmp(out.open(), at, " = ", value, true);
  }
  if let Some(value) = &comparison.gt {
    push_cmp(out.open(), at, " > ", value, false);
  }
  if let Some(value) = &comparison.gte {
    push_cmp(out.open(), at, " >= ", value, false);
  }
  if let Some(value) = &comparison.lt {
    push_cmp(out.open(), at, " < ", value, false);
  }
  if let Some(value) = &comparison.lte {
    push_cmp(out.open(), at, " <= ", value, false);
  }
  if let Some(values) = &comparison.in_ {
    push_in(out.open(), at, values, false);
  }
  if let Some(values) = &comparison.not_in {
    push_in(out.open(), at, values, true);
  }
}

#[cfg(feature = "mysql")]
mod mysql;

#[cfg(feature = "postgres")]
mod postgres;

#[cfg(test)]
mod tests;