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::*;

/// A `ref` COLUMN's filter: the column's own operators, and — beside them, in the same object — the
/// predicate over the row the reference points at.
///
/// ```graphql
/// clips(where: { coverId: { eq: 3 } })                        # the foreign key itself
/// clips(where: { coverId: { related: { title: { eq: "…" } } } })   # the row it points at
/// clips(where: { coverId: { in: [1, 2], related: { … } } })   # both, conjoined
/// ```
///
/// # It WIDENS the column's filter rather than standing beside it
///
/// A `ref` field is already a filterable column, and the nested question is about the same field. So
/// `coverId` keeps its name and its object grows one arm: no second top-level field, no second
/// declaration word, and every spelling a client already sends keeps working unchanged. A record
/// declaring `ref` gets the nested question for free.
///
/// # ADDITIVE, deliberately not `@oneOf`
///
/// `{ in: […], related: {…} }` is a real question — *one of these three covers, and its title starts
/// with "dawn"* — and the two halves conjoin exactly as two columns of the same filter do. Exclusivity
/// would refuse it for no gain: unlike a quantifier vocabulary, where two arms at once is a second
/// question wearing one field's clothes, a foreign key's own operators and its target's predicate
/// narrow the same row from two directions.
///
/// The reverse position is the OTHER shape and stays `@oneOf`: see
/// [`RelatedFilter`](super::RelatedFilter), whose four words are alternatives.
///
/// # No quantifiers, and null through the EXISTING vocabulary
///
/// A `ref` field carries ONE id, so there is at most one row on the far side and *some* / *every* /
/// *none* all collapse into the same question. A NULLABLE reference asks its null test where every
/// other nullable column asks it — on [`Nullable`](super::Nullable), one layer out — so this type
/// mints no null word of its own and a `NOT NULL` reference has none to mint.
///
/// # `R` is the TARGET's own filter
///
/// `<<Target as Graphql>::Input as GraphqlInput>::Filter` at an emitted position — the same
/// projection chain a reverse position takes to the SOURCE's filter. So the nested predicate is
/// whatever the target's declaration published, recursively, and this type states nothing about it.
///
/// Nothing about that projection is a STRING: a declaration names the target TYPE and the chain
/// finds its filter, so a renamed wire face moves both ends at once and a target that publishes none
/// is `E0277` at the `ref` that named it.
///
/// # The arm is BOXED, and the recursion is why
///
/// `R` may reach back to the filter this wrapper is a field of — `Clip.reelId` asking a `Reel`
/// predicate whose own `clips` position asks a `Clip`'s — so an unboxed arm makes both types
/// infinitely large and the report is `E0072`. Unlimited nesting with no indirection does not exist
/// in Rust; the reference implementation this shape is taken from boxes the wire side and reference
/// counts the storage side, and this is the wire side.
///
/// The box is the WRAPPER's rather than the holder's, which is the opposite of where a reverse
/// position's box sits: a reverse position names its neighbour ONCE and the emitted filter puts the
/// `Box` on, while this arm's recursion is inside a framework type that every `ref` column shares —
/// so putting it here is what keeps one emitted spelling for every reference rather than one the
/// emitter would have to decide per target.
///
/// What it costs is an allocation per WRITTEN level at PARSE time: none where the arm is absent, one
/// where a client wrote `related`, and never one per row — a filter is parsed once and rendered once,
/// however many rows the statement then answers.
#[derive(Debug, Clone, PartialEq)]
pub struct RefFilter<F, R> {
  pub(crate) column: F,
  pub(crate) related: Option<Box<R>>,
}

impl<F, R> RefFilter<F, R> {
  /// `column`'s operators, with no predicate asked of the row it points at.
  #[inline]
  pub const fn new(column: F) -> Self {
    Self {
      column,
      related: None,
    }
  }

  /// The column's own filter — its operators alone. The nested predicate belongs to this type.
  #[inline]
  pub const fn column(&self) -> &F {
    &self.column
  }

  /// The predicate asked of the row this reference points at, or [`None`](Option::None) where the
  /// client asked none.
  ///
  /// The pointer does not reach a caller: what is asked of the far side is a predicate, and whether
  /// this level allocated to hold it is this type's business.
  #[inline]
  pub fn related(&self) -> Option<&R> {
    self.related.as_deref()
  }

  /// The same filter, asking `related` of the far side.
  #[must_use]
  #[inline]
  pub fn with_related(mut self, related: R) -> Self {
    self.related = Some(Box::new(related));
    self
  }

  /// The two halves, taken apart — what a CROSSING spends.
  ///
  /// The column half becomes a predicate on the foreign key and the nested half becomes a semi-join
  /// through it, and the two land in different members of a record's comparison: one wire field, two
  /// predicates, conjoined by the record's own lowering. A crossing therefore needs both by value,
  /// and there is no borrow of one that lets the other be moved.
  ///
  /// The nested half leaves BOXED, because that is what a crossing spends it as: the storage side
  /// carries the same recursion and puts the same indirection in, so unwrapping here would free a
  /// pointer the next line allocates again.
  #[inline]
  pub fn into_parts(self) -> (F, Option<Box<R>>) {
    (self.column, self.related)
  }

  /// Convert the column's filter with `f`, keeping the nested predicate exactly as it stands.
  ///
  /// [`Nullable::try_map`](super::Nullable::try_map)'s rule, one wrapper over: `f` takes the whole
  /// column FILTER, because this type's first parameter is the filter it wraps. The nested predicate
  /// never converts here — it is the TARGET's filter and crosses through the target's own row.
  pub fn try_map<G, E>(self, f: impl FnOnce(F) -> Result<G, E>) -> Result<RefFilter<G, R>, E> {
    Ok(RefFilter {
      column: f(self.column)?,
      related: self.related,
    })
  }
}

impl<F: GraphqlFilter, R> RefFilter<F, R> {
  /// True while NOTHING is asked — no operator of the column's, and no predicate of the target's.
  ///
  /// The nested half counts as asked whenever it is PRESENT, however empty the predicate inside it:
  /// `{ related: {} }` is *this reference is live*, which is a question the semi-join answers and an
  /// absent arm does not ask. That is [`RelatedFilter::is_empty`](super::RelatedFilter::is_empty)'s
  /// reading of a present quantifier, and it is the same reading because it is the same fact.
  #[inline]
  pub fn is_empty(&self) -> bool {
    self.related.is_none() && self.column.is_empty()
  }
}

impl<F: Default, R> Default for RefFilter<F, R> {
  #[inline]
  fn default() -> Self {
    Self::new(F::default())
  }
}

impl<F: GraphqlFilter, R> GraphqlFilter for RefFilter<F, R> {
  #[inline]
  fn is_empty(&self) -> bool {
    Self::is_empty(self)
  }
}

/// The bound's row: an OPERAND converter reaches the column's operands through the wrapped kind's
/// own row, exactly as it does through [`Nullable`](super::Nullable).
impl<F: TryMapFilter<D, V>, R, D, V> TryMapFilter<D, V> for RefFilter<F, R> {
  type Mapped = RefFilter<F::Mapped, R>;

  #[inline]
  fn try_map_filter<E, G>(self, f: G) -> Result<Self::Mapped, E>
  where
    G: FnMut(D) -> Result<V, E>,
  {
    self.try_map(|column| column.try_map_filter(f))
  }
}

/// Equating a `ref` column equates its FOREIGN KEY, with no predicate asked of the far side.
///
/// A lineage walk equates the id a column carries; it is not asking about the target's own columns,
/// and an arm that also set the nested half would narrow by a predicate nobody wrote.
impl<F: EqualsFilter<T>, R, T> EqualsFilter<T> for RefFilter<F, R> {
  #[inline]
  fn equals(value: T) -> Self {
    Self::new(F::equals(value))
  }
}

/// The WIRE FACE, over BOTH parameters — the one input object in this module that reads its field
/// list off the REGISTRY rather than out of a macro's own list.
///
/// # Why the fields are read back rather than restated
///
/// Every other face here is emitted by [`filter_input_object!`](super), which knows the concrete
/// kind and writes its fields out. This wrapper cannot be: a `ref` column's id may be any storable
/// type, so `F` ranges over every registered filter kind — including the four with hand-written
/// registrations of their own — and a macro arm per kind would be a list free to fall behind the
/// kinds. So `F` is REGISTERED first and its `input_fields` are read back off the registry, which
/// makes this face *`F`'s fields plus `related`* by construction rather than by upkeep.
///
/// A kind that registers as anything but an input object contributes no fields, and the arm is still
/// there. That state is unreachable through the emitter — a column's filter is an input object —
/// and the empty map is the only honest answer to *what fields does a scalar have*.
///
/// # The name is built from BOTH sides, because both vary
///
/// `Int64RefCoverFilter`: the column's operand, the word `Ref`, the target's. GraphQL has no
/// generics, so two instantiations with different fields cannot share a name — and a scheme naming
/// only one side would collide the moment two columns of different id types point at one record, or
/// one id type points at two. Both halves go through
/// [`operand_of`](super::operand_of), which is the scheme this crate's registry already made
/// injective.
///
/// # The shape is FLAT, and `parse` hands the same object down
///
/// `{ eq: 3, related: {…} }`, never `{ column: { eq: 3 }, related: {…} }` — which is what makes the
/// widening invisible to a client that never asks the nested question. `parse` reads `related` off
/// the object and gives the SAME object to `F`'s own parse, which reads its keys by name and ignores
/// every other; that is [`Nullable`](super::Nullable)'s arrangement, for its reason: `F`'s fields
/// keep exactly one parser.
#[cfg(feature = "async-graphql")]
impl<F: async_graphql::InputType, R: async_graphql::InputType> async_graphql::InputType
  for RefFilter<F, R>
{
  type RawValueType = Self;

  fn type_name() -> ::std::borrow::Cow<'static, str> {
    let (column, target) = (F::type_name(), R::type_name());
    ::std::borrow::Cow::Owned(::std::format!(
      "{}Ref{}Filter",
      super::operand_of(&column),
      super::operand_of(&target),
    ))
  }

  fn create_type_info(registry: &mut async_graphql::registry::Registry) -> ::std::string::String {
    registry.create_input_type::<Self, _>(
      async_graphql::registry::MetaTypeId::InputObject,
      |registry| {
        // The column's own face, registered first: what comes back is the name it registered under,
        // which is the key its `input_fields` are then read from.
        let column = <F as async_graphql::InputType>::create_type_info(registry);
        let mut input_fields = match registry.types.get(column.trim_end_matches('!')) {
          ::std::option::Option::Some(async_graphql::registry::MetaType::InputObject {
            input_fields,
            ..
          }) => input_fields.clone(),
          _ => async_graphql::indexmap::IndexMap::new(),
        };
        input_fields.extend(__ingraph_filter_input_fields!(
          registry,
          "related" : ::core::option::Option<R>
        ));
        async_graphql::registry::MetaType::InputObject {
          name: ::std::borrow::Cow::into_owned(Self::type_name()),
          description: ::std::option::Option::None,
          input_fields,
          visible: ::std::option::Option::None,
          inaccessible: false,
          tags: ::std::vec::Vec::new(),
          rust_typename: ::std::option::Option::Some(::std::any::type_name::<Self>()),
          // ADDITIVE, deliberately: see the type's own note on why a foreign key's operators and its
          // target's predicate are not alternatives.
          oneof: false,
          directive_invocations: ::std::vec::Vec::new(),
        }
      },
    )
  }

  fn parse(
    value: ::std::option::Option<async_graphql::Value>,
  ) -> async_graphql::InputValueResult<Self> {
    if let ::std::option::Option::Some(async_graphql::Value::Object(object)) = value {
      // Parsed UNBOXED and boxed here: the schema knows `R`, and the pointer is the Rust half of
      // this type's recursion rather than anything a document says. One allocation per written
      // level, and none for the arm nobody wrote.
      let related = <::core::option::Option<R> as async_graphql::InputType>::parse(
        object.get("related").cloned(),
      )
      .map_err(async_graphql::InputValueError::propagate)?
      .map(::std::boxed::Box::new);
      let column = <F as async_graphql::InputType>::parse(::std::option::Option::Some(
        async_graphql::Value::Object(object),
      ))
      .map_err(async_graphql::InputValueError::propagate)?;
      return ::std::result::Result::Ok(Self { column, related });
    }
    // A BARE VALUE is the column's own shorthand and reaches `F`'s parse unchanged — the widening
    // adds an arm and takes nothing away, so `coverId: 42` still asks the foreign key.
    <F as async_graphql::InputType>::parse(value)
      .map(Self::new)
      .map_err(async_graphql::InputValueError::propagate)
  }

  fn to_value(&self) -> async_graphql::Value {
    let mut map = match async_graphql::InputType::to_value(&self.column) {
      async_graphql::Value::Object(map) => map,
      _ => async_graphql::indexmap::IndexMap::new(),
    };
    map.insert(
      async_graphql::Name::new("related"),
      match &self.related {
        ::std::option::Option::Some(related) => async_graphql::InputType::to_value(&**related),
        ::std::option::Option::None => async_graphql::Value::Null,
      },
    );
    async_graphql::Value::Object(map)
  }

  #[inline]
  fn as_raw_value(&self) -> ::std::option::Option<&Self::RawValueType> {
    ::std::option::Option::Some(self)
  }
}

#[cfg(feature = "async-graphql")]
impl<F: async_graphql::InputType, R: async_graphql::InputType> async_graphql::InputObjectType
  for RefFilter<F, R>
{
}

#[cfg(test)]
mod tests;