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 set filter — for an UNORDERED collection column, generic over the element type `T`. Every
/// operator here ignores order and multiplicity: `eq`/`ne` are set equality, `encloses` /
/// `enclosed_by` are superset / subset, `overlaps` is a non-empty intersection, and `has_element` is
/// membership.
///
/// # It was [`ListFilter`]'s shape parameter, and the operators are why it is a type
///
/// One collection filter carried all of these under a marker naming the column ordered or unordered,
/// and the marker changed exactly one thing: what `eq` MEANT. The other four operators here are
/// order- and multiplicity-blind whichever marker was named, so an ordered column asked `overlaps`
/// was already being read as a set. Two operator sets that overlap in one slot are two types, not one
/// type and a flag.
///
/// Postgres draws the line itself — `@>` / `<@` / `&&` are the set operators and `=` is the sequence
/// one — so the split moves a distinction the engine already makes up to the filter layer. MySQL's
/// `JSON_CONTAINS` compares two arrays as sets while its `=` on the same two is element-wise, which
/// is the same division under different names.
///
/// # `has_element` is not sugar for `encloses` of the singleton
///
/// It reads as one, and both lower through the same containment form. What differs is the BIND:
/// `has_element: x` binds one element where `encloses: [x]` ships a collection operand, and on
/// Postgres sqlx writes a 20-byte array header for the second. The predicate is the same and the
/// wire is not, so the single-element spelling is a capability rather than a convenience.
///
/// # There are no ordering operators, and their absence is the split paying for itself
///
/// A collection ordering is element-wise and lexicographic, so it reads the stored element order —
/// and a set's depends on insertion. That used to be a runtime refusal on every dialect, Postgres
/// included: the operator existed on the filter, the shape marker said the column had no order worth
/// reading, and the crossing returned an error naming the operator. With the shape in the TYPE there
/// is no slot to set, so the same mistake is `E0599` at the call site instead:
///
/// ```compile_fail,E0599
/// let _ = ingraph::SetFilter::<i64>::new().with_gt([1i64]);
/// ```
///
/// The positive twin, which must COMPILE — stable rustdoc runs a `compile_fail` block just far
/// enough to see it fail and never checks why, so the pair shares its call shape and one half has to
/// be positive:
///
/// ```
/// let _ = ingraph::SetFilter::<i64>::new().with_encloses([1i64]);
/// ```
///
/// The other direction holds too: a set operator on a sequence is the same error, so neither kind
/// can be asked the other's question.
///
/// ```compile_fail,E0599
/// let _ = ingraph::ListFilter::<i64>::new().with_overlaps([1i64]);
/// ```
///
/// ```
/// let _ = ingraph::ListFilter::<i64>::new().with_lte([1i64]);
/// ```
///
/// # The three set operators are polarsync's `@>`, `<@` and `&&`
///
/// They are the whole of what a `set(…)` column has that a `list(…)` one has not, and the per-
/// operator audit against polarsync's own `ArrayFilter` — which draws no such line and carries all
/// nine on one type — is written out at [`ListFilter`], beside the four ordering operators that are
/// the other half of the same split.
///
/// # `any` and `count` are on BOTH kinds, and that is the split holding
///
/// Neither reads the stored order. *Some element satisfies this filter* and *this collection holds
/// this many* are the same questions whether or not order and multiplicity carry meaning, so both
/// belong on both kinds — exactly as `has_element` does, and unlike the five operators the split
/// moved. See [`ListFilter`] for what `VF` is, where `any` overlaps `has_element`, and why a `count`
/// operand is a `usize`.
#[derive(Debug, Clone, PartialEq)]
pub struct SetFilter<T, VF = <<T as DefaultMarker>::Marker as ToGraphqlFilter>::Filter> {
  pub(crate) eq: Option<Box<[T]>>,
  pub(crate) ne: Option<Box<[T]>>,
  pub(crate) encloses: Option<Box<[T]>>,
  pub(crate) enclosed_by: Option<Box<[T]>>,
  pub(crate) overlaps: Option<Box<[T]>>,
  pub(crate) has_element: Option<T>,
  pub(crate) any: Option<VF>,
  pub(crate) count: Option<ScalarFilter<usize>>,
}

impl<T, VF> SetFilter<T, VF> {
  /// The empty filter — no operator set.
  #[inline]
  pub const fn new() -> Self {
    Self {
      eq: None,
      ne: None,
      encloses: None,
      enclosed_by: None,
      overlaps: None,
      has_element: None,
      any: None,
      count: 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.
  ///
  /// A present `any` holding an empty element filter is NOT empty and a present `count` holding an
  /// empty scalar filter IS, for the reason [`ListFilter::is_empty`] gives: one slot is quantified
  /// and the other is not.
  #[inline]
  pub const fn is_empty(&self) -> bool {
    self.eq.is_none()
      && self.ne.is_none()
      && self.encloses.is_none()
      && self.enclosed_by.is_none()
      && self.overlaps.is_none()
      && self.has_element.is_none()
      && self.any.is_none()
      && match &self.count {
        Some(count) => count.is_empty(),
        None => true,
      }
  }

  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!(encloses: [T] => with_encloses, set_encloses, maybe_encloses, update_encloses);
  opt_accessor!(
    enclosed_by: [T] => with_enclosed_by, set_enclosed_by, maybe_enclosed_by, update_enclosed_by
  );
  opt_accessor!(overlaps: [T] => with_overlaps, set_overlaps, maybe_overlaps, update_overlaps);
  opt_accessor!(
    has_element: T => with_has_element, set_has_element, maybe_has_element, update_has_element
  );
  opt_accessor!(any: VF => with_any, set_any, maybe_any, update_any);
  opt_accessor!(
    count: ScalarFilter<usize> => with_count, set_count, maybe_count, update_count
  );

  /// Convert every ELEMENT 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.
  ///
  /// `f` maps ONE ELEMENT, not a collection. Five of the six element slots hold a whole collection
  /// operand and the sixth a single element, and both are made of the same `T` — so a single element
  /// converter serves all six, and `has_element` is not a special case.
  ///
  /// `any` and `count` pass through untouched, for the reason [`ListFilter::try_map`] gives.
  pub fn try_map<U, E, F>(self, mut f: F) -> Result<SetFilter<U, VF>, E>
  where
    F: FnMut(T) -> Result<U, E>,
  {
    Ok(SetFilter {
      eq: map_operands(self.eq, &mut f)?,
      ne: map_operands(self.ne, &mut f)?,
      encloses: map_operands(self.encloses, &mut f)?,
      enclosed_by: map_operands(self.enclosed_by, &mut f)?,
      overlaps: map_operands(self.overlaps, &mut f)?,
      has_element: map_operand(self.has_element, &mut f)?,
      any: self.any,
      count: self.count,
    })
  }
}

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

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

/// The WIRE FACE, written over the two PARAMETERS — [`ListFilter`](super::ListFilter)'s row, for the
/// other collection shape.
///
/// Everything that row's note says holds here: one impl replaces a hand-maintained table and
/// reproduces every name in it, the impl is local at every pair of parameters, and the schema name
/// comes from the ELEMENT'S FILTER because the element's own name is not injective — see
/// [`operand_of`](super::operand_of).
///
/// The two shapes stay two impls rather than one over a shared field list, for
/// the reason the two macro tables were two: a sequence and a set share six operator names and no
/// more, so a single face parameterised on the field list would be that list written twice at every
/// use.
#[cfg(feature = "async-graphql")]
impl<T, VF> async_graphql::InputType for SetFilter<T, VF>
where
  T: crate::ToGraphqlInput + Send + Sync,
  <T as crate::ToGraphqlInput>::Input: async_graphql::InputType,
  VF: async_graphql::InputType,
{
  type RawValueType = Self;

  fn type_name() -> ::std::borrow::Cow<'static, str> {
    let element = VF::type_name();
    ::std::borrow::Cow::Owned(::std::format!("{}SetFilter", super::operand_of(&element)))
  }

  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> {
    if let ::std::option::Option::Some(async_graphql::Value::Object(object)) = value {
      ::std::result::Result::Ok(Self {
        eq: super::via::cross_list::<T, Self>(&object, "eq")?,
        ne: super::via::cross_list::<T, Self>(&object, "ne")?,
        encloses: super::via::cross_list::<T, Self>(&object, "encloses")?,
        enclosed_by: super::via::cross_list::<T, Self>(&object, "enclosedBy")?,
        overlaps: super::via::cross_list::<T, Self>(&object, "overlaps")?,
        has_element: super::via::cross::<T, Self>(&object, "hasElement")?,
        any: super::parse_slot::<_, Self>(&object, "any")?,
        count: super::parse_slot::<_, Self>(&object, "count")?,
      })
    } else {
      ::std::result::Result::Err(async_graphql::InputValueError::expected_type(
        value.unwrap_or_default(),
      ))
    }
  }

  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, VF> async_graphql::InputObjectType for SetFilter<T, VF>
where
  T: crate::ToGraphqlInput + Send + Sync,
  <T as crate::ToGraphqlInput>::Input: async_graphql::InputType,
  VF: async_graphql::InputType,
{
}

/// The object a set face renders — the eight names in the order the registration declares them, with
/// the five collection operands and `hasElement` written back through the ELEMENT's own crossing.
///
/// The sequence face's `list_values` twin, and a function for its reason: `__ingraph_filter_value_map!`
/// renders each slot through the DOMAIN type's own `InputType`, and the crossing exists exactly
/// because the domain type may not have one.
#[cfg(feature = "async-graphql")]
fn set_values<T, VF>(
  filter: &SetFilter<T, VF>,
) -> async_graphql::indexmap::IndexMap<async_graphql::Name, async_graphql::Value>
where
  T: crate::ToGraphqlInput,
  <T as crate::ToGraphqlInput>::Input: async_graphql::InputType,
  VF: async_graphql::InputType,
{
  let mut map = async_graphql::indexmap::IndexMap::new();
  map.insert(
    async_graphql::Name::new("eq"),
    super::via::carry_list(&filter.eq),
  );
  map.insert(
    async_graphql::Name::new("ne"),
    super::via::carry_list(&filter.ne),
  );
  map.insert(
    async_graphql::Name::new("encloses"),
    super::via::carry_list(&filter.encloses),
  );
  map.insert(
    async_graphql::Name::new("enclosedBy"),
    super::via::carry_list(&filter.enclosed_by),
  );
  map.insert(
    async_graphql::Name::new("overlaps"),
    super::via::carry_list(&filter.overlaps),
  );
  map.insert(
    async_graphql::Name::new("hasElement"),
    super::via::carry(&filter.has_element),
  );
  map.insert(
    async_graphql::Name::new("any"),
    async_graphql::InputType::to_value(&filter.any),
  );
  map.insert(
    async_graphql::Name::new("count"),
    async_graphql::InputType::to_value(&filter.count),
  );
  map
}

/// The NULLABLE row — the sequence face's, for this shape.
#[cfg(feature = "async-graphql")]
impl<T, VF> crate::NullableFace for SetFilter<T, VF>
where
  T: crate::ToGraphqlInput + Send + Sync,
  <T as crate::ToGraphqlInput>::Input: async_graphql::InputType,
  VF: async_graphql::InputType,
{
  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<::std::boxed::Box<[<T as crate::ToGraphqlInput>::Input]>>,
      "ne" : ::core::option::Option<::std::boxed::Box<[<T as crate::ToGraphqlInput>::Input]>>,
      "encloses" : ::core::option::Option<::std::boxed::Box<[<T as crate::ToGraphqlInput>::Input]>>,
      "enclosedBy" : ::core::option::Option<::std::boxed::Box<[<T as crate::ToGraphqlInput>::Input]>>,
      "overlaps" : ::core::option::Option<::std::boxed::Box<[<T as crate::ToGraphqlInput>::Input]>>,
      "hasElement" : ::core::option::Option<<T as crate::ToGraphqlInput>::Input>,
      "any" : ::core::option::Option<VF>,
      "count" : ::core::option::Option<ScalarFilter<usize>>,
    )
  }

  fn bare_values(
    &self,
  ) -> async_graphql::indexmap::IndexMap<async_graphql::Name, async_graphql::Value> {
    set_values(self)
  }
}