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 filter-kind → comparison-type map: [`ToDatabaseComparison`], the refinement an emitted
//! predicate CROSSES through ([`ToCrossedComparison`]), the refinement of it an `flatten` column
//! crosses through ([`ToFlattenedComparison`]), and the map a REVERSE RELATION position crosses
//! through ([`ToRelatedComparison`]).

use super::{At, Backend, ComplexComparison, CompositeComparison, TryFromFilter};

/// A filter kind mapped to the comparison it crosses into for one storage type and one backend.
///
/// Type-level and method-free, for the reason [`ToGraphqlFilter`](crate::ToGraphqlFilter) is: there
/// is nothing here to no-op. The counterpart in the reference implementation is value-level, and
/// every one of its blanket impls is a function whose two branches return the same value, one of
/// them carrying a comment that the line exists to silence a lint. A trait with no method cannot
/// acquire that shape.
///
/// # Keyed on the filter, not on the storage type
///
/// Keying on the storage type loses the operator set — `TextFilter<String>` and
/// `ScalarFilter<String>` would collapse onto one comparison, and the twelve substring operators
/// would have nowhere to go. The filter kind is what carries the question.
///
/// # `V` is a parameter even where the storage form looks fixed
///
/// A boolean column's storage is a DECLARATION, not a law: the same [`BooleanFilter`] may be
/// declared to store as a native `BOOLEAN`, as `0`/`1`, or as `'Y'`/`'N'`. So even the kind with no
/// type parameter of its own crosses into a comparison that has one.
///
/// # What the codegen emits, and why it stays a projection
///
/// ```text
/// <<FieldTy as ToGraphqlFilter>::Filter as ToDatabaseComparison<StorageTy, Db>>::Comparison
/// ```
///
/// Hard-coding a kind → comparison table in the emitter would close a surface downstream extends: a
/// downstream filter kind arrives with its own row here and needs no emitter change.
///
/// # The comparison a crossing names can be LOWERED, and that is an item bound
///
/// `Comparison: ComplexComparison<Db>` is a promise every row keeps, and it is stated here because
/// it cannot be stated anywhere else. A caller holding the projection —
/// `<F as ToDatabaseComparison<V, Db>>::Comparison`, which is what an expansion writes for every
/// column — has a CONCRETE self type, so rustc resolves it through the impl that defines it and a
/// bound written at the caller demands whatever THAT impl demands of `Db`. Five spellings were
/// measured and none serves every kind at once: the flat kinds cross under `Db: sqlx::Database`
/// while [`ListFilter`](crate::ListFilter)'s and [`SetFilter`](crate::SetFilter)'s cross under
/// [`CollectionStorage<V>`](crate::comparison::sql::CollectionStorage), so no single `Db` bound
/// is spellable, and a helper trait carrying both capabilities is PROVED rather than assumed
/// through its own blanket and fails on the same kinds.
///
/// On the associated type the obligation moves to the party that can discharge it. Each row proves
/// the promise for its own reason — at a concrete dialect, where the dialect's `ComplexComparison`
/// impl exists — and a caller states only the crossing.
///
/// `Db: Backend` follows from naming [`ComplexComparison`] at all, which is keyed on the BACKEND
/// rather than on a driver's `Database`. It is not elaborated: a `where F: ToDatabaseComparison<V,
/// Db>` at a caller is well-formed only with `Db: Backend` beside it, which is a bound about the
/// database and not about a column's crossing, and is one every lowering already carries because
/// [`ComplexComparison::apply`](crate::ComplexComparison::apply) spells `Db::Builder`.
///
/// # The CROSSING is not a second item bound here, and the reason is no longer the edge table
///
/// `Comparison: TryFromFilter<Self>` reads like the other half of the same promise and is not
/// stated. **The reason it used to carry is retired and the record should say which.** It read that
/// the crossing was REFUTED by the kind with two storage strategies, because a collection's crossing
/// lands on [`SqlEdgeComparison`](crate::comparison::sql::SqlEdgeComparison) wherever a dialect keeps
/// a value list in an edge table and that comparison was constructed WITH its addressing — none of
/// which is in a filter. It no longer is: the addressing arrives at
/// [`apply`](crate::ComplexComparison::apply) through [`At`](crate::At), and both edge kinds
/// implement [`TryFromFilter`](crate::TryFromFilter) like every other kind.
///
/// What remains is the paragraph above, applied to the other trait: a bound spelled at a CALLER
/// resolves through the impl that defines the projection, so it demands whatever that impl demands
/// of `Db`, and no one spelling serves both the flat kinds and the collection ones. The promise also
/// cannot travel down to [`CollectionStorage`](crate::comparison::sql::CollectionStorage) as the
/// lowering one does, because the filter's DOMAIN type is not a parameter there and no `for<D>` over
/// types exists to state it with.
///
/// So a caller gets the LOWERING from the crossing, and the construction arrives through
/// [`ToCrossedComparison`] instead — a refinement whose two METHODS return the projection rather
/// than naming it in a bound, which is the one place the normalisation above does not happen.
/// Whether the MAP itself can carry a second item bound is still open rather than refuted; it is no
/// longer the only way to the crossing, and so no longer worth paying a row for.
///
/// # What the wall is really about is the DIALECT, and a caller at a concrete one walks past it
///
/// A caller that names the BACKEND rather than carrying it as a parameter normalises the projection
/// and needs no bound at all: the comparison resolves to a kind, that kind's
/// [`TryFromFilter`](crate::TryFromFilter) row applies, and its inherent `try_from_filter_with` is
/// callable. `ingraph-derive`'s INTERFACE expansion is exactly that caller — an interface's engine
/// face is per database, so its crossing is written per database — and the same code at a generic
/// `Db` fails with the four errors above, measured. The question that left open — whether a caller
/// which must stay dialect-GENERIC can reach the crossing at all — is now **answered yes**, and the
/// item bound was not what answered it: see [`ToCrossedComparison`], where the crossing is a method
/// and so is never a bound the wall can be reached through.
///
/// [`BooleanFilter`]: crate::BooleanFilter
pub trait ToDatabaseComparison<V, Db: Backend> {
  /// The comparison a filter of this kind crosses into, holding `V` and lowering for `Db`.
  type Comparison: ComplexComparison<Db>;
}

/// **The two rows an emitted predicate SPENDS on one column, reached without naming the comparison**
/// — the map above refined to a crossing that really builds, with the two methods that build it.
///
/// A wire-faced holder writes one spelling for every kind of column: *cross what the client sent*,
/// or *hold the empty comparison where the client asked nothing*. Those are the two rows, and this
/// is the one form of them an expansion can state at a `Db` it has not named.
///
/// # Why they are METHODS, and it is [`ToLoweredRelatedComparison`]'s reason at the column
///
/// An emitted comparison holds each member at `<F as ToDatabaseComparison<V, Db>>::Comparison` and
/// has to cross into it while `Db` is still a parameter. Every way of SAYING *that projection
/// crosses* puts the projection where rustc has to RESOLVE it, and resolving it means selecting the
/// impl that defines it, which means proving whatever THAT impl demands of the database. Four
/// spellings measured, all reporting the SQL family's own clause back at the caller:
///
/// ```text
/// error[E0271]: type mismatch resolving `<Db as Backend>::Builder<'q> == SqlConjunction<'q, Db>`
/// error[E0277]: the trait bound `Db: sqlx::Database` is not satisfied
/// error[E0277]: `<Db as Backend>::Buffer` doesn't implement `std::fmt::Display`
/// error[E0277]: `u32` has no carrier in `Db`: no column of that dialect can hold one
/// ```
///
/// — the predicate written with the projection as its SELF TYPE; the same written as an
/// associated-type bound on the map; the same again moved onto a packaging trait's SUPERTRAIT, which
/// normalises exactly as eagerly; and the concrete-comparison-name form, which never was a different
/// question because what is concrete in that head is the BACKEND.
///
/// So the supertrait here is BARE. A caller states `F: ToCrossedComparison<V, Db>` — self type the
/// FILTER — and elaboration hands back `F: ToDatabaseComparison<V, Db>`, a predicate with nothing in
/// it to normalise. The projection appears only in the signatures below, where it arrives RIGID and
/// is the very type the emitted member already carries, so the two agree by SPELLING and never by
/// normalisation.
///
/// # ONE row for every kind, and the measurement is why
///
/// The design this closes proposed a table with one row per filter kind, each row restating that
/// kind's own lowering clause at the crossing — the spelling that made a dialect-generic pair
/// compile when it was first measured (`Db: sqlx::Database + for<'q> Backend<Builder<'q> =
/// SqlConjunction<'q, Db>, Buffer: Display>` and `V: Carrier<Db> + ColumnKind` for a scalar, and
/// `Db: CollectionStorage<V, VF>` plus that strategy's own crossing for a collection). That table is
/// real and it compiles; what it costs is that **every type argument in it has to be spelled
/// CONCRETELY**. A projection standing in a `where` clause is not normalised against an obligation
/// spelled with the type it resolves to, measured — `<<u32 as DefaultMarker>::Marker as
/// ToGraphqlFilter>::ColumnFilter` in the clause leaves `Db: CollectionStorage<Vec<u32>,
/// ScalarFilter<u32>>` unsatisfied — so an emitter splicing such rows would have to know each
/// column's KIND, its ELEMENT and that element's own filter type, from tokens. That is the
/// hard-coded kind table [`ToDatabaseComparison`]'s own note refuses, and the tier that would spend
/// it admits no interpretation word to read a kind off in the first place.
///
/// Moving the crossing onto a method removes the reason for the table rather than the table's
/// content: with the projection off the bound there is nothing per-kind left to state, and this
/// row's clause is the two rows THEMSELVES — `Comparison: TryFromFilter<Self> + Default`, stated
/// once, proved per kind by the kind's own impls. A per-kind row could not state less, because it
/// would have to prove exactly this; it could only be FORGOTTEN by the next kind to arrive.
///
/// # Blanket-implemented, deliberately — a downstream joins one level down
///
/// [`ToFlattenedComparison`]'s arrangement, for its reason: nothing implements this by hand, and a
/// downstream filter kind joins by giving its comparison [`TryFromFilter`] and [`Default`], which
/// are the facts this refinement is ABOUT. A kind that has them is crossable the moment it has a
/// [`ToDatabaseComparison`] row, with no second registration to remember.
///
/// # Where the refusal lands, and what it says
///
/// At the first use that names the comparison at a real backend, which is the deferral the whole
/// crossing already follows. A fragment holding a column no dialect can store still compiles; the
/// record that stores one at SQLite is where the message below is reported, naming the filter kind
/// and the database rather than a projection nobody wrote.
#[diagnostic::on_unimplemented(
  message = "`{Self}` has no crossing into a comparison for `{Db}`",
  label = "this column's filter kind cannot be crossed at that database",
  note = "a filter kind is crossable where it has a `ToDatabaseComparison<{V}, {Db}>` row AND \
          the comparison that row names has `TryFromFilter` from `{Self}` and `Default`",
  note = "a COLLECTION column reaches its row through `CollectionStorage<{V}, …>`, whose \
          element form the declaration names per database with `<db>(type = \"…\")`"
)]
pub trait ToCrossedComparison<V, Db: Backend>: ToDatabaseComparison<V, Db> + Sized {
  /// Cross this filter into the comparison the map names for it.
  ///
  /// # Errors
  ///
  /// Whatever the kind's own crossing refused with, boxed — the type an emitted crossing answers
  /// with at every tier, because a row's columns may each fail differently and no narrower type
  /// names all of them.
  fn cross(self) -> Result<Self::Comparison, Box<dyn core::error::Error + Send + Sync + 'static>>;

  /// The EMPTY comparison of this kind: what a column the client said nothing about lowers to.
  ///
  /// Not the same as asking for nothing to match — an empty comparison renders no conjunct.
  fn empty() -> Self::Comparison;
}

/// The row itself, and the one thing on it that is a DIAGNOSTIC decision rather than a typing one.
///
/// [`do_not_recommend`](diagnostic::do_not_recommend) is what makes the message above reachable at
/// all. With a blanket in the way rustc reports the INNERMOST unmet obligation, so a kind whose
/// comparison lacks `Default` was two errors about `Default` and `FromFilter` on a type the reader
/// never wrote, with the trait itself appearing only as a `required for …` note — precisely the
/// silent `E0277` this refinement exists to replace. Measured both ways, and the attribute is a win
/// twice over: the direct case becomes the written sentence, and the COLLECTION case — where the
/// real cause is a missing carrier one tier further down — gains *`ListFilter<u32,
/// ScalarFilter<u32>>` has no crossing into a comparison for `Sqlite`* beside the carrier's own
/// message rather than instead of it.
#[diagnostic::do_not_recommend]
impl<F, V, Db> ToCrossedComparison<V, Db> for F
where
  Db: Backend,
  F: ToDatabaseComparison<
      V,
      Db,
      Comparison: TryFromFilter<
        F,
        Error: Into<Box<dyn core::error::Error + Send + Sync + 'static>>,
      > + Default,
    >,
{
  #[inline]
  fn cross(self) -> Result<Self::Comparison, Box<dyn core::error::Error + Send + Sync + 'static>> {
    <Self::Comparison as TryFromFilter<Self>>::try_from_filter(self).map_err(Into::into)
  }

  #[inline]
  fn empty() -> Self::Comparison {
    Default::default()
  }
}

/// A RELATION position mapped to the comparison it crosses into for one backend, holding the far
/// side's own predicate.
///
/// # It is [`ToDatabaseComparison`]'s shape for a position whose parameter is a PREDICATE
///
/// Every argument that map's own note makes holds here, one parameter shorter. A column crossing is
/// keyed on the FILTER and parameterised by the type this database STORES; a relation position is
/// parameterised by the far side's COMPARISON, which is the only thing it carries — a reverse
/// position stores nothing at all, and a forward one's stored column is already the column crossing's
/// business.
///
/// BOTH DIRECTIONS go through it, told apart by the self type:
/// [`RelatedFilter`](crate::RelatedFilter) is the reverse position's quantifier vocabulary and
/// answers a derived kind; [`RefFilter`](crate::RefFilter) is a `ref` column's widened filter and
/// answers an OPTIONAL semi-join through the reference. One map, two wire shapes.
///
/// # It exists so an UNGATED struct can name a GATED kind
///
/// A record's comparison is generic in its database and is emitted at TOP LEVEL, outside every
/// backend gate — a declaration naming one dialect must not need that dialect's driver to compile.
/// [`comparison::sql`](crate::comparison::sql) is `#[cfg(feature = "sqlx")]`, so a member spelled
/// `SqlDerivedComparison<C, DB>` in that struct names a path a lean build has not got, and the
/// refusal lands inside an expansion its author cannot edit. Spelled as a PROJECTION through this
/// map, the member names one ungated trait and rustc resolves it to the family's kind at whatever
/// dialect a caller reaches it through.
///
/// # It carries NO ITEM BOUND, and the reason is MEASURED
///
/// It used to promise `Comparison: ComplexComparison<Db>`, which is the fact a record's own lowering
/// needs about each relation member. A promise costs the row that keeps it: the SQL row proved it by
/// demanding `C: CollapsibleComparison<Db>` of the far side's predicate — **and that turns *this
/// member lowers* into a demand on the NEIGHBOUR made wherever the projection is NAMED**, since a
/// struct holding the projection carries the map's bound in its own `where` clause.
///
/// On the CANONICAL PAIR that closes into a cycle. `Clip` holds a `ref` at `Reel` and `Reel` holds
/// the reverse position back — the ordinary shape of one relation, and this crate's own fixture — so
/// naming `ClipSqliteComparison<Sqlite>` asks `Box<ReelSqliteComparison<Sqlite>>` to collapse, which
/// asks whether `ReelSqliteComparison<Sqlite>` is even SIZED, which normalises its own reverse
/// member, which asks `ClipSqliteComparison<Sqlite>` to lower. Measured, at both declarations:
/// *overflow evaluating the requirement `ReelSqliteComparison<Sqlite>: MetaSized`*. **Boxing does
/// not fix it** — the pointer cuts the SIZE recursion and the trait obligations close the loop one
/// level above.
///
/// With no item bound the rows ask nothing of `C`, so the projection normalises on the dialect alone
/// and the member's size falls out of the `Box` it already holds. The promise did not disappear; it
/// moved to [`ToLoweredRelatedComparison`], which is what a record's lowering states and spends.
///
/// # The FAMILIES are told apart by `Db`, and the head bound is what does it
///
/// `Db: sqlx::Database` leads the SQL row's clause for the coherence reason
/// [`ToDatabaseComparison`]'s scalar row states: [`Backend`] is a trait this crate declares, so a
/// local `Mongo` implements it and the two rows would overlap on that bound alone. It is now the
/// WHOLE of that clause — with nothing to prove about the comparison it names, a row owes only the
/// bound that keeps it from overlapping its sibling.
pub trait ToRelatedComparison<C, Db: Backend> {
  /// The comparison this position crosses into, quantifying `C` over the far side's rows.
  ///
  /// Bound by nothing — see the trait's note for the cycle an item bound here closes, and
  /// [`ToLoweredRelatedComparison`] for where the promise it used to carry is kept instead.
  type Comparison;
}

/// **The lowering of a relation position, reached through the position's own FILTER** — the map
/// above, refined to a crossing whose comparison really renders, with the two methods that render it.
///
/// # Why the fact is METHODS here rather than a bound anywhere
///
/// A record's emitted lowering holds its relation member at
/// `<F as ToRelatedComparison<C, Db>>::Comparison` and has to apply it, at a `Db` that is still a
/// parameter. Every way of SAYING *that projection lowers* puts the projection where rustc resolves
/// it through the impl that defines it, and what comes back is what the SQL row demands of `Db` —
/// `sqlx::Database`, a pinned `Builder`, a pinned `Buffer` — none of which a dialect-generic
/// expansion may write. Three spellings were measured on the same declarations and failed
/// identically:
///
/// - the plain predicate, `<F as ToRelatedComparison<C, Db>>::Comparison: ComplexComparison<Db>`;
/// - the associated-type bound, `F: ToRelatedComparison<C, Db, Comparison: ComplexComparison<Db>>`;
/// - the same bound moved onto a refinement's SUPERTRAIT, which normalises just as eagerly.
///
/// That is the wall [`ToFlattenedComparison`] records for its own refinement, three measurements over.
/// The way past it is the one that trait already takes — put the projection somewhere rustc has no
/// reason to normalise — and here the projection can be moved off the CALL as well as off the bound:
/// the comparison arrives as an ARGUMENT, so an expansion writes
/// `<F as ToLoweredRelatedComparison<C, Db>>::apply(&self.member, at, builder)` and names no
/// projection at all.
///
/// # It is what keeps a MUTUAL relation compilable
///
/// The neighbour's demand lives on THIS impl, which is proven where a record's lowering is proven —
/// at a concrete dialect — rather than wherever a comparison type is named. So `Clip` may hold a
/// `ref` at `Reel` while `Reel` holds the reverse position back, at any depth a client writes: the
/// obligation reaches the neighbour's own `CollapsibleComparison` impl, which is emitted CONCRETELY
/// at the dialect and carries only its id's predicate, and terminates there in one step.
///
/// # Blanket-free, deliberately
///
/// [`ToFlattenedComparison`] is blanket-implemented because its refinement is an AUDIT with nothing to
/// carry. This one carries a rendering, and a rendering is per FAMILY: the SQL row threads a
/// `SqlConjunction` and MongoDB's builds `$lookup` stages. So each family writes its own row beside
/// its `ToRelatedComparison` one, and a third family joins by writing both.
pub trait ToLoweredRelatedComparison<C, Db: Backend>: ToRelatedComparison<C, Db> {
  /// How many conjuncts `comparison` renders — [`ComplexComparison::conjuncts`]'s answer, reached
  /// without naming the type that gives it.
  fn conjuncts(comparison: &Self::Comparison) -> usize;

  /// Render `comparison`'s conjuncts for `at` into `builder`, and give the builder back —
  /// [`ComplexComparison::apply`], reached the same way.
  ///
  /// # Errors
  ///
  /// Whatever the position's own lowering refuses with: a relation nested past the aliases minted
  /// for it, or a row addressed by more than one column.
  fn apply<'q>(
    comparison: &'q Self::Comparison,
    at: At<'_>,
    builder: Db::Builder<'q>,
  ) -> Result<Db::Builder<'q>, Db::Error>;
}

/// The crossing a `flatten` column makes: the same map, refined to a comparison that occupies MORE
/// THAN ONE column.
///
/// Blanket-implemented, so nothing implements it by hand and a downstream joins by implementing
/// [`CompositeComparison`] on its comparison. What it exists for is the SPELLING — being the one form
/// of the requirement an expansion can write.
///
/// # Why the obvious spelling is unwritable, measured
///
/// The requirement is *this column's comparison is a composite*, and the comparison is
/// `<F as ToDatabaseComparison<V, Db>>::Comparison`. An emitted comparison struct is generic over its
/// database, so `Db` is a PARAMETER there — and a `where` clause whose self type is that projection
/// makes rustc resolve it through the impl that DEFINES it rather than through the crossing the same
/// clause assumes. What comes back is whatever that impl demands of `Db`: for this crate's flat kinds
/// `Db: sqlx::Database`, `V: Carrier<Db>` and `Db::Builder<'q> == SqlConjunction<'q, Db>`, none of
/// which an expansion may write and the last of which no `Db` bound can supply. It is the same wall
/// that keeps `Debug`, `Clone` and `Default` off a generated comparison, and stating the bound
/// through an associated-type bound (`ToDatabaseComparison<V, Db, Comparison: …>`) hits it
/// identically — measured, both spellings, at a generic `Db`.
///
/// A blanket impl moves the projection OFF the self type: the emitted predicate is
/// `F: ToFlattenedComparison<V, Db>`, whose self type is the filter, so nothing is normalised until a
/// caller names a dialect — and there `Db` is concrete, the projection resolves, and the refusal is
/// [`CompositeComparison`]'s `E0277` with its own wording.
///
/// # Where the refusal therefore lands
///
/// At the first use that names the comparison at a real backend, not at the declaration. That is not
/// a weakening of the rule but the rule the whole crossing already follows: `ToDatabaseComparison`
/// itself is an ASSUMPTION in a generated comparison's `where` clause, so a column whose type no
/// database can store also compiles until something names a dialect. One deferral, not two.
///
/// # It carries the crossing as its SUPERTRAIT
///
/// So an emitted column states one bound rather than two, and the plain crossing arrives by
/// elaboration — which is what keeps the projection resolvable in the field type beside it.
pub trait ToFlattenedComparison<V, Db: Backend>: ToDatabaseComparison<V, Db> {}

impl<F, V, Db> ToFlattenedComparison<V, Db> for F
where
  Db: Backend,
  F: ToDatabaseComparison<V, Db>,
  F::Comparison: CompositeComparison<Db>,
{
}

#[cfg(test)]
mod tests;