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
//! The fixture every test in this family runs against, and the two facts that belong to the module
//! rather than to one of its files.
//!
//! # The bindings are written BY HAND, which is the third-party proof as well as the harness
//!
//! `ingraph-codegen` cannot reach this crate, so a test here cannot be an expansion. What it can be
//! is the same thing a third party writes: a record, its document, its order-by and its cursor
//! value, bound to the engine through nothing but the public traits. Everything the engine asks of
//! a declaration is asked of this file too, so a seam that could only be satisfied from inside the
//! emitter would not compile here — which is `query::sql::find`'s own arrangement, one backend over.

use std::sync::Arc;

use bson::{Bson, Document, doc};

use super::{
  MongoExtract, MongoHop, MongoNesting, MongoOrdering, MongoQuery, MongoSubjects, MongoTypeError,
  MongoWrite, field,
};
use crate::{
  ComplexComparison, CursorValue, FieldName, Identifiable, OrderDirection, OrderTerm, Record,
  RecordAddress, TermName, Transformer,
  comparison::{
    At, Backend, CollapsibleComparison,
    mongo::{Mongo, MongoCarrier, MongoRefComparison, MongoRelatedDocument, MongoScalarComparison},
  },
  query::{CrossingError, mongo::MongoExtractionError},
};

/// A shot inside a media: a lineage column, an id, a text column, a NULLABLE sort column — which is
/// what makes the ordering exercise the null position rather than skipping past it — and a
/// REFERENCE, which is what a nested ordering term crosses.
#[derive(Debug, Clone, PartialEq)]
pub(super) struct Shot {
  pub(super) media: i64,
  pub(super) id: i64,
  pub(super) title: String,
  pub(super) score: Option<f64>,
  pub(super) cover: Option<i64>,
}

/// The key, `lineage ⊕ id` — the OUTPUT vocabulary a record hands over, which is not the address.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct ShotKey {
  media: i64,
  id: i64,
}

impl Identifiable for Shot {
  type Id = i64;

  fn id_ref(&self) -> &i64 {
    &self.id
  }
}

impl Transformer for Shot {
  type Key = ShotKey;
  type Lineage = i64;
  type Record = Self;
  type Graphql = ();

  fn key(&self) -> ShotKey {
    ShotKey {
      media: self.media,
      id: self.id,
    }
  }
}

/// The stored document, field for field — including the id, whose Rust field is `id` and whose BSON
/// key is `_id`. The two names never meet in this struct, which is the point: the mapping is the
/// extraction's and the renderer's, so a row is an ordinary Rust value either side of it.
#[derive(Debug, Clone, PartialEq)]
pub(super) struct ShotMongo {
  pub(super) media: i64,
  pub(super) id: i64,
  pub(super) title: String,
  pub(super) score: Option<f64>,
  pub(super) cover: Option<i64>,
}

/// The keyframe a shot's `cover_id` points at — the target comparison a relation position holds,
/// with the one field a package golden needs to see inside a join's own pipeline.
#[derive(Debug, Default)]
pub(super) struct KeyframeFilter {
  pub(super) title: MongoScalarComparison<String>,
}

impl ComplexComparison<Mongo> for KeyframeFilter {
  fn conjuncts(&self) -> usize {
    self.title.conjuncts()
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: <Mongo as Backend>::Builder<'q>,
  ) -> Result<<Mongo as Backend>::Builder<'q>, <Mongo as Backend>::Error> {
    let title = at.frame(FieldName::new("title"));
    self.title.apply(title.at(), builder)
  }
}

/// It never collapses, so every package below actually opens the join it is about. A generated
/// comparison answers from the operators it set; this one answers from what the fixture is FOR.
impl CollapsibleComparison<Mongo> for KeyframeFilter {
  type Id = MongoScalarComparison<i64>;

  fn only_id(&self) -> Option<&MongoScalarComparison<i64>> {
    None
  }
}

/// The collection a `cover_id` points at, with the join fields its expansion would have minted.
///
/// Spelled to `DEPTH_CEILING` rather than to the one depth a relation golden needs, because the
/// nested ORDERING takes its hop names off this same table and a chain has to have names to run out
/// of. `[0]` is minted like the rest and is never worn.
const KEYFRAME: MongoRelatedDocument = MongoRelatedDocument::new(
  RecordAddress::new(FieldName::new("keyframe"), &[FieldName::new("id")]),
  &[
    "__ig_keyframe_0__",
    "__ig_keyframe_1__",
    "__ig_keyframe_2__",
    "__ig_keyframe_3__",
    "__ig_keyframe_4__",
    "__ig_keyframe_5__",
    "__ig_keyframe_6__",
    "__ig_keyframe_7__",
  ],
);

/// The collection a keyframe's own `strip_id` points at — the second hop of the two-hop order.
const STRIP: MongoRelatedDocument = MongoRelatedDocument::new(
  RecordAddress::new(FieldName::new("strip"), &[FieldName::new("id")]),
  &[
    "__ig_strip_0__",
    "__ig_strip_1__",
    "__ig_strip_2__",
    "__ig_strip_3__",
    "__ig_strip_4__",
    "__ig_strip_5__",
    "__ig_strip_6__",
    "__ig_strip_7__",
  ],
);

/// The LOWERED filter over that document — one slot per column, in the storage types, plus the
/// RELATION position the record's `cover_id` carries.
#[derive(Debug)]
pub(super) struct ShotFilter {
  pub(super) title: MongoScalarComparison<String>,
  pub(super) score: MongoScalarComparison<f64>,
  pub(super) cover: MongoRefComparison<KeyframeFilter>,
}

/// Written out rather than derived, because a relation position holds the ADDRESS of the collection
/// it points at and no address is a default — which is the same reason a generated comparison states
/// its own `new` beside the slots.
impl Default for ShotFilter {
  fn default() -> Self {
    Self {
      title: MongoScalarComparison::new(),
      score: MongoScalarComparison::new(),
      cover: MongoRefComparison::new(KEYFRAME, KeyframeFilter::default()),
    }
  }
}

impl ComplexComparison<Mongo> for ShotFilter {
  fn conjuncts(&self) -> usize {
    self.title.conjuncts() + self.score.conjuncts() + ComplexComparison::conjuncts(&self.cover)
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: <Mongo as Backend>::Builder<'q>,
  ) -> Result<<Mongo as Backend>::Builder<'q>, <Mongo as Backend>::Error> {
    let title = at.frame(FieldName::new("title"));
    let builder = self.title.apply(title.at(), builder)?;
    let score = at.frame(FieldName::new("score"));
    let builder = self.score.apply(score.at(), builder)?;
    // The relation is applied at the REFERENCE field, which is what a forward position joins on.
    let cover = at.frame(FieldName::new("cover_id"));
    self.cover.apply(cover.at(), builder)
  }
}

impl Record<Mongo> for Shot {
  type Row = ShotMongo;
  type Comparison = ShotFilter;
  type OrderBy = ShotOrder;
}

/// One ordering term over the record: which column, and which way it runs — or, for the last
/// variant, WHICH REFERENCE it crosses and the target's own order beyond it.
///
/// `Arc` rather than [`Box`], for the reason
/// [`SqlOrdering::Order`](crate::query::sql::SqlOrdering::Order) records: a term is cloned once per
/// document per term, and a `Box` clone is a deep copy whose cost grows with the nesting.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum ShotOrder {
  Title(OrderDirection),
  Score(OrderDirection),
  Id(OrderDirection),
  Cover(Arc<KeyframeOrder>),
}

/// The target's own order-by, which is the type a nested term carries.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum KeyframeOrder {
  Title(OrderDirection),
  Strip(Arc<StripOrder>),
}

/// One hop further, so the fixture reaches DEPTH TWO — which is the case a chain of `$lookup`s
/// exists for.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum StripOrder {
  Label(OrderDirection),
}

/// The reference a `cover` term crosses: the keyframe a shot's `cover_id` names.
const VIA_COVER: MongoHop = MongoHop::new(KEYFRAME, FieldName::new("cover_id"));

/// The one a keyframe's own `strip_id` names.
const VIA_STRIP: MongoHop = MongoHop::new(STRIP, FieldName::new("strip_id"));

impl ShotOrder {
  /// The term this variant renders as — the identity a rename cannot move, the field this database
  /// spells it, the direction, and whether the field can hold `null`.
  ///
  /// A NESTED term's identity is keyed on the REFERENCE FIELD and never on the target type, so two
  /// references at one collection would be two different orders; its column is the reference the
  /// hop crosses, and nothing renders it — the subject is the materialized alias, in every position.
  /// It is always NULLABLE, whatever the target's own field says: a document whose reference is
  /// absent, and one whose reference points at nothing, both leave the `$lookup` with an empty array
  /// and the sort field unwritten.
  fn term(&self) -> OrderTerm {
    match self {
      Self::Title(direction) => {
        OrderTerm::new(TermName::new("title"), FieldName::new("title"), *direction)
      }
      // The one NULLABLE column term, which is what makes the keyset's trailing-null arm reachable.
      Self::Score(direction) => {
        OrderTerm::nullable(TermName::new("score"), FieldName::new("score"), *direction)
      }
      Self::Id(direction) => OrderTerm::new(TermName::new("id"), FieldName::new("id"), *direction),
      Self::Cover(target) => {
        let (identity, direction) = match &**target {
          KeyframeOrder::Title(direction) => ("cover_id.title", *direction),
          KeyframeOrder::Strip(strip) => match &**strip {
            StripOrder::Label(direction) => ("cover_id.strip_id.label", *direction),
          },
        };
        OrderTerm::nullable(
          TermName::new(identity),
          FieldName::new("cover_id"),
          direction,
        )
      }
    }
  }
}

/// What every term of one completed order sorts by, INDEXED BY LEVEL — the parallel structure a
/// generated provider builds, where a plain level holds [`None`] and sorts by its own field.
#[derive(Debug, Clone, PartialEq)]
pub(super) struct ShotSubjects(Vec<Option<MongoNesting>>);

impl MongoSubjects for ShotSubjects {
  fn nesting(&self, _: &[OrderTerm], level: usize) -> Option<&MongoNesting> {
    self.0[level].as_ref()
  }
}

/// The references one term crosses and the field it reads, or [`None`] where it reads a field of
/// the shot itself.
fn nesting(order: &ShotOrder) -> Option<MongoNesting> {
  let ShotOrder::Cover(target) = order else {
    return None;
  };
  Some(match &**target {
    KeyframeOrder::Title(_) => MongoNesting::new(VIA_COVER, FieldName::new("title")),
    KeyframeOrder::Strip(strip) => match &**strip {
      StripOrder::Label(_) => MongoNesting::new(VIA_STRIP, FieldName::new("label")).via(VIA_COVER),
    },
  })
}

/// One slot of a cursor over this database's stored values — the record's own sum over its
/// orderable columns, the nested ones included.
#[derive(Debug, Clone, PartialEq)]
pub(super) enum ShotCursor {
  Title(String),
  Score(f64),
  Id(i64),
  CoverTitle(String),
  CoverStripLabel(String),
}

/// A slot BINDS through [`MongoCarrier`], which is the whole of what makes a cursor value
/// per-backend: the bytes it carries are shared and what it becomes in a filter is not.
impl MongoCarrier for ShotCursor {
  fn to_bson(&self) -> Bson {
    match self {
      Self::Title(value) | Self::CoverTitle(value) | Self::CoverStripLabel(value) => {
        value.to_bson()
      }
      Self::Score(value) => value.to_bson(),
      Self::Id(value) => value.to_bson(),
    }
  }
}

/// The codec carries a TAG, and the tag is the column — so a forged frame cannot move a text value
/// into a numeric column's slot by rearranging the bytes.
impl CursorValue for ShotCursor {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    match self {
      Self::Title(value) => {
        out.push(0);
        value.write_cursor(out);
      }
      Self::Score(value) => {
        out.push(1);
        value.write_cursor(out);
      }
      Self::Id(value) => {
        out.push(2);
        value.write_cursor(out);
      }
      Self::CoverTitle(value) => {
        out.push(3);
        value.write_cursor(out);
      }
      Self::CoverStripLabel(value) => {
        out.push(4);
        value.write_cursor(out);
      }
    }
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let (tag, rest) = bytes.split_first()?;
    match *tag {
      0 => String::read_cursor(rest).map(Self::Title),
      1 => f64::read_cursor(rest).map(Self::Score),
      2 => i64::read_cursor(rest).map(Self::Id),
      3 => String::read_cursor(rest).map(Self::CoverTitle),
      4 => String::read_cursor(rest).map(Self::CoverStripLabel),
      _ => None,
    }
  }
}

impl MongoQuery for ShotMongo {
  type Record = Shot;

  const ADDRESS: RecordAddress =
    RecordAddress::new(FieldName::new("shot"), &[FieldName::new("id")]);
  /// The join fields a relation over this collection would land its documents in, spelled out the
  /// way the mint writes them. Eight, because that is
  /// [`DEPTH_CEILING`](crate::query::DEPTH_CEILING); `[0]` is never worn.
  const ALIASES: &'static [&'static str] = &[
    "__ig_shot_0__",
    "__ig_shot_1__",
    "__ig_shot_2__",
    "__ig_shot_3__",
    "__ig_shot_4__",
    "__ig_shot_5__",
    "__ig_shot_6__",
    "__ig_shot_7__",
  ];
  const FIELDS: &'static [&'static FieldName] = &[
    FieldName::new("media"),
    FieldName::new("id"),
    FieldName::new("title"),
    FieldName::new("score"),
    FieldName::new("cover_id"),
  ];

  fn id(id: &i64) -> Result<Bson, CrossingError> {
    Ok(id.to_bson())
  }

  /// The extraction an emitted document carries, written here the way the emitter writes it: one
  /// [`field`] call per column, under the name the document spells it — which is `_id` for the id.
  fn from_document(document: &Document) -> Result<Self, MongoExtractionError> {
    Ok(Self {
      media: field(document, "media")?,
      id: field(document, "_id")?,
      title: field(document, "title")?,
      score: field(document, "score")?,
      cover: field(document, "cover_id")?,
    })
  }

  fn record(self) -> Result<Shot, CrossingError> {
    Ok(Shot {
      media: self.media,
      id: self.id,
      title: self.title,
      score: self.score,
      cover: self.cover,
    })
  }
}

/// The WRITE half of the same binding, written the way an emitter would write it: the crossing IN,
/// and one entry per field under the key this database spells it — the exact inverse of
/// `from_document` above, in the same order, so the round trip is visible in one file.
///
/// The optional columns take no branch, which is
/// [`MongoCarrier for Option<T>`](crate::MongoCarrier)'s doing: `None` writes `null` there rather
/// than at every field of every document, exactly as `MongoExtract for Option<T>` reads one back.
impl MongoWrite for ShotMongo {
  fn row(record: Shot) -> Result<Self, CrossingError> {
    Ok(Self {
      media: record.media,
      id: record.id,
      title: record.title,
      score: record.score,
      cover: record.cover,
    })
  }

  fn document(&self) -> Document {
    let mut document = Document::new();
    document.insert("media", self.media.to_bson());
    document.insert("_id", self.id.to_bson());
    document.insert("title", self.title.to_bson());
    document.insert("score", self.score.to_bson());
    document.insert("cover_id", self.cover.to_bson());
    document
  }
}

impl MongoOrdering for ShotMongo {
  type Order = ShotOrder;
  type Subjects = ShotSubjects;
  type Value = ShotCursor;

  /// The client's terms, then the id ascending — MOVED rather than repeated where a term already
  /// names it, which is what keeps a `$sort` document from needing a key twice.
  fn complete(written: &[ShotOrder]) -> Vec<ShotOrder> {
    let mut order: Vec<ShotOrder> = written
      .iter()
      .filter(|term| !matches!(term, ShotOrder::Id(_)))
      .cloned()
      .collect();
    order.push(ShotOrder::Id(OrderDirection::Asc));
    order
  }

  fn term(order: ShotOrder) -> OrderTerm {
    order.term()
  }

  fn subjects(order: &[ShotOrder]) -> ShotSubjects {
    ShotSubjects(order.iter().map(nesting).collect())
  }

  /// The three plain terms read the DECODED document, where the extraction already put their
  /// values; the nested one reads the RAW one at the alias the engine materialized it under, which
  /// is a field no `FIELDS` entry names and therefore one `self` cannot hold.
  fn value(
    &self,
    order: ShotOrder,
    raw: &Document,
    alias: &str,
  ) -> Result<Option<ShotCursor>, MongoTypeError> {
    let materialized = |mint: fn(String) -> ShotCursor| {
      <Option<String> as MongoExtract>::extract(raw.get(alias)).map(|value| value.map(mint))
    };
    match order {
      ShotOrder::Title(_) => Ok(Some(ShotCursor::Title(self.title.clone()))),
      ShotOrder::Score(_) => Ok(self.score.map(ShotCursor::Score)),
      ShotOrder::Id(_) => Ok(Some(ShotCursor::Id(self.id))),
      ShotOrder::Cover(target) => match &*target {
        KeyframeOrder::Title(_) => materialized(ShotCursor::CoverTitle),
        KeyframeOrder::Strip(_) => materialized(ShotCursor::CoverStripLabel),
      },
    }
  }
}

/// The completed order a page runs in, as terms — built once here because four files render it.
pub(super) fn terms(written: &[ShotOrder]) -> Vec<OrderTerm> {
  <ShotMongo as MongoOrdering>::complete(written)
    .into_iter()
    .map(<ShotMongo as MongoOrdering>::term)
    .collect()
}

/// What that completed order sorts by — the other half of the pair, so no test can build the terms
/// from one order and the subjects from another.
pub(super) fn subjects(written: &[ShotOrder]) -> ShotSubjects {
  <ShotMongo as MongoOrdering>::subjects(&<ShotMongo as MongoOrdering>::complete(written))
}

/// `cover.title` ascending — one hop, and the order every nested golden below runs.
pub(super) fn by_cover_title() -> [ShotOrder; 1] {
  [ShotOrder::Cover(Arc::new(KeyframeOrder::Title(
    OrderDirection::Asc,
  )))]
}

/// `cover.strip.label` ascending — two hops, which is the chain.
pub(super) fn by_cover_strip_label() -> [ShotOrder; 1] {
  [ShotOrder::Cover(Arc::new(KeyframeOrder::Strip(Arc::new(
    StripOrder::Label(OrderDirection::Asc),
  ))))]
}

/// A subjects party whose FIRST term is one nesting of a CHOSEN depth — the shape the ceiling
/// assertions need, and one the fixture's own provider cannot build, its nestings being what the
/// declaration wrote.
pub(super) struct DeepSubjects(MongoNesting);

impl DeepSubjects {
  /// A nesting crossing `hops` references, every one of them the shot's own cover field — a
  /// self-reference, which mints exactly as many names as a chain of distinct collections would.
  pub(super) fn crossing(hops: usize) -> Self {
    let hop = MongoHop::new(
      MongoRelatedDocument::of::<ShotMongo>(),
      FieldName::new("cover_id"),
    );
    let mut nesting = MongoNesting::new(hop, FieldName::new("title"));
    for _ in 1..hops {
      nesting = nesting.via(hop);
    }
    Self(nesting)
  }
}

impl MongoSubjects for DeepSubjects {
  fn nesting(&self, _: &[OrderTerm], level: usize) -> Option<&MongoNesting> {
    (level == 0).then_some(&self.0)
  }
}

/// A filter over the title, which every package golden below carries so that the `$match` is a
/// real predicate rather than an empty document.
pub(super) fn titled(title: &str) -> ShotFilter {
  let mut filter = ShotFilter::default();
  filter.title.eq = Some(title.to_owned());
  filter
}

/// A filter over the COVER's title — the relation position asked, which is what turns a package into
/// a joined one.
pub(super) fn covering(title: &str) -> ShotFilter {
  let mut target = KeyframeFilter::default();
  target.title.eq = Some(title.to_owned());
  ShotFilter {
    cover: MongoRefComparison::new(KEYFRAME, target),
    ..ShotFilter::default()
  }
}

/// A relation position reads BOTH halves off one document binding, which is what makes them
/// impossible to mismatch — the address and the join fields are the same collection's or the call
/// does not compile.
#[test]
fn a_related_document_reads_its_address_and_its_join_fields_off_one_binding() {
  let related = MongoRelatedDocument::of::<ShotMongo>();

  assert_eq!(related.address(), &<ShotMongo as MongoQuery>::ADDRESS);
  assert_eq!(
    <ShotMongo as MongoQuery>::ALIASES[1],
    "__ig_shot_1__",
    "the mint's shape is the SQL family's, under a different job"
  );
  let _ = related;
}

/// The record's id becomes `_id` everywhere a field path is rendered, and the ADDRESS is what
/// decides it — see [`field_key`](crate::comparison::mongo::field_key).
///
/// Asserted through the BACKEND row rather than the free function, so what is measured is what a
/// comparison would actually be handed.
#[test]
fn the_records_own_id_renders_as_the_documents_underscore_id() {
  let address = <ShotMongo as MongoQuery>::ADDRESS;
  let rendered = |name| {
    let frame = At::new(&address).frame(FieldName::new(name));
    let mut out = String::new();
    <Mongo as Backend>::write_column(frame.at(), &mut out);
    out
  };

  assert_eq!(rendered("id"), "_id");
  assert_eq!(rendered("title"), "title");
}

/// A field called `id` BELOW the top level is a field of a subdocument, and the document's own id is
/// at the top level by definition — so the mapping stops at the first segment.
#[test]
fn a_nested_id_keeps_its_own_name() {
  let address = <ShotMongo as MongoQuery>::ADDRESS;
  let outer = At::new(&address).frame(FieldName::new("cover"));
  let inner = outer.at().frame(FieldName::new("id"));
  let mut out = String::new();
  <Mongo as Backend>::write_column(inner.at(), &mut out);

  assert_eq!(out, "cover.id");
}

/// The document round-trips: what [`MongoQuery::from_document`] reads is what the fixture holds,
/// with the id taken from `_id` and an absent nullable field answering [`None`].
#[test]
fn the_extraction_reads_a_whole_document() {
  let document =
    doc! { "media": 7i64, "_id": 12i64, "title": "a red car", "score": 0.5, "cover_id": 4i64 };
  assert_eq!(
    ShotMongo::from_document(&document),
    Ok(ShotMongo {
      media: 7,
      id: 12,
      title: "a red car".to_owned(),
      score: Some(0.5),
      cover: Some(4),
    })
  );

  let sparse = doc! { "media": 7i64, "_id": 12i64, "title": "a red car" };
  assert_eq!(
    ShotMongo::from_document(&sparse).map(|row| row.score),
    Ok(None)
  );
}

/// A missing `_id` is refused BY NAME, which is the whole of what the field context buys: the
/// refusal names the key a reader would go and look for rather than the Rust field.
#[test]
fn a_missing_id_is_refused_under_the_key_the_document_spells() {
  let document = doc! { "media": 7i64, "title": "a red car" };
  let refusal = ShotMongo::from_document(&document).expect_err("no `_id`");

  assert_eq!(refusal.field(), "_id");
  assert_eq!(
    refusal.to_string(),
    "`_id` did not read: this field is not in the document"
  );
}

/// The extraction is the NO-BYPASS pin: every column goes through [`field`], so the typed refusal
/// survives to the caller. A decode that read a value out of the document directly — the shape
/// `#[serde(deserialize_with = …)]` would have produced — loses the field name and the cause both,
/// and this is what says so.
#[test]
fn every_column_is_read_through_the_one_extraction_authority() {
  let document = doc! { "media": 7i64, "_id": 12i64, "title": 3i64, "score": 0.5 };
  let refusal = ShotMongo::from_document(&document).expect_err("`title` is not a string");

  assert_eq!(refusal.field(), "title");
  assert_eq!(
    refusal.cause(),
    &super::MongoTypeError::wrong_type("string", "long")
  );
}

/// A document is opaque to `MongoExtract` at the leaf, so the trait's own error carries no field —
/// which is why [`field`] exists and why nothing else is allowed to call `extract` directly.
#[test]
fn a_leaf_refusal_carries_no_field_and_the_wrapper_adds_it() {
  assert_eq!(
    <i64 as MongoExtract>::extract(None),
    Err(super::MongoTypeError::Absent)
  );
  assert_eq!(
    field::<i64>(&doc! {}, "score").expect_err("absent").field(),
    "score"
  );
}

/// **The FROZEN BOUNDARY.** A nested term's cursor value is read off the document the page
/// RETURNED, at the alias the engine materialized it under — never re-derived through the
/// reference.
///
/// Re-deriving it would compare against whatever the target document holds NOW, so a rename between
/// two pages would silently empty or duplicate the next one. Reading the value the page actually
/// sorted at is what makes a cursor mean *where I stopped*.
#[test]
fn a_nested_terms_cursor_value_is_read_at_the_engines_own_alias() {
  let alias = super::sort_alias(0);
  let order = ShotOrder::Cover(Arc::new(KeyframeOrder::Title(OrderDirection::Asc)));
  let document = doc! {
    "media": 7i64, "_id": 12i64, "title": "a red car", "cover_id": 4i64, "__ig_ord0__": "Autumn",
  };
  let row = ShotMongo::from_document(&document).expect("a whole document");

  assert_eq!(
    row.value(order.clone(), &document, &alias),
    Ok(Some(ShotCursor::CoverTitle("Autumn".to_owned())))
  );

  // A document whose `$lookup` found nothing has no such field, and `$first` of an empty array
  // writes none — which is the framework's own position for a missing value, in the cursor exactly
  // as in the `$sort`.
  let unjoined = doc! { "media": 7i64, "_id": 12i64, "title": "a red car" };
  let row = ShotMongo::from_document(&unjoined).expect("a whole document");

  assert_eq!(row.value(order, &unjoined, &alias), Ok(None));
}

/// A term over a field of the document itself reads the DECODED row and ignores both the raw
/// document and the alias — which is why they cost a plain order nothing.
#[test]
fn a_plain_terms_cursor_value_ignores_the_raw_document() {
  let document =
    doc! { "media": 7i64, "_id": 12i64, "title": "a red car", "__ig_ord0__": "Autumn" };
  let row = ShotMongo::from_document(&document).expect("a whole document");

  assert_eq!(
    row.value(
      ShotOrder::Title(OrderDirection::Asc),
      &doc! {},
      &super::sort_alias(0)
    ),
    Ok(Some(ShotCursor::Title("a red car".to_owned())))
  );
}

/// The materialized value is TYPED, and a slot that cannot hold what the join produced refuses
/// rather than answering [`None`] — which would put the boundary at the null group and page the
/// wrong documents.
#[test]
fn a_materialized_value_of_the_wrong_type_is_refused() {
  let document = doc! { "media": 7i64, "_id": 12i64, "title": "a red car", "__ig_ord0__": 3i64 };
  let row = ShotMongo::from_document(&document).expect("a whole document");

  assert_eq!(
    row.value(
      ShotOrder::Cover(Arc::new(KeyframeOrder::Title(OrderDirection::Asc))),
      &document,
      &super::sort_alias(0)
    ),
    Err(MongoTypeError::wrong_type("string", "long"))
  );
}

/// **The freed name.** A document carrying a column literally spelled `__ord_0` keeps it: the
/// engine writes and reads `__ig_ord0__`, so the two live side by side and the declaration's value
/// is neither read as a boundary nor overwritten by `$addFields`.
///
/// Before the mint moved inside the reserved namespace this was the exposure the constant recorded
/// and could not close — `ingraph-derive` fences `__ig` and nothing else, so a name minted outside
/// it was a name the fence never claimed.
#[test]
fn a_column_spelled_the_old_way_is_the_declarations_and_stays_untouched() {
  let alias = super::sort_alias(0);
  let document = doc! {
    "media": 7i64,
    "_id": 12i64,
    "title": "a red car",
    "cover_id": 4i64,
    "__ord_0": "the declaration's own",
    "__ig_ord0__": "Autumn",
  };
  let row = ShotMongo::from_document(&document).expect("a whole document");

  assert_eq!(
    row.value(
      ShotOrder::Cover(Arc::new(KeyframeOrder::Title(OrderDirection::Asc))),
      &document,
      &alias
    ),
    Ok(Some(ShotCursor::CoverTitle("Autumn".to_owned()))),
    "the boundary is the engine's field, not the one the declaration owns"
  );
  assert_eq!(
    document.get_str("__ord_0").ok(),
    Some("the declaration's own"),
    "and the declaration's field is still what it stored"
  );
}

/// **The cursor does not carry the alias, and this is the fence that says so.**
///
/// An [`OrderSignature`](crate::OrderSignature) folds the terms' rename-proof IDENTITIES and their
/// directions, and nothing else — not the field a database spells, and not the name an engine
/// materialized a nested value under. So renaming the mint cannot refuse a cursor a client is
/// holding, which is the property this number being FROZEN states.
///
/// It is a byte fence rather than a round trip: a signature that ever folded in a rendered name
/// would move, and a moved signature is every outstanding cursor refused with
/// [`CursorError::Order`](crate::CursorError::Order).
#[test]
fn the_order_signature_folds_no_rendered_name() {
  let nested = crate::OrderSignature::of(&terms(&by_cover_title()));

  assert_eq!(nested.get(), 0xa3ea_9224_7e71_33df);
}