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
//! The detect house's SQL side — the two filters' storage-side twins, and the one lowering shape
//! both of them are.
//!
//! ```text
//!   { label: { contains: "retriever" }, confidence: { gte: 0.8 }, bbox: { x: { lt: 0.5 } } }
//!        │
//!        ▼   the classification at the address it was given, the box one segment below
//!   instr("f_label", $1) > 0 AND "f_confidence" >= $2 AND "f_bbox_x" < $3
//! ```
//!
//! # EVERY conjunct is a HALF's, and that is the whole of this file
//!
//! There is no whole-value operator anywhere in this house — see [`DetectionFilter`], where the
//! absence is argued — so a comparison here holds one child per facet and renders nothing of its
//! own. It pushes a FRAME where a facet takes a segment and passes the address through where a facet
//! is flattened, which is exactly what
//! [`SqlDetectedLanguageComparison`](crate::primitives::lang::SqlDetectedLanguageComparison) does
//! over its identity and its confidence.
//!
//! # ONE address arrives, and the parts divide it
//!
//! A [`Detection`]'s two halves each push a segment, so a detection at `top` reaches `top_label` and
//! `top_confidence`. A [`LocatedDetection<T>`]'s classification is applied at `at` UNCHANGED —
//! flattening is exactly that — and its box pushes one segment of its own, so a finding at `subject`
//! reaches `subject_label`, `subject_confidence` and `subject_bbox_x` and its three siblings.
//!
//! [`DetectionFilter`]: super::DetectionFilter

use core::{convert::Infallible, fmt};

use smol_bytes::Utf8Bytes;

use crate::{
  At, Backend, ColumnKind, ComplexComparison, CompositeComparison, Score, SqlBoundingBoxComparison,
  ToDatabaseComparison, TryFromFilter,
  comparison::sql::{SqlConjunction, SqlEnumComparison, SqlScalarComparison, SqlTextComparison},
};

use super::{
  BarcodeDetection, BarcodeDetectionFilter, Detection, DetectionFilter, DocumentSegment,
  DocumentSegmentFilter, Label, LocatedDetection, LocatedDetectionFilter, Symbology, TextDetection,
  TextDetectionFilter,
  barcode::{PAYLOAD, SYMBOLOGY},
  detection::{CONFIDENCE, LABEL, SEGMENTS as DETECTION_SEGMENTS},
  located::BBOX,
  segment::QUAD,
  text::TEXT,
};

/// [`DetectionFilter`](super::DetectionFilter)'s storage-side twin — the label's comparison and the
/// confidence's, and nothing of its own.
///
/// Generic over the BACKEND and not one type per backend, for the reason both halves are: a label
/// binds as text in all three dialects and [`Score`] binds the wrapped `f32` in all three.
pub struct SqlDetectionComparison<Db> {
  label: SqlTextComparison<Label, Db>,
  confidence: SqlScalarComparison<Score, Db>,
}

impl<Db> SqlDetectionComparison<Db> {
  /// The empty comparison — no operator set on either half.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self {
      label: SqlTextComparison::new(),
      confidence: SqlScalarComparison::new(),
    }
  }

  /// The twenty text operators over the label column.
  #[inline]
  pub const fn label(&self) -> &SqlTextComparison<Label, Db> {
    &self.label
  }

  /// The operators over the confidence column, whose storage type is [`Score`] itself.
  #[inline]
  pub const fn confidence(&self) -> &SqlScalarComparison<Score, Db> {
    &self.confidence
  }
}

/// The lowering: one frame per half, in segment order.
///
/// The text half's bound is stated as `SqlTextComparison<Label, Db>: ComplexComparison<Db>` rather
/// than as the union of what three dialects need, and the reason is that kind's own: two of its
/// three lowerings derive a `LIKE` pattern and want `AsRef<str>` where SQLite wants only its carrier,
/// so naming the union here would impose SQLite a bound SQLite's lowering never uses.
impl<Db> ComplexComparison<Db> for SqlDetectionComparison<Db>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>>,
  SqlTextComparison<Label, Db>: ComplexComparison<Db>,
  SqlScalarComparison<Score, Db>: ComplexComparison<Db>,
{
  #[inline]
  fn conjuncts(&self) -> usize {
    ComplexComparison::<Db>::conjuncts(&self.label)
      + ComplexComparison::<Db>::conjuncts(&self.confidence)
  }

  /// Threading one accumulator through both is what makes the two facets guard ONE detection all the
  /// way down: the conjuncts join with ` AND `, so a row satisfies this comparison when its own
  /// label and its own confidence both answer.
  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: Db::Builder<'q>,
  ) -> Result<Db::Builder<'q>, Db::Error> {
    let label = at.frame(LABEL);
    let builder = self.label.apply(label.at(), builder)?;
    let confidence = at.frame(CONFIDENCE);

    self.confidence.apply(confidence.at(), builder)
  }
}

/// The one place the columns a detection spans are stated — [`Detection`](super::Detection)'s own
/// [`ColumnKind`] row, read rather than restated.
impl<Db> CompositeComparison<Db> for SqlDetectionComparison<Db>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>>,
  SqlTextComparison<Label, Db>: ComplexComparison<Db>,
  SqlScalarComparison<Score, Db>: ComplexComparison<Db>,
{
  const SEGMENTS: &'static [crate::ColumnShape] = DETECTION_SEGMENTS;
}

impl<Db> Default for SqlDetectionComparison<Db> {
  #[inline]
  fn default() -> Self {
    Self::new()
  }
}

// Written out rather than derived, for the reason this crate's own comparison kinds write theirs
// out: a derive would bound `Db`, which is a marker no dialect type implements anything for.
impl<Db> fmt::Debug for SqlDetectionComparison<Db> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("SqlDetectionComparison")
      .field("label", &self.label)
      .field("confidence", &self.confidence)
      .finish()
  }
}

impl<Db> Clone for SqlDetectionComparison<Db> {
  fn clone(&self) -> Self {
    Self {
      label: self.label.clone(),
      confidence: self.confidence.clone(),
    }
  }
}

impl<Db> PartialEq for SqlDetectionComparison<Db> {
  fn eq(&self, other: &Self) -> bool {
    self.label == other.label && self.confidence == other.confidence
  }
}

/// **THE ROUTING ROW** — a [`Detection`](super::Detection) column is reached by a
/// [`DetectionFilter`](super::DetectionFilter), in every SQL dialect.
///
/// The storage type is the DOMAIN TYPE and not the `(Label, Score)` pair its two columns hold, and
/// the difference is what makes this house DECLARABLE. A record naming a field of this type asks its
/// emitted `FromRow` for `ToDatabaseComparison<Detection, Db>` — the type it wrote, not a tuple
/// nothing spells — so a pair-shaped row would leave the declaration with `E0277` naming a type it
/// never mentioned. [`SqlDetectedLanguageComparison`](crate::primitives::lang::SqlDetectedLanguageComparison)
/// routes on the pair, which is consistent with that family having no `Assemble` row and therefore
/// no declaration that can hold one bare; the geometry house routes on the holder, and this house
/// follows the house that can be declared.
impl<Db> ToDatabaseComparison<Detection, Db> for DetectionFilter
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>>,
  SqlTextComparison<Label, Db>: ComplexComparison<Db>,
  SqlScalarComparison<Score, Db>: ComplexComparison<Db>,
{
  type Comparison = SqlDetectionComparison<Db>;
}

/// The crossing, and the only route into a [`SqlDetectionComparison`].
///
/// [`Infallible`], and both halves are why. The label crosses through `Label: TryFrom<Label>`, which
/// is std's reflexive blanket and cannot fail. The confidence's own refusal is
/// [`ScoreKind`](crate::ScoreKind)'s and belongs to the EXACT width rather than to this one: a
/// `ConfidenceOperand` is a value in `[0.0, 1.0]` judged on its own digits at construction, `0.0`
/// and `1.0` are exactly representable at every binary width, and rounding to nearest never crosses
/// a representable bound — so [`Score`], which is binary, holds every operand that can be built.
///
/// That arm is `expect`ed rather than folded into an error type, exactly as
/// [`SqlDetectedLanguageComparison`](crate::primitives::lang::SqlDetectedLanguageComparison)'s
/// crossing does: publishing a failure mode this crossing has not got would be a wider error than
/// the truth.
impl<Db> TryFromFilter<DetectionFilter> for SqlDetectionComparison<Db> {
  type Error = Infallible;

  fn try_from_filter(filter: DetectionFilter) -> Result<Self, Self::Error> {
    // Destructured rather than read through the getters, so a field added to the filter tomorrow is
    // an `E0027` here instead of a facet silently not crossing.
    let DetectionFilter { label, confidence } = filter;

    // A facet is OPTIONAL on the wire, and an absent one asks nothing — which is the empty filter.
    Ok(Self {
      label: SqlTextComparison::try_from_filter(label.unwrap_or_default())
        .expect("a label crosses into itself"),
      confidence: SqlScalarComparison::try_from_filter(confidence.unwrap_or_default())
        .expect("a binary width holds every confidence operand"),
    })
  }
}

/// [`LocatedDetectionFilter`](super::LocatedDetectionFilter)'s storage-side twin — the
/// classification's whole comparison, and the box's beside it.
///
/// # THREE parameters, and each is somebody else's
///
/// `T` is the geometry component's own Rust type and `C` is that component's comparison — the pair
/// [`SqlBoundingBoxComparison`] takes, carried through for its reason: a composite comparison has to
/// state the COLUMNS it spans, and a generic one needs the value's type present for its `SEGMENTS`
/// to be readable at all. `Db` is the classification half's, which every text and scalar comparison
/// in this crate carries.
///
/// That is where this kind sits between its two neighbours.
/// [`SqlBoundingBoxComparison`] has no `Db` because none of its fields holds one;
/// [`SqlTimeRangedComparison`](crate::SqlTimeRangedComparison) has one because its range half does.
/// This type holds both kinds of half, so it names both.
pub struct SqlLocatedDetectionComparison<T, C, Db> {
  detection: SqlDetectionComparison<Db>,
  bbox: SqlBoundingBoxComparison<T, C>,
}

impl<T, C, Db> SqlLocatedDetectionComparison<T, C, Db> {
  /// The empty comparison — no operator set on any of the three facets.
  #[inline]
  #[must_use]
  pub fn new() -> Self
  where
    C: Default,
  {
    Self {
      detection: SqlDetectionComparison::new(),
      bbox: SqlBoundingBoxComparison::new(),
    }
  }

  /// The classification's whole comparison — the label's column and the confidence's.
  #[inline]
  pub const fn detection(&self) -> &SqlDetectionComparison<Db> {
    &self.detection
  }

  /// The geometry's whole comparison — four columns, and every question that family asks of them.
  #[inline]
  pub const fn bbox(&self) -> &SqlBoundingBoxComparison<T, C> {
    &self.bbox
  }
}

/// The lowering: the classification at the address it was given, then the box one segment below.
///
/// **The nesting is the recursion**, and it goes both ways: everything a detection's comparison can
/// answer is answerable one level up without a line of it being restated, and the frames compose — a
/// box at `bbox` reaches `bbox_x` and its siblings, and the same comparison applied at the TOP LEVEL
/// reaches `x`.
impl<T, C, Db> ComplexComparison<Db> for SqlLocatedDetectionComparison<T, C, Db>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>>,
  SqlDetectionComparison<Db>: ComplexComparison<Db>,
  C: ComplexComparison<Db>,
{
  #[inline]
  fn conjuncts(&self) -> usize {
    ComplexComparison::<Db>::conjuncts(&self.detection)
      + ComplexComparison::<Db>::conjuncts(&self.bbox)
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: Db::Builder<'q>,
  ) -> Result<Db::Builder<'q>, Db::Error> {
    let builder = self.detection.apply(at, builder)?;
    let bbox = at.frame(BBOX);

    self.bbox.apply(bbox.at(), builder)
  }
}

/// The columns a located detection spans — [`LocatedDetection<T>`](super::LocatedDetection)'s own
/// row, read.
impl<T, C, Db> CompositeComparison<Db> for SqlLocatedDetectionComparison<T, C, Db>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>>,
  SqlDetectionComparison<Db>: ComplexComparison<Db>,
  C: ComplexComparison<Db>,
  T: ColumnKind,
{
  const SEGMENTS: &'static [crate::ColumnShape] = <LocatedDetection<T> as ColumnKind>::SEGMENTS;
}

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

impl<T, C: fmt::Debug, Db> fmt::Debug for SqlLocatedDetectionComparison<T, C, Db> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("SqlLocatedDetectionComparison")
      .field("detection", &self.detection)
      .field("bbox", &self.bbox)
      .finish()
  }
}

impl<T, C: Clone, Db> Clone for SqlLocatedDetectionComparison<T, C, Db> {
  fn clone(&self) -> Self {
    Self {
      detection: self.detection.clone(),
      bbox: self.bbox.clone(),
    }
  }
}

impl<T, C: PartialEq, Db> PartialEq for SqlLocatedDetectionComparison<T, C, Db> {
  fn eq(&self, other: &Self) -> bool {
    self.detection == other.detection && self.bbox == other.bbox
  }
}

/// **THE ROUTING ROW** for a located-detection column — reached by a
/// [`LocatedDetectionFilter`](super::LocatedDetectionFilter) over whatever filter the geometry
/// component's own family routes with.
impl<T, CF, Db> ToDatabaseComparison<LocatedDetection<T>, Db> for LocatedDetectionFilter<CF>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>>,
  SqlDetectionComparison<Db>: ComplexComparison<Db>,
  CF: ToDatabaseComparison<T, Db>,
{
  type Comparison = SqlLocatedDetectionComparison<T, CF::Comparison, Db>;
}

/// The crossing, delegating to each half's own.
///
/// The error is the GEOMETRY component's, unwrapped rather than boxed in a variant of this house's
/// own: the classification half's crossing is [`Infallible`] — see
/// [`SqlDetectionComparison`]'s row — so every refusal this crossing can produce is one the
/// component family already names, and widening it here would publish a failure mode that does not
/// exist.
impl<T, CF, C, Db> TryFromFilter<LocatedDetectionFilter<CF>>
  for SqlLocatedDetectionComparison<T, C, Db>
where
  CF: Default,
  C: TryFromFilter<CF>,
{
  type Error = C::Error;

  fn try_from_filter(filter: LocatedDetectionFilter<CF>) -> Result<Self, Self::Error> {
    let LocatedDetectionFilter { detection, bbox } = filter;

    Ok(Self {
      detection: SqlDetectionComparison::try_from_filter(detection)
        .unwrap_or_else(|never| match never {}),
      bbox: SqlBoundingBoxComparison::try_from_filter(bbox.unwrap_or_default())?,
    })
  }
}

/// [`TextDetectionFilter`](super::TextDetectionFilter)'s storage-side twin — the words' comparison,
/// the confidence's, and the region's.
///
/// The parameters are [`SqlLocatedDetectionComparison`]'s and carry its argument: `T` and `C` are
/// the geometry component's type and its comparison, `Db` is what the text and scalar halves carry.
pub struct SqlTextDetectionComparison<T, C, Db> {
  text: SqlTextComparison<Utf8Bytes, Db>,
  confidence: SqlScalarComparison<Score, Db>,
  bbox: SqlBoundingBoxComparison<T, C>,
}

impl<T, C, Db> SqlTextDetectionComparison<T, C, Db> {
  /// The empty comparison — no operator set on any of the three facets.
  #[inline]
  #[must_use]
  pub fn new() -> Self
  where
    C: Default,
  {
    Self {
      text: SqlTextComparison::new(),
      confidence: SqlScalarComparison::new(),
      bbox: SqlBoundingBoxComparison::new(),
    }
  }

  /// The twenty text operators over the recognised string's column.
  #[inline]
  pub const fn text(&self) -> &SqlTextComparison<Utf8Bytes, Db> {
    &self.text
  }

  /// The operators over the confidence column.
  #[inline]
  pub const fn confidence(&self) -> &SqlScalarComparison<Score, Db> {
    &self.confidence
  }

  /// The geometry's whole comparison — five columns, the derived area among them.
  #[inline]
  pub const fn bbox(&self) -> &SqlBoundingBoxComparison<T, C> {
    &self.bbox
  }
}

/// The lowering: one frame per facet, in segment order.
impl<T, C, Db> ComplexComparison<Db> for SqlTextDetectionComparison<T, C, Db>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>>,
  SqlTextComparison<Utf8Bytes, Db>: ComplexComparison<Db>,
  SqlScalarComparison<Score, Db>: ComplexComparison<Db>,
  C: ComplexComparison<Db>,
{
  #[inline]
  fn conjuncts(&self) -> usize {
    ComplexComparison::<Db>::conjuncts(&self.text)
      + ComplexComparison::<Db>::conjuncts(&self.confidence)
      + ComplexComparison::<Db>::conjuncts(&self.bbox)
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: Db::Builder<'q>,
  ) -> Result<Db::Builder<'q>, Db::Error> {
    let text = at.frame(TEXT);
    let builder = self.text.apply(text.at(), builder)?;
    let confidence = at.frame(CONFIDENCE);
    let builder = self.confidence.apply(confidence.at(), builder)?;
    let bbox = at.frame(BBOX);

    self.bbox.apply(bbox.at(), builder)
  }
}

/// The columns a reading spans — [`TextDetection<T>`](super::TextDetection)'s own row, read.
impl<T, C, Db> CompositeComparison<Db> for SqlTextDetectionComparison<T, C, Db>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>>,
  SqlTextComparison<Utf8Bytes, Db>: ComplexComparison<Db>,
  SqlScalarComparison<Score, Db>: ComplexComparison<Db>,
  C: ComplexComparison<Db>,
  T: ColumnKind,
{
  const SEGMENTS: &'static [crate::ColumnShape] = <TextDetection<T> as ColumnKind>::SEGMENTS;
}

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

impl<T, C: fmt::Debug, Db> fmt::Debug for SqlTextDetectionComparison<T, C, Db> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("SqlTextDetectionComparison")
      .field("text", &self.text)
      .field("confidence", &self.confidence)
      .field("bbox", &self.bbox)
      .finish()
  }
}

impl<T, C: Clone, Db> Clone for SqlTextDetectionComparison<T, C, Db> {
  fn clone(&self) -> Self {
    Self {
      text: self.text.clone(),
      confidence: self.confidence.clone(),
      bbox: self.bbox.clone(),
    }
  }
}

impl<T, C: PartialEq, Db> PartialEq for SqlTextDetectionComparison<T, C, Db> {
  fn eq(&self, other: &Self) -> bool {
    self.text == other.text && self.confidence == other.confidence && self.bbox == other.bbox
  }
}

/// **THE ROUTING ROW** for a text-detection column.
impl<T, CF, Db> ToDatabaseComparison<TextDetection<T>, Db> for TextDetectionFilter<CF>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>>,
  SqlTextComparison<Utf8Bytes, Db>: ComplexComparison<Db>,
  SqlScalarComparison<Score, Db>: ComplexComparison<Db>,
  CF: ToDatabaseComparison<T, Db>,
{
  type Comparison = SqlTextDetectionComparison<T, CF::Comparison, Db>;
}

/// The crossing, delegating to each facet's own — and the error is the GEOMETRY component's, for
/// [`SqlLocatedDetectionComparison`]'s reason: the text half crosses through std's reflexive
/// blanket and the confidence's operand is exactly representable at every binary width.
impl<T, CF, C, Db> TryFromFilter<TextDetectionFilter<CF>> for SqlTextDetectionComparison<T, C, Db>
where
  CF: Default,
  C: TryFromFilter<CF>,
{
  type Error = C::Error;

  fn try_from_filter(filter: TextDetectionFilter<CF>) -> Result<Self, Self::Error> {
    let TextDetectionFilter {
      text,
      confidence,
      bbox,
    } = filter;

    Ok(Self {
      text: SqlTextComparison::try_from_filter(text.unwrap_or_default())
        .expect("a text carrier crosses into itself"),
      confidence: SqlScalarComparison::try_from_filter(confidence.unwrap_or_default())
        .expect("a binary width holds every confidence operand"),
      bbox: SqlBoundingBoxComparison::try_from_filter(bbox.unwrap_or_default())?,
    })
  }
}

/// [`BarcodeDetectionFilter`](super::BarcodeDetectionFilter)'s storage-side twin — four comparisons,
/// and the two text-shaped ones reached through two different kinds.
///
/// The payload takes the TEXT lowering and the symbology the ENUM one, which is the filter's own
/// division rendered: `instr("f_payload", $1) > 0` beside `"f_symbology" IN ($2, $3)`. Both bind a
/// string; what differs is which questions can be asked, and that is a property of the VOCABULARY
/// rather than of the column's storage word.
pub struct SqlBarcodeDetectionComparison<T, C, Db> {
  payload: SqlTextComparison<Utf8Bytes, Db>,
  symbology: SqlEnumComparison<Symbology, Db>,
  confidence: SqlScalarComparison<Score, Db>,
  bbox: SqlBoundingBoxComparison<T, C>,
}

impl<T, C, Db> SqlBarcodeDetectionComparison<T, C, Db> {
  /// The empty comparison — no operator set on any of the four facets.
  #[inline]
  #[must_use]
  pub fn new() -> Self
  where
    C: Default,
  {
    Self {
      payload: SqlTextComparison::new(),
      symbology: SqlEnumComparison::new(),
      confidence: SqlScalarComparison::new(),
      bbox: SqlBoundingBoxComparison::new(),
    }
  }

  /// The twenty text operators over the decoded payload's column.
  #[inline]
  pub const fn payload(&self) -> &SqlTextComparison<Utf8Bytes, Db> {
    &self.payload
  }

  /// The four membership operators over the standard's column.
  #[inline]
  pub const fn symbology(&self) -> &SqlEnumComparison<Symbology, Db> {
    &self.symbology
  }

  /// The operators over the confidence column.
  #[inline]
  pub const fn confidence(&self) -> &SqlScalarComparison<Score, Db> {
    &self.confidence
  }

  /// The geometry's whole comparison.
  #[inline]
  pub const fn bbox(&self) -> &SqlBoundingBoxComparison<T, C> {
    &self.bbox
  }
}

/// The lowering: one frame per facet, in segment order.
impl<T, C, Db> ComplexComparison<Db> for SqlBarcodeDetectionComparison<T, C, Db>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>>,
  SqlTextComparison<Utf8Bytes, Db>: ComplexComparison<Db>,
  SqlEnumComparison<Symbology, Db>: ComplexComparison<Db>,
  SqlScalarComparison<Score, Db>: ComplexComparison<Db>,
  C: ComplexComparison<Db>,
{
  #[inline]
  fn conjuncts(&self) -> usize {
    ComplexComparison::<Db>::conjuncts(&self.payload)
      + ComplexComparison::<Db>::conjuncts(&self.symbology)
      + ComplexComparison::<Db>::conjuncts(&self.confidence)
      + ComplexComparison::<Db>::conjuncts(&self.bbox)
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: Db::Builder<'q>,
  ) -> Result<Db::Builder<'q>, Db::Error> {
    let payload = at.frame(PAYLOAD);
    let builder = self.payload.apply(payload.at(), builder)?;
    let symbology = at.frame(SYMBOLOGY);
    let builder = self.symbology.apply(symbology.at(), builder)?;
    let confidence = at.frame(CONFIDENCE);
    let builder = self.confidence.apply(confidence.at(), builder)?;
    let bbox = at.frame(BBOX);

    self.bbox.apply(bbox.at(), builder)
  }
}

/// The columns a decoded code spans — [`BarcodeDetection<T>`](super::BarcodeDetection)'s own row,
/// read.
impl<T, C, Db> CompositeComparison<Db> for SqlBarcodeDetectionComparison<T, C, Db>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>>,
  SqlTextComparison<Utf8Bytes, Db>: ComplexComparison<Db>,
  SqlEnumComparison<Symbology, Db>: ComplexComparison<Db>,
  SqlScalarComparison<Score, Db>: ComplexComparison<Db>,
  C: ComplexComparison<Db>,
  T: ColumnKind,
{
  const SEGMENTS: &'static [crate::ColumnShape] = <BarcodeDetection<T> as ColumnKind>::SEGMENTS;
}

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

impl<T, C: fmt::Debug, Db> fmt::Debug for SqlBarcodeDetectionComparison<T, C, Db> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("SqlBarcodeDetectionComparison")
      .field("payload", &self.payload)
      .field("symbology", &self.symbology)
      .field("confidence", &self.confidence)
      .field("bbox", &self.bbox)
      .finish()
  }
}

impl<T, C: Clone, Db> Clone for SqlBarcodeDetectionComparison<T, C, Db> {
  fn clone(&self) -> Self {
    Self {
      payload: self.payload.clone(),
      symbology: self.symbology.clone(),
      confidence: self.confidence.clone(),
      bbox: self.bbox.clone(),
    }
  }
}

impl<T, C: PartialEq, Db> PartialEq for SqlBarcodeDetectionComparison<T, C, Db> {
  fn eq(&self, other: &Self) -> bool {
    self.payload == other.payload
      && self.symbology == other.symbology
      && self.confidence == other.confidence
      && self.bbox == other.bbox
  }
}

/// **THE ROUTING ROW** for a barcode-detection column.
impl<T, CF, Db> ToDatabaseComparison<BarcodeDetection<T>, Db> for BarcodeDetectionFilter<CF>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>>,
  SqlTextComparison<Utf8Bytes, Db>: ComplexComparison<Db>,
  SqlEnumComparison<Symbology, Db>: ComplexComparison<Db>,
  SqlScalarComparison<Score, Db>: ComplexComparison<Db>,
  CF: ToDatabaseComparison<T, Db>,
{
  type Comparison = SqlBarcodeDetectionComparison<T, CF::Comparison, Db>;
}

/// The crossing, delegating to each facet's own.
///
/// The symbology's is [`Infallible`] too, and the reason is that vocabulary's openness: every word
/// names a symbology, so the crossing has nothing to refuse. That is the one place this house's two
/// text-shaped facets agree.
impl<T, CF, C, Db> TryFromFilter<BarcodeDetectionFilter<CF>>
  for SqlBarcodeDetectionComparison<T, C, Db>
where
  CF: Default,
  C: TryFromFilter<CF>,
{
  type Error = C::Error;

  fn try_from_filter(filter: BarcodeDetectionFilter<CF>) -> Result<Self, Self::Error> {
    let BarcodeDetectionFilter {
      payload,
      symbology,
      confidence,
      bbox,
    } = filter;

    Ok(Self {
      payload: SqlTextComparison::try_from_filter(payload.unwrap_or_default())
        .expect("a text carrier crosses into itself"),
      symbology: SqlEnumComparison::try_from_filter(symbology.unwrap_or_default())
        .expect("a symbology crosses into itself"),
      confidence: SqlScalarComparison::try_from_filter(confidence.unwrap_or_default())
        .expect("a binary width holds every confidence operand"),
      bbox: SqlBoundingBoxComparison::try_from_filter(bbox.unwrap_or_default())?,
    })
  }
}

/// [`DocumentSegmentFilter`](super::DocumentSegmentFilter)'s storage-side twin — the quad's whole
/// comparison and the confidence's.
///
/// It carries the deepest frame stack in the crate: a segment at `page` frames `quad`, the quad
/// frames a CORNER, and the corner frames a component — three descents to `page_quad_top_left_x`.
/// Nothing here knows that; each level pushes one frame and lets the level below render, which is
/// the recursion the geometry house's own comparisons are built on.
pub struct SqlDocumentSegmentComparison<T, C, Db> {
  quad: crate::SqlQuadComparison<T, C>,
  confidence: SqlScalarComparison<Score, Db>,
}

impl<T, C, Db> SqlDocumentSegmentComparison<T, C, Db> {
  /// The empty comparison — no operator set on either facet.
  #[inline]
  #[must_use]
  pub fn new() -> Self
  where
    C: Default,
  {
    Self {
      quad: crate::SqlQuadComparison::new(),
      confidence: SqlScalarComparison::new(),
    }
  }

  /// The four corners' whole comparison.
  #[inline]
  pub const fn quad(&self) -> &crate::SqlQuadComparison<T, C> {
    &self.quad
  }

  /// The operators over the confidence column.
  #[inline]
  pub const fn confidence(&self) -> &SqlScalarComparison<Score, Db> {
    &self.confidence
  }
}

/// The lowering: the quad one segment below, then the confidence at this level.
impl<T, C, Db> ComplexComparison<Db> for SqlDocumentSegmentComparison<T, C, Db>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>>,
  SqlScalarComparison<Score, Db>: ComplexComparison<Db>,
  C: ComplexComparison<Db>,
{
  #[inline]
  fn conjuncts(&self) -> usize {
    ComplexComparison::<Db>::conjuncts(&self.quad)
      + ComplexComparison::<Db>::conjuncts(&self.confidence)
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: Db::Builder<'q>,
  ) -> Result<Db::Builder<'q>, Db::Error> {
    let quad = at.frame(QUAD);
    let builder = self.quad.apply(quad.at(), builder)?;
    let confidence = at.frame(CONFIDENCE);

    self.confidence.apply(confidence.at(), builder)
  }
}

/// The columns a segment spans — [`DocumentSegment<T>`](super::DocumentSegment)'s own row, read.
impl<T, C, Db> CompositeComparison<Db> for SqlDocumentSegmentComparison<T, C, Db>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>>,
  SqlScalarComparison<Score, Db>: ComplexComparison<Db>,
  C: ComplexComparison<Db>,
  T: ColumnKind,
{
  const SEGMENTS: &'static [crate::ColumnShape] = <DocumentSegment<T> as ColumnKind>::SEGMENTS;
}

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

impl<T, C: fmt::Debug, Db> fmt::Debug for SqlDocumentSegmentComparison<T, C, Db> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("SqlDocumentSegmentComparison")
      .field("quad", &self.quad)
      .field("confidence", &self.confidence)
      .finish()
  }
}

impl<T, C: Clone, Db> Clone for SqlDocumentSegmentComparison<T, C, Db> {
  fn clone(&self) -> Self {
    Self {
      quad: self.quad.clone(),
      confidence: self.confidence.clone(),
    }
  }
}

impl<T, C: PartialEq, Db> PartialEq for SqlDocumentSegmentComparison<T, C, Db> {
  fn eq(&self, other: &Self) -> bool {
    self.quad == other.quad && self.confidence == other.confidence
  }
}

/// **THE ROUTING ROW** for a document-segment column.
impl<T, CF, Db> ToDatabaseComparison<DocumentSegment<T>, Db> for DocumentSegmentFilter<CF>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>>,
  SqlScalarComparison<Score, Db>: ComplexComparison<Db>,
  CF: ToDatabaseComparison<T, Db>,
{
  type Comparison = SqlDocumentSegmentComparison<T, CF::Comparison, Db>;
}

/// The crossing, delegating to each facet's own.
impl<T, CF, C, Db> TryFromFilter<DocumentSegmentFilter<CF>>
  for SqlDocumentSegmentComparison<T, C, Db>
where
  CF: Default,
  C: TryFromFilter<CF>,
{
  type Error = C::Error;

  fn try_from_filter(filter: DocumentSegmentFilter<CF>) -> Result<Self, Self::Error> {
    let DocumentSegmentFilter { quad, confidence } = filter;

    Ok(Self {
      quad: crate::SqlQuadComparison::try_from_filter(quad.unwrap_or_default())?,
      confidence: SqlScalarComparison::try_from_filter(confidence.unwrap_or_default())
        .expect("a binary width holds every confidence operand"),
    })
  }
}