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, SqlLoweringError, not_wrapped,
      push_count_slots, render_column,
    },
  },
};

impl<V, C> SqlListComparison<V, C, sqlx::MySql> {
  /// Cross a [`ListFilter`] into a MySQL 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 MySQL sequence comparison, converting each ELEMENT with `f` and
  /// the nested ELEMENT FILTER with `g`.
  ///
  /// # Errors
  ///
  /// [`ListCrossingError::JsonOrdering`] when any ordering operator is set — MySQL's `JSON` type
  /// has an ordering over VALUES and not the element-wise one this operator names;
  /// [`ListCrossingError::Operand`] when `f` refuses an element;
  /// [`ListCrossingError::Element`] when the element filter's own crossing refuses.
  ///
  /// `any` crosses here and is refused at the LOWERING — the element scope is an address, and an
  /// address arrives with the application. See
  /// [`SqlLoweringError::JsonElementScope`](crate::comparison::sql::SqlLoweringError::JsonElementScope).
  ///
  /// `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>,
  {
    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::MySql>
{
  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::MySql>> ComplexComparison<sqlx::MySql>
  for SqlListComparison<V, C, sqlx::MySql>
{
  #[inline]
  fn conjuncts(&self) -> usize {
    Self::conjuncts(self)
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    mut builder: <sqlx::MySql as Backend>::Builder<'q>,
  ) -> Result<<sqlx::MySql as Backend>::Builder<'q>, <sqlx::MySql as Backend>::Error> {
    refuse_element_scope(self.any.as_ref())?;
    push_json_list_slots(self, at, &mut builder, push_collection_op);
    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::MySql>> ComplexComparison<sqlx::MySql>
  for SqlSetComparison<V, C, sqlx::MySql>
{
  #[inline]
  fn conjuncts(&self) -> usize {
    Self::conjuncts(self)
  }

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

/// The one thing a collection kept in a MySQL `JSON` column cannot be asked, refused before any slot
/// is walked so that the accumulator is left as it was found.
///
/// `JSON_TABLE` is the only element scope this dialect has, and it fails twice — the natural `EXISTS`
/// spelling is silently emptied by the semijoin transform, and the form that survives it needs a
/// column TYPE this layer does not hold. Both are measured at
/// [`SqlLoweringError::JsonElementScope`], which is also where the reason a REFUSAL beats the two
/// operators that happen to work is stated.
///
/// Both kinds call it, because the slot is on both and neither dialect half can answer it.
fn refuse_element_scope<C>(element: Option<&C>) -> Result<(), SqlLoweringError> {
  match element {
    Some(_) => Err(SqlLoweringError::JsonElementScope),
    None => Ok(()),
  }
}

/// The `count` slot both walks end with, and the one element question this dialect's JSON column
/// CAN answer.
///
/// `JSON_LENGTH` is a scalar function over the stored value rather than a table function over its
/// members, so nothing here meets the optimizer transform that makes `any` unanswerable — see
/// [`SqlLoweringError::JsonElementScope`]. A cardinality is asked about the column, and an element
/// question is asked about a row this dialect cannot produce.
///
/// Measured on MySQL 8.4.11: `JSON_LENGTH(CAST('[]' AS JSON))` is `0`, so the empty array is counted
/// rather than skipped, and a `NULL` column yields `NULL`.
fn push_json_count(
  count: Option<&SqlCountComparison<i64, sqlx::MySql>>,
  at: At<'_>,
  out: &mut SqlConjunction<'_, sqlx::MySql>,
) {
  let Some(count) = count else {
    return;
  };
  let column = render_column::<sqlx::MySql>(at);
  push_count_slots(count, out, |qb| {
    qb.push("JSON_LENGTH(");
    qb.push(&column);
    qb.push(")");
  });
}

fn push_collection_op(
  qb: &mut sqlx::QueryBuilder<sqlx::MySql>,
  at: At<'_>,
  op: CollectionOp,
  operand_json: &str,
  negated: bool,
) {
  // Bracketed ONCE for the several places a containment pair names the column.
  let column = render_column::<sqlx::MySql>(at);
  not_wrapped(qb, negated, |qb| match op {
    // MySQL's `=` on two JSON arrays is element-wise and order-sensitive, which is the sequence
    // form; `JSON_CONTAINS` compares arrays as SETS, so mutual containment is a genuine set
    // equality.
    CollectionOp::SequenceEq => {
      qb.push(&column);
      qb.push(" = ");
      push_json(qb, operand_json);
    }
    CollectionOp::SetEq => {
      qb.push("( JSON_CONTAINS(");
      qb.push(&column);
      qb.push(", ");
      push_json(qb, operand_json);
      qb.push(") AND JSON_CONTAINS(");
      push_json(qb, operand_json);
      qb.push(", ");
      qb.push(&column);
      qb.push(") )");
    }
    // `JSON_CONTAINS(target, candidate)` is `candidate ⊆ target`.
    CollectionOp::Encloses => {
      qb.push("JSON_CONTAINS(");
      qb.push(&column);
      qb.push(", ");
      push_json(qb, operand_json);
      qb.push(")");
    }
    CollectionOp::EnclosedBy => {
      qb.push("JSON_CONTAINS(");
      push_json(qb, operand_json);
      qb.push(", ");
      qb.push(&column);
      qb.push(")");
    }
    CollectionOp::Overlaps => {
      qb.push("JSON_OVERLAPS(");
      qb.push(&column);
      qb.push(", ");
      push_json(qb, operand_json);
      qb.push(")");
    }
  });
}

/// Bind canonical JSON text through an explicit `CAST(? AS JSON)` — MySQL has no implicit
/// text-to-JSON assignment cast, so this is what types the operand for the functions above.
fn push_json(qb: &mut sqlx::QueryBuilder<sqlx::MySql>, json: &str) {
  qb.push("CAST(");
  qb.push_bind(json.to_owned());
  qb.push(" AS JSON)");
}