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
use super::{
  JsonElement, ListCrossingError, SqlListComparison, SqlSetComparison, cross_count, cross_element,
  flatten_list, from_stored, ordering_operator, push_json_list_slots, push_json_set_slots,
};
use crate::{
  ListFilter, TryMapFilter,
  comparison::{
    At, Backend, ComplexComparison, TryFromFilter,
    sql::{
      CollectionOp, SqlConjunction, SqlCountComparison, not_wrapped, push_count_slots,
      push_element_scope, render_column,
    },
  },
};

impl<V, C> SqlListComparison<V, C, sqlx::Sqlite> {
  /// Cross a [`ListFilter`] into a SQLite sequence comparison through ONE converter — see
  /// [`SqlEdgeComparison::try_from_filter_with`](crate::comparison::sql::SqlEdgeComparison::try_from_filter_with)
  /// for what the single converter is and why a declaration gets one.
  ///
  /// # Errors
  ///
  /// As [`try_from_filter_with_element`](Self::try_from_filter_with_element), with `f`'s refusal
  /// standing for both levels of operand. The JSON-ordering refusal keeps its place at the front:
  /// the element filter crosses in the `g` slot, which runs after it.
  pub fn try_from_filter_with<D, VF, E, F>(
    filter: ListFilter<D, VF>,
    f: F,
  ) -> Result<Self, ListCrossingError<E, <C as TryFromFilter<VF::Mapped>>::Error>>
  where
    F: Fn(D) -> Result<V, E>,
    VF: TryMapFilter<D, V>,
    C: TryFromFilter<VF::Mapped>,
  {
    Self::try_from_filter_with_element(filter, &f, |element| {
      let stored = element
        .try_map_filter(&f)
        .map_err(ListCrossingError::Operand)?;
      C::try_from_filter(stored).map_err(ListCrossingError::Element)
    })
    .map_err(flatten_list)
  }

  /// Cross a [`ListFilter`] into a SQLite sequence comparison, converting each ELEMENT with `f` and
  /// the nested ELEMENT FILTER with `g`.
  ///
  /// # Errors
  ///
  /// [`ListCrossingError::JsonOrdering`] when any ordering operator is set — this dialect stores a
  /// collection as JSON and has no element-wise order for one; [`ListCrossingError::Operand`] when
  /// `f` refuses an element; [`ListCrossingError::Element`] when the element filter's own crossing
  /// refuses.
  ///
  /// `g` crosses the ELEMENT filter, and it is a second function rather than a use of `f` because
  /// the two convert different things: `f` maps one ELEMENT into its storage type, while the `any`
  /// slot holds a whole FILTER whose own operands are the element kind's to convert. A caller
  /// holding ONE converter for both is asking [`try_from_filter_with`](Self::try_from_filter_with),
  /// which composes them; the identity crossing below passes [`TryFromFilter::try_from_filter`] and
  /// needs no closure at all.
  pub fn try_from_filter_with_element<D, VF, E, F, X, G>(
    filter: ListFilter<D, VF>,
    f: F,
    g: G,
  ) -> Result<Self, ListCrossingError<E, X>>
  where
    F: FnMut(D) -> Result<V, E>,
    G: FnOnce(VF) -> Result<C, X>,
  {
    // Checked BEFORE the operands convert, as every other crossing in this family checks its
    // refusal: a column that has no answer has none whatever the elements turn into.
    if let Some(operator) = ordering_operator(&filter) {
      return Err(ListCrossingError::JsonOrdering(operator));
    }
    let mut stored = filter.try_map(f).map_err(ListCrossingError::Operand)?;
    let any = cross_element(stored.any.take(), g).map_err(ListCrossingError::Element)?;
    let count = cross_count(stored.count.take()).map_err(ListCrossingError::Cardinality)?;
    Ok(from_stored(stored, any, count))
  }
}

impl<D, VF, V: TryFrom<D>, C: TryFromFilter<VF>> TryFromFilter<ListFilter<D, VF>>
  for SqlListComparison<V, C, sqlx::Sqlite>
{
  type Error = ListCrossingError<V::Error, C::Error>;

  fn try_from_filter(filter: ListFilter<D, VF>) -> Result<Self, Self::Error> {
    Self::try_from_filter_with_element(filter, V::try_from, C::try_from_filter)
  }
}

/// One impl per dialect, because what differs is the LEAF below rather than the walk above:
/// `push_json_list_slots` is this kind's one JSON slot walk and both JSON dialects call it, so the
/// impls cannot come to disagree about which operators render or in what order.
impl<V: JsonElement, C: ComplexComparison<sqlx::Sqlite>> ComplexComparison<sqlx::Sqlite>
  for SqlListComparison<V, C, sqlx::Sqlite>
{
  #[inline]
  fn conjuncts(&self) -> usize {
    Self::conjuncts(self)
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    mut builder: <sqlx::Sqlite as Backend>::Builder<'q>,
  ) -> Result<<sqlx::Sqlite as Backend>::Builder<'q>, <sqlx::Sqlite as Backend>::Error> {
    push_json_list_slots(self, at, &mut builder, push_collection_op);
    push_json_any(self.any.as_ref(), at, &mut builder)?;
    push_json_count(self.count.as_ref(), at, &mut builder);
    Ok(builder)
  }
}

/// The set kind reaches the same leaf through the other walk: what a dialect renders is one
/// vocabulary, and which operators are asked of it is the KIND's.
impl<V: JsonElement, C: ComplexComparison<sqlx::Sqlite>> ComplexComparison<sqlx::Sqlite>
  for SqlSetComparison<V, C, sqlx::Sqlite>
{
  #[inline]
  fn conjuncts(&self) -> usize {
    Self::conjuncts(self)
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    mut builder: <sqlx::Sqlite as Backend>::Builder<'q>,
  ) -> Result<<sqlx::Sqlite as Backend>::Builder<'q>, <sqlx::Sqlite as Backend>::Error> {
    push_json_set_slots(self, at, &mut builder, push_collection_op);
    push_json_any(self.any.as_ref(), at, &mut builder)?;
    push_json_count(self.count.as_ref(), at, &mut builder);
    Ok(builder)
  }
}

/// The `any` slot both walks end with: `json_each` IS an element scope, so the element comparison
/// renders inside it at the one address every scope names its member with.
///
/// # `json_each` DECODES, and the two encodings have to agree
///
/// A collection kept in a SQLite column is JSON TEXT written through [`JsonElement`], and
/// `json_each` hands back each member as the SQL value that token decodes to — an INTEGER for `1`, a
/// REAL for `1.5`, TEXT for `"hdr"`. The element comparison binds through
/// [`Carrier`](crate::comparison::sql::Carrier), which is a different encoding of the same value,
/// and `any` is exact only where the two land on the same SQL value.
///
/// Measured on SQLite 3.51.0, they agree for the NUMBER, BOOLEAN and TEXT vocabularies —
/// `value = ?`, `value > ?` and `value LIKE ?` each admit exactly the rows whose elements match. They
/// do NOT agree for the BYTE ones: `JsonElement` writes a blob as a lowercase hex STRING, so
/// `json_each` yields TEXT where the carrier binds a BLOB, and `X'6162' = '6162'` is false in SQLite.
/// A byte-element collection kept as a JSON column therefore has no usable element scope.
///
/// It is not a strategy a declaration lands in: [`CollectionStorage`](super::CollectionStorage)
/// sends every SQLite collection to an edge table, where the element is a real column bound by the
/// same carrier on both sides and the question does not arise. What reaches here is a collection
/// ALREADY held as a JSON column, which is a comparison written by hand.
fn push_json_any<C>(
  element: Option<&C>,
  at: At<'_>,
  out: &mut SqlConjunction<'_, sqlx::Sqlite>,
) -> Result<(), <sqlx::Sqlite as Backend>::Error>
where
  C: ComplexComparison<sqlx::Sqlite>,
{
  let Some(element) = element else {
    return Ok(());
  };
  let column = render_column::<sqlx::Sqlite>(at);
  push_element_scope(out.open(), element, at, |qb| {
    qb.push("json_each(");
    qb.push(&column);
    qb.push(")");
  })
}

/// The `count` slot both walks end with: `json_array_length` IS this dialect's cardinality, so the
/// count comparison renders against it exactly as a scalar comparison renders against a column.
///
/// It needs no refusal and no `NULL` care of its own. Measured on SQLite 3.51.0:
/// `json_array_length('[]')` is `0`, so `count: { eq: 0 }` admits a row holding the empty array and
/// `count: { lt: 2 }` admits it too — where the Postgres array's `array_length` is `NULL` there and
/// admits neither. A column that is itself `NULL` yields `NULL` and matches nothing, which is the
/// same three-valued answer every other operator gives a `NULL` column.
fn push_json_count(
  count: Option<&SqlCountComparison<i64, sqlx::Sqlite>>,
  at: At<'_>,
  out: &mut SqlConjunction<'_, sqlx::Sqlite>,
) {
  let Some(count) = count else {
    return;
  };
  let column = render_column::<sqlx::Sqlite>(at);
  push_count_slots(count, out, |qb| {
    qb.push("json_array_length(");
    qb.push(&column);
    qb.push(")");
  });
}

fn push_collection_op(
  qb: &mut sqlx::QueryBuilder<sqlx::Sqlite>,
  at: At<'_>,
  op: CollectionOp,
  operand_json: &str,
  negated: bool,
) {
  // Bracketed ONCE for the several places a set expression names the column, which is also what
  // keeps `Each::Column` holding rendered text rather than a name to be rendered later.
  let column = render_column::<sqlx::Sqlite>(at);
  not_wrapped(qb, negated, |qb| match op {
    // A SEQUENCE stores its elements in order, so equality is canonical-text equality of the stored
    // JSON; a SET's stored text depends on insert order, so equality is mutual containment — the
    // operand bound once per direction.
    CollectionOp::SequenceEq => {
      qb.push(&column);
      qb.push(" = ");
      qb.push_bind(operand_json.to_owned());
    }
    CollectionOp::SetEq => {
      let stored = Each::Column(&column);
      let operand = Each::Operand(operand_json);
      qb.push("( ");
      push_contained(qb, &operand, &stored);
      qb.push(" AND ");
      push_contained(qb, &stored, &operand);
      qb.push(" )");
    }
    CollectionOp::Encloses => {
      push_contained(qb, &Each::Operand(operand_json), &Each::Column(&column))
    }
    CollectionOp::EnclosedBy => {
      push_contained(qb, &Each::Column(&column), &Each::Operand(operand_json))
    }
    CollectionOp::Overlaps => {
      push_overlapping(qb, &Each::Column(&column), &Each::Operand(operand_json))
    }
  });
}

/// One side of a `json_each` set expression: the bracketed collection column, which is raw SQL text,
/// or the operand's canonical JSON, which is a bind.
enum Each<'a> {
  Column(&'a str),
  Operand(&'a str),
}

fn push_each(qb: &mut sqlx::QueryBuilder<sqlx::Sqlite>, arg: &Each<'_>) {
  qb.push("json_each(");
  match arg {
    Each::Column(quoted) => {
      qb.push(*quoted);
    }
    Each::Operand(json) => {
      qb.push_bind((*json).to_owned());
    }
  }
  qb.push(")");
}

/// Element containment `sub ⊆ sup`. Both sides go through the same element encoding, so
/// `json_each` value equality is exact; an empty `sub` is vacuously contained.
fn push_contained(qb: &mut sqlx::QueryBuilder<sqlx::Sqlite>, sub: &Each<'_>, sup: &Each<'_>) {
  qb.push("NOT EXISTS (SELECT 1 FROM ");
  push_each(qb, sub);
  qb.push(" WHERE value NOT IN (SELECT value FROM ");
  push_each(qb, sup);
  qb.push("))");
}

/// A non-empty element intersection.
fn push_overlapping(qb: &mut sqlx::QueryBuilder<sqlx::Sqlite>, a: &Each<'_>, b: &Each<'_>) {
  qb.push("EXISTS (SELECT 1 FROM ");
  push_each(qb, a);
  qb.push(" WHERE value IN (SELECT value FROM ");
  push_each(qb, b);
  qb.push("))");
}