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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
use super::*;
#[cfg(feature = "async-graphql")]
use crate::{
  flags::{self, FlagsValue},
  graphql::FlagsInput,
};

#[cfg(test)]
mod tests;

/// The FLAGS filter — seven hard words over a bit set, and four sugar words that fold into four of
/// them before anything lowers.
///
/// # The word table
///
/// | word | family | asks |
/// |---|---|---|
/// | `eq` `ne` `in` `notIn` | INTEGER | the whole value, compared or enumerated |
/// | `hasAll` | MASK | every bit of the operand is set |
/// | `hasAny` | MASK | at least one bit of the operand is set |
/// | `hasNone` | MASK | no bit of the operand is set |
/// | `isEmpty` `isAll` | sugar | the two boolean sentences |
/// | one per declared flag | sugar | that bit, set or clear |
///
/// Words CONJOIN, as every filter's do. A nullable column wraps the whole of it in
/// [`Nullable`](crate::Nullable) and gains `isNull` there, unchanged.
///
/// # There is ONE lowering authority, and the sugar never reaches it
///
/// [`FlagsFilter`] holds SEVEN slots and no more. `isEmpty`, `isAll` and the per-flag fan are
/// parsed and immediately folded into four of those seven — `eq`, `ne`, `hasAll`, `hasNone` — so a
/// comparison kind has four families to lower and no sugar to interpret, and there is exactly one
/// place in the crate that decides what `isAll` means.
///
/// The fold table, whole:
///
/// | sugar | folds to | why that word |
/// |---|---|---|
/// | `isEmpty: true` | `eq(∅)` | `Flags::is_empty` IS `bits == 0` |
/// | `isEmpty: false` | `ne(∅)` | its negation, in the same slot |
/// | `isAll: true` | `eq(ALL)` | see below |
/// | `isAll: false` | `ne(ALL)` | its negation, in the same slot |
/// | `<flag>: true` | `hasAll(bit)` | one-bit mask |
/// | `<flag>: false` | `hasNone(bit)` | one-bit mask |
///
/// **`isAll` is an equality and not a mask word**, and that is what
/// [`flags`](crate::flags)'s strictness buys. `Flags::is_all` asks whether every declared bit is
/// set and TOLERATES undeclared ones, which would be `hasAll(ALL)` — a mask word whose negation the
/// family does not have, so `isAll: false` would have nowhere to go. Since no value in this system
/// can carry an undeclared bit — both the operand door and the stored decode refuse one — `is_all`
/// and `bits == ALL` are the same question, and the equality family already carries both polarities.
///
/// **The per-flag fan MERGES where the sentences COLLIDE.** Two mask words of the same kind conjoin
/// by union — `hasAll(a) ∧ hasAll(b)` is `hasAll(a|b)` — so a fan of booleans and an explicit
/// `hasAll` accumulate into one slot with nothing lost. Two equalities do not: `eq(∅) ∧ eq(ALL)` is
/// unsatisfiable and `Option<T>` holds one operand, so a declaration writing `isEmpty` beside `eq`,
/// or `isEmpty: false` beside `isAll: false`, is REFUSED at the parse naming both words. That is
/// the same posture the declaration grammars take towards a second answer to one question.
#[derive(Debug, Clone, PartialEq)]
pub struct FlagsFilter<T> {
  pub(crate) eq: Option<T>,
  pub(crate) ne: Option<T>,
  pub(crate) in_: Option<Box<[T]>>,
  pub(crate) not_in: Option<Box<[T]>>,
  pub(crate) has_all: Option<T>,
  pub(crate) has_any: Option<T>,
  pub(crate) has_none: Option<T>,
}

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

  /// True while NO operator slot is set — so a lowering would emit nothing for this field.
  ///
  /// Inherent for [`EnumFilter`](crate::EnumFilter)'s reason: *is anything set* is a property of
  /// the FILTER and identical on every backend, and asking it should not make a caller name a
  /// dialect.
  #[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()
      && self.has_all.is_none()
      && self.has_any.is_none()
      && self.has_none.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);
  opt_accessor!(has_all: T => with_has_all, set_has_all, maybe_has_all, update_has_all);
  opt_accessor!(has_any: T => with_has_any, set_has_any, maybe_has_any, update_has_any);
  opt_accessor!(has_none: T => with_has_none, set_has_none, maybe_has_none, update_has_none);

  /// 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.
  ///
  /// The mask words never collapse, whatever else is set: `hasAll` names a SET of stored values
  /// rather than one, so `fk IN (SELECT key FROM child WHERE (key & m) = m)` is not `fk = v` for
  /// any `v`. The reasoning for the negated four is [`EnumFilter::is_referential`]'s, unchanged.
  #[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()
      && self.has_all.is_none()
      && self.has_any.is_none()
      && self.has_none.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.
  pub fn try_map<U, E, F>(self, mut f: F) -> Result<FlagsFilter<U>, E>
  where
    F: FnMut(T) -> Result<U, E>,
  {
    Ok(FlagsFilter {
      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)?,
      has_all: map_operand(self.has_all, &mut f)?,
      has_any: map_operand(self.has_any, &mut f)?,
      has_none: map_operand(self.has_none, &mut f)?,
    })
  }
}

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

impl<T, U> TryMapFilter<T, U> for FlagsFilter<T> {
  type Mapped = FlagsFilter<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)
  }
}

impl<T> EqualsFilter<T> for FlagsFilter<T> {
  #[inline]
  fn equals(value: T) -> Self {
    Self::new().with_eq(value)
  }
}

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

/// The FOLD, which is the whole reason the sugar never reaches a lowering — and which exists only
/// where there is a wire to fold sugar OFF of.
#[cfg(feature = "async-graphql")]
impl<T: FlagsValue> FlagsFilter<T> {
  /// The two boolean SENTENCES, folded into the equality family.
  ///
  /// One function for both, because they differ only in the operand they compare against — which is
  /// what makes the fold table above a table rather than two special cases.
  fn fold_sentence(&mut self, asked: bool, against: T) -> bool {
    let slot = if asked { &mut self.eq } else { &mut self.ne };
    if slot.is_some() {
      return false;
    }
    *slot = Some(against);
    true
  }

  /// One per-flag boolean, folded into the mask family by UNION — which is what the conjunction of
  /// two same-kind mask words already is, so nothing is lost and nothing collides.
  fn fold_flag(&mut self, asked: bool, bit: T) {
    let slot = if asked {
      &mut self.has_all
    } else {
      &mut self.has_none
    };
    *slot = Some(slot.map_or(bit, |held| held.union(bit)));
  }
}

/// The WIRE FACE, written over a PARAMETER for [`EnumFilter`](crate::EnumFilter)'s reason: a
/// declaring crate's flags type is not one this crate could have a table row for, and one generic
/// impl closes the set with nothing orphaned.
///
/// # The bound is [`FlagsValue`] and it is spent twice over
///
/// Where the enum face asks only that its operand crosses the wire, this one reads the DECLARED BIT
/// TABLE at runtime: the per-flag fan is one input field per bit, and the fold that answers it needs
/// the bit's value. So the bound is the vocabulary trait rather than `InputType`, and the operand's
/// own wire face comes from [`FlagsInput<T>`] — which is this crate's type, so the whole face is
/// local impls at every `T`.
///
/// # The name, and the one it is derived from
///
/// `<vocabulary>Filter` — `TrackDisposition` gives `TrackDispositionFilter` — beside
/// `TrackDispositionInput` for the operand and `TrackDisposition` for the object face. Three names,
/// one source, computed rather than spelled. The nullable twin takes `Nullable` in front of THIS
/// name for [`filter_input_object!`]'s reason.
#[cfg(feature = "async-graphql")]
impl<T: FlagsValue> async_graphql::InputType for FlagsFilter<T> {
  type RawValueType = Self;

  fn type_name() -> ::std::borrow::Cow<'static, str> {
    ::std::borrow::Cow::Owned(::std::format!("{}Filter", T::GRAPHQL_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`. A bare LIST is refused by `sent` and stays
      // refused here: a list is the operand's own first spelling AND the shape `in` takes, so a
      // bare one would be two readings of one document. `eq: ["DEFAULT"]` says which.
      super::Sent::Bare(bare) => {
        let mut object = async_graphql::indexmap::IndexMap::new();
        object.insert(async_graphql::Name::new("eq"), bare);
        object
      }
      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));
      }
    };

    let mut filter = Self {
      eq: operand::<T, Self>(&object, "eq")?,
      ne: operand::<T, Self>(&object, "ne")?,
      in_: operands::<T, Self>(&object, "in")?,
      not_in: operands::<T, Self>(&object, "notIn")?,
      has_all: operand::<T, Self>(&object, "hasAll")?,
      has_any: operand::<T, Self>(&object, "hasAny")?,
      has_none: operand::<T, Self>(&object, "hasNone")?,
    };

    // THE FOLD. Everything below this line writes into the seven slots above and nothing else, so
    // what a lowering sees is those seven whatever a document wrote.
    for (word, against) in [
      ("isEmpty", flags::empty::<T>()),
      ("isAll", flags::all::<T>()),
    ] {
      let ::std::option::Option::Some(asked) =
        parse_slot::<::std::option::Option<bool>, Self>(&object, word)?
      else {
        continue;
      };
      if !filter.fold_sentence(asked, against) {
        return ::std::result::Result::Err(async_graphql::InputValueError::custom(::std::format!(
          "`{word}` is `{}` compared against a value, and this filter already carries one — a \
           conjunction of two equalities on one column is not something one slot can hold. Write \
           the one you mean",
          if asked { "eq" } else { "ne" }
        )));
      }
    }
    for bit in flags::bits::<T>() {
      if let ::std::option::Option::Some(asked) =
        parse_slot::<::std::option::Option<bool>, Self>(&object, bit.field)?
      {
        filter.fold_flag(asked, bit.value);
      }
    }

    ::std::result::Result::Ok(filter)
  }

  /// The SEVEN hard words, and no sugar.
  ///
  /// A filter holds no sugar to render — the fold consumed it at the parse — so what comes back out
  /// is the canonical form of whatever went in. That is the same *wide in, strict out* bargain the
  /// operand scalar makes, one layer up.
  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)
  }
}

/// One operand slot, read through the wide door and unwrapped.
#[cfg(feature = "async-graphql")]
fn operand<T: FlagsValue, F: async_graphql::InputType>(
  object: &async_graphql::indexmap::IndexMap<async_graphql::Name, async_graphql::Value>,
  name: &str,
) -> Result<Option<T>, async_graphql::InputValueError<F>> {
  Ok(parse_slot::<Option<FlagsInput<T>>, F>(object, name)?.map(FlagsInput::into_inner))
}

/// One membership slot, read through the wide door once per element.
#[cfg(feature = "async-graphql")]
fn operands<T: FlagsValue, F: async_graphql::InputType>(
  object: &async_graphql::indexmap::IndexMap<async_graphql::Name, async_graphql::Value>,
  name: &str,
) -> Result<Option<Box<[T]>>, async_graphql::InputValueError<F>> {
  Ok(
    parse_slot::<Option<Box<[FlagsInput<T>]>>, F>(object, name)?.map(|carried| {
      carried
        .into_vec()
        .into_iter()
        .map(FlagsInput::into_inner)
        .collect()
    }),
  )
}

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

/// The NULLABLE row, and the field list both faces read.
///
/// The list is assembled rather than written out, because half of it is the DECLARATION's: seven
/// hard words, two sentences, then one boolean per declared bit in declaration order. A
/// `filter_input_object!` invocation cannot express that half — its pairs are literals — which is
/// why this face is written by hand where every other registered filter's is generated.
#[cfg(feature = "async-graphql")]
impl<T: FlagsValue> crate::NullableFace for FlagsFilter<T> {
  fn bare_fields(
    registry: &mut async_graphql::registry::Registry,
  ) -> async_graphql::indexmap::IndexMap<
    ::std::string::String,
    async_graphql::registry::MetaInputValue,
  > {
    let mut fields = __ingraph_filter_input_fields!(
      registry,
      "eq" : ::core::option::Option<FlagsInput<T>>,
      "ne" : ::core::option::Option<FlagsInput<T>>,
      "in" : ::core::option::Option<::std::boxed::Box<[FlagsInput<T>]>>,
      "notIn" : ::core::option::Option<::std::boxed::Box<[FlagsInput<T>]>>,
      "hasAll" : ::core::option::Option<FlagsInput<T>>,
      "hasAny" : ::core::option::Option<FlagsInput<T>>,
      "hasNone" : ::core::option::Option<FlagsInput<T>>,
      "isEmpty" : ::core::option::Option<bool>,
      "isAll" : ::core::option::Option<bool>,
    );
    let boolean =
      <::core::option::Option<bool> as async_graphql::InputType>::create_type_info(registry);
    for bit in flags::bits::<T>() {
      fields.insert(
        ::std::string::String::from(bit.field),
        async_graphql::registry::MetaInputValue {
          name: ::std::string::String::from(bit.field),
          description: ::std::option::Option::None,
          ty: boolean.clone(),
          deprecation: async_graphql::registry::Deprecation::NoDeprecated,
          default_value: ::std::option::Option::None,
          visible: ::std::option::Option::None,
          inaccessible: false,
          tags: ::std::vec::Vec::new(),
          is_secret: false,
          directive_invocations: ::std::vec::Vec::new(),
        },
      );
    }
    fields
  }

  fn bare_values(
    &self,
  ) -> async_graphql::indexmap::IndexMap<async_graphql::Name, async_graphql::Value> {
    let carried = FlagsFilter {
      eq: self.eq.map(FlagsInput::new),
      ne: self.ne.map(FlagsInput::new),
      in_: self
        .in_
        .as_ref()
        .map(|values| values.iter().copied().map(FlagsInput::new).collect()),
      not_in: self
        .not_in
        .as_ref()
        .map(|values| values.iter().copied().map(FlagsInput::new).collect()),
      has_all: self.has_all.map(FlagsInput::new),
      has_any: self.has_any.map(FlagsInput::new),
      has_none: self.has_none.map(FlagsInput::new),
    };
    __ingraph_filter_value_map!(
      carried,
      "eq" : eq,
      "ne" : ne,
      "in" : in_,
      "notIn" : not_in,
      "hasAll" : has_all,
      "hasAny" : has_any,
      "hasNone" : has_none
    )
  }
}