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
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
use super::{ListCrossingError, SqlListComparison, SqlSetComparison};
// Named by the SQLite module alone — the dialect-free crossing whose error it is has its assertion
// there — so it carries that gate rather than the family root's.
#[cfg(feature = "sqlite")]
use super::SetCrossingError;
use crate::comparison::sql::SqlScalarComparison;
#[cfg(any(feature = "sqlite", feature = "postgres"))]
use crate::comparison::sql::SqlTextComparison;
#[cfg(all(feature = "postgres", feature = "jiff", feature = "time"))]
use crate::comparison::sql::{SqlEdgeComparison, SqlEdgeSetComparison};

/// The two column-stored kinds with their ELEMENT comparison supplied, because almost nothing here
/// is about the element's KIND: these tests assert the collection's own operators, and spelling the
/// element comparison at each of eighty-odd call sites would bury what each one says.
///
/// The default is the SCALAR comparison, which is what a numeric element crosses into; a test whose
/// members are strings, bytes or booleans names its own third argument, so the sites where the
/// element's kind matters are exactly the ones that say so. The `any` tests name it always.
type Sequence<V, Db, C = SqlScalarComparison<V, Db>> = SqlListComparison<V, C, Db>;
type Unordered<V, Db, C = SqlScalarComparison<V, Db>> = SqlSetComparison<V, C, Db>;
/// The other storage strategy under the same convention, for the rows that name it.
///
/// Gated with the TEMPORAL wrapper beside the dialect, because every row that spells its strategy
/// through these is a `Temporal<T>`'s and [`Temporal`](crate::Temporal) is `jiff` + `time`. The
/// tests that reach the edge table without the wrapper name the two comparisons directly, so they
/// keep their coverage in a build with neither.
#[cfg(all(feature = "postgres", feature = "jiff", feature = "time"))]
type EdgeSequence<V, Db, C = SqlScalarComparison<V, Db>> = SqlEdgeComparison<V, C, Db>;
#[cfg(all(feature = "postgres", feature = "jiff", feature = "time"))]
type EdgeUnordered<V, Db, C = SqlScalarComparison<V, Db>> = SqlEdgeSetComparison<V, C, Db>;
/// The element FILTER those defaults are the crossing of — what a `CollectionStorage` row is keyed
/// on, so a test naming the trait names this beside the storage type.
#[cfg(feature = "postgres")]
type ElementFilter<V> = crate::ScalarFilter<V>;
/// The same two over a TEXT element, for the tests whose members are strings — a `Vec<String>`
/// resolves to `TextFilter<String>` for one member, so that is what its element comparison is.
///
/// Gated with the two dialect modules that name them: a build with the family root and no dialect
/// renders nothing, so it has no assertion for a text element either.
#[cfg(feature = "sqlite")]
type TextSequence<V, Db> = SqlListComparison<V, SqlTextComparison<V, Db>, Db>;
#[cfg(any(feature = "sqlite", feature = "postgres"))]
type TextUnordered<V, Db> = SqlSetComparison<V, SqlTextComparison<V, Db>, Db>;

/// The four operator names both JSON refusals share, so the two dialects can never come to disagree
/// about which operators are the ordering ones.
#[cfg(any(feature = "sqlite", feature = "mysql"))]
const ORDERING: [&str; 4] = ["gt", "gte", "lt", "lte"];

#[cfg(feature = "sqlite")]
mod sqlite {
  use core::convert::Infallible;

  use super::{
    ListCrossingError, ORDERING, Sequence, SetCrossingError, TextSequence, TextUnordered, Unordered,
  };
  use crate::{
    ListFilter, QuantifiedFilter, SetFilter, TextFilter,
    comparison::{
      TryFromFilter,
      sql::{
        SqlTextComparison,
        tests::{render, threaded},
      },
    },
  };

  /// A tag column stored as its element LENGTHS — a crossing that changes the value rather than
  /// only its type, so a pass-through mutation shows in the operand and not only in the SQL.
  fn length(tag: String) -> Result<i64, Infallible> {
    Ok(tag.len() as i64)
  }

  /// **The dialect's own refusal still comes first**, with one converter in play rather than two.
  ///
  /// The composition puts the nested filter's operands in the `g` slot, where the two-function entry
  /// already put the element crossing — so the JSON-ordering refusal is reached before any operand
  /// converts, at either level. Converting the nested filter FIRST would compile and answer, and it
  /// would answer with an OPERAND's refusal for a column that has no answer to give whatever its
  /// operands turn into.
  ///
  /// The nested operand is deliberately one the converter declines, so the two orders are two
  /// different errors rather than one error and a success.
  #[test]
  fn a_dialect_refusal_precedes_the_one_converter_at_either_level() {
    let filter = ListFilter::<u64, crate::ScalarFilter<u64>>::new()
      .with_gt([1u64])
      .with_any(crate::ScalarFilter::new().with_eq(u64::MAX));

    let refused = Sequence::<i64, sqlx::Sqlite>::try_from_filter_with(filter, i64::try_from);

    assert!(
      matches!(refused, Err(ListCrossingError::JsonOrdering("gt"))),
      "the column has no element-wise order, whatever its operands convert to"
    );
  }

  /// **The one converter reaches the NESTED filter's operands**, on the column-stored kind as on the
  /// edge-table one — the `any` slot holds a whole FILTER, whose operands are made of the same
  /// elements the collection's own slots hold.
  #[test]
  fn the_one_converter_reaches_the_nested_element_filter() {
    let filter = SetFilter::<String, TextFilter<String>>::new()
      .with_has_element("stereo".to_owned())
      .with_any(TextFilter::<String>::new().with_eq("hdr".to_owned()));

    let crossed = TextUnordered::<i64, sqlx::Sqlite>::try_from_filter_with(filter, length).unwrap();

    assert_eq!(crossed.has_element(), Some(&6i64));
    assert_eq!(
      crossed.any().expect("the element question").eq(),
      Some(&3i64),
      "the nested operand crossed through the same converter, one level down"
    );
  }

  /// One converter, every slot: the ones that hold a whole collection and the one that holds a
  /// single element are made of the same `T`.
  #[test]
  fn one_element_converter_serves_every_slot() {
    let filter = SetFilter::<String>::new()
      .with_encloses(["hdr".to_owned(), "sdr".to_owned()])
      .with_has_element("stereo".to_owned());

    let crossed = TextUnordered::<i64, sqlx::Sqlite>::try_from_filter_with(filter, length).unwrap();

    assert_eq!(crossed.encloses(), Some(&[3i64, 3][..]));
    assert_eq!(crossed.has_element(), Some(&6i64));
    assert_eq!(crossed.conjuncts(), 2);
  }

  /// The identity crossing reaches [`Infallible`] in its OPERAND half only — the arrangement the
  /// byte kind already has, and for the same reason: the other variant is a refusal that has nothing
  /// to do with converting.
  #[test]
  fn the_identity_crossing_is_infallible_in_its_operand_half() {
    let crossed: Result<TextSequence<String, sqlx::Sqlite>, ListCrossingError<Infallible>> =
      TextSequence::try_from_filter(ListFilter::<String>::new().with_eq(["hdr".to_owned()]));
    assert_eq!(crossed.unwrap().eq().unwrap(), ["hdr".to_owned()]);
  }

  /// A set crossing refuses NOTHING but the converter's own failure, so its error IS the converter's
  /// — there is no wrapper variant to unwrap. That is the split paying for itself: every operator a
  /// set carries is answerable on every dialect.
  #[test]
  fn a_set_crossing_carries_the_converters_error_undressed() {
    let crossed: Result<TextUnordered<String, sqlx::Sqlite>, SetCrossingError<Infallible>> =
      TextUnordered::try_from_filter(SetFilter::<String>::new().with_overlaps(["hdr".to_owned()]));
    assert_eq!(crossed.unwrap().overlaps().unwrap(), ["hdr".to_owned()]);
  }

  /// THE bind claim, and the reason this kind needs no array bind on a dialect that has none: the
  /// operand is one canonical JSON value however many elements it holds. A thousand-element
  /// `encloses` costs ONE bind where a thousand-element `IN` would cost a thousand, so the 32766
  /// ceiling this dialect has is unreachable from here.
  #[test]
  fn a_collection_operand_binds_once_whatever_its_length() {
    for len in [0usize, 1, 3, 1000] {
      let operand: Vec<i64> = (0..len as i64).collect();
      let crossed = Unordered::<i64, sqlx::Sqlite>::try_from_filter(
        SetFilter::<i64>::new().with_encloses(operand),
      )
      .unwrap();

      let (_, binds) = render::<sqlx::Sqlite, _>("t", &crossed);
      assert_eq!(binds, 1, "an {len}-element operand");
    }
  }

  /// The set's whole-collection equality is the ONE operator that binds twice — once per direction of
  /// a mutual containment — and it is still independent of the operand's length. The sequence's is
  /// the stored text compared directly, which is what the two kinds exist to keep apart.
  #[test]
  fn set_equality_binds_each_direction_and_sequence_equality_does_not() {
    let sequence = Sequence::<i64, sqlx::Sqlite>::try_from_filter(
      ListFilter::<i64>::new().with_eq([1i64, 2, 3]),
    )
    .unwrap();
    let set = Unordered::<i64, sqlx::Sqlite>::try_from_filter(
      SetFilter::<i64>::new().with_eq([1i64, 2, 3]),
    )
    .unwrap();

    assert_eq!(
      render::<sqlx::Sqlite, _>("t", &sequence),
      ("\"t\" = ?".to_owned(), 1)
    );
    let (sql, binds) = render::<sqlx::Sqlite, _>("t", &set);
    assert_eq!(binds, 2);
    assert_eq!(
      sql,
      "( NOT EXISTS (SELECT 1 FROM json_each(?) WHERE value NOT IN (SELECT value FROM \
       json_each(\"t\"))) AND NOT EXISTS (SELECT 1 FROM json_each(\"t\") WHERE value NOT IN \
       (SELECT value FROM json_each(?))) )"
    );
  }

  #[test]
  fn every_set_operator_renders_its_own_conjunct() {
    let filter = SetFilter::<i64>::new()
      .with_eq([1i64])
      .with_ne([2i64])
      .with_encloses([3i64])
      .with_enclosed_by([4i64])
      .with_overlaps([5i64])
      .with_has_element(6i64);
    let crossed = Unordered::<i64, sqlx::Sqlite>::try_from_filter(filter).unwrap();

    assert_eq!(crossed.conjuncts(), 6);
    let (sql, binds) = render::<sqlx::Sqlite, _>("t", &crossed);
    assert_eq!(binds, 8);
    assert_eq!(
      sql,
      "( NOT EXISTS (SELECT 1 FROM json_each(?) WHERE value NOT IN (SELECT value FROM \
       json_each(\"t\"))) AND NOT EXISTS (SELECT 1 FROM json_each(\"t\") WHERE value NOT IN \
       (SELECT value FROM json_each(?))) ) AND \
       NOT ( ( NOT EXISTS (SELECT 1 FROM json_each(?) WHERE value NOT IN (SELECT value FROM \
       json_each(\"t\"))) AND NOT EXISTS (SELECT 1 FROM json_each(\"t\") WHERE value NOT IN \
       (SELECT value FROM json_each(?))) ) ) AND \
       NOT EXISTS (SELECT 1 FROM json_each(?) WHERE value NOT IN (SELECT value FROM \
       json_each(\"t\"))) AND \
       NOT EXISTS (SELECT 1 FROM json_each(\"t\") WHERE value NOT IN (SELECT value FROM \
       json_each(?))) AND \
       EXISTS (SELECT 1 FROM json_each(\"t\") WHERE value IN (SELECT value FROM json_each(?))) AND \
       NOT EXISTS (SELECT 1 FROM json_each(?) WHERE value NOT IN (SELECT value FROM \
       json_each(\"t\")))"
    );
  }

  /// The sequence kind's three answerable slots, in the order the filter declares them.
  #[test]
  fn every_sequence_operator_renders_its_own_conjunct() {
    let filter = ListFilter::<i64>::new()
      .with_eq([1i64])
      .with_ne([2i64])
      .with_has_element(3i64);
    let crossed = Sequence::<i64, sqlx::Sqlite>::try_from_filter(filter).unwrap();

    assert_eq!(crossed.conjuncts(), 3);
    assert_eq!(
      render::<sqlx::Sqlite, _>("t", &crossed),
      (
        "\"t\" = ? AND NOT ( \"t\" = ? ) AND \
         NOT EXISTS (SELECT 1 FROM json_each(?) WHERE value NOT IN (SELECT value FROM \
         json_each(\"t\")))"
          .to_owned(),
        3
      )
    );
  }

  /// The dialect refusal: this engine has no array type, so a collection ordering has nothing to
  /// render into and is refused at the crossing rather than approximated with a text comparison of
  /// the stored JSON — which is what `col < ?` on a JSON-holding TEXT column would actually be.
  #[test]
  fn an_ordering_operator_is_refused_because_the_collection_is_json() {
    for (operator, filter) in [
      ("gt", ListFilter::<i64>::new().with_gt([1i64])),
      ("gte", ListFilter::<i64>::new().with_gte([1i64])),
      ("lt", ListFilter::<i64>::new().with_lt([1i64])),
      ("lte", ListFilter::<i64>::new().with_lte([1i64])),
    ] {
      let refused = Sequence::<i64, sqlx::Sqlite>::try_from_filter(filter);
      assert_eq!(
        refused.unwrap_err(),
        ListCrossingError::JsonOrdering(operator)
      );
    }
    assert_eq!(ORDERING, ["gt", "gte", "lt", "lte"]);

    // Every other operator crosses.
    assert!(
      Sequence::<i64, sqlx::Sqlite>::try_from_filter(ListFilter::<i64>::new().with_eq([1i64]),)
        .is_ok()
    );
  }

  /// The refusal is checked BEFORE the operands convert, as the byte kind's is: a question this
  /// dialect cannot answer has no answer whatever the elements would have turned into.
  #[test]
  fn the_dialect_is_checked_before_the_operands_convert() {
    let refused = Sequence::<u8, sqlx::Sqlite>::try_from_filter(
      ListFilter::<u64>::new()
        .with_gt([1u64])
        // This element cannot become a `u8`, and its error is not the one reported.
        .with_eq([999u64]),
    );
    assert_eq!(refused.unwrap_err(), ListCrossingError::JsonOrdering("gt"));
  }

  /// Membership IS containment of the singleton, so it renders the `encloses` form over a
  /// one-element operand rather than an operator of its own — and it renders the SAME form on both
  /// kinds, because "is `x` in this collection" does not read the stored order.
  #[test]
  fn membership_is_containment_of_the_singleton_on_both_kinds() {
    let member = Unordered::<i64, sqlx::Sqlite>::try_from_filter(
      SetFilter::<i64>::new().with_has_element(6i64),
    )
    .unwrap();
    let singleton = Unordered::<i64, sqlx::Sqlite>::try_from_filter(
      SetFilter::<i64>::new().with_encloses([6i64]),
    )
    .unwrap();
    let sequence = Sequence::<i64, sqlx::Sqlite>::try_from_filter(
      ListFilter::<i64>::new().with_has_element(6i64),
    )
    .unwrap();

    assert_eq!(
      render::<sqlx::Sqlite, _>("t", &member),
      render::<sqlx::Sqlite, _>("t", &singleton)
    );
    assert_eq!(
      render::<sqlx::Sqlite, _>("t", &sequence),
      render::<sqlx::Sqlite, _>("t", &member)
    );
  }

  /// …and its operand is the singleton ARRAY, not the bare element.
  ///
  /// The test above cannot see that: the operand is inside a bind, so `[6]` and `6` render the same
  /// `?` and the same count. This asks the element itself, which is the only party that was there —
  /// [`Probe`] reports the buffer length at the moment it was asked for its token, and a `1` means an
  /// array bracket was already open.
  ///
  /// It matters because `json_each` over a bare scalar is not the same query: SQLite yields ONE row
  /// whose value is the scalar, so the predicate would happen to work for a one-element operand and
  /// stop meaning containment.
  #[test]
  fn the_membership_operand_is_the_singleton_array() {
    use core::cell::Cell;

    use crate::comparison::sql::JsonElement;

    /// An element that records where in the buffer it was written.
    #[derive(Debug, PartialEq)]
    struct Probe {
      offset: Cell<usize>,
    }

    // The reading one MEMBER is guarded by, which a collection filter over it now projects through.
    impl crate::ScalarFilterMarker for Probe {
      type Filter = crate::ScalarFilter<Probe>;
    }

    impl crate::DefaultMarker for Probe {
      type Marker = crate::ScalarMarker<Probe>;
    }

    // The element comparison this probe's collection holds is never set and never rendered; it is
    // still a type the lowering names, so the probe carries the one row that lets it be one.
    impl<Db: sqlx::Database> crate::comparison::sql::Carrier<Db> for Probe
    where
      i64: crate::comparison::sql::Carrier<Db>,
    {
      fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
        crate::comparison::sql::Carrier::push_bind(&0i64, qb);
      }
    }

    /// ONE column, the default body — the width beside the bind, which the scalar lowering reads.
    impl crate::ColumnKind for Probe {}

    impl JsonElement for Probe {
      fn push_json(&self, out: &mut String) {
        self.offset.set(out.len());
        out.push('0');
      }
    }

    let crossed = Unordered::<Probe, sqlx::Sqlite>::try_from_filter(
      SetFilter::<Probe>::new().with_has_element(Probe {
        offset: Cell::new(usize::MAX),
      }),
    )
    .unwrap();
    render::<sqlx::Sqlite, _>("t", &crossed);

    assert_eq!(
      crossed.has_element().unwrap().offset.get(),
      1,
      "the element was written at offset 0, so nothing opened an array around it"
    );
  }

  /// The threaded lowering reaches THIS dialect's leaf: the `json_each` set expressions, which
  /// neither other dialect writes — Postgres asks its array operators directly and MySQL calls
  /// `JSON_CONTAINS`.
  #[test]
  fn the_threaded_lowering_renders_this_dialect_leaf() {
    let crossed = Unordered::<i64, sqlx::Sqlite>::try_from_filter(
      SetFilter::<i64>::new()
        .with_encloses([3i64])
        .with_overlaps([5i64]),
    )
    .unwrap();

    assert_eq!(
      threaded::<sqlx::Sqlite, _>("t", &crossed),
      "SELECT \"id\" FROM \"t\" WHERE \
       NOT EXISTS (SELECT 1 FROM json_each(?) WHERE value NOT IN (SELECT value FROM \
       json_each(\"t\"))) AND \
       EXISTS (SELECT 1 FROM json_each(\"t\") WHERE value IN (SELECT value FROM json_each(?)))"
    );
  }

  /// `json_each` IS an element scope on this dialect, so `any` opens one and renders the ELEMENT's
  /// own comparison inside it — at the address every scope names its member with, which is what lets
  /// a text element bring the substring family that a scalar element does not have.
  #[test]
  fn an_element_question_opens_a_json_each_scope() {
    let crossed = TextUnordered::<String, sqlx::Sqlite>::try_from_filter_with_element(
      SetFilter::<String, TextFilter<String>>::new()
        .with_any(TextFilter::<String>::new().with_starts_with("hd".to_owned())),
      Ok::<_, Infallible>,
      SqlTextComparison::try_from_filter,
    )
    .unwrap();

    // The element's address renders QUOTED — `"value"` — where this module's own set expressions
    // write it bare, because an element comparison goes through `Backend::write_column` like every
    // other address. Measured on SQLite 3.51.0: both spellings resolve to `json_each`'s column, and
    // do so even where the PARENT carries its own `value` column whose contents would have matched.
    assert_eq!(
      render::<sqlx::Sqlite, _>("t", &crossed),
      (
        "EXISTS (SELECT 1 FROM json_each(\"t\") WHERE substr(\"value\", 1, length(?)) = ?)"
          .to_owned(),
        2
      )
    );
    // ONE conjunct however many operators the element comparison holds: they land inside a scope
    // that is itself the conjunct.
    assert_eq!(crossed.conjuncts(), 1);
  }

  /// **THE NARROW KIND LOWERS THROUGH THE WIDE KIND'S OWN TWO ARMS**, so what it renders is what the
  /// wide filter renders with its other seven slots unset.
  ///
  /// Asserted as EQUALITY between the two crossings rather than against re-stated SQL, which is the
  /// only form of the claim a second implementation of the two arms could not pass. The SQL is
  /// asserted once beside it so the pair still says what is rendered rather than only that two
  /// things agree.
  #[test]
  fn a_quantified_crossing_renders_what_the_wide_one_does() {
    let narrow = Sequence::<i64, sqlx::Sqlite>::try_from_filter(
      QuantifiedFilter::<i64>::new()
        .with_any(crate::ScalarFilter::new().with_eq(1))
        .with_count(crate::ScalarFilter::new().with_gte(2)),
    )
    .unwrap();
    let wide = Sequence::<i64, sqlx::Sqlite>::try_from_filter(
      ListFilter::<i64>::new()
        .with_any(crate::ScalarFilter::new().with_eq(1))
        .with_count(crate::ScalarFilter::new().with_gte(2)),
    )
    .unwrap();

    assert_eq!(narrow, wide);
    assert_eq!(narrow.conjuncts(), wide.conjuncts());
    assert_eq!(
      render::<sqlx::Sqlite, _>("t", &narrow),
      render::<sqlx::Sqlite, _>("t", &wide)
    );
    assert_eq!(
      render::<sqlx::Sqlite, _>("t", &narrow),
      (
        "EXISTS (SELECT 1 FROM json_each(\"t\") WHERE \"value\" = ?) AND \
         json_array_length(\"t\") >= ?"
          .to_owned(),
        2
      )
    );
  }

  /// The seven element slots stay UNSET, read back off the comparison's own getters — so a slot
  /// arriving would red this rather than pass as an extra conjunct nobody counted.
  ///
  /// The ORDERING four are the ones worth naming here: this dialect REFUSES them at the wide
  /// crossing, and the narrow one has no refusal to make because there is no slot to hold one.
  #[test]
  fn a_quantified_crossing_leaves_every_element_slot_absent() {
    let crossed = Sequence::<i64, sqlx::Sqlite>::try_from_filter(
      QuantifiedFilter::<i64>::new().with_any(crate::ScalarFilter::new()),
    )
    .unwrap();

    assert!(crossed.has_element().is_none());
    assert!(crossed.eq().is_none());
    assert!(crossed.ne().is_none());
    assert!(crossed.gt().is_none());
    assert!(crossed.gte().is_none());
    assert!(crossed.lt().is_none());
    assert!(crossed.lte().is_none());
    // The quantifier law survives the crossing: a present `any` holding an empty element filter is
    // the collection being non-empty, which is one conjunct and not none.
    assert!(!crossed.is_empty());
    assert_eq!(crossed.conjuncts(), 1);
    assert_eq!(
      render::<sqlx::Sqlite, _>("t", &crossed),
      ("EXISTS (SELECT 1 FROM json_each(\"t\"))".to_owned(), 0)
    );
  }

  /// An `any` whose element comparison is EMPTY renders the scope and no `WHERE`, which is the
  /// question it asks: every element satisfies the empty filter, so *some element satisfies it* is
  /// *this collection has an element*.
  ///
  /// The guard is the inner accumulator's own — it pushes its lead on the first conjunct anything
  /// writes — so what would break this is a lead pushed eagerly rather than a missing `is_empty`
  /// check. Removing the ` WHERE ` lead is what the assertion would catch.
  #[test]
  fn an_empty_element_comparison_is_the_collection_being_non_empty() {
    let crossed = Unordered::<i64, sqlx::Sqlite>::try_from_filter(
      SetFilter::<i64>::new().with_any(crate::ScalarFilter::new()),
    )
    .unwrap();

    assert_eq!(
      render::<sqlx::Sqlite, _>("t", &crossed),
      ("EXISTS (SELECT 1 FROM json_each(\"t\"))".to_owned(), 0)
    );
    assert!(!crossed.is_empty());
  }

  /// `json_array_length` is this dialect's cardinality, and it needs no care about the empty array:
  /// measured on SQLite 3.51.0, `json_array_length('[]')` is `0`. The Postgres note beside
  /// `push_array_count` is where that comparison is drawn.
  #[test]
  fn a_cardinality_is_json_array_length() {
    let crossed = Unordered::<i64, sqlx::Sqlite>::try_from_filter(
      SetFilter::<i64>::new().with_count(crate::ScalarFilter::new().with_gt(3).with_lte(9)),
    )
    .unwrap();

    assert_eq!(
      render::<sqlx::Sqlite, _>("t", &crossed),
      (
        "json_array_length(\"t\") > ? AND json_array_length(\"t\") <= ?".to_owned(),
        2
      )
    );
    // ONE conjunct PER operator, because they land beside the collection's own rather than inside a
    // scope — which is the whole difference from `any` above.
    assert_eq!(crossed.conjuncts(), 2);
  }

  /// A `count` holding an EMPTY scalar filter renders nothing and leaves the comparison empty. It is
  /// not quantified, so asking no question about one number excludes no row — the fold-in
  /// `Nullable` already makes, and the opposite of the element scope's answer above.
  #[test]
  fn an_empty_cardinality_folds_in() {
    let crossed = Unordered::<i64, sqlx::Sqlite>::try_from_filter(
      SetFilter::<i64>::new().with_count(crate::ScalarFilter::new()),
    )
    .unwrap();

    assert_eq!(render::<sqlx::Sqlite, _>("t", &crossed), (String::new(), 0));
    assert_eq!(crossed.conjuncts(), 0);
    assert!(crossed.is_empty());
    // …and the FILTER says the same before it ever crosses, which is what a caller asks.
    assert!(
      SetFilter::<i64>::new()
        .with_count(crate::ScalarFilter::new())
        .is_empty()
    );
  }

  /// The cardinality's membership pair reaches the same empty-list asymmetry every other membership
  /// operator has, because it renders through the same form: `notIn: []` matches every row and
  /// `in: []` matches none.
  #[test]
  fn a_cardinality_membership_degenerates_like_every_other() {
    let none = Unordered::<i64, sqlx::Sqlite>::try_from_filter(
      SetFilter::<i64>::new().with_count(crate::ScalarFilter::new().with_in_([])),
    )
    .unwrap();
    let every = Unordered::<i64, sqlx::Sqlite>::try_from_filter(
      SetFilter::<i64>::new().with_count(crate::ScalarFilter::new().with_not_in([])),
    )
    .unwrap();

    assert_eq!(
      render::<sqlx::Sqlite, _>("t", &none),
      ("1 = 0".to_owned(), 0)
    );
    assert_eq!(
      render::<sqlx::Sqlite, _>("t", &every),
      ("NOT ( 1 = 0 )".to_owned(), 0)
    );
  }
}

/// The dialect this whole split exists for: Postgres has a native `ARRAY`, its containment operators
/// and an element-wise `<`, and the previous lowering reached none of them.
#[cfg(feature = "postgres")]
mod postgres {
  use super::{Sequence, Unordered};
  use crate::{
    ListFilter, SetFilter,
    comparison::{
      TryFromFilter,
      sql::tests::{render, threaded},
    },
  };

  /// The regression this rework exists to prevent, stated as the thing a reader can check without
  /// knowing any of the above: a Postgres collection comparison does not mention JSON.
  ///
  /// It would have caught the original defect on its own — every operator lowered through `jsonb`,
  /// `jsonb_array_elements` or a `::jsonb` cast, and each of those carries the substring.
  #[test]
  fn no_postgres_rendering_mentions_json() {
    let sequence = Sequence::<i64, sqlx::Postgres>::try_from_filter(
      ListFilter::<i64>::new()
        .with_eq([1i64])
        .with_ne([2i64])
        .with_gt([3i64])
        .with_gte([4i64])
        .with_lt([5i64])
        .with_lte([6i64])
        .with_has_element(7i64),
    )
    .unwrap();
    let (sql, _) = render::<sqlx::Postgres, _>("t", &sequence);
    assert!(
      !sql.to_lowercase().contains("json"),
      "a native-array lowering renders no JSON: {sql}"
    );

    // And the set kind, whose equality takes the other branch.
    let set = Unordered::<i64, sqlx::Postgres>::try_from_filter(
      SetFilter::<i64>::new()
        .with_eq([1i64])
        .with_encloses([2i64])
        .with_enclosed_by([3i64])
        .with_overlaps([4i64])
        .with_has_element(5i64),
    )
    .unwrap();
    let (sql, _) = render::<sqlx::Postgres, _>("t", &set);
    assert!(!sql.to_lowercase().contains("json"), "{sql}");
  }

  /// Every sequence operator, in the order the filter declares them, against the native operators.
  #[test]
  fn every_sequence_operator_renders_its_own_conjunct() {
    let filter = ListFilter::<i64>::new()
      .with_eq([1i64])
      .with_ne([2i64])
      .with_gt([3i64])
      .with_gte([4i64])
      .with_lt([5i64])
      .with_lte([6i64])
      .with_has_element(7i64);
    let crossed = Sequence::<i64, sqlx::Postgres>::try_from_filter(filter).unwrap();

    assert_eq!(crossed.conjuncts(), 7);
    assert_eq!(
      render::<sqlx::Postgres, _>("t", &crossed),
      (
        "\"t\" = $1 AND NOT ( \"t\" = $2 ) AND \"t\" > $3 AND \"t\" >= $4 AND \"t\" < $5 AND \
         \"t\" <= $6 AND \"t\" @> $7"
          .to_owned(),
        7
      )
    );
  }

  /// Every set operator, likewise — and the two lists have exactly `eq`, `ne` and `has_element` in
  /// common, which is the split stated as SQL.
  #[test]
  fn every_set_operator_renders_its_own_conjunct() {
    let filter = SetFilter::<i64>::new()
      .with_eq([1i64])
      .with_ne([2i64])
      .with_encloses([3i64])
      .with_enclosed_by([4i64])
      .with_overlaps([5i64])
      .with_has_element(6i64);
    let crossed = Unordered::<i64, sqlx::Postgres>::try_from_filter(filter).unwrap();

    assert_eq!(crossed.conjuncts(), 6);
    assert_eq!(
      render::<sqlx::Postgres, _>("t", &crossed),
      (
        "( \"t\" @> $1 AND \"t\" <@ $2 ) AND NOT ( ( \"t\" @> $3 AND \"t\" <@ $4 ) ) AND \
         \"t\" @> $5 AND \"t\" <@ $6 AND \"t\" && $7 AND \"t\" @> $8"
          .to_owned(),
        8
      )
    );
  }

  /// The bind claim survives the encoding change: an ARRAY of N elements is ONE parameter, so the
  /// 65535 ceiling stays unreachable from this kind.
  #[test]
  fn a_collection_operand_binds_once_whatever_its_length() {
    for len in [0usize, 1, 3, 1000] {
      let operand: Vec<i64> = (0..len as i64).collect();
      let crossed = Unordered::<i64, sqlx::Postgres>::try_from_filter(
        SetFilter::<i64>::new().with_encloses(operand),
      )
      .unwrap();

      let (sql, binds) = render::<sqlx::Postgres, _>("t", &crossed);
      assert_eq!(binds, 1, "an {len}-element operand");
      assert_eq!(sql, "\"t\" @> $1");
    }
  }

  /// The KIND changes the SQL for equality and for nothing else — the two forms are as far apart as
  /// they get, `=` against a two-sided `@>`/`<@` — while `has_element`, the one operator both carry
  /// besides equality, reads the same on either.
  #[test]
  fn the_kind_splits_equality_and_leaves_membership_alone() {
    let sequence =
      Sequence::<i64, sqlx::Postgres>::try_from_filter(ListFilter::<i64>::new().with_eq([1i64, 2]))
        .unwrap();
    let set =
      Unordered::<i64, sqlx::Postgres>::try_from_filter(SetFilter::<i64>::new().with_eq([1i64, 2]))
        .unwrap();

    assert_eq!(
      render::<sqlx::Postgres, _>("t", &sequence),
      ("\"t\" = $1".to_owned(), 1)
    );
    assert_eq!(
      render::<sqlx::Postgres, _>("t", &set),
      ("( \"t\" @> $1 AND \"t\" <@ $2 )".to_owned(), 2)
    );

    let sequence_member = Sequence::<i64, sqlx::Postgres>::try_from_filter(
      ListFilter::<i64>::new().with_has_element(1i64),
    )
    .unwrap();
    let set_member = Unordered::<i64, sqlx::Postgres>::try_from_filter(
      SetFilter::<i64>::new().with_has_element(1i64),
    )
    .unwrap();

    assert_eq!(
      render::<sqlx::Postgres, _>("t", &sequence_member),
      render::<sqlx::Postgres, _>("t", &set_member)
    );
    assert_eq!(
      render::<sqlx::Postgres, _>("t", &set_member),
      ("\"t\" @> $1".to_owned(), 1)
    );
  }

  /// Membership is containment of the SINGLETON here too, and the operand is an array of one — the
  /// bare element would be `anyelement @> anyarray`, which is not an operator Postgres has.
  #[test]
  fn membership_is_containment_of_the_singleton() {
    let member = Unordered::<i64, sqlx::Postgres>::try_from_filter(
      SetFilter::<i64>::new().with_has_element(6i64),
    )
    .unwrap();
    let singleton = Unordered::<i64, sqlx::Postgres>::try_from_filter(
      SetFilter::<i64>::new().with_encloses([6i64]),
    )
    .unwrap();

    assert_eq!(
      render::<sqlx::Postgres, _>("t", &member),
      render::<sqlx::Postgres, _>("t", &singleton)
    );
  }

  /// …and the operand really is an ARRAY of one, not the bare element.
  ///
  /// The test above cannot see that and neither can the SQL: `"t" @> $1` is what both spellings
  /// render, and both bind once. A mutation that swaps `push_bind(&[element])` for
  /// `push_bind(element)` therefore survived every offline assertion this kind had — it fails only
  /// against a live server, as `operator does not exist: bigint[] @> bigint`.
  ///
  /// So the element is asked instead. sqlx encodes a Postgres array by writing a 20-byte header —
  /// dimensions, flags, element OID, length, lower bound — before the first element, and a bare bind
  /// writes none of it, so the buffer offset the element is handed says which path it took. This is
  /// the same measurement the SQLite twin makes over the JSON buffer, on the other encoding.
  ///
  /// It is also the measurement that keeps `has_element` on the filter at all: as a predicate it IS
  /// `encloses` of the singleton, and it is a different BIND.
  #[test]
  fn the_membership_operand_is_the_singleton_array() {
    use core::cell::Cell;

    use sqlx::postgres::{PgArgumentBuffer, PgHasArrayType, PgTypeInfo};

    /// An element that records how much had been written when it was asked to encode.
    #[derive(Debug, PartialEq)]
    struct Probe {
      offset: Cell<usize>,
    }

    impl crate::ScalarFilterMarker for Probe {
      type Filter = crate::ScalarFilter<Probe>;
    }

    impl crate::DefaultMarker for Probe {
      type Marker = crate::ScalarMarker<Probe>;
    }

    // The element comparison this probe's collection holds is never set and never rendered; it is
    // still a type the lowering names, so the probe carries the one row that lets it be one.
    impl<Db: sqlx::Database> crate::comparison::sql::Carrier<Db> for Probe
    where
      i64: crate::comparison::sql::Carrier<Db>,
    {
      fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
        crate::comparison::sql::Carrier::push_bind(&0i64, qb);
      }
    }

    /// ONE column, the default body — the width beside the bind, which the scalar lowering reads.
    impl crate::ColumnKind for Probe {}

    impl From<i64> for Probe {
      fn from(_: i64) -> Self {
        Self {
          offset: Cell::new(usize::MAX),
        }
      }
    }

    impl sqlx::Type<sqlx::Postgres> for Probe {
      fn type_info() -> PgTypeInfo {
        <i64 as sqlx::Type<sqlx::Postgres>>::type_info()
      }
    }

    impl PgHasArrayType for Probe {
      fn array_type_info() -> PgTypeInfo {
        <i64 as PgHasArrayType>::array_type_info()
      }
    }

    impl sqlx::Encode<'_, sqlx::Postgres> for Probe {
      fn encode_by_ref(
        &self,
        buf: &mut PgArgumentBuffer,
      ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
        self.offset.set(buf.len());
        <i64 as sqlx::Encode<'_, sqlx::Postgres>>::encode_by_ref(&0i64, buf)
      }
    }

    // The same probe under `encloses`, which is unambiguously an array operand — the CONTROL, so
    // the assertion is a comparison between two paths rather than a pinned sqlx header size.
    let control = Unordered::<Probe, sqlx::Postgres>::try_from_filter(
      SetFilter::<i64>::new().with_encloses([1i64]),
    )
    .unwrap();
    render::<sqlx::Postgres, _>("t", &control);
    let array_offset = control.encloses().unwrap()[0].offset.get();

    let member = Unordered::<Probe, sqlx::Postgres>::try_from_filter(
      SetFilter::<i64>::new().with_has_element(1i64),
    )
    .unwrap();
    render::<sqlx::Postgres, _>("t", &member);

    assert_ne!(array_offset, usize::MAX, "the control element encoded");
    assert!(
      array_offset > 0,
      "an array writes its header before the first element"
    );
    assert_eq!(
      member.has_element().unwrap().offset.get(),
      array_offset,
      "the membership operand took the same encoding path its `encloses` twin did"
    );
  }

  /// The ordering family is answered here and refused on the two JSON dialects, and that asymmetry
  /// is the capability difference said out loud: Postgres has an element-wise `<` over arrays.
  #[test]
  fn an_ordering_operator_is_answered_because_the_array_is_native() {
    let ordered =
      Sequence::<i64, sqlx::Postgres>::try_from_filter(ListFilter::<i64>::new().with_gt([1i64]))
        .unwrap();
    assert_eq!(
      render::<sqlx::Postgres, _>("t", &ordered),
      ("\"t\" > $1".to_owned(), 1)
    );
  }

  /// An element type with no `PgHasArrayType` row has no ARRAY lowering here, and the omission is an
  /// unsatisfied bound rather than a query that binds something plausible. `BeU64` is the case that
  /// actually occurs: it is a blob carrier this crate declares, and sqlx names no array type for it.
  ///
  /// The claim is a compile-time one and is pinned as a doctest on the module rather than here — see
  /// `collection`'s Postgres note. Where such a type ends up instead is the `strategy` module below.
  #[test]
  fn a_declared_element_type_renders_through_its_own_array_type() {
    let crossed = super::TextUnordered::<String, sqlx::Postgres>::try_from_filter(
      SetFilter::<String>::new().with_encloses(["hdr".to_owned()]),
    )
    .unwrap();

    assert_eq!(
      render::<sqlx::Postgres, _>("t", &crossed),
      ("\"t\" @> $1".to_owned(), 1)
    );
  }

  /// `unnest` is a real element scope on this dialect, and the ALIAS LIST is what names its column:
  /// a bare `AS "__ig_element_0__"` would leave the member called `unnest`, and the element comparison
  /// addresses `value`.
  ///
  /// Measured on PostgreSQL 14.23: this predicate admits exactly the rows with a matching element,
  /// including where the PARENT carries its own `value` column whose contents would have matched.
  #[test]
  fn an_element_question_opens_an_unnest_scope() {
    use crate::{TextFilter, comparison::sql::SqlTextComparison};

    let crossed = super::TextUnordered::<String, sqlx::Postgres>::try_from_filter_with_element(
      SetFilter::<String, TextFilter<String>>::new()
        .with_any(TextFilter::<String>::new().with_starts_with("hd".to_owned())),
      Ok::<_, core::convert::Infallible>,
      SqlTextComparison::try_from_filter,
    )
    .unwrap();

    assert_eq!(
      render::<sqlx::Postgres, _>("t", &crossed),
      (
        "EXISTS (SELECT 1 FROM unnest(\"t\") AS \"__ig_element_0__\"(\"value\") WHERE \"value\" LIKE \
         $1 ESCAPE '\\')"
          .to_owned(),
        1
      )
    );
    assert_eq!(crossed.conjuncts(), 1);
  }

  /// The cardinality is `cardinality` and NOT `array_length`, and the empty array is the whole
  /// reason — see `push_array_count` for the measurement. This assertion is what would notice the
  /// call being changed back.
  #[test]
  fn a_cardinality_is_cardinality_and_not_array_length() {
    let crossed = Unordered::<i64, sqlx::Postgres>::try_from_filter(
      SetFilter::<i64>::new().with_count(crate::ScalarFilter::new().with_eq(0)),
    )
    .unwrap();

    let (sql, binds) = render::<sqlx::Postgres, _>("t", &crossed);
    assert_eq!((sql.as_str(), binds), ("cardinality(\"t\") = $1", 1));
    // Stated as an absence too: `array_length` answers `NULL` for the empty array, so a rendering
    // that named it would admit no row at all for the operand this test binds.
    assert!(!sql.contains("array_length"));
  }

  /// The threaded lowering reaches THIS dialect's leaf: the NATIVE array operators, and no JSON —
  /// which is the regression this kind's split exists to prevent, asserted on the threaded path too
  /// because a second impl is a second place a collection could come to lower through `jsonb`.
  #[test]
  fn the_threaded_lowering_renders_this_dialect_leaf() {
    let crossed = Unordered::<i64, sqlx::Postgres>::try_from_filter(
      SetFilter::<i64>::new()
        .with_encloses([7i64])
        .with_enclosed_by([8i64])
        .with_overlaps([9i64]),
    )
    .unwrap();

    let sql = threaded::<sqlx::Postgres, _>("t", &crossed);
    assert_eq!(
      sql,
      "SELECT \"id\" FROM \"t\" WHERE \"t\" @> $1 AND \"t\" <@ $2 AND \"t\" && $3"
    );
    assert!(!sql.contains("json"), "{sql}");
  }
}

/// The Postgres strategy table: which comparisons each element type's row names, and whether those
/// comparisons can be lowered at all.
///
/// It is the crossing that is asked here rather than any comparison, because the defect this table
/// exists for was invisible from all of them — the column-stored kinds lower correctly for the types
/// they admit, and the ones they do not admit reached them anyway.
#[cfg(feature = "postgres")]
mod strategy {
  use super::{ElementFilter, Sequence, Unordered};
  // The names only a `Temporal<T>` site spells: the edge aliases where the wrapper states its
  // strategy, and the two `Scalar*` spellings where it states its element's. Each carries the
  // wrapper's gate rather than this module's, so a build with the dialect and no temporal
  // vocabulary keeps every test that does not need one.
  #[cfg(all(feature = "jiff", feature = "time"))]
  use super::{EdgeSequence, EdgeUnordered};
  use crate::{
    BeI128, BeU64, BeU128, ListFilter, SetFilter,
    comparison::{
      ComplexComparison, TryFromFilter,
      sql::{
        CollectionStorage, PgCollectionStorage, SqlEdgeComparison, SqlEdgeSetComparison,
        tests::render,
      },
    },
  };
  #[cfg(all(feature = "jiff", feature = "time"))]
  use crate::{ScalarFilter, comparison::sql::postgres::ScalarComparison};

  /// Whatever the crossing picks for `V`, BOTH answers must be comparisons this dialect can actually
  /// LOWER.
  ///
  /// The whole of the test is its where-clause: a row naming a strategy whose bounds `V` does not
  /// meet is a call to this function that does not compile. That is the check the dialect-keyed
  /// answer could not make, because it named one strategy for every element and the bound was only
  /// read at the lowering — where nothing called it either.
  fn crossing_lowers<V>()
  where
    sqlx::Postgres: CollectionStorage<V, ElementFilter<V>>,
    <sqlx::Postgres as CollectionStorage<V, ElementFilter<V>>>::Sequence:
      ComplexComparison<sqlx::Postgres>,
    <sqlx::Postgres as CollectionStorage<V, ElementFilter<V>>>::Set:
      ComplexComparison<sqlx::Postgres>,
  {
  }

  /// Every element type this crate ships a row for, in both the owned and the borrowed form.
  ///
  /// A list rather than one call per type: what is being asserted is the same sentence about each,
  /// and the failure a reader has to act on is a compile error naming the type in the call.
  #[test]
  fn every_shipped_row_names_comparisons_that_lower() {
    macro_rules! owned_and_borrowed {
      ($( $ty:ty ),+ $(,)?) => {
        $(
          crossing_lowers::<$ty>();
          crossing_lowers::<&$ty>();
        )+
      };
    }

    owned_and_borrowed!(
      bool,
      i8,
      i16,
      i32,
      i64,
      u8,
      u16,
      u32,
      f32,
      f64,
      String,
      Vec<u8>,
      crate::Score,
      BeU64,
      BeU128,
      BeI128,
      ::core::time::Duration,
      sqlx::postgres::types::PgInterval,
    );

    #[cfg(feature = "time")]
    owned_and_borrowed!(time::OffsetDateTime, time::Date, time::Time);

    // The wrapper over each of the three storage forms, which is what a `jiff` field's collection
    // crosses into — all three rather than the instant alone, since each reads its own `T`'s row.
    #[cfg(all(feature = "jiff", feature = "time"))]
    owned_and_borrowed!(
      crate::Temporal<time::OffsetDateTime>,
      crate::Temporal<time::Date>,
      crate::Temporal<time::Time>,
    );

    // The wrapper over an element that declared the EDGE table, which the three above cannot
    // exercise. It is a shipped row for the same reason they are — a downstream
    // `TemporalStorage` names its own storage form, and every type in the table above is a form it
    // may name — and `i8` and `BeU64` are the two ways an element reaches that half: one has
    // sqlx's three and declines the array, and the other has no array type to decline.
    #[cfg(all(feature = "jiff", feature = "time"))]
    owned_and_borrowed!(crate::Temporal<i8>, crate::Temporal<BeU64>,);
  }

  /// The wrapper takes WHICHEVER strategies its element declared: an element with a usable array
  /// type keeps the array through it, and one that declared the edge table keeps the edge table
  /// through it. Both halves in one call, so neither can move without the other being read — and
  /// both ANSWERS of each half, since a row states two.
  ///
  /// Asserted as TYPES. The two strategies do render different SQL, but the row that picks between
  /// them is read at the CROSSING — a test that only rendered would be pinning the consequence and
  /// leaving the choice free to be made some other way.
  #[cfg(all(feature = "jiff", feature = "time"))]
  #[test]
  fn a_temporal_collection_takes_whichever_strategy_its_element_declared() {
    use crate::Temporal;

    /// `A` names the column-stored comparisons over itself and `E` the edge ones. Either flipping —
    /// or either losing its row, which is what the wrapper over an edge element had — is an
    /// unsatisfied bound on this call rather than a different rendering.
    fn follows_its_element<A, E, AC, EC>()
    where
      sqlx::Postgres: CollectionStorage<
          A,
          ElementFilter<A>,
          Sequence = Sequence<A, sqlx::Postgres, AC>,
          Set = Unordered<A, sqlx::Postgres, AC>,
        > + CollectionStorage<
          E,
          ElementFilter<E>,
          Sequence = EdgeSequence<E, sqlx::Postgres, EC>,
          Set = EdgeUnordered<E, sqlx::Postgres, EC>,
        >,
    {
    }

    follows_its_element::<
      Temporal<time::OffsetDateTime>,
      Temporal<BeU64>,
      ScalarComparison<Temporal<time::OffsetDateTime>>,
      ScalarComparison<Temporal<BeU64>>,
    >();
    // `Temporal<i8>` is the pair a capability bound would get wrong: `i8` has all three of sqlx's
    // rows and declares the edge table anyway, so a strategy deduced from
    // `PgHasArrayType + Type + Encode` would send it to an array of `"char"` where the column its
    // carrier binds into is `smallint`.
    follows_its_element::<
      Temporal<time::Date>,
      Temporal<i8>,
      ScalarComparison<Temporal<time::Date>>,
      ScalarComparison<Temporal<i8>>,
    >();
    // The borrowed halves, which read the same OWNED row on the element.
    follows_its_element::<
      &Temporal<time::Time>,
      &Temporal<BeU64>,
      ScalarComparison<&Temporal<time::Time>>,
      ScalarComparison<&Temporal<BeU64>>,
    >();
  }

  /// The edge half is a working crossing and not only a type equality. It is reachable because
  /// [`TemporalStorage`](crate::TemporalStorage) is public and open — a downstream temporal type
  /// names whatever storage form it likes, and this crate's blob carrier is one a declaration can
  /// name — so `Temporal<BeU64>` is a collection somebody can actually declare.
  #[cfg(all(feature = "jiff", feature = "time"))]
  #[test]
  fn a_temporal_collection_over_a_blob_carrier_renders_the_edge_table() {
    use crate::Temporal;

    /// A downstream temporal type whose storage form is the blob carrier.
    struct Era(u64);

    impl crate::ScalarFilterMarker for Era {
      type Filter = crate::ScalarFilter<Era>;
    }

    impl crate::DefaultMarker for Era {
      type Marker = crate::ScalarMarker<Era>;
    }

    impl crate::TemporalStorage for Era {
      type Storage = BeU64;

      fn to_storage(&self) -> Self::Storage {
        BeU64(self.0)
      }
    }

    // The annotation is half the assertion, as it is for the unwrapped blob carrier below: it is
    // the crossing's answer, so a row that moved to the array strategy stops this compiling rather
    // than rendering something else.
    let crossed: <sqlx::Postgres as CollectionStorage<
      Temporal<BeU64>,
      ElementFilter<Temporal<BeU64>>,
    >>::Sequence =
      SqlEdgeComparison::try_from_filter(ListFilter::<Era>::new().with_has_element(Era(7)))
        .unwrap();

    // The harness's row is `p` keyed by `id`, so an `eras` column's elements are kept in `p_eras`.
    assert_eq!(
      render::<sqlx::Postgres, _>("eras", &crossed),
      (
        "EXISTS (SELECT 1 FROM \"p_eras\" WHERE \"p_eras\".\"id\" = \"p\".\"id\" AND \
         \"p_eras\".\"eras\" = $1)"
          .to_owned(),
        1
      )
    );
  }

  /// The whole point of giving [`Temporal<T>`](crate::Temporal) sqlx's three
  /// traits: a `Vec<jiff::Timestamp>` and a `Vec<time::OffsetDateTime>` are ONE physical shape.
  /// Before it the wrapper had a [`Carrier`](crate::comparison::sql::Carrier) row and none of
  /// sqlx's, so it could not name an array type and the same logical column landed in an array on
  /// one declaration and in an edge table on the other.
  ///
  /// None of that is visible in the SQL — `"t" @> $1` is what both write — so the strategy is
  /// asserted as a TYPE and the operand as its encoded BYTES.
  #[cfg(all(feature = "jiff", feature = "time"))]
  #[test]
  fn a_temporal_collection_takes_the_array_where_times_own_does() {
    use crate::Temporal;

    /// Both element types name the column-stored comparisons over themselves. Either row moving back
    /// to the edge table is an unsatisfied bound on this call rather than a different rendering.
    fn both_take_the_array<A, B, AC, BC>()
    where
      sqlx::Postgres: CollectionStorage<
          A,
          ElementFilter<A>,
          Sequence = Sequence<A, sqlx::Postgres, AC>,
          Set = Unordered<A, sqlx::Postgres, AC>,
        > + CollectionStorage<
          B,
          ElementFilter<B>,
          Sequence = Sequence<B, sqlx::Postgres, BC>,
          Set = Unordered<B, sqlx::Postgres, BC>,
        >,
    {
    }

    both_take_the_array::<
      Temporal<time::OffsetDateTime>,
      time::OffsetDateTime,
      ScalarComparison<Temporal<time::OffsetDateTime>>,
      ScalarComparison<time::OffsetDateTime>,
    >();
    both_take_the_array::<
      Temporal<time::Date>,
      time::Date,
      ScalarComparison<Temporal<time::Date>>,
      ScalarComparison<time::Date>,
    >();
    both_take_the_array::<
      Temporal<time::Time>,
      time::Time,
      ScalarComparison<Temporal<time::Time>>,
      ScalarComparison<time::Time>,
    >();
    both_take_the_array::<
      &Temporal<time::OffsetDateTime>,
      &time::OffsetDateTime,
      ScalarComparison<&Temporal<time::OffsetDateTime>>,
      ScalarComparison<&time::OffsetDateTime>,
    >();

    let stamp: jiff::Timestamp = "2024-05-06T07:08:09.123456789Z".parse().unwrap();
    let plain = time::OffsetDateTime::from_unix_timestamp_nanos(stamp.as_nanosecond()).unwrap();

    // The annotation is half of each assertion: it is the CROSSING's answer, so a row that named
    // the edge table stops this compiling instead of rendering something else.
    let from_jiff: <sqlx::Postgres as CollectionStorage<
      Temporal<time::OffsetDateTime>,
      ElementFilter<Temporal<time::OffsetDateTime>>,
    >>::Set =
      Unordered::try_from_filter(SetFilter::<jiff::Timestamp>::new().with_encloses([stamp]))
        .unwrap();
    let from_time: <sqlx::Postgres as CollectionStorage<
      time::OffsetDateTime,
      ElementFilter<time::OffsetDateTime>,
    >>::Set = Unordered::try_from_filter(
      SetFilter::<time::OffsetDateTime, ScalarFilter<time::OffsetDateTime>>::new()
        .with_encloses([plain]),
    )
    .unwrap();

    assert_eq!(
      render::<sqlx::Postgres, _>("t", &from_jiff),
      ("\"t\" @> $1".to_owned(), 1)
    );
    assert_eq!(
      render::<sqlx::Postgres, _>("t", &from_jiff),
      render::<sqlx::Postgres, _>("t", &from_time)
    );

    // THE OPERAND, which the two renderings above cannot see: the same column, the same array OF
    // it, and the same bytes for the same instant. A Postgres array encodes its ELEMENT OID into
    // the operand, so the byte equality covers the type the engine is told as well as the value.
    assert_eq!(
      <Temporal<time::OffsetDateTime> as sqlx::Type<sqlx::Postgres>>::type_info(),
      <time::OffsetDateTime as sqlx::Type<sqlx::Postgres>>::type_info()
    );
    assert_eq!(
      <Temporal<time::OffsetDateTime> as sqlx::postgres::PgHasArrayType>::array_type_info(),
      <time::OffsetDateTime as sqlx::postgres::PgHasArrayType>::array_type_info()
    );
    assert_eq!(
      encoded(from_jiff.encloses().unwrap()),
      encoded(from_time.encloses().unwrap())
    );

    // ... and the equality is not two constant headers meeting: a different instant through the
    // same crossing encodes differently, which is what makes the one above a statement about the
    // VALUE. A second apart rather than a nanosecond, because a Postgres `TIMESTAMPTZ` bind
    // truncates to microseconds.
    let later: jiff::Timestamp = "2024-05-06T07:08:10.123456789Z".parse().unwrap();
    let from_later: Unordered<Temporal<time::OffsetDateTime>, sqlx::Postgres> =
      Unordered::try_from_filter(SetFilter::<jiff::Timestamp>::new().with_encloses([later]))
        .unwrap();
    assert_ne!(
      encoded(from_jiff.encloses().unwrap()),
      encoded(from_later.encloses().unwrap())
    );
  }

  /// One collection operand, encoded the way the Postgres lowering binds it — as ONE array
  /// parameter, through the element's own sqlx rows rather than through
  /// [`Carrier`](crate::comparison::sql::Carrier).
  ///
  /// It exists because the bound value is not observable from the rendered SQL, and an array's
  /// bind is not observable from a bind COUNT either: `@> $1` says the same thing whatever went
  /// into `$1` and whatever type the engine was told it is.
  #[cfg(all(feature = "jiff", feature = "time"))]
  fn encoded<V>(values: &[V]) -> Vec<u8>
  where
    V: sqlx::Type<sqlx::Postgres> + for<'q> sqlx::Encode<'q, sqlx::Postgres>,
  {
    let mut buf = sqlx::postgres::PgArgumentBuffer::default();
    let _ = sqlx::Encode::<sqlx::Postgres>::encode_by_ref(&values, &mut buf).unwrap();
    buf.to_vec()
  }

  /// The case the table exists for: a blob carrier binds fine as a scalar, sqlx names no array type
  /// for it, and before the table it resolved to the array strategy and then failed at the lowering.
  ///
  /// The type annotation on the binding is half the assertion — it is the crossing's answer, so a
  /// row that moved back to the array strategy stops compiling here rather than rendering something
  /// else.
  #[test]
  fn a_blob_carrier_reaches_the_edge_table() {
    let crossed: <sqlx::Postgres as CollectionStorage<BeU64, ElementFilter<BeU64>>>::Sequence =
      SqlEdgeComparison::try_from_filter(ListFilter::<u64>::new().with_has_element(7)).unwrap();

    // The harness's row is `p` keyed by `id`, so a `keys` column's elements are kept in `p_keys`.
    assert_eq!(
      render::<sqlx::Postgres, _>("keys", &crossed),
      (
        "EXISTS (SELECT 1 FROM \"p_keys\" WHERE \"p_keys\".\"id\" = \"p\".\"id\" AND \
         \"p_keys\".\"keys\" = $1)"
          .to_owned(),
        1
      )
    );
  }

  /// The other half, so the table is not read as "the array is what everything gets": an element
  /// with a usable array type still takes the array, and it is the same binding-annotation check.
  #[test]
  fn an_element_with_a_usable_array_type_keeps_it() {
    let crossed: <sqlx::Postgres as CollectionStorage<i64, ElementFilter<i64>>>::Set =
      Unordered::try_from_filter(SetFilter::<i64>::new().with_encloses([1i64])).unwrap();

    assert_eq!(
      render::<sqlx::Postgres, _>("t", &crossed),
      ("\"t\" @> $1".to_owned(), 1)
    );
  }

  /// The second thing the table buys, and the one that is a CHOICE rather than a fallback: an
  /// element type with a perfectly good `PgHasArrayType` naming the edge table anyway — a list long
  /// enough that an unindexed `@>` is the wrong plan, or an index shape an array cannot give.
  ///
  /// One row is the whole of it, and the row below is that row. It was unspellable while the dialect
  /// answered: `CollectionStorage for Postgres` said `Sequence` for every element and a
  /// second impl was `E0119`.
  #[test]
  fn an_array_capable_element_may_decline_the_array() {
    /// A downstream element that CAN be an array — all three sqlx traits, delegating to `i64` — and
    /// declines. `Carrier` is what the edge strategy lowers through, exactly as it would for any
    /// element joining that path.
    #[derive(Debug, Clone, Copy, PartialEq)]
    struct Crowded(i64);

    impl From<i64> for Crowded {
      fn from(value: i64) -> Self {
        Self(value)
      }
    }

    impl sqlx::Type<sqlx::Postgres> for Crowded {
      fn type_info() -> sqlx::postgres::PgTypeInfo {
        <i64 as sqlx::Type<sqlx::Postgres>>::type_info()
      }
    }

    impl sqlx::postgres::PgHasArrayType for Crowded {
      fn array_type_info() -> sqlx::postgres::PgTypeInfo {
        <i64 as sqlx::postgres::PgHasArrayType>::array_type_info()
      }
    }

    impl sqlx::Encode<'_, sqlx::Postgres> for Crowded {
      fn encode_by_ref(
        &self,
        buf: &mut sqlx::postgres::PgArgumentBuffer,
      ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
        <i64 as sqlx::Encode<'_, sqlx::Postgres>>::encode_by_ref(&self.0, buf)
      }
    }

    impl crate::comparison::sql::Carrier<sqlx::Postgres> for Crowded {
      fn push_bind(&self, qb: &mut sqlx::QueryBuilder<sqlx::Postgres>) {
        qb.push_bind(self.0);
      }
    }

    /// ONE column, the default body — the width beside the bind, which the scalar lowering reads.
    impl crate::ColumnKind for Crowded {}

    // THE ROW. Everything above is what makes the declining meaningful; these two lines are the
    // choice, and they are two because a row states one answer per shape.
    impl<VF: crate::comparison::ToDatabaseComparison<Crowded, sqlx::Postgres>>
      PgCollectionStorage<VF> for Crowded
    {
      type Sequence = SqlEdgeComparison<Crowded, VF::Comparison, sqlx::Postgres>;
      type Set = SqlEdgeSetComparison<Crowded, VF::Comparison, sqlx::Postgres>;
    }

    // The array strategy is genuinely available to it — asserted rather than assumed, since a type
    // that could not have taken the array would make the declining vacuous.
    fn array_is_available<V>()
    where
      Sequence<V, sqlx::Postgres>: ComplexComparison<sqlx::Postgres>,
      Unordered<V, sqlx::Postgres>: ComplexComparison<sqlx::Postgres>,
    {
    }
    array_is_available::<Crowded>();

    // The wrapper keeps the decision, which is where the seam would close if the wrapper answered
    // for itself: `Temporal` and `PgCollectionStorage` both belong to this crate, so a strategy the
    // wrapper could not re-state would be a gap the declaring party has no way to fill.
    #[cfg(all(feature = "jiff", feature = "time"))]
    {
      use crate::Temporal;

      fn the_wrapper_declines_too<V, C>()
      where
        sqlx::Postgres: CollectionStorage<
            Temporal<V>,
            ElementFilter<Temporal<V>>,
            Sequence = EdgeSequence<Temporal<V>, sqlx::Postgres, C>,
            Set = EdgeUnordered<Temporal<V>, sqlx::Postgres, C>,
          >,
      {
      }

      the_wrapper_declines_too::<Crowded, ScalarComparison<Temporal<Crowded>>>();
    }

    let crossed: <sqlx::Postgres as CollectionStorage<Crowded, ElementFilter<Crowded>>>::Set =
      SqlEdgeSetComparison::try_from_filter(SetFilter::<i64>::new().with_overlaps([1i64, 2]))
        .unwrap();

    let (sql, binds) = render::<sqlx::Postgres, _>("tags", &crossed);
    assert!(sql.starts_with("EXISTS (SELECT 1 FROM \"p_tags\""), "{sql}");
    assert!(
      !sql.contains("@>"),
      "the array operators are not on this path: {sql}"
    );
    assert_eq!(binds, 2);
  }
}

#[cfg(feature = "mysql")]
mod mysql {
  use super::{ListCrossingError, ORDERING, Sequence, Unordered};
  use crate::{
    FieldName, ListFilter, SetFilter,
    comparison::{
      At, ComplexComparison, TryFromFilter,
      sql::{
        SqlConjunction, SqlLoweringError,
        tests::{ROW, render, threaded},
      },
    },
  };

  /// MySQL's operand needs an explicit `CAST(? AS JSON)` — it has no implicit text-to-JSON
  /// assignment cast, so without it the functions would compare a string to an array.
  #[test]
  fn the_operand_is_cast_into_json() {
    let crossed = Unordered::<i64, sqlx::MySql>::try_from_filter(
      SetFilter::<i64>::new().with_overlaps([1i64, 2]),
    )
    .unwrap();

    assert_eq!(
      render::<sqlx::MySql, _>("t", &crossed),
      ("JSON_OVERLAPS(`t`, CAST(? AS JSON))".to_owned(), 1)
    );
  }

  #[test]
  fn every_set_operator_renders_its_own_conjunct() {
    let filter = SetFilter::<i64>::new()
      .with_eq([1i64])
      .with_ne([2i64])
      .with_encloses([3i64])
      .with_enclosed_by([4i64])
      .with_overlaps([5i64])
      .with_has_element(6i64);
    let crossed = Unordered::<i64, sqlx::MySql>::try_from_filter(filter).unwrap();

    assert_eq!(crossed.conjuncts(), 6);
    assert_eq!(
      render::<sqlx::MySql, _>("t", &crossed),
      (
        "( JSON_CONTAINS(`t`, CAST(? AS JSON)) AND JSON_CONTAINS(CAST(? AS JSON), `t`) ) AND \
         NOT ( ( JSON_CONTAINS(`t`, CAST(? AS JSON)) AND JSON_CONTAINS(CAST(? AS JSON), `t`) ) ) \
         AND JSON_CONTAINS(`t`, CAST(? AS JSON)) AND JSON_CONTAINS(CAST(? AS JSON), `t`) AND \
         JSON_OVERLAPS(`t`, CAST(? AS JSON)) AND JSON_CONTAINS(`t`, CAST(? AS JSON))"
          .to_owned(),
        8
      )
    );
  }

  /// The sequence kind's three answerable slots: MySQL's `=` on two JSON arrays is element-wise and
  /// order-sensitive, which is exactly the question this kind asks.
  #[test]
  fn every_sequence_operator_renders_its_own_conjunct() {
    let filter = ListFilter::<i64>::new()
      .with_eq([1i64])
      .with_ne([2i64])
      .with_has_element(3i64);
    let crossed = Sequence::<i64, sqlx::MySql>::try_from_filter(filter).unwrap();

    assert_eq!(crossed.conjuncts(), 3);
    assert_eq!(
      render::<sqlx::MySql, _>("t", &crossed),
      (
        "`t` = CAST(? AS JSON) AND NOT ( `t` = CAST(? AS JSON) ) AND \
         JSON_CONTAINS(`t`, CAST(? AS JSON))"
          .to_owned(),
        3
      )
    );
  }

  /// MySQL DOES define an ordering over JSON values, and it is not this one: it ranks by element
  /// TYPE before value, so `col < ?` would answer a different question under the same operator
  /// name.
  #[test]
  fn an_ordering_operator_is_refused_because_the_collection_is_json() {
    for (operator, filter) in [
      ("gt", ListFilter::<i64>::new().with_gt([1i64])),
      ("gte", ListFilter::<i64>::new().with_gte([1i64])),
      ("lt", ListFilter::<i64>::new().with_lt([1i64])),
      ("lte", ListFilter::<i64>::new().with_lte([1i64])),
    ] {
      let refused = Sequence::<i64, sqlx::MySql>::try_from_filter(filter);
      assert_eq!(
        refused.unwrap_err(),
        ListCrossingError::JsonOrdering(operator)
      );
    }
    assert_eq!(ORDERING, ["gt", "gte", "lt", "lte"]);
  }

  /// The threaded lowering reaches THIS dialect's leaf: `JSON_CONTAINS` / `JSON_OVERLAPS` over an
  /// operand cast into `JSON`, which is neither of the other two spellings.
  #[test]
  fn the_threaded_lowering_renders_this_dialect_leaf() {
    let crossed = Unordered::<i64, sqlx::MySql>::try_from_filter(
      SetFilter::<i64>::new()
        .with_encloses([3i64])
        .with_overlaps([5i64]),
    )
    .unwrap();

    assert_eq!(
      threaded::<sqlx::MySql, _>("t", &crossed),
      "SELECT \"id\" FROM \"t\" WHERE JSON_CONTAINS(`t`, CAST(? AS JSON)) AND \
       JSON_OVERLAPS(`t`, CAST(? AS JSON))"
    );
  }

  /// The one operator a collection kept in a MySQL `JSON` column cannot answer, refused at the
  /// LOWERING because an element scope is an ADDRESS and an address arrives with the application.
  ///
  /// Both kinds refuse, because the slot is on both and neither dialect half has a scope. What the
  /// refusal costs is stated where it is raised — `SqlLoweringError::JsonElementScope` carries the
  /// two measurements against MySQL 8.4.11 that rule out `JSON_TABLE`.
  #[test]
  fn an_element_question_is_refused_because_this_dialect_has_no_scope() {
    let set = Unordered::<i64, sqlx::MySql>::try_from_filter(
      SetFilter::<i64>::new().with_any(crate::ScalarFilter::new().with_eq(1)),
    )
    .unwrap();
    let sequence = Sequence::<i64, sqlx::MySql>::try_from_filter(
      ListFilter::<i64>::new().with_any(crate::ScalarFilter::new().with_eq(1)),
    )
    .unwrap();

    assert_eq!(refusal(&set), Some(SqlLoweringError::JsonElementScope));
    assert_eq!(refusal(&sequence), Some(SqlLoweringError::JsonElementScope));
  }

  /// What a refusal returns, and that it leaves the accumulator as it was found — the check runs
  /// BEFORE any slot is walked, so a refused statement has nothing half-written in it.
  ///
  /// It renders by hand rather than through the shared harness because the harness unwraps: what is
  /// under test here is the `Err`, and the buffer it left behind.
  fn refusal<C: ComplexComparison<sqlx::MySql>>(comparison: &C) -> Option<SqlLoweringError> {
    let mut qb = sqlx::QueryBuilder::<sqlx::MySql>::default();
    let frame = At::new(&ROW).frame(FieldName::new("t"));
    let error = {
      let out = SqlConjunction::with_lead(&mut qb, "");
      comparison.apply(frame.at(), out).err()
    };
    assert_eq!(qb.sql(), "");
    error
  }

  /// `JSON_LENGTH` is this dialect's cardinality, and it is the one element question its JSON column
  /// CAN answer: a scalar function over the stored value meets no optimizer transform, where the
  /// table function `any` would need does.
  ///
  /// Measured on MySQL 8.4.11: `JSON_LENGTH(CAST('[]' AS JSON))` is `0`, so the empty array counts
  /// as zero rather than as `NULL`.
  #[test]
  fn a_cardinality_is_json_length() {
    let crossed = Unordered::<i64, sqlx::MySql>::try_from_filter(
      SetFilter::<i64>::new().with_count(crate::ScalarFilter::new().with_gte(1)),
    )
    .unwrap();

    assert_eq!(
      render::<sqlx::MySql, _>("t", &crossed),
      ("JSON_LENGTH(`t`) >= ?".to_owned(), 1)
    );
  }
}

/// The one refusal left names the operator it declined, and reaches a downstream without any dialect
/// compiled — the crate's leanest build matches on the same type.
///
/// The variant that left with the shape parameter was an unordered column asked to compare as a
/// magnitude. It has no producer now and no type: [`SetFilter`](crate::SetFilter) has no ordering
/// slot, so the question is unaskable rather than answered with an error.
#[test]
fn the_crossing_error_names_the_operator_it_refused() {
  let json: ListCrossingError<core::convert::Infallible> = ListCrossingError::JsonOrdering("gt");

  assert!(json.to_string().contains("JSON"));
  assert!(json.to_string().contains("\"gt\""));
}

/// Each kind counts its own slots, without any dialect — the kind macro's arithmetic is not a
/// rendering detail, and the two kinds do not share a struct.
#[test]
fn each_kind_counts_its_own_slots() {
  let sequence: Sequence<i64, ()> = Sequence {
    eq: Some(Box::from([1i64])),
    lt: Some(Box::from([2i64])),
    ..Sequence::new()
  };
  let set: Unordered<i64, ()> = Unordered {
    eq: Some(Box::from([1i64])),
    overlaps: Some(Box::from([2i64])),
    ..Unordered::new()
  };

  assert_eq!(sequence.conjuncts(), 2);
  assert_eq!(set.conjuncts(), 2);
  assert_eq!(sequence.eq(), set.eq());
}