quarb-sql 0.50.0

SQL importer for the Quarb query engine
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
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
//! The reverse direction: Quarb → SQL.
//!
//! Walks the query's *reflection arbor* — the locked vocabulary is
//! the stable surface for query-rewriting tooling — and emits an
//! equivalent `SELECT` statement, refusing what the SQL query core
//! cannot express. Fragments and pure macros expand before
//! reflection, so they translate for free.
//!
//! The translatable subset mirrors the importer: `/table/*`
//! branches with predicates (→ `WHERE`), witness joins (`<=>` with
//! `$*1` equality → `JOIN ... ON`, remaining conditions → `WHERE`,
//! `$*k` select fields qualified), `rec(...)` select lists,
//! whole-table and grouped aggregates (`GROUP BY`, a filter after
//! the reduction → `HAVING`), `sort_by`/`reverse`/`top` →
//! `ORDER BY`/`LIMIT`, `@| [..n]` → `LIMIT`, and single-column
//! `unique` → `DISTINCT`.
//!
//! Deliberately refused: `-->` resolution chains — the foreign-key
//! targets live in the *schema*, not the query text, so a chain
//! cannot be compiled to a join without a database at hand; spell
//! the join explicitly with `<=>` to export it. Also refused:
//! registers beyond the grouped-aggregate pattern, windows,
//! captures, and regex matching (`LIKE` dialects disagree).
//!
//! Notes carry the standing divergences: truthiness (`[::c]` →
//! `IS NOT NULL`, but Quarb also treats `0` and `''` as falsy),
//! `*=` → `LIKE` case-folding dialects, and join cardinality
//! (Quarb's existential binding never multiplies rows; SQL `JOIN`
//! does when several left rows match).

use crate::{SqlError, Translation};
use quarb::reflect::QueryArbor;
use quarb::{AstAdapter, NodeId, Value};

/// Translate a Quarb query to a SQL `SELECT` statement.
pub fn export(quarb: &str) -> Result<Translation, SqlError> {
    refuse_marker(quarb)?;
    let arbor =
        QueryArbor::parse(quarb).map_err(|e| SqlError::Syntax(format!("parsing Quarb: {e}")))?;
    refuse_groups(&arbor)?;
    let mut ex = Exporter {
        arbor,
        notes: Vec::new(),
        strict: false,
        dialect: None,
        from_table: String::new(),
        join_on_cols: Vec::new(),
        join_table: None,
        column_types: ColumnTypes::default(),
        from_sql: String::new(),
        join_sql: None,
        in_on: false,
        aggregate: false,
        keyed_hops: false,
    };
    let query = ex.query()?;
    Ok(Translation {
        query,
        notes: ex.notes,
    })
}

/// The exporter rewrites `__LEFT__` (the join's left table) and
/// `__AGG__` (the HAVING aggregate) as internal placeholders.
/// Query text containing either marker would be rewritten inside
/// its own string literals — and could spoof the emitted SQL — so
/// such queries stay on the scan path.
fn refuse_marker(quarb: &str) -> Result<(), SqlError> {
    for marker in ["__LEFT__", "__AGG__"] {
        if quarb.contains(marker) {
            return Err(SqlError::Unsupported(format!(
                "query text contains the reserved marker \"{marker}\""
            )));
        }
    }
    Ok(())
}

/// A pushdown plan: SQL whose execution is provably identical to
/// the Quarb query's — plus the table whose primary key must order
/// the rows (`None` for a single aggregate row, where order is
/// moot). The driver appends the `ORDER BY`, since the key lives in
/// its catalog.
pub struct Pushdown {
    pub sql: String,
    pub order_table: Option<String>,
    /// Present when the plan contains a witness JOIN: the joined
    /// table and the columns its ON equalities bind on it
    /// (collected structurally from the arbor, so query text
    /// cannot spoof them).
    /// The plan is only sound if those columns form a unique key
    /// of the joined table — each FROM row must find at most one
    /// witness, else SQL multiplies rows where Quarb's existential
    /// binding does not. The *driver* must verify against its
    /// catalog before executing, and fall back to the scan if it
    /// cannot.
    pub join_left: Option<(String, Vec<String>)>,
    /// What the plan takes for granted about column types. Quarb
    /// compares by value (a numeric-looking text and a number meet
    /// as numbers, a number and other text never meet); SQL
    /// compares by the column's type, and the loosely typed engines
    /// (SQLite, MySQL) coerce by rules of their own. The plan is
    /// the scan's only where the columns it compares with a number
    /// are numeric-typed and those it compares with text are not:
    /// the caller asks its catalog and scans when one is otherwise.
    /// (A strictly typed engine rejects the mismatch itself, which
    /// sends the caller to the scan as well.)
    pub column_types: ColumnTypes,
    /// The tables the plan reads (the FROM table, then a joined one).
    pub tables: Vec<String>,
}

/// The column types a pushed plan assumes (see
/// [`Pushdown::column_types`]).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ColumnTypes {
    /// Columns compared with a numeric literal.
    pub numeric: Vec<String>,
    /// Columns compared with a text literal.
    pub text: Vec<String>,
    /// Columns the plan extracts a JSON path from on the strength
    /// of the column's declaration alone (the hop carried no
    /// `<json>`): the pushed `json_extract` is the scan's only where
    /// the catalog declares the column json, since the scan grafts
    /// a leaf only as declared (spec: Grafting).
    pub json: Vec<String>,
}

impl ColumnTypes {
    pub fn is_empty(&self) -> bool {
        self.numeric.is_empty() && self.text.is_empty() && self.json.is_empty()
    }

    /// The assumptions a catalog does not bear out: the columns
    /// compared with a number that are not numeric-typed, and those
    /// compared with text that are. `catalog` lists every column of
    /// the tables read, with whether its type is numeric and
    /// whether it is declared json; names meet without regard to
    /// case. A column the catalog does not list is unknown, and
    /// counts as unmet.
    pub fn unmet(&self, catalog: &[(String, bool, bool)]) -> Vec<String> {
        let met = |column: &str, pick: fn(&(String, bool, bool)) -> bool, want: bool| {
            let mut found = catalog
                .iter()
                .filter(|(name, ..)| name.eq_ignore_ascii_case(column))
                .peekable();
            found.peek().is_some() && found.all(|entry| pick(entry) == want)
        };
        let numeric = |e: &(String, bool, bool)| e.1;
        let json = |e: &(String, bool, bool)| e.2;
        let mut out: Vec<String> = Vec::new();
        for (columns, pick, want) in [
            (
                &self.numeric,
                numeric as fn(&(String, bool, bool)) -> bool,
                true,
            ),
            (&self.text, numeric, false),
            (&self.json, json, true),
        ] {
            for c in columns {
                if !met(c, pick, want) && !out.contains(c) {
                    out.push(c.clone());
                }
            }
        }
        out
    }
}

/// The target SQL dialect, for the one construct whose emitted
/// SQL is not portable: a filter that navigates *into* a JSON
/// column, which each engine extracts with its own operator.
/// The rest of a pushdown is dialect-agnostic. A query with no
/// JSON-column filter emits identical SQL regardless of dialect.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Dialect {
    Postgres,
    MySql,
    Sqlite,
    Mssql,
    Oracle,
}

/// Attempt the pushdown translation: `Some` only when every
/// construct in the query is in the verified-safe set. Anything
/// else — including everything `export` would merely annotate with
/// a divergence note — returns `None`, and the caller scans.
///
/// `dialect` enables JSON-column-path pushdown for that engine
/// (fixed-path string equality only); `None` keeps such filters
/// on the client-side graft.
pub fn pushdown(quarb: &str, dialect: Option<Dialect>) -> Option<Pushdown> {
    pushdown_explained(quarb, dialect).ok()
}

/// [`pushdown`], keeping the refusal: the error names the first
/// construct that kept the query on the scan path.
pub fn pushdown_explained(quarb: &str, dialect: Option<Dialect>) -> Result<Pushdown, SqlError> {
    refuse_marker(quarb)?;
    let arbor =
        QueryArbor::parse(quarb).map_err(|e| SqlError::Syntax(format!("parsing Quarb: {e}")))?;
    refuse_groups(&arbor)?;
    let mut ex = Exporter {
        arbor,
        notes: Vec::new(),
        strict: true,
        dialect,
        from_table: String::new(),
        join_on_cols: Vec::new(),
        join_table: None,
        column_types: ColumnTypes::default(),
        from_sql: String::new(),
        join_sql: None,
        in_on: false,
        aggregate: false,
        keyed_hops: false,
    };
    let sql = ex.query()?;
    let order_table = if ex.aggregate {
        None
    } else {
        // Rows come back in the driver's document order — the FROM
        // table's (driver-first correlation).
        Some(ex.from_table.clone())
    };
    let join_left = ex.join_table.clone().map(|t| (t, ex.join_on_cols.clone()));
    let mut tables = vec![ex.from_table.clone()];
    tables.extend(ex.join_table.clone());
    Ok(Pushdown {
        sql,
        order_table,
        join_left,
        column_types: ex.column_types.clone(),
        tables,
    })
}

/// The dialect-specific SQL that extracts a JSON scalar at a
/// fixed object path, unquoted to text. `path` holds plain
/// object keys (identifier-safe, per `json_path`), so no
/// per-dialect path-escaping is needed. Each engine's operator
/// returns the value as text and yields NULL for an absent path
/// or a non-scalar — matching the graft, which excludes those
/// rows too.
fn json_extract(dialect: Dialect, qual: Option<&str>, col: &str, path: &[String]) -> String {
    let qcol = match qual {
        Some(q) => format!("{q}.{col}"),
        None => col.to_string(),
    };
    match dialect {
        // `#>>` takes a text-array path and returns text; the
        // `::jsonb` cast lets it work on json, jsonb, and
        // text-holding-JSON columns alike (an invalid-JSON row
        // errors, and the driver falls back to the scan).
        Dialect::Postgres => format!("({qcol}::jsonb #>> '{{{}}}')", path.join(",")),
        // JSON_UNQUOTE(JSON_EXTRACT(...)) is the `->>` shorthand
        // spelled out — portable across MySQL and MariaDB, where
        // the `->>` operator itself is not.
        Dialect::MySql => {
            format!("JSON_UNQUOTE(JSON_EXTRACT({qcol}, '$.{}'))", path.join("."))
        }
        Dialect::Sqlite => format!("json_extract({qcol}, '$.{}')", path.join(".")),
        // JSON_VALUE returns a scalar as text (lax mode: NULL on a
        // missing path or a non-scalar, no error).
        Dialect::Mssql | Dialect::Oracle => format!("JSON_VALUE({qcol}, '$.{}')", path.join(".")),
    }
}

/// Wrap a JSON-path condition in the dialect's validity guard,
/// where a cheap one exists. SQLite and MySQL error the whole
/// statement on one malformed-JSON row — which turned every
/// pushdown over a dirty table into a silent fallback scan — and
/// the graft excludes such rows anyway (no parse, no subtree), so
/// the guard is observationally identical. SQL Server gets ISJSON;
/// Oracle's JSON_VALUE is lax already; PostgreSQL has no guard
/// short of the ::jsonb cast itself (an invalid row errors and the
/// caller falls back to the scan).
fn json_valid_guard(dialect: Dialect, qual: Option<&str>, col: &str, cond: String) -> String {
    let qcol = match qual {
        Some(q) => format!("{q}.{col}"),
        None => col.to_string(),
    };
    match dialect {
        Dialect::Sqlite => format!("(json_valid({qcol}) AND {cond})"),
        Dialect::MySql => format!("(JSON_VALID({qcol}) AND {cond})"),
        Dialect::Mssql => format!("(ISJSON({qcol}) = 1 AND {cond})"),
        Dialect::Postgres | Dialect::Oracle => format!("({cond})"),
    }
}

/// The dialect's JSON type probe at a fixed path — non-NULL iff
/// the path exists. A JSON `null` value reports its type ('null'),
/// so existence still sees it, matching the graft, where a
/// null-valued key is a node. Only the dialects with a native
/// probe participate.
fn json_type_probe(
    dialect: Dialect,
    qual: Option<&str>,
    col: &str,
    path: &[String],
) -> Option<String> {
    let qcol = match qual {
        Some(q) => format!("{q}.{col}"),
        None => col.to_string(),
    };
    match dialect {
        Dialect::Sqlite => Some(format!("json_type({qcol}, '$.{}')", path.join("."))),
        Dialect::Postgres => Some(format!(
            "jsonb_typeof({qcol}::jsonb #> '{{{}}}')",
            path.join(",")
        )),
        Dialect::MySql | Dialect::Mssql | Dialect::Oracle => None,
    }
}

/// Flip a comparison for a swapped operand order (`lit OP path` →
/// `path OP' lit`).
fn flip_op(op: &str) -> String {
    match op {
        "<" => ">".into(),
        "<=" => ">=".into(),
        ">" => "<".into(),
        ">=" => "<=".into(),
        other => other.into(),
    }
}

/// SQL keywords that must not appear as a bare identifier or `AS`
/// alias — quoting them portably differs by dialect, so strict
/// mode refuses and export mode quotes with double quotes plus a
/// note.
const SQL_KEYWORDS: &[&str] = &[
    "all",
    "and",
    "as",
    "asc",
    "by",
    "case",
    "cross",
    "desc",
    "distinct",
    "else",
    "end",
    "except",
    "exists",
    "from",
    "group",
    "having",
    "in",
    "index",
    "inner",
    "intersect",
    "into",
    "is",
    "join",
    "left",
    "like",
    "limit",
    "not",
    "null",
    "offset",
    "on",
    "or",
    "order",
    "outer",
    "right",
    "select",
    "set",
    "table",
    "then",
    "union",
    "unique",
    "update",
    "using",
    "values",
    "when",
    "where",
];

/// A bare SQL identifier, portable across the target dialects: a
/// letter or underscore, then letters, digits, and underscores,
/// and not a reserved word.
fn is_plain_ident(name: &str) -> bool {
    !name.is_empty()
        && name
            .chars()
            .next()
            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
        && !SQL_KEYWORDS.contains(&name.to_ascii_lowercase().as_str())
}

/// The SELECT under construction.
#[derive(Default)]
struct Select {
    select: Vec<String>,
    distinct: bool,
    from: String,
    join: Option<(String, String)>, // (table, ON condition)
    /// The join keeps every FROM row (`<=>?`, the outer
    /// correlation): a LEFT JOIN.
    join_outer: bool,
    wheres: Vec<String>,
    group_by: Option<String>,
    having: Option<String>,
    order_by: Option<(String, bool)>, // (expr, desc)
    limit: Option<String>,
}

impl Select {
    fn render(&self) -> String {
        let mut out = String::from("SELECT ");
        if self.distinct {
            out.push_str("DISTINCT ");
        }
        if self.select.is_empty() {
            out.push('*');
        } else {
            out.push_str(&self.select.join(", "));
        }
        out.push_str(&format!(" FROM {}", self.from));
        if let Some((t, on)) = &self.join {
            let kind = if self.join_outer { "LEFT JOIN" } else { "JOIN" };
            out.push_str(&format!(" {kind} {t} ON {on}"));
        }
        if !self.wheres.is_empty() {
            out.push_str(&format!(" WHERE {}", self.wheres.join(" AND ")));
        }
        if let Some(g) = &self.group_by {
            out.push_str(&format!(" GROUP BY {g}"));
        }
        if let Some(h) = &self.having {
            out.push_str(&format!(" HAVING {h}"));
        }
        if let Some((e, desc)) = &self.order_by {
            out.push_str(&format!(" ORDER BY {e}"));
            if *desc {
                out.push_str(" DESC");
            }
        }
        if let Some(n) = &self.limit {
            out.push_str(&format!(" LIMIT {n}"));
        }
        out
    }
}

/// A partial-pushdown plan: the leading row predicates as a WHERE
/// clause for `table`'s fetch. The caller runs the *original* query
/// against the filtered adapter — the engine re-applies the pushed
/// predicates (a no-op on pre-filtered rows), so no rewriting.
pub struct Partial {
    pub table: String,
    pub where_sql: String,
    /// As [`Pushdown::column_types`]: the prefilter keeps every row
    /// the scan would only where these assumptions hold.
    pub column_types: ColumnTypes,
}

/// Attempt a partial pushdown: `Some` when the query's leading row
/// predicates translate strictly and the rest of the query provably
/// cannot observe the filtering. The gates, each with its reason:
/// a single `/table/*` branch with no correlations (other shapes
/// address other data); only the *leading* run of expression
/// predicates pushes (a positional predicate before an expression
/// one sees unfiltered rows on the scan path); the table's name
/// appears exactly once among the query's steps (a second reach —
/// `^`-anchored subcontexts, self-references — would see the
/// filtered subset); no crosslink or resolution axes anywhere
/// (backlinks and reverse resolution into the table would too);
/// and no `:` / `:::` metadata anywhere (a filtered `:::n-rows`
/// would lie).
pub fn partial_pushdown(quarb: &str, dialect: Option<Dialect>) -> Option<Partial> {
    partial_pushdown_explained(quarb, dialect).ok()
}

/// [`partial_pushdown`], keeping the refusal reason. `dialect`
/// enables the JSON-column prefilters — the strict fixed-path
/// string equality, plus the relaxed superset forms (numeric
/// comparisons, existence) that are safe here and only here,
/// because the caller re-runs the original query over the
/// fetched subset.
pub fn partial_pushdown_explained(
    quarb: &str,
    dialect: Option<Dialect>,
) -> Result<Partial, SqlError> {
    partial_pushdown_with(quarb, dialect, false)
}

/// [`partial_pushdown_explained`] for an adapter that reads hops by
/// key and filters only the table's listing
/// (`RelationalModel::with_filtered_listing`): crosslinks and
/// resolutions no longer refuse the prefilter, since a hop into the
/// filtered table reads its row unfiltered. What still refuses: a
/// second navigation into the table, and a `<--` or `=>` scope that
/// could list it.
pub fn partial_pushdown_keyed(quarb: &str, dialect: Option<Dialect>) -> Result<Partial, SqlError> {
    partial_pushdown_with(quarb, dialect, true)
}

fn partial_pushdown_with(
    quarb: &str,
    dialect: Option<Dialect>,
    keyed_hops: bool,
) -> Result<Partial, SqlError> {
    refuse_marker(quarb)?;
    let arbor =
        QueryArbor::parse(quarb).map_err(|e| SqlError::Syntax(format!("parsing Quarb: {e}")))?;
    refuse_groups(&arbor)?;
    let mut ex = Exporter {
        arbor,
        notes: Vec::new(),
        strict: true,
        dialect,
        from_table: String::new(),
        join_on_cols: Vec::new(),
        join_table: None,
        column_types: ColumnTypes::default(),
        from_sql: String::new(),
        join_sql: None,
        in_on: false,
        aggregate: false,
        keyed_hops,
    };
    ex.partial()
}

/// Refuse a query carrying path-pattern groups: neither the SQL
/// translation nor the pushdown safe set covers them, and the shape
/// checks below count only `step` children — an unguarded group
/// would silently vanish from the translation. Refused queries fall
/// back to the scan path, which evaluates groups correctly.
fn refuse_groups(arbor: &QueryArbor) -> Result<(), SqlError> {
    let mut stack = vec![arbor.root()];
    while let Some(n) = stack.pop() {
        if arbor.name(n).as_deref() == Some("group") {
            return Err(SqlError::Unsupported(
                "path patterns (groups and quantifiers)".into(),
            ));
        }
        stack.extend(arbor.children(n));
    }
    Ok(())
}

struct Exporter {
    arbor: QueryArbor,
    notes: Vec<String>,
    /// Pushdown mode: refuse every construct whose SQL semantics
    /// are not provably identical to Quarb's (LIKE case folding,
    /// truthiness, group/distinct/sort ordering).
    strict: bool,
    /// The target dialect for JSON-column-path pushdown; `None`
    /// leaves such filters on the client-side graft.
    dialect: Option<Dialect>,
    from_table: String,
    join_on_cols: Vec<String>,
    join_table: Option<String>,
    /// What the comparisons assume of column types (see
    /// [`Pushdown::column_types`]).
    column_types: ColumnTypes,
    from_sql: String,
    join_sql: Option<String>,
    in_on: bool,
    aggregate: bool,
    /// The adapter reads hops by key (the pushed-down WHERE filters
    /// the table's listing only), so crosslinks and resolutions are
    /// safe beside the prefilter.
    keyed_hops: bool,
}

impl Exporter {
    fn kids(&self, n: NodeId, kind: &str) -> Vec<NodeId> {
        self.arbor
            .children(n)
            .into_iter()
            .filter(|&c| self.arbor.name(c).as_deref() == Some(kind))
            .collect()
    }

    fn kid(&self, n: NodeId, kind: &str) -> Option<NodeId> {
        self.kids(n, kind).into_iter().next()
    }

    fn prop(&self, n: NodeId, key: &str) -> Option<Value> {
        self.arbor.property(n, key)
    }

    fn prop_s(&self, n: NodeId, key: &str) -> String {
        self.prop(n, key).map(|v| v.to_string()).unwrap_or_default()
    }

    fn kind(&self, n: NodeId) -> String {
        self.arbor.name(n).unwrap_or_default()
    }

    /// Whether `n` is a bare `null` literal operand.
    fn is_null_literal(&self, n: NodeId) -> bool {
        self.kind(n) == "literal" && self.prop_s(n, "type") == "null"
    }

    /// The partial-pushdown analysis (see [`partial_pushdown`]).
    fn partial(&mut self) -> Result<Partial, SqlError> {
        let root = self.arbor.root();
        let q = self
            .kid(root, "query")
            .ok_or_else(|| SqlError::Unsupported("empty query".into()))?;
        // A correlation does not forbid the prefilter: the driver's
        // own predicates restrict the driver's rows whatever the join
        // then binds. What must not happen is the join (or anything
        // else) reaching the filtered table a second time — a
        // self-join would see only the filtered rows — and the
        // whole-query gates below refuse exactly that: they walk the
        // correlation entries too.
        let branches = self.kids(q, "branch");
        if branches.len() != 1 {
            return Err(SqlError::Unsupported("a branch union".into()));
        }
        let (table, preds) = self.table_branch_lead(branches[0], self.keyed_hops)?;

        // Whole-query gates.
        let all = self.walk_all(root);
        let mut table_mentions = 0;
        for n in &all {
            match self.kind(*n).as_str() {
                "step" => {
                    let axis = self.prop_s(*n, "axis");
                    // A crosslink, a resolution or a value match may
                    // land in (or search) the filtered table and would
                    // see only its filtered rows: `=>` and the scoped
                    // `<--` carry their scope as text, so the table
                    // count below cannot see them.
                    if matches!(axis.as_str(), "->" | "<-" | "--" | "-->" | "<--" | "=>") {
                        // Where hops are read by key they are exact
                        // beside the prefilter. A scope is a listing,
                        // though: it is safe only when it plainly
                        // lists another table (`/other/…`), and an
                        // unscoped `=>` walks every table.
                        let scope = self.prop_s(*n, "scope");
                        let lists_other_table = scope
                            .strip_prefix('/')
                            .and_then(|rest| rest.split(['/', '[', '<']).next())
                            .is_some_and(|first| {
                                !first.is_empty()
                                    && first != table
                                    && first.chars().all(|c| c.is_alphanumeric() || c == '_')
                            });
                        let safe = self.keyed_hops
                            && if scope.is_empty() {
                                axis != "=>"
                            } else {
                                lists_other_table
                            };
                        if !safe {
                            return Err(SqlError::Unsupported(
                                "crosslink/resolution axes could reach \
                                 the filtered table"
                                    .into(),
                            ));
                        }
                    }
                    if self.prop_s(*n, "matcher") == table {
                        table_mentions += 1;
                    }
                }
                "projection" if self.prop_s(*n, "kind") != "property" => {
                    return Err(SqlError::Unsupported(
                        "metadata would observe the filtering \
                         (:::n-rows, :index)"
                            .into(),
                    ));
                }
                _ => {}
            }
        }
        if table_mentions != 1 {
            return Err(SqlError::Unsupported(
                "the table is reached more than once".into(),
            ));
        }

        // The leading run of expression predicates. Strict
        // translation first; a predicate the strict translator
        // refuses tries the relaxed prefilter ladder — superset
        // semantics: the fetched set may hold extra rows, because
        // the caller re-runs the ORIGINAL query, which re-applies
        // every predicate; it must never lose a matching row. An
        // untranslatable predicate is skipped, not fatal — a
        // shorter conjunction is still a superset filter. A
        // positional predicate (index/range) ends the run:
        // predicates after it filter a positionally-selected
        // subsequence.
        let mut conds = Vec::new();
        for p in preds {
            if self.prop_s(p, "kind") != "expr" {
                break;
            }
            match self.predicate_cond(p, None) {
                Ok(c) => conds.push(c),
                Err(_) => {
                    if let Some(c) = self.prefilter_cond(p) {
                        conds.push(c);
                    }
                }
            }
        }
        if conds.is_empty() {
            return Err(SqlError::Unsupported(
                "no leading expression predicates to push".into(),
            ));
        }
        Ok(Partial {
            table,
            where_sql: conds.join(" AND "),
            column_types: self.column_types.clone(),
        })
    }

    /// The relaxed prefilter for one refused expression predicate:
    /// the AND of whatever conjuncts translate, each a superset of
    /// the rows its Quarb counterpart keeps. None when nothing
    /// does — the predicate stays entirely on the engine.
    fn prefilter_cond(&mut self, p: NodeId) -> Option<String> {
        let parts: Vec<String> = self
            .arbor
            .children(p)
            .into_iter()
            .filter_map(|c| {
                self.pred_expr(c, None)
                    .ok()
                    .or_else(|| self.prefilter_expr(c))
            })
            .collect();
        if parts.is_empty() {
            None
        } else {
            Some(parts.join(" AND "))
        }
    }

    /// One conjunct's superset prefilter — fixed-path JSON shapes
    /// only, per dialect. Every form here is proven to keep every
    /// row the graft would match (extras are fine; the engine
    /// re-checks). The proofs lean on three graft facts: absent
    /// paths match no comparison; `value_eq`/`value_cmp` coerce
    /// numeric-looking strings numerically; and Str-to-Str
    /// ordering is bytewise.
    fn prefilter_expr(&mut self, e: NodeId) -> Option<String> {
        let dialect = self.dialect?;
        match self.kind(e).as_str() {
            // A bare truthy path: existence (with `::`, value
            // truthiness — existence is its superset). The type
            // probe sees JSON null too, as the graft does.
            "path" => {
                let (col, path) = self.json_path_loose(e)?;
                self.note_json_column(e, &col);
                let probe = json_type_probe(dialect, None, &col, &path)?;
                Some(json_valid_guard(
                    dialect,
                    None,
                    &col,
                    format!("{probe} IS NOT NULL"),
                ))
            }
            "compare" => {
                let op = self.prop_s(e, "op");
                let kids = self.arbor.children(e);
                if kids.len() != 2 {
                    return None;
                }
                for (pi, li) in [(0usize, 1usize), (1, 0)] {
                    let Some((col, path)) = self.json_path(kids[pi]) else {
                        continue;
                    };
                    if self.kind(kids[li]) != "literal" {
                        continue;
                    }
                    let ty = self.prop_s(kids[li], "type");
                    if ty == "null" {
                        return None;
                    }
                    let raw = self
                        .prop(kids[li], "value")
                        .map(|v| v.to_string())
                        .unwrap_or_default();
                    let op = if pi == 0 { op.clone() } else { flip_op(&op) };
                    self.note_json_column(kids[pi], &col);
                    return self.json_prefilter(dialect, &col, &path, &op, &ty, &raw);
                }
                None
            }
            _ => None,
        }
    }

    /// Build the dialect's superset prefilter for
    /// `json_path OP literal`.
    fn json_prefilter(
        &self,
        d: Dialect,
        col: &str,
        path: &[String],
        op: &str,
        lit_ty: &str,
        raw: &str,
    ) -> Option<String> {
        if !matches!(op, "=" | "!=" | "<" | "<=" | ">" | ">=") {
            return None;
        }
        // `!=` matches every present path whose value isn't the
        // literal — including JSON null and cross-typed values —
        // so its floor is existence.
        if op == "!=" {
            let probe = json_type_probe(d, None, col, path)?;
            return Some(json_valid_guard(
                d,
                None,
                col,
                format!("{probe} IS NOT NULL"),
            ));
        }
        let numeric_lit = raw.trim().parse::<f64>().is_ok_and(|f| f.is_finite())
            && (lit_ty != "text" || !raw.trim().is_empty());
        if numeric_lit {
            let num: f64 = raw.trim().parse().ok()?;
            // Past 2^53 the engines' exact integers and the
            // graft's f64 part ways at the boundary.
            if num.abs() >= 9_007_199_254_740_992.0 {
                return None;
            }
            let lit = raw.trim();
            match d {
                // Typed extract: JSON numbers compare numerically
                // (both sides parse the same source text to f64);
                // string values escape through the type probe —
                // the graft may coerce them, the server must not
                // drop them.
                Dialect::Sqlite => {
                    let ex = json_extract(d, None, col, path);
                    let ty = json_type_probe(d, None, col, path)?;
                    Some(json_valid_guard(
                        d,
                        None,
                        col,
                        format!("({ex} {op} {lit} OR {ty} = 'text')"),
                    ))
                }
                // float8 is the graft's f64; jsonb numbers print
                // exactly, so the cast parses the same decimal.
                // Strings escape; everything else can't match.
                Dialect::Postgres => {
                    let text = json_extract(d, None, col, path);
                    let ty = json_type_probe(d, None, col, path)?;
                    Some(format!(
                        "(CASE WHEN {ty} = 'number' THEN ({text})::float8 {op} {lit} \
                         WHEN {ty} = 'string' THEN true ELSE false END)"
                    ))
                }
                Dialect::MySql | Dialect::Mssql | Dialect::Oracle => None,
            }
        } else if lit_ty == "text" {
            if raw.contains('\'') || raw.contains('\\') {
                return None;
            }
            match d {
                // Typed extract again: string values order bytewise
                // on both sides; numbers and booleans sit below
                // text in SQLite's cross-type order, so `<` keeps
                // them (extras, re-checked) and `>` drops them
                // (the graft refuses to order Str against them).
                Dialect::Sqlite => {
                    let ex = json_extract(d, None, col, path);
                    Some(json_valid_guard(d, None, col, format!("{ex} {op} '{raw}'")))
                }
                // Text ordering elsewhere runs into collation; the
                // engine keeps those.
                _ => None,
            }
        } else {
            None
        }
    }

    /// [`json_path`], loosened for existence: the projection may
    /// be absent (a bare structural path) as well as the bare
    /// `::`.
    /// Whether a JSON path under a column reads the column as JSON
    /// on the strength of its declaration alone: the column hop
    /// (the first step) carries no `<json>` trait. Such a column is
    /// an assumption of the plan ([`ColumnTypes::json`]); with the
    /// trait the graft is declared on the hop and holds on both
    /// roads.
    fn note_json_column(&mut self, o: NodeId, col: &str) {
        let declared_on_hop = self.kids(o, "step").first().is_some_and(|s| {
            self.kids(*s, "trait").iter().any(|t| {
                matches!(self.prop(*t, "alts"), Some(Value::List(alts))
                    if alts.iter().any(|a| matches!(a, Value::Str(x) if x == "json")))
            })
        });
        if !declared_on_hop && !self.column_types.json.iter().any(|c| c == col) {
            self.column_types.json.push(col.to_string());
        }
    }

    fn json_path_loose(&self, o: NodeId) -> Option<(String, Vec<String>)> {
        if self.json_path(o).is_some() {
            return self.json_path(o);
        }
        if self.kind(o) != "path" || self.kid(o, "projection").is_some() {
            return None;
        }
        let steps = self.kids(o, "step");
        if steps.len() < 2 {
            return None;
        }
        let mut names = Vec::with_capacity(steps.len());
        for s in &steps {
            if self.prop_s(*s, "axis") != "/"
                || self.prop_s(*s, "matcher-kind") != "name"
                || self.kid(*s, "predicate").is_some()
            {
                return None;
            }
            let name = self.prop_s(*s, "matcher");
            let plain = !name.is_empty()
                && name
                    .chars()
                    .next()
                    .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
                && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
            if !plain {
                return None;
            }
            names.push(name);
        }
        let col = names.remove(0);
        Some((col, names))
    }

    fn walk_all(&self, n: NodeId) -> Vec<NodeId> {
        let mut out = vec![n];
        let mut i = 0;
        while i < out.len() {
            out.extend(self.arbor.children(out[i]));
            i += 1;
        }
        out
    }

    fn query(&mut self) -> Result<String, SqlError> {
        let root = self.arbor.root();
        let q = self
            .kid(root, "query")
            .ok_or_else(|| SqlError::Unsupported("empty query".into()))?;
        let mut sel = Select::default();

        // Correlations: exactly one becomes the JOIN's left table.
        let corrs = self.kids(q, "query");
        let branches = self.kids(q, "branch");
        if branches.len() != 1 {
            return Err(SqlError::Unsupported(
                "a branch union (SQL has UNION, but result shapes differ; export one branch)"
                    .into(),
            ));
        }

        if corrs.len() > 1 {
            return Err(SqlError::Unsupported(
                "more than one correlation context".into(),
            ));
        }
        if let Some(corr) = corrs.first() {
            // Driver-first: the query's own branch is the FROM
            // table (the driver); the correlation entry is the
            // joined table, whose `$$` equalities form the ON.
            let (ltable, lpreds) = self.table_branch(branches[0])?;
            let (rtable, rpreds) = self.table_branch(self.kids(*corr, "branch")[0])?;
            // The SQL renderings of the two table names (validated
            // or quoted); the raw names stay in the plan metadata,
            // which the driver matches against its catalog.
            let lsql = self.sql_ident(&ltable, "table name")?;
            let rsql = self.sql_ident(&rtable, "table name")?;
            self.from_sql = lsql.clone();
            self.join_sql = Some(rsql.clone());
            // The driver's own predicates are plain WHERE.
            let driver_conds: Vec<NodeId> = lpreds;
            // Split the joined expression's predicates: `$$`
            // equalities form the ON, the rest the WHERE.
            let mut on = Vec::new();
            let mut wheres = Vec::new();
            for p in rpreds {
                self.split_join_pred(p, &rsql, &mut on, &mut wheres)?;
            }
            // `<=>?` — the outer correlation keeps a driver row no
            // joined row admits, its witness null: a LEFT JOIN. The
            // joined expression's own predicates then select the
            // witness, so they belong to the ON; in a WHERE they
            // would discard the unmatched rows again.
            let outer = matches!(self.prop(*corr, "outer"), Some(Value::Bool(true)));
            if outer {
                on.append(&mut wheres);
            }
            sel.join_outer = outer;
            if on.is_empty() {
                return Err(SqlError::Unsupported(
                    "a correlation without a '$$' equality (no JOIN condition)".into(),
                ));
            }
            for p in driver_conds {
                let cond = self.predicate_cond(p, Some(&lsql.clone()))?;
                wheres.push(cond);
            }
            self.notes.push(
                "JOIN: Quarb's binding is existential (one row per FROM row, \
                 bound to its first witness); SQL multiplies rows when \
                 several joined rows match"
                    .to_string(),
            );
            sel.from = lsql.clone();
            self.from_table = ltable;
            self.join_table = Some(rtable);
            sel.join = Some((rsql.clone(), on.join(" AND ")));
            sel.wheres = wheres;
            // A terminal projection on the driving branch is a
            // one-column select of the FROM table.
            if let Some(proj) = self.kid(branches[0], "projection") {
                let col = self.projection_col(proj)?;
                let col = self.sql_ident(&col, "column name")?;
                sel.select.push(format!("{lsql}.{col}"));
            }
            if self
                .kid(self.kids(*corr, "branch")[0], "projection")
                .is_some()
            {
                return Err(SqlError::Unsupported(
                    "a projection on the joined expression (project the witness \
                     in the pipeline: '$*1::col')"
                        .into(),
                ));
            }
            self.pipeline(q, &mut sel, Some((&lsql, &rsql)))?;
        } else {
            let (table, preds) = self.table_branch(branches[0])?;
            sel.from = self.sql_ident(&table, "table name")?;
            self.from_table = table;
            for p in preds {
                let cond = self.predicate_cond(p, None)?;
                sel.wheres.push(cond);
            }
            // A terminal projection is a one-column select.
            if let Some(proj) = self.kid(branches[0], "projection") {
                let col = self.projection_col(proj)?;
                sel.select.push(self.sql_ident(&col, "column name")?);
            }
            self.pipeline(q, &mut sel, None)?;
        }
        Ok(sel.render())
    }

    /// A `/table/*[preds]` branch: the table name and the row-step
    /// predicate nodes.
    fn table_branch(&mut self, b: NodeId) -> Result<(String, Vec<NodeId>), SqlError> {
        self.table_branch_lead(b, false)
    }

    /// [`table_branch`]; with `more`, the branch may go on after
    /// `/table/*[…]` (a hop, a cell): the prefilter concerns its
    /// first two steps only, and the steps after them are held to
    /// the whole-query gates.
    fn table_branch_lead(
        &mut self,
        b: NodeId,
        more: bool,
    ) -> Result<(String, Vec<NodeId>), SqlError> {
        let steps = self.kids(b, "step");
        if steps.len() < 2 || (steps.len() > 2 && !more) {
            return Err(SqlError::Unsupported(
                "navigation beyond /table/* (SQL sees tables and rows)".into(),
            ));
        }
        let (t, rows) = (steps[0], steps[1]);
        if self.prop_s(t, "axis") != "/"
            || self.prop_s(t, "matcher-kind") != "name"
            || self.prop_s(rows, "axis") != "/"
            || self.prop_s(rows, "matcher-kind") != "any"
        {
            return Err(SqlError::Unsupported(
                "navigation beyond /table/* (SQL sees tables and rows)".into(),
            ));
        }
        if self.kid(t, "predicate").is_some() {
            return Err(SqlError::Unsupported("a predicate on the table hop".into()));
        }
        Ok((self.prop_s(t, "matcher"), self.kids(rows, "predicate")))
    }

    /// One row predicate as a WHERE condition (qualify columns with
    /// `qualifier` when joining).
    fn predicate_cond(&mut self, p: NodeId, qual: Option<&str>) -> Result<String, SqlError> {
        if self.prop_s(p, "kind") != "expr" {
            return Err(SqlError::Unsupported(
                "a positional predicate on rows (SQL rows are unordered; ORDER BY + LIMIT)".into(),
            ));
        }
        let parts: Vec<String> = self
            .arbor
            .children(p)
            .into_iter()
            .map(|c| self.pred_expr(c, qual))
            .collect::<Result<_, _>>()?;
        Ok(parts.join(" AND "))
    }

    fn pred_expr(&mut self, e: NodeId, qual: Option<&str>) -> Result<String, SqlError> {
        match self.kind(e).as_str() {
            "and" | "or" => {
                let op = self.kind(e).to_uppercase();
                let kids: Vec<String> = self
                    .arbor
                    .children(e)
                    .into_iter()
                    .map(|c| self.pred_expr(c, qual))
                    .collect::<Result<_, _>>()?;
                Ok(format!("({})", kids.join(&format!(" {op} "))))
            }
            "not" => {
                // SQL's `NOT` propagates UNKNOWN: `NOT (x = 5)` is
                // UNKNOWN for a NULL `x` and drops the row, but Quarb's
                // negation keeps it (the inner `value_eq` is false, so
                // its negation is true). Not provably identical without
                // the schema — the pushdown paths refuse it and scan.
                if self.strict {
                    return Err(SqlError::Semantics(
                        "SQL NOT propagates UNKNOWN, dropping the NULL rows \
                         Quarb keeps"
                            .into(),
                    ));
                }
                let inner: Vec<String> = self
                    .arbor
                    .children(e)
                    .into_iter()
                    .map(|c| self.pred_expr(c, qual))
                    .collect::<Result<_, _>>()?;
                Ok(format!("NOT ({})", inner.join(" AND ")))
            }
            "parens" => {
                let inner: Vec<String> = self
                    .arbor
                    .children(e)
                    .into_iter()
                    .map(|c| self.pred_expr(c, qual))
                    .collect::<Result<_, _>>()?;
                Ok(format!("({})", inner.join(" AND ")))
            }
            "compare" => {
                let op = self.prop_s(e, "op");
                let kids = self.arbor.children(e);
                // A comparison against a bare `null` literal. Quarb's
                // `value_eq` treats NULL as an ordinary value
                // (`value_eq(NULL, NULL)` is true, `value_eq(NULL, x)`
                // false), so `= null` keeps exactly the NULL rows and
                // `!= null` the non-NULL rows. SQL's `= NULL` / `<>
                // NULL` are always UNKNOWN and drop every row; the
                // `IS [NOT] NULL` forms are provably identical (and
                // portable across every target dialect).
                if matches!(op.as_str(), "=" | "!=")
                    && (self.is_null_literal(kids[0]) || self.is_null_literal(kids[1]))
                {
                    let other = if self.is_null_literal(kids[0]) {
                        kids[1]
                    } else {
                        kids[0]
                    };
                    let col = self.operand(other, qual)?;
                    return Ok(if op == "=" {
                        format!("{col} IS NULL")
                    } else {
                        format!("{col} IS NOT NULL")
                    });
                }
                // JSON-column-path pushdown: `[/col/a/b:: = 'lit']`
                // navigates into a JSON column and compares a fixed
                // path to a string literal. Only this exact shape —
                // fixed object path, string equality, and a literal
                // that does NOT look numeric — is provably identical
                // to the client-side graft (each engine's scalar
                // extractor unquotes to text, and an absent path or
                // non-string value excludes the row on both sides,
                // matching Quarb's `value_eq` on non-numeric text).
                // Numeric casts, `!=`, wildcards, and deeper
                // predicates fall through to the ordinary operand
                // logic below, which refuses the navigation; the
                // partial-pushdown prefilter ladder picks those up
                // with superset semantics. Enabled only when a
                // dialect is set.
                if op == "="
                    && let Some(dialect) = self.dialect
                {
                    for (pi, li) in [(0usize, 1usize), (1, 0)] {
                        if self.is_text_literal(kids[li])
                            && let Some((col, path)) = self.json_path(kids[pi])
                        {
                            self.note_json_column(kids[pi], &col);
                            // Quarb's value_eq compares numeric-looking
                            // strings numerically — '150' matches the
                            // JSON number 150, and the string "150.0".
                            // No engine's text extractor coerces that
                            // way, so the pushed compare would drop
                            // rows the graft keeps. Refuse; the
                            // prefilter ladder handles it as a
                            // superset.
                            let raw = self
                                .prop(kids[li], "value")
                                .map(|v| v.to_string())
                                .unwrap_or_default();
                            if raw.trim().parse::<f64>().is_ok() {
                                return Err(SqlError::Semantics(
                                    "a numeric-looking text literal against a \
                                     JSON path compares numerically in Quarb \
                                     (value coercion); no SQL extractor \
                                     matches that"
                                        .into(),
                                ));
                            }
                            let lit = self.operand(kids[li], qual)?;
                            let extract = json_extract(dialect, qual, &col, &path);
                            return Ok(json_valid_guard(
                                dialect,
                                qual,
                                &col,
                                format!("{extract} = {lit}"),
                            ));
                        }
                    }
                }
                // Any other JSON-path comparison: name the real
                // reason, not the generic flat-rows refusal — only
                // fixed-path string equality is provably identical
                // (Quarb coerces numeric-looking values; no
                // engine's extractor matches that). The partial
                // prefilter ladder covers these shapes.
                if self.dialect.is_some() {
                    for side in [kids[0], kids[1]] {
                        if self.json_path(side).is_some() || self.json_path_loose(side).is_some() {
                            return Err(SqlError::Semantics(
                                "a JSON-path comparison pushes whole only as \
                                 fixed-path string equality (Quarb coerces \
                                 numeric-looking values; no extractor matches \
                                 that); this shape rides the partial prefilter"
                                    .into(),
                            ));
                        }
                    }
                }
                // Quarb compares by value; SQL by the column's type.
                // A column against a numeric literal is the scan's
                // comparison only on a numeric-typed column, and
                // against a text literal only on a column that is
                // not (MySQL reads `n = 'abc'` as `n = 0`): the
                // catalog decides, so both are recorded for the
                // caller. A numeric-looking TEXT literal meets
                // numbers as a number in Quarb and compares as text
                // in SQL, on every engine, so it does not push.
                if self.strict {
                    for (ci, li) in [(0usize, 1usize), (1, 0)] {
                        let Some(column) = self.column_operand(kids[ci]) else {
                            continue;
                        };
                        if self.kind(kids[li]) != "literal" {
                            continue;
                        }
                        let numeric = self
                            .prop(kids[li], "value")
                            .is_some_and(|v| Value::Str(v.to_string()).numeric_reading().is_some());
                        let list = match (self.prop_s(kids[li], "type").as_str(), numeric) {
                            ("null", _) => continue,
                            ("text", true) => {
                                return Err(SqlError::Semantics(
                                    "a numeric-looking text literal compares \
                                     numerically in Quarb (value coercion); SQL \
                                     compares it as text"
                                        .into(),
                                ));
                            }
                            ("text", false) => &mut self.column_types.text,
                            (_, true) => &mut self.column_types.numeric,
                            (_, false) => continue,
                        };
                        if !list.contains(&column) {
                            list.push(column);
                        }
                    }
                }
                let l = self.operand(kids[0], qual)?;
                // Ruling #33: a pattern literal on `=` pushes as
                // LIKE — a `%` per star, each literal segment
                // escaped, in order. Anchoring matches exactly:
                // LIKE anchors both ends, a flanking star lifts
                // one. The case-folding caveat is `*=`'s; `!=`
                // with a pattern rides the scan (NOT LIKE drops
                // the NULL rows Quarb keeps).
                if self.kind(kids[1]) == "pattern" {
                    if op.as_str() != "=" {
                        return Err(SqlError::Unsupported(format!(
                            "a pattern literal on '{op}' (only '=' pushes)"
                        )));
                    }
                    // PostgreSQL's LIKE is case-sensitive under its
                    // deterministic collations — provably what the
                    // pattern test does — so the strict push is
                    // sound there (and a prefix pattern is
                    // index-sargable server-side). Everywhere else
                    // case folding is ambient state (SQLite pragma,
                    // MySQL/MSSQL collation), so strict refuses.
                    if self.strict && self.dialect != Some(Dialect::Postgres) {
                        return Err(SqlError::Semantics(
                            "LIKE case folding differs per engine \
                             (provably case-sensitive only on PostgreSQL)"
                                .into(),
                        ));
                    }
                    if !self.strict {
                        self.notes.push(
                            "pattern → LIKE: Quarb's pattern test is \
                             case-sensitive; LIKE folds case on \
                             SQLite/MySQL but not PostgreSQL"
                                .to_string(),
                        );
                    }
                    let mut like = String::new();
                    for kid in self.arbor.children(kids[1]) {
                        match self.kind(kid).as_str() {
                            "star" => like.push('%'),
                            _ => {
                                let raw = self
                                    .prop(kid, "value")
                                    .map(|v| v.to_string())
                                    .unwrap_or_default();
                                like.push_str(
                                    &raw.replace('\\', "\\\\")
                                        .replace('%', "\\%")
                                        .replace('_', "\\_")
                                        .replace('\'', "''"),
                                );
                            }
                        }
                    }
                    return Ok(format!("{l} LIKE '{like}' ESCAPE '\\'"));
                }
                let r = self.operand(kids[1], qual)?;
                Ok(match op.as_str() {
                    "=" => format!("{l} = {r}"),
                    "!=" => {
                        // Quarb keeps rows whose operand is NULL (its
                        // `value_eq` is false there, so `!=` is true);
                        // SQL's `<>` is UNKNOWN for a NULL operand and
                        // drops those rows. Not provably identical
                        // without the schema, so pushdown refuses it;
                        // the display translation keeps `<>` and notes
                        // the divergence.
                        if self.strict {
                            return Err(SqlError::Semantics(
                                "'!=' drops the NULL rows Quarb keeps \
                                 (SQL '<>' is UNKNOWN for NULL; use '!= null' \
                                 for IS NOT NULL)"
                                    .into(),
                            ));
                        }
                        self.notes.push(
                            "'!=' → '<>': Quarb keeps rows whose column is NULL; \
                             SQL's '<>' drops them (use '!= null' for IS NOT NULL)"
                                .to_string(),
                        );
                        format!("{l} <> {r}")
                    }
                    "<" | "<=" | ">" | ">=" => format!("{l} {op} {r}"),
                    "*=" => {
                        // The same PostgreSQL rung as the pattern
                        // literal above: LIKE is provably
                        // case-sensitive there, so `*=` pushes
                        // strict too.
                        if self.strict && self.dialect != Some(Dialect::Postgres) {
                            return Err(SqlError::Semantics(
                                "LIKE case folding differs per engine \
                                 (provably case-sensitive only on PostgreSQL)"
                                    .into(),
                            ));
                        }
                        // The pattern must be a text literal: a
                        // column or computed operand holds a value,
                        // not a pattern, and SQL LIKE cannot express
                        // "contains that value" portably.
                        if !self.is_text_literal(kids[1]) {
                            return Err(SqlError::Unsupported(
                                "'*=' with a non-literal pattern".into(),
                            ));
                        }
                        self.notes.push(
                            "*= → LIKE: Quarb's substring test is case-sensitive; LIKE \
                             folds case on SQLite/MySQL but not PostgreSQL"
                                .to_string(),
                        );
                        // Escape LIKE's metacharacters, then quote.
                        // The explicit ESCAPE makes '\' the escape
                        // everywhere — SQLite, MSSQL, and Oracle
                        // have no default escape character.
                        let raw = self
                            .prop(kids[1], "value")
                            .map(|v| v.to_string())
                            .unwrap_or_default();
                        let pat = raw
                            .replace('\\', "\\\\")
                            .replace('%', "\\%")
                            .replace('_', "\\_")
                            .replace('\'', "''");
                        format!("{l} LIKE '%{pat}%' ESCAPE '\\'")
                    }
                    "==" | "!==" | "=~" | "!~" => {
                        return Err(SqlError::Semantics(
                            "regex matching means a different REGEXP engine per \
                             backend; regexes run engine-side"
                                .into(),
                        ));
                    }
                    other => {
                        return Err(SqlError::Unsupported(format!("the '{other}' comparison")));
                    }
                })
            }
            // A bare truthy operand.
            _ => {
                if self.strict {
                    return Err(SqlError::Semantics(
                        "truthiness diverges (0 and '' are falsy in Quarb)".into(),
                    ));
                }
                self.notes.push(
                    "truthiness: '[::c]' exports as IS NOT NULL, but Quarb also treats \
                     0 and '' as falsy"
                        .to_string(),
                );
                Ok(format!("{} IS NOT NULL", self.operand(e, qual)?))
            }
        }
    }

    fn operand(&mut self, o: NodeId, qual: Option<&str>) -> Result<String, SqlError> {
        match self.kind(o).as_str() {
            "literal" => {
                let v = self.prop(o, "value").unwrap_or(Value::Null);
                match self.prop_s(o, "type").as_str() {
                    "text" => {
                        let s = v.to_string();
                        // No single escaping is portable across the
                        // pushdown's target dialects: MySQL (default
                        // sql_mode) and BigQuery read `\` as an escape
                        // while SQLite/PostgreSQL/DuckDB take it
                        // literally, and BigQuery rejects the `''`
                        // quote-doubling the others require. A literal
                        // carrying either character cannot be pushed as
                        // provably identical SQL, so refuse it and let
                        // the caller scan. (The display translation
                        // keeps its best-effort `''`-doubling.)
                        if self.strict && (s.contains('\'') || s.contains('\\')) {
                            return Err(SqlError::Semantics(
                                "a text literal with a quote or backslash \
                                 has no escaping portable across SQL dialects"
                                    .into(),
                            ));
                        }
                        Ok(format!("'{}'", s.replace('\'', "''")))
                    }
                    "null" => Ok("NULL".to_string()),
                    _ => Ok(v.to_string()),
                }
            }
            "path" => {
                if self.kid(o, "step").is_some() {
                    // A step here is either navigation (refused) or
                    // a resolution chain (refused with the reason).
                    let s = self.kids(o, "step")[0];
                    if self.prop_s(s, "axis") == "-->" {
                        return Err(SqlError::Unsupported(
                            "a '-->' resolution chain: the foreign-key targets live in \
                             the schema, not the query — spell the join with '<=>' to \
                             export it"
                                .into(),
                        ));
                    }
                    return Err(SqlError::Unsupported(
                        "navigation inside a predicate (SQL rows are flat)".into(),
                    ));
                }
                let p = self
                    .kid(o, "projection")
                    .ok_or_else(|| SqlError::Unsupported("an empty path operand".into()))?;
                let col = self.projection_col(p)?;
                let col = self.sql_ident(&col, "column name")?;
                Ok(match qual {
                    Some(q) => format!("{q}.{col}"),
                    None => col,
                })
            }
            "context" => {
                // `$*1::col` — the joined expression's witness, in
                // pipeline position: the joined table's column.
                // Anything else is outside the verified-safe set.
                let p = self
                    .kid(o, "projection")
                    .ok_or_else(|| SqlError::Unsupported("a bare '$*' reference".into()))?;
                let col = self.projection_col(p)?;
                let col = self.sql_ident(&col, "column name")?;
                if matches!(self.prop(o, "index"), Some(Value::Int(0))) {
                    // `$$0::col` — the driver, legal only inside the
                    // joined expression's ON bracket (the parser
                    // refuses it anywhere else).
                    if !self.in_on {
                        return Err(SqlError::Unsupported(
                            "a '$$0' reference outside the join's ON".into(),
                        ));
                    }
                    if self.kid(o, "step").is_some() {
                        return Err(SqlError::Unsupported(
                            "a '$$0' reference beyond a plain column ($$0::col)".into(),
                        ));
                    }
                    return Ok(format!("{}.{col}", self.from_sql.clone()));
                }
                if self.in_on {
                    return Err(SqlError::Unsupported(
                        "a '$*' reference inside the ON (the driver is '$$0')".into(),
                    ));
                }
                let Some(join) = self.join_sql.clone() else {
                    return Err(SqlError::Unsupported(
                        "a '$*' reference outside a correlation join".into(),
                    ));
                };
                match self.prop(o, "index") {
                    Some(Value::Int(1)) => Ok(format!("{join}.{col}")),
                    None => Err(SqlError::Unsupported("a bare '$*' reference".into())),
                    Some(v) => Err(SqlError::Unsupported(format!(
                        "pushdown: $*{v} beyond a two-branch correlation"
                    ))),
                }
            }
            "invoking" => {
                // `$$__::col` — the invoking position of an enclosing
                // query body, never the driver (that is `$$0`, a
                // context of index 0, since draft 153). SQL has no
                // enclosing body to read.
                Err(SqlError::Unsupported(
                    "a '$$__' reference (the driver inside the ON is '$$0')".into(),
                ))
            }
            "arith" => {
                let op = self.prop_s(o, "op");
                let kids = self.arbor.children(o);
                let l = self.operand(kids[0], qual)?;
                let r = self.operand(kids[1], qual)?;
                Ok(match op.as_str() {
                    "+" | "-" | "*" => format!("({l} {op} {r})"),
                    "div" => format!("({l} / {r})"),
                    "mod" => format!("({l} % {r})"),
                    other => return Err(SqlError::Unsupported(format!("'{other}' arithmetic"))),
                })
            }
            other => Err(SqlError::Unsupported(format!(
                "the '{other}' operand (registers, topics, and captures are Quarb-side state)"
            ))),
        }
    }

    fn projection_col(&mut self, p: NodeId) -> Result<String, SqlError> {
        match self.prop_s(p, "kind").as_str() {
            "property" => match self.prop(p, "key") {
                Some(k) => Ok(k.to_string()),
                None => Err(SqlError::Unsupported(
                    "the bare '::' projection (name the column)".into(),
                )),
            },
            other => Err(SqlError::Unsupported(format!(
                "the {other} metadata projection"
            ))),
        }
    }

    /// The column a plain column operand names (`::col`, `$*1::col`):
    /// a path without a step, or a context reference, projecting a
    /// named property.
    /// A numeric reducer (`sum`, `mean`, `min`, `max`) pushed over a
    /// column is the scan's only on a numeric-typed column: the
    /// scan lifts unit text (`'18 parasang'` under a declared unit)
    /// to quantities and orders texts as texts, where SQL sums a
    /// text column by its leading digits and orders it by
    /// collation. Recorded for the caller's catalog as a
    /// comparison's assumption is.
    fn assume_numeric(&mut self, column: Option<String>) {
        if !self.strict {
            return;
        }
        if let Some(c) = column
            && !self.column_types.numeric.contains(&c)
        {
            self.column_types.numeric.push(c);
        }
    }

    fn column_operand(&self, o: NodeId) -> Option<String> {
        match self.kind(o).as_str() {
            "path" if self.kid(o, "step").is_none() => {}
            "context" => {}
            _ => return None,
        }
        let p = self.kid(o, "projection")?;
        if self.prop_s(p, "kind") != "property" {
            return None;
        }
        self.prop(p, "key").map(|k| k.to_string())
    }

    /// Whether `o` is a text string literal (`'London'`).
    fn is_text_literal(&self, o: NodeId) -> bool {
        self.kind(o) == "literal" && self.prop_s(o, "type") == "text"
    }

    /// If `o` is the one JSON-column-path shape pushdown handles —
    /// `/col/seg/seg…::`, a plain-navigation path (every hop `/`
    /// and a plain-identifier object key, no wildcards, no nested
    /// predicate), at least one segment past the column, ending in
    /// the bare `::` projection — return `(column, [json segments])`.
    /// Anything else is `None` (and falls back to the graft).
    fn json_path(&self, o: NodeId) -> Option<(String, Vec<String>)> {
        if self.kind(o) != "path" {
            return None;
        }
        let steps = self.kids(o, "step");
        if steps.len() < 2 {
            return None;
        }
        // The projection must be the bare `::` (default value of
        // the JSON leaf), not `::key` or a `:::`/`:` metadata form.
        let proj = self.kid(o, "projection")?;
        if self.prop_s(proj, "kind") != "property" || self.prop(proj, "key").is_some() {
            return None;
        }
        let mut names = Vec::with_capacity(steps.len());
        for s in &steps {
            if self.prop_s(*s, "axis") != "/"
                || self.prop_s(*s, "matcher-kind") != "name"
                || self.kid(*s, "predicate").is_some()
            {
                return None;
            }
            let name = self.prop_s(*s, "matcher");
            // Plain object keys only — no array indices, no
            // characters that would need per-dialect path escaping.
            let plain = !name.is_empty()
                && name
                    .chars()
                    .next()
                    .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
                && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
            if !plain {
                return None;
            }
            names.push(name);
        }
        let col = names.remove(0);
        Some((col, names))
    }

    /// A safe `AS` alias: bare when it is a plain identifier and
    /// not an SQL keyword; otherwise strict mode refuses (quoting
    /// dialects disagree) and export mode double-quotes, noting it.
    fn alias(&mut self, name: &str) -> Result<String, SqlError> {
        if is_plain_ident(name) {
            return Ok(name.to_string());
        }
        if self.strict {
            return Err(SqlError::Unsupported(format!(
                "pushdown: field name {name:?} needs SQL quoting \
                 (dialects disagree); rename the field"
            )));
        }
        self.notes
            .push(format!("field name {name:?} double-quoted (ANSI)"));
        Ok(format!("\"{}\"", name.replace('"', "\"\"")))
    }

    /// A table or column name rendered into SQL. Bare when it is a
    /// plain identifier; otherwise strict mode refuses — a name
    /// like `a OR b` would silently rewrite the emitted SQL's
    /// meaning, breaking the provably-identical guarantee (and a
    /// portable quoting does not exist) — and export mode
    /// double-quotes with a note.
    fn sql_ident(&mut self, name: &str, what: &str) -> Result<String, SqlError> {
        if is_plain_ident(name) {
            return Ok(name.to_string());
        }
        if self.strict {
            return Err(SqlError::Unsupported(format!(
                "pushdown: {what} {name:?} is not a plain SQL identifier"
            )));
        }
        self.notes
            .push(format!("{what} {name:?} double-quoted (ANSI)"));
        Ok(format!("\"{}\"", name.replace('"', "\"\"")))
    }

    /// Split a joined-side predicate: `col = $*1::col2` equalities
    /// become the ON condition; everything else the WHERE.
    /// `ltable` and `rtable` are the tables' SQL renderings.
    fn split_join_pred(
        &mut self,
        p: NodeId,
        rtable: &str,
        on: &mut Vec<String>,
        wheres: &mut Vec<String>,
    ) -> Result<(), SqlError> {
        if self.prop_s(p, "kind") != "expr" {
            return Err(SqlError::Unsupported(
                "a positional predicate on the joined side".into(),
            ));
        }
        // Flatten top-level ANDs; each conjunct routes to ON or
        // WHERE.
        fn conjuncts(ex: &Exporter, e: NodeId, out: &mut Vec<NodeId>) {
            if ex.kind(e) == "and" {
                for c in ex.arbor.children(e) {
                    conjuncts(ex, c, out);
                }
            } else {
                out.push(e);
            }
        }
        let mut parts = Vec::new();
        for c in self.arbor.children(p) {
            conjuncts(self, c, &mut parts);
        }
        for e in parts {
            let uses_driver = self.subtree_has_driver(e);
            self.in_on = true;
            let cond = self.pred_expr(e, Some(rtable));
            self.in_on = false;
            let cond = cond?;
            if uses_driver && self.kind(e) == "compare" && self.prop_s(e, "op") == "=" {
                // Record which joined-table columns the ON binds —
                // the uniqueness obligation (see
                // Pushdown::join_left). Collected from the arbor's
                // bare-column operand nodes, never from the
                // rendered SQL text, so neither a literal nor an
                // unusual column name can corrupt the obligation.
                self.collect_join_cols(e)?;
                on.push(cond);
            } else {
                wheres.push(cond);
            }
        }
        Ok(())
    }

    /// The joined-table columns the ON equality binds: every bare
    /// column operand (`::col`) in `e`'s subtree, appended to the
    /// join obligation with their raw (catalog) names.
    fn collect_join_cols(&mut self, e: NodeId) -> Result<(), SqlError> {
        // The `$$0` side is the driver — not part of the joined
        // table's obligation.
        if self.is_driver(e) {
            return Ok(());
        }
        if self.kind(e) == "path"
            && self.kid(e, "step").is_none()
            && let Some(p) = self.kid(e, "projection")
        {
            let col = self.projection_col(p)?;
            self.join_on_cols.push(col);
        }
        for c in self.arbor.children(e) {
            self.collect_join_cols(c)?;
        }
        Ok(())
    }

    /// `$$0`: a context operand of index 0 (the driver).
    fn is_driver(&self, n: NodeId) -> bool {
        self.kind(n) == "context" && matches!(self.prop(n, "index"), Some(Value::Int(0)))
    }

    fn subtree_has_driver(&self, n: NodeId) -> bool {
        self.is_driver(n)
            || self
                .arbor
                .children(n)
                .into_iter()
                .any(|c| self.subtree_has_driver(c))
    }

    /// Consume the pipeline into SELECT clauses.
    fn pipeline(
        &mut self,
        q: NodeId,
        sel: &mut Select,
        join: Option<(&str, &str)>,
    ) -> Result<(), SqlError> {
        let Some(pipe) = self.kid(q, "pipeline") else {
            return Ok(());
        };
        let commands: Vec<NodeId> = self.arbor.children(pipe);
        let mut i = 0;
        // A pending per-row value (`| ::col`) feeding an aggregate,
        // and the column it names where it is one.
        let mut pending_col: Option<String> = None;
        let mut pending_name: Option<String> = None;
        // After a grouped reduction: (key, agg_sql, alias).
        let mut grouped: Option<(String, String, String)> = None;

        while i < commands.len() {
            let s = commands[i];
            match self.kind(s).as_str() {
                "expr" => {
                    let kids = self.arbor.children(s);
                    pending_col = Some(self.operand(kids[0], join.map(|(l, _)| l))?);
                    pending_name = self.column_operand(kids[0]);
                }
                "cmd" => {
                    let name = self.prop_s(s, "name");
                    match name.as_str() {
                        "rec" | "record" => {
                            sel.select = self.record_fields(s, join)?;
                        }
                        // A reducing aggregate on the plain pipe:
                        // the grouped reduction.
                        "count" | "sum" | "mean" | "avg" | "min" | "max" => {
                            let (key, _, _) = grouped.as_ref().ok_or_else(|| {
                                SqlError::Unsupported(format!(
                                    "'| {name}' outside a group (use '@| {name}')"
                                ))
                            })?;
                            // Quarb's count counts every member,
                            // nulls included: COUNT(*), never the
                            // NULL-skipping COUNT(col).
                            let col = if name == "count" {
                                pending_col = None;
                                None
                            } else {
                                self.assume_numeric(pending_name.take());
                                pending_col.take()
                            };
                            let agg = sql_agg(&name, col)?;
                            grouped = Some((key.clone(), agg.clone(), agg));
                        }
                        other => {
                            // sort/unique/top and kin are spellable
                            // in SQL but with the backend's own
                            // collation and duplicate semantics —
                            // name the divergence, not a missing
                            // feature.
                            if matches!(other, "sort" | "sort_by" | "unique" | "top" | "bottom") {
                                return Err(SqlError::Semantics(format!(
                                    "'{other}' means the backend's collation and \
                                     duplicate semantics; one engine-side ordering \
                                     keeps it identical everywhere"
                                )));
                            }
                            return Err(SqlError::Unsupported(format!(
                                "the '{other}' pipeline command"
                            )));
                        }
                    }
                }
                "push" => {
                    // An alias for the grouped aggregate.
                    if let Some((k, agg, _)) = grouped.take() {
                        let alias = self.prop_s(s, "name");
                        grouped = Some((k, agg, alias));
                    } else {
                        return Err(SqlError::Unsupported(
                            "a register push (Quarb-side state)".into(),
                        ));
                    }
                }
                "filter" => {
                    if grouped.is_some() {
                        // HAVING: `$_` / the alias refer to the
                        // aggregate.
                        let cond = self.having_cond(s)?;
                        sel.having = Some(cond);
                    } else {
                        return Err(SqlError::Unsupported(
                            "a mid-pipeline filter (put it in the row predicate)".into(),
                        ));
                    }
                }
                "recall" => {
                    // `| %.` finalizes the grouped record.
                    if self.prop_s(s, "ref") != "%." {
                        return Err(SqlError::Unsupported(
                            "a register recall (Quarb-side state)".into(),
                        ));
                    }
                    let (key, agg, alias) = grouped.clone().ok_or_else(|| {
                        SqlError::Unsupported("'%.', with nothing grouped".into())
                    })?;
                    let alias = self.alias(&alias)?;
                    sel.select = vec![key.clone(), format!("{agg} AS {alias}")];
                    // The HAVING condition compared the aggregate
                    // through $_ — substitute the real expression.
                    if let Some(h) = sel.having.take() {
                        sel.having = Some(h.replace("__AGG__", &agg));
                    }
                }
                "agg" => {
                    let name = self.prop_s(s, "name");
                    match name.as_str() {
                        "count" | "sum" | "mean" | "avg" | "min" | "max" => {
                            // Quarb's count counts every row, nulls
                            // included: COUNT(*) regardless of a
                            // pending column.
                            let col = if name == "count" {
                                pending_col = None;
                                None
                            } else {
                                self.assume_numeric(pending_name.take());
                                pending_col.take()
                            };
                            sel.select = vec![sql_agg(&name, col)?];
                            self.aggregate = true;
                        }
                        "group" => {
                            if self.strict {
                                return Err(SqlError::Semantics(
                                    "GROUP BY result order is unordered in SQL".into(),
                                ));
                            }
                            self.notes.push(
                                "GROUP BY: SQL keeps a NULL-key group; Quarb's group \
                                 drops null keys"
                                    .to_string(),
                            );
                            let key = self.group_key(s, join)?;
                            sel.group_by = Some(key.clone());
                            grouped = Some((key, String::new(), String::new()));
                        }
                        "sort_by" => {
                            if self.strict {
                                return Err(SqlError::Semantics(
                                    "ORDER BY collations differ per engine".into(),
                                ));
                            }
                            // A sort after a positional selection
                            // (or a second sort) cannot render: the
                            // fixed SELECT shape orders before
                            // LIMIT, and has one ORDER BY.
                            if sel.limit.is_some() {
                                return Err(SqlError::Unsupported(
                                    "a sort after a positional selection (SQL orders \
                                     before LIMIT)"
                                        .into(),
                                ));
                            }
                            if sel.order_by.is_some() {
                                return Err(SqlError::Unsupported(
                                    "a second sort (SQL has a single ORDER BY)".into(),
                                ));
                            }
                            let kids = self.arbor.children(s);
                            let e = self.operand(kids[0], join.map(|(l, _)| l))?;
                            sel.order_by = Some((e, false));
                        }
                        "reverse" => match &mut sel.order_by {
                            Some((_, desc)) => *desc = true,
                            None => {
                                return Err(SqlError::Unsupported(
                                    "reverse without an ORDER BY (rows are unordered)".into(),
                                ));
                            }
                        },
                        "top" => {
                            if self.strict {
                                return Err(SqlError::Semantics(
                                    "ORDER BY collations differ per engine".into(),
                                ));
                            }
                            if sel.limit.is_some() {
                                return Err(SqlError::Unsupported(
                                    "'top' after a positional selection (SQL orders \
                                     before LIMIT)"
                                        .into(),
                                ));
                            }
                            if sel.order_by.is_some() {
                                return Err(SqlError::Unsupported(
                                    "a second sort (SQL has a single ORDER BY)".into(),
                                ));
                            }
                            let kids = self.arbor.children(s);
                            let n = self.prop_s(kids[0], "value");
                            let e = self.operand(kids[1], join.map(|(l, _)| l))?;
                            sel.order_by = Some((e, true));
                            sel.limit = Some(n);
                        }
                        "unique" => {
                            if self.strict {
                                return Err(SqlError::Unsupported(
                                    "pushdown: DISTINCT result order is unordered in SQL".into(),
                                ));
                            }
                            // Quarb dedups the limited rows; SQL
                            // applies DISTINCT before LIMIT.
                            if sel.limit.is_some() {
                                return Err(SqlError::Unsupported(
                                    "'unique' after a positional selection (SQL applies \
                                     DISTINCT before LIMIT)"
                                        .into(),
                                ));
                            }
                            if let Some(c) = pending_col.take() {
                                sel.select = vec![c];
                            }
                            sel.distinct = true;
                        }
                        other => {
                            return Err(SqlError::Unsupported(format!("the '{other}' aggregate")));
                        }
                    }
                }
                "select" => {
                    if self.strict {
                        return Err(SqlError::Unsupported(
                            "pushdown: LIMIT without a guaranteed order".into(),
                        ));
                    }
                    // `@| [..n]` → LIMIT.
                    if sel.limit.is_some() {
                        return Err(SqlError::Unsupported(
                            "a second positional selection".into(),
                        ));
                    }
                    let p = self.arbor.children(s)[0];
                    match (self.prop_s(p, "kind").as_str(), self.prop(p, "to")) {
                        ("range", Some(Value::Int(n)))
                            if self.prop(p, "from").is_none() && n > 0 =>
                        {
                            sel.limit = Some(n.to_string());
                        }
                        _ => {
                            return Err(SqlError::Unsupported(
                                "positional selection beyond '@| [..n]'".into(),
                            ));
                        }
                    }
                }
                other => {
                    return Err(SqlError::Unsupported(format!(
                        "the '{other}' command (windows, subcontexts, and registers are \
                         Quarb-side state)"
                    )));
                }
            }
            i += 1;
        }
        // A pending column with no aggregate is a one-column select.
        if let Some(c) = pending_col
            && sel.select.is_empty()
        {
            sel.select = vec![c];
        }
        Ok(())
    }

    fn group_key(&mut self, s: NodeId, join: Option<(&str, &str)>) -> Result<String, SqlError> {
        let kids = self.arbor.children(s);
        // group(::k) or group("name", expr) — the key expression is
        // the last child; a literal first child is its name.
        let key = kids
            .iter()
            .rev()
            .find(|&&k| self.kind(k) != "literal")
            .ok_or_else(|| SqlError::Unsupported("a literal group key".into()))?;
        self.operand(*key, join.map(|(l, _)| l))
    }

    /// A HAVING filter: `$_` and `$.name` refer to the aggregate.
    fn having_cond(&mut self, s: NodeId) -> Result<String, SqlError> {
        let kids = self.arbor.children(s);
        if kids.len() != 1 || self.kind(kids[0]) != "compare" {
            return Err(SqlError::Unsupported(
                "HAVING translates for a single comparison".into(),
            ));
        }
        let e = kids[0];
        let op = self.prop_s(e, "op");
        let cmp_kids = self.arbor.children(e);
        let l = match self.kind(cmp_kids[0]).as_str() {
            "topic" | "recall" => "__AGG__".to_string(),
            _ => {
                return Err(SqlError::Unsupported(
                    "HAVING compares the aggregate ($_ or its register)".into(),
                ));
            }
        };
        let r = self.operand(cmp_kids[1], None)?;
        Ok(format!("{l} {op} {r}"))
    }

    /// `rec(...)` fields as a select list.
    fn record_fields(
        &mut self,
        s: NodeId,
        join: Option<(&str, &str)>,
    ) -> Result<Vec<String>, SqlError> {
        let kids = self.arbor.children(s);
        let mut fields = Vec::new();
        let mut i = 0;
        while i < kids.len() {
            let k = kids[i];
            if self.kind(k) == "literal" {
                let name = self.prop_s(k, "value");
                let value = self.operand(kids[i + 1], join.map(|(l, _)| l))?;
                let name = self.alias(&name)?;
                fields.push(format!("{value} AS {name}"));
                i += 2;
            } else {
                let value = self.operand(k, join.map(|(l, _)| l))?;
                fields.push(value);
                i += 1;
            }
        }
        Ok(fields)
    }
}

fn sql_agg(name: &str, col: Option<String>) -> Result<String, SqlError> {
    let f = match name {
        "count" => "COUNT",
        "sum" => "SUM",
        "mean" | "avg" => "AVG",
        "min" => "MIN",
        "max" => "MAX",
        _ => unreachable!("checked by caller"),
    };
    match col {
        Some(c) => Ok(format!("{f}({c})")),
        // Only COUNT aggregates bare rows; SUM(*) and friends are
        // not SQL.
        None if f == "COUNT" => Ok("COUNT(*)".to_string()),
        None => Err(SqlError::Unsupported(format!(
            "'{name}' over row nodes (project a column first: '| ::col @| {name}')"
        ))),
    }
}

#[cfg(test)]
mod null_and_literal_tests {
    use super::{Dialect, export, partial_pushdown, pushdown};

    // Grouped pipeline that never pushes, so `partial_pushdown` hinges
    // only on the leading predicate (mirrors the crate's partial gate).
    const GROUPED: &str = " | ::x @| group(\"g\", ::x) | count | .n | %.";

    #[test]
    fn pattern_literal_pushes_as_like() {
        // Ruling #33: segments in order, a `%` per star, LIKE's
        // metacharacters escaped. Strict push only where LIKE is
        // provably case-sensitive (PostgreSQL); everywhere else the
        // pattern rides the scan.
        let q = "/users/*[::name == 'app-'*]::id";
        let p = pushdown(q, Some(Dialect::Postgres)).unwrap();
        assert_eq!(
            p.sql,
            "SELECT id FROM users WHERE name LIKE 'app-%' ESCAPE '\\'"
        );
        assert!(pushdown(q, Some(Dialect::Sqlite)).is_none());
        assert!(pushdown(q, Some(Dialect::MySql)).is_none());
        // contains and multi-segment shapes
        let p = pushdown("/users/*[::name == *'web'*]::id", Some(Dialect::Postgres)).unwrap();
        assert!(p.sql.contains("LIKE '%web%'"), "{}", p.sql);
        let p = pushdown(
            "/users/*[::name == *'a'*'.gz']::id",
            Some(Dialect::Postgres),
        )
        .unwrap();
        assert!(p.sql.contains("LIKE '%a%.gz'"), "{}", p.sql);
        // LIKE metacharacters in a segment are escaped
        let p = pushdown("/users/*[::name == *'50%_x'*]::id", Some(Dialect::Postgres)).unwrap();
        assert!(p.sql.contains("LIKE '%50\\%\\_x%'"), "{}", p.sql);
        // `!=` with a pattern rides the scan
        assert!(pushdown("/users/*[::name !== *'web'*]::id", Some(Dialect::Postgres)).is_none());
        // the `*=` alias gains the same PostgreSQL rung
        let p = pushdown("/users/*[::name *= 'web']::id", Some(Dialect::Postgres)).unwrap();
        assert!(p.sql.contains("LIKE '%web%'"), "{}", p.sql);
        assert!(pushdown("/users/*[::name *= 'web']::id", Some(Dialect::Sqlite)).is_none());
    }

    #[test]
    fn json_column_path_pushdown_per_dialect() {
        // `[/col/a/b:: = 'lit']` navigates into a JSON column; each
        // dialect extracts the fixed path to text and compares.
        // Verified live against all five engines to match the graft.
        let q = "/orders/*[/data/meta/tier:: = 'gold']::id";
        let sql = |d| pushdown(q, Some(d)).unwrap().sql;
        assert_eq!(
            sql(Dialect::Postgres),
            "SELECT id FROM orders WHERE ((data::jsonb #>> '{meta,tier}') = 'gold')"
        );
        assert_eq!(
            sql(Dialect::MySql),
            "SELECT id FROM orders WHERE (JSON_VALID(data) AND \
             JSON_UNQUOTE(JSON_EXTRACT(data, '$.meta.tier')) = 'gold')"
        );
        assert_eq!(
            sql(Dialect::Sqlite),
            "SELECT id FROM orders WHERE (json_valid(data) AND \
             json_extract(data, '$.meta.tier') = 'gold')"
        );
        assert_eq!(
            sql(Dialect::Mssql),
            "SELECT id FROM orders WHERE (ISJSON(data) = 1 AND \
             JSON_VALUE(data, '$.meta.tier') = 'gold')"
        );
        assert_eq!(
            sql(Dialect::Oracle),
            "SELECT id FROM orders WHERE (JSON_VALUE(data, '$.meta.tier') = 'gold')"
        );
        // With no dialect, the JSON navigation is not pushable — it
        // falls back to the client-side graft.
        assert!(pushdown(q, None).is_none());
    }

    #[test]
    fn json_pushdown_only_string_equality() {
        // Numeric comparison, `!=`, and a wildcard hop stay off the
        // pushdown path (they are not provably identical to the
        // graft), so they refuse and scan even with a dialect set.
        let d = Some(Dialect::Sqlite);
        assert!(pushdown("/o/*[/data/n:: > 2]::id", d).is_none());
        assert!(pushdown("/o/*[/data/tier:: != 'gold']::id", d).is_none());
        assert!(pushdown("/o/*[/data/items/*/sku:: = 'A1']::id", d).is_none());
    }

    #[test]
    fn json_pushdown_refuses_numeric_looking_literal() {
        // value_eq coerces numeric-looking strings ('150' matches
        // the JSON number 150 and the string "150.0"); no engine's
        // extractor does, so the push would drop rows.
        let q = "/orders/*[/data/total:: = '150']::id";
        assert!(pushdown(q, Some(Dialect::Sqlite)).is_none());
        assert!(pushdown(q, Some(Dialect::Postgres)).is_none());
    }

    #[test]
    fn partial_json_prefilters_sqlite() {
        // Exact string equality rides the strict gate.
        let p = partial_pushdown(
            "/orders/*[/payload/customer/geo/city:: = 'Lyon']::id",
            Some(Dialect::Sqlite),
        )
        .unwrap();
        assert_eq!(p.table, "orders");
        assert_eq!(
            p.where_sql,
            "(json_valid(payload) AND \
             json_extract(payload, '$.customer.geo.city') = 'Lyon')"
        );
        // Numeric comparison: typed compare, text values escape.
        let p = partial_pushdown(
            "/orders/*[/payload/total:: > 150]::id",
            Some(Dialect::Sqlite),
        )
        .unwrap();
        assert_eq!(
            p.where_sql,
            "(json_valid(payload) AND (json_extract(payload, '$.total') > 150 \
             OR json_type(payload, '$.total') = 'text'))"
        );
        // Bare existence.
        let p = partial_pushdown("/orders/*[/payload/gift]::id", Some(Dialect::Sqlite)).unwrap();
        assert_eq!(
            p.where_sql,
            "(json_valid(payload) AND json_type(payload, '$.gift') IS NOT NULL)"
        );
        // != floors at existence.
        let p = partial_pushdown(
            "/orders/*[/payload/status:: != 'x']::id",
            Some(Dialect::Sqlite),
        )
        .unwrap();
        assert_eq!(
            p.where_sql,
            "(json_valid(payload) AND json_type(payload, '$.status') IS NOT NULL)"
        );
        // A flipped literal flips the operator.
        let p = partial_pushdown(
            "/orders/*[150 < /payload/total::]::id",
            Some(Dialect::Sqlite),
        )
        .unwrap();
        assert!(p.where_sql.contains("> 150"), "{}", p.where_sql);
        // Without a dialect, JSON predicates stay on the engine.
        assert!(partial_pushdown("/orders/*[/payload/gift]::id", None).is_none());
    }

    #[test]
    fn partial_json_prefilters_postgres() {
        let p = partial_pushdown(
            "/orders/*[/payload/total:: > 150]::id",
            Some(Dialect::Postgres),
        )
        .unwrap();
        assert_eq!(
            p.where_sql,
            "(CASE WHEN jsonb_typeof(payload::jsonb #> '{total}') = 'number' \
             THEN ((payload::jsonb #>> '{total}'))::float8 > 150 \
             WHEN jsonb_typeof(payload::jsonb #> '{total}') = 'string' \
             THEN true ELSE false END)"
        );
        let p = partial_pushdown("/orders/*[/payload/gift]::id", Some(Dialect::Postgres)).unwrap();
        assert_eq!(
            p.where_sql,
            "(jsonb_typeof(payload::jsonb #> '{gift}') IS NOT NULL)"
        );
    }

    #[test]
    fn partial_skips_untranslatable_keeps_prefix() {
        // A refused predicate no prefilter covers is skipped — the
        // shorter conjunction is still a superset (the engine
        // re-applies the original) — rather than aborting the plan.
        let p = partial_pushdown(
            "/orders/*[::status = 'shipped'][/payload/line_items/*/sku:: = 'X']::id",
            Some(Dialect::Sqlite),
        )
        .unwrap();
        assert_eq!(p.where_sql, "status = 'shipped'");
    }

    #[test]
    fn null_literal_compares_use_is_null() {
        // `= null` / `!= null` are provably identical to Quarb's
        // value_eq(NULL, …) semantics, never the always-UNKNOWN
        // `x = NULL`; they translate — and push — in both modes.
        assert_eq!(
            export("/t/*[::x = null] | ::x").unwrap().query,
            "SELECT x FROM t WHERE x IS NULL"
        );
        assert_eq!(
            export("/t/*[::x != null] | ::x").unwrap().query,
            "SELECT x FROM t WHERE x IS NOT NULL"
        );
        assert_eq!(
            pushdown("/t/*[::x = null] | ::x", None).unwrap().sql,
            "SELECT x FROM t WHERE x IS NULL"
        );
        assert_eq!(
            pushdown("/t/*[::x != null] | ::x", None).unwrap().sql,
            "SELECT x FROM t WHERE x IS NOT NULL"
        );
    }

    #[test]
    fn ne_and_not_refuse_pushdown_but_display_diverges() {
        // `!=` against a non-null value and `not(...)` drop the NULL
        // rows Quarb keeps under SQL three-valued logic: the pushdown
        // paths refuse (and scan), full and partial alike.
        assert!(pushdown("/t/*[::x != 5] | ::x", None).is_none());
        assert!(pushdown("/t/*[!::x = 5] | ::x", None).is_none());
        assert!(partial_pushdown(&format!("/t/*[::x != 5]{GROUPED}"), None).is_none());
        assert!(partial_pushdown(&format!("/t/*[!::x = 5]{GROUPED}"), None).is_none());
        // The display translation still emits `<>`, flagged with a note.
        let t = export("/t/*[::x != 5] | ::x").unwrap();
        assert_eq!(t.query, "SELECT x FROM t WHERE x <> 5");
        assert!(t.notes.iter().any(|n| n.contains("NULL")));
    }

    #[test]
    fn unescapable_text_literal_refuses_pushdown() {
        // A backslash (MySQL/BigQuery escape) or an apostrophe
        // (BigQuery rejects '' doubling) has no portable escaping, so
        // pushdown refuses; a clean literal still pushes.
        assert!(pushdown("/files/*[::path = \"C:\\temp\"] | ::path", None).is_none());
        assert!(pushdown("/t/*[::name = \"it's\"] | ::name", None).is_none());
        assert!(partial_pushdown(&format!("/t/*[::name = \"it's\"]{GROUPED}"), None).is_none());
        assert_eq!(
            pushdown("/t/*[::name = \"rare\"] | ::name", None)
                .unwrap()
                .sql,
            "SELECT name FROM t WHERE name = 'rare'"
        );
    }
}