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

/// The enum filter — equality + membership only (no ordering, no substring). An enum
/// column stores as, through the enum type's own backend operand impl (text name or integer
/// discriminant).
#[derive(Debug, Clone, PartialEq)]
pub struct EnumFilter<T> {
  pub(crate) eq: Option<T>,
  pub(crate) ne: Option<T>,
  pub(crate) in_: Option<Box<[T]>>,
  pub(crate) not_in: Option<Box<[T]>>,
}

impl<T> EnumFilter<T> {
  /// The empty filter — no operator set.
  #[inline]
  pub const fn new() -> Self {
    Self {
      eq: None,
      ne: None,
      in_: None,
      not_in: None,
    }
  }

  /// True while NO operator slot is set — so a lowering would emit nothing for this field.
  ///
  /// Inherent, not the backend traits' provided `is_empty`: "is anything set" is a property of the
  /// FILTER, identical on every backend, and asking it should not make a caller name a dialect (with
  /// two families compiled, `f.is_empty()` through the traits is `E0283`). The inherent method wins
  /// method resolution, so every call site reads the same either way.
  #[inline]
  pub const fn is_empty(&self) -> bool {
    self.eq.is_none() && self.ne.is_none() && self.in_.is_none() && self.not_in.is_none()
  }

  opt_accessor!(eq: T => with_eq, set_eq, maybe_eq, update_eq);
  opt_accessor!(ne: T => with_ne, set_ne, maybe_ne, update_ne);
  opt_accessor!(in_: [T] => with_in_, set_in_, maybe_in_, update_in_);
  opt_accessor!(not_in: [T] => with_not_in, set_not_in, maybe_not_in, update_not_in);

  /// True when this filter's ONLY set operator is a plain `eq` or a plain `in_` — the shape a
  /// relation may rewrite onto the PARENT's foreign key instead of running a subquery.
  ///
  /// Sound only under referential integrity: every fk references an existing child row, so
  /// `fk IN (SELECT key FROM child WHERE key = v)` is exactly `fk = v`. A negated shape
  /// (`ne`/`not_in`) is NOT equivalent under dangling references, an ordering operator does not
  /// name a single child row, and a case-insensitive match compares differently on the two
  /// columns — so none of them ever collapses.
  #[inline]
  pub const fn is_referential(&self) -> bool {
    (self.eq.is_some() ^ self.in_.is_some()) && self.ne.is_none() && self.not_in.is_none()
  }

  /// Convert every set operand with `f`, keeping the operator set exactly as it stands — see
  /// [`ScalarFilter::try_map`] for what this primitive is for and what it promises about lists.
  ///
  /// An enum reaches for it more often than any other kind: a variant's stored form is a name or a
  /// discriminant that the enum's own code writes, so the converter is almost always a declared one.
  pub fn try_map<U, E, F>(self, mut f: F) -> Result<EnumFilter<U>, E>
  where
    F: FnMut(T) -> Result<U, E>,
  {
    Ok(EnumFilter {
      eq: map_operand(self.eq, &mut f)?,
      ne: map_operand(self.ne, &mut f)?,
      in_: map_operands(self.in_, &mut f)?,
      not_in: map_operands(self.not_in, &mut f)?,
    })
  }
}

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

/// The bound's row, so a collection of a closed vocabulary crosses through one declared converter
/// like any other.
impl<T, U> TryMapFilter<T, U> for EnumFilter<T> {
  type Mapped = EnumFilter<U>;

  #[inline]
  fn try_map_filter<E, F>(self, f: F) -> Result<Self::Mapped, E>
  where
    F: FnMut(T) -> Result<U, E>,
  {
    self.try_map(f)
  }
}

/// The bound's row: `new()` and the inherent `with_eq`, reached where the kind is a parameter rather
/// than a spelling.
impl<T> EqualsFilter<T> for EnumFilter<T> {
  #[inline]
  fn equals(value: T) -> Self {
    Self::new().with_eq(value)
  }
}

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

/// The WIRE FACE, and the one in this crate written over a PARAMETER rather than per instantiation.
///
/// The FIRST face written this way, and the shape every other kind has since taken: the two
/// collection kinds followed it, and the text, scalar and byte tables followed those onto the
/// CARRIER AXIS. Every operand a TABLE row could name was a type this crate owns — `i64` under
/// `I64Filter`, now a [`Builtin`](crate::Builtin) row rather than a registration. An enum's
/// operand is a DECLARER's type, so there was never a table for it to be in: the set is open, and a
/// row per member is a row this crate cannot write.
///
/// One generic impl closes it, and closes it with nothing orphaned. [`EnumFilter`] is this crate's
/// own type, so `impl async_graphql::InputType for EnumFilter<T>` is a LOCAL impl at any `T` —
/// coherence is not in the conversation. What a declaring crate supplies is the enum's OWN wire face
/// (`Codec: InputType`), which is a local impl there, and this row does the rest for every enum at
/// once.
///
/// # The bound is `InputType` and nothing narrower
///
/// The body needs one thing of `T`: that it crosses the wire. `type_name` asks for its schema name,
/// `parse` reads `Option<T>` and `Option<Box<[T]>>` through async-graphql's own wrappers, and
/// `to_value` renders a borrowed operand. `EnumType` — async-graphql's *this is a GraphQL enum*
/// contract — would ALSO hold for every type a declaration reaches this filter with, and would buy
/// the impl nothing it uses, so it is not asked for. The framework-open reading is the same one: what
/// a declaring crate may put in this position is its business, and a bound this row does not spend is
/// a rule it would be inventing.
///
/// # The NAME is derived, and that is what makes it uniquely spellable
///
/// `<T's schema name>Filter` — `Codec` gives `CodecFilter` — which is the modifier convention the
/// scalar and text READINGS derive from the roster (`i64` → `I64Filter`), computed here because the
/// operand's name is not this crate's to know. It works HERE and does not work for a collection: an
/// enum's own schema name is its own, where async-graphql gives every integer width the one name
/// `Int` — which is why the collection faces derive from the element's FILTER instead, and why the
/// two derivations are not one function. The nullable twin takes `Nullable` in front of THIS name rather
/// than of a second `format!`, for [`filter_input_object!`]'s own reason: two spellings of one name
/// are two things that can come to disagree.
///
/// Injectivity comes with it. Two distinct GraphQL type names give two distinct filter names,
/// because prefixing and suffixing a name preserves distinctness — so the hand-maintained uniqueness
/// the tables argue for by eye is DERIVED here rather than restated. What it does not rule out is a
/// declared enum whose own schema name is one of this crate's operand names: an enum named `Int64`
/// claims `I64Filter`, which `Builtin`'s reading of `i64` holds, and async-graphql answers that the way it
/// answers any two Rust types under one GraphQL name — `Registry::create_type` panics when a schema
/// names both. Pinned in `graphql::tests::wire`.
#[cfg(feature = "async-graphql")]
impl<T: async_graphql::InputType> async_graphql::InputType for EnumFilter<T> {
  type RawValueType = Self;

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

  fn create_type_info(registry: &mut async_graphql::registry::Registry) -> ::std::string::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: ::std::option::Option::None,
        input_fields: <Self as crate::NullableFace>::bare_fields(registry),
        visible: ::std::option::Option::None,
        inaccessible: false,
        tags: ::std::vec::Vec::new(),
        rust_typename: ::std::option::Option::Some(::std::any::type_name::<Self>()),
        oneof: false,
        directive_invocations: ::std::vec::Vec::new(),
      },
    )
  }

  fn parse(
    value: ::std::option::Option<async_graphql::Value>,
  ) -> async_graphql::InputValueResult<Self> {
    let object = match super::sent(value) {
      super::Sent::Longhand(object) => object,
      // Rule ① — a bare value is this filter's `eq`, put under that key so the slot below reads it
      // through the same crossing the longhand takes rather than through a second reading.
      super::Sent::Bare(bare) => {
        let mut object = async_graphql::indexmap::IndexMap::new();
        object.insert(async_graphql::Name::new("eq"), bare);
        object
      }
      // A `NOT NULL` column's filter has no null test to set, so rule ② is refused here — which is
      // nullability being a TYPE rather than a slot, said at the parse.
      super::Sent::Null => {
        return ::std::result::Result::Err(async_graphql::InputValueError::expected_type(
          async_graphql::Value::Null,
        ));
      }
      super::Sent::Refused(sent) => {
        return ::std::result::Result::Err(async_graphql::InputValueError::expected_type(sent));
      }
    };
    ::std::result::Result::Ok(Self {
      eq: parse_slot::<_, Self>(&object, "eq")?,
      ne: parse_slot::<_, Self>(&object, "ne")?,
      in_: parse_slot::<_, Self>(&object, "in")?,
      not_in: parse_slot::<_, Self>(&object, "notIn")?,
    })
  }

  fn to_value(&self) -> async_graphql::Value {
    async_graphql::Value::Object(<Self as crate::NullableFace>::bare_values(self))
  }

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

#[cfg(feature = "async-graphql")]
impl<T: async_graphql::InputType> async_graphql::InputObjectType for EnumFilter<T> {}

/// The NULLABLE row, for the reason [`filter_input_object!`] emits one from every invocation:
/// nullability is a TYPE here, so a registered filter that fed no `NullableFace` would leave every
/// `Option<Codec>` column unspellable — and the way that face went missing once already was a
/// registration site able to mint one alone.
///
/// The twin the blanket assembles is FLAT and its `parse` hands the SAME object to `EnumFilter`'s
/// own, so the operator fields keep one parser shared with the bare face.
#[cfg(feature = "async-graphql")]
impl<T: async_graphql::InputType> crate::NullableFace for EnumFilter<T> {
  fn bare_fields(
    registry: &mut async_graphql::registry::Registry,
  ) -> async_graphql::indexmap::IndexMap<
    ::std::string::String,
    async_graphql::registry::MetaInputValue,
  > {
    __ingraph_filter_input_fields!(
      registry,
      "eq" : ::core::option::Option<T>,
      "ne" : ::core::option::Option<T>,
      "in" : ::core::option::Option<::std::boxed::Box<[T]>>,
      "notIn" : ::core::option::Option<::std::boxed::Box<[T]>>,
    )
  }

  fn bare_values(
    &self,
  ) -> async_graphql::indexmap::IndexMap<async_graphql::Name, async_graphql::Value> {
    __ingraph_filter_value_map!(self, "eq" : eq, "ne" : ne, "in" : in_, "notIn" : not_in)
  }
}