ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
//! The collection kinds' second storage strategy: [`SqlEdgeComparison`] for a sequence and
//! [`SqlEdgeSetComparison`] for a set.
//!
//! # Why a collection has four comparison types and not one impl per dialect
//!
//! Two of the four axes are here. The first is what is STORED: SQLite and MySQL — which have no
//! array type — keep a value list in a second table, one row per element, and Postgres keeps it in a
//! native `ARRAY` column for the elements an array can hold and in this table for the rest. A
//! comparison over a column and a comparison over a correlated table do not differ in their SQL; they
//! differ in what they must be told, and a correlated one has to be told the row's table and its key
//! columns that a column name alone does not carry.
//!
//! Putting those on the column-stored kinds would leave them dead on every dialect that keeps a
//! value list in its own column. So the strategy is the TYPE, the per-dialect choice between them is
//! [`CollectionStorage`](super::CollectionStorage), and
//! [`ToDatabaseComparison`](crate::ToDatabaseComparison) — whose `Comparison` is already keyed on
//! `Db` — is where the choice lands. What these kinds need and the others do not is the ROW, and
//! that arrives with every application through [`At`] rather than being held here, so no other kind
//! pays for it beyond a parameter it ignores.
//!
//! The second axis is the collection's SHAPE, and under an edge table it decides a STORAGE fact
//! rather than only a rendering: a sequence's rows carry an ORDINAL column and a set's do not, its
//! rows being `(key…, value)` unique. That is why the two kinds here are two types and not one with
//! a marker — [`Scope`] derives three names and [`OrderedScope`] a fourth, and the fourth is
//! unspellable on a set's table.
//!
//! ```text
//! sequence   <table>_<field>:  (key…, <field>_ordinal, <field>)
//!               PRIMARY KEY    (key…, <field>_ordinal)   -- order and duplicates preserved
//!               INDEX          (key…, <field>)           -- containment seeks
//!
//! set        <table>_<field>:  (key…, <field>)
//!               PRIMARY KEY    (key…, <field>)           -- membership unique, order absent
//! ```
//!
//! **Ordinals are 0-based and dense.** Every positional form below reads them, and a writer that
//! numbers from one answers a different question under the same operator name.
//!
//! # These are GENERIC over the dialect, where the column-stored kinds are three impls each
//!
//! Measured on SQLite 3.51.0, PostgreSQL 16.14 and MySQL 8.4.11: every form below parses and answers
//! the same question in all three. `EXISTS`, `IN`, a row-value `(a, b) IN ((?, ?), …)`, a `COALESCE`
//! over a scalar subquery with `ORDER BY … LIMIT 1`, and a `UNION ALL` derived table whose columns
//! are BOUND parameters are one spelling everywhere — the last of those being the one worth naming,
//! since MySQL types a parameter from its context and a derived table's select list gives it none.
//! The whole bound is `V: Carrier<Db>`, which is what [`SqlKeyIn`](super::SqlKeyIn) already asks
//! for.
//!
//! The column-stored kinds need three impls each because `V: PgHasArrayType` is a bound one dialect
//! can carry and the others cannot. Nothing here is like that, so under this family's rule —
//! *non-uniform gets one impl per backend* — a uniform strategy takes one generic impl.
//!
//! # What was measured, and how a wrong answer here would look
//!
//! Every form below renders plausible SQL when it is wrong, which is the defect class this whole
//! layer keeps finding: the text reads correctly, the bind count matches, and the row set is
//! different. So the check is not on the text. Against all three engines, the operators over both
//! shapes were asked of a corpus of stored collections — empty, duplicated, reordered, of several
//! lengths — and their answers compared against the same question computed in Rust from the data; on
//! Postgres, the column-stored kinds were asked the SAME questions over the SAME rows, so the two
//! strategies are compared with the engine held constant. All three engines and both lowerings admit
//! the same rows, and Postgres's native array ordering is what fixes the meaning the ordering family
//! below has to reproduce.
//!
//! That comparison is sensitive rather than merely green, and each of four mutations shows up in
//! it: correlating the edge table to itself instead of to the parent, numbering ordinals from one,
//! giving `gte` a strict length test, and rendering `encloses` as `overlaps`. The first is the one
//! to keep in mind — it is well-formed SQL that turns every operator into a question about the whole
//! edge table.
//!
//! Postgres therefore has these lowerings for every element and not only for the ones its array
//! cannot hold, and that is not an accident kept by accident: it is what makes the engine constant
//! in that comparison, and it is what lets an element type with a perfectly good array type name
//! this strategy anyway — see [`PgCollectionStorage`](super::PgCollectionStorage).
//!
//! # Why every operator is an `EXISTS` and not a scan
//!
//! The JSON forms a value list would otherwise take on SQLite and MySQL all WORK — they are the
//! column-stored kinds' impls for those two dialects, which is what a collection already held as a
//! JSON array is still compared through. What they cannot do is use an INDEX: `json_each` is a
//! table-valued function, so SQLite's form is a full scan with a JSON parse per row, and
//! `JSON_CONTAINS` on a plain `JSON` column is not sargable on MySQL either. An edge table indexed
//! `(key…, value)` answers containment with a seek. SQLite is this project's primary database, so
//! the default cannot be the form that scans it.
//!
//! # The names this module derives rather than invents
//!
//! Every name here comes out of the one [`At`] a lowering is handed. The key columns and the table
//! the predicate correlates BACK to are the row's, read off [`RecordAddress`](crate::RecordAddress).
//! The value column is the one this address names, rendered by the backend exactly as
//! [`ComplexComparison::apply`](crate::ComplexComparison::apply) says; the ordinal column is one
//! frame below it; and the edge TABLE is [`edge_table`]'s, which is a join over a different
//! namespace and therefore its own operation. So the only naming rules here are ones the crate
//! already has, and every party that has to spell an edge table's names the same way can — because
//! all three names are stated as OPERATIONS rather than as a convention to reproduce.
//!
//! # Who the parties are, and what each does with the same three names
//!
//! | party | what it makes of them |
//! |---|---|
//! | the two kinds here | the correlated `EXISTS` every operator lowers to |
//! | [`hydrate`](crate::query::sql) | the aggregate on a page's SELECT list, and the gather beside it |
//! | `ingraph-codegen`'s query face | the plan a generated row STATES — one path per collection column, from which the engine makes the rest |
//! | the caller's own migration | the `CREATE TABLE` the other three read |
//!
//! Three of the four DERIVE, and the derivation is the same one: none of them joins a name by hand,
//! so none of them can drift from another. What the fourth has is a text, which is why it is the one
//! that can be wrong — and a first-party DDL emitter, when it arrives, is the fifth party and the
//! one that closes that gap by deriving where the migration writes.
//!
//! The codegen party is worth naming because it is the newest and the most easily mistaken for a
//! second convention: what it emits is a PATH — the collection column's own name in this database —
//! and `edge_table`, the `<field>_ordinal` frame and the parent key columns are all made from it
//! HERE. A plan naming the wrong path is therefore a wrong TABLE rather than a subtly wrong
//! statement, which is the failure mode worth having: measured on SQLite, a plan handed
//! `<field>_ordinal` where the value column belongs answers `no such table: splice_tags_ordinal`
//! rather than a quietly wrong collection.
//!
//! It is also the operation that REFUSES. An edge table holds a FIELD's elements, so an address
//! naming no field has none, and both kinds return
//! [`SqlLoweringError::EdgeWithoutField`](super::SqlLoweringError::EdgeWithoutField) there rather
//! than rendering — the one address at which a correlation would have been well-formed and constant
//! instead of unparseable.
//!
//! What that costs is a table whose name is not the schema's to choose: an edge table is the row's
//! table run together with the column's path and nothing else. It buys the thing the strategy could
//! not otherwise have — an address a filter never had to carry.

use core::marker::PhantomData;

use smol_bytes::Utf8BytesMut;

use super::{
  Carrier, ELEMENT_ALIAS, ELEMENT_VALUE, ListCrossingError, QuoteIdent, SetCrossingError,
  SqlConjunction, SqlCountComparison, SqlLoweringError, StrategyOver,
  collection::{cross_count, cross_element, flatten_list, flatten_set},
  dialect::{push_quoted_ident, push_quoted_qualified, push_quoted_scope},
  not_wrapped, push_count_slots, push_element_scope, quote_ident, quote_qualified,
};
use crate::{
  FieldName, ListFilter, QuantifiedFilter, SetFilter, TryMapFilter,
  comparison::{At, Backend, ComplexComparison, Path, TryFromFilter},
};

comparison_kind! {
  /// A [`ListFilter`]'s storage-side twin for a SEQUENCE kept in an edge table: the same nine
  /// operators, over the element type this database stores the members as.
  ///
  /// # What each operator becomes
  ///
  /// | operator | form | seeks `(key…, value)` |
  /// |---|---|---|
  /// | `has_element` | `EXISTS (… AND value = ?)` | yes |
  /// | `eq` / `ne` | `NOT EXISTS (… AND (ordinal, value) NOT IN ((?, ?), …))` and a row count | the anti-join scans this parent's rows |
  /// | `gt` / `gte` / `lt` / `lte` | the first differing ordinal, then the lengths | no — an ordering reads every element |
  /// | `any` | `EXISTS (SELECT 1 FROM ( <this parent's elements, projected> ) AS __ig_element_0__ WHERE …)` | whatever the ELEMENT comparison asks for |
  /// | `count` | the correlated `(SELECT COUNT(*) …)`, under the scalar operators | no — a count reads every element |
  ///
  /// The last two are the two slots that hold a whole COMPARISON rather than an operand, and neither
  /// is a question about this shape: `any` and `count` are on the set kind too, spelled identically.
  ///
  /// # The ordering family is expressible here, and that is a change worth stating
  ///
  /// On SQLite and MySQL these four had no answer at all: both stored a collection as JSON, JSON has
  /// no element-wise collection order, and the crossing refused them —
  /// [`ListCrossingError::JsonOrdering`]. An ordinal column is exactly the missing thing, so an
  /// edge-table sequence ANSWERS them, and it answers them with the same semantics Postgres's native
  /// array `<` has: compare element-wise at the first position where the two differ, and if neither
  /// runs out of matching elements first, compare the lengths.
  ///
  /// So this crossing refuses nothing structural on any dialect, and the reason it once did — an
  /// unordered column has no stored order to read — is now a different type with no ordering slot.
  ///
  /// # The bind count DOES follow the operand's length here
  ///
  /// That is the trade the strategy makes, and it is the opposite of the column-stored kinds': an
  /// array operand is bound as ONE parameter however many elements it holds, while an edge-table
  /// predicate binds each element separately, because each is compared to a stored row. The count is
  /// one bind per element — two for the positional forms, which bind an ordinal beside each value,
  /// plus one for the length — so it is exactly the arithmetic [`push_in`](super::push_in) has, and
  /// it takes no ceiling for the same reason: the number a caller passes IS the number that reaches
  /// the limit, where [`SqlKeyIn`](super::SqlKeyIn)'s is multiplied by a width the caller did not
  /// choose.
  ///
  /// # It holds OPERATORS, and where they are evaluated arrives with the application
  ///
  /// This comparison used to be constructed with its addressing — the parent's table, the edge table
  /// and the key columns — and its own doc drew a ruling from that: *"it is constructed with its
  /// addressing, so [`TryFromFilter`] is not its crossing"*. The observation was right and **the
  /// ruling was wrong.** `TryFromFilter` takes a filter and nothing else, and none of those three is
  /// in a filter; what was missing was not the capability but a CHANNEL for the addressing.
  ///
  /// [`At`] is that channel. It arrives at [`apply`](ComplexComparison::apply), where the caller
  /// already hands down the schema knowledge a column name is, so this kind's crossing is now the
  /// same one every other kind has. That is what makes an entity with a collection column reachable
  /// from a GraphQL filter at all: a generated comparison composes its fields' crossings, and one
  /// field that could not cross refused the whole entity rather than only itself.
  ///
  /// The property that replaces the old one is the stronger one: a comparison built from a filter
  /// alone can be applied against ANY row the caller names, because the row was never in it.
  ///
  /// [`ListCrossingError::JsonOrdering`]: super::ListCrossingError::JsonOrdering
  /// [`TryFromFilter`]: crate::TryFromFilter
  SqlEdgeComparison {
    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 an edge table: the same eight operators,
  /// over the element type this database stores the members as.
  ///
  /// # What each operator becomes
  ///
  /// | operator | form | seeks `(key…, value)` |
  /// |---|---|---|
  /// | `has_element` | `EXISTS (… AND value = ?)` | yes |
  /// | `encloses` | one `EXISTS (… AND value = ?)` per element, `AND`ed | yes |
  /// | `overlaps` | `EXISTS (… AND value IN (?, …))` | yes |
  /// | `enclosed_by` | `NOT EXISTS (… AND value NOT IN (?, …))` | the anti-join scans this parent's rows |
  /// | `eq` / `ne` | `encloses` and `enclosed_by` together | as above |
  /// | `any` / `count` | the sequence kind's, unchanged | as there |
  ///
  /// # A separate kind because the TABLE is a different shape
  ///
  /// Everywhere else the two collection shapes guard one physical column and differ in which
  /// operators reach it. Here they do not: a sequence's edge rows carry an ordinal and a set's do
  /// not, so [`Scope`] — the three names every form below renders — has nothing to say about an
  /// ordinal and this kind never names one. The sequence kind reads a fourth name through
  /// [`OrderedScope`], which is where the ordinal is derived and the only place it is.
  ///
  /// # The bind count DOES follow the operand's length here
  ///
  /// One bind per element, for the reason the sequence kind's does: each element is compared to a
  /// stored row rather than shipped as one array operand. Set equality binds the operand twice, once
  /// for each direction of the mutual containment.
  ///
  /// The two nested slots are the exception in both directions. `any` binds whatever the ELEMENT
  /// comparison binds, which is that kind's arithmetic and not this one's, and `count` binds one
  /// integer per operator whatever the collection holds.
  SqlEdgeSetComparison {
    one { has_element }
    many { eq, ne, encloses, enclosed_by, overlaps }
    element { any: C }
    cardinality { count }
  }
}

impl<V, C, Db> SqlEdgeComparison<V, C, Db> {
  /// Cross a [`ListFilter`] into an edge-table sequence comparison through ONE converter, which
  /// carries this collection's own operands and the ones inside its `any` filter alike.
  ///
  /// **This is where a DECLARED operand converter enters**, and one function is what a declaration
  /// gets because one function is what a declaration IS: it names the hop from a domain element to
  /// the form this column stores, and every operand a collection filter carries — its own, and the
  /// nested filter's — is made of that same element. So the declaration fills both slots of
  /// [`try_from_filter_with_element`](Self::try_from_filter_with_element) and a caller writes it
  /// once.
  ///
  /// It is also what lets a caller cross a column WITHOUT knowing its kind: this signature is the
  /// flat kinds' signature, so one call site serves a scalar column and a collection alike and the
  /// compiler dispatches.
  ///
  /// The nested filter's operands are the converter's too, so a refusal there is
  /// [`ListCrossingError::Operand`] — what the converter refused is an element whichever level it
  /// was written at. [`ListCrossingError::Element`] stays the ELEMENT COMPARISON's own refusal,
  /// which is the identity crossing once the operands have already arrived in storage form.
  ///
  /// The converter is `Fn` where the two-function entry takes `FnMut`, and the reason is the
  /// composition rather than taste: ONE converter has to be live at two slots of the same call, so
  /// it is passed by shared reference to both. A declared converter is a function item and satisfies
  /// it; a converter carrying state between calls is the one shape that has to name its two hops
  /// separately.
  ///
  /// Nothing here runs before the kind's own refusals do. The element filter crosses inside the
  /// `g` slot, which is where the two-function entry already put it, so a dialect that declines an
  /// OPERATOR still declines it before any operand converts.
  ///
  /// # 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: ListFilter<D, VF>,
    f: F,
  ) -> Result<Self, ListCrossingError<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(ListCrossingError::Operand)?;
      C::try_from_filter(stored).map_err(ListCrossingError::Element)
    })
    .map_err(flatten_list)
  }

  /// Cross a [`ListFilter`] into an edge-table sequence comparison, converting each ELEMENT with
  /// `f` and the nested ELEMENT FILTER with `g`.
  ///
  /// Dialect-free, where the column-stored kind's crossings each name their database: an ordinal
  /// column answers the ordering family on every engine and a derived table is an element scope on
  /// every engine, so this strategy has nothing of its own to refuse.
  ///
  /// # Errors
  ///
  /// [`ListCrossingError::Operand`] when `f` refuses an element and [`ListCrossingError::Element`]
  /// when the element filter's own crossing refuses. The error type is the kind's rather than `f`'s
  /// own so that a caller crossing a [`ListFilter`] writes one match arm whichever strategy stores
  /// the column.
  ///
  /// `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. This entry is what remains for
  /// the caller whose two hops really are two functions.
  pub fn try_from_filter_with_element<D, VF, E, F, X, G>(
    filter: ListFilter<D, VF>,
    f: F,
    g: G,
  ) -> Result<Self, ListCrossingError<E, X>>
  where
    F: FnMut(D) -> Result<V, E>,
    G: FnOnce(VF) -> Result<C, X>,
  {
    let stored = filter.try_map(f).map_err(ListCrossingError::Operand)?;
    let any = cross_element(stored.any, g).map_err(ListCrossingError::Element)?;
    let count = cross_count(stored.count).map_err(ListCrossingError::Cardinality)?;
    Ok(Self {
      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> SqlEdgeSetComparison<V, C, Db> {
  /// Cross a [`SetFilter`] into an edge-table set comparison through ONE converter — see
  /// [`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 an edge-table set comparison, converting each ELEMENT with `f` and
  /// the nested ELEMENT FILTER with `g`.
  ///
  /// # Errors
  ///
  /// [`SetCrossingError::Operand`] for whatever `f` refuses an element with, and
  /// [`SetCrossingError::Element`] for whatever the ELEMENT filter's own crossing refuses. No
  /// dialect or strategy declines an OPERATOR a set carries.
  ///
  /// `g` crosses the ELEMENT filter, and it is a second function rather than a use of `f` because
  /// the two convert different things — see
  /// [`SqlEdgeComparison::try_from_filter_with_element`], whose note this shares.
  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 stored = filter.try_map(f).map_err(SetCrossingError::Operand)?;
    let any = cross_element(stored.any, 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 edge-table sequence kind re-stated is that kind: the dialect keeps, and only the element
/// moves. The table a comparison correlates against is addressing rather than type — it arrives
/// through [`At`] — so there is nothing here for it to carry.
impl<V, C: StrategyOver<W>, Db, W> StrategyOver<W> for SqlEdgeComparison<V, C, Db> {
  type Comparison = SqlEdgeComparison<W, C::Comparison, Db>;
}

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

/// The identity crossing for an edge-table sequence — a `Vec<String>` whose elements are stored as
/// `TEXT` is the common one.
///
/// This is the impl the whole [`At`] design exists to make writable, and it is generic over the
/// dialect because the crossing is: which strategy stores a collection is
/// [`CollectionStorage`](super::CollectionStorage)'s answer, and by the time a filter reaches here
/// it has been given.
///
/// # Errors
///
/// As [`try_from_filter_with_element`](SqlEdgeComparison::try_from_filter_with_element).
impl<D, VF, V: TryFrom<D>, C: TryFromFilter<VF>, Db> TryFromFilter<ListFilter<D, VF>>
  for SqlEdgeComparison<V, C, Db>
{
  type Error = ListCrossingError<V::Error, C::Error>;

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

/// The NARROW crossing into an edge-table sequence comparison — the strategy the two JSON dialects
/// keep every collection in, so this is the impl a quantified column reaches on SQLite and MySQL.
///
/// Its twin one module over — the column-stored sequence kind's — carries the whole argument: the
/// two arms are [`cross_element`] and [`cross_count`] CALLED rather than restated, the seven element
/// slots stay unset structurally because nothing writes them, and the error is the wide kind's at an
/// uninhabited `E`. See
/// [`SqlListComparison`](super::SqlListComparison)'s row.
///
/// # Errors
///
/// [`ListCrossingError::Element`] for whatever the element filter's own crossing refuses, and
/// [`ListCrossingError::Cardinality`] for a `count` operand past this family's integer. The other
/// two variants cannot arrive — one is uninhabited here, and one names operators this kind has not
/// got.
impl<D, VF, V, C: TryFromFilter<VF>, Db> TryFromFilter<QuantifiedFilter<D, VF>>
  for SqlEdgeComparison<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 identity crossing for an edge-table set.
///
/// # Errors
///
/// As [`try_from_filter_with_element`](SqlEdgeSetComparison::try_from_filter_with_element).
impl<D, VF, V: TryFrom<D>, C: TryFromFilter<VF>, Db> TryFromFilter<SetFilter<D, VF>>
  for SqlEdgeSetComparison<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)
  }
}

/// ONE impl for every dialect, because the forms below are one spelling everywhere and the whole
/// bound is `V: Carrier<Db>` — the arrangement [`SqlKeyIn`](super::SqlKeyIn) has, for the same
/// reason and measured the same way.
///
/// `i64: Carrier<Db>` is the second half of that bound and it carries no dialect either: the
/// positional forms bind an ORDINAL beside each value and a row COUNT beside the length test, and
/// both are integers this crate computed. They bind rather than being written into the text because
/// this family's rule about operands has no exception for an operand the crate produced itself.
///
/// The refusal is PINNED to [`SqlLoweringError`], as [`SqlKeyIn`](super::SqlKeyIn)'s is and for the
/// same reason: 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. What it refuses is the ADDRESS rather than the operand
/// — see [`edge_table`].
///
/// # The BUFFER is pinned too, and these two kinds are the only ones that pin it
///
/// Every uniform kind asks [`Backend<Buffer: Display>`](crate::Backend::Buffer) — the one capability
/// [`sqlx::QueryBuilder::push`] costs — and so stays open to a backend rendering into something that
/// is not this family's buffer. The correlated kinds cannot: [`Scope`] holds its three finished
/// names as [`Utf8BytesMut`] and derives them with [`split`](Utf8BytesMut::split), which is an
/// INHERENT method rather than a trait's, so there is no bound to ask for instead. Widening it would
/// mean a `Scope<B>` over a trait for splitting a buffer in place, and neither `core` nor `std`
/// declares one.
///
/// The cost is that a hand-written CORRELATED comparison generic over the dialect restates the
/// equality. That is the honest price of the one thing this kind does that the others do not.
impl<V, C, Db> ComplexComparison<Db> for SqlEdgeComparison<V, C, Db>
where
  Db: sqlx::Database
    + QuoteIdent
    + for<'q> Backend<
      Builder<'q> = SqlConjunction<'q, Db>,
      Error = SqlLoweringError,
      Buffer = Utf8BytesMut,
    >,
  V: Carrier<Db>,
  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 scope = OrderedScope::new::<Db>(at)?;
    push_sequence_slots(self, &scope, &mut builder);
    push_edge_any::<C, Db>(self.any.as_ref(), at, &scope.scope, &mut builder)?;
    push_edge_count(self.count.as_ref(), &scope.scope, &mut builder);
    Ok(builder)
  }
}

/// The set kind's impl, generic for the same reason and under the same bounds. `i64: Carrier<Db>` is
/// here because the CARDINALITY slot binds one: no ORDINAL reaches this kind — a set's table has
/// none — but *how many* is a number on either shape, so the bound the sequence kind carried for its
/// positions is now carried by both for their lengths.
impl<V, C, Db> ComplexComparison<Db> for SqlEdgeSetComparison<V, C, Db>
where
  Db: sqlx::Database
    + QuoteIdent
    + for<'q> Backend<
      Builder<'q> = SqlConjunction<'q, Db>,
      Error = SqlLoweringError,
      Buffer = Utf8BytesMut,
    >,
  V: Carrier<Db>,
  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 scope = Scope::new::<Db>(at)?;
    push_set_slots(self, &scope, &mut builder);
    push_edge_any::<C, Db>(self.any.as_ref(), at, &scope, &mut builder)?;
    push_edge_count(self.count.as_ref(), &scope, &mut builder);
    Ok(builder)
  }
}

/// The three names every edge-table 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 whole of what a correlation
/// is — two qualified names per key column and the ` AND ` between them — is built once here and
/// pushed as a unit by each form below.
///
/// # All of them come out of ONE buffer
///
/// The edge table's bracketed name appears in every field here — `FROM <table>`, the qualifier on
/// each side of the correlation, and the qualifier on the value column — so a scope over a
/// single-key row writes it three times, and the sequence kind's fourth name writes it again.
/// [`Scope::with_edge`] renders them into one [`Utf8BytesMut`] and [`splits`](Utf8BytesMut::split)
/// each off as it is finished, so the next begins in what the split left behind. Splitting rather
/// than concatenating is what keeps each name inside the inline range that a single joined buffer
/// would leave; above it they share one allocation instead of taking one each.
///
/// Measured on a `media` row with a `tags` edge, crossing a one-element set filter and rendering
/// it: 17 allocations before and 4 after, and 26 against 7 where the row has two key columns. What
/// remains is the operand's own.
/// `pub(super)` on the TYPE and on the two names the composite kind spends, and on nothing else:
/// its `value` is the SCALAR element's one column and has no reader there, and both constructors
/// are called from inside this module. The widening is exactly the surface [`SegmentScope`] hands
/// over.
pub(super) struct Scope {
  /// The edge table, bracketed — what each `FROM` names and what each column below qualifies with.
  pub(super) table: Utf8BytesMut,
  /// The value column, qualified and bracketed.
  value: Utf8BytesMut,
  /// `<edge>."k" = <parent>."k"` for every key column, joined with ` AND `.
  pub(super) correlation: Utf8BytesMut,
}

/// A [`Scope`] over a SEQUENCE's edge table, which has one column more.
///
/// The ordinal is derived here and nowhere else, which is what makes "a set's table has no ordinal"
/// a fact about the types rather than a rule to remember: the set kind builds a [`Scope`], so no
/// form it reaches has a name to misuse.
struct OrderedScope {
  scope: Scope,
  /// The ordinal column, qualified and bracketed.
  ordinal: Utf8BytesMut,
}

/// What the derived table an ordering renders its operand as is called, and the two columns it
/// projects.
///
/// A LITERAL for the reason [`ELEMENT_ALIAS`](super::ELEMENT_ALIAS) is one: it stands for no table,
/// so a mint keyed on a table name and a depth has nothing to be a function of here. It is an ALIAS
/// rather than a schema name — scoped to the subquery it appears in, so it can collide with nothing
/// the caller declared, and qualified at every use, so it cannot be confused with the edge table's
/// own columns.
///
/// Its depth reads `0` on a stronger ground than the element scope's: this one cannot NEST at all.
/// [`push_ordering`] is handed a slice of operand values rather than a comparison, so nothing
/// renders inside the subquery that could open a second operand table. Which matters, because unlike
/// the element scope's this alias IS referenced — both columns below qualify with it — so shadowing
/// would be a wrong answer rather than a harmless one. There is simply nothing to shadow it.
const OPERAND_ALIAS: &str = "__ig_operand_0__";
/// The alias's ordinal column, joined against the stored ordinal.
const OPERAND_ORDINAL: &str = "ordinal";
/// The alias's value column, compared against the stored value.
const OPERAND_VALUE: &str = "value";

impl Scope {
  /// Derive the addressing every form shares from where the predicate is applied.
  ///
  /// Neither name is invented here: the edge table is [`edge_table`]'s, and the value column is the
  /// one this address names, qualified by the table holding it. The third thing a correlation needs
  /// — the key columns — is read off the row, which is the only part of the addressing that is data
  /// rather than a derivation.
  ///
  /// # Errors
  ///
  /// As [`edge_table`], and BEFORE any slot is walked — so an address the strategy has no table for
  /// is refused whatever the comparison holds, and a refusal leaves the accumulator as it was found.
  fn new<Db: QuoteIdent + Backend<Buffer = Utf8BytesMut>>(
    at: At<'_>,
  ) -> Result<Self, SqlLoweringError> {
    let edge = edge_table(at)?;
    let mut names = Db::buffer();
    Ok(Self::with_edge::<Db>(
      at,
      FieldName::new(&edge),
      at.parent_keys(),
      &mut names,
    ))
  }

  /// The same, with the edge table's name already derived and the buffer handed in — so
  /// [`OrderedScope`] derives the table once for both the shared addressing and its own ordinal
  /// column, and takes its fourth name out of the same buffer as the first three.
  fn with_edge<Db: QuoteIdent + Backend<Buffer = Utf8BytesMut>>(
    at: At<'_>,
    edge: &FieldName,
    parent: Option<&[&'static FieldName]>,
    names: &mut Utf8BytesMut,
  ) -> Self {
    push_quoted_ident::<Db>(edge, names);
    let table = names.split();

    for (i, key) in at.record().keys().iter().enumerate() {
      if i > 0 {
        names.push_str(" AND ");
      }
      push_quoted_qualified::<Db>(edge, key, names);
      names.push_str(" = ");
      // The PARENT side wears whatever the enclosing `FROM` called it — its own table at the
      // statement's level, and a relation's alias inside one. The edge table above is DERIVED from
      // the real name and is not a scope, so it takes `edge` rather than the qualifier.
      //
      // And it wears whatever that scope calls the COLUMN, which is the second half of the same
      // question — see [`At::parent_keys`]. The two sides were always two facts: an edge table's
      // parent-key column is named after the row's address column, and the parent qualifier's
      // column is named whatever the parent scope projects. A scope selecting the row's own table
      // makes them one string, which is why one name served until a UNION's arms projected every
      // member's address `AS "id"`.
      push_quoted_scope::<Db>(at.qualifier(), parent_key(parent, i, key), names);
    }
    let correlation = names.split();

    push_qualified_column::<Db>(edge, at, names);
    let value = names.split();

    Self {
      table,
      value,
      correlation,
    }
  }
}

impl OrderedScope {
  /// The shared addressing plus the ordinal column, which is one FRAME below the value column —
  /// the same relation a composite's parts have to the composite, so it needs no rule of its own.
  ///
  /// # Errors
  ///
  /// As [`Scope::new`].
  fn new<Db: QuoteIdent + Backend<Buffer = Utf8BytesMut>>(
    at: At<'_>,
  ) -> Result<Self, SqlLoweringError> {
    let edge = edge_table(at)?;
    let edge = FieldName::new(&edge);
    let ordinal = at.frame(FieldName::new("ordinal"));
    let mut names = Db::buffer();
    let scope = Scope::with_edge::<Db>(at, edge, at.parent_keys(), &mut names);
    push_qualified_column::<Db>(edge, ordinal.at(), &mut names);
    Ok(Self {
      scope,
      ordinal: names.split(),
    })
  }
}

/// A [`Scope`] over a COMPOSITE element's edge table, which has one value column per SEGMENT.
///
/// It is [`OrderedScope`]'s twin on the other axis. That one derives a fourth name a SET's table has
/// not got; this one derives the value column N times over where the shared scope derives it once,
/// and the two never meet: a composite element's operators are the three that read no ordinal, so
/// nothing here has an ordinal to want.
///
/// The columns are derived HERE, in the module that derives every other edge-table name, so the
/// naming contract this crate keeps — *three of the four parties DERIVE, and none of them joins a
/// name by hand* — gains a fifth column-shaped party rather than a second convention.
pub(super) struct SegmentScope {
  pub(super) scope: Scope,
  /// `<edge>."<field>_<leaf…>"` for every LEAF of the element, in the element type's own order.
  pub(super) columns: Vec<Utf8BytesMut>,
}

impl SegmentScope {
  /// The shared addressing plus one qualified column per LEAF of the element — each at the address
  /// the element's own shape puts it at below the collection's column, which is the relation a
  /// composite's parts already have to the composite and the same one the ordinal is derived
  /// through.
  ///
  /// # The LEAVES, not the parts — and the flattening is not this module's rule
  ///
  /// A part may itself be composite, so the walk is
  /// [`fold_leaves`](super::fold_leaves) — the ONE descent this family makes over a shape tree, which
  /// a row's own `SELECT` list and a composite operand's row value already take. A `Vec<Detection>`
  /// whose element flattens an identity therefore reaches `heard_language` and its siblings here for
  /// exactly the reason a DIRECT column of that element reaches them: the same segments, two
  /// spellings, one authority.
  ///
  /// # Errors
  ///
  /// As [`Scope::new`].
  pub(super) fn new<Db: QuoteIdent + Backend<Buffer = Utf8BytesMut>>(
    at: At<'_>,
    segments: &[crate::ColumnShape],
  ) -> Result<Self, SqlLoweringError> {
    let edge = edge_table(at)?;
    let edge = FieldName::new(&edge);
    let mut names = Db::buffer();
    let scope = Scope::with_edge::<Db>(at, edge, at.parent_keys(), &mut names);
    let mut columns = Vec::with_capacity(crate::width(segments));
    super::fold_leaves(at, segments, (), &mut |(), leaf| {
      push_qualified_column::<Db>(edge, leaf, &mut names);
      columns.push(names.split());
    });
    Ok(Self { scope, columns })
  }
}

/// The name of the table an edge-stored collection's elements are kept in: the ROW's table extended
/// by every segment of the column this address names, run together with `_`.
///
/// # A different join from [`Backend::write_column`]'s, though both spell `_` here
///
/// That one names a COLUMN — segments of one path inside one namespace — and this names a TABLE.
/// Reaching for the column renderer would make the two one operation, and then a backend that
/// nested its columns under some other character would rename every edge table as a side effect.
/// They agree today because SQL's namespace is flat; that is a coincidence of one family rather
/// than a shared rule.
///
/// # It is the whole PATH rather than its last segment
///
/// A table's name has to be as unique as the column set it stands for, and a leaf segment is not:
/// two composites of one row may each carry a `tags` field, and named from the leaf alone their
/// edge tables collide. The path is exactly what makes a column name unique in the flat namespace,
/// so it is exactly what makes the table's unique too — and for a column directly under the row it
/// is the one segment, so nothing about the ordinary case changes.
///
/// Public for the reason [`quote_ident`] is: a correlated kind declared downstream derives the same
/// name rather than restating the join.
///
/// # Errors
///
/// [`SqlLoweringError::EdgeWithoutField`] at the TOP LEVEL. An edge table holds a FIELD's elements
/// and the empty path names no field, so the join above would extend the row's table by nothing and
/// hand back the row's own name — under which every correlation built from it joins the row to
/// itself. There is no edge table at that address, which is why this answers with a refusal rather
/// than with a name.
pub fn edge_table(at: At<'_>) -> Result<Utf8BytesMut, SqlLoweringError> {
  let Some(path) = at.path() else {
    return Err(SqlLoweringError::EdgeWithoutField(at.record().table()));
  };
  let mut name = Utf8BytesMut::new();
  name.push_str(at.record().table());
  extend(path, &mut name);
  Ok(name)
}

/// What the PARENT scope calls the key column at `index` — the override where one was given for it,
/// and the row's own name otherwise.
///
/// Positional against [`RecordAddress::keys`](crate::RecordAddress::keys), so a list shorter than
/// the key leaves the columns past its end naming themselves: an override states the columns whose
/// two names DIFFER, and saying nothing about a column is saying they agree. Which is the same
/// answer the [`None`] case gives for every column, and is what keeps every record's lowering
/// byte-for-byte what it was.
#[inline]
fn parent_key<'a>(
  parent: Option<&[&'a FieldName]>,
  index: usize,
  own: &'a FieldName,
) -> &'a FieldName {
  match parent.and_then(|keys| keys.get(index)) {
    Some(key) => key,
    None => own,
  }
}

/// Every segment from the root down, each preceded by the `_` that joins it to what came before.
fn extend(path: &Path<'_>, out: &mut Utf8BytesMut) {
  if let Some(parent) = path.parent() {
    extend(parent, out);
  }
  out.push('_');
  out.push_str(path.name());
}

/// `<edge>.<column>` appended to `out` — one of the edge table's columns, qualified by it.
///
/// Composed rather than reached through [`quote_qualified`](super::quote_qualified), because the
/// halves are not the same kind of name: the qualifier is a TABLE, where the column is a path only
/// the backend renders.
fn push_qualified_column<Db: QuoteIdent + Backend<Buffer = Utf8BytesMut>>(
  edge: &FieldName,
  at: At<'_>,
  out: &mut Utf8BytesMut,
) {
  push_quoted_ident::<Db>(edge, out);
  out.push('.');
  Db::write_column(at, out);
}

/// The sequence kind's seven slots in the order the FILTER declares them — this strategy's walk for
/// that kind, held beside the impl rather than inside it so the order is one statement rather than
/// an inlined habit.
fn push_sequence_slots<V, C, Db>(
  comparison: &SqlEdgeComparison<V, C, Db>,
  scope: &OrderedScope,
  out: &mut SqlConjunction<'_, Db>,
) where
  Db: sqlx::Database + QuoteIdent,
  V: Carrier<Db>,
  i64: Carrier<Db>,
{
  for (slot, negated) in [(&comparison.eq, false), (&comparison.ne, true)] {
    if let Some(values) = slot {
      push_positional_whole(out.open(), scope, values, negated);
    }
  }
  // Element-wise and lexicographic, which is what a Postgres array's own comparison operators do
  // and what an ordinal column makes answerable here.
  for (slot, order) in [
    (&comparison.gt, CollectionOrder::Gt),
    (&comparison.gte, CollectionOrder::Gte),
    (&comparison.lt, CollectionOrder::Lt),
    (&comparison.lte, CollectionOrder::Lte),
  ] {
    if let Some(values) = slot {
      push_ordering(out.open(), scope, values, order);
    }
  }
  push_membership(comparison.has_element.as_ref(), &scope.scope, out);
}

/// The set kind's six slots, likewise.
fn push_set_slots<V, C, Db>(
  comparison: &SqlEdgeSetComparison<V, C, Db>,
  scope: &Scope,
  out: &mut SqlConjunction<'_, Db>,
) where
  Db: sqlx::Database + QuoteIdent,
  V: Carrier<Db>,
{
  for (slot, negated) in [(&comparison.eq, false), (&comparison.ne, true)] {
    if let Some(values) = slot {
      push_mutual_containment(out.open(), scope, values, negated);
    }
  }
  if let Some(values) = &comparison.encloses {
    push_encloses(out.open(), scope, values);
  }
  if let Some(values) = &comparison.enclosed_by {
    push_enclosed_by(out.open(), scope, values);
  }
  if let Some(values) = &comparison.overlaps {
    push_overlaps(out.open(), scope, values);
  }
  push_membership(comparison.has_element.as_ref(), scope, out);
}

/// The `has_element` slot both walks end with.
///
/// Membership IS containment of the singleton, so it needs no form of its own — and it takes the
/// same path, which is what keeps the two renderings identical rather than merely alike. It reads
/// only the shared [`Scope`], which is why a sequence answers it without its ordinal.
fn push_membership<V, Db>(element: Option<&V>, scope: &Scope, out: &mut SqlConjunction<'_, Db>)
where
  Db: sqlx::Database,
  V: Carrier<Db>,
{
  if let Some(element) = element {
    push_encloses(out.open(), scope, core::slice::from_ref(element));
  }
}

/// The `any` slot both walks end with: this parent's elements, PROJECTED under the one name every
/// element scope binds its member with, so the element comparison renders inside exactly as it does
/// over a `json_each` or an `unnest`.
///
/// ```text
/// EXISTS (SELECT 1 FROM ( SELECT <value> AS "value" FROM <edge> WHERE <correlation> )
///           AS "__ig_element_0__"[ WHERE <element predicates>])
/// ```
///
/// # The derived table is what makes the element's address an [`At`]
///
/// Every other form here names the value column QUALIFIED — `<edge>."tags"` — because the edge table
/// and the parent share their key column names and an unqualified reference would resolve to the
/// wrong one (see [`quote_qualified`]). An element comparison cannot render a qualified name: it is
/// handed an address and asks [`Backend::write_column`] for it, which joins a PATH inside one
/// namespace and has no qualifier to give. Renaming the column in a derived table moves the
/// qualification to where this module already does it and leaves the element comparison an ordinary
/// address — the alternative being to hand it a rendered string, which is the one thing the address
/// model exists to prevent.
///
/// It costs a subquery level and no correctness: the projection carries the correlation, so the
/// derived table holds exactly this parent's elements.
///
/// # Measured on all three engines
///
/// SQLite 3.51.0, PostgreSQL 14.23 and MySQL 8.4.11 each admit exactly the rows with a matching
/// element, including where the PARENT carries its own `value` column whose contents would have
/// matched — an unqualified name resolves to the innermost scope. MySQL is the one worth naming: a
/// correlated derived table survives its semijoin transform where a correlated `JSON_TABLE` does
/// not, which is why this strategy answers `any` on a dialect whose JSON columns cannot.
fn push_edge_any<C, Db>(
  element: Option<&C>,
  at: At<'_>,
  scope: &Scope,
  out: &mut SqlConjunction<'_, Db>,
) -> Result<(), Db::Error>
where
  Db: sqlx::Database
    + QuoteIdent
    + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer = Utf8BytesMut>,
  C: ComplexComparison<Db>,
{
  let Some(element) = element else {
    return Ok(());
  };
  push_element_scope(out.open(), element, at, |qb| {
    qb.push("( SELECT ");
    qb.push(&scope.value);
    qb.push(" AS ");
    qb.push(quote_ident::<Db>(ELEMENT_VALUE));
    qb.push(" FROM ");
    qb.push(&scope.table);
    qb.push(" WHERE ");
    qb.push(&scope.correlation);
    qb.push(" ) AS ");
    qb.push(quote_ident::<Db>(ELEMENT_ALIAS));
  })
}

/// The `count` slot both walks end with: the correlated `COUNT(*)` this strategy already builds, as
/// the left-hand side of a cardinality comparison.
///
/// ```text
/// (SELECT COUNT(*) FROM <edge> WHERE <correlation>) <op> ?
/// ```
///
/// It reads only the shared [`Scope`], so a sequence answers it without its ordinal — a cardinality
/// does not read positions. And it needs no `NULL` care at all, which is the one place this strategy
/// is simpler than a column: `COUNT(*)` over no matching rows is `0`, so a parent with no elements
/// answers `count: { eq: 0 }` with `true` where a Postgres array's `array_length` would answer
/// `NULL`. Measured on MySQL 8.4.11 against a fabricated edge table, and it is `COUNT(*)`'s defined
/// behaviour on all three.
///
/// [`push_count`] is the same expression the whole-sequence equality and the four orderings already
/// compare a length against, so a `count` operator and the length half of a `gt` read the same
/// number by construction.
pub(super) fn push_edge_count<Db>(
  count: Option<&SqlCountComparison<i64, Db>>,
  scope: &Scope,
  out: &mut SqlConjunction<'_, Db>,
) where
  Db: sqlx::Database,
  i64: Carrier<Db>,
{
  let Some(count) = count else {
    return;
  };
  push_count_slots(count, out, |qb| push_count(qb, scope));
}

/// `[NOT ]EXISTS (SELECT 1 FROM <edge> WHERE <correlation>[ <rest>])`.
fn push_exists<Db>(
  qb: &mut sqlx::QueryBuilder<Db>,
  scope: &Scope,
  negated: bool,
  rest: impl FnOnce(&mut sqlx::QueryBuilder<Db>),
) where
  Db: sqlx::Database,
{
  qb.push(if negated { "NOT EXISTS (" } else { "EXISTS (" });
  qb.push("SELECT 1 FROM ");
  qb.push(&scope.table);
  qb.push(" WHERE ");
  qb.push(&scope.correlation);
  rest(qb);
  qb.push(")");
}

/// `(SELECT COUNT(*) FROM <edge> WHERE <correlation>)` — how many elements this parent's collection
/// holds.
fn push_count<Db: sqlx::Database>(qb: &mut sqlx::QueryBuilder<Db>, scope: &Scope) {
  qb.push("(SELECT COUNT(*) FROM ");
  qb.push(&scope.table);
  qb.push(" WHERE ");
  qb.push(&scope.correlation);
  qb.push(")");
}

/// `<value> IN (?, …)`, or its negation — the membership of one stored element in the operand.
fn push_value_in<V, Db>(qb: &mut sqlx::QueryBuilder<Db>, scope: &Scope, values: &[V], negated: bool)
where
  Db: sqlx::Database,
  V: Carrier<Db>,
{
  qb.push(&scope.value);
  qb.push(if negated { " NOT IN (" } else { " IN (" });
  for (i, value) in values.iter().enumerate() {
    if i > 0 {
      qb.push(", ");
    }
    value.push_bind(qb);
  }
  qb.push(")");
}

/// The column's elements include every element of the operand: one indexed `EXISTS` per element.
///
/// An EMPTY operand is vacuously enclosed and renders `1 = 1`, which is the same reading
/// [`push_in`](super::push_in) gives an empty list — the operator is present with an operand that
/// asks nothing, where an absent `encloses` also asks nothing but by not being there.
///
/// One element renders the bare `EXISTS`, which is what makes `has_element` and a singleton
/// `encloses` the same rendering rather than two that agree.
fn push_encloses<V, Db>(qb: &mut sqlx::QueryBuilder<Db>, scope: &Scope, values: &[V])
where
  Db: sqlx::Database,
  V: Carrier<Db>,
{
  if values.is_empty() {
    qb.push("1 = 1");
    return;
  }
  let bracketed = values.len() > 1;
  if bracketed {
    qb.push("( ");
  }
  for (i, value) in values.iter().enumerate() {
    if i > 0 {
      qb.push(" AND ");
    }
    push_exists(qb, scope, false, |qb| {
      qb.push(" AND ");
      qb.push(&scope.value);
      qb.push(" = ");
      value.push_bind(qb);
    });
  }
  if bracketed {
    qb.push(" )");
  }
}

/// The operand's elements include every element of the column: no stored element is outside it.
///
/// An EMPTY operand encloses only the empty collection, so the anti-join degenerates to "this parent
/// has no elements" rather than to a `NOT IN ()` no dialect parses.
fn push_enclosed_by<V, Db>(qb: &mut sqlx::QueryBuilder<Db>, scope: &Scope, values: &[V])
where
  Db: sqlx::Database,
  V: Carrier<Db>,
{
  push_exists(qb, scope, true, |qb| {
    if !values.is_empty() {
      qb.push(" AND ");
      push_value_in(qb, scope, values, true);
    }
  });
}

/// A non-empty intersection. An EMPTY operand intersects nothing and renders `1 = 0`.
fn push_overlaps<V, Db>(qb: &mut sqlx::QueryBuilder<Db>, scope: &Scope, values: &[V])
where
  Db: sqlx::Database,
  V: Carrier<Db>,
{
  if values.is_empty() {
    qb.push("1 = 0");
    return;
  }
  push_exists(qb, scope, false, |qb| {
    qb.push(" AND ");
    push_value_in(qb, scope, values, false);
  });
}

/// Set equality: containment in both directions.
///
/// An EMPTY operand is the empty set, so the pair collapses to "this parent has no elements" — the
/// same predicate the sequence form gives an empty operand, which is the one case the two shapes
/// agree on.
fn push_mutual_containment<V, Db>(
  qb: &mut sqlx::QueryBuilder<Db>,
  scope: &Scope,
  values: &[V],
  negated: bool,
) where
  Db: sqlx::Database,
  V: Carrier<Db>,
{
  not_wrapped(qb, negated, |qb| {
    if values.is_empty() {
      push_exists(qb, scope, true, |_| ());
    } else {
      qb.push("( ");
      push_encloses(qb, scope, values);
      qb.push(" AND ");
      push_enclosed_by(qb, scope, values);
      qb.push(" )");
    }
  });
}

/// Element-wise equality of the whole sequence: no stored `(ordinal, value)` pair is outside the
/// operand, and the two are the same length.
///
/// The length test is what the anti-join alone cannot give — it admits any PREFIX of the operand —
/// and it reads the same count the ordering family's `COALESCE` falls back to.
fn push_positional_whole<V, Db>(
  qb: &mut sqlx::QueryBuilder<Db>,
  scope: &OrderedScope,
  values: &[V],
  negated: bool,
) where
  Db: sqlx::Database,
  V: Carrier<Db>,
  i64: Carrier<Db>,
{
  not_wrapped(qb, negated, |qb| {
    if values.is_empty() {
      push_exists(qb, &scope.scope, true, |_| ());
      return;
    }
    qb.push("( ");
    push_exists(qb, &scope.scope, true, |qb| {
      qb.push(" AND (");
      qb.push(&scope.ordinal);
      qb.push(", ");
      qb.push(&scope.scope.value);
      qb.push(") NOT IN (");
      for (i, value) in values.iter().enumerate() {
        if i > 0 {
          qb.push(", ");
        }
        qb.push("(");
        push_ordinal(qb, i);
        qb.push(", ");
        value.push_bind(qb);
        qb.push(")");
      }
      qb.push(")");
    });
    qb.push(" AND ");
    push_count(qb, &scope.scope);
    qb.push(" = ");
    push_ordinal(qb, values.len());
    qb.push(" )");
  });
}

/// A lexicographic collection ordering: compare at the FIRST ordinal where the two differ, and where
/// neither differs within the overlap, compare the lengths.
///
/// ```text
/// COALESCE(
///   (SELECT <value> <element> <operand value>
///      FROM <edge> JOIN ( SELECT ? AS ordinal, ? AS value UNION ALL … ) AS __ig_operand_0__
///        ON <operand ordinal> = <ordinal>
///     WHERE <correlation> AND <value> <> <operand value>
///     ORDER BY <ordinal> LIMIT 1),
///   <count> <length> ?)
/// ```
///
/// The `JOIN` pairs only the ordinals both sides have, so the scalar subquery is `NULL` exactly when
/// every overlapping position matches — which is when the answer is the length comparison, and which
/// is what `COALESCE` is reading. `<element>` is ` > ` for both upper operators and ` < ` for both
/// lower ones, while `<length>` carries the strictness: that is the whole difference between `gt`
/// and `gte`, since a first difference decides the question outright and only equal collections
/// reach the lengths.
///
/// An EMPTY operand has no positions to differ at, so each of the four reduces to its length test
/// against zero — and two of those are constants.
fn push_ordering<V, Db>(
  qb: &mut sqlx::QueryBuilder<Db>,
  scope: &OrderedScope,
  values: &[V],
  order: CollectionOrder,
) where
  Db: sqlx::Database + QuoteIdent,
  V: Carrier<Db>,
  i64: Carrier<Db>,
{
  if values.is_empty() {
    match order {
      // Against the empty collection two of the four still ask something — whether this parent has
      // any elements at all — and the other two are settled by the operator alone.
      CollectionOrder::Gt => push_exists(qb, &scope.scope, false, |_| ()),
      CollectionOrder::Lte => push_exists(qb, &scope.scope, true, |_| ()),
      CollectionOrder::Gte => {
        qb.push("1 = 1");
      }
      CollectionOrder::Lt => {
        qb.push("1 = 0");
      }
    }
    return;
  }

  let alias = FieldName::new(OPERAND_ALIAS);
  let operand = quote_ident::<Db>(alias);
  let operand_ordinal = quote_qualified::<Db>(alias, FieldName::new(OPERAND_ORDINAL));
  let operand_value = quote_qualified::<Db>(alias, FieldName::new(OPERAND_VALUE));

  qb.push("COALESCE((SELECT ");
  qb.push(&scope.scope.value);
  qb.push(order.element());
  qb.push(&operand_value);
  qb.push(" FROM ");
  qb.push(&scope.scope.table);
  qb.push(" JOIN ( ");
  for (i, value) in values.iter().enumerate() {
    if i > 0 {
      qb.push(" UNION ALL ");
    }
    qb.push("SELECT ");
    push_ordinal(qb, i);
    if i == 0 {
      qb.push(" AS ");
      qb.push(quote_ident::<Db>(FieldName::new(OPERAND_ORDINAL)));
    }
    qb.push(", ");
    value.push_bind(qb);
    if i == 0 {
      qb.push(" AS ");
      qb.push(quote_ident::<Db>(FieldName::new(OPERAND_VALUE)));
    }
  }
  qb.push(" ) AS ");
  qb.push(&operand);
  qb.push(" ON ");
  qb.push(&operand_ordinal);
  qb.push(" = ");
  qb.push(&scope.ordinal);
  qb.push(" WHERE ");
  qb.push(&scope.scope.correlation);
  qb.push(" AND ");
  qb.push(&scope.scope.value);
  qb.push(" <> ");
  qb.push(&operand_value);
  qb.push(" ORDER BY ");
  qb.push(&scope.ordinal);
  qb.push(" LIMIT 1), ");
  push_count(qb, &scope.scope);
  qb.push(order.length());
  push_ordinal(qb, values.len());
  qb.push(")");
}

/// Which of the four collection orderings an operator asks for.
///
/// A unit enum rather than the two SQL fragments passed side by side: they are not independent —
/// ` > ` with ` <= ` is not an operator anything means — and a pair of `&str` arguments of one type
/// is the shape that can be given in the wrong order and still render.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CollectionOrder {
  Gt,
  Gte,
  Lt,
  Lte,
}

impl CollectionOrder {
  /// How the two ELEMENTS at the first differing position compare. Both upper operators ask the
  /// same question there, and so do both lower ones: a position where the two differ decides the
  /// whole comparison, so strictness cannot reach it.
  const fn element(self) -> &'static str {
    match self {
      Self::Gt | Self::Gte => " > ",
      Self::Lt | Self::Lte => " < ",
    }
  }

  /// How the two LENGTHS compare when no position differs — the one place the strictness shows,
  /// because that is exactly the case where the collections are equal on their overlap.
  const fn length(self) -> &'static str {
    match self {
      Self::Gt => " > ",
      Self::Gte => " >= ",
      Self::Lt => " < ",
      Self::Lte => " <= ",
    }
  }
}

/// Bind one position or one length.
///
/// It goes through [`Carrier`] rather than into the SQL text, and the reason is that this family's
/// soundness rule has no exception for a value the crate produced itself: an operand reaches the
/// statement through a bind, and an ordinal is an operand that happens to be a counter. A `usize`
/// past `i64::MAX` is not a collection any engine here can hold, and saturating is the same answer
/// as refusing would be.
///
/// The WRITE lane spends it too — an edge row's ordinal is the same counter at the same type — so
/// the one place a position becomes an operand is this one, and the predicate a statement carrying
/// an ordinal owes is `i64: Carrier<Db>` whichever direction it runs in.
pub(crate) fn push_ordinal<Db: sqlx::Database>(qb: &mut sqlx::QueryBuilder<Db>, position: usize)
where
  i64: Carrier<Db>,
{
  let position = i64::try_from(position).unwrap_or(i64::MAX);
  position.push_bind(qb);
}

#[cfg(test)]
mod tests;