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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
//! The two collection comparisons — [`MongoListComparison`] for a sequence and
//! [`MongoSetComparison`] for a set — and the element scope they share.
//!
//! # TWO comparisons where the SQL family needs four, and a document array is the whole reason
//!
//! A collection column here is a BSON ARRAY, natively, for every element type. There is no strategy
//! to choose: no `CollectionStorage` row, no `PgCollectionStorage` table, no edge table, and no JSON
//! encoding — because the operand and the stored value are the same kind of value, so
//! [`membership`] writes both. The SQL family splits four ways over the two questions this backend
//! never asks (*can this dialect keep a collection in a column* and *can this element type live in
//! an array*), and neither has an answer other than yes.
//!
//! What that costs is the INDEX the edge table exists to give. A multikey index answers membership
//! and the element scope with a seek — measured on 8.2.12, `{tags: {$eq: 5}}` examines one key and
//! `{tags: {$elemMatch: {$gt: 1}}}` examines five — so the case SQLite sends to an edge table is the
//! case MongoDB indexes natively. The cardinality is the one that scans, and that is a property of
//! a length not being an element rather than of this encoding: see
//! [`MongoCountComparison`](super::MongoCountComparison).
//!
//! # The ordering operators are HONEST here, which is not what the family's other blob-shaped
//! measurement predicted
//!
//! The byte kind refuses a variable-width column's `$gt` because BSON
//! orders `BinData` by LENGTH before bytes, and an array had every reason to be the same shape of
//! trap: MongoDB compares an array field against a scalar operand by traversing its MEMBERS, so
//! `{tags: {$lt: 1}}` asks whether SOME member is less than one.
//!
//! Measured on 8.2.12, an ARRAY operand does not behave that way, and the mechanism is TYPE
//! BRACKETING: a comparison operator only considers values of the operand's own BSON type, so
//! `{tags: {$gt: [1, 2]}}` considers arrays and nothing else. Against `[2, 1]`, `[3]`, `[1]`, `[]`,
//! a missing field and a string, `$gt [1,2]` returns exactly `[2,1]` and `[3]` and `$lt [1,2]`
//! exactly `[1]` and `[]` — the element-wise lexicographic order, shorter prefix first, which is
//! precisely what a Postgres `ARRAY`'s own `<` gives. The blob trap was checked directly and did not
//! appear: a `BinData` member outranks an ARRAY in BSON's type order, yet `$gt` over a column of
//! them returned nothing, because the bracket had already excluded it.
//!
//! So the four ordering slots are WIRED rather than refused, and this backend agrees with Postgres
//! about a question SQLite and MySQL both decline.
//!
//! The one contamination the bracket leaves is a member that is ITSELF an array — measured,
//! `{v: {$gt: [1,2]}}` matches `[[9], 1]` through its member — and no [`MongoCarrier`] row this
//! crate ships produces a `Bson::Array`, so no element type it ships can reach it. A downstream row
//! that returned one would put its collection's whole-array operators outside this reasoning, which
//! is the same standing the `$`-in-a-field-name hazard has: stated, and the row author's.
//!
//! # `has_element` is the bare member match, and it is the SAME key `eq` writes
//!
//! Membership is what MongoDB's implicit traversal already does: `{tags: {$eq: 5}}` matches a
//! document whose array HOLDS five. So `has_element` needs no operator of its own — and on a
//! sequence that means it collides with the whole-collection `eq`, whose key is also `$eq`. The
//! accumulator's fold is the answer and it was built for exactly this: the second becomes an `$and`
//! branch. Nothing is dropped, and the two questions stay distinct because the OPERAND shapes differ
//! — one is the array, one is a member.

use bson::{Bson, Document};

use super::{
  Mongo, MongoCarrier, MongoConjunction, MongoCountComparison, MongoLoweringError, MongoOperator,
  NOR, count::push_count_slots, field_path, membership,
};
use crate::{
  ListFilter, QuantifiedFilter, ScalarFilter, SetFilter, TryMapFilter,
  comparison::{At, Backend, ComplexComparison, ToDatabaseComparison, TryFromFilter},
};

mongo_comparison_kind! {
  /// A [`ListFilter`]'s storage-side twin: the same nine operators, over the ELEMENT type this
  /// database stores the members as.
  ///
  /// | operator | key | |
  /// |---|---|---|
  /// | `eq` / `ne` | `$eq` / `$ne` | the whole array, element by element |
  /// | `gt` / `gte` / `lt` / `lte` | `$gt` / `$gte` / `$lt` / `$lte` | element-wise and lexicographic — see this module's measurement |
  /// | `has_element` | `$eq` | the bare member match, which is what implicit traversal already is |
  /// | `any` | `$elemMatch` | ONE member satisfies a whole comparison |
  /// | `count` | `$expr` | beside the field's keys rather than under them |
  ///
  /// # NOTHING is refused, where its SQL twin refuses on two dialects out of three
  ///
  /// [`ListCrossingError::JsonOrdering`](crate::comparison::sql::ListCrossingError::JsonOrdering)
  /// exists because SQLite and MySQL keep a collection as JSON and JSON has no element-wise
  /// collection order. BSON has one and it is the right one, so this crossing carries no such
  /// variant and every operator on the filter reaches a key.
  ///
  /// # `C` is the MEMBER's comparison, and it is a type parameter for the reason its SQL twin's is
  ///
  /// The `any` slot is not an operand — it is whatever the ELEMENT's own filter kind crossed into,
  /// so a text member brings the substring family and a scalar one does not, with nothing here
  /// choosing between them. What renders it is [`element_scope`], and what it may write there is
  /// narrower than what it may write at a field: see [`MongoConjunction::element`].
  MongoListComparison {
    one { has_element }
    many { eq, ne, gt, gte, lt, lte }
    element { any: C }
    cardinality { count }
  }
}

mongo_comparison_kind! {
  /// A [`SetFilter`]'s storage-side twin: the same eight operators, over the ELEMENT type this
  /// database stores the members as.
  ///
  /// # MongoDB has no set type either, so the split is in the OPERATORS
  ///
  /// A set and a sequence occupy the same BSON array, exactly as they occupy the same Postgres
  /// `ARRAY` and the same JSON column, and what differs is which operators are emitted against it.
  /// Two of them have no direct operator at all and are built:
  ///
  /// | operator | rendering |
  /// |---|---|
  /// | `encloses` | `$all` — every operand is a member, order- and multiplicity-blind |
  /// | `overlaps` | `$in` — some member is an operand |
  /// | `has_element` | `$eq` — the bare member match |
  /// | `enclosed_by` | `$type: "array"` and `$not: {$elemMatch: {$nin: […]}}` — no member lies outside |
  /// | `eq` | those two AND `$all`: mutual containment, which is what set equality is |
  /// | `ne` | `$nor` of the equality document, because negating a conjunction is a disjunction |
  /// | `any` / `count` | the sequence kind's, unchanged |
  ///
  /// # `$type: "array"` is not decoration, and `$not` is why
  ///
  /// A subset test says *no member lies outside the operand*, and a document with NO such field
  /// satisfies that vacuously — measured, `{tags: {$not: {$elemMatch: {$nin: [1,2]}}}}` returns the
  /// document with no `tags` and the one whose `tags` is a string. Every other backend answers a
  /// missing collection with no row: Postgres's `<@` on a NULL column is NULL. So the guard is what
  /// makes this backend answer the same question as the others, and with it the same measurement
  /// returns exactly the arrays that are subsets.
  ///
  /// It is NOT applied to `encloses` or `overlaps`, and that is the guard being written where it is
  /// needed rather than everywhere: `$all` and `$in` are already bracketed by having an operand to
  /// compare against, so a missing field fails them on its own.
  ///
  /// # An EMPTY operand is where `$all` stops meaning what set theory means
  ///
  /// Every set encloses the empty set, and Postgres agrees — `tags @> '{}'` is true of every array —
  /// but `{tags: {$all: []}}` matches NO document. So an empty `encloses` renders the guard ALONE,
  /// which is the vacuous truth stated exactly: this field is an array. An empty `eq` drops the
  /// `$all` for the same reason and keeps the rest, leaving *is an array, and no member lies outside
  /// nothing* — the empty array, and measured to be exactly it.
  ///
  /// That is deliberately NOT the reading `$in: []` gets, and the difference is the operators'
  /// own: an empty intersection is empty, so `overlaps: []` matching nothing is the answer rather
  /// than a degeneration.
  MongoSetComparison {
    one { has_element }
    many { eq, ne, encloses, enclosed_by, overlaps }
    element { any: C }
    cardinality { count }
  }
}

/// Why a [`ListFilter`]'s or a [`SetFilter`]'s operands did not become storage values.
///
/// # ONE type for both kinds, where the SQL family needs two
///
/// [`ListCrossingError`](crate::comparison::sql::ListCrossingError) carries a variant
/// [`SetCrossingError`](crate::comparison::sql::SetCrossingError) does not — a sequence stored as
/// JSON asked to compare as a magnitude — and that is the whole of what separates them there. This
/// backend refuses no operator of either kind, so the two crossings can fail in exactly the same
/// three ways and a second type would be the same three variants under another name.
///
/// # Two converter errors, because a collection filter holds two kinds of operand
///
/// `E` is the ELEMENT converter's — the `f` a crossing is given, or the storage type's own
/// [`TryFrom`] where it is not — and `X` is the ELEMENT FILTER's crossing error, which belongs to
/// whatever kind guards one member. They are independent: a `Vec<[u8; 32]>` converts its elements
/// with one and crosses its `any` slot with
/// [`MongoBytesCrossingError`](super::MongoBytesCrossingError), and no bound makes those one type.
///
/// `X` DEFAULTS to `E`, which is the case every value kind produces: a scalar, text, enum or boolean
/// member crosses with exactly its storage type's conversion error, so
/// `MongoCollectionCrossingError<Infallible>` still spells the identity crossing over such a member.
///
/// # The CARDINALITY's failure is a variant and not a third parameter
///
/// A `count` operand is a `usize` and this family compares a cardinality as `i64`, so what can fail
/// there is fixed by the family rather than chosen by a caller — there is nothing for a parameter to
/// range over.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MongoCollectionCrossingError<E, X = E> {
  /// An element did not convert into the type this database stores it as — the converter's own
  /// error.
  ///
  /// Either LEVEL: an operand written inside the nested `any` filter is an element too, so the
  /// one-converter crossing reports its refusal here rather than under `Element`.
  Operand(E),
  /// The ELEMENT filter did not cross into an element comparison — that crossing's own error.
  Element(X),
  /// A `count` operand does not fit the integer this family compares a cardinality as.
  ///
  /// Refused rather than saturated: an operand a client sent is not a number this crate may
  /// substitute, and a substituted one is a wrong result set reported as a right one. No collection
  /// a BSON document can hold reaches it.
  Cardinality(core::num::TryFromIntError),
}

impl<E: core::fmt::Display, X: core::fmt::Display> core::fmt::Display
  for MongoCollectionCrossingError<E, X>
{
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self {
      Self::Operand(error) => error.fmt(f),
      Self::Element(error) => error.fmt(f),
      Self::Cardinality(error) => error.fmt(f),
    }
  }
}

impl<E, X> std::error::Error for MongoCollectionCrossingError<E, X>
where
  E: std::error::Error + 'static,
  X: std::error::Error + 'static,
{
  fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
    match self {
      Self::Operand(error) => Some(error),
      Self::Element(error) => Some(error),
      Self::Cardinality(error) => Some(error),
    }
  }
}

/// Cross ONE element filter into the comparison a collection holds, or `None` where the operator is
/// absent.
///
/// The `any` half of both crossings — the `Option` walk, so that two crossings hold one statement of
/// what an absent operator crosses into.
///
/// `g` is the element's own CROSSING rather than the element converter, and the division is
/// [`Nullable`](crate::Nullable)'s: a wrapper's parameter ranges over what it holds, and this slot
/// holds a whole filter.
fn cross_element<VF, C, X>(
  filter: Option<VF>,
  g: impl FnOnce(VF) -> Result<C, X>,
) -> Result<Option<C>, X> {
  match filter {
    Some(filter) => g(filter).map(Some),
    None => Ok(None),
  }
}

/// Cross ONE cardinality filter into the count comparison a collection holds, or `None` where the
/// operator is absent.
///
/// It takes NO converter where [`cross_element`] does: a cardinality is a `usize` on one side and
/// this family's `i64` on the other, so the conversion is settled here rather than by the caller —
/// which is the same fact the concrete error variant states.
fn cross_count(
  filter: Option<ScalarFilter<usize>>,
) -> Result<Option<MongoCountComparison<i64>>, core::num::TryFromIntError> {
  match filter {
    Some(filter) => MongoCountComparison::try_from_filter(filter).map(Some),
    None => Ok(None),
  }
}

/// Collapse the element leg's own refusal into the crossing's, so ONE declared converter's refusal
/// reads the same at both levels — the document family's copy of the SQL one, over the error type
/// this family refuses with.
///
/// `Element(inner) => inner` is the whole of the collapse: the one-converter crossings report the
/// CONVERTER's refusal as `Operand` inside the `g` slot, and a caller is owed one level.
fn flatten_collection<E, X>(
  why: MongoCollectionCrossingError<E, MongoCollectionCrossingError<E, X>>,
) -> MongoCollectionCrossingError<E, X> {
  match why {
    MongoCollectionCrossingError::Operand(error) => MongoCollectionCrossingError::Operand(error),
    MongoCollectionCrossingError::Element(inner) => inner,
    MongoCollectionCrossingError::Cardinality(error) => {
      MongoCollectionCrossingError::Cardinality(error)
    }
  }
}

impl<V, C> MongoListComparison<V, C> {
  /// Cross a [`ListFilter`] into this comparison through ONE converter, which carries this
  /// collection's own operands and the ones inside its `any` filter alike.
  ///
  /// **This is where a DECLARED converter enters** (`mongo(into = …)`), and one function is
  /// what a declaration gets because one function is what a declaration IS: it names the hop from a
  /// domain element to the form this column stores, and every operand a collection filter carries is
  /// made of that same element. So the declaration fills both slots of
  /// [`try_from_filter_with_element`](Self::try_from_filter_with_element) and a caller writes it
  /// once — the same composition the SQL family's collection kinds make, stated at
  /// [`SqlEdgeComparison::try_from_filter_with`](crate::comparison::sql::SqlEdgeComparison::try_from_filter_with).
  ///
  /// # Errors
  ///
  /// As [`try_from_filter_with_element`](Self::try_from_filter_with_element), with `f`'s refusal
  /// standing for both levels of operand.
  pub fn try_from_filter_with<D, VF, E, F>(
    filter: ListFilter<D, VF>,
    f: F,
  ) -> Result<Self, MongoCollectionCrossingError<E, <C as TryFromFilter<VF::Mapped>>::Error>>
  where
    F: Fn(D) -> Result<V, E>,
    VF: TryMapFilter<D, V>,
    C: TryFromFilter<VF::Mapped>,
  {
    Self::try_from_filter_with_element(filter, &f, |element| {
      let stored = element
        .try_map_filter(&f)
        .map_err(MongoCollectionCrossingError::Operand)?;
      C::try_from_filter(stored).map_err(MongoCollectionCrossingError::Element)
    })
    .map_err(flatten_collection)
  }

  /// Cross a [`ListFilter`] into this comparison, converting each ELEMENT with `f` and the element
  /// FILTER with `g`.
  ///
  /// The trait crossing below is this same call with the storage type's own [`TryFrom`] and the
  /// element comparison's own crossing in their place.
  ///
  /// # Errors
  ///
  /// [`MongoCollectionCrossingError::Operand`] for whatever `f` refuses an element with,
  /// [`MongoCollectionCrossingError::Element`] for whatever `g` refuses the element filter with,
  /// and [`MongoCollectionCrossingError::Cardinality`] for a `count` operand past `i64`.
  ///
  /// `g` is a second function rather than a use of `f` because the two convert different things:
  /// `f` maps one ELEMENT into its storage type, while the `any` slot holds a whole FILTER whose own
  /// operands are the element kind's to convert. A caller holding ONE converter for both is asking
  /// [`try_from_filter_with`](Self::try_from_filter_with), which composes them.
  pub fn try_from_filter_with_element<D, VF, E, F, X, G>(
    filter: ListFilter<D, VF>,
    f: F,
    g: G,
  ) -> Result<Self, MongoCollectionCrossingError<E, X>>
  where
    F: FnMut(D) -> Result<V, E>,
    G: FnOnce(VF) -> Result<C, X>,
  {
    let mut stored = filter
      .try_map(f)
      .map_err(MongoCollectionCrossingError::Operand)?;
    let any = cross_element(stored.any.take(), g).map_err(MongoCollectionCrossingError::Element)?;
    let count = cross_count(stored.count).map_err(MongoCollectionCrossingError::Cardinality)?;
    Ok(Self {
      has_element: stored.has_element,
      eq: stored.eq,
      ne: stored.ne,
      gt: stored.gt,
      gte: stored.gte,
      lt: stored.lt,
      lte: stored.lte,
      any,
      count,
    })
  }
}

impl<V, C> MongoSetComparison<V, C> {
  /// Cross a [`SetFilter`] into this comparison through ONE converter — see
  /// [`MongoListComparison::try_from_filter_with`] for what the single converter is and why a
  /// declaration gets one.
  ///
  /// # Errors
  ///
  /// As [`try_from_filter_with_element`](Self::try_from_filter_with_element), with `f`'s refusal
  /// standing for both levels of operand.
  pub fn try_from_filter_with<D, VF, E, F>(
    filter: SetFilter<D, VF>,
    f: F,
  ) -> Result<Self, MongoCollectionCrossingError<E, <C as TryFromFilter<VF::Mapped>>::Error>>
  where
    F: Fn(D) -> Result<V, E>,
    VF: TryMapFilter<D, V>,
    C: TryFromFilter<VF::Mapped>,
  {
    Self::try_from_filter_with_element(filter, &f, |element| {
      let stored = element
        .try_map_filter(&f)
        .map_err(MongoCollectionCrossingError::Operand)?;
      C::try_from_filter(stored).map_err(MongoCollectionCrossingError::Element)
    })
    .map_err(flatten_collection)
  }

  /// Cross a [`SetFilter`] into this comparison, converting each ELEMENT with `f` and the element
  /// FILTER with `g`.
  ///
  /// # Errors
  ///
  /// As [`MongoListComparison::try_from_filter_with_element`], whose three failures these are.
  pub fn try_from_filter_with_element<D, VF, E, F, X, G>(
    filter: SetFilter<D, VF>,
    f: F,
    g: G,
  ) -> Result<Self, MongoCollectionCrossingError<E, X>>
  where
    F: FnMut(D) -> Result<V, E>,
    G: FnOnce(VF) -> Result<C, X>,
  {
    let mut stored = filter
      .try_map(f)
      .map_err(MongoCollectionCrossingError::Operand)?;
    let any = cross_element(stored.any.take(), g).map_err(MongoCollectionCrossingError::Element)?;
    let count = cross_count(stored.count).map_err(MongoCollectionCrossingError::Cardinality)?;
    Ok(Self {
      has_element: stored.has_element,
      eq: stored.eq,
      ne: stored.ne,
      encloses: stored.encloses,
      enclosed_by: stored.enclosed_by,
      overlaps: stored.overlaps,
      any,
      count,
    })
  }
}

/// The sequence filter crosses into the sequence comparison, and the ELEMENT filter crosses FIRST.
///
/// `VF` is the member's filter kind, and the comparison this collection holds is whatever THAT
/// filter crosses into over the SAME storage type — because a collection's members are stored as
/// `V`, in the array beside its siblings. So this row projects through `VF`'s own crossing, which is
/// what keeps the member's vocabulary the member's.
///
/// The projection sits in the associated type and in the where-clause rather than in this header's
/// ARGUMENTS, which is what keeps it resolvable: `V` and [`Mongo`] are both concrete here, so an
/// expansion assuming this predicate at a database it has not named yet has nothing to infer. The
/// SQL family reaches the same property by a different route — its projection lives inside a storage
/// row, because there the dialect is the thing not yet named.
///
/// It does not overlap the SQL family's row for the same filter, for the coherence reason
/// [`MongoScalarComparison`](super::MongoScalarComparison)'s row records: that one is keyed on
/// `Db: CollectionStorage<V, VF>`, whose supertrait is the FOREIGN `sqlx::Database`, and [`Mongo`]
/// is local and has no such row.
impl<D, VF, V> ToDatabaseComparison<V, Mongo> for ListFilter<D, VF>
where
  V: MongoCarrier,
  VF: ToDatabaseComparison<V, Mongo>,
{
  type Comparison = MongoListComparison<V, VF::Comparison>;
}

/// The same map for a set.
impl<D, VF, V> ToDatabaseComparison<V, Mongo> for SetFilter<D, VF>
where
  V: MongoCarrier,
  VF: ToDatabaseComparison<V, Mongo>,
{
  type Comparison = MongoSetComparison<V, VF::Comparison>;
}

/// The NARROW collection reads the SEQUENCE comparison, for the reason its SQL twin reads the
/// sequence strategy: a quantified column's members are written in the order the writer produced
/// them and the filter simply declines to ask about that order. There is one BSON array either way,
/// so what the choice decides here is only which struct holds the two crossed slots.
impl<D, VF, V> ToDatabaseComparison<V, Mongo> for QuantifiedFilter<D, VF>
where
  V: MongoCarrier,
  VF: ToDatabaseComparison<V, Mongo>,
{
  type Comparison = MongoListComparison<V, VF::Comparison>;
}

/// The identity crossing for a sequence — a `Vec<String>` stored as an array of strings is the
/// common one.
///
/// # Errors
///
/// As [`try_from_filter_with_element`](MongoListComparison::try_from_filter_with_element).
impl<D, VF, V: TryFrom<D>, C: TryFromFilter<VF>> TryFromFilter<ListFilter<D, VF>>
  for MongoListComparison<V, C>
{
  type Error = MongoCollectionCrossingError<V::Error, C::Error>;

  fn try_from_filter(filter: ListFilter<D, VF>) -> Result<Self, Self::Error> {
    Self::try_from_filter_with_element(filter, V::try_from, C::try_from_filter)
  }
}

/// The NARROW crossing, into the sequence comparison this backend keeps every collection in.
///
/// # The two arms are the wide kinds' own, called rather than restated
///
/// [`cross_element`] and [`cross_count`] are what both existing crossings put their `any` and
/// `count` slots through, so *what an absent operator crosses into* and *how a `usize` cardinality
/// becomes this family's `i64`* keep one statement each and this kind inherits both. What is left is
/// `Self::new()` and two assignments: the seven element slots stay unset STRUCTURALLY, because
/// nothing writes them.
///
/// It takes NO element converter, where the wide crossings take one or two. There is no element
/// operand to convert — which is what the error type says next.
///
/// # Errors
///
/// [`MongoCollectionCrossingError::Element`] for whatever the element filter's own crossing refuses,
/// and [`MongoCollectionCrossingError::Cardinality`] for a `count` operand past `i64`.
///
/// [`Operand`](MongoCollectionCrossingError::Operand) cannot arrive and is not merely unused: it
/// carries [`Infallible`](core::convert::Infallible) here, so the variant is UNINHABITED and the
/// compiler is what states that this crossing never refuses an operand.
///
/// The error type is the wide kinds' all the same, at a different `E` — so a cell already absorbing
/// a collection's refusal absorbs this one through the same row.
impl<D, VF, V, C: TryFromFilter<VF>> TryFromFilter<QuantifiedFilter<D, VF>>
  for MongoListComparison<V, C>
{
  type Error = MongoCollectionCrossingError<core::convert::Infallible, C::Error>;

  fn try_from_filter(filter: QuantifiedFilter<D, VF>) -> Result<Self, Self::Error> {
    let mut crossed = Self::new();
    crossed.any = cross_element(filter.any, C::try_from_filter)
      .map_err(MongoCollectionCrossingError::Element)?;
    crossed.count = cross_count(filter.count).map_err(MongoCollectionCrossingError::Cardinality)?;
    Ok(crossed)
  }
}

/// The identity crossing for a set.
///
/// # Errors
///
/// As [`try_from_filter_with_element`](MongoSetComparison::try_from_filter_with_element).
impl<D, VF, V: TryFrom<D>, C: TryFromFilter<VF>> TryFromFilter<SetFilter<D, VF>>
  for MongoSetComparison<V, C>
{
  type Error = MongoCollectionCrossingError<V::Error, C::Error>;

  fn try_from_filter(filter: SetFilter<D, VF>) -> Result<Self, Self::Error> {
    Self::try_from_filter_with_element(filter, V::try_from, C::try_from_filter)
  }
}

/// The BSON type alias `$type` names an array by.
///
/// A string rather than the numeric code, because the alias is what a reader of a stored filter can
/// check against MongoDB's own table; the two are the same test.
const ARRAY_TYPE: &str = "array";

/// `{$elemMatch: <the member's predicates>}` — the `any` operator's whole operand.
///
/// # The member's address is a fresh EMPTY path at the SAME row
///
/// A correlated element comparison correlates to the record the collection hangs off, so the row
/// travels; the PATH does not, because the member is not below the collection's field — it IS the
/// value under it, and `$elemMatch` has already named the field. That is where this parts from
/// [`push_element_scope`](crate::comparison::sql) , which pushes one segment for the scope column
/// SQL needs and MongoDB has not got.
///
/// # The EMPTY scope is `{$exists: true}` rather than `{}`
///
/// `∃x ∈ S. true` is `S ≠ ∅`, so an element comparison with no operator set has to render the
/// predicate *this collection has a member* — the reading
/// [`ListFilter::is_empty`](crate::ListFilter::is_empty) states, and the reason a present `any` does
/// not fold in the way a present `count` does.
///
/// `{}` is NOT that predicate. Measured on 8.2.12, an empty scope document is read as the QUERY form
/// and matches only members that are DOCUMENTS: over `[1, 2]`, `[5]`, `[]`, a missing field and a
/// string it returns nothing at all, where the target is the two non-empty arrays. Every member of
/// an array exists, so `{$exists: true}` is the tautology over members, and the same measurement
/// returns exactly the non-empty arrays through it.
///
/// # Errors
///
/// Whatever the member's own comparison cannot write inside a scope — see
/// [`MongoLoweringError`], whose three variants are the whole of it.
fn element_scope<C: ComplexComparison<Mongo>>(
  element: &C,
  at: At<'_>,
) -> Result<Bson, MongoLoweringError> {
  let mut scope = element
    .apply(at.top(), MongoConjunction::element())?
    .into_element_document()?;
  if scope.is_empty() {
    scope.insert(MongoOperator::Exists.as_str(), Bson::Boolean(true));
  }
  Ok(Bson::Document(scope))
}

/// `{$elemMatch: {$nin: […]}}` — SOME member lies outside `elements`, which is the predicate a
/// subset test negates.
///
/// It is the one place this family writes an element scope by hand rather than through
/// [`element_scope`], and the reason is that there is no member COMPARISON here to render: the
/// predicate is one operator over the collection's own operands.
fn outside<V: MongoCarrier>(elements: &[V]) -> Bson {
  let mut excluded = Document::new();
  excluded.insert(MongoOperator::Nin.as_str(), membership(elements));

  let mut scope = Document::new();
  scope.insert(MongoOperator::ElemMatch.as_str(), Bson::Document(excluded));
  Bson::Document(scope)
}

/// Walk the operators a stored set EQUAL to `elements` satisfies, in the order they are written.
///
/// A walk rather than a rendered document because its two callers need different things from it:
/// `eq` merges each operator into the field's own key, where `ne` collects them into one document to
/// negate. Stating the equality once is what keeps a set and its negation from drifting apart.
///
/// `$all` is omitted for an EMPTY operand — see [`MongoSetComparison`] for the measurement, which is
/// that `{$all: []}` matches nothing where every set encloses the empty one.
fn set_equality<V: MongoCarrier>(elements: &[V], mut write: impl FnMut(MongoOperator, Bson)) {
  write(MongoOperator::Type, Bson::String(ARRAY_TYPE.to_owned()));
  if !elements.is_empty() {
    write(MongoOperator::All, membership(elements));
  }
  write(MongoOperator::Not, outside(elements));
}

/// The two slots both kinds share, walked after each kind's own: the member match, the element
/// scope, and the cardinality.
///
/// Shared as a function because the three are the same three questions whichever kind asks them —
/// `has_element`, `any` and `count` are on both filters for exactly that reason — and a second
/// statement of them is a second place for the two kinds to disagree.
fn push_shared_slots<V: MongoCarrier, C: ComplexComparison<Mongo>>(
  has_element: Option<&V>,
  any: Option<&C>,
  count: Option<&MongoCountComparison<i64>>,
  field: &str,
  at: At<'_>,
  builder: &mut MongoConjunction,
) -> Result<(), MongoLoweringError> {
  if let Some(element) = has_element {
    builder.merge(field, MongoOperator::Eq, element.to_bson());
  }
  if let Some(any) = any {
    builder.merge(field, MongoOperator::ElemMatch, element_scope(any, at)?);
  }
  if let Some(count) = count {
    push_count_slots(count, field, builder);
  }
  Ok(())
}

/// The six whole-collection operators map one-to-one onto `$eq`, `$ne`, `$gt`, `$gte`, `$lt` and
/// `$lte`, and the operand is the array itself — see this module's note for the measurement that
/// says the last four are the element-wise order every other backend with an array type gives.
///
/// The field path is rendered ONCE, for the reason
/// [`MongoScalarComparison`](super::MongoScalarComparison)'s walk gives: a BSON key is a string that
/// every operator of this comparison merges under.
impl<V: MongoCarrier, C: ComplexComparison<Mongo>> ComplexComparison<Mongo>
  for MongoListComparison<V, C>
{
  #[inline]
  fn conjuncts(&self) -> usize {
    Self::conjuncts(self)
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    mut builder: <Mongo as Backend>::Builder<'q>,
  ) -> Result<<Mongo as Backend>::Builder<'q>, <Mongo as Backend>::Error> {
    let field = field_path(at);
    for (slot, op) in [
      (&self.eq, MongoOperator::Eq),
      (&self.ne, MongoOperator::Ne),
      (&self.gt, MongoOperator::Gt),
      (&self.gte, MongoOperator::Gte),
      (&self.lt, MongoOperator::Lt),
      (&self.lte, MongoOperator::Lte),
    ] {
      if let Some(elements) = slot {
        builder.merge(&field, op, membership(elements));
      }
    }
    push_shared_slots(
      self.has_element.as_ref(),
      self.any.as_ref(),
      self.count.as_ref(),
      &field,
      at,
      &mut builder,
    )?;
    Ok(builder)
  }
}

/// Three of the five whole-collection operators are one key each and two are BUILT — see
/// [`MongoSetComparison`] for the table and for what `$type: "array"` closes.
///
/// # This kind OVERFLOWS its own entry, and it is the second in the family to
///
/// `eq` and `enclosed_by` both write `$type` and `$not`, and `eq` and `encloses` both write `$all`,
/// so a comparison setting more than one of the three has keys no single operator document can
/// hold. The accumulator's fold is the answer, exactly as it is for
/// [`MongoTextComparison`](super::MongoTextComparison)'s twelve affix slots reaching two keys: the
/// first merges and the rest become `$and` branches. What that costs is one redundant branch where
/// two slots write the SAME guard — an `$and` of a true thing already said — and it is correct
/// rather than minimal.
impl<V: MongoCarrier, C: ComplexComparison<Mongo>> ComplexComparison<Mongo>
  for MongoSetComparison<V, C>
{
  #[inline]
  fn conjuncts(&self) -> usize {
    Self::conjuncts(self)
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    mut builder: <Mongo as Backend>::Builder<'q>,
  ) -> Result<<Mongo as Backend>::Builder<'q>, <Mongo as Backend>::Error> {
    let field = field_path(at);
    if let Some(elements) = &self.eq {
      set_equality(elements, |op, value| builder.merge(&field, op, value));
    }
    if let Some(elements) = &self.ne {
      let mut operators = Document::new();
      set_equality(elements, |op, value| {
        operators.insert(op.as_str(), value);
      });

      let mut equal = Document::new();
      equal.insert(&field, Bson::Document(operators));

      let mut negation = Document::new();
      negation.insert(NOR, Bson::Array(vec![Bson::Document(equal)]));
      builder.and(negation);
    }
    if let Some(elements) = &self.encloses {
      if elements.is_empty() {
        builder.merge(
          &field,
          MongoOperator::Type,
          Bson::String(ARRAY_TYPE.to_owned()),
        );
      } else {
        builder.merge(&field, MongoOperator::All, membership(elements));
      }
    }
    if let Some(elements) = &self.enclosed_by {
      builder.merge(
        &field,
        MongoOperator::Type,
        Bson::String(ARRAY_TYPE.to_owned()),
      );
      builder.merge(&field, MongoOperator::Not, outside(elements));
    }
    if let Some(elements) = &self.overlaps {
      builder.merge(&field, MongoOperator::In, membership(elements));
    }
    push_shared_slots(
      self.has_element.as_ref(),
      self.any.as_ref(),
      self.count.as_ref(),
      &field,
      at,
      &mut builder,
    )?;
    Ok(builder)
  }
}

#[cfg(test)]
mod tests;