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
//! The relation kinds: [`SqlRefComparison`] for a predicate reached THROUGH a foreign key, and
//! [`SqlDerivedComparison`] for the reverse position that has none.
//!
//! # The two arities, and why they are two types
//!
//! A `ref` field carries the target's id, so a forward relation is a MEMBERSHIP over one column:
//! `fk IN ( SELECT id FROM target WHERE … )`, at most one matching row by the id's uniqueness. The
//! reverse position — the rows whose own `ref` points back here — has no column on this row at all,
//! so it is a QUANTIFIER over a correlated subquery: some child, every child, no child, how many.
//!
//! One kind with a marker would have to carry both a foreign key it sometimes has and a quantifier
//! set that sometimes means nothing. They are two questions with two operator sets, which is the
//! same argument that makes a sequence and a set two kinds under [`edge`](super::edge).
//!
//! # Every nested scope is ALIASED, and a self-relation is why
//!
//! A subquery here selects from a table and joins back to the row outside it, so the two sides have
//! to be tellable apart. Naming each by its TABLE does that exactly while the tables differ — and a
//! record that refers to its own kind breaks it silently: `scene.parent_id` naming a `scene` gave
//! `"scene"."parent_id" = "scene"."id"`, both halves resolving to the inner scope, every quantifier
//! quietly answering *is any row its own parent*. It renders, it binds, it runs, and it returns the
//! wrong rows.
//!
//! So the inner `FROM` takes an ALIAS — `FROM "scene" "__ig_scene_1__"` — and everything inside
//! refers to the row by that name while the outer row keeps whatever ITS scope calls it. The names
//! are minted at expansion and indexed by NESTING DEPTH, which [`At::depth`] carries and
//! [`RelatedRow`] resolves; depth ZERO wears none, the statement's own `FROM` naming the real table.
//! Past the last minted name the lowering answers [`SqlLoweringError::RelationDepth`] rather than
//! reusing one, reuse being the same silent class over again.
//!
//! # What is CALLER-SUPPLIED, and why it is held rather than handed at `apply`
//!
//! Both kinds hold a [`RelatedRow`] naming the row the subquery selects FROM — the target for a
//! forward reference, the source for a reverse one — and the reverse kind holds one column name
//! beside it: the child's own column that carries this row's id.
//!
//! That is a departure from every other kind here, and it is deliberate. The address arriving
//! through [`At`] is the row the predicate CONSTRAINS, which is the caller's per-application choice;
//! the address held is the row the relation POINTS AT, which is part of the question. `cover: { …
//! }` is meaningless without knowing which table `cover` names, so a comparison that did not carry
//! it would not be a relation predicate. [`ComplexComparison::apply`] has no second channel in any
//! case — its parameters are the address and the builder — so a lowering that needs a second row
//! holds it.
//!
//! It replaces `legacy/ingraph`'s registry, whose `resolve_child` picked the unique registered
//! schema containing every column the related query referenced — a subset match that could silently
//! resolve a BROADER schema in place of a missing child, and the sole source of its
//! `AmbiguousRelation`. A caller that names its target cannot be ambiguous.
//!
//! Inside it the carrier is [`RecordAddress`] rather than a table-and-column pair of its own, and
//! the reason is stronger than *it holds the right two things*: the nested comparison is a
//! comparison over the TARGET's row, so it is applied at [`At::nested`] of that row — and a nested
//! predicate that is itself correlated (a collection under an edge table, a relation one level
//! further out) reads the target's own table and key columns from there. A pair carrying only what
//! the semi-join projects would render the outer statement and then have nothing to hand the inner
//! one.
//!
//! # Both refuse a WIDE address, and refuse it before anything is written
//!
//! A relation joins one column to one column: a `ref` field is one column carrying
//! `<Target as Identifiable>::Id`, and an id is one column because every table's id is unique. So a
//! row addressed by several columns has no single name for either side of the join, and both kinds
//! answer [`SqlLoweringError::RelationWidth`] rather than rendering — the forward kind about its
//! TARGET, whose id the subquery projects, and the reverse kind about the PARENT, whose id the
//! correlation compares against.
//!
//! The refusal is raised before either kind opens a conjunct, 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.

use core::{fmt::Display, marker::PhantomData};

use smol_bytes::Utf8BytesMut;

use super::{
  Carrier, QuoteIdent, RelationDepthError, RelationWidthError, SqlConjunction, SqlCountComparison,
  SqlLoweringError,
  dialect::{push_quoted_ident, push_quoted_scope},
  push_column, push_count_slots,
};
use crate::{
  FieldName,
  comparison::{At, Backend, CollapsibleComparison, ComplexComparison, RecordAddress},
};

/// The row on the far side of a relation, and every name a nested scope may call it by.
///
/// # Two facts about ONE row, so they arrive as one value
///
/// A relation subquery needs both: the [`RecordAddress`] says which table to select from and which
/// column to join on, and the alias table says what to CALL that table inside the statement. Passed
/// as two arguments they could be about two different rows — an address for `keyframe` beside the
/// aliases minted for `shot` renders perfectly well and correlates the wrong two tables — and no
/// layer below could tell. [`of`](Self::of) is what closes that: both halves come off ONE row type's
/// [`SqlQuery`](crate::query::sql::SqlQuery) binding, so there is nothing to mismatch.
///
/// # Why the aliases are not on the address itself
///
/// [`RecordAddress::table`] has a second reader — [`edge_table`](super::edge_table) DERIVES a
/// dependent table's name from it — so the row's identity and the row's scope names are answers to
/// different questions. See the address's own note.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct RelatedRow {
  address: RecordAddress,
  aliases: &'static [&'static str],
}

impl RelatedRow {
  /// The row `Row` stores, with the aliases its expansion minted — both read off one binding, which
  /// is what makes them impossible to mismatch.
  ///
  /// This is what an emitted relation position writes. It is also what a hand-written one should:
  /// the alternative spells an address and an alias table beside each other and asks a reader to
  /// check they are about the same table.
  #[inline]
  #[must_use]
  pub const fn of<Row, Db>() -> Self
  where
    Row: crate::query::sql::SqlQuery<Db>,
    Db: Backend + sqlx::Database,
  {
    Self {
      address: Row::ADDRESS,
      aliases: Row::ALIASES,
    }
  }

  /// The same pair stated directly, for a caller with no row type to read them off.
  #[inline]
  #[must_use]
  pub const fn new(address: RecordAddress, aliases: &'static [&'static str]) -> Self {
    Self { address, aliases }
  }

  /// Which row this is.
  #[inline]
  #[must_use]
  pub const fn address(&self) -> &RecordAddress {
    &self.address
  }

  /// What a scope one level inside `enclosing` calls this row.
  ///
  /// # Errors
  ///
  /// [`SqlLoweringError::RelationDepth`] past the last alias minted. Reusing one instead is the
  /// silent case this whole mechanism exists to close: SQL resolves a reference to the innermost
  /// scope that has a match, so a repeated alias correlates the wrong two rows and the statement
  /// still answers.
  fn scope(&self, enclosing: usize) -> Result<&'static str, SqlLoweringError> {
    let depth = enclosing + 1;
    match self.aliases.get(depth) {
      Some(alias) => Ok(alias),
      None => Err(SqlLoweringError::RelationDepth(RelationDepthError::new(
        self.address.table(),
        depth,
        self.aliases.len(),
      ))),
    }
  }

  /// `<table> <alias>` — the row source a nested scope over this row opens its `FROM` with,
  /// bracketed for the dialect.
  ///
  /// The TABLE is the real one and the ALIAS is what everything inside refers to it by. Both halves
  /// come from here so that a `FROM` and the correlation beside it cannot disagree about either.
  fn row_source<Db: QuoteIdent>(&self, alias: &str) -> Utf8BytesMut {
    let mut item = Utf8BytesMut::new();
    push_quoted_ident::<Db>(self.address.table(), &mut item);
    item.push(' ');
    push_quoted_ident::<Db>(FieldName::new(alias), &mut item);
    item
  }
}

/// A predicate over the row a `ref` field POINTS AT, lowered as a semi-join through the foreign key.
///
/// ```text
/// "cover_id" IN ( SELECT "__ig_keyframe_1__"."id" FROM "keyframe" "__ig_keyframe_1__"
///                  WHERE "title" = ? )
/// ```
///
/// # It holds the nested comparison BARE, not behind an `Option`
///
/// An absent nested predicate and an empty one ask the same question — *nothing* — and both lower
/// to no conjunct at all. `legacy/ingraph` held an `Option` because its wire filter did and gave the
/// two states one behaviour; a second state with no second meaning is one a caller can reason
/// wrongly about, so the emptiness is the nested comparison's own
/// [`is_empty`](ComplexComparison::is_empty) and there is no wrapper to unwrap.
///
/// That is also what a degenerate `fk IN ( SELECT id FROM target )` would have been: not *nothing*
/// but *this reference is live* — a question about the foreign key's nullability wearing a
/// relation's clothes.
///
/// # The nested comparison must be COLLAPSIBLE, which is the optimisation being on by default
///
/// The bound is [`CollapsibleComparison`] rather than [`ComplexComparison`], so every target
/// comparison answers whether the predicate constrains its id alone — and when it does, this kind
/// renders that constraint on the FOREIGN KEY and no subquery at all. A target that declines simply
/// answers `None` and pays for one, which is what the seam's default would have been; making it a
/// bound is what keeps a target from being silently un-collapsible by forgetting the impl.
///
/// # No inherent conjunct count
///
/// Every other kind here carries one, and this one cannot: its count depends on whether the nested
/// predicate collapses, which is a capability of `C` that an inherent method has no bound to ask
/// for. [`ComplexComparison::conjuncts`] is the only place the question is answerable, so it is the
/// only place it is answered.
pub struct SqlRefComparison<C, Db> {
  target: RelatedRow,
  nested: C,
  // `fn() -> Db` rather than a bare parameter, for the reason `comparison_kind!` writes the same
  // marker: the dialect must not contribute an auto-trait or variance obligation. This kind needs
  // the marker where the reverse one does not — nothing else here names `Db`.
  db: PhantomData<fn() -> Db>,
}

impl<C, Db> SqlRefComparison<C, Db> {
  /// A predicate over `target`'s row, reached through the foreign key this comparison is applied at.
  #[inline]
  pub const fn new(target: RelatedRow, nested: C) -> Self {
    Self {
      target,
      nested,
      db: PhantomData,
    }
  }

  /// The row this reference points at — the table the subquery selects from, the id column it
  /// projects, and the names it wears one level in.
  #[inline]
  pub const fn target(&self) -> &RelatedRow {
    &self.target
  }

  /// The predicate asked of that row.
  #[inline]
  pub const fn nested(&self) -> &C {
    &self.nested
  }
}

/// A predicate over the rows whose own `ref` field points BACK at this one, asked through the four
/// quantifiers a collection is asked through.
///
/// ```text
/// any    EXISTS (SELECT 1 FROM "track" "__ig_track_1__"
///                 WHERE "__ig_track_1__"."video_id" = "video"."id" AND …)
/// none   NOT EXISTS (…)
/// all    NOT EXISTS (… AND NOT ( … ))
/// count  (SELECT COUNT(*) FROM "track" "__ig_track_1__"
///          WHERE "__ig_track_1__"."video_id" = "video"."id") > ?
/// ```
///
/// # The vocabulary is the COLLECTION's, verbatim
///
/// `any` / `all` / `none` / `count` — one word, one meaning, whether the members are a column's
/// elements or another table's rows. What differs is the SCOPE each opens, which is this kind's
/// business and not the vocabulary's.
///
/// # `all` over a row with NO children is TRUE
///
/// A decision rather than an accident of the rendering, and the rendering is chosen to match it:
/// *every child satisfies P* over an empty set is vacuously true, so a parent with no children
/// passes every `all`. See [`push_all`] for the form and for what it does with SQL's third truth
/// value.
///
/// # It names no column of this row, so the applied PATH goes unread
///
/// A derived position is not stored anywhere — the only columns it touches are the child's foreign
/// key and this row's id, and both are known without it. That is the opposite of
/// [`SqlEdgeComparison`](super::SqlEdgeComparison), which derives its edge table FROM the path and
/// refuses the empty one; this kind reads [`At::record`] and nothing else, so the same comparison
/// renders identically wherever a caller frames it.
///
/// # `Db` needs no marker here
///
/// The cardinality slot is a [`SqlCountComparison<i64, Db>`](SqlCountComparison), so the parameter
/// is genuinely used and a `PhantomData` beside it would be a second statement of the same fact.
pub struct SqlDerivedComparison<C, Db> {
  source: RelatedRow,
  points_back: &'static FieldName,
  any: Option<C>,
  all: Option<C>,
  none: Option<C>,
  count: Option<SqlCountComparison<i64, Db>>,
}

impl<C, Db> SqlDerivedComparison<C, Db> {
  /// The rows of `source` whose `points_back` column carries this row's id — with no quantifier
  /// asked yet.
  ///
  /// `points_back` is the column of `source` that carries this row's id, **in the name THIS DATABASE
  /// stores it under** — which is what [`stored_column`](crate::stored_column) answers when it is
  /// asked with the declared name a reverse position wrote. WHICH field is asked for is
  /// [`Related::COLUMNS`](crate::Related::COLUMNS)' business, since a source may refer to this
  /// record through more than one; what that field is CALLED here is the row's.
  #[inline]
  pub const fn new(source: RelatedRow, points_back: &'static FieldName) -> Self {
    Self {
      source,
      points_back,
      any: None,
      all: None,
      none: None,
      count: None,
    }
  }

  /// Ask whether SOME of those rows satisfy `nested`.
  #[inline]
  #[must_use]
  pub fn with_any(mut self, nested: C) -> Self {
    self.any = Some(nested);
    self
  }

  /// Ask whether EVERY one of them does — vacuously true where there are none.
  #[inline]
  #[must_use]
  pub fn with_all(mut self, nested: C) -> Self {
    self.all = Some(nested);
    self
  }

  /// Ask whether NONE of them does.
  #[inline]
  #[must_use]
  pub fn with_none(mut self, nested: C) -> Self {
    self.none = Some(nested);
    self
  }

  /// Ask HOW MANY there are — the cardinality of the whole position, which no nested predicate
  /// narrows, exactly as a collection's `count` counts its elements rather than its matches.
  #[inline]
  #[must_use]
  pub fn with_count(mut self, count: SqlCountComparison<i64, Db>) -> Self {
    self.count = Some(count);
    self
  }

  /// The row the position gathers, and the column of it that carries this row's id.
  #[inline]
  pub const fn source(&self) -> (&RelatedRow, &'static FieldName) {
    (&self.source, self.points_back)
  }

  /// The predicate SOME of those rows must satisfy, or `None` while the quantifier is absent.
  #[inline]
  pub const fn any(&self) -> Option<&C> {
    self.any.as_ref()
  }

  /// The predicate EVERY one of them must satisfy.
  #[inline]
  pub const fn all(&self) -> Option<&C> {
    self.all.as_ref()
  }

  /// The predicate NONE of them may satisfy.
  #[inline]
  pub const fn none(&self) -> Option<&C> {
    self.none.as_ref()
  }

  /// The comparison the position's cardinality is asked under.
  #[inline]
  pub const fn count(&self) -> Option<&SqlCountComparison<i64, Db>> {
    self.count.as_ref()
  }

  /// How many conjuncts this comparison lowers to.
  ///
  /// A present quantifier counts ONCE however much the predicate inside it holds, because those
  /// conjuncts land inside a scope that is itself one conjunct — including where the predicate is
  /// empty, which is the quantifier asked of the position itself. A present cardinality counts what
  /// IT counts, its operators landing beside these rather than inside them. Both readings are
  /// [`comparison_kind!`](super)'s own, over the same two slot shapes.
  #[inline]
  pub const fn conjuncts(&self) -> usize {
    (self.any.is_some() as usize)
      + (self.all.is_some() as usize)
      + (self.none.is_some() as usize)
      + match &self.count {
        Some(count) => count.conjuncts(),
        None => 0,
      }
  }

  /// True while no quantifier is asked, so a lowering would emit nothing.
  #[inline]
  pub const fn is_empty(&self) -> bool {
    self.conjuncts() == 0
  }
}

/// Written out rather than derived, for the reason `comparison_kind!` writes its three: a derive
/// would bound `Db`, which is a marker neither kind's values carry.
impl<C: core::fmt::Debug, Db> core::fmt::Debug for SqlRefComparison<C, Db> {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("SqlRefComparison")
      .field("target", &self.target)
      .field("nested", &self.nested)
      .finish()
  }
}

impl<C: Clone, Db> Clone for SqlRefComparison<C, Db> {
  fn clone(&self) -> Self {
    Self {
      target: self.target,
      nested: self.nested.clone(),
      db: PhantomData,
    }
  }
}

impl<C: PartialEq, Db> PartialEq for SqlRefComparison<C, Db> {
  fn eq(&self, other: &Self) -> bool {
    self.target == other.target && self.nested == other.nested
  }
}

impl<C: core::fmt::Debug, Db> core::fmt::Debug for SqlDerivedComparison<C, Db> {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("SqlDerivedComparison")
      .field("source", &self.source)
      .field("points_back", &self.points_back)
      .field("any", &self.any)
      .field("all", &self.all)
      .field("none", &self.none)
      .field("count", &self.count)
      .finish()
  }
}

impl<C: Clone, Db> Clone for SqlDerivedComparison<C, Db> {
  fn clone(&self) -> Self {
    Self {
      source: self.source,
      points_back: self.points_back,
      any: self.any.clone(),
      all: self.all.clone(),
      none: self.none.clone(),
      count: self.count.clone(),
    }
  }
}

impl<C: PartialEq, Db> PartialEq for SqlDerivedComparison<C, Db> {
  fn eq(&self, other: &Self) -> bool {
    self.source == other.source
      && self.points_back == other.points_back
      && self.any == other.any
      && self.all == other.all
      && self.none == other.none
      && self.count == other.count
  }
}

/// ONE impl for every dialect. `fk IN ( SELECT id FROM t WHERE … )` parses and answers the same
/// question in all three, and the whole bound is what the nested comparison itself asks for — the
/// arrangement [`SqlEdgeComparison`](super::SqlEdgeComparison) has, for the same reason.
///
/// The refusal is PINNED to [`SqlLoweringError`], as the correlated kinds' is: this impl has a no of
/// its own to give, and an unconstrained `Db::Error` is a projection it could not build a value of.
impl<C, Db> ComplexComparison<Db> for SqlRefComparison<C, Db>
where
  Db: sqlx::Database
    + QuoteIdent
    + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
  C: CollapsibleComparison<Db>,
{
  fn conjuncts(&self) -> usize {
    match self.nested.only_id() {
      // The collapsed form is the id's OWN conjuncts, not one: `{ id: { gt: 3, lt: 9 } }` lands on
      // the foreign key as two predicates at this level, where the subquery would have held both
      // inside one.
      Some(id) => id.conjuncts(),
      None => usize::from(!self.nested.is_empty()),
    }
  }

  /// # The subquery renders NO `ORDER BY` and NO `LIMIT`, deliberately
  ///
  /// `fk IN (SELECT id FROM target WHERE … ORDER BY … LIMIT n)` limits GLOBALLY rather than per
  /// parent, so what it expresses is *the parents of the globally-first N matching targets* —
  /// order-dependent global membership, which is not a relational predicate anybody means. The thing
  /// an author does mean there is the top N children PER PARENT, which needs a lateral join or a
  /// window function and is a different construct this seam never had.
  ///
  /// A ceiling here could not be a resource lever either: it would change the ANSWER, dropping
  /// parents that qualify. The outer statement's own `LIMIT` is the PAGE's and is unaffected.
  ///
  /// # A refusal from INSIDE leaves the accumulator mid-predicate
  ///
  /// The nested comparison may refuse, and by then `fk IN ( SELECT id FROM target` is written.
  /// Unlike the width refusal, which is raised before anything is pushed, this one cannot be: what
  /// declines is a comparison this method does not read. A refused statement is discarded whole by
  /// its caller, so the buffer's contents at that point are never executed — the same reading
  /// [`push_element_scope`](super::push_element_scope) states.
  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: Db::Builder<'q>,
  ) -> Result<Db::Builder<'q>, Db::Error> {
    // Before anything is written, and whichever branch follows: the width is the RELATION's fact.
    let id = one_column(self.target.address())?;
    if let Some(collapsed) = self.nested.only_id() {
      // The whole optimisation: the target's constraint on its own id, rendered at the FOREIGN
      // KEY's address instead. Every operator, every bind and every bracket is the id comparison's
      // own, so there is no second spelling of the collapsed predicate to keep in step. No alias is
      // taken, because no subquery is opened — the collapsed form stays at THIS depth.
      return collapsed.apply(at, builder);
    }
    if self.nested.is_empty() {
      return Ok(builder);
    }
    // The scope's own name, resolved before anything is written, for the reason the width is: a
    // ceiling reached is a fact about the RELATION and not about the predicate inside it.
    let scope = self.target.scope(at.depth())?;
    let from = self.target.row_source::<Db>(scope);
    let mut inner = builder
      .sub_select_with(|qb| push_column(qb, at))
      .push_field_with(|qb| {
        // QUALIFIED by the alias, though one table is in scope and a bare name would resolve to it.
        // The projection and the correlation below then read the same way, which is what keeps a
        // reader from having to work out which of them the aliasing reached.
        // A local buffer rather than `Db::buffer()`: this kind's bound says its buffer merely
        // DISPLAYS, where the reverse kind pins it to `Utf8BytesMut`. What is assembled here is one
        // qualified name and never reaches the backend as a buffer, so it needs neither.
        let mut projected = Utf8BytesMut::new();
        push_quoted_scope::<Db>(scope, id, &mut projected);
        qb.push(projected.as_str());
      })
      .from(from.as_str())
      .begin_where();
    {
      // The target's own top level, ONE LEVEL IN and under the name this `FROM` just gave it: the
      // nested comparison frames its columns below this, and a nested CORRELATED comparison reads
      // the target's table, its keys and its scope name off it.
      let nested = SqlConjunction::new(inner.inner_mut());
      self
        .nested
        .apply(At::nested(self.target.address(), at.depth(), scope), nested)?;
    }
    Ok(inner.finalize())
  }
}

/// **The SQL family's answer to the FORWARD position's crossing map**: a `ref` column's widened
/// filter becomes an OPTIONAL semi-join through the reference.
///
/// # Optional, because *nothing was asked* has no value to be
///
/// The reverse kind carries four `Option` slots of its own, so an unasked position is a bare one.
/// This kind holds the far side's comparison BARE — there is no quantifier layer — and an emitted
/// comparison has no `Default` to fill it with, so the absence is the [`Option`] and
/// `ComplexComparison for Option<C>` is what lowers it to nothing.
///
/// # It asks NOTHING of `C`, and that is what keeps a MUTUAL relation compilable
///
/// The kind's own lowering wants a [`CollapsibleComparison`] — it asks the nested predicate whether
/// it constrains the target's id alone, and renders that constraint on the FOREIGN KEY when it does
/// — and this row used to restate that bound to keep the map's item bound. Restated HERE it becomes
/// a demand on the NEIGHBOUR made wherever the projection is named, which on the ordinary pair (a
/// `ref` one way, a `derived` the other) closes into the measured `E0275`
/// [`ToRelatedComparison`](crate::ToRelatedComparison)'s note records.
///
/// The bound stays where it always was, on the kind's [`ComplexComparison`] impl below and on the
/// [`ToLoweredRelatedComparison`](crate::comparison::ToLoweredRelatedComparison) row beside this
/// one. A target whose comparison cannot collapse is still `E0277` — at the record's own lowering,
/// where the member is applied, rather than at every mention of the type that holds it.
impl<F, R, C, Db: sqlx::Database + Backend> crate::ToRelatedComparison<C, Db>
  for crate::RefFilter<F, R>
{
  type Comparison = Option<SqlRefComparison<C, Db>>;
}

/// The LOWERING of a forward position, reached through the widened filter rather than through the
/// comparison's own type.
///
/// The clause is this kind's, restated where it is spent: `C: CollapsibleComparison<Db>` because the
/// semi-join asks the far side whether it collapses, and the dialect predicates because the rendering
/// threads a [`SqlConjunction`]. Proven where a record's own lowering is proven — at a concrete
/// dialect — which is what keeps the neighbour's demand off every naming of the comparison type.
impl<F, R, C, Db> crate::comparison::ToLoweredRelatedComparison<C, Db> for crate::RefFilter<F, R>
where
  Db: sqlx::Database
    + QuoteIdent
    + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
  C: CollapsibleComparison<Db>,
{
  #[inline]
  fn conjuncts(comparison: &Self::Comparison) -> usize {
    ComplexComparison::<Db>::conjuncts(comparison)
  }

  #[inline]
  fn apply<'q>(
    comparison: &'q Self::Comparison,
    at: At<'_>,
    builder: Db::Builder<'q>,
  ) -> Result<Db::Builder<'q>, Db::Error> {
    ComplexComparison::<Db>::apply(comparison, at, builder)
  }
}

/// **The SQL family's answer to the reverse position's crossing map**: a wire quantifier over `F`
/// becomes this kind, holding whatever the far side's own filter crossed into.
///
/// # The clause is the COHERENCE bound and nothing else
///
/// It used to be this kind's own lowering, restated, because the map promised
/// [`ComplexComparison`] of what it names and a row had to prove it. The map promises nothing now —
/// see [`ToRelatedComparison`](crate::ToRelatedComparison) for the cycle that promise closed — so
/// this row asks nothing of `C` and nothing of `Db` beyond what tells the two families apart. The
/// lowering's own clause, `i64: Carrier<Db>` included, is on the [`ComplexComparison`] impl below and
/// on the [`ToLoweredRelatedComparison`](crate::comparison::ToLoweredRelatedComparison) row beside
/// this one.
///
/// `Db: sqlx::Database` leads for the coherence reason the scalar kind's own crossing states: without
/// it this row and MongoDB's would overlap, [`Backend`] being a trait a local `Mongo` implements.
///
/// The SELF type is the WIRE FILTER rather than the far side's comparison, which is what keeps the
/// map keyed the way every other crossing here is: a filter kind is what carries the question.
impl<F, C, Db: sqlx::Database + Backend> crate::ToRelatedComparison<C, Db>
  for crate::RelatedFilter<F>
{
  type Comparison = SqlDerivedComparison<C, Db>;
}

/// The LOWERING of a reverse position, reached through the quantifier vocabulary rather than through
/// the comparison's own type — the forward row's twin, over this kind's own clause.
impl<F, C, Db> crate::comparison::ToLoweredRelatedComparison<C, Db> for crate::RelatedFilter<F>
where
  Db: sqlx::Database
    + QuoteIdent
    + for<'q> Backend<
      Builder<'q> = SqlConjunction<'q, Db>,
      Error = SqlLoweringError,
      Buffer = Utf8BytesMut,
    >,
  C: ComplexComparison<Db>,
  i64: Carrier<Db>,
{
  #[inline]
  fn conjuncts(comparison: &Self::Comparison) -> usize {
    ComplexComparison::<Db>::conjuncts(comparison)
  }

  #[inline]
  fn apply<'q>(
    comparison: &'q Self::Comparison,
    at: At<'_>,
    builder: Db::Builder<'q>,
  ) -> Result<Db::Builder<'q>, Db::Error> {
    ComplexComparison::<Db>::apply(comparison, at, builder)
  }
}

/// ONE impl for every dialect, for the reason above. `i64: Carrier<Db>` is the cardinality slot's,
/// which binds one integer per operator whatever the position holds.
impl<C, Db> ComplexComparison<Db> for SqlDerivedComparison<C, Db>
where
  Db: sqlx::Database
    + QuoteIdent
    + for<'q> Backend<
      Builder<'q> = SqlConjunction<'q, Db>,
      Error = SqlLoweringError,
      Buffer = Utf8BytesMut,
    >,
  C: ComplexComparison<Db>,
  i64: Carrier<Db>,
{
  #[inline]
  fn conjuncts(&self) -> usize {
    Self::conjuncts(self)
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    mut builder: Db::Builder<'q>,
  ) -> Result<Db::Builder<'q>, Db::Error> {
    let alias = self.source.scope(at.depth())?;
    let scope = Correlation::new::<Db>(at, &self.source, self.points_back, alias)?;
    // The address every quantifier's nested predicate is applied at: the SOURCE's row, one level in,
    // under the name this correlation just gave it. Built once, because the three quantifiers open
    // three scopes of the same shape at the same depth.
    let inner = At::nested(self.source.address(), at.depth(), alias);
    push_quantifiers(self, &scope, inner, &mut builder)?;
    push_related_count(self.count.as_ref(), &scope, &mut builder);
    Ok(builder)
  }
}

/// The two names every reverse predicate renders, bracketed ONCE for the several places each of them
/// appears.
///
/// It is all TEXT and no operand: an identifier cannot be bound, so the correlation — two qualified
/// names and the ` = ` between them — is built once here and pushed as a unit by each form below.
/// Both come out of one buffer, which [`Utf8BytesMut::split`] hands off in pieces, so a position
/// asked three quantifiers renders its names once rather than three times. That is
/// [`Scope`](super::edge)'s arrangement, over two names where it has three.
struct Correlation {
  /// `<source table> <alias>` — the `FROM` item each quantifier opens with.
  table: Utf8BytesMut,
  /// `<alias>."points_back" = <parent scope>."id"`.
  correlation: Utf8BytesMut,
}

impl Correlation {
  /// Derive the addressing every form shares from where the predicate is applied and what the
  /// position holds.
  ///
  /// # The two sides are QUALIFIED, and that is the assertion the whole shape rests on
  ///
  /// The source and the parent may carry columns of the same name — a child's own `id` beside its
  /// parent's is the ordinary case — and SQL resolves an unqualified name to the innermost scope. An
  /// unqualified correlation would compare the child's column to itself, hold for every row of the
  /// child table, and turn every quantifier into a question about the WHOLE table. It renders, it
  /// binds the same operands, and it returns rows nobody asked for.
  ///
  /// # Qualifying by NAME was not enough, and the self-relation is why
  ///
  /// Both sides used to be qualified by their TABLES, which is correct exactly while the two tables
  /// are different. Where a record refers to its own kind — `scene.parent_id` naming a `scene` —
  /// both qualifiers were the same string, both resolved to the inner scope, and the correlation
  /// became `"scene"."parent_id" = "scene"."id"`: every quantifier silently answered *is any row its
  /// own parent* instead of the correlated question. Measured against SQLite, the reverse `any` over
  /// a four-row corpus admitted NO rows where two qualify.
  ///
  /// So the source is named by its ALIAS — one level in, from its own minted table — and the parent
  /// by whatever ITS enclosing `FROM` called it, which [`At::qualifier`] answers. The two are
  /// different strings at every depth, which is what makes the shape correct rather than merely
  /// usually correct.
  ///
  /// # Errors
  ///
  /// [`SqlLoweringError::RelationWidth`] where the PARENT is addressed by more than one column: the
  /// child carries one foreign key, so there is one name to compare against and a second parent key
  /// would have nothing to meet.
  fn new<Db: QuoteIdent + Backend<Buffer = Utf8BytesMut>>(
    at: At<'_>,
    source: &RelatedRow,
    points_back: &'static FieldName,
    alias: &str,
  ) -> Result<Self, SqlLoweringError> {
    let id = one_column(at.record())?;
    let mut names = Db::buffer();

    push_quoted_ident::<Db>(source.address().table(), &mut names);
    names.push(' ');
    push_quoted_ident::<Db>(FieldName::new(alias), &mut names);
    let table = names.split();

    push_quoted_scope::<Db>(alias, points_back, &mut names);
    names.push_str(" = ");
    push_quoted_scope::<Db>(at.qualifier(), id, &mut names);

    Ok(Self {
      table,
      correlation: names.split(),
    })
  }
}

/// The ONE column a relation's two sides meet on.
///
/// A `ref` field carries `<Target as Identifiable>::Id` and an id is one column, so a row addressed
/// by several has no name for either side of the join. Answered here for both kinds, so the reading
/// is one statement rather than two that could disagree about which row is at fault.
///
/// # Errors
///
/// [`SqlLoweringError::RelationWidth`], naming the row whose address is too wide.
fn one_column(row: &RecordAddress) -> Result<&'static FieldName, SqlLoweringError> {
  match row.keys() {
    [only] => Ok(only),
    columns => Err(SqlLoweringError::RelationWidth(RelationWidthError::new(
      row.table(),
      columns.len(),
    ))),
  }
}

/// The reverse kind's three quantifier slots in the order the vocabulary declares them — this kind's
/// walk, held beside the impl rather than inside it so the order is one statement rather than an
/// inlined habit.
fn push_quantifiers<C, Db>(
  comparison: &SqlDerivedComparison<C, Db>,
  scope: &Correlation,
  at: At<'_>,
  out: &mut SqlConjunction<'_, Db>,
) -> Result<(), Db::Error>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>>,
  C: ComplexComparison<Db>,
{
  if let Some(nested) = &comparison.any {
    push_quantified(out.open(), scope, at, nested, false)?;
  }
  if let Some(nested) = &comparison.all {
    push_all(out.open(), scope, at, nested)?;
  }
  if let Some(nested) = &comparison.none {
    push_quantified(out.open(), scope, at, nested, true)?;
  }
  Ok(())
}

/// `[NOT ]EXISTS (SELECT 1 FROM <source> WHERE <correlation>[ AND <nested>])` — `any` and its
/// negation, which is `none`.
///
/// One form for both, because *no child satisfies P* IS *not (some child satisfies P)* and nothing
/// about the scope changes between them. The nested predicate is threaded an accumulator whose lead
/// is ` AND `, so it joins the correlation exactly as a second conjunct would and an EMPTY predicate
/// writes nothing at all — leaving `EXISTS (SELECT 1 FROM …)`, which is *this row has a child*, the
/// honest reading of the empty case and the same one
/// [`push_element_scope`](super::push_element_scope) arrives at.
///
/// The subquery is BARE for the reason the forward kind's is; it is also self-limiting, since
/// `EXISTS` short-circuits at the first matching row.
fn push_quantified<C, Db>(
  qb: &mut sqlx::QueryBuilder<Db>,
  scope: &Correlation,
  at: At<'_>,
  nested: &C,
  negated: bool,
) -> Result<(), Db::Error>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>>,
  C: ComplexComparison<Db>,
{
  qb.push(if negated {
    "NOT EXISTS (SELECT 1 FROM "
  } else {
    "EXISTS (SELECT 1 FROM "
  });
  qb.push(&scope.table);
  qb.push(" WHERE ");
  qb.push(&scope.correlation);
  nested.apply(at, SqlConjunction::with_lead(qb, " AND "))?;
  qb.push(")");
  Ok(())
}

/// `NOT EXISTS (SELECT 1 FROM <source> WHERE <correlation> AND NOT ( <nested> ))` — `all`, as the
/// absence of a counterexample.
///
/// # An EMPTY predicate is `1 = 1`, and it is the reduction rather than a special case
///
/// `NOT ( )` is unparseable, so this is the one quantifier that has to look before it writes. What
/// it writes is what the general form reduces to: nothing to negate is `true`, `<correlation> AND
/// NOT true` is false for every child, and `NOT EXISTS` over no rows is true. So `all` with no
/// predicate holds for every row — including one with no children, which is the same answer the
/// non-empty form gives it.
///
/// # The vacuous case is the form's, not a branch
///
/// A row with no children has no counterexample either, so `NOT EXISTS` is true and *every child
/// satisfies P* holds vacuously. That is the decision recorded in the ruling, and it costs no code:
/// the alternative reading — *some child, and every one of them* — would have needed an `EXISTS`
/// beside this one.
///
/// # SQL's third truth value counts as SATISFYING
///
/// A child whose predicate evaluates to `NULL` — a comparison against a `NULL` column — makes
/// `NOT ( … )` `NULL` too, so the child is not a counterexample and the parent still passes. That is
/// `NOT EXISTS`'s own semantics rather than a choice made here, and it is what a caller asking `all`
/// over a nullable column gets on all three engines.
fn push_all<C, Db>(
  qb: &mut sqlx::QueryBuilder<Db>,
  scope: &Correlation,
  at: At<'_>,
  nested: &C,
) -> Result<(), Db::Error>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>>,
  C: ComplexComparison<Db>,
{
  if nested.is_empty() {
    qb.push("1 = 1");
    return Ok(());
  }
  qb.push("NOT EXISTS (SELECT 1 FROM ");
  qb.push(&scope.table);
  qb.push(" WHERE ");
  qb.push(&scope.correlation);
  qb.push(" AND NOT ( ");
  nested.apply(at, SqlConjunction::with_lead(qb, ""))?;
  qb.push(" ))");
  Ok(())
}

/// The `count` slot: the correlated `COUNT(*)` over the whole position, as the left-hand side of a
/// cardinality comparison.
///
/// ```text
/// (SELECT COUNT(*) FROM <source> WHERE <correlation>) <op> ?
/// ```
///
/// It needs no `NULL` care: `COUNT(*)` over no matching rows is `0`, so a row with no children
/// answers `count: { eq: 0 }` with `true`.
fn push_related_count<Db>(
  count: Option<&SqlCountComparison<i64, Db>>,
  scope: &Correlation,
  out: &mut SqlConjunction<'_, Db>,
) where
  Db: sqlx::Database,
  i64: Carrier<Db>,
{
  let Some(count) = count else {
    return;
  };
  push_count_slots(count, out, |qb| {
    qb.push("(SELECT COUNT(*) FROM ");
    qb.push(&scope.table);
    qb.push(" WHERE ");
    qb.push(&scope.correlation);
    qb.push(")");
  });
}

#[cfg(test)]
mod tests;