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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
//! What the two collection kinds render, and the three things an element scope refuses.

/// The COMPOSITE element's own corpus — a sub-document array, which this backend answers with the
/// rows it already had. Its own file because the finding is that nothing widened.
mod composite;

use bson::{Document, doc};

use super::{MongoCollectionCrossingError, MongoListComparison, MongoSetComparison};
use crate::{
  At, ComplexComparison, FieldName, ListFilter, Mongo, QuantifiedFilter, RecordAddress,
  ScalarFilter, SetFilter, TextFilter, TryFromFilter,
  comparison::mongo::{
    MongoConjunction, MongoLoweringError, MongoOperator, MongoScalarComparison, MongoTextComparison,
  },
};

/// The row every address below names. Nothing here is correlated, so no test reads it.
const ROW: RecordAddress = RecordAddress::new(FieldName::new("media"), &[FieldName::new("id")]);

/// A sequence of `i64` whose members are guarded by a scalar comparison — the ordinary shape.
type Sequence = MongoListComparison<i64, MongoScalarComparison<i64>>;
/// A set of `i64`, likewise.
type Set = MongoSetComparison<i64, MongoScalarComparison<i64>>;

/// Lower one comparison at one column of [`ROW`] and finish the filter.
fn rendered<C: ComplexComparison<Mongo>>(comparison: &C, column: &str) -> Document {
  let frame = At::new(&ROW).frame(FieldName::new(column));
  comparison
    .apply(frame.at(), MongoConjunction::new())
    .expect("this comparison writes nothing an element scope has to hold")
    .into_document()
}

/// The refusal one comparison's lowering gives, or `None`.
fn refusal<C: ComplexComparison<Mongo>>(comparison: &C) -> Option<MongoLoweringError> {
  let frame = At::new(&ROW).frame(FieldName::new("tags"));
  comparison.apply(frame.at(), MongoConjunction::new()).err()
}

/// The whole array is the operand, and it needs no encoding of its own: a list of operands and a
/// stored array are the same BSON value, which is what the SQL family's canonical JSON string
/// exists to work around.
#[test]
fn whole_collection_equality_binds_the_array_itself() {
  let comparison =
    Sequence::try_from_filter(ListFilter::<i64>::new().with_eq([1, 2])).expect("the identity");
  assert_eq!(
    rendered(&comparison, "tags"),
    doc! { "tags": { "$eq": [ 1i64, 2i64 ] } }
  );
}

/// **The measurement this kind rests on.** BSON compares an array field against an ARRAY operand
/// element-wise and lexicographically, because a comparison operator is TYPE-BRACKETED and considers
/// no other type — so the four ordering slots are wired rather than refused, and this backend agrees
/// with Postgres about a question SQLite and MySQL both decline.
#[test]
fn the_ordering_operators_are_wired_rather_than_refused() {
  let comparison = Sequence::try_from_filter(
    ListFilter::<i64>::new()
      .with_gt([1])
      .with_gte([2])
      .with_lt([3])
      .with_lte([4]),
  )
  .expect("the identity");

  assert_eq!(comparison.conjuncts(), 4);
  assert_eq!(
    rendered(&comparison, "tags"),
    doc! {
      "tags": {
        "$gt": [ 1i64 ],
        "$gte": [ 2i64 ],
        "$lt": [ 3i64 ],
        "$lte": [ 4i64 ],
      },
    }
  );
}

/// `has_element` is the bare member match, which is exactly what implicit traversal already does —
/// so it writes `$eq`, the key the whole-collection equality also writes, and the second becomes an
/// `$and` branch through the fold built for that case.
#[test]
fn membership_and_whole_collection_equality_share_a_key_and_overflow() {
  let comparison =
    Sequence::try_from_filter(ListFilter::<i64>::new().with_eq([1, 2]).with_has_element(5))
      .expect("the identity");

  assert_eq!(
    rendered(&comparison, "tags"),
    doc! {
      "tags": { "$eq": [ 1i64, 2i64 ] },
      "$and": [ { "tags": { "$eq": 5i64 } } ],
    }
  );
}

/// The element scope's whole point: ONE member satisfies the comparison, where the bare operators
/// MongoDB applies per member may be satisfied by different ones. The member's operators are the
/// scope document's own keys, because the member has no field name.
#[test]
fn the_element_scope_writes_the_members_operators_bare() {
  let comparison = Sequence::try_from_filter(
    ListFilter::<i64>::new().with_any(ScalarFilter::new().with_gt(1).with_lt(6)),
  )
  .expect("the identity");

  assert_eq!(comparison.conjuncts(), 1);
  assert_eq!(
    rendered(&comparison, "tags"),
    doc! { "tags": { "$elemMatch": { "$gt": 1i64, "$lt": 6i64 } } }
  );
}

/// An EMPTY element comparison is a predicate rather than the absence of one — `∃x. true` is
/// `S ≠ ∅` — and `{}` is not it: measured, an empty scope document matches only members that are
/// documents. `{$exists: true}` is the tautology over members, and it renders the non-empty arrays.
#[test]
fn an_empty_element_comparison_asks_for_a_non_empty_collection() {
  let comparison =
    Sequence::try_from_filter(ListFilter::<i64>::new().with_any(ScalarFilter::new()))
      .expect("the identity");

  assert!(!comparison.is_empty());
  assert_eq!(
    rendered(&comparison, "tags"),
    doc! { "tags": { "$elemMatch": { "$exists": true } } }
  );
}

/// A cardinality lands BESIDE the field's keys rather than under them, because `$expr` is a
/// top-level operator — so a collection asked two questions renders one merged key and one `$and`
/// branch.
#[test]
fn a_cardinality_lands_beside_the_fields_keys() {
  let comparison = Sequence::try_from_filter(
    ListFilter::<i64>::new()
      .with_has_element(5)
      .with_count(ScalarFilter::new().with_gt(3)),
  )
  .expect("the identity");

  assert_eq!(comparison.conjuncts(), 2);
  assert_eq!(
    rendered(&comparison, "tags"),
    doc! {
      "tags": { "$eq": 5i64 },
      "$and": [ {
        "$expr": {
          "$and": [
            { "$isArray": "$tags" },
            { "$gt": [ { "$size": "$tags" }, 3i64 ] },
          ],
        },
      } ],
    }
  );
}

/// An empty `count` folds in where an empty `any` does not, and the QUANTIFIER is the whole of the
/// difference: nothing quantifies a length, so asking nothing about one excludes no document.
#[test]
fn an_empty_cardinality_folds_in() {
  let comparison =
    Sequence::try_from_filter(ListFilter::<i64>::new().with_count(ScalarFilter::new()))
      .expect("the identity");

  assert!(comparison.is_empty());
  assert!(rendered(&comparison, "tags").is_empty());
}

/// **THE NARROW KIND LOWERS THROUGH THE WIDE KIND'S OWN TWO ARMS**, so what it renders is what the
/// wide filter renders with its other seven slots unset — asserted as document EQUALITY between the
/// two crossings rather than by re-stating the expected BSON, which is the only form of the claim a
/// second implementation could not pass.
///
/// The crossing takes no element converter and can refuse no operand: its
/// [`Operand`](MongoCollectionCrossingError::Operand) variant carries `Infallible`. What is left is
/// the element filter's own refusal and a cardinality past `i64`, which are the two the wide kinds
/// have as well.
#[test]
fn the_quantified_crossing_renders_what_the_wide_one_does() {
  let narrow = Sequence::try_from_filter(
    QuantifiedFilter::<i64>::new()
      .with_any(ScalarFilter::new().with_gt(1).with_lt(6))
      .with_count(ScalarFilter::new().with_gte(2)),
  )
  .expect("a quantified crossing refuses no operand");
  let wide = Sequence::try_from_filter(
    ListFilter::<i64>::new()
      .with_any(ScalarFilter::new().with_gt(1).with_lt(6))
      .with_count(ScalarFilter::new().with_gte(2)),
  )
  .expect("the identity");

  assert_eq!(narrow, wide);
  assert_eq!(narrow.conjuncts(), wide.conjuncts());
  assert_eq!(rendered(&narrow, "tags"), rendered(&wide, "tags"));
}

/// The QUANTIFIER law survives the crossing intact, which is the half of the reading that could have
/// been lost by a kind carrying only these two slots: a present `any` holding an empty element
/// filter renders the non-empty test, and a present `count` holding an empty scalar filter renders
/// nothing at all.
#[test]
fn the_quantifier_law_crosses_with_the_two_slots() {
  let quantified =
    Sequence::try_from_filter(QuantifiedFilter::<i64>::new().with_any(ScalarFilter::new()))
      .expect("a quantified crossing refuses no operand");

  assert!(!quantified.is_empty());
  assert_eq!(
    rendered(&quantified, "tags"),
    doc! { "tags": { "$elemMatch": { "$exists": true } } }
  );

  let counted =
    Sequence::try_from_filter(QuantifiedFilter::<i64>::new().with_count(ScalarFilter::new()))
      .expect("a quantified crossing refuses no operand");

  assert!(counted.is_empty());
  assert!(rendered(&counted, "tags").is_empty());
}

/// The seven element slots stay UNSET, and they stay unset structurally: nothing in the crossing
/// writes them. Read back off the comparison's own getters, so a slot arriving would red this rather
/// than pass as an extra key nobody looked for.
#[test]
fn the_quantified_crossing_leaves_every_element_slot_absent() {
  let comparison = Sequence::try_from_filter(
    QuantifiedFilter::<i64>::new().with_any(ScalarFilter::new().with_eq(1)),
  )
  .expect("a quantified crossing refuses no operand");

  assert!(comparison.has_element().is_none());
  assert!(comparison.eq().is_none());
  assert!(comparison.ne().is_none());
  assert!(comparison.gt().is_none());
  assert!(comparison.gte().is_none());
  assert!(comparison.lt().is_none());
  assert!(comparison.lte().is_none());
  assert_eq!(comparison.conjuncts(), 1);
}

/// The CARDINALITY refusal is the one this crossing keeps, and it is the family's rather than the
/// element's: a length is compared as `i64` here whatever the members are, so an operand past that
/// is refused rather than saturated.
#[test]
fn a_cardinality_past_the_family_integer_is_refused() {
  let refused = Sequence::try_from_filter(
    QuantifiedFilter::<i64>::new().with_count(ScalarFilter::new().with_eq(usize::MAX)),
  );

  assert!(matches!(
    refused,
    Err(MongoCollectionCrossingError::Cardinality(_))
  ));
}

/// The three set operators MongoDB has directly.
#[test]
fn the_direct_set_operators_are_one_key_each() {
  let comparison = Set::try_from_filter(
    SetFilter::<i64>::new()
      .with_encloses([1, 2])
      .with_overlaps([3])
      .with_has_element(4),
  )
  .expect("the identity");

  assert_eq!(
    rendered(&comparison, "tags"),
    doc! {
      "tags": {
        "$all": [ 1i64, 2i64 ],
        "$in": [ 3i64 ],
        "$eq": 4i64,
      },
    }
  );
}

/// A subset test says *no member lies outside the operand*, which a document with NO such field
/// satisfies vacuously — so the guard is what makes this backend answer the same question Postgres's
/// `<@` answers on a NULL column, which is no rows.
#[test]
fn a_subset_test_is_guarded_against_the_missing_field() {
  let comparison =
    Set::try_from_filter(SetFilter::<i64>::new().with_enclosed_by([1, 2])).expect("the identity");

  assert_eq!(
    rendered(&comparison, "tags"),
    doc! {
      "tags": {
        "$type": "array",
        "$not": { "$elemMatch": { "$nin": [ 1i64, 2i64 ] } },
      },
    }
  );
}

/// Set equality is MUTUAL containment, which is three operators rather than the `$eq` a sequence
/// takes: `{tags: {$eq: [1,2]}}` is ordered and multiplicity-sensitive and would answer a different
/// question under the same operator name.
#[test]
fn set_equality_is_mutual_containment() {
  let comparison =
    Set::try_from_filter(SetFilter::<i64>::new().with_eq([1, 2])).expect("the identity");

  assert_eq!(
    rendered(&comparison, "tags"),
    doc! {
      "tags": {
        "$type": "array",
        "$all": [ 1i64, 2i64 ],
        "$not": { "$elemMatch": { "$nin": [ 1i64, 2i64 ] } },
      },
    }
  );
}

/// Negating a conjunction is a DISJUNCTION, which no operator document can hold — `$not` takes one
/// operator's operand rather than a field's whole predicate — so a set inequality is `$nor` of
/// exactly the equality document.
#[test]
fn set_inequality_negates_the_whole_equality_document() {
  let comparison =
    Set::try_from_filter(SetFilter::<i64>::new().with_ne([1, 2])).expect("the identity");

  assert_eq!(
    rendered(&comparison, "tags"),
    doc! {
      "$and": [ {
        "$nor": [ {
          "tags": {
            "$type": "array",
            "$all": [ 1i64, 2i64 ],
            "$not": { "$elemMatch": { "$nin": [ 1i64, 2i64 ] } },
          },
        } ],
      } ],
    }
  );
}

/// **The empty operand is where `$all` stops meaning what set theory means.** Every set encloses the
/// empty one and `{$all: []}` matches NO document, so an empty `encloses` renders the vacuous truth
/// directly: this field is an array.
#[test]
fn enclosing_nothing_is_the_guard_alone() {
  let comparison =
    Set::try_from_filter(SetFilter::<i64>::new().with_encloses([])).expect("the identity");

  assert_eq!(
    rendered(&comparison, "tags"),
    doc! { "tags": { "$type": "array" } }
  );
}

/// The same omission inside set equality leaves *is an array, and no member lies outside nothing* —
/// which is the empty array, and measured to be exactly it.
#[test]
fn equality_with_an_empty_operand_drops_only_the_all() {
  let comparison = Set::try_from_filter(SetFilter::<i64>::new().with_eq([])).expect("the identity");

  assert_eq!(
    rendered(&comparison, "tags"),
    doc! {
      "tags": {
        "$type": "array",
        "$not": { "$elemMatch": { "$nin": [] } },
      },
    }
  );
}

/// An empty `overlaps` is NOT a degeneration and gets no special case: an empty intersection is
/// empty, so matching nothing is the answer.
#[test]
fn overlapping_nothing_matches_nothing_by_the_operators_own_reading() {
  let comparison =
    Set::try_from_filter(SetFilter::<i64>::new().with_overlaps([])).expect("the identity");

  assert_eq!(
    rendered(&comparison, "tags"),
    doc! { "tags": { "$in": [] } }
  );
}

/// Two slots writing the same key overflow into `$and`, exactly as the text kind's affix slots do —
/// and where the shared key is the GUARD, the extra branch says a true thing twice. Correct rather
/// than minimal.
#[test]
fn two_set_operators_sharing_a_key_overflow() {
  let comparison = Set::try_from_filter(
    SetFilter::<i64>::new()
      .with_eq([1])
      .with_enclosed_by([1, 2]),
  )
  .expect("the identity");

  assert_eq!(
    rendered(&comparison, "tags"),
    doc! {
      "tags": {
        "$type": "array",
        "$all": [ 1i64 ],
        "$not": { "$elemMatch": { "$nin": [ 1i64 ] } },
      },
      "$and": [
        { "tags": { "$type": "array" } },
        { "tags": { "$not": { "$elemMatch": { "$nin": [ 1i64, 2i64 ] } } } },
      ],
    }
  );
}

/// **The refusal the element scope exists to make.** A text member setting two positive affix
/// operators writes `$regex` twice, which at a field overflows into `$and` and inside `$elemMatch`
/// has no spelling: measured, `{$elemMatch: {$and: [{$gt: 1}]}}` is *unknown top level operator*.
#[test]
fn an_element_comparison_that_overflows_is_refused() {
  let comparison = MongoListComparison::<String, MongoTextComparison<String>>::try_from_filter(
    ListFilter::<String, TextFilter<String>>::new().with_any(
      TextFilter::<String>::new()
        .with_contains("cam".to_owned())
        .with_starts_with("ca".to_owned()),
    ),
  )
  .expect("the identity");

  assert_eq!(
    refusal(&comparison),
    Some(MongoLoweringError::ElementConjunction)
  );
}

/// A member setting ONE affix operator is refused nothing, which is what makes the refusal above
/// exact rather than a whole kind declined.
#[test]
fn one_affix_operator_on_a_member_renders() {
  let comparison = MongoListComparison::<String, MongoTextComparison<String>>::try_from_filter(
    ListFilter::<String, TextFilter<String>>::new()
      .with_any(TextFilter::<String>::new().with_contains("cam".to_owned())),
  )
  .expect("the identity");

  assert_eq!(
    rendered(&comparison, "tags"),
    doc! {
      "tags": {
        "$elemMatch": {
          "$regex": bson::Regex {
            pattern: "cam".try_into().unwrap(),
            options: "".try_into().unwrap(),
          },
        },
      },
    }
  );
}

/// `$all` inside an element scope is the DANGEROUS row: the server raises nothing and matches
/// nothing. The refusal names it, which is what [`MongoOperator::in_element_scope`] is a per-row
/// fact for.
#[test]
fn an_operator_the_element_scope_ignores_is_refused_by_name() {
  let comparison = MongoListComparison::<i64, Set>::try_from_filter(
    ListFilter::<i64, SetFilter<i64>>::new().with_any(SetFilter::new().with_encloses([1])),
  )
  .expect("the identity");

  assert_eq!(
    refusal(&comparison),
    Some(MongoLoweringError::ElementOperator(MongoOperator::All))
  );
}

/// A nested cardinality needs `$expr`, which the server allows only at the top level — so a member
/// asked how long IT is has no spelling inside `$elemMatch`.
#[test]
fn a_nested_cardinality_has_no_element_scope() {
  let comparison = MongoListComparison::<i64, Set>::try_from_filter(
    ListFilter::<i64, SetFilter<i64>>::new()
      .with_any(SetFilter::new().with_count(ScalarFilter::new().with_gt(1))),
  )
  .expect("the identity");

  assert_eq!(
    refusal(&comparison),
    Some(MongoLoweringError::ElementDocument)
  );
}

/// A `count` operand is a `usize` and this family compares a cardinality as `i64`, so an operand
/// past the width is refused at the CROSSING, named as its own failure rather than the element
/// converter's.
#[test]
#[cfg(target_pointer_width = "64")]
fn a_cardinality_past_the_width_is_refused_at_the_crossing() {
  let crossed = Sequence::try_from_filter(
    ListFilter::<i64>::new().with_count(ScalarFilter::new().with_eq(usize::MAX)),
  );
  assert!(matches!(
    crossed,
    Err(MongoCollectionCrossingError::Cardinality(_))
  ));
}

/// The ELEMENT's crossing error is its own and nothing relates it to the element converter's, which
/// is why this error carries two parameters. A `Vec<u8>` member asked for a substring reaches the
/// byte kind's refusal, unchanged.
#[test]
fn the_element_crossings_refusal_travels_as_its_own() {
  use crate::{BytesFilter, comparison::mongo::MongoBytesComparison};

  let crossed = MongoListComparison::<Vec<u8>, MongoBytesComparison<Vec<u8>>>::try_from_filter(
    ListFilter::<Vec<u8>, BytesFilter<Vec<u8>>>::new()
      .with_any(BytesFilter::new().with_contains(b"ab".to_vec())),
  );
  assert!(matches!(
    crossed,
    Err(MongoCollectionCrossingError::Element(_))
  ));
}

/// A composite member renders the QUERY form and keeps the fold, so a collection of subdocuments is
/// refused nothing a top-level comparison is not — measured, `{$elemMatch: {"p.q": {$eq: 5}}}` and
/// an `$and` of field documents inside a scope are both legal.
#[test]
fn a_member_addressed_by_a_field_is_the_query_form() {
  // Stands in for a composite member: it pushes a frame, so it writes a FIELD key rather than a
  // bare operator, which is the other of `$elemMatch`'s two forms.
  struct Member(MongoScalarComparison<i64>);

  impl ComplexComparison<Mongo> for Member {
    fn conjuncts(&self) -> usize {
      ComplexComparison::<Mongo>::conjuncts(&self.0)
    }

    fn apply(
      &self,
      at: At<'_>,
      builder: MongoConjunction,
    ) -> Result<MongoConjunction, MongoLoweringError> {
      let frame = at.frame(FieldName::new("price"));
      self.0.apply(frame.at(), builder)
    }
  }

  let mut comparison = MongoListComparison::<i64, Member>::new();
  comparison.any = Some(Member(
    MongoScalarComparison::try_from_filter(ScalarFilter::<i64>::new().with_gt(5))
      .expect("the identity"),
  ));

  assert_eq!(
    rendered(&comparison, "items"),
    doc! { "items": { "$elemMatch": { "price": { "$gt": 5i64 } } } }
  );
}

/// **One declared converter fills both slots here too**, which is what makes the two families spell
/// a declaration the same way: the document family's collection kinds carry the same nested `any`
/// slot and therefore the same second level of operand.
///
/// The stored form is the element's LENGTH, so an operand that skipped the converter would be a
/// question about `"hdr"` where the column holds `3`, and the two assertions are the two levels.
#[test]
fn one_declared_converter_reaches_both_levels() {
  fn length(tag: String) -> Result<i64, core::convert::Infallible> {
    Ok(tag.len() as i64)
  }

  let filter = SetFilter::<String, TextFilter<String>>::new()
    .with_has_element("stereo".to_owned())
    .with_any(TextFilter::<String>::new().with_eq("hdr".to_owned()));

  let crossed =
    MongoSetComparison::<i64, MongoTextComparison<i64>>::try_from_filter_with(filter, length)
      .expect("an infallible crossing");

  assert_eq!(crossed.has_element(), Some(&6i64));
  assert_eq!(
    crossed.any().expect("the element question").eq(),
    Some(&3i64),
    "the nested operand crossed through the same converter, one level down"
  );
}