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 item bound from the CALLER's side: what a holder of the crossing's projection may do with
//! it, and what it does not have to say to do it.
//!
//! Every function here is generic in the filter kind, the storage type and the database, and none
//! of them is what an expansion could not write. That is the whole assertion: these compile, and
//! the same bodies written against an unbounded `type Comparison` do not — the projection has a
//! concrete self type, so a bound stated HERE resolves through the impl that defines it and demands
//! whatever that impl demands of `Db`, which differs per kind.
//!
//! Most items here gate on `sqlite`, the SQL family's base feature, because a lowering needs a
//! [`Backend`] concretely NAMED — `Emitted`, `lower`, `lower_pair` and the tests around them all
//! reach for a `sqlx` dialect or its comparison types. The roster helper (`crosses`, below) is the
//! one exception: its own bound is `Db: Backend` and nothing narrower, so it is compiled for every
//! family, and each roster opens its own family's feature before naming a concrete `Db` — `sqlite`
//! and `postgres` for the SQL rows, `mongo` for MongoDB's.

#[cfg(feature = "sqlite")]
use crate::{
  At, Backend, ComplexComparison, FieldName, RecordAddress, ScalarFilter, TextFilter,
  comparison::{
    ToDatabaseComparison, TryFromFilter,
    sql::{SqlConjunction, SqlScalarComparison, SqlTextComparison},
  },
};

/// The row every lowering here constrains, as an expansion states one: beside the schema, `const`.
#[cfg(feature = "sqlite")]
const ROW: RecordAddress = RecordAddress::new(FieldName::new("track"), &[FieldName::new("id")]);

/// The SHAPE an expansion emits, written by hand: one field per column at the crossing's
/// projection, one crossing predicate per column, and `Db` a bare parameter.
///
/// `Db: Backend` is what this shape costs beyond the crossings, and it is not optional — a
/// `where F: ToDatabaseComparison<V, Db>` is well formed only beside it, so without it EVERY
/// expansion is `E0277: the trait bound Db: Backend is not satisfied`, reported at the derive.
/// That is one predicate for an emitter to add and a name it may write, unlike the
/// `Db: sqlx::Database` a per-column bound would have demanded; this struct is the standing check
/// that the one predicate is enough.
#[cfg(feature = "sqlite")]
struct Emitted<Db>
where
  Db: Backend,
  ScalarFilter<i64>: ToDatabaseComparison<i64, Db>,
  TextFilter<String>: ToDatabaseComparison<String, Db>,
{
  bitrate: <ScalarFilter<i64> as ToDatabaseComparison<i64, Db>>::Comparison,
  codec: <TextFilter<String> as ToDatabaseComparison<String, Db>>::Comparison,
}

/// And the impl the emitter writes beside it, whose body needs no bound the struct did not already
/// carry.
///
/// Each column pushes a FRAME, because a whole entity's comparison is the composite case: it is
/// handed ONE address and each of its columns is one segment below it.
///
/// It is a MIRROR rather than a duplicate of `ingraph-codegen`'s emission: this file compiles
/// inside the framework, where a change to the trait's shape reddens it immediately, and it is what
/// the emitter's own shape was written against.
#[cfg(feature = "sqlite")]
impl<Db> ComplexComparison<Db> for Emitted<Db>
where
  Db: Backend,
  ScalarFilter<i64>: ToDatabaseComparison<i64, Db>,
  TextFilter<String>: ToDatabaseComparison<String, Db>,
{
  fn conjuncts(&self) -> usize {
    self.bitrate.conjuncts() + self.codec.conjuncts()
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: Db::Builder<'q>,
  ) -> Result<Db::Builder<'q>, Db::Error> {
    let bitrate = at.frame(FieldName::new("bitrate"));
    let builder = self.bitrate.apply(bitrate.at(), builder)?;
    let codec = at.frame(FieldName::new("codec"));
    self.codec.apply(codec.at(), builder)
  }
}

/// Lower one column held at the crossing's projection.
///
/// The SIGNATURE is the assertion. `Db: Backend` is about the database rather than about the
/// column — it is what naming `Db::Builder` costs, and every lowering carries it — and
/// `F: ToDatabaseComparison<V, Db>` is the crossing an expansion writes anyway, because it is what
/// makes the field's type well formed. There is no third predicate, and before the item bound the
/// only third predicate that would have worked was one no expansion may write.
#[cfg(feature = "sqlite")]
fn lower<'q, F, V, Db>(
  column: &'q <F as ToDatabaseComparison<V, Db>>::Comparison,
  at: At<'_>,
  builder: Db::Builder<'q>,
) -> Result<Db::Builder<'q>, Db::Error>
where
  Db: Backend,
  F: ToDatabaseComparison<V, Db>,
{
  column.apply(at, builder)
}

/// The whole subtree's conjunct count, over the same projection.
///
/// The second of the trait's two methods, and the one a generated `conjuncts` sums.
#[cfg(feature = "sqlite")]
fn conjuncts<F, V, Db>(column: &<F as ToDatabaseComparison<V, Db>>::Comparison) -> usize
where
  Db: Backend,
  F: ToDatabaseComparison<V, Db>,
{
  column.conjuncts()
}

/// Two columns of DIFFERENT crossings, threading ONE builder — which is the body a generated
/// comparison's own `apply` has.
///
/// The two kinds cross under bounds that disagree, and neither is named here. That is what the item
/// bound moved: the obligation is the DEFINING row's, discharged where the dialect is concrete, and
/// this caller states only that each column crossed.
#[cfg(feature = "sqlite")]
fn lower_pair<'q, F0, V0, F1, V1, Db>(
  first: (&'q <F0 as ToDatabaseComparison<V0, Db>>::Comparison, At<'_>),
  second: (&'q <F1 as ToDatabaseComparison<V1, Db>>::Comparison, At<'_>),
  builder: Db::Builder<'q>,
) -> Result<Db::Builder<'q>, Db::Error>
where
  Db: Backend,
  F0: ToDatabaseComparison<V0, Db>,
  F1: ToDatabaseComparison<V1, Db>,
{
  let builder = lower::<F0, V0, Db>(first.0, first.1, builder)?;
  lower::<F1, V1, Db>(second.0, second.1, builder)
}

/// A scalar column and a text column, held at their projections and lowered through one
/// accumulator.
///
/// The two are not the same kind on purpose: a scalar's lowering is ONE generic impl over the
/// dialects and a text column's is three concrete ones, and a caller holding both projections
/// distinguishes them nowhere.
#[cfg(feature = "sqlite")]
#[test]
fn columns_held_at_the_projection_lower_with_no_predicate_about_it() {
  let bitrate: SqlScalarComparison<i64, sqlx::Sqlite> =
    TryFromFilter::try_from_filter(ScalarFilter::<i64>::new().with_eq(1i64)).unwrap();
  let codec: SqlTextComparison<String, sqlx::Sqlite> =
    TryFromFilter::try_from_filter(TextFilter::<String>::new().with_eq("av1".to_owned())).unwrap();

  assert_eq!(
    conjuncts::<ScalarFilter<i64>, i64, sqlx::Sqlite>(&bitrate),
    1
  );
  assert_eq!(
    conjuncts::<TextFilter<String>, String, sqlx::Sqlite>(&codec),
    1
  );

  let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
  let bitrate_at = At::new(&ROW).frame(FieldName::new("bitrate"));
  let codec_at = At::new(&ROW).frame(FieldName::new("codec"));
  let written = lower_pair::<ScalarFilter<i64>, i64, TextFilter<String>, String, sqlx::Sqlite>(
    (&bitrate, bitrate_at.at()),
    (&codec, codec_at.at()),
    SqlConjunction::new(&mut qb),
  )
  .unwrap()
  .written();

  assert_eq!(written, 2);
  assert_eq!(qb.sql(), r#" WHERE "bitrate" = ? AND "codec" = ?"#);
}

/// The emitted shape, built and lowered: two columns of different kinds under one entity name.
///
/// This is the deliverable the item bound exists for — an entity comparison whose fields are
/// projections, whose `apply` threads one accumulator through them, and whose whole bound list is
/// `Db: Backend` and one crossing per column. `ingraph-derive`'s `Pipeline` fixture is the same
/// claim over an expansion; this one holds it inside the crate that declares the trait.
#[cfg(feature = "sqlite")]
#[test]
fn the_emitted_shape_lowers_its_columns_through_one_accumulator() {
  let comparison = Emitted::<sqlx::Sqlite> {
    bitrate: TryFromFilter::try_from_filter(ScalarFilter::<i64>::new().with_gt(1i64)).unwrap(),
    codec: TryFromFilter::try_from_filter(TextFilter::<String>::new().with_eq("av1".to_owned()))
      .unwrap(),
  };

  assert_eq!(ComplexComparison::<sqlx::Sqlite>::conjuncts(&comparison), 2);

  let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
  comparison
    .apply(
      At::new(&ROW).frame(FieldName::new("track")).at(),
      SqlConjunction::new(&mut qb),
    )
    .unwrap();

  assert_eq!(
    qb.sql(),
    r#" WHERE "track_bitrate" > ? AND "track_codec" = ?"#
  );
}

/// **THE KIND ROSTER** — one line per filter kind this crate ships, each asserting that the kind
/// CROSSES: its comparison can be built from it and has an empty value.
///
/// The census, and it is a compile-time one on purpose. A kind whose comparison gains an obligation
/// the crossing cannot discharge — a `Default` that acquires a bound, a `TryFromFilter` that stops
/// applying — takes its own line here red, naming the kind and the database, rather than reaching a
/// declaring crate as an `E0277` about a projection nobody wrote. That is the drift protection the
/// per-kind clause table was proposed for, kept at the one place a kind is SHIPPED.
///
/// `Db` is a parameter and the only bound is `Db: Backend`, so the roster is about the KIND and
/// about neither a dialect nor a FAMILY. This helper is therefore UNGATED — fully qualified rather
/// than importing [`Backend`], since the import above lives behind `sqlite` — and each roster below
/// opens its own family's feature before it names a concrete `Db`.
const fn crosses<F, V, Db>()
where
  Db: crate::Backend,
  F: crate::comparison::ToCrossedComparison<V, Db>,
{
}

/// Every kind, at SQLite.
///
/// The DURATION kind is absent from this dialect's lines rather than from the roster: SQLite ships
/// no `ToDatabaseComparison` row for it, having no interval column for one to land in, so its line
/// is at the second dialect below.
///
/// The COMPOSITE kind is not here and cannot be: a fragment's filter is MINTED by an expansion, so
/// its row is emitted rather than shipped, and `ingraph`'s own crate has no declaration to mint one.
/// `ingraph/tests/fragment_generic_crossing.rs` is that line of the roster, stood on from a
/// declaring crate — which is the only vantage that has one.
#[cfg(feature = "sqlite")]
#[test]
fn every_shipped_filter_kind_crosses() {
  use crate::{
    BooleanFilter, BytesFilter, Confidence, ConfidenceFilter, EnumFilter, FixedBytesFilter,
    ListFilter, Nullable, QuantifiedFilter, ScalarFilter, SetFilter, TextFilter,
  };

  // The VALUE families.
  crosses::<ScalarFilter<i64>, i64, sqlx::Sqlite>();
  crosses::<TextFilter<String>, String, sqlx::Sqlite>();
  crosses::<BytesFilter<Vec<u8>>, Vec<u8>, sqlx::Sqlite>();
  crosses::<FixedBytesFilter<Vec<u8>, 16>, Vec<u8>, sqlx::Sqlite>();
  crosses::<EnumFilter<String>, String, sqlx::Sqlite>();
  // The FLAGS kind is the one line here that a lane can decline, and it is written the way the
  // `jiff` line below is written for the same reason: `FlagsFilter` is exported behind `flags`, so
  // an ungated NAME in the import above is `E0432` in every `sqlite` build that does not also carry
  // that word — which is the whole `--features runtime,sqlite` lane. Fully qualified inside the
  // gate rather than imported, since a `use` list cannot carry a per-item `#[cfg]`.
  #[cfg(feature = "flags")]
  crosses::<crate::FlagsFilter<i64>, i64, sqlx::Sqlite>();
  crosses::<BooleanFilter, bool, sqlx::Sqlite>();
  crosses::<ConfidenceFilter, Confidence<f32>, sqlx::Sqlite>();

  // The three COLLECTION readings, over the ELEMENT form the dialect's strategy holds.
  crosses::<ListFilter<String, TextFilter<String>>, String, sqlx::Sqlite>();
  crosses::<SetFilter<String, TextFilter<String>>, String, sqlx::Sqlite>();
  crosses::<QuantifiedFilter<String, TextFilter<String>>, String, sqlx::Sqlite>();

  // The WRAPPER, which recurses into whichever of the above it holds.
  crosses::<Nullable<ScalarFilter<i64>>, Option<i64>, sqlx::Sqlite>();
  crosses::<Nullable<TextFilter<String>>, Option<String>, sqlx::Sqlite>();
}

/// The same roster at a SECOND dialect, which is what makes the crossing a fact about the KIND
/// rather than about SQLite.
///
/// Postgres is the dialect with a strategy CHOICE, so its collection lines carry the element's own
/// [`PgCollectionStorage`](crate::comparison::sql::PgCollectionStorage) row rather than the
/// dialect's — the one place a kind's crossing depends on something below the kind.
#[cfg(feature = "postgres")]
#[test]
fn the_roster_holds_at_a_second_dialect() {
  use crate::{BooleanFilter, BytesFilter, EnumFilter, Nullable, ScalarFilter, TextFilter};

  crosses::<ScalarFilter<i64>, i64, sqlx::Postgres>();
  crosses::<TextFilter<String>, String, sqlx::Postgres>();
  crosses::<BytesFilter<Vec<u8>>, Vec<u8>, sqlx::Postgres>();
  crosses::<EnumFilter<String>, String, sqlx::Postgres>();
  crosses::<BooleanFilter, bool, sqlx::Postgres>();
  crosses::<Nullable<ScalarFilter<i64>>, Option<i64>, sqlx::Postgres>();
  // The DURATION kind's line, and it is here rather than above because SQLite ships no duration
  // row at all: that dialect has no interval column for one to land in.
  #[cfg(feature = "jiff")]
  crosses::<crate::DurationFilter, crate::PgDuration, sqlx::Postgres>();
}

/// The same roster at the MONGODB family — five kinds rather than the SQL family's twelve, matching
/// exactly what a throwaway probe measured before this test promoted it (the clause-table knife's
/// report, 呈裁 #6: `ToCrossedComparison<…, Mongo>`, scalar/text/enum/boolean/nullable, rc 0). The
/// SAME kind-generic row that serves a second DIALECT above serves a second FAMILY here, with
/// nothing added at `crosses` or at the trait it calls.
///
/// FIVE IS NOT THE CEILING: this family's own modules also carry `ToDatabaseComparison<_, Mongo>`
/// rows for bytes, fixed-bytes, flags, confidence, duration and the three collection readings. This
/// roster names what the probe measured rather than auditing the rest — extending it to the full
/// dozen is a follow-up, not assumed here.
///
/// `Mongo` takes no per-dialect line the way `DurationFilter` does above it: this family is ONE
/// backend rather than a set of dialects, so wherever a kind's row is named here, there is nowhere
/// else to check it.
#[cfg(feature = "mongo")]
#[test]
fn the_roster_holds_at_the_mongo_family() {
  use crate::{BooleanFilter, EnumFilter, Nullable, ScalarFilter, TextFilter};

  crosses::<ScalarFilter<i64>, i64, crate::Mongo>();
  crosses::<TextFilter<String>, String, crate::Mongo>();
  crosses::<EnumFilter<String>, String, crate::Mongo>();
  crosses::<BooleanFilter, bool, crate::Mongo>();
  crosses::<Nullable<ScalarFilter<i64>>, Option<i64>, crate::Mongo>();
}

/// The wrapper composes under the same signature, which is what a nullable column reaches the
/// caller as.
///
/// `Nullable<ScalarFilter<i64>>` crosses to `SqlNullable<SqlScalarComparison<i64, Sqlite>, i64>`, and the
/// caller below is the same generic function — the composite's inner conjunct and its null test both
/// arrive through one `apply` it wrote no bound for.
#[cfg(feature = "sqlite")]
#[test]
fn a_composite_column_lowers_through_the_same_projection() {
  use crate::{Nullable, comparison::sql::SqlNullable};

  let optional: SqlNullable<SqlScalarComparison<i64, sqlx::Sqlite>, i64> =
    TryFromFilter::try_from_filter(
      Nullable::new(ScalarFilter::<i64>::new().with_eq(1i64)).with_null(false),
    )
    .unwrap();

  assert_eq!(
    conjuncts::<Nullable<ScalarFilter<i64>>, Option<i64>, sqlx::Sqlite>(&optional),
    2
  );

  let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
  lower::<Nullable<ScalarFilter<i64>>, Option<i64>, sqlx::Sqlite>(
    &optional,
    At::new(&ROW).frame(FieldName::new("bitrate")).at(),
    SqlConjunction::new(&mut qb),
  )
  .unwrap();

  assert_eq!(
    qb.sql(),
    r#" WHERE "bitrate" = ? AND "bitrate" IS NOT NULL"#
  );
}