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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
//! The MongoDB comparison family: the storage-typed predicates a filter crosses into, and the
//! lowering that renders one into a BSON filter document.
//!
//! It is the second BACKEND rather than a fourth dialect, and the difference is the whole reason
//! this module exists beside [`sql`](super::sql) instead of inside it. There are no dialects to
//! split against — one wire format, one query vocabulary — so where the SQL family has a table of
//! (kind × dialect) impls this one has a list of kinds, and where a SQL comparison carries its
//! `Db` in its own type a MongoDB one carries nothing.
//!
//! # The accumulator holds the OPPOSITE fact from the SQL one
//!
//! [`SqlConjunction`](super::sql::SqlConjunction) exists to hold the one bit no conjunct's writer
//! holds alone: whether this conjunct is the FIRST, so that the clause keyword is pushed once and
//! ` AND ` before every later one. **A BSON filter document has neither a lead nor a separator** —
//! its keys are implicitly ANDed — so that bit has nothing to decide here, and [`MongoConjunction`]
//! does not hold it.
//!
//! What it holds instead is the entries it has already made, because the two families disagree
//! about what a SECOND conjunct on ONE field is. SQL appends, and two operators on one column are
//! two conjuncts: `"a" > ? AND "a" < ?`. A document cannot append, because its keys are unique —
//! `{a: {$gt: 1}, a: {$lt: 5}}` is one key holding one of the two. So this accumulator MERGES into
//! the operator document it has already opened for that field: `{a: {$gt: 1, $lt: 5}}`.
//!
//! [`apply`](crate::ComplexComparison::apply)'s contract survives that difference intact, which is
//! worth stating rather than assuming: it says *append your conjuncts to this accumulator and hand
//! it back*, and says nothing about how the accumulator tells one conjunct from the next.
//! Separating them is SQL's answer to that question and merging is MongoDB's.
//!
//! # Where merging runs out
//!
//! Two conjuncts sharing a field AND an operator have no merged form at all: `$gt` appears once
//! under a field or not at all. That is reachable — two comparisons threaded through one
//! accumulator at one path — and MongoDB's own answer to it is `$and`, a list of whole filter
//! documents. So [`MongoConjunction::merge`] merges where a document can hold the result and
//! OVERFLOWS into a top-level `$and` where it cannot, and
//! [`into_document`](MongoConjunction::into_document) is where the two halves meet. Nothing is
//! dropped and nothing is refused; the fold is the price of the unique-key rule.
//!
//! # A RELATION is not a key at all, so the accumulator also carries STAGES
//!
//! A join is the one question no filter document holds: MongoDB answers it with `$lookup`, which is
//! a pipeline STAGE. So a relation position contributes stages BESIDE this accumulator's `$match`
//! rather than keys inside it — [`MongoConjunction::join`] is that third seam, next to `merge` (a
//! field's operator) and `and` (a whole filter document), and
//! [`into_predicate`](MongoConjunction::into_predicate) is the finisher that hands both halves back.
//!
//! The stages one relation contributes are a self-contained run: `$lookup` gathers the related
//! documents into a field, `$match` tests that field, and `$project` drops it again. Consuming the
//! field before the next join opens is what lets the join field be named by NESTING DEPTH alone —
//! two sibling relations over one collection would otherwise write one document key twice, and the
//! second `$lookup` would overwrite the first. See [`relation`](self::relation) for the four
//! quantifiers and the two refusals the arrangement keeps.
//!
//! # `conjuncts` counts OPERATORS here, and that is the trait's name reading as SQL's
//!
//! [`ComplexComparison::conjuncts`](crate::ComplexComparison::conjuncts) is a count of what
//! [`apply`](crate::ComplexComparison::apply) emits, and in SQL that is literally the number of
//! ` AND `-joined terms. Merging means the finished document holds FEWER keys than that — two
//! operators on one field are one key — so on this backend the number counts operators and matches
//! nothing structural in the output.
//!
//! It survives because of what it is asked: every caller uses it through
//! [`is_empty`](crate::ComplexComparison::is_empty), which only ever compares it to zero, and zero
//! operators is an empty document either way. The name is SQL's; the question it answers is not.
//!
//! # Nothing here is quoted, and nothing here can be
//!
//! The SQL family closes the identifier hazard by BRACKETING and doubling the bracket, so a name
//! carrying the quote character cannot close its own quoting. A BSON key has no brackets: a dot IS
//! the path separator and a leading `$` IS an operator sigil, and neither has an escape. So
//! [`write_field_path`] joins the segments and escapes nothing, and a segment carrying either
//! character addresses something other than the field it names.
//!
//! That exposure is a SCHEMA author's rather than a query author's, and the type system is what
//! makes it so: a segment is a [`FieldName`](crate::FieldName) built from a `&'static str`, which
//! a [`RecordAddress`](crate::RecordAddress) and a [`Frame`](crate::Frame) are the only ways to
//! supply, and both are `const`. No operand reaches this position. The refusal that would close it
//! entirely has nowhere to be returned from — [`Backend::write_column`](crate::Backend::write_column)
//! writes and does not answer — so it is stated here rather than half-built.
//!
//! # The ELEMENT SCOPE is a second position, and the empty path means the opposite thing in it
//!
//! `$elemMatch` asks whether ONE member of an array satisfies a whole predicate, and the predicate
//! inside it is written against the BARE element: `{tags: {$elemMatch: {$gt: 1, $lt: 6}}}` names no
//! field, because there is no field below an array of numbers to name. That is the address the SQL
//! family spells `ELEMENT_VALUE` — a scope column called `value` — and the two cannot be the same
//! word, because a document array's members have no column. Measured, against MongoDB 8.2.12: a
//! `value` key inside `$elemMatch` matches nothing at all on an array of scalars, which is the
//! silent miss this family refuses everywhere else.
//!
//! So the element's address is the EMPTY path, and [`MongoConjunction::element`] is the accumulator
//! that reads it that way. At the top of a `find` filter an empty path is a caller error and
//! `ABSENT_FIELD` makes the server say so; inside an element scope the very same address is the
//! member, and the operators written at it are the scope document's own keys. One address, two
//! readings, and the accumulator is what holds which one is in force — never the [`At`], which is
//! the same in both.
//!
//! # What the value form will not hold, and why this family finally has a lowering refusal
//!
//! `$elemMatch` has TWO forms and they do not mix: the VALUE form above, and a QUERY form naming
//! fields — `{items: {$elemMatch: {price: {$gt: 5}}}}` — which is what a composite element pushing
//! frames renders into, dotted paths included. A composite is therefore free; the value form is
//! where the language runs out, and three ways, each measured:
//!
//! - **It hosts no `$and`.** `{$elemMatch: {$and: [{$gt: 1}]}}` is *unknown top level operator:
//!   $gt* — an `$and` branch is a QUERY document, so a bare operator inside one has no reading.
//!   That is exactly what [`MongoConjunction`] overflows into, so an element comparison writing two
//!   conjuncts under one operator has no spelling here. It is the ORDINARY case rather than an edge:
//!   [`MongoTextComparison`] reaches ten of its twenty slots through `$regex` and `$not`.
//! - **It hosts no top-level operator.** `$expr` answers *`$expr` can only be applied to the
//!   top-level document* in BOTH forms, and `$nor` fails the same way `$and` does.
//! - **`$all` inside it matches nothing** rather than being refused, on an element that is itself an
//!   array. That one is the dangerous member of the three, and it is why
//!   [`MongoOperator::in_element_scope`] is a per-row fact rather than a rule about shapes.
//!
//! None of the three can be seen at the crossing, because what refuses is a comparison the
//! collection kind does not read — the same reason MySQL declines `any` at its lowering rather than
//! at its crossing. So [`Backend::Error`](crate::Backend::Error) for [`Mongo`] is
//! [`MongoLoweringError`] and no longer [`Infallible`](core::convert::Infallible), which is the day
//! that row said it was waiting for.

use bson::{Bson, Document};

use crate::{
  FieldName,
  comparison::{At, Path},
};

/// Generate one MongoDB comparison kind: the struct, its constructor, its emptiness and conjunct
/// counts, and its projected getters.
///
/// `one { … }` names the slots holding a single operand and `many { … }` the slots holding a list;
/// both hold STORAGE values, so both are over the same `V`.
///
/// # Deliberately not the SQL family's `comparison_kind!`
///
/// The reason is the one `emit/mongo.rs` gives for being a second FILE rather than a switch inside
/// `emit/sql.rs`: the switch would be over a distinction only one side has. That macro's shape is a
/// consequence of the `Db` parameter — the phantom field it needs, and the hand-written [`Debug`],
/// [`Clone`] and [`PartialEq`] a derive cannot supply for a marker implementing none of the three.
/// A MongoDB comparison has no dialect to remember, so it has no phantom, so all three are derives
/// and the two macros have nothing left to share but their slot lists.
///
/// The getters project for the same reason theirs do: a caller is handed the operand, never the
/// `Option<Box<[V]>>` it is stored in, which is an allocation choice rather than part of the
/// vocabulary. `eq` and `ne` shadow [`PartialEq`]'s methods for call syntax exactly as they do
/// there, and the `==` operator is unaffected.
/// `element { … }` and `cardinality { … }` are the collection kinds' two extra slots, and each holds
/// a whole COMPARISON rather than an operand: the one ONE member is asked, and the one this
/// collection's LENGTH is asked. The element's is a type parameter because a member's vocabulary is
/// its own; the cardinality's is not, because a collection of any element type counts the same way.
macro_rules! mongo_comparison_kind {
  (
    $(#[$meta:meta])*
    $name:ident {
      one { $( $one:ident ),+ $(,)? }
      many { $( $many:ident ),+ $(,)? }
      $( element { $any:ident : $elem:ident } )?
      $( cardinality { $count:ident } )?
    }
  ) => {
    $(#[$meta])*
    #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
    pub struct $name<V $(, $elem )?> {
      $( pub(crate) $one: ::core::option::Option<V>, )+
      $( pub(crate) $many: ::core::option::Option<::std::boxed::Box<[V]>>, )+
      $( pub(crate) $any: ::core::option::Option<$elem>, )?
      $(
        pub(crate) $count: ::core::option::Option<
          $crate::comparison::mongo::MongoCountComparison<i64>
        >,
      )?
    }

    impl<V $(, $elem )?> $name<V $(, $elem )?> {
      /// The empty comparison — no operator set.
      #[inline]
      pub const fn new() -> Self {
        Self {
          $( $one: ::core::option::Option::None, )+
          $( $many: ::core::option::Option::None, )+
          $( $any: ::core::option::Option::None, )?
          $( $count: ::core::option::Option::None, )?
        }
      }

      /// True while NO operator slot is set, so a lowering would write nothing for this field.
      ///
      /// A present ELEMENT slot counts even when the comparison inside it is empty, and the
      /// QUANTIFIER is why — see [`ListFilter::is_empty`](crate::ListFilter::is_empty), whose
      /// reading this mirrors: an element scope opened with no predicate in it asks whether the
      /// collection HAS a member. A present CARDINALITY slot holding an empty comparison does not
      /// count, for the other half of that reading: nothing quantifies it, so an empty one asks
      /// nothing and writes nothing.
      #[inline]
      pub const fn is_empty(&self) -> bool {
        $( self.$one.is_none() && )+
        $( self.$many.is_none() && )+
        $( self.$any.is_none() && )?
        $( match &self.$count {
          ::core::option::Option::Some(count) => count.is_empty(),
          ::core::option::Option::None => true,
        } && )?
        true
      }

      /// How many operators this comparison writes — one per set slot.
      ///
      /// A set membership slot counts even when the list inside it is empty: `in_: []` is the
      /// operator present with an operand that asks for no documents, where an absent `in_` asks
      /// for every one. A present ELEMENT slot counts ONCE however many operators the comparison
      /// inside it writes, because those land inside one `$elemMatch`. A present CARDINALITY slot
      /// counts what IT counts, because its expressions land beside this comparison's own keys.
      #[inline]
      pub const fn conjuncts(&self) -> usize {
        0
        $( + (self.$one.is_some() as usize) )+
        $( + (self.$many.is_some() as usize) )+
        $( + (self.$any.is_some() as usize) )?
        $( + match &self.$count {
          ::core::option::Option::Some(count) => count.conjuncts(),
          ::core::option::Option::None => 0,
        } )?
      }

      $(
        #[doc = concat!("The `", stringify!($one), "` operand, in the type this database stores.")]
        #[inline]
        pub const fn $one(&self) -> ::core::option::Option<&V> {
          self.$one.as_ref()
        }
      )+

      $(
        #[doc = concat!("The `", stringify!($many), "` operands, in the type this database stores.")]
        #[inline]
        pub fn $many(&self) -> ::core::option::Option<&[V]> {
          self.$many.as_deref()
        }
      )+

      $(
        #[doc = concat!(
          "The comparison ONE member of this collection is asked under `", stringify!($any),
          "`, or `None` while the operator is absent."
        )]
        #[inline]
        pub const fn $any(&self) -> ::core::option::Option<&$elem> {
          self.$any.as_ref()
        }
      )?

      $(
        #[doc = concat!(
          "The comparison this collection's LENGTH is asked under `", stringify!($count),
          "`, or `None` while the operator is absent."
        )]
        #[inline]
        pub const fn $count(
          &self,
        ) -> ::core::option::Option<&$crate::comparison::mongo::MongoCountComparison<i64>> {
          self.$count.as_ref()
        }
      )?
    }

    impl<V $(, $elem )?> ::core::default::Default for $name<V $(, $elem )?> {
      #[inline]
      fn default() -> Self {
        Self::new()
      }
    }
  };
}

mod boolean;
mod bytes;
mod carrier;
mod collection;
mod count;
#[cfg(feature = "jiff")]
mod duration;
mod enumeration;
#[cfg(feature = "flags")]
mod flags;
mod nullable;
mod relation;
mod scalar;
mod text;

/// The two causes a relation refuses for on EVERY backend, re-exported so that a reader matching on
/// [`MongoLoweringError`] finds their payloads under this family's own path.
pub use crate::comparison::{RelationDepthError, RelationWidthError};
pub use boolean::MongoBooleanComparison;
pub use bytes::{MongoBytesComparison, MongoBytesCrossingError};
pub use carrier::MongoCarrier;
pub use collection::{MongoCollectionCrossingError, MongoListComparison, MongoSetComparison};
pub use count::MongoCountComparison;
#[cfg(feature = "jiff")]
pub use duration::MongoDurationComparison;
pub use enumeration::MongoEnumComparison;
#[cfg(feature = "flags")]
pub use flags::MongoFlagsComparison;
pub use nullable::{MongoNullable, MongoNullableCrossingError};
/// The join body and the width check, reached by the nested ORDERING as well as by the two relation
/// kinds — a hop is a join, so it opens the same `$lookup` and refuses the same wide address.
pub(crate) use relation::{Lookup, one_key};
pub use relation::{MongoDerivedComparison, MongoRefComparison, MongoRelatedDocument};
pub use scalar::MongoScalarComparison;
pub use text::{MongoTextComparison, text_regex};

/// The backend a MongoDB comparison renders for.
///
/// UNINHABITED, because it is a name and never a value: it appears as
/// [`ComplexComparison<Mongo>`](crate::ComplexComparison) and
/// [`ToDatabaseComparison<V, Mongo>`](crate::ToDatabaseComparison) and in no struct, since a MongoDB
/// comparison has no dialect to remember and so carries no marker field. The SQL rows name
/// `sqlx::Sqlite` and its siblings, which are sqlx's own unit structs for sqlx's own reasons; this
/// crate has no such reason, and an empty enum is the shape that says a value would have no meaning
/// rather than merely no use.
pub enum Mongo {}

/// The `$`-prefixed key one FIELD operator is written under.
///
/// A closed vocabulary because it is MongoDB's own wire alphabet rather than a surface a downstream
/// extends — the same standing the SQL family's [`CollectionOp`](super::sql::CollectionOp) and the
/// shared [`TextMatch`](super::TextMatch) have — and it is spelled as a type rather than as the
/// `&str` literal a SQL operator is because the two failure modes are not the same. A misspelled
/// SQL operator does not parse. A `$` dropped from `{a: {$gt: 1}}` leaves `{a: {gt: 1}}`, which is
/// a well-formed exact match against a subdocument: a different question, answered without
/// complaint.
///
/// It grows as the family does, and each row arrives with the kind that writes it. The collection
/// kinds brought four; `$size` is NOT among them, because a cardinality is asked with eight
/// operators and `$size` answers one — the kind that counts states the measurement.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MongoOperator {
  /// The field equals the operand.
  ///
  /// It is also [`MongoNullable`]'s key for *this column is null*, with `null` as the operand, and
  /// that row is where the reading is stated: `{v: {$eq: null}}` matches a field written as null AND
  /// a document with no such field, which is MongoDB's own convention rather than a conflation this
  /// crate arranges.
  Eq,
  /// The field differs from the operand — INCLUDING where the field is absent, which is the one
  /// place this vocabulary is not SQL's `<>` under another name.
  ///
  /// [`MongoNullable`] spends exactly that absence: since `{$eq: null}` HOLDS the missing field,
  /// its negation excludes it, so *this column holds a value* is one key with no
  /// [`Exists`](Self::Exists) beside it.
  Ne,
  /// The field is greater than the operand.
  Gt,
  /// The field is greater than or equal to the operand.
  Gte,
  /// The field is less than the operand.
  Lt,
  /// The field is less than or equal to the operand.
  Lte,
  /// The field equals one of the operands.
  In,
  /// The field equals none of the operands.
  Nin,
  /// The field matches the operand, which is a REGULAR EXPRESSION rather than a value —
  /// [`text_regex`] is where one is built and where the escaping that makes an operand inert lives.
  ///
  /// The operand is a BSON regular expression rather than a string, and that is what keeps its
  /// case-folding flag with it: `$options` is a SECOND key beside this one, and this family's
  /// accumulator merges a single (field, operator, value) at a time, so an overflow could separate
  /// the two.
  Regex,
  /// The field does NOT match the operand — the negated affix slots, and the only member here whose
  /// operand is another predicate rather than a value.
  ///
  /// It is a field-level key like its neighbours, so it merges and overflows exactly as they do:
  /// `$not` appears once under a field or not at all, and two negated matches on one field are one
  /// merged key and one `$and` branch.
  ///
  /// What sits under it here is always a BSON regular expression, which every server version
  /// accepts; `{$not: {$regex: …}}` is the other spelling and it is the one MongoDB only learned in
  /// 4.0.7. Like [`Ne`](Self::Ne), it MATCHES A DOCUMENT WHERE THE FIELD IS ABSENT, which is
  /// [`MongoNullable`]'s question rather than this vocabulary's — a filter that wants the absence
  /// excluded asks the column's null test, beside the match, under its own key.
  Not,
  /// The field is an array holding EVERY one of the operands — a superset, ignoring order and
  /// multiplicity, which is what [`MongoSetComparison`]'s `encloses` asks.
  ///
  /// An EMPTY operand list is where it stops meaning what set theory means: every set encloses the
  /// empty one, and `{tags: {$all: []}}` matches NO document. So the set kind writes a plain
  /// [`Type`](Self::Type) test there instead, rather than an operator that is false where the answer
  /// is vacuously true.
  All,
  /// ONE member of the field's array satisfies the operand, which is a whole predicate rather than a
  /// value.
  ///
  /// The distinction that earns it a row of its own is that the bare operators MongoDB already
  /// applies per element — `{tags: {$gt: 1, $lt: 6}}` — may be satisfied by DIFFERENT members, where
  /// this one binds them to one. Measured on 8.2.12 against `[1, 9]`: the bare form matches and this
  /// one does not.
  ElemMatch,
  /// The field's BSON type is the operand, named as the string BSON alias.
  ///
  /// Written by the set kind alone, and always as `"array"`. Its job is to close what `$not` opens:
  /// a subset test is *no member lies outside the operand*, which a document with NO such field
  /// satisfies vacuously, where every other backend answers a missing collection with no row at all.
  Type,
  /// Whether the field is present — `true` is the only operand this family writes.
  ///
  /// The one place the empty predicate needs a spelling. `{tags: {$elemMatch: {}}}` is not it:
  /// measured, an empty scope document is read as the QUERY form and matches only members that are
  /// DOCUMENTS, so it answers nothing at all over an array of scalars. Every member of an array
  /// exists, so `{$exists: true}` inside the scope is the tautology over members — which is what
  /// makes `∃x. true` render as *this field is a non-empty array*.
  Exists,
  /// Every bit of the operand mask is SET in the field's integer — the flags kind's `hasAll`.
  ///
  /// NATIVE, where SQL spells the same question with an arithmetic expression: MongoDB's query
  /// language carries the three bitwise predicates itself, so this family binds a mask and never
  /// builds a `$expr` around `$bitAnd`. The operand is written as an integer bitmask, which is one
  /// of the three forms the server takes (a mask, a `BinData`, or an array of bit POSITIONS) and the
  /// one the storage carrier already produces.
  BitsAllSet,
  /// At least one bit of the operand mask is SET — the flags kind's `hasAny`.
  BitsAnySet,
  /// No bit of the operand mask is set — the flags kind's `hasNone`.
  ///
  /// The server's own name for it is `$bitsAllClear`, and the two words say one thing: *all of the
  /// mask is clear* is *none of the mask is set*. Which side a kind's word takes is a fact about the
  /// filter's vocabulary and not about this one.
  BitsAllClear,
}

impl MongoOperator {
  /// The `$`-prefixed BSON key this operator is written under.
  #[inline]
  pub const fn as_str(self) -> &'static str {
    match self {
      Self::Eq => "$eq",
      Self::Ne => "$ne",
      Self::Gt => "$gt",
      Self::Gte => "$gte",
      Self::Lt => "$lt",
      Self::Lte => "$lte",
      Self::In => "$in",
      Self::Nin => "$nin",
      Self::Regex => "$regex",
      Self::Not => "$not",
      Self::All => "$all",
      Self::ElemMatch => "$elemMatch",
      Self::Type => "$type",
      Self::Exists => "$exists",
      Self::BitsAllSet => "$bitsAllSet",
      Self::BitsAnySet => "$bitsAnySet",
      Self::BitsAllClear => "$bitsAllClear",
    }
  }

  /// Whether `$elemMatch`'s VALUE form — the one applying operators to the bare member — ANSWERS
  /// this operator.
  ///
  /// A per-row fact rather than a rule about shapes, because the one row that says no says it by
  /// matching nothing. Measured on MongoDB 8.2.12, over `[[1, 2], [8]]`:
  /// `{$elemMatch: {$all: [1]}}` returns no document where the member `[1, 2]` holds `1`, and the
  /// server raises nothing. Every other row answers there — including [`ElemMatch`](Self::ElemMatch)
  /// itself, so a collection of collections nests, and [`Not`](Self::Not),
  /// [`Regex`](Self::Regex) and [`Type`](Self::Type), each checked positively.
  ///
  /// What reads it is [`MongoConjunction::element`], which refuses rather than writing a predicate
  /// whose answer would be *no documents* for a reason the caller never asked about. The rows that
  /// cannot appear in the scope AT ALL are a different question and are not here: `$expr` and `$nor`
  /// are top-level operators rather than field ones, so they never became rows of this type.
  #[inline]
  pub const fn in_element_scope(self) -> bool {
    !matches!(self, Self::All)
  }
}

/// MongoDB's DOCUMENT-level conjunction, and the only `$`-key this family writes at a position that
/// is not a field's.
///
/// Not a row in [`MongoOperator`], because that vocabulary is the operators a field's key holds and
/// this one takes a list of whole filter documents instead. A type whose values are legal in two
/// unrelated positions is a type that cannot say where each belongs.
const AND: &str = "$and";

/// MongoDB's aggregation-expression escape, and the second key this family writes at a position that
/// is not a field's.
///
/// It takes an EXPRESSION rather than a predicate, which is what a cardinality needs: `$size` over a
/// column is a value computed from it, and no operator document on the column itself can hold one.
/// The server is explicit that it belongs nowhere else — *`$expr` can only be applied to the
/// top-level document* — so it reaches a filter through [`MongoConjunction::and`] and never through
/// the merge.
const EXPR: &str = "$expr";

/// MongoDB's document-level NEGATED disjunction — no branch matches — and the third key this family
/// writes at a position that is not a field's.
///
/// A set INEQUALITY is what needs it. Set equality is a conjunction of three operators under one
/// field, and its negation is therefore a DISJUNCTION, which no operator document can hold: `$not`
/// takes one operator's operand rather than a field's whole predicate. `{$nor: [<the equality>]}` is
/// the negation of exactly that document and nothing else.
const NOR: &str = "$nor";

/// The `$match` STAGE's key.
///
/// A THIRD vocabulary beside [`MongoOperator`] and the three top-level operators above, and the one
/// row of it two parties write: a package's whole predicate is a `$match`, and so is the test a
/// relation's join makes on the field it filled. A stage name is legal only as a pipeline element's
/// single key where an operator is legal only inside a filter, so the two could not have been one
/// type — but one string is one string, and two spellings of it are two places for a stage to be
/// named wrongly.
pub(crate) const MATCH: &str = "$match";

/// The `$project` STAGE's key, here for the reason [`MATCH`] is: two parties write it.
///
/// A relation's join drops the field it filled once the `$match` beside it has read it, and a nested
/// ORDERING drops the arrays its hops filled once the sort value has been taken off them — see
/// [`MongoNesting`](crate::query::mongo::MongoNesting). Both are the same sentence, and consuming
/// the field before the next join opens is what lets EITHER be named by nesting depth alone.
pub(crate) const PROJECT: &str = "$project";

/// What [`write_field_path`] writes where there is no field to name.
///
/// The top level names no column, so a comparison over one applied there has no key to render, and
/// the SQL family's answer — write nothing — does not carry: an empty BSON key is LEGAL, so
/// `{"": {$eq: 1}}` is a well-formed filter matching documents with a field actually called `""`.
/// A caller error resolved is worse than one refused, which is the whole of why the SQL rows write
/// nothing and leave the surrounding predicate unparseable.
///
/// A bare `$` is the shortest key MongoDB refuses in this position: a top-level key beginning with
/// `$` is read as an operator, and the server answers *unknown top level operator: $*. So the
/// refusal lands where SQL's does — at the engine, loudly — rather than as a filter that quietly
/// matches nothing.
const ABSENT_FIELD: &str = "$";

/// The BSON key a record's own id is stored under, whatever the declaration calls the column.
///
/// MongoDB's name rather than this crate's: the server mints an `_id` for every document that
/// arrives without one and indexes it uniquely, so a framework storing its id under a second name
/// would carry two identities per document and index the one it did not choose.
///
/// The declaration and the wire face still say `id`. What that costs is one mapping, and this
/// module is one of its two homes — [`field_key`] below, reached by every party that renders a
/// field path, which is the filter, the `$sort` and the keyset alike. The other is the EXTRACTION,
/// which reads the id back out of this key.
pub const ID: &str = "_id";

/// The BSON key `name` is written under in the document `record` addresses — `name` itself, or
/// [`ID`] where it is the row's own id.
///
/// # The ADDRESS is what decides it, not the spelling
///
/// A column called `id` on a record addressed by something else is an ordinary field and stays one;
/// a column called `uuid` that IS the address becomes `_id`. So a declaration renaming its id
/// column, in the schema or per database, moves the mapping with it rather than losing it — which a
/// rule keyed on the word `id` could not do.
///
/// # It maps a SINGLE-column address only
///
/// A framework-emitted document is addressed by one column, which is the id. A user-declared
/// physical layout addressed by several has no single field to be `_id`, and MongoDB's own answer
/// there is a COMPOSITE `_id` subdocument — a shape this lane does not build, so it maps nothing
/// and every column keeps its own key. That leaves such a document with a server-minted `_id`
/// beside its declared key columns, which is legal and is not what this framework means by an
/// address; the lane refuses to page one rather than pretending, and the refusal is the missing
/// binding rather than a runtime no.
#[must_use]
pub fn field_key<'a>(record: &crate::RecordAddress, name: &'a FieldName) -> &'a str {
  match record.keys() {
    [key] if *key == name => ID,
    _ => name.as_str(),
  }
}

/// The dotted field path `at` names, written into `out`: the segments of its
/// [`Path`](crate::Path) joined with `.`, and nothing bracketed or escaped.
///
/// This is what [`Backend::write_column`](crate::Backend::write_column) answers with for
/// [`Mongo`], and it is public for the reason [`quote_column`](super::sql::quote_column) is: a
/// comparison kind declared downstream renders its field path through this rather than restating
/// how one is spelled.
///
/// # The `.` is the ADDRESSING, where SQL's `_` is a character in a name
///
/// `timebase_num` is one SQL identifier that happens to hold an underscore, because SQL's namespace
/// is flat and a composite occupies sibling columns. `timebase.num` is a field of a SUBDOCUMENT,
/// which is what a composite is here. The two families therefore need the same segments and
/// nothing else from each other, which is what [`Path`](crate::Path) holding no joining convention
/// buys.
///
/// # The EMPTY path writes `$`
///
/// See `ABSENT_FIELD` — the reasoning is that constant's, since it is the decision rather than
/// the rendering.
///
/// # The ROW's OWN ID writes [`ID`]
///
/// A single-segment path naming the column `at` is addressed by is the document's `_id` — see
/// [`field_key`], which is where that is decided and why. It is done HERE rather than at each
/// caller because this is the one position every rendered field path goes through: a filter's
/// column, a `$sort` entry and a keyset arm all arrive at the same function, so the mapping cannot
/// hold in two of them and lapse in the third.
///
/// A path with a PARENT is never mapped, whatever its last segment spells: `cover.id` is a field of
/// a subdocument, and the document's own `_id` is at the top level by definition.
pub fn write_field_path(at: At<'_>, out: &mut String) {
  match at.path() {
    Some(path) if path.parent().is_none() => out.push_str(field_key(at.record(), path.name())),
    Some(path) => push_segments(path, out),
    None => out.push_str(ABSENT_FIELD),
  }
}

/// The segments from the ROOT down, `.` between them.
///
/// Recursive because [`Path`](crate::Path) is a cons list built innermost-last, exactly as
/// `quote_column`'s walk is: reversing it into an iterator would need the allocation the cons list
/// exists to avoid.
fn push_segments(path: &Path<'_>, out: &mut String) {
  if let Some(parent) = path.parent() {
    push_segments(parent, out);
    out.push('.');
  }
  out.push_str(path.name());
}

/// The dotted field path `at` names, as the KEY a filter document holds this predicate under.
///
/// [`write_field_path`]'s counterpart for the caller that needs the name as a value rather than
/// appended to a buffer, which here is every kind: a BSON key IS a string, and a comparison setting
/// several operators writes them all under one. So this renders once per comparison where the SQL
/// family renders once per conjunct, and that falls out of the merge rather than being arranged.
///
/// Public for the reason [`write_field_path`] is.
#[must_use]
pub fn field_path(at: At<'_>) -> String {
  let mut path = String::new();
  write_field_path(at, &mut path);
  path
}

/// The operand list `$in` and `$nin` take — and, unchanged, the WHOLE-COLLECTION operand the
/// collection kinds compare against.
///
/// One writer for both because BSON does not distinguish them: a list of operands and a stored array
/// are the same `Bson::Array`, so `{tags: {$eq: [1, 2]}}` and `{tags: {$in: [1, 2]}}` differ in the
/// operator alone. The SQL family needs a second encoding here — `json_elements`, a canonical string
/// — precisely because a SQL operand is not the column's own shape.
///
/// An EMPTY list needs no special case for `$in` and `$nin`, and that is a genuine agreement rather
/// than an absence of one: `$in: []` matches nothing and `$nin: []` matches everything, which is the
/// same truth table the SQL family arrives at by degenerating to `1 = 0` inside its negation wrap.
/// The operator PRESENT with an empty operand asks for no documents; the operator absent asks for
/// every one. `$all` is where that stops holding, and the set kind states what it does instead.
fn membership<V: MongoCarrier>(values: &[V]) -> Bson {
  Bson::Array(values.iter().map(MongoCarrier::to_bson).collect())
}

/// Why a MongoDB comparison could not be rendered.
///
/// Four of the six members are one thing an ELEMENT SCOPE cannot hold; the other two are the
/// addressing a RELATION needs and did not get, and they are the query layer's own payloads rather
/// than this family's — see [`RelationWidthError`] and [`RelationDepthError`].
///
/// # `Relation` was a member here and is not one now
///
/// It said *a relation predicate is a join and `find` has none*, and it was true while this family
/// rendered into a `find` filter and nothing else. The lane renders an AGGREGATION now — every lane,
/// flat query included — so `$lookup` has a position, and the blanket refusal became the rendering
/// in [`relation`](self::relation). What is left of it is the two shapes `$lookup` genuinely has no
/// spelling for, each named below.
///
/// # It is the family's FIRST refusal, and the crossing is why there were none before
///
/// Every other failure a MongoDB comparison can have happens at the CROSSING — an operand that will
/// not convert, an operator no width can answer — and by the time a comparison exists it holds
/// storage values that rendering cannot reject. That is what let
/// [`Backend::Error`](crate::Backend::Error) for [`Mongo`] say
/// [`Infallible`](core::convert::Infallible), and its own note said the day a kind could refuse it
/// would be named.
///
/// `$elemMatch` is that day, and the reason it could not be a crossing error is the reason
/// [`SqlLoweringError::JsonElementScope`](super::sql::SqlLoweringError::JsonElementScope) is not
/// one either: what refuses is the ELEMENT's comparison, whose operator set the collection holding
/// it cannot read — it has a type parameter there and a [`ComplexComparison`] bound, and neither
/// says which keys the thing will write. The refusal is knowable exactly when it writes them.
///
/// # A refusal rather than a document the server would reject
///
/// The family's standing rule is that a caller error must be REFUSED rather than resolved, and
/// `ABSENT_FIELD` implements it by writing a key the server has no reading for. That is second best
/// and says so: it is what a position with no return path can do. This position has one —
/// [`ComplexComparison::apply`](crate::ComplexComparison::apply) answers with a `Result` — so the
/// refusal is typed, names the operator where there is one to name, and never leaves the buffer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MongoLoweringError {
  /// An operator `$elemMatch`'s value form does not answer, named here by the row that carries the
  /// measurement — [`MongoOperator::in_element_scope`].
  ElementOperator(MongoOperator),
  /// Two conjuncts inside one element scope that no single scope document can hold: the same
  /// operator twice, or a bare operator beside a field name.
  ///
  /// The value form hosts no `$and`, so the fold [`MongoConjunction`] uses everywhere else has no
  /// spelling here — and the two FORMS of `$elemMatch` do not mix, so a comparison writing at the
  /// member AND at a field below it is the same refusal under a second cause. Both are the value
  /// form running out, which is why they are one variant.
  ElementConjunction,
  /// A TOP-LEVEL operator — `$expr` or `$nor` — inside an element scope, which neither form hosts.
  ///
  /// It is what a nested collection's `count` or a nested set's `ne` would need, and the server is
  /// explicit about the first: *`$expr` can only be applied to the top-level document*.
  ElementDocument,
  /// A RELATION predicate inside an element scope, which is a filter document and cannot hold a
  /// pipeline stage.
  ///
  /// `$lookup` is a stage, so a relation contributes stages beside a `$match` rather than keys
  /// inside one — and an `$elemMatch` has no pipeline around it to put them in. It is the element
  /// scope's fourth limit and the only one that is not about an operator.
  ///
  /// Reachable from a collection of COMPOSITES whose element comparison carries a relation slot: the
  /// collection kind opens the scope, and what refuses is a comparison it cannot read.
  ElementRelation,
  /// A relation NESTED inside an `all`, whose lowering negates the predicate it is given.
  ///
  /// `all` is *no child fails* — a `$lookup` whose own pipeline matches the children the predicate
  /// EXCLUDES, under `$nor`, required to come back empty. `$nor` takes filter DOCUMENTS, so a
  /// predicate that is itself a join has nothing to be negated as: its stages would have to run
  /// inside a query operator that holds none.
  ///
  /// Its three neighbours compose without this. `any` and `none` pass their predicate through
  /// UNNEGATED — the negation is on the emptiness test outside the join — so a relation inside
  /// either nests, and `count` asks nothing of the children at all.
  NegatedRelation,
  /// A relation whose target — or whose parent — is addressed by SEVERAL columns; the payload
  /// carries which row and how many.
  ///
  /// `$lookup` matches ONE `localField` against ONE `foreignField`, which is the same one-to-one
  /// join the SQL family's semi-join is. It bites twice as hard here: a document's own id is the
  /// `_id` key, and [`field_key`] maps a SINGLE-column address onto it, so a row addressed by
  /// several has no `_id` for either side of the join to name.
  ///
  /// Raised BEFORE either kind writes a stage, so it is a property of the RELATION rather than of
  /// the predicate inside it — the same relation cannot answer one filter and refuse another.
  RelationWidth(RelationWidthError),
  /// A relation nested deeper than its target's join fields were minted for; the payload carries
  /// which row, how deep, and how many.
  ///
  /// Reusing a name is the alternative, and here it is silent in a way of its own: a `$lookup`'s
  /// `as` is a FIELD of the document it is joining onto, so a repeated one is written twice and the
  /// second stage overwrites the first. The predicate that reads it then tests a set the filter
  /// never asked about, and the pipeline runs.
  RelationDepth(RelationDepthError),
}

impl core::fmt::Display for MongoLoweringError {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self {
      Self::ElementOperator(op) => write!(
        f,
        "operator {:?} inside an element scope matches no document rather than being refused, so \
         this crate will not write one",
        op.as_str()
      ),
      Self::ElementConjunction => f.write_str(
        "an element scope holds one predicate per operator and cannot mix a bare operator with a \
         field name, and MongoDB has no `$and` inside one to fold the rest into",
      ),
      Self::ElementDocument => f.write_str(
        "a top-level operator cannot be applied inside an element scope, so a nested collection's \
         cardinality or set inequality has no spelling there",
      ),
      Self::ElementRelation => f.write_str(
        "a relation is a `$lookup`, which is a pipeline stage, and an element scope is a filter \
         document with no pipeline around it to hold one",
      ),
      Self::NegatedRelation => f.write_str(
        "`all` negates the predicate it is given with `$nor`, which takes filter documents, so a \
         relation nested inside one has no stage position",
      ),
      Self::RelationWidth(width) => {
        let table: &str = width.table();
        write!(
          f,
          "`{table}` is addressed by {} columns and `$lookup` joins one field to one field",
          width.columns()
        )
      }
      Self::RelationDepth(depth) => {
        let table: &str = depth.table();
        write!(
          f,
          "a relation over `{table}` nests {} levels deep and its join fields are minted for {}",
          depth.depth(),
          depth.ceiling()
        )
      }
    }
  }
}

impl std::error::Error for MongoLoweringError {}

/// Which of the two positions an accumulator is filling, which is the one thing the [`At`] cannot
/// say — the empty path is the same address at the top of a filter and inside `$elemMatch`, and the
/// two readings are opposite.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
enum Scope {
  /// The top of a `find` filter: an empty path names no field and `ABSENT_FIELD` makes the server
  /// say so.
  #[default]
  Filter,
  /// Inside `$elemMatch`: an empty path IS the member, and the operators written at it are the
  /// scope document's own keys.
  Element,
}

/// The AND accumulator a MongoDB comparison's lowering merges its conjuncts into, and the type
/// [`Backend::Builder`](crate::Backend::Builder) names for [`Mongo`].
///
/// See this module's note for what it holds and why that is not what
/// [`SqlConjunction`](super::sql::SqlConjunction) holds. In short: a document's keys are implicitly
/// ANDed, so there is no lead and no separator to count toward — and its keys are UNIQUE, so a
/// second operator on a field has to join the operator document the first one opened.
///
/// # It carries no lifetime, and the GAT slot it fills has one
///
/// Every value it holds is a [`Bson`], which OWNS its bytes — a string, a binary blob, a nested
/// document. So there is nothing here to borrow from the operands, and
/// `<Mongo as Backend>::Builder<'q>` resolves to this type with `'q` unused. The slot stays useful
/// for a backend whose builder does borrow; this one measured out not to be it.
#[derive(Debug, Default)]
#[must_use]
pub struct MongoConjunction {
  /// One key per field, each holding that field's operator document.
  ///
  /// The INVARIANT every method below maintains: every value here is a [`Bson::Document`] of
  /// operator keys, because [`merge`](Self::merge) is the only writer and that is the only shape it
  /// writes.
  merged: Document,
  /// The conjuncts no key of `merged` could hold, each a whole filter document, folded under `$and`
  /// when the accumulator is finished.
  ///
  /// Two things land here and `top_level` is what tells them apart: a field and operator already
  /// present, which is this crate's own fold, and a document a kind contributed through
  /// [`and`](Self::and), which is a top-level operator with no field position at all.
  overflow: Vec<Document>,
  /// Whether any entry of `overflow` came from [`and`](Self::and) — so a top-level operator is in
  /// force, and no element scope can hold this accumulator whatever else it holds.
  top_level: bool,
  /// Which position this accumulator is filling.
  scope: Scope,
  /// The stages every relation contributed, in the order the relations were crossed — each a
  /// `$lookup`, the `$match` reading the field it landed its rows in, and the `$project` dropping
  /// that field again.
  ///
  /// They run AFTER this accumulator's own `$match` rather than before it, which is the cheaper of
  /// two orders that answer the same question: conjuncts commute, so filtering on the document's own
  /// columns first is a join over fewer documents.
  joins: Vec<Document>,
  /// Every collection those stages read, in the order they were joined, without repeats — the fact
  /// the package carries and the execution lane's read concern is chosen from.
  reads: Vec<&'static FieldName>,
  /// The FIRST thing asked of an element scope that it cannot hold, kept until the accumulator is
  /// finished.
  ///
  /// [`merge`](Self::merge) writes and does not answer — the signature every kind already calls —
  /// so a refusal it discovers has nowhere to go but here, and
  /// [`into_element_document`](Self::into_element_document) is where it surfaces. The FIRST rather
  /// than the last, because a later cause is a consequence of a comparison that was already
  /// unrenderable.
  refusal: Option<MongoLoweringError>,
}

impl MongoConjunction {
  /// Start accumulating a `find` filter: no field constrained, so an accumulator nothing writes to
  /// finishes as `{}` — the filter that matches every document.
  ///
  /// That degenerate case is the same one
  /// [`SqlConjunction::new`](super::sql::SqlConjunction::new) answers by pushing no clause keyword,
  /// and it falls out here rather than being arranged: an empty document has no ` WHERE ` to have
  /// emitted.
  #[inline]
  pub fn new() -> Self {
    Self::default()
  }

  /// Start accumulating the predicates INSIDE an `$elemMatch`, where the empty path is the member
  /// rather than a caller error.
  ///
  /// The only difference from [`new`](Self::new) is what the two readings of that address are, and
  /// the accumulator is where the choice lives because the [`At`] cannot carry it: an element
  /// comparison is applied at the same row and the same empty path a top-level one would be.
  ///
  /// It is also where the value form's limits are enforced, since this is the only place that knows
  /// they are in force — see [`into_element_document`](Self::into_element_document), which is where
  /// what it noticed comes back.
  #[inline]
  pub fn element() -> Self {
    Self {
      scope: Scope::Element,
      ..Self::default()
    }
  }

  /// Add `{field: {op: value}}` to the filter, merging it into the operator document `field`
  /// already has.
  ///
  /// # What the guard decides
  ///
  /// A field whose key is not yet present opens one. A field that has the key and NOT this
  /// operator gains it — `{a: {$gt: 1}}` becoming `{a: {$gt: 1, $lt: 5}}`, which is the whole of
  /// what a document can do that SQL does with a second conjunct.
  ///
  /// Anything else is a conjunct no single key can hold, and it goes to the overflow rather than
  /// over the top of what is there: the operator already present, and — unreachably, since this is
  /// the only writer — a value that is not an operator document. Overwriting either would be the
  /// silent loss the unique-key rule invites; a second `$and` branch says the same thing MongoDB
  /// says.
  ///
  /// # What an ELEMENT scope notices here, and why it cannot say so
  ///
  /// An operator written at the MEMBER — the empty path — inside an element scope has to be one the
  /// value form answers, and [`MongoOperator::in_element_scope`] is the row that knows. This is
  /// where the pair is first visible together and the method cannot answer, so what it noticed is
  /// kept for [`into_element_document`](Self::into_element_document). Changing the signature to
  /// return one instead would put a `Result` on the call every kind in this family already makes,
  /// to report something none of them can cause.
  pub fn merge(&mut self, field: &str, op: MongoOperator, value: Bson) {
    if self.scope == Scope::Element && field == ABSENT_FIELD && !op.in_element_scope() {
      self.refuse(MongoLoweringError::ElementOperator(op));
    }
    match self.merged.get_mut(field) {
      Some(Bson::Document(operators)) if !operators.contains_key(op.as_str()) => {
        operators.insert(op.as_str(), value);
      }
      Some(_) => self.overflow.push(field_predicate(field, op, value)),
      None => {
        self
          .merged
          .insert(field, Bson::Document(operator_document(op, value)));
      }
    }
  }

  /// Add a whole filter DOCUMENT as a conjunct — the seam for an operator MongoDB reads only at the
  /// top level, where a field's operator document has no position to put one.
  ///
  /// `$expr` and `$nor` are the two this family writes: a cardinality is an expression over the
  /// column rather than a predicate on it, and a set INEQUALITY is the negation of a conjunction
  /// that no single key can hold. Neither is a [`MongoOperator`] row for the reason `AND` is not —
  /// a type whose values are legal in two unrelated positions cannot say where each belongs.
  ///
  /// It lands in the same overflow the merge fold uses, because a top-level operator and a repeated
  /// one need the same thing from the finished document: to be ANDed beside the merged keys. What
  /// it also records is that it is NOT a fold — an element scope hosts no top-level operator in
  /// either of its forms, so an accumulator given one can never be finished as an element document.
  pub fn and(&mut self, document: Document) {
    self.top_level = true;
    if self.scope == Scope::Element {
      self.refuse(MongoLoweringError::ElementDocument);
    }
    self.overflow.push(document);
  }

  /// Add the STAGES one relation contributes, and record every collection they read.
  ///
  /// The third seam beside [`merge`](Self::merge) and [`and`](Self::and), and the only one whose
  /// argument is not a filter: `$lookup` is a pipeline stage, so what a relation writes runs beside
  /// this accumulator's `$match` rather than inside it. What arrives is the whole self-contained run
  /// — the join, the test on the field it filled, and the projection dropping that field — because
  /// the accumulator has no business knowing which of them is which.
  ///
  /// `reads` is the JOINED collections rather than one name, so a relation carrying a relation hands
  /// up everything under it in one call. Repeats are dropped here rather than at the package: the
  /// read concern's question is *is this more than one collection*, and a collection joined twice is
  /// still one.
  ///
  /// # An ELEMENT scope cannot hold this, and it notices here
  ///
  /// `$elemMatch` is a filter document with no pipeline around it, so a stage has nowhere to go. The
  /// method writes rather than answering — the signature a relation already calls — so what it
  /// noticed is kept for [`into_element_document`](Self::into_element_document), exactly as the
  /// operator check in `merge` and the top-level check in `and` are.
  pub fn join(&mut self, stages: Vec<Document>, reads: Vec<&'static FieldName>) {
    if self.scope == Scope::Element {
      self.refuse(MongoLoweringError::ElementRelation);
    }
    self.joins.extend(stages);
    for collection in reads {
      if !self.reads.contains(&collection) {
        self.reads.push(collection);
      }
    }
  }

  /// The finished predicate: the `$match` document, the stages a relation joined, and what those
  /// read.
  ///
  /// The finisher for the position that HAS a pipeline, which is every package this crate builds and
  /// every `$lookup` sub-pipeline inside one. [`into_document`](Self::into_document) is the same
  /// merge without the stages, and it is what the element scope and a leaf-only caller finish with.
  pub fn into_predicate(mut self) -> MongoPredicate {
    let joins = core::mem::take(&mut self.joins);
    let reads = core::mem::take(&mut self.reads);
    MongoPredicate {
      filter: self.into_document(),
      joins,
      reads,
    }
  }

  /// The finished filter document — every merged key, and the overflow beside them.
  ///
  /// The merged fields are the document, and the overflow — if there is any — arrives as a top-level
  /// `$and` beside them. That is MongoDB's own fold and it composes with the merged keys rather
  /// than replacing them: a top-level `$and` is ANDed with its siblings, so
  /// `{b: {$gt: 1}, $and: [ … ]}` says exactly what the two halves each say.
  ///
  /// # It answers the KEYS alone, which is the whole predicate for everything but a relation
  ///
  /// A `$lookup` is a stage and has no filter-document spelling, so an accumulator a relation wrote
  /// into is not finished by this — [`into_predicate`](Self::into_predicate) is, and it is what
  /// every package goes through. This one stays because two positions genuinely have no pipeline to
  /// put a stage in and therefore nothing to lose: an `$elemMatch`'s scope, which refuses a relation
  /// outright, and a caller assembling a filter out of leaf comparisons.
  #[must_use]
  pub fn into_document(mut self) -> Document {
    if !self.overflow.is_empty() {
      let branches = self.overflow.into_iter().map(Bson::Document).collect();
      self.merged.insert(AND, Bson::Array(branches));
    }
    self.merged
  }

  /// The finished document an `$elemMatch` holds, or why this element comparison has none.
  ///
  /// # The two forms are read off the KEYS, because that is what decides them
  ///
  /// A conjunct written at the empty path is under `ABSENT_FIELD`, which is the MEMBER here. Lifting
  /// that one key's operator document to the top IS the value form, and every other key is a field
  /// below the member, which is the query form. So the shape of what was written picks the form and
  /// nothing has to be declared.
  ///
  /// # Errors
  ///
  /// [`MongoLoweringError::ElementOperator`] for an operator the value form does not answer,
  /// [`MongoLoweringError::ElementDocument`] for a top-level operator, and
  /// [`MongoLoweringError::ElementConjunction`] where the value form is in force and anything else
  /// was written: an `$and` branch it cannot hold, or a field name it cannot mix with.
  ///
  /// The query form keeps the fold — `{$elemMatch: {$and: [{p: {$gt: 1}}, {p: {$lt: 6}}]}}` is
  /// legal and was measured — so a composite element is refused nothing that a top-level one is not.
  pub fn into_element_document(mut self) -> Result<Document, MongoLoweringError> {
    if let Some(refusal) = self.refusal {
      return Err(refusal);
    }
    let member = match self.merged.remove(ABSENT_FIELD) {
      Some(Bson::Document(operators)) => operators,
      // Unreachable: `merge` is the only writer and writes only operator documents. Putting it back
      // is what keeps an impossible case from being a dropped conjunct rather than a wrong answer.
      Some(other) => {
        self.merged.insert(ABSENT_FIELD, other);
        return Ok(self.into_document());
      }
      None => return Ok(self.into_document()),
    };
    if self.merged.is_empty() && self.overflow.is_empty() {
      Ok(member)
    } else {
      Err(MongoLoweringError::ElementConjunction)
    }
  }

  /// Keep the FIRST refusal, since a later one is a consequence of a comparison that already had no
  /// rendering.
  fn refuse(&mut self, refusal: MongoLoweringError) {
    self.refusal.get_or_insert(refusal);
  }
}

/// What a MongoDB predicate becomes once a relation is in it: the `$match` document, the stages the
/// joins contributed, and every collection those stages read.
///
/// # Three facts rather than one document, because a join is not a key
///
/// Every other backend's lowering finishes as one value. This one cannot: `$lookup` is a stage, so a
/// predicate holding a relation is a RUN of stages and the filter is only its first. Handing the
/// three back separately is what lets each caller write the `$match` its own position wants — a
/// package writes one ALWAYS, empty included, so that every package is one shape a reader can check,
/// and a `$lookup`'s own sub-pipeline writes none for an empty predicate because a no-op stage
/// inside a join is noise.
///
/// # The reads travel with the stages, and that is the read concern staying honest
///
/// A pipeline touching more than one collection needs a snapshot to see one state of the database.
/// The party that ADDED the `$lookup` is the party that knows what it looks into, so the fact moves
/// with the stage rather than being recovered by reading the pipeline back at execution time. See
/// [`MongoPipeline::reads`](crate::query::mongo::MongoPipeline::reads), which is where it lands.
#[derive(Debug, Clone, Default, PartialEq)]
#[must_use = "a predicate renders nothing until its stages are taken"]
pub struct MongoPredicate {
  filter: Document,
  joins: Vec<Document>,
  reads: Vec<&'static FieldName>,
}

impl MongoPredicate {
  /// The `$match` document — every merged key, and the overflow beside them.
  #[inline]
  pub const fn filter(&self) -> &Document {
    &self.filter
  }

  /// The stages the joins contributed, in the order the relations were crossed. They belong AFTER
  /// the `$match` and before any `$sort`.
  #[inline]
  #[must_use]
  pub fn joins(&self) -> &[Document] {
    &self.joins
  }

  /// Every collection those stages read, without repeats — empty where nothing joined.
  #[inline]
  #[must_use]
  pub fn reads(&self) -> &[&'static FieldName] {
    &self.reads
  }

  /// The three, taken — which is what a caller assembling a pipeline needs, since all three are
  /// moved into it.
  #[inline]
  #[must_use]
  pub fn into_parts(self) -> (Document, Vec<Document>, Vec<&'static FieldName>) {
    (self.filter, self.joins, self.reads)
  }
}

/// `{op: value}` — a field's operator document, holding one operator.
fn operator_document(op: MongoOperator, value: Bson) -> Document {
  let mut operators = Document::new();
  operators.insert(op.as_str(), value);
  operators
}

/// `{field: {op: value}}` — one field's whole predicate, which is what an `$and` branch is.
fn field_predicate(field: &str, op: MongoOperator, value: Bson) -> Document {
  let mut predicate = Document::new();
  predicate.insert(field, Bson::Document(operator_document(op, value)));
  predicate
}

#[cfg(test)]
mod tests;