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

#[cfg(all(test, feature = "async-graphql"))]
mod tests;

/// A NULLABLE column's filter: `F`'s operators, plus the null test — which exists here and in no
/// other filter type.
///
/// Nullability is a fact about the COLUMN, so it is carried by the type. A bare `T` resolves to its
/// plain filter and an `Option<T>` to this wrapper — one blanket over every `T`, since a nullable
/// column has exactly one reading whatever it wraps — which is what makes `IS NULL` against a
/// `NOT NULL` column unrepresentable rather than merely unsatisfiable. The
/// predecessor put an `is_null` slot on all six kinds and registered `T` and `Option<T>` to the SAME
/// filter, so a client could ask a `NOT NULL` column whether it was null and get an empty result set —
/// a query that cannot match reported as a query that matched nothing, which an agentic consumer has
/// no way to tell apart from an honest miss.
///
/// One wrapper rather than a nullable TWIN per kind: twins are an M×N over the kinds, and a
/// generic default (`BytesFilter<B, K = Variable>`) would then be declared in two places, free to
/// drift apart. Named for what it modifies — `Nullable<ScalarFilter<i64>>` reads as the modifier it
/// is, where `NullableScalarFilter<i64>` stutters.
///
/// # The guarantee, as the compiler sees it
///
/// A nullable column's filter takes the null test:
///
/// ```
/// use ingraph::{DefaultMarker, GraphqlFilter, Nullable, ScalarFilter, ToGraphqlFilter};
///
/// // What an expansion writes for a field of type `T`.
/// type Column<T> = <<T as DefaultMarker>::Marker as ToGraphqlFilter>::Filter;
///
/// // `Option<u32>` is a NULLABLE column, and this is the type it resolves to.
/// let f: Column<Option<u32>> = Nullable::new(ScalarFilter::new().with_eq(1)).with_null(false);
/// assert!(!f.is_empty());
/// ```
///
/// A `NOT NULL` column's does not — there is no such operator on the type at all (`E0599`):
///
/// ```compile_fail,E0599
/// use ingraph::{DefaultMarker, GraphqlFilter, Nullable, ScalarFilter, ToGraphqlFilter};
///
/// type Column<T> = <<T as DefaultMarker>::Marker as ToGraphqlFilter>::Filter;
///
/// // Bare `u32` is a `NOT NULL` column, and this is the type it resolves to.
/// let f: Column<u32> = ScalarFilter::new().with_eq(1);
/// let _ = f.with_null(false);
/// ```
///
/// The two earn their keep only together. Stable rustdoc runs a `compile_fail` block just far enough
/// to see it fail and never checks WHY, so the negative one alone would still "pass" with the imports
/// gone stale; the positive twin shares those imports and that `with_eq` call and must COMPILE. And
/// they fail in opposite directions: pointing the `Option` blanket back at the bare filter reds the
/// FIRST block, while giving a bare `T` the wrapper reds the SECOND.
///
/// # No `Deref` to `F`
///
/// The inner filter is reached through [`inner`](Self::inner), and it answers about ITS operators
/// alone. A whole-filter question must account for the null slot too: [`is_empty`](Self::is_empty)
/// does, and [`ScalarFilter::is_referential`] — asked on the inner filter — does not. That is why
/// there is no transparent access: a nullable foreign key has no `is_referential` to call, so it
/// cannot collapse onto the parent column, and `inner().is_referential()` is visibly a question about
/// the inner filter rather than about this one.
#[derive(Debug, Clone, PartialEq)]
pub struct Nullable<F> {
  pub(crate) inner: F,
  pub(crate) null: Option<bool>,
}

impl<F> Nullable<F> {
  /// `inner`'s operators, with the null test unset.
  #[inline]
  pub const fn new(inner: F) -> Self {
    Self { inner, null: None }
  }

  /// The wrapped filter — its own operators only. The null test belongs to this type.
  #[inline]
  pub const fn inner(&self) -> &F {
    &self.inner
  }

  opt_accessor!(null: bool => with_null, set_null, maybe_null, update_null);

  /// Convert the wrapped filter with `f`, keeping the null test exactly as it stands.
  ///
  /// `f` takes the whole inner FILTER rather than an operand, and that is this wrapper's own rule
  /// rather than an exception to it: every kind's `try_map` maps that kind's type parameter, and
  /// this one's parameter is the filter it wraps. The operands are the inner kind's to map, through
  /// its own `try_map`, which is what a nested call spells out —
  /// `nullable.try_map(|inner| inner.try_map(convert))`.
  ///
  /// The null test never converts. It is a question about the COLUMN rather than about a value, so
  /// no storage type can change what it asks.
  pub fn try_map<G, E>(self, f: impl FnOnce(F) -> Result<G, E>) -> Result<Nullable<G>, E> {
    Ok(Nullable {
      inner: f(self.inner)?,
      null: self.null,
    })
  }
}

impl<F: GraphqlFilter> Nullable<F> {
  /// True while NO operator slot is set — neither the null test nor any of `F`'s.
  ///
  /// Not `const`, unlike the five kinds' own: `F`'s half of the answer arrives through a trait
  /// method.
  #[inline]
  pub fn is_empty(&self) -> bool {
    self.null.is_none() && self.inner.is_empty()
  }
}

/// The bound's row, and the ONE that reaches for a second: this wrapper's own `try_map` takes the
/// inner FILTER, so an OPERAND converter reaches the operands only by asking the wrapped kind for
/// its row too. That is the nested call `try_map`'s note spells out, written once here.
impl<F: TryMapFilter<D, V>, D, V> TryMapFilter<D, V> for Nullable<F> {
  type Mapped = Nullable<F::Mapped>;

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

/// The row this whole trait exists for, and the one that makes its parameter mean one thing: a
/// column DECLARED at `Option<T>` is equated to an `Option<T>`.
///
/// `EqualsFilter<T>` reads *the filter for a column declared at `T`* at every row, and this wrapper
/// is what a declared `Option` resolves to — so the operand carries the same `Option` the
/// declaration wrote, and an emitter holding a column's type holds its operand's type too. The
/// alternative, taking a bare `T` here, would make the parameter mean the DECLARED type at eight
/// rows and the wrapped one at the ninth, and a type-blind caller could no longer name it.
///
/// The two arms are the two things such a column can be asked, and both are what a declaration can
/// spell:
///
/// * `Some(v)` — the wrapped kind's equality, with the null test unset. `IS NULL` is a question
///   about the COLUMN rather than about a value, so equating one never answers it, and an arm that
///   also wrote `null: Some(false)` would drop the rows a caller asked for by a predicate nobody
///   wrote.
/// * `None` — the null test alone, over `F`'s empty filter: *this column IS null*, which is the
///   only reading an absent operand has on a column that can hold one.
impl<F: EqualsFilter<T> + Default, T> EqualsFilter<Option<T>> for Nullable<F> {
  #[inline]
  fn equals(value: Option<T>) -> Self {
    match value {
      Some(value) => Self::new(F::equals(value)),
      None => Self::new(F::default()).with_null(true),
    }
  }
}

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

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

/// A bare filter face taken apart into the two pieces its NULLABLE twin is assembled from — the
/// DELEGATION TRAIT that makes [`Nullable<F>`]'s wire face ONE blanket row.
///
/// # The wall this is the door through
///
/// `Nullable` is this crate's type and `async_graphql::InputType` is async-graphql's, so a
/// DECLARING crate cannot write `impl InputType for Nullable<TimebaseFilter>`: `E0117`, RFC 2451
/// admitting no `ForeignTrait for ForeignType<Local>`. This crate cannot write it either, never
/// having heard of `TimebaseFilter`. An `Option<Timebase>` column was therefore unspellable on the
/// wire whatever either side did — the hole `ingraph-codegen`'s element mode recorded and routed
/// around by aliasing its enum family onto a framework type.
///
/// What blocked the obvious fix was `E0119`: one generic `impl<F> InputType for Nullable<F>` here
/// overlapped the concrete `Nullable<ScalarFilter<i64>>` rows the registrations minted. So the rows
/// moved onto THIS trait — every one of them, which is what leaves the generic impl unopposed. It is
/// exactly the move [`TextWire`](crate::TextWire) made for `TextFilter`'s own face, one type over: a
/// per-instantiation table becomes a delegation a downstream crate can join, because the impl it
/// writes names a LOCAL self type.
///
/// # What a row supplies, and what it does NOT
///
/// The twin is FLAT — the bare face's fields beside `isNull` in one input object — and its whole
/// remaining behaviour is derivable from the bare face:
///
/// * the NAME is `Nullable` before the bare face's own, written once in the blanket so a row cannot
///   disagree with it;
/// * `parse` reads `isNull` off the object and hands the SAME object to `Self::parse`, which reads
///   its keys by name and ignores every other — so the operator slots keep exactly one parser;
/// * the SHORTHAND LAW's rule ② lands there and only there, over `Self::default()`.
///
/// That leaves the two pieces a bare face keeps to itself, because both are built INSIDE
/// `create_type_info`'s registry closure and `to_value`'s body where nothing can reach them.
///
/// # `Default` and `InputType` sit on the seat
///
/// Both are structural rather than incidental. The null-test-alone state is `Self::default()` under
/// the wrapper, and every other arm delegates to `Self::parse` — so a row missing either could not
/// be spent at all, and stating them here makes that `E0277` at the row a reader can go and fix
/// instead of an unsatisfied blanket at a use site far away.
#[cfg(feature = "async-graphql")]
pub trait NullableFace: async_graphql::InputType + Default {
  /// This face's input fields, in the order it publishes them — the list the nullable twin
  /// registers with `isNull` appended.
  fn bare_fields(
    registry: &mut async_graphql::registry::Registry,
  ) -> async_graphql::indexmap::IndexMap<String, async_graphql::registry::MetaInputValue>;

  /// This face's rendered slots, in that same order — the map the nullable twin renders with
  /// `isNull` appended.
  fn bare_values(
    &self,
  ) -> async_graphql::indexmap::IndexMap<async_graphql::Name, async_graphql::Value>;
}

/// The ONE wire face every nullable column wears, and the row the delegation trait was minted for.
///
/// Its name is `Nullable` before the wrapped face's own, computed HERE rather than declared by the
/// row: the modifier prefix is the framework's naming law, and a second literal at each row would be
/// free to disagree with the name that row already publishes.
#[cfg(feature = "async-graphql")]
impl<F: NullableFace> async_graphql::InputType for Nullable<F> {
  type RawValueType = Self;

  fn type_name() -> std::borrow::Cow<'static, str> {
    std::borrow::Cow::Owned(std::format!("Nullable{}", F::type_name()))
  }

  fn create_type_info(registry: &mut async_graphql::registry::Registry) -> String {
    registry.create_input_type::<Self, _>(
      async_graphql::registry::MetaTypeId::InputObject,
      |registry| async_graphql::registry::MetaType::InputObject {
        name: std::borrow::Cow::into_owned(Self::type_name()),
        description: None,
        // The bare face's field list, then the null test — the whole difference between the two
        // input objects, in one line. `F` itself is NOT registered from here: a schema exposing
        // only nullable columns of this type has no use for the bare object, and the delegating
        // `parse` below needs the impl rather than the registration.
        input_fields: {
          let mut fields = F::bare_fields(registry);
          fields.extend(__ingraph_filter_input_fields!(
            registry,
            "isNull" : ::core::option::Option<bool>
          ));
          fields
        },
        visible: None,
        inaccessible: false,
        tags: Vec::new(),
        rust_typename: Some(std::any::type_name::<Self>()),
        oneof: false,
        directive_invocations: Vec::new(),
      },
    )
  }

  /// # The SHORTHAND LAW, at the face that HAS a null test
  ///
  /// Rule ② lands here and nowhere else: an explicit `null` is `isNull: true` over the empty
  /// filter, which is a different state from ABSENT — absent asks nothing, and this asks *is this
  /// column null*. Rule ① is DELEGATED to the bare face rather than restated, so the two faces
  /// cannot come to disagree about what a bare value means — and a wrapped kind with no `eq`
  /// refuses it exactly as it does undressed.
  fn parse(value: Option<async_graphql::Value>) -> async_graphql::InputValueResult<Self> {
    match super::sent(value) {
      super::Sent::Longhand(object) => {
        let null = super::parse_slot::<_, Self>(&object, "isNull")?;
        let inner = F::parse(Some(async_graphql::Value::Object(object)))
          .map_err(async_graphql::InputValueError::propagate)?;
        Ok(Self::new(inner).maybe_null(null))
      }
      super::Sent::Bare(bare) => {
        let inner = F::parse(Some(bare)).map_err(async_graphql::InputValueError::propagate)?;
        Ok(Self::new(inner))
      }
      super::Sent::Null => Ok(Self::new(F::default()).with_null(true)),
      super::Sent::Refused(sent) => Err(async_graphql::InputValueError::expected_type(sent)),
    }
  }

  fn to_value(&self) -> async_graphql::Value {
    let mut map = self.inner.bare_values();
    map.insert(
      async_graphql::Name::new("isNull"),
      async_graphql::InputType::to_value(&self.null),
    );
    async_graphql::Value::Object(map)
  }

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

#[cfg(feature = "async-graphql")]
impl<F: NullableFace> async_graphql::InputObjectType for Nullable<F> {}