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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
use core::marker::PhantomData;

use super::*;
use crate::graphql::carrier::Builtin;

/// The scalar / orderable filter — every ordering + equality + membership operator.
/// `T` is the field's Rust type; a set slot lowers through that type's own backend operand impl.
///
/// # The second parameter, and what it is for
///
/// `I` names the reading the operands cross the wire under — see [`ScalarWire`](crate::ScalarWire) —
/// and it is what lets a DECLARING crate give its own scalar a wire face. The framework's wire face
/// is ONE generic row over `I`, so there is no second row for coherence to hit and the PARAMETER
/// renames nothing: [`Builtin`] carries `i32` under `I32Filter`, `Timestamp` under
/// `TimestampFilter` and `usize` under `CountFilter`, and which name each of those is comes from the
/// roster rather than from this type — see [`roster`](crate::graphql::roster) for the law that
/// decides it.
///
/// It DEFAULTS, so every spelling written before the axis existed means what it meant:
/// `ScalarFilter<i64>` IS `ScalarFilter<i64, Builtin>`.
///
/// The parameter takes no part in the operators, the crossing into a comparison, or storage — it is
/// read at the wire face and nowhere else, which is why [`try_map`](Self::try_map) carries it
/// through unchanged: what a storage type changes is the VALUE, not the reading.
pub struct ScalarFilter<T, I = Builtin> {
  pub(crate) eq: Option<T>,
  pub(crate) ne: Option<T>,
  pub(crate) gt: Option<T>,
  pub(crate) gte: Option<T>,
  pub(crate) lt: Option<T>,
  pub(crate) lte: Option<T>,
  pub(crate) in_: Option<Box<[T]>>,
  pub(crate) not_in: Option<Box<[T]>>,
  // `fn() -> I` (not a bare `I`) so the reading contributes no auto-trait or variance obligation:
  // the filter is `Send`/`Sync` on `T` alone, exactly as before the parameter existed. The shape
  // [`TextFilter`]'s own reading parameter takes, for the same reason.
  pub(crate) wire: PhantomData<fn() -> I>,
}

impl<T, I> ScalarFilter<T, I> {
  /// The empty filter — no operator set.
  #[inline]
  pub const fn new() -> Self {
    Self {
      eq: None,
      ne: None,
      gt: None,
      gte: None,
      lt: None,
      lte: None,
      in_: None,
      not_in: None,
      wire: PhantomData,
    }
  }

  /// 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.gt.is_none()
      && self.gte.is_none()
      && self.lt.is_none()
      && self.lte.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!(gt: T => with_gt, set_gt, maybe_gt, update_gt);
  opt_accessor!(gte: T => with_gte, set_gte, maybe_gte, update_gte);
  opt_accessor!(lt: T => with_lt, set_lt, maybe_lt, update_lt);
  opt_accessor!(lte: T => with_lte, set_lte, maybe_lte, update_lte);
  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.
  ///
  /// A NULLABLE key's filter never reaches this question: it is a [`Nullable<ScalarFilter<T>>`], and
  /// the wrapper has no `is_referential` of its own. So the null test — which names no child row
  /// either — cannot be smuggled into a collapse by asking the inner filter, because the answer the
  /// caller needs is not one the inner filter offers.
  #[inline]
  pub const fn is_referential(&self) -> bool {
    let one_set = self.eq.is_some() ^ self.in_.is_some();
    one_set
      && self.ne.is_none()
      && self.gt.is_none()
      && self.gte.is_none()
      && self.lt.is_none()
      && self.lte.is_none()
      && self.not_in.is_none()
  }

  /// Convert every set operand with `f`, keeping the operator set exactly as it stands.
  ///
  /// The primitive the CROSSING is built on: a comparison's `try_from_filter` is this call with the
  /// storage type's own [`TryFrom`] supplied, and a declared converter is this call with a named
  /// function supplied. Public for the same reason: the crossing that needs it is not always this
  /// crate's, and a downstream filter type composed of these kinds has to reach it.
  ///
  /// It TRANSFORMS without exposing — the operands never leave the filter — where the getters above
  /// INSPECT without moving. The two are complements rather than alternatives.
  ///
  /// Consuming, so the identity map moves its operands rather than cloning them. A list slot is
  /// converted element by element and the first failure wins; an empty list stays an empty list, so
  /// `in: []` keeps asking for no rows.
  pub fn try_map<U, E, F>(self, mut f: F) -> Result<ScalarFilter<U, I>, E>
  where
    F: FnMut(T) -> Result<U, E>,
  {
    Ok(ScalarFilter {
      eq: map_operand(self.eq, &mut f)?,
      ne: map_operand(self.ne, &mut f)?,
      gt: map_operand(self.gt, &mut f)?,
      gte: map_operand(self.gte, &mut f)?,
      lt: map_operand(self.lt, &mut f)?,
      lte: map_operand(self.lte, &mut f)?,
      in_: map_operands(self.in_, &mut f)?,
      not_in: map_operands(self.not_in, &mut f)?,
      wire: PhantomData,
    })
  }
}

/// The bound's row: [`try_map`](ScalarFilter::try_map) itself, reached where the kind is a parameter
/// rather than a spelling.
///
/// The READING rides through unchanged, for the reason [`TextFilter`]'s row states: a crossing
/// converts the operands and asks nothing of the wire, so resetting it to [`Builtin`] would silently
/// claim the framework's reading of a type it has never heard of.
impl<T, U, I> TryMapFilter<T, U> for ScalarFilter<T, I> {
  type Mapped = ScalarFilter<U, I>;

  #[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, I> EqualsFilter<T> for ScalarFilter<T, I> {
  #[inline]
  fn equals(value: T) -> Self {
    Self::new().with_eq(value)
  }
}

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

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

// `Debug`, `Clone` and `PartialEq` are written out rather than derived, for the reason
// [`TextFilter`]'s and [`BytesFilter`]'s are: a derive would put its bound on EVERY parameter, so
// `ScalarFilter<Rate, RateWire>` would be `Clone` only while a reading marker nobody constructs were
// `Clone` too. The operands decide, and the reading takes no part.
impl<T: core::fmt::Debug, I> core::fmt::Debug for ScalarFilter<T, I> {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("ScalarFilter")
      .field("eq", &self.eq)
      .field("ne", &self.ne)
      .field("gt", &self.gt)
      .field("gte", &self.gte)
      .field("lt", &self.lt)
      .field("lte", &self.lte)
      .field("in_", &self.in_)
      .field("not_in", &self.not_in)
      .finish()
  }
}

impl<T: Clone, I> Clone for ScalarFilter<T, I> {
  fn clone(&self) -> Self {
    Self {
      eq: self.eq.clone(),
      ne: self.ne.clone(),
      gt: self.gt.clone(),
      gte: self.gte.clone(),
      lt: self.lt.clone(),
      lte: self.lte.clone(),
      in_: self.in_.clone(),
      not_in: self.not_in.clone(),
      wire: PhantomData,
    }
  }
}

impl<T: PartialEq, I> PartialEq for ScalarFilter<T, I> {
  fn eq(&self, other: &Self) -> bool {
    self.eq == other.eq
      && self.ne == other.ne
      && self.gt == other.gt
      && self.gte == other.gte
      && self.lt == other.lt
      && self.lte == other.lte
      && self.in_ == other.in_
      && self.not_in == other.not_in
  }
}

/// The field list this face registers, in declaration order.
///
/// One function read by the face and by its [`NullableFace`](crate::NullableFace) row alike — the
/// arrangement [`TextFilter`]'s own face states: *the nullable face is the bare face's fields plus
/// the null test* is one list read twice rather than two lists kept in step by hand.
///
/// Every slot is typed `I::Carrier` and not `T`: the operands cross, so what a client writes is the
/// CARRIER's form, and the domain type's own wire face — which it may not have — is exactly what
/// this face does not ask for.
#[cfg(feature = "async-graphql")]
fn scalar_fields<T, I>(
  registry: &mut async_graphql::registry::Registry,
) -> async_graphql::indexmap::IndexMap<::std::string::String, async_graphql::registry::MetaInputValue>
where
  I: crate::ScalarWire<T>,
  I::Carrier: async_graphql::InputType,
{
  __ingraph_filter_input_fields!(
    registry,
    "eq" : ::core::option::Option<<I as crate::ScalarWire<T>>::Carrier>,
    "ne" : ::core::option::Option<<I as crate::ScalarWire<T>>::Carrier>,
    "gt" : ::core::option::Option<<I as crate::ScalarWire<T>>::Carrier>,
    "gte" : ::core::option::Option<<I as crate::ScalarWire<T>>::Carrier>,
    "lt" : ::core::option::Option<<I as crate::ScalarWire<T>>::Carrier>,
    "lte" : ::core::option::Option<<I as crate::ScalarWire<T>>::Carrier>,
    "in" : ::core::option::Option<::std::boxed::Box<[<I as crate::ScalarWire<T>>::Carrier]>>,
    "notIn" : ::core::option::Option<::std::boxed::Box<[<I as crate::ScalarWire<T>>::Carrier]>>,
  )
}

/// The object this face renders — the same eight names in the same order the registration declares.
#[cfg(feature = "async-graphql")]
fn scalar_values<T, I>(
  filter: &ScalarFilter<T, I>,
) -> async_graphql::indexmap::IndexMap<async_graphql::Name, async_graphql::Value>
where
  I: crate::ScalarWire<T>,
  I::Carrier: async_graphql::InputType,
{
  let mut map = async_graphql::indexmap::IndexMap::new();
  map.insert(
    async_graphql::Name::new("eq"),
    via::carried(&filter.eq, I::carry),
  );
  map.insert(
    async_graphql::Name::new("ne"),
    via::carried(&filter.ne, I::carry),
  );
  map.insert(
    async_graphql::Name::new("gt"),
    via::carried(&filter.gt, I::carry),
  );
  map.insert(
    async_graphql::Name::new("gte"),
    via::carried(&filter.gte, I::carry),
  );
  map.insert(
    async_graphql::Name::new("lt"),
    via::carried(&filter.lt, I::carry),
  );
  map.insert(
    async_graphql::Name::new("lte"),
    via::carried(&filter.lte, I::carry),
  );
  map.insert(
    async_graphql::Name::new("in"),
    via::carried_list(&filter.in_, I::carry),
  );
  map.insert(
    async_graphql::Name::new("notIn"),
    via::carried_list(&filter.not_in, I::carry),
  );
  map
}

/// The WIRE FACE, and the row the CARRIER AXIS was extended for: ONE generic impl over the reading,
/// where this crate carried twenty-seven concrete registrations.
///
/// # What one row buys that twenty-seven could not
///
/// A declaring crate cannot write `impl InputType for ScalarFilter<Rate>` — `E0117`, both the trait
/// and the outer type being foreign to it, and RFC 2451 does not admit `ForeignTrait for
/// ForeignType<Local>` — and this crate could not have written a generic row beside the concrete
/// ones, those being impls a generic one overlaps (`E0119`). So a declarer's own single-column
/// scalar reached the framework's ordering face in neither crate, and the road left was to MINT a
/// filter of its own. With every concrete row moved onto [`Builtin`] as
/// [`ScalarWire`](crate::ScalarWire) rows there is exactly one impl here, coherence has nothing to
/// reason about, and a declaring crate joins by implementing that trait on a marker it owns.
///
/// # The NAME comes from the reading
///
/// `I::NAME`, so a name is a property of the READING and never of this type: `Builtin`'s row for
/// `i32` names `I32Filter` — derived from the roster's scalar name — and its row for `usize` names
/// `CountFilter`, which is a role rather than a width. A declarer's marker names its own, and the
/// clash rule is async-graphql's own — `Registry::create_type` panics when one schema puts two Rust
/// types under one GraphQL name.
///
/// # The bound is the reading and nothing else
///
/// Not `T: InputType`: the operands cross through `I::Carrier`, so the OPERAND's own wire face is
/// exactly what this face does not ask for — which is what admits `u128`, an operand with no
/// `InputType` in any crate but async-graphql's own.
///
/// `I::Carrier: InputType` IS async-graphql's demand, written HERE rather than on the trait's seat
/// because that is the law: the map says which form an operand crosses as, and each backend asks
/// what it needs of that form where it SPENDS it.
///
/// `T: Send + Sync` is not a second face — it is `InputType`'s own supertrait, asked of `Self` and
/// reaching `T` through the eight `Option<T>` slots.
#[cfg(feature = "async-graphql")]
impl<T, I> async_graphql::InputType for ScalarFilter<T, I>
where
  T: Send + Sync,
  I: crate::ScalarWire<T>,
  I::Carrier: async_graphql::InputType,
{
  type RawValueType = Self;

  #[inline]
  fn type_name() -> ::std::borrow::Cow<'static, str> {
    ::std::borrow::Cow::Borrowed(<I as crate::ScalarWire<T>>::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::string::String::from(<I as crate::ScalarWire<T>>::NAME),
        description: ::std::option::Option::None,
        input_fields: scalar_fields::<T, I>(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(),
      },
    )
  }

  /// # The SHORTHAND LAW, at the ordering face
  ///
  /// Rule ① — a bare value is this filter's `eq`, put under that key so the CARRIER crossing below
  /// is the same one the longhand takes rather than a second reading of the operand. An explicit
  /// `null` is the NULL TEST, which this face has not got: a `NOT NULL` column cannot be asked
  /// whether it is null, and refusing here is that fact rather than a gap.
  fn parse(
    value: ::std::option::Option<async_graphql::Value>,
  ) -> async_graphql::InputValueResult<Self> {
    let object = match super::sent(value) {
      super::Sent::Longhand(object) => object,
      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));
      }
    };
    ::std::result::Result::Ok(Self {
      eq: via::crossed::<_, _, _, Self>(&object, "eq", I::cross)?,
      ne: via::crossed::<_, _, _, Self>(&object, "ne", I::cross)?,
      gt: via::crossed::<_, _, _, Self>(&object, "gt", I::cross)?,
      gte: via::crossed::<_, _, _, Self>(&object, "gte", I::cross)?,
      lt: via::crossed::<_, _, _, Self>(&object, "lt", I::cross)?,
      lte: via::crossed::<_, _, _, Self>(&object, "lte", I::cross)?,
      in_: via::crossed_list::<_, _, _, Self>(&object, "in", I::cross)?,
      not_in: via::crossed_list::<_, _, _, Self>(&object, "notIn", I::cross)?,
      wire: PhantomData,
    })
  }

  fn to_value(&self) -> async_graphql::Value {
    async_graphql::Value::Object(scalar_values::<T, I>(self))
  }

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

#[cfg(feature = "async-graphql")]
impl<T, I> async_graphql::InputObjectType for ScalarFilter<T, I>
where
  T: Send + Sync,
  I: crate::ScalarWire<T>,
  I::Carrier: async_graphql::InputType,
{
}

/// The NULLABLE row — the two pieces [`Nullable`]'s own blanket assembles this kind's twin from.
#[cfg(feature = "async-graphql")]
impl<T, I> crate::NullableFace for ScalarFilter<T, I>
where
  T: Send + Sync,
  I: crate::ScalarWire<T>,
  I::Carrier: async_graphql::InputType,
{
  fn bare_fields(
    registry: &mut async_graphql::registry::Registry,
  ) -> async_graphql::indexmap::IndexMap<
    ::std::string::String,
    async_graphql::registry::MetaInputValue,
  > {
    scalar_fields::<T, I>(registry)
  }

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