ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
//! The collection comparisons for a collection kept IN ITS OWN COLUMN — [`SqlListComparison`] for a
//! sequence and [`SqlSetComparison`] for a set — with one concrete lowering of each per dialect.
//!
//! The two are separate types rather than one under a shape marker for the reason
//! [`ListFilter`](crate::ListFilter) and [`SetFilter`](crate::SetFilter) are: they hold different
//! operators. What they share is the storage question — which of them a dialect can keep in a column
//! at all — and that is [`CollectionStorage`], one row per dialect answering for both.

use core::marker::PhantomData;

// Gated with their only users, the two dialects with no array type: they name `Carrier` and the
// second storage strategy's two kinds in their storage rows, and the shared JSON slot walks below
// are themselves gated with the per-dialect impls that call them. An import carries the cfg its
// consumer carries, and the run that catches a mismatch is the one where the family root is on and
// every dialect is off. Postgres reaches the same two kinds from its own module, where the element
// type rather than the dialect names them.
#[cfg(any(feature = "sqlite", feature = "mysql"))]
use super::{
  Carrier, CollectionOp, JsonElement, SqlConjunction, SqlEdgeComparison, SqlEdgeSetComparison,
  json_elements,
};
#[cfg(any(feature = "sqlite", feature = "mysql"))]
use crate::comparison::At;
use crate::{
  ListFilter, QuantifiedFilter, SetFilter, TryMapFilter,
  comparison::{Backend, ComplexComparison, ToDatabaseComparison, TryFromFilter},
};

comparison_kind! {
  /// A [`ListFilter`]'s storage-side twin for a SEQUENCE kept in its own column: the same nine
  /// operators, over the ELEMENT type this database stores the members as.
  ///
  /// # One of two strategies, and [`CollectionStorage`] is where a dialect picks
  ///
  /// Postgres can name this one, because it has a native `ARRAY` and the operators to match — and
  /// it names it per ELEMENT TYPE, through [`PgCollectionStorage`], because an array holds only the
  /// elements sqlx names an array type for. SQLite and MySQL name
  /// [`SqlEdgeComparison`](super::SqlEdgeComparison) for every element, because what they can keep
  /// in a column is JSON and a JSON collection cannot be indexed. This kind is what a sequence
  /// stored in a column is compared through wherever one IS stored that way, which is what the
  /// three impls below are.
  ///
  /// # The kind whose dialects agree about NOTHING — which is why it is three impls
  ///
  /// | dialect | column | operand | ordering |
  /// |---|---|---|---|
  /// | Postgres | native `ARRAY` | the ELEMENTS, bound as one array — `V: PgHasArrayType` | element-wise `<`, native |
  /// | SQLite | TEXT holding a JSON array | one canonical JSON string — `V: JsonElement` | none |
  /// | MySQL | native `JSON` | one canonical JSON string — `V: JsonElement` | none |
  ///
  /// The bounds are disjoint, and that is the point this kind proves. `V: PgHasArrayType` is a trait
  /// sqlx declares for Postgres and for nothing else, so ONE impl over three dialects could not ask
  /// for it — and the version of this kind that had one lowered Postgres through `jsonb`, on an
  /// engine with native arrays and the operators to match. The JSON encoding was not a judgement
  /// about Postgres; it was what the impl shape left available.
  ///
  /// # The JSON lowerings are correct, and correctness is not what settled the default
  ///
  /// Neither SQLite nor MySQL has an array type, so a collection kept in a column there is JSON, and
  /// both give the right answer for whole-collection equality and for membership. What they cannot
  /// do is ORDER two collections, and that is refused at the crossing rather than approximated — see
  /// [`ListCrossingError::JsonOrdering`].
  ///
  /// What they also cannot do is use an INDEX, which is the whole of why [`CollectionStorage`]
  /// sends a declared value list to an edge table on those two dialects instead. These two impls
  /// are what a sequence ALREADY held as a JSON array is compared through.
  ///
  /// # The bind count does not follow the operand's LENGTH
  ///
  /// One bind per operator on every dialect. Postgres binds an ARRAY of N elements as one parameter
  /// and the other two bind one JSON string, so a thousand-element `eq` costs one bind where a
  /// thousand-element `IN` costs a thousand — the 65535 / 32766 ceilings are unreachable from this
  /// kind on any dialect.
  ///
  /// # `has_element` is the exception to the operand SHAPE and not to the encoding
  ///
  /// It holds one element and lowers as containment of the singleton collection, so it takes the
  /// same path as the six whole-collection slots on every dialect. Containment is order-blind where
  /// every other operator here is not, and that is membership's own nature rather than this kind
  /// borrowing from [`SqlSetComparison`]: "is `x` in this sequence" has no positional answer to
  /// give.
  ///
  /// # `any` holds a COMPARISON, and `C` is the element's
  ///
  /// The eighth slot is not an operand. It is the comparison ONE element of this collection is
  /// asked, which is whatever the element's own filter kind crossed into — a scalar's, a text's, a
  /// byte string's — so it is a type parameter rather than another `Option<V>`. What renders it is
  /// [`push_element_scope`](super::push_element_scope), which opens a scope naming the member and
  /// hands the comparison an [`At`] like any other.
  ///
  /// Only ONE of this kind's two dialect groups can answer it. Postgres has `unnest`, which is a
  /// real element scope; SQLite has `json_each`, which is one for the element vocabularies whose
  /// canonical JSON token decodes to the value their carrier binds; MySQL has neither and refuses —
  /// see [`SqlLoweringError::JsonElementScope`](super::SqlLoweringError::JsonElementScope).
  ///
  /// # `count` holds a comparison too, and every dialect answers it
  ///
  /// The ninth slot is a [`SqlCountComparison`](super::SqlCountComparison) — the eight operators a
  /// number takes, against this column's LENGTH. Each dialect names its own cardinality
  /// (`json_array_length`, `cardinality`, `JSON_LENGTH`) and the operators to the right of it are
  /// one walk, so a count is one question with three spellings of the expression it compares.
  ///
  /// MySQL answers it where it refuses `any`, and the difference is what each needs: a cardinality
  /// is a SCALAR function over the stored value, where an element question needs a table function
  /// whose rows the optimizer moves out from under the correlation.
  SqlListComparison {
    one { has_element }
    many { eq, ne, gt, gte, lt, lte }
    element { any: C }
    cardinality { count }
  }
}

comparison_kind! {
  /// A [`SetFilter`]'s storage-side twin for a set kept in its own column: the same eight
  /// operators, over the ELEMENT type this database stores the members as.
  ///
  /// # No engine has a set type, so this is a column shape it shares with the sequence
  ///
  /// Postgres has no set type and stores one in an `ARRAY` column; SQLite and MySQL have neither and
  /// store one as JSON. MySQL's `SET` is real and does not generalise — it is a fixed enumerated
  /// type of at most 64 members declared in the schema, so an open vocabulary cannot use it. The two
  /// column-stored kinds therefore guard the same physical column and differ in which operators they
  /// emit against it, which is exactly what the shape parameter they replace used to decide.
  ///
  /// | dialect | operators |
  /// |---|---|
  /// | Postgres | `@>` `<@` `&&`, all native; equality is mutual containment |
  /// | SQLite | `json_each` set expressions |
  /// | MySQL | `JSON_CONTAINS` / `JSON_OVERLAPS` |
  ///
  /// # No OPERATOR here can be refused, which is why the crossing is ONE impl
  ///
  /// The sequence kind's crossings are per-dialect because two dialects cannot answer an ordering.
  /// Every operator here is order- and multiplicity-blind, so all three dialects and both storage
  /// strategies answer all six, and no dialect has a no to give about them. That is what makes the
  /// crossing dialect-free, and it is the split paying for itself: the crossing error used to carry
  /// a variant for an unordered column asked to compare as a magnitude, and no such column can be
  /// asked any more.
  ///
  /// One dialect does refuse `any`, and it refuses at the LOWERING rather than here — the element
  /// SCOPE is an address, and an address arrives with the application. So this crossing stays one
  /// impl and gains only the two failures every collection crossing now has: the ELEMENT crossing's
  /// own, and a `count` operand no cardinality integer can hold.
  ///
  /// # Whole-collection equality binds each direction
  ///
  /// A set's stored element order is an artefact of insertion, so its equality is mutual containment
  /// and costs two binds where every other operator costs one. The bind count still does not follow
  /// the operand's LENGTH on any dialect.
  ///
  /// `has_element` holds one element and lowers as containment of the singleton, so it takes the
  /// same path as the five whole-collection slots. `any` and `count` each hold a whole COMPARISON
  /// and take none of them — see [`SqlListComparison`], whose two slots these are the twins of.
  SqlSetComparison {
    one { has_element }
    many { eq, ne, encloses, enclosed_by, overlaps }
    element { any: C }
    cardinality { count }
  }
}

/// Why a [`ListFilter`]'s operands did not become storage values.
///
/// The second crossing error in the family, and it carries the same shape
/// [`BytesCrossingError`](super::BytesCrossingError) does: the converter's own failure beside the
/// refusal the vocabulary can express but this dialect cannot answer. A refusal says so, where an
/// empty result set would read as an honest miss.
///
/// # Two converter errors, because a collection filter now holds two kinds of operand
///
/// `E` is the ELEMENT converter's — the `f` a crossing is given, or the storage type's own
/// [`TryFrom`] where it is not — and `X` is the ELEMENT FILTER's crossing error, which belongs to
/// whatever kind guards one member. They are independent: a `Vec<[u8; 32]>` converts its elements
/// with one and crosses its `any` slot with [`BytesCrossingError`](super::BytesCrossingError), and
/// no bound makes those one type.
///
/// `X` DEFAULTS to `E`, which is the case every value kind produces: a scalar, text, enum, boolean
/// or duration element crosses with exactly its storage type's conversion error, so
/// `ListCrossingError<Infallible>` still spells the identity crossing over such an element.
///
/// # The CARDINALITY's failure is a variant and not a third parameter
///
/// A `count` operand is a `usize` and this family compares a cardinality as `i64`, so what can fail
/// there is fixed by the family rather than chosen by a caller — there is nothing for a parameter to
/// range over. That is the whole difference from the two above, each of which carries a converter
/// somebody else wrote.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ListCrossingError<E, X = E> {
  /// An element did not convert into the column's storage type — the converter's own error.
  ///
  /// Either LEVEL: an operand written inside the nested `any` filter is an element too, so the
  /// one-converter crossing reports its refusal here rather than under `Element`.
  Operand(E),
  /// The ELEMENT filter did not cross into an element comparison — that crossing's own error.
  Element(X),
  /// A `count` operand does not fit the integer this family compares a cardinality as.
  ///
  /// Refused rather than saturated: an operand a client sent is not a number this crate may
  /// substitute, and a substituted one is a wrong result set reported as a right one. No collection
  /// any engine here can hold reaches it.
  Cardinality(core::num::TryFromIntError),
  /// A sequence stored as JSON was asked to compare as a magnitude, named here by its operator
  /// (`"gt"` / `"gte"` / `"lt"` / `"lte"`).
  ///
  /// SQLite and MySQL have no array type: a collection column is a JSON array, and JSON has no
  /// element-wise collection order. MySQL does define an ordering over JSON VALUES, and it is not
  /// this one — it ranks by element type before value — so adopting it would answer a different
  /// question under the same operator name. Postgres has the operator natively and an edge table has
  /// an ordinal column, so neither raises this.
  JsonOrdering(&'static str),
}

impl<E: core::fmt::Display, X: core::fmt::Display> core::fmt::Display for ListCrossingError<E, X> {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self {
      Self::Operand(error) => error.fmt(f),
      Self::Element(error) => error.fmt(f),
      Self::Cardinality(error) => error.fmt(f),
      Self::JsonOrdering(operator) => write!(
        f,
        "operator {operator:?} compares collections element-wise and this dialect stores a \
         collection as JSON, which has no such order"
      ),
    }
  }
}

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

/// Why a [`SetFilter`]'s operands did not become storage values.
///
/// It exists because a collection filter carries a nested FILTER — the `any` slot — and a nested
/// filter crosses through its own kind with its own error. Before that slot, a set crossing's only
/// failure was the element converter's and its error simply WAS the converter's; there is now a
/// second, so there is a type.
///
/// What it still has no variant for is a REFUSAL, and that absence is the same load-bearing one it
/// always was: [`ListCrossingError::JsonOrdering`] has no counterpart here, because the operator
/// that raises it is not on this kind. The one dialect that declines `any` declines it at the
/// lowering rather than at the crossing — the element scope is an ADDRESS — so nothing here names a
/// dialect either.
///
/// `E` and `X` are [`ListCrossingError`]'s two, with the same default and for the same reason, and
/// the cardinality variant is that type's for the reason stated there.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SetCrossingError<E, X = E> {
  /// An element did not convert into the column's storage type — the converter's own error.
  ///
  /// Either LEVEL: an operand written inside the nested `any` filter is an element too, so the
  /// one-converter crossing reports its refusal here rather than under `Element`.
  Operand(E),
  /// The ELEMENT filter did not cross into an element comparison — that crossing's own error.
  Element(X),
  /// A `count` operand does not fit the integer this family compares a cardinality as — as
  /// [`ListCrossingError::Cardinality`].
  Cardinality(core::num::TryFromIntError),
}

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

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

/// Collapse the element leg's own refusal into the crossing's, which is what makes ONE declared
/// converter's refusal read the same at both levels.
///
/// The one-converter crossings hand the `g` slot a closure that reports the CONVERTER's refusal as
/// [`ListCrossingError::Operand`] and the element comparison's as
/// [`ListCrossingError::Element`] — so what comes back is this type inside its own `Element`, and
/// what a caller is owed is one level. `Element(inner) => inner` is the whole of the collapse; the
/// other three arms are the outer crossing's own refusals, which the inner leg never produces and
/// which nothing here should be able to invent a second spelling of.
///
/// Shared by every kind that refuses with [`ListCrossingError`] — the edge-table sequence and the
/// three column-stored ones — because a nested operand is the converter's refusal on all four.
pub(super) fn flatten_list<E, X>(
  why: ListCrossingError<E, ListCrossingError<E, X>>,
) -> ListCrossingError<E, X> {
  match why {
    ListCrossingError::Operand(error) => ListCrossingError::Operand(error),
    ListCrossingError::Element(inner) => inner,
    ListCrossingError::Cardinality(error) => ListCrossingError::Cardinality(error),
    ListCrossingError::JsonOrdering(operator) => ListCrossingError::JsonOrdering(operator),
  }
}

/// The same collapse for a set — see [`flatten_list`], whose note this shares. A set has no
/// ordering refusal to carry through, which is the one arm of difference.
pub(super) fn flatten_set<E, X>(
  why: SetCrossingError<E, SetCrossingError<E, X>>,
) -> SetCrossingError<E, X> {
  match why {
    SetCrossingError::Operand(error) => SetCrossingError::Operand(error),
    SetCrossingError::Element(inner) => inner,
    SetCrossingError::Cardinality(error) => SetCrossingError::Cardinality(error),
  }
}

/// The first ordering operator `filter` sets, by name — the list both refusals walk, so the two
/// cannot disagree about which four operators are the ordering ones.
///
/// Gated with the two JSON dialects that are its only callers: an edge-table sequence has an ordinal
/// column and answers all four, and Postgres has the operator natively, so neither asks.
#[cfg(any(feature = "sqlite", feature = "mysql"))]
pub(super) fn ordering_operator<D, VF>(filter: &ListFilter<D, VF>) -> Option<&'static str> {
  [
    ("gt", filter.gt().is_some()),
    ("gte", filter.gte().is_some()),
    ("lt", filter.lt().is_some()),
    ("lte", filter.lte().is_some()),
  ]
  .into_iter()
  .find_map(|(name, set)| set.then_some(name))
}

/// Cross ONE element filter into the element comparison a collection holds, or `None` where the
/// operator is absent.
///
/// The `any` half of every collection crossing, shared by all four kinds and both shapes — the
/// `Option` walk, so that six crossings hold one statement of what an absent operator crosses into.
///
/// `g` is the element's own crossing rather than the element CONVERTER, and the division is
/// [`Nullable`](crate::Nullable)'s: a wrapper's parameter ranges over what it holds, and this slot
/// holds a whole filter.
///
/// It is what makes the second error variant necessary, and also why that variant cannot be folded
/// into the first: `g`'s error is the element kind's, and nothing relates it to the element
/// converter's.
// Not gated on a dialect, where `from_stored` below is: two of the six crossings this serves are the
// correlated kinds', which name no database.
pub(super) fn cross_element<VF, C, X>(
  filter: Option<VF>,
  g: impl FnOnce(VF) -> Result<C, X>,
) -> Result<Option<C>, X> {
  match filter {
    Some(filter) => g(filter).map(Some),
    None => Ok(None),
  }
}

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

/// The half of a sequence crossing that is the same in every dialect: the already-converted filter's
/// slots, moved across. What differs is the REFUSAL each dialect makes first.
#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
fn from_stored<V, VF, C, Db>(
  stored: ListFilter<V, VF>,
  any: Option<C>,
  count: Option<super::SqlCountComparison<i64, Db>>,
) -> SqlListComparison<V, C, Db> {
  SqlListComparison {
    has_element: stored.has_element,
    eq: stored.eq,
    ne: stored.ne,
    gt: stored.gt,
    gte: stored.gte,
    lt: stored.lt,
    lte: stored.lte,
    any,
    count,
    db: PhantomData,
  }
}

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

  /// Cross a [`SetFilter`] into a column-stored set comparison, converting each ELEMENT with `f` and
  /// the nested ELEMENT FILTER with `g`.
  ///
  /// Dialect-free, where the sequence kind's three crossings each name their database: every
  /// operator a set carries is answerable on all three, so no dialect has a refusal to make here.
  ///
  /// # Errors
  ///
  /// [`SetCrossingError::Operand`] for whatever `f` refuses an element with, and
  /// [`SetCrossingError::Element`] for whatever `g` refuses the element filter with.
  ///
  /// `g` crosses the ELEMENT filter, and it is a second function rather than a use of `f` because
  /// the two convert different things: `f` maps one ELEMENT into its storage type, while the `any`
  /// slot holds a whole FILTER whose own operands are the element kind's to convert. A caller
  /// holding ONE converter for both is asking [`try_from_filter_with`](Self::try_from_filter_with),
  /// which composes them; the identity crossing below passes [`TryFromFilter::try_from_filter`] and
  /// needs no closure at all.
  pub fn try_from_filter_with_element<D, VF, E, F, X, G>(
    filter: SetFilter<D, VF>,
    f: F,
    g: G,
  ) -> Result<Self, SetCrossingError<E, X>>
  where
    F: FnMut(D) -> Result<V, E>,
    G: FnOnce(VF) -> Result<C, X>,
  {
    let mut stored = filter.try_map(f).map_err(SetCrossingError::Operand)?;
    let any = cross_element(stored.any.take(), g).map_err(SetCrossingError::Element)?;
    let count = cross_count(stored.count).map_err(SetCrossingError::Cardinality)?;
    Ok(Self {
      has_element: stored.has_element,
      eq: stored.eq,
      ne: stored.ne,
      encloses: stored.encloses,
      enclosed_by: stored.enclosed_by,
      overlaps: stored.overlaps,
      any,
      count,
      db: PhantomData,
    })
  }
}

/// The identity crossing for a column-stored set — a set of `String` kept in a `text[]` is the
/// common one.
///
/// # Errors
///
/// As [`try_from_filter_with_element`](SqlSetComparison::try_from_filter_with_element).
impl<D, VF, V: TryFrom<D>, C: TryFromFilter<VF>, Db> TryFromFilter<SetFilter<D, VF>>
  for SqlSetComparison<V, C, Db>
{
  type Error = SetCrossingError<V::Error, C::Error>;

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

/// Which storage strategy a dialect keeps a value list in, named by the comparisons that address it.
///
/// # The one split in this family that is not about spelling
///
/// Every other per-dialect split here is a disagreement about how to WRITE a question, or about the
/// bounds an operand needs. This one is a disagreement about what is STORED. SQLite and MySQL have
/// no array type: what they can keep in a column is JSON, and both JSON forms give the right answer
/// while neither can use an INDEX — `json_each` is a table-valued function, so SQLite's is a full
/// scan with a JSON parse per row, and `JSON_CONTAINS` is not sargable on a plain `JSON` column.
/// SQLite is this project's primary database, so those two keep a value list in an EDGE TABLE and
/// name [`SqlEdgeComparison`](super::SqlEdgeComparison) and
/// [`SqlEdgeSetComparison`](super::SqlEdgeSetComparison), whose every operator is an indexed
/// `EXISTS`. Postgres has a native `ARRAY` and can keep a value list in the column — for the element
/// types whose bytes an array can actually hold, which is not all of them, so its row delegates to
/// [`PgCollectionStorage`] rather than answering.
///
/// Two storage shapes are two comparison TYPES rather than more impls of one, because what the
/// second one needs is not a different rendering: it is a table name and the parent's key columns,
/// which [`ComplexComparison::apply`](crate::ComplexComparison::apply) does not carry and which
/// would be dead on a dialect keeping a list in its column.
///
/// # Two associated types, because the shape stopped being a parameter
///
/// This trait was keyed on a `List` / `Set` marker that every row was generic over and no row read:
/// the shape decided what a comparison MEANT and never which strategy stored it. With the collection
/// filter split in two, the shape is the NAME of an answer instead — a row states both, and states
/// them independently. An element type whose sequence belongs in an array column while its set
/// belongs in an edge table costs one row either way, and a parameter no row branched on could not
/// express it at all.
///
/// # A trait rather than one [`ToDatabaseComparison`] row per dialect
///
/// The map stays ONE impl per filter kind and what varies is an associated type stated per dialect —
/// the arrangement [`QuoteIdent`](super::QuoteIdent) and [`BindCeiling`](super::BindCeiling) already
/// have one level further out, where the dialect states a character or a number and the work is
/// written once. It is also what keeps the choice open: a dialect this crate does not ship states
/// its own strategy in a row of its own, where concrete rows would have to be edited to admit a
/// fourth.
///
/// # The lowering promise travels DOWN to here, because this is where the strategy is chosen
///
/// [`ToDatabaseComparison::Comparison`](crate::ToDatabaseComparison::Comparison) promises
/// [`ComplexComparison`], and the two rows below it hand that question straight to this trait: their
/// `Comparison` IS one of this one's, so a promise stated only up there would have to be proved from
/// `Db: CollectionStorage<V>` alone, where the types are opaque. Restating it here is what makes it
/// provable, and it is stated at the right place — a dialect choosing a strategy is choosing a
/// comparison, and a strategy whose comparison cannot be lowered is not one.
///
/// It is also what keeps the choice OPEN under the promise: a dialect this crate does not ship
/// states its own row and keeps the same promise, rather than the promise being a list of the four
/// types this file happens to name.
///
/// # `VF` is the ELEMENT's FILTER, and the element's crossing happens in the ROW
///
/// A collection comparison holds the comparison one MEMBER is asked, so a strategy names that
/// strategy over this element type AND that element's comparison. What travels here is the element's
/// FILTER rather than its comparison, and the difference is where
/// `<VF as ToDatabaseComparison<V, Db>>::Comparison` is written: inside a row, which is selected only
/// once a dialect is named.
///
/// Written on THIS trait instead, it would land in
/// [`ToDatabaseComparison`]'s own header — and an emitted comparison assumes exactly that predicate
/// at a database it has not named yet. A projection in it makes rustc resolve the inner crossing to
/// know the outer trait-ref's arguments, and a nested crossing is not something an expansion states.
/// Measured: every collection column in `ingraph-derive`'s fixtures failed as
/// *`__INGRAPH_DB__: CollectionStorage<Vec<String>, _>` is not satisfied*, with the second argument
/// an inference variable. With the filter here the trait-ref is concrete on both arguments, and the
/// assumption applies exactly as it did before this parameter existed.
pub trait CollectionStorage<V, VF>: sqlx::Database + Backend {
  /// The comparison a [`ListFilter`] crosses into on this dialect.
  type Sequence: ComplexComparison<Self>;
  /// The comparison a [`SetFilter`] crosses into on this dialect.
  type Set: ComplexComparison<Self>;
}

/// The one dialect with a choice to make, so its row makes none: it states whatever the ELEMENT
/// type's [`PgCollectionStorage`] row states, and that is where array-versus-edge is decided.
#[cfg(feature = "postgres")]
impl<V: PgCollectionStorage<VF>, VF> CollectionStorage<V, VF> for sqlx::Postgres {
  type Sequence = <V as PgCollectionStorage<VF>>::Sequence;
  type Set = <V as PgCollectionStorage<VF>>::Set;
}

/// Which storage strategy Postgres keeps a collection of THIS element type in — the half of
/// [`CollectionStorage`] that the one dialect with two usable strategies cannot answer from the
/// dialect alone.
///
/// Public, and for the reason [`Carrier`](super::Carrier) is: this is the surface a downstream
/// element type joins the collection vocabulary through on Postgres, and a type with a row here
/// needs nothing else from this crate to be filtered on as a list or as a set.
///
/// # Why the dialect cannot answer alone
///
/// Both column-stored kinds' Postgres lowerings are bounded `V: PgHasArrayType` — the sqlx row
/// naming the array type OID an element lives in — and a great many element types have no such row.
/// This crate's own [`BeU64`](crate::BeU64) is one: it binds fine as a scalar and sqlx names no
/// array type for a blob carrier. A dialect-keyed answer sends every one of them to a column-stored
/// kind and the bound then fails at the LOWERING, naming a sqlx trait, with no fallback and no way
/// to ask for one.
///
/// So the refusal moves here, and moving it is half of what this trait buys: a missing row is
/// `E0277` at the crossing, naming the row a reader can go and write, where it used to be `E0599`
/// on `apply` naming `PgHasArrayType`. That message is pinned as exact text —
/// `tests/pg_collection_strategy/` — because it is the deliverable rather than a side effect.
///
/// # Why the choice is declared rather than deduced
///
/// The two impls that would deduce it —
///
/// ```text
/// impl<V: PgHasArrayType> CollectionStorage<V> for Postgres { … }
/// impl<V>                 CollectionStorage<V> for Postgres { … }
/// ```
///
/// — are `E0119`, and both routes out of that are unstable: `V: !PgHasArrayType` is a negative bound
/// and the alternative is specialization. So the choice is a ROW, and the row is keyed on the
/// element type because that is what it is a fact about.
///
/// A blanket `impl<V: PgHasArrayType> PgCollectionStorage for V` is refused for the same reason one
/// level down: it would make the array case automatic and then leave a type WITHOUT an array type
/// unable to be given a row at all, since a specific impl would overlap the blanket and rustc will
/// not prove the negative for a foreign trait. That closes the surface this trait exists to open.
/// Per-type rows are what [`Carrier`](super::Carrier) already asks for, and a downstream pays the
/// same one-line price here that it pays there.
///
/// # A row that has the array and declines it is legal, and that is the second thing this buys
///
/// The strategy is not a fallback for types the array cannot hold. An element type with a perfectly
/// good `PgHasArrayType` may name the edge table anyway — a list long enough that an unindexed `@>`
/// over it is the wrong plan, or an index shape an array cannot give — and it costs one row. That
/// was unspellable while the dialect answered.
///
/// # The two answers are independent, which the shape parameter could not make them
///
/// A row states its sequence strategy and its set strategy separately, so an element may keep an
/// ordered column in an array and send its unordered one to an edge table — where an index on
/// `(key…, value)` answers containment with a seek and an array cannot. Every row this crate ships
/// states the same strategy twice, and that is a fact about these elements rather than a rule.
///
/// # The rows this crate ships
///
/// One per element type in the Postgres [`Carrier`](super::Carrier) table, and the rule that picks
/// between the two is a single question: **does sqlx's array type for this element match the column
/// its carrier row binds into?** Where it does, the array; where it does not — or where there is no
/// array type at all — the edge table. See the two lists beside the rows themselves.
///
/// # The lowering promise travels ONE level further, for the reason it reached
/// [`CollectionStorage`] at all
///
/// Postgres's row states whatever this one states — its two answers ARE this one's — so a promise
/// that stopped at the dialect would have to be proved from `V: PgCollectionStorage` alone, where
/// the types are opaque. Restating it here is what makes it provable, and it lands where the choice
/// is actually made: an element type picking a strategy is picking a comparison, and a strategy
/// whose comparison cannot be lowered is not one.
///
/// # `VF` travels here too, for the reason it reached [`CollectionStorage`]
///
/// A strategy names a comparison and a collection comparison holds the ELEMENT's, so a row states
/// its answer over both. A row is still one line per element type, and it is where the element's own
/// crossing is finally written — at a named dialect, which is the only place a projection through it
/// resolves.
///
/// # The refusal is WRITTEN, and the list beside it is made to stop moving
///
/// Unimplemented, rustc names the eight types with a row that sort first and says *and N others*.
/// Which eight was a function of the FEATURE SET — the wrapper's rows are `jiff` + `time`, so their
/// presence displaced another entry — and the fixture that pins this refusal as exact text was
/// therefore unassertable in any build without both, which is what kept a dialect-only build red.
/// The wrapper's two rows carry [`do_not_recommend`](diagnostic::do_not_recommend) and no other row
/// does: they were the only entries that could come and go, so suppressing exactly them settles the
/// text and leaves the list itself — which is a real suggestion to whoever reads it.
///
/// The sentence above is what a reader acts on, and it is written rather than inferred from that
/// list, which names types and not the thing to do. The second note is there because this bound has
/// a second way to fail that the first does not describe: `Self` may HAVE a row while `{VF}` has no
/// [`ToDatabaseComparison`](crate::comparison::ToDatabaseComparison) into it. Which message a reader
/// sees then depends on what they wrote — a failing PROJECTION is reported at that crossing directly
/// and never reaches this text, while a caller who named this bound in a where-clause gets this one,
/// and there the note is the only thing distinguishing the two missing pieces.
#[cfg(feature = "postgres")]
#[diagnostic::on_unimplemented(
  message = "a collection of `{Self}` has no Postgres storage strategy",
  label = "this element type has no `PgCollectionStorage` row",
  note = "write `impl PgCollectionStorage<{VF}> for {Self}` stating its `Sequence` and \
          `Set`: the array kinds where sqlx's array type for `{Self}` is the array of the \
          column its `Carrier` row binds into, the edge-table kinds where it is not or \
          where there is no array type at all",
  note = "if `{Self}` already has a row, then `{VF}` is what is missing — an element filter \
          reaches a strategy through `ToDatabaseComparison<{Self}, sqlx::Postgres>`"
)]
pub trait PgCollectionStorage<VF> {
  /// The comparison a [`ListFilter`] over a sequence of `Self` crosses into on Postgres.
  type Sequence: ComplexComparison<sqlx::Postgres>;
  /// The comparison a [`SetFilter`] over a set of `Self` crosses into on Postgres.
  type Set: ComplexComparison<sqlx::Postgres>;
}

/// One collection strategy, re-stated over a different element type.
///
/// `Self` is a comparison some element's storage row named, `V` is the element the same strategy is
/// wanted over, and [`Comparison`](Self::Comparison) is that strategy holding `V`. The four rows
/// this crate ships are the whole of it: each kind re-stated is that kind.
///
/// # What needs it
///
/// A WRAPPER element stores exactly where the element it wraps does, so its strategy has to be that
/// element's — and [`Temporal<T>`](super::Temporal) is the one such element this crate ships. What
/// stands in the way is that a storage row states a COMPARISON rather than a strategy token, and a
/// comparison names its element: reading `T`'s row gives `Strategy<T, Db>` where the wrapper needs
/// `Strategy<Temporal<T>, Db>`. An associated type cannot rewrite the element inside one. This is
/// what does, and it is the same manoeuvre the borrowed halves of the [`PgCollectionStorage`] table
/// make by hand — `&'a V`'s row is a fresh row over the same strategies rather than a delegation to
/// `V`'s, for want of exactly this.
///
/// # It reads a declaration and makes none
///
/// Which row matches is settled by the comparison the element ALREADY declared, so nothing here
/// asks whether an element can be held in an array. That question is [`PgCollectionStorage`]'s to
/// refuse: deducing an array row from `T: PgHasArrayType + Type + Encode` admits `Temporal<i8>`
/// wrongly, since `i8` satisfies all three while this crate's carrier widens it to `smallint` and
/// sqlx types it `"char"`. A trait that is handed the answer cannot reintroduce that.
///
/// # Generic in the dialect, where its consumer is not
///
/// Substituting an element is not a per-dialect fact, and all four kinds are already generic in
/// `Db`. The one caller is Postgres's, because Postgres is the one dialect with two strategies to
/// pick between — see [`CollectionStorage`].
///
/// # Openness
///
/// A downstream comparison type joins by writing one row for itself, exactly as
/// [`Carrier`](super::Carrier) and [`PgCollectionStorage`] are joined, and the orphan rule allows
/// it because the self type is the downstream's. Without one, a wrapper over an element whose row
/// names that comparison has no row of its own — which is the honest answer, and the same one an
/// element with no storage row at all gets.
pub trait StrategyOver<V> {
  /// The strategy `Self` is, over element type `V`.
  type Comparison;
}

/// The column-stored sequence kind re-stated is that kind: the dialect keeps, and the element MOVES
/// — both the collection's own operands and the comparison one MEMBER is asked, since a member is
/// stored in the same form the collection's operands are.
///
/// The element comparison re-states through this same trait, which is what keeps the two halves from
/// disagreeing: `Temporal<T>`'s members bind as `Temporal<T>`, so its element comparison is over the
/// wrapper too, and a crossing from the DOMAIN element's filter — `ScalarFilter<jiff::Timestamp>` —
/// reaches it exactly as the collection's own operands do. Keeping `T`'s element comparison instead
/// compiles and then refuses the crossing, which is how the recursion was found.
impl<V, C: StrategyOver<W>, Db, W> StrategyOver<W> for SqlListComparison<V, C, Db> {
  type Comparison = SqlListComparison<W, C::Comparison, Db>;
}

/// The column-stored set kind, likewise.
impl<V, C: StrategyOver<W>, Db, W> StrategyOver<W> for SqlSetComparison<V, C, Db> {
  type Comparison = SqlSetComparison<W, C::Comparison, Db>;
}

/// No array type, and the JSON alternative cannot be indexed — so an edge table, for both shapes.
///
/// The bound is the edge comparisons' lowering: one bind per element through the dialect's carrier
/// table.
#[cfg(feature = "sqlite")]
impl<V: Carrier<sqlx::Sqlite>, VF: ToDatabaseComparison<V, sqlx::Sqlite>> CollectionStorage<V, VF>
  for sqlx::Sqlite
{
  type Sequence = SqlEdgeComparison<V, VF::Comparison, sqlx::Sqlite>;
  type Set = SqlEdgeSetComparison<V, VF::Comparison, sqlx::Sqlite>;
}

/// No general array type — its `SET` is a fixed enumerated type of at most 64 members, not one —
/// and the same JSON ceiling, so the same edge table.
#[cfg(feature = "mysql")]
impl<V: Carrier<sqlx::MySql>, VF: ToDatabaseComparison<V, sqlx::MySql>> CollectionStorage<V, VF>
  for sqlx::MySql
{
  type Sequence = SqlEdgeComparison<V, VF::Comparison, sqlx::MySql>;
  type Set = SqlEdgeSetComparison<V, VF::Comparison, sqlx::MySql>;
}

/// The type-level map, keyed on the dialect's declared strategy: a [`ListFilter`] crosses into
/// whichever comparison the database that answers keeps a SEQUENCE in.
///
/// It is the crossing where the choice lands rather than anything below it, because
/// [`ToDatabaseComparison`]'s `Comparison` is already keyed on `Db`. Nothing about
/// [`ComplexComparison`](crate::ComplexComparison) changes and no other filter kind pays for it.
///
/// # The element filter crosses FIRST, and the collection reads its answer
///
/// `VF` is the element's filter kind, and the comparison the collection holds is whatever THAT
/// filter crosses into over the SAME storage type and the same dialect — because a collection's
/// members are stored as `V`, whether in a column, an array or an edge row. So this row projects
/// through `VF`'s own crossing and hands the result to the storage map, which is what keeps the
/// element's vocabulary the element's: a text element brings the substring family and a scalar one
/// does not, with nothing here choosing between them.
impl<D, VF, V, Db: CollectionStorage<V, VF>> ToDatabaseComparison<V, Db> for ListFilter<D, VF> {
  type Comparison = <Db as CollectionStorage<V, VF>>::Sequence;
}

/// The same map for a set, reading the other half of the same row.
impl<D, VF, V, Db: CollectionStorage<V, VF>> ToDatabaseComparison<V, Db> for SetFilter<D, VF> {
  type Comparison = <Db as CollectionStorage<V, VF>>::Set;
}

/// The narrow collection reads the SEQUENCE half, and that is a storage fact rather than a choice
/// between two equally good rows.
///
/// [`CollectionStorage`]'s two answers name a STRATEGY — a native array, or an edge table — and
/// nothing about which operators a filter publishes. A quantified column's elements are written in
/// the order the writer produced them, so a sequence is what is stored; the filter simply declines to
/// ask about that order. Reading the `Set` half instead would name the strategy an UNORDERED column
/// takes, and the two differ in the shape of the table on the dialects where they differ at all.
///
/// So no third associated type is added, and none is wanted: a row this crate does not ship would
/// have to answer it, and what it would answer is the sequence strategy it already states.
impl<D, VF, V, Db: CollectionStorage<V, VF>> ToDatabaseComparison<V, Db>
  for QuantifiedFilter<D, VF>
{
  type Comparison = <Db as CollectionStorage<V, VF>>::Sequence;
}

/// The narrow crossing into a column-stored sequence comparison — ONE impl for every dialect, where
/// the wide sequence crossing is three.
///
/// # The two arms are the wide kinds' own, called rather than restated
///
/// [`cross_element`] and [`cross_count`] are what a collection crossing's `any` and `count` slots go
/// through, on all six of the existing ones. This crossing calls exactly those two, so *what an
/// absent operator crosses into* and *how a `usize` cardinality becomes this family's integer* have
/// one statement each in the whole crate and this kind inherits both. What is left here is
/// `Self::new()` and two assignments, which is not semantics: the seven element slots stay unset
/// STRUCTURALLY — nothing writes them — rather than by seven `None`s a reader has to count.
///
/// # Dialect-free, where the wide sequence crossing names its database
///
/// [`ListCrossingError::JsonOrdering`] is why that one is per-dialect: two dialects cannot answer an
/// element-wise collection ordering, so each refuses before crossing. This kind has no ordering
/// operator for any dialect to refuse, which is the same reason [`SqlSetComparison`]'s crossing is
/// one impl.
///
/// # Errors
///
/// [`ListCrossingError::Element`] for whatever the ELEMENT filter's own crossing refuses, and
/// [`ListCrossingError::Cardinality`] for a `count` operand past the integer this family compares a
/// length as.
///
/// The other two variants cannot arrive, and each is closed by something different.
/// [`Operand`](ListCrossingError::Operand) carries [`Infallible`](core::convert::Infallible) here —
/// this filter holds no element operand, so there is no converter to refuse one and the variant is
/// UNINHABITED, which is the compiler stating it rather than this sentence.
/// [`JsonOrdering`](ListCrossingError::JsonOrdering) is inhabited and unreachable: it names one of
/// four operators none of which is on this kind.
///
/// The error type is the wide kind's all the same, at a different `E`. That is what a caller gets
/// from the reuse — a cell already absorbing a column-stored sequence's refusal absorbs this one
/// through the same row, where a fourth crossing-error type whose whole content is two variants of
/// an existing one would have cost every declaration another `From`.
impl<D, VF, V, C: TryFromFilter<VF>, Db> TryFromFilter<QuantifiedFilter<D, VF>>
  for SqlListComparison<V, C, Db>
{
  type Error = ListCrossingError<core::convert::Infallible, C::Error>;

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

/// The sequence slot walk the JSON-storing dialects share: whole-collection equality in the order
/// the FILTER declares it, then `has_element` — which is the order a client wrote and not the order
/// the struct stores, where the single-operand slot leads because the kind macro groups slots by
/// arity.
///
/// The four ORDERING slots are absent from it, and that is the single-gate rule rather than an
/// omission: neither of these dialects can answer them, so neither crossing lets one be set. A
/// second check here would be a second place for the two to disagree.
///
/// Shared by SQLite and MySQL and by nothing else. Postgres stores a collection as a native array
/// and its lowering binds the ELEMENTS rather than one JSON value, so it neither reads
/// [`JsonElement`] nor calls this walk.
// Gated with its only callers, the two JSON impls below.
#[cfg(any(feature = "sqlite", feature = "mysql"))]
fn push_json_list_slots<V, C, Db, L>(
  comparison: &SqlListComparison<V, C, Db>,
  at: At<'_>,
  out: &mut SqlConjunction<'_, Db>,
  leaf: L,
) where
  Db: sqlx::Database,
  V: JsonElement,
  L: Fn(&mut sqlx::QueryBuilder<Db>, At<'_>, CollectionOp, &str, bool),
{
  let mut slot = |values: &Option<Box<[V]>>, negated| {
    if let Some(elements) = values {
      let json = json_elements(elements);
      leaf(out.open(), at, CollectionOp::SequenceEq, &json, negated);
    }
  };
  slot(&comparison.eq, false);
  slot(&comparison.ne, true);
  push_json_membership(comparison.has_element.as_ref(), at, out, leaf);
}

/// The set slot walk the JSON-storing dialects share, in the order the FILTER declares its slots.
// Gated with its only callers, the two JSON impls below.
#[cfg(any(feature = "sqlite", feature = "mysql"))]
fn push_json_set_slots<V, C, Db, L>(
  comparison: &SqlSetComparison<V, C, Db>,
  at: At<'_>,
  out: &mut SqlConjunction<'_, Db>,
  leaf: L,
) where
  Db: sqlx::Database,
  V: JsonElement,
  L: Fn(&mut sqlx::QueryBuilder<Db>, At<'_>, CollectionOp, &str, bool),
{
  let mut slot = |values: &Option<Box<[V]>>, op, negated| {
    if let Some(elements) = values {
      let json = json_elements(elements);
      leaf(out.open(), at, op, &json, negated);
    }
  };
  slot(&comparison.eq, CollectionOp::SetEq, false);
  slot(&comparison.ne, CollectionOp::SetEq, true);
  slot(&comparison.encloses, CollectionOp::Encloses, false);
  slot(&comparison.enclosed_by, CollectionOp::EnclosedBy, false);
  slot(&comparison.overlaps, CollectionOp::Overlaps, false);
  push_json_membership(comparison.has_element.as_ref(), at, out, leaf);
}

/// The `has_element` slot both walks end with.
///
/// Membership IS containment of the singleton, so it needs no operator of its own — and it encodes
/// through the same writer, which is what keeps its token identical to the one the same value would
/// carry inside a list operand. Both kinds reach it, because the question is the same one whether
/// the column's order is meaningful.
// Gated with its only callers, the two walks above.
#[cfg(any(feature = "sqlite", feature = "mysql"))]
fn push_json_membership<V, Db, L>(
  element: Option<&V>,
  at: At<'_>,
  out: &mut SqlConjunction<'_, Db>,
  leaf: L,
) where
  Db: sqlx::Database,
  V: JsonElement,
  L: Fn(&mut sqlx::QueryBuilder<Db>, At<'_>, CollectionOp, &str, bool),
{
  if let Some(element) = element {
    let json = json_elements(core::slice::from_ref(element));
    leaf(out.open(), at, CollectionOp::Encloses, &json, false);
  }
}

/// MySQL has a native `JSON` type and the `JSON_CONTAINS` / `JSON_OVERLAPS` functions over it.
#[cfg(feature = "mysql")]
mod mysql;

/// Postgres has a native `ARRAY` type, its containment operators (`@>` `<@` `&&`) and an
/// element-wise `<` — so both lowerings here bind the operand's ELEMENTS as one array and ask the
/// engine directly. Nothing on this path is JSON.
///
/// # The bound that could not be asked for before
///
/// `V: PgHasArrayType` is declared by sqlx-postgres and by no other driver: it is the row that names
/// the array type OID an element lives in, and it is what makes `push_bind(&[V])` type as
/// `V[]` rather than fail. A single `impl<…, Db> ComplexComparison<Db>` had no way to require it, which
/// is the whole reason the collection kind lowered through `jsonb` here — an encoding chosen by the
/// impl shape rather than by anything about Postgres.
///
/// An element type with no `PgHasArrayType` row therefore has no ARRAY lowering on this dialect,
/// and the omission is an unsatisfied bound naming the missing trait. Such a type reaches an edge
/// table instead — [`PgCollectionStorage`] is where it says so — but naming these kinds for it
/// directly still does not compile, and [`BeU64`](crate::BeU64) is the case that actually occurs:
/// this crate's own blob carrier, which binds fine as a SCALAR and which sqlx names no array type
/// for.
///
/// ```compile_fail,E0599
/// use ingraph::{
///   At, BeU64, ComplexComparison, FieldName, RecordAddress, SetFilter, TryFromFilter,
///   comparison::sql::{SqlConjunction, SqlScalarComparison, SqlSetComparison},
/// };
///
/// type Element = SqlScalarComparison<BeU64, sqlx::Postgres>;
/// let c = SqlSetComparison::<BeU64, Element, sqlx::Postgres>::try_from_filter(
///   SetFilter::<u64>::new().with_encloses([1u64]),
/// )
/// .unwrap();
/// let mut qb = sqlx::QueryBuilder::<sqlx::Postgres>::default();
/// const ROW: RecordAddress = RecordAddress::new(FieldName::new("t"), &[FieldName::new("id")]);
/// let out = SqlConjunction::with_lead(&mut qb, "");
/// let frame = At::new(&ROW).frame(FieldName::new("t"));
/// c.apply(frame.at(), out).unwrap();
/// ```
///
/// Its twin, which must COMPILE — stable rustdoc runs a `compile_fail` block just far enough to see
/// it fail and never checks why, so the pair shares its call shape and one half has to be positive:
///
/// ```
/// use ingraph::{
///   At, ComplexComparison, FieldName, RecordAddress, SetFilter, TryFromFilter,
///   comparison::sql::{SqlConjunction, SqlScalarComparison, SqlSetComparison},
/// };
///
/// type Element = SqlScalarComparison<i64, sqlx::Postgres>;
/// let c = SqlSetComparison::<i64, Element, sqlx::Postgres>::try_from_filter(
///   SetFilter::<i64>::new().with_encloses([1i64]),
/// )
/// .unwrap();
/// let mut qb = sqlx::QueryBuilder::<sqlx::Postgres>::default();
/// const ROW: RecordAddress = RecordAddress::new(FieldName::new("t"), &[FieldName::new("id")]);
/// let out = SqlConjunction::with_lead(&mut qb, "");
/// let frame = At::new(&ROW).frame(FieldName::new("t"));
/// c.apply(frame.at(), out).unwrap();
/// assert_eq!(qb.sql(), "\"t\" @> $1");
/// ```
///
/// # `ARRAY` is ordered, which is what lets one column shape carry both kinds
///
/// A Postgres array keeps its element order, so a sequence's equality is `=` and a set's is mutual
/// containment. The JSON dialects make the same split for the same reason, under other spellings.
#[cfg(feature = "postgres")]
mod postgres;

/// SQLite has no array type and no `JSON` type: a collection column is TEXT holding a JSON array,
/// and every element question is a `json_each` set expression over it.
#[cfg(feature = "sqlite")]
mod sqlite;

#[cfg(test)]
mod tests;