powdb-query 0.29.1

PowQL lexer, parser, planner, and executor — compiled query engine for PowDB
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
//! Expression evaluation functions for the PowDB executor.

use crate::ast::*;
use crate::result::QueryError;
use powdb_storage::catalog::Catalog;
use powdb_storage::types::*;

/// The expression evaluator's error channel.
///
/// `eval_expr` returns a `Value` and is called from closures the storage scan
/// drives, so it has nowhere to put an error. Every unrepresentable arithmetic
/// result therefore became `Value::Empty`, which is indistinguishable from a
/// missing column: `.big * 2` produced NULL in a projection, filtered nothing
/// out in a predicate, and an `update` wrote that NULL into a required column,
/// while `sum` over the same values refused the same overflow outright.
///
/// A fault recorded here is turned into the statement's error at the two
/// execution boundaries every plan crosses, `Engine::execute_lowered` and
/// `Engine::execute_plan_readonly` (see `Engine::raise_arith_fault`). Both take
/// unconditionally, so a fault recorded by an outer frame and collected by a
/// nested one (a correlated subquery, a view's source query) is still raised,
/// as that frame's error rather than the outer one's: attribution can move, the
/// refusal cannot be lost. Nothing else clears the slot, so nothing leaks into
/// the next statement either.
///
/// The first fault wins, because it is the one the query hit first; later rows
/// cannot overwrite it.
mod arith_fault {
    use std::cell::RefCell;

    thread_local! {
        static FAULT: RefCell<Option<String>> = const { RefCell::new(None) };
    }

    pub(super) fn record(message: String) {
        FAULT.with(|fault| {
            let mut slot = fault.borrow_mut();
            if slot.is_none() {
                *slot = Some(message);
            }
        });
    }

    pub(crate) fn take() -> Option<String> {
        FAULT.with(|fault| fault.borrow_mut().take())
    }
}

pub(crate) use arith_fault::take as take_arith_fault;

/// Record an integer-arithmetic overflow and yield the empty set for this row.
/// The empty value never reaches the caller as an answer: the statement fails
/// with the recorded message.
fn overflow(label: &str) -> Value {
    arith_fault::record(format!(
        "cannot compute {label}: the integer result overflows int64"
    ));
    Value::Empty
}

/// Record a zero divisor, matching the message validation gives the literal
/// form so the two spellings of the same mistake read the same.
fn divide_by_zero() -> Value {
    arith_fault::record(
        "cannot divide by zero: the divisor is zero for at least one row".to_string(),
    );
    Value::Empty
}

pub(super) fn collect_field_refs(expr: &Expr, out: &mut Vec<String>) {
    match expr {
        Expr::Field(name) => out.push(name.clone()),
        Expr::QualifiedField { qualifier, field } => {
            out.push(format!("{qualifier}.{field}"));
        }
        Expr::BinaryOp(l, _, r) => {
            collect_field_refs(l, out);
            collect_field_refs(r, out);
        }
        Expr::UnaryOp(_, inner) => collect_field_refs(inner, out),
        Expr::FunctionCall(_, inner, _) => collect_field_refs(inner, out),
        Expr::Coalesce(l, r) => {
            collect_field_refs(l, out);
            collect_field_refs(r, out);
        }
        Expr::InList { expr, list, .. } => {
            collect_field_refs(expr, out);
            for item in list {
                collect_field_refs(item, out);
            }
        }
        Expr::ScalarFunc(_, args) => {
            for a in args {
                collect_field_refs(a, out);
            }
        }
        Expr::Cast(inner, _) => {
            collect_field_refs(inner, out);
        }
        Expr::Case { whens, else_expr } => {
            for (c, r) in whens {
                collect_field_refs(c, out);
                collect_field_refs(r, out);
            }
            if let Some(e) = else_expr {
                collect_field_refs(e, out);
            }
        }
        // A JSON path references only the column named by its base; the
        // segments address into that value and name no additional columns.
        Expr::JsonPath { base, .. } => collect_field_refs(base, out),
        _ => {}
    }
}

/// Detect whether a subquery is correlated: any `Expr::Field` reference in
/// the subquery's filter that doesn't match a column in the subquery's
/// source table indicates a reference to an outer scope.
///
/// Replace outer-scope field references in a correlated subquery's filter
/// with literal values from the current outer row. Inner fields are left
/// unchanged. A bare field name that both scopes expose is refused directly:
/// the old "inner wins" rule silently answered the wrong query for
/// `Order.id = User.id`-style schemas.
pub(super) fn substitute_outer_refs(
    expr: &Expr,
    subquery: &QueryExpr,
    catalog: &Catalog,
    outer_row: &[Value],
    outer_columns: &[String],
) -> Result<Expr, QueryError> {
    let sub_cols: Vec<String> = catalog
        .schema(&subquery.source)
        .map(|s| s.columns.iter().map(|c| c.name.clone()).collect())
        .unwrap_or_default();
    let local_qualifiers = local_qualifiers(subquery);
    substitute_outer_refs_inner(expr, &sub_cols, &local_qualifiers, outer_row, outer_columns)
}

fn outer_column_indices(field: &str, outer_columns: &[String]) -> Vec<usize> {
    outer_columns
        .iter()
        .enumerate()
        .filter_map(|(index, column)| {
            (column == field
                || matches!(
                    column.rsplit_once('.'),
                    Some((_, outer_field)) if outer_field == field
                ))
            .then_some(index)
        })
        .collect()
}

fn unique_outer_column_index(
    field: &str,
    outer_columns: &[String],
) -> Result<Option<usize>, QueryError> {
    match outer_column_indices(field, outer_columns).as_slice() {
        [] => Ok(None),
        [index] => Ok(Some(*index)),
        _ => Err(ambiguous_correlated_field(field)),
    }
}

fn exact_outer_column_index(alias: &str, field: &str, outer_columns: &[String]) -> Option<usize> {
    let qualified = format!("{alias}.{field}");
    outer_columns
        .iter()
        .position(|column| column == &qualified)
        .or_else(|| {
            let bare_matches: Vec<usize> = outer_columns
                .iter()
                .enumerate()
                .filter_map(|(index, column)| {
                    (!column.contains('.') && column == field).then_some(index)
                })
                .collect();
            match bare_matches.as_slice() {
                [index] => Some(*index),
                _ => None,
            }
        })
}

fn has_outer_column(field: &str, outer_columns: &[String]) -> bool {
    outer_columns.iter().any(|column| {
        column == field
            || matches!(
                column.rsplit_once('.'),
                Some((_, outer_field)) if outer_field == field
            )
    })
}

fn local_qualifiers(subquery: &QueryExpr) -> Vec<String> {
    let mut qualifiers = vec![subquery.source.clone()];
    if let Some(alias) = &subquery.alias {
        qualifiers.push(alias.clone());
    }
    qualifiers.sort();
    qualifiers.dedup();
    qualifiers
}

fn ambiguous_correlated_field(name: &str) -> QueryError {
    QueryError::Execution(format!(
        "ambiguous bare correlated field `{name}`; qualify the inner field \
         with its inner alias or the outer field with its outer alias"
    ))
}

fn unknown_correlated_qualifier(qualifier: &str, field: &str) -> QueryError {
    let reference = if outer_correlation_alias(qualifier).is_some() {
        format!("outer field `{field}`")
    } else {
        format!("correlated field `{qualifier}.{field}`")
    };
    QueryError::Execution(format!(
        "unknown {reference}; qualify inner fields with the subquery alias and \
         outer fields with a visible outer alias"
    ))
}

fn substitute_outer_refs_inner(
    expr: &Expr,
    sub_cols: &[String],
    local_qualifiers: &[String],
    outer_row: &[Value],
    outer_columns: &[String],
) -> Result<Expr, QueryError> {
    match expr {
        Expr::Field(name) => {
            let inner_has = sub_cols.iter().any(|c| c == name);
            let outer_index = unique_outer_column_index(name, outer_columns)?;
            match (inner_has, outer_index) {
                (true, Some(_)) => Err(ambiguous_correlated_field(name)),
                (true, None) => Ok(expr.clone()),
                (false, Some(i)) => Ok(value_to_expr(outer_row[i].clone())),
                (false, None) => Ok(expr.clone()),
            }
        }
        Expr::QualifiedField { qualifier, field } => {
            if local_qualifiers.iter().any(|local| local == qualifier) {
                Ok(expr.clone())
            } else if let Some(alias) = outer_correlation_alias(qualifier) {
                if let Some(i) = exact_outer_column_index(alias, field, outer_columns) {
                    Ok(value_to_expr(outer_row[i].clone()))
                } else {
                    Err(unknown_correlated_qualifier(qualifier, field))
                }
            } else if let Some(i) = outer_columns
                .iter()
                .position(|column| column == &format!("{qualifier}.{field}"))
            {
                Ok(value_to_expr(outer_row[i].clone()))
            } else {
                Ok(expr.clone())
            }
        }
        Expr::BinaryOp(l, op, r) => {
            let l = substitute_outer_refs_inner(
                l,
                sub_cols,
                local_qualifiers,
                outer_row,
                outer_columns,
            )?;
            let r = substitute_outer_refs_inner(
                r,
                sub_cols,
                local_qualifiers,
                outer_row,
                outer_columns,
            )?;
            Ok(Expr::BinaryOp(Box::new(l), *op, Box::new(r)))
        }
        Expr::UnaryOp(op, inner) => {
            let inner = substitute_outer_refs_inner(
                inner,
                sub_cols,
                local_qualifiers,
                outer_row,
                outer_columns,
            )?;
            Ok(Expr::UnaryOp(*op, Box::new(inner)))
        }
        Expr::FunctionCall(func, inner, mode) => {
            let inner = substitute_outer_refs_inner(
                inner,
                sub_cols,
                local_qualifiers,
                outer_row,
                outer_columns,
            )?;
            Ok(Expr::FunctionCall(*func, Box::new(inner), *mode))
        }
        Expr::InList {
            expr: e,
            list,
            negated,
        } => {
            let e = substitute_outer_refs_inner(
                e,
                sub_cols,
                local_qualifiers,
                outer_row,
                outer_columns,
            )?;
            let list = list
                .iter()
                .map(|item| {
                    substitute_outer_refs_inner(
                        item,
                        sub_cols,
                        local_qualifiers,
                        outer_row,
                        outer_columns,
                    )
                })
                .collect::<Result<Vec<_>, QueryError>>()?;
            Ok(Expr::InList {
                expr: Box::new(e),
                list,
                negated: *negated,
            })
        }
        Expr::Coalesce(l, r) => {
            let l = substitute_outer_refs_inner(
                l,
                sub_cols,
                local_qualifiers,
                outer_row,
                outer_columns,
            )?;
            let r = substitute_outer_refs_inner(
                r,
                sub_cols,
                local_qualifiers,
                outer_row,
                outer_columns,
            )?;
            Ok(Expr::Coalesce(Box::new(l), Box::new(r)))
        }
        Expr::ScalarFunc(func, args) => Ok(Expr::ScalarFunc(
            *func,
            args.iter()
                .map(|arg| {
                    substitute_outer_refs_inner(
                        arg,
                        sub_cols,
                        local_qualifiers,
                        outer_row,
                        outer_columns,
                    )
                })
                .collect::<Result<Vec<_>, QueryError>>()?,
        )),
        Expr::Cast(inner, cast_type) => {
            let inner = substitute_outer_refs_inner(
                inner,
                sub_cols,
                local_qualifiers,
                outer_row,
                outer_columns,
            )?;
            Ok(Expr::Cast(Box::new(inner), *cast_type))
        }
        Expr::Case { whens, else_expr } => {
            let whens = whens
                .iter()
                .map(|(cond, result)| -> Result<_, QueryError> {
                    Ok((
                        Box::new(substitute_outer_refs_inner(
                            cond,
                            sub_cols,
                            local_qualifiers,
                            outer_row,
                            outer_columns,
                        )?),
                        Box::new(substitute_outer_refs_inner(
                            result,
                            sub_cols,
                            local_qualifiers,
                            outer_row,
                            outer_columns,
                        )?),
                    ))
                })
                .collect::<Result<Vec<_>, QueryError>>()?;
            let else_expr = else_expr
                .as_ref()
                .map(|else_expr| {
                    substitute_outer_refs_inner(
                        else_expr,
                        sub_cols,
                        local_qualifiers,
                        outer_row,
                        outer_columns,
                    )
                    .map(Box::new)
                })
                .transpose()?;
            Ok(Expr::Case { whens, else_expr })
        }
        Expr::JsonPath { base, segments } => {
            let base = substitute_outer_refs_inner(
                base,
                sub_cols,
                local_qualifiers,
                outer_row,
                outer_columns,
            )?;
            Ok(Expr::JsonPath {
                base: Box::new(base),
                segments: segments.clone(),
            })
        }
        other => Ok(other.clone()),
    }
}

pub(super) fn validate_subquery_scope(
    subquery: &QueryExpr,
    catalog: &Catalog,
    outer_columns: Option<&[String]>,
) -> Result<(), QueryError> {
    let Some(filter) = &subquery.filter else {
        return Ok(());
    };
    let Some(schema) = catalog.schema(&subquery.source) else {
        return Ok(());
    };
    let table_cols: Vec<String> = schema.columns.iter().map(|c| c.name.clone()).collect();
    let local_qualifiers = local_qualifiers(subquery);
    validate_scope_expr(
        filter,
        &subquery.source,
        &table_cols,
        &local_qualifiers,
        outer_columns,
    )
}

fn validate_scope_expr(
    expr: &Expr,
    subquery_source: &str,
    sub_cols: &[String],
    local_qualifiers: &[String],
    outer_columns: Option<&[String]>,
) -> Result<(), QueryError> {
    match expr {
        Expr::Field(name) => {
            let inner_has = sub_cols.iter().any(|c| c == name);
            let outer_count =
                outer_columns.map_or(0, |columns| outer_column_indices(name, columns).len());
            match (inner_has, outer_count) {
                (true, count) if count > 0 => Err(ambiguous_correlated_field(name)),
                (false, 0) => Err(QueryError::ColumnNotFound {
                    table: subquery_source.to_string(),
                    column: name.clone(),
                }),
                (false, 1) => Ok(()),
                (false, _) => Err(ambiguous_correlated_field(name)),
                _ => Ok(()),
            }
        }
        Expr::QualifiedField { qualifier, field } => {
            if local_qualifiers.iter().any(|local| local == qualifier) {
                if sub_cols.iter().any(|column| column == field) {
                    Ok(())
                } else {
                    Err(QueryError::ColumnNotFound {
                        table: subquery_source.to_string(),
                        column: field.clone(),
                    })
                }
            } else if let Some(alias) = outer_correlation_alias(qualifier) {
                if outer_columns.is_some_and(|columns| {
                    exact_outer_column_index(alias, field, columns).is_some()
                }) {
                    Ok(())
                } else {
                    Err(unknown_correlated_qualifier(qualifier, field))
                }
            } else if outer_columns.is_some_and(|columns| {
                columns
                    .iter()
                    .any(|column| column == &format!("{qualifier}.{field}"))
            }) {
                Ok(())
            } else {
                Err(unknown_correlated_qualifier(qualifier, field))
            }
        }
        Expr::BinaryOp(left, _, right) | Expr::Coalesce(left, right) => {
            validate_scope_expr(
                left,
                subquery_source,
                sub_cols,
                local_qualifiers,
                outer_columns,
            )?;
            validate_scope_expr(
                right,
                subquery_source,
                sub_cols,
                local_qualifiers,
                outer_columns,
            )
        }
        Expr::UnaryOp(_, inner)
        | Expr::Cast(inner, _)
        | Expr::FunctionCall(_, inner, _)
        | Expr::JsonPath { base: inner, .. } => validate_scope_expr(
            inner,
            subquery_source,
            sub_cols,
            local_qualifiers,
            outer_columns,
        ),
        Expr::ScalarFunc(_, args) => args.iter().try_for_each(|arg| {
            validate_scope_expr(
                arg,
                subquery_source,
                sub_cols,
                local_qualifiers,
                outer_columns,
            )
        }),
        Expr::InList { expr, list, .. } => {
            validate_scope_expr(
                expr,
                subquery_source,
                sub_cols,
                local_qualifiers,
                outer_columns,
            )?;
            list.iter().try_for_each(|item| {
                validate_scope_expr(
                    item,
                    subquery_source,
                    sub_cols,
                    local_qualifiers,
                    outer_columns,
                )
            })
        }
        Expr::Case { whens, else_expr } => {
            for (cond, result) in whens {
                validate_scope_expr(
                    cond,
                    subquery_source,
                    sub_cols,
                    local_qualifiers,
                    outer_columns,
                )?;
                validate_scope_expr(
                    result,
                    subquery_source,
                    sub_cols,
                    local_qualifiers,
                    outer_columns,
                )?;
            }
            if let Some(else_expr) = else_expr {
                validate_scope_expr(
                    else_expr,
                    subquery_source,
                    sub_cols,
                    local_qualifiers,
                    outer_columns,
                )?;
            }
            Ok(())
        }
        Expr::InSubquery { expr, subquery, .. } => {
            validate_scope_expr(
                expr,
                subquery_source,
                sub_cols,
                local_qualifiers,
                outer_columns,
            )?;
            let _ = subquery;
            Ok(())
        }
        Expr::ExistsSubquery { .. } => Ok(()),
        _ => Ok(()),
    }
}

pub(super) fn is_correlated_subquery(
    subquery: &QueryExpr,
    catalog: &Catalog,
    outer_columns: Option<&[String]>,
) -> bool {
    let filter = match &subquery.filter {
        Some(f) => f,
        None => return false,
    };
    if catalog.schema(&subquery.source).is_none() {
        return false; // table not found — not correlation, just an error
    }
    let mut refs = Vec::new();
    collect_field_refs(filter, &mut refs);
    let local_qualifiers = local_qualifiers(subquery);
    refs.iter().any(|r| {
        if let Some((qualifier, field)) = r.split_once('.') {
            if local_qualifiers.iter().any(|local| local == qualifier) {
                false
            } else if let Some(alias) = outer_correlation_alias(qualifier) {
                outer_columns.is_some_and(|columns| {
                    exact_outer_column_index(alias, field, columns).is_some()
                })
            } else {
                outer_columns.is_some_and(|columns| columns.iter().any(|column| column == r))
            }
        } else {
            outer_columns.is_some_and(|columns| has_outer_column(r, columns))
        }
    })
}

pub(super) fn contains_subquery(expr: &Expr) -> bool {
    match expr {
        Expr::InSubquery { .. } => true,
        Expr::ExistsSubquery { .. } => true,
        Expr::BinaryOp(l, _, r) => contains_subquery(l) || contains_subquery(r),
        Expr::UnaryOp(_, inner) => contains_subquery(inner),
        Expr::InList { expr, list, .. } => {
            contains_subquery(expr) || list.iter().any(contains_subquery)
        }
        Expr::Case { whens, else_expr } => {
            whens
                .iter()
                .any(|(c, r)| contains_subquery(c) || contains_subquery(r))
                || else_expr.as_ref().is_some_and(|e| contains_subquery(e))
        }
        Expr::ScalarFunc(_, args) => args.iter().any(contains_subquery),
        Expr::Cast(inner, _) => contains_subquery(inner),
        Expr::FunctionCall(_, inner, _) => contains_subquery(inner),
        Expr::Coalesce(l, r) => contains_subquery(l) || contains_subquery(r),
        _ => false,
    }
}

pub(super) fn value_to_expr(val: Value) -> Expr {
    match val {
        Value::Int(v) => Expr::Literal(Literal::Int(v)),
        Value::Float(v) => Expr::Literal(Literal::Float(v)),
        Value::Str(v) => Expr::Literal(Literal::String(v)),
        Value::Bool(v) => Expr::Literal(Literal::Bool(v)),
        Value::Empty => Expr::Null,
        // DateTime / Uuid / Bytes have no Literal form; carry the value verbatim
        // so subquery comparisons see the real value, not a bogus Int(0).
        other => Expr::ValueLit(other),
    }
}

pub(super) fn coerce_value(val: Value, col: &ColumnDef) -> Result<Value, String> {
    use TypeId::*;
    match (&val, col.type_id) {
        // A missing value passes through, even for a `required` column. That is
        // a known gap: a per-row expression that evaluates to the empty set
        // (division by a per-row zero, a missing JSON path) can land in a
        // required column. Rejecting it here is worse, because coercion runs
        // per row *inside* the expression-update write loop
        // (`plan_exec/dispatch.rs`), which writes each row as it goes and
        // commits when the statement returns whether or not it errored: the
        // rejection turned one bad row into a torn, durably committed update of
        // the rows before it. Closing this needs statement-level atomicity, not
        // a per-row refusal on the write path.
        (Value::Empty, _) => Ok(val),
        (Value::Int(_), Int) => Ok(val),
        (Value::Float(_), Float) => Ok(val),
        (Value::Bool(_), Bool) => Ok(val),
        (Value::Str(_), Str) => Ok(val),
        // An already-encoded PJ1 document passes through untouched (e.g. a
        // `returning`/subquery value flowing back into a json column).
        (Value::Json(_), Json) => Ok(val),
        // A string literal into a json column is parsed and canonicalized to
        // PJ1 at write time (the storage layer does not auto-coerce text). The
        // error is prefixed `invalid JSON` so it survives the server's
        // safe-error allowlist ("invalid" is a known-safe prefix).
        (Value::Str(s), Json) => powdb_storage::pj1::parse_json_text(s)
            .map(|bytes| Value::Json(bytes.into_boxed_slice()))
            .map_err(|e| format!("invalid JSON for column '{}': {}", col.name, e)),
        (Value::DateTime(_), DateTime) => Ok(val),
        (Value::Uuid(_), Uuid) => Ok(val),
        (Value::Bytes(_), Bytes) => Ok(val),
        (Value::Int(v), Float) => Ok(Value::Float(*v as f64)),
        (Value::Int(v), DateTime) => Ok(Value::Int(*v)),
        (Value::Str(s), DateTime) => Err(format!(
            "column '{}' is datetime — use an integer timestamp, not a string (\"{}\")",
            col.name, s
        )),
        // A plain string literal into a uuid/bytes column is coerced (and
        // validated) per row at execution time — so a bulk-load insert keeps
        // one cached plan and each row's value is checked independently.
        (Value::Str(s), Uuid) => parse_uuid_str(s).map(Value::Uuid).ok_or_else(|| {
            format!(
                "column '{}' is uuid — expected canonical 8-4-4-4-12 hex, got \"{}\"",
                col.name, s
            )
        }),
        (Value::Str(s), Bytes) => parse_hex_bytes(s).map(Value::Bytes).ok_or_else(|| {
            format!(
                "column '{}' is bytes — expected Postgres bytea hex (\\x-prefixed, even length), got \"{}\"",
                col.name, s
            )
        }),
        // A float into an int column is accepted only when it IS that
        // integer. `*v as i64` truncates toward zero and saturates at the ends
        // of the range, so `30.7` was stored as 30, `-0.5` as 0 and `1e300` as
        // `i64::MAX`: the column refused a string outright and silently
        // rewrote the near-miss number.
        (Value::Float(v), Int) => exact_i64(*v).map(Value::Int).ok_or_else(|| {
            format!(
                "column '{}' is int and {v} is not a whole number in range; \
                 write an integer",
                col.name
            )
        }),
        _ => Err(format!(
            "type mismatch for column '{}': expected {:?}, got {}",
            col.name,
            col.type_id,
            match &val {
                Value::Int(_) => "int",
                Value::Float(_) => "float",
                Value::Bool(_) => "bool",
                Value::Str(_) => "str",
                Value::Empty => "null",
                _ => "other",
            }
        )),
    }
}

/// `v` as an `i64` when the conversion is exact: a whole number inside the
/// range. Anything else has no integer to become.
fn exact_i64(v: f64) -> Option<i64> {
    if !v.is_finite() || v.fract() != 0.0 {
        return None;
    }
    // 2^63 is exactly representable; every i64 lies in [-2^63, 2^63).
    if !(-9_223_372_036_854_775_808.0..9_223_372_036_854_775_808.0).contains(&v) {
        return None;
    }
    Some(v as i64)
}

pub(super) fn literal_to_value(expr: &Expr) -> Result<Value, String> {
    match expr {
        Expr::Literal(Literal::Int(v)) => Ok(Value::Int(*v)),
        Expr::Literal(Literal::Float(v)) => Ok(Value::Float(*v)),
        Expr::Literal(Literal::String(v)) => Ok(Value::Str(v.clone())),
        Expr::Literal(Literal::Bool(v)) => Ok(Value::Bool(*v)),
        // A value the typed-literal coercion pass already resolved (a uuid,
        // datetime or bytes comparison key). It is the only literal form that
        // can address those columns' index lanes.
        Expr::ValueLit(v) => Ok(v.clone()),
        Expr::Null => Ok(Value::Empty),
        // Const-fold cast sugar in value position: `uuid("…")`, `bytes("…")`,
        // `cast(1718000000, "datetime")`. A failed cast errors (the whole
        // statement aborts before any write) rather than silently inserting
        // null.
        Expr::Cast(inner, cast_type) => {
            let v = literal_to_value(inner)?;
            match eval_cast(v, *cast_type) {
                Value::Empty => Err(format!("cast to {cast_type:?} produced no value")),
                out => Ok(out),
            }
        }
        _ => Err("expected literal value".into()),
    }
}

/// Parse a canonical hyphenated `8-4-4-4-12` UUID string (case-insensitive)
/// into its 16 raw bytes. Returns `None` on any deviation from the canonical
/// form (wrong length, misplaced hyphens, non-hex digit).
fn parse_uuid_str(s: &str) -> Option<[u8; 16]> {
    let b = s.as_bytes();
    if b.len() != 36 || b[8] != b'-' || b[13] != b'-' || b[18] != b'-' || b[23] != b'-' {
        return None;
    }
    let mut out = [0u8; 16];
    let mut oi = 0usize;
    let mut hi: Option<u8> = None;
    for (pos, &c) in b.iter().enumerate() {
        if matches!(pos, 8 | 13 | 18 | 23) {
            continue;
        }
        let nib = hex_nibble(c)?;
        match hi {
            None => hi = Some(nib),
            Some(h) => {
                out[oi] = (h << 4) | nib;
                oi += 1;
                hi = None;
            }
        }
    }
    Some(out)
}

/// Parse Postgres bytea text encoding — a `\x` prefix followed by an
/// even-length run of hex digits — into raw bytes. Returns `None` if the
/// prefix is missing, the length is odd, or a non-hex digit appears. PowQL
/// source spells the prefix `"\\x…"` (the lexer collapses `\\` to one `\`).
fn parse_hex_bytes(s: &str) -> Option<Vec<u8>> {
    let rest = s.strip_prefix("\\x")?;
    let b = rest.as_bytes();
    if b.len() % 2 != 0 {
        return None;
    }
    let mut out = Vec::with_capacity(b.len() / 2);
    let mut i = 0usize;
    while i < b.len() {
        out.push((hex_nibble(b[i])? << 4) | hex_nibble(b[i + 1])?);
        i += 2;
    }
    Some(out)
}

fn hex_nibble(c: u8) -> Option<u8> {
    match c {
        b'0'..=b'9' => Some(c - b'0'),
        b'a'..=b'f' => Some(c - b'a' + 10),
        b'A'..=b'F' => Some(c - b'A' + 10),
        _ => None,
    }
}

/// Mission C Phase 5: direct Literal→Value conversion used by the
/// prepared-statement Insert fast path. Skips the `Expr::Literal` unwrap
/// and the `Result` plumbing of [`literal_to_value`]. String literals
/// still clone because the row needs an owned `Value::Str`.
#[inline]
pub(super) fn literal_value_from(lit: &Literal) -> Value {
    match lit {
        Literal::Int(v) => Value::Int(*v),
        Literal::Float(v) => Value::Float(*v),
        Literal::String(v) => Value::Str(v.clone()),
        Literal::Bool(v) => Value::Bool(*v),
    }
}

/// Mission C Phase 13: moving companion to [`literal_value_from`] used
/// by [`Engine::execute_prepared_take`]. Pulls the `String` out of a
/// `Literal::String` via `mem::take`, leaving an empty string behind
/// so the caller's slice remains valid (but with blanked-out strings).
/// On the insert fast path this removes one heap alloc per string
/// column per row.
#[inline]
pub(super) fn literal_value_take(lit: &mut Literal) -> Value {
    match lit {
        Literal::Int(v) => Value::Int(*v),
        Literal::Float(v) => Value::Float(*v),
        Literal::String(v) => Value::Str(std::mem::take(v)),
        Literal::Bool(v) => Value::Bool(*v),
    }
}

/// Comparison-semantics mode for the six comparison operators
/// (`= != < > <= >=`).
///
/// - `Filter`: a missing (`Empty`) operand never matches — the row is excluded.
///   This is SQL NULL semantics and matches the compiled predicate leaves.
///   Used for every filter, HAVING, CASE, and nested-projection residual.
/// - `Join`: comparisons keep the raw `Value` order / equality, so a JOIN key
///   equality still matches `Empty = Empty` (PowDB deliberately joins on
///   missing keys; see `plan_exec/join.rs`). Used only for JOIN `ON` / residual
///   conditions so the hash and nested-loop join paths stay identical and
///   unchanged.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum CmpMode {
    Filter,
    Join,
}

pub(super) fn eval_expr(expr: &Expr, row: &[Value], columns: &[String]) -> Value {
    eval_expr_mode(expr, row, columns, CmpMode::Filter)
}

/// Resolve an unqualified field name against the row's column names.
///
/// An exact match wins. Failing that, a join names its output columns
/// `alias.field`, and PowQL accepts the unqualified `.field` spelling inside a
/// join (`User join Order on User.id = Order.user_id { .name, .amount }`), so
/// the bare name also resolves against the field half of a qualified column.
/// Without that second pass the exact match missed and every such projection
/// evaluated to `Empty`: a row of NULLs for a query the validator accepted.
///
/// A bare name two aliases both expose has no single answer; that case is a
/// typed error raised by `validate_column_references` before any row is read,
/// so the first suffix match here is the only match.
pub(super) fn resolve_column_index(name: &str, columns: &[String]) -> Option<usize> {
    if let Some(index) = columns.iter().position(|c| c == name) {
        return Some(index);
    }
    columns
        .iter()
        .position(|c| matches!(c.split_once('.'), Some((_, field)) if field == name))
}

pub(super) fn eval_expr_mode(
    expr: &Expr,
    row: &[Value],
    columns: &[String],
    mode: CmpMode,
) -> Value {
    match expr {
        Expr::Field(name) => resolve_column_index(name, columns)
            .map(|i| row[i].clone())
            .unwrap_or(Value::Empty),
        Expr::QualifiedField { qualifier, field } => {
            // Mission E1.2: join queries emit columns named `alias.field`,
            // so the lookup is a direct prefix+tail match. We compare in
            // pieces to avoid allocating a fresh `format!("{q}.{f}")` on
            // every row — the join loop can evaluate this tens of thousands
            // of times per query.
            let q = qualifier.as_bytes();
            let f = field.as_bytes();
            let idx = columns.iter().position(|c| {
                let b = c.as_bytes();
                b.len() == q.len() + 1 + f.len()
                    && b[..q.len()] == *q
                    && b[q.len()] == b'.'
                    && b[q.len() + 1..] == *f
            });
            idx.map(|i| row[i].clone()).unwrap_or(Value::Empty)
        }
        Expr::Literal(lit) => match lit {
            Literal::Int(v) => Value::Int(*v),
            Literal::Float(v) => Value::Float(*v),
            Literal::String(v) => Value::Str(v.clone()),
            Literal::Bool(v) => Value::Bool(*v),
        },
        // Nested sub-queries only appear inside a projection; the planner
        // routes them to `NestedProject`, so they never reach evaluation.
        Expr::NestedQuery(_) => Value::Empty,
        // Scalar link paths likewise route to `NestedProjectField::Link` and
        // never reach evaluation.
        Expr::LinkPath { .. } => Value::Empty,
        Expr::BinaryOp(left, op, right) => {
            let l = eval_expr_mode(left, row, columns, mode);
            let r = eval_expr_mode(right, row, columns, mode);
            eval_binop_mode(&l, *op, &r, mode)
        }
        Expr::Coalesce(left, right) => {
            let l = eval_expr_mode(left, row, columns, mode);
            if l.is_empty() {
                eval_expr_mode(right, row, columns, mode)
            } else {
                l
            }
        }
        Expr::InList {
            expr,
            list,
            negated,
        } => {
            let val = eval_expr_mode(expr, row, columns, mode);
            // Operator-level rule (Filter mode): a missing tested value never
            // matches `in` OR `not in`, exactly like `!=` and the six
            // comparisons above. Only the explicit `not ( ... )` form is the
            // two-valued complement. Join mode keeps raw `Value` semantics for
            // parity with join-mode comparisons (which skip the Empty guard).
            if mode == CmpMode::Filter && val.is_empty() {
                return Value::Bool(false);
            }
            // `x in (a, b)` is defined as `x = a or x = b`, so it has to use
            // the same comparison the `=` path uses. Testing with `Value`'s
            // strictly typed `PartialEq` made the two operators disagree on the
            // same pair: `.n = 28.0` matched a stored int 28 and
            // `.n in (28.0)` did not.
            let found = list.iter().any(|item| {
                let iv = eval_expr_mode(item, row, columns, mode);
                eval_binop_mode(&val, BinOp::Eq, &iv, mode) == Value::Bool(true)
            });
            Value::Bool(if *negated { !found } else { found })
        }
        Expr::InSubquery { .. } => {
            // Should have been materialized into InList before eval_expr.
            Value::Empty
        }
        Expr::ExistsSubquery { .. } => {
            // Should have been materialized into a Bool literal before
            // eval_expr (see materialize_subqueries).
            Value::Empty
        }
        Expr::UnaryOp(op, inner) => {
            let v = eval_expr_mode(inner, row, columns, mode);
            match op {
                // Two-valued, as docs/POWQL.md states for every other `not`:
                // a missing value never matches, so the predicate it stands
                // for is false and its complement is true. Without this,
                // `not .b` excluded the rows with no `b` while
                // `not (.b = true)`, the same predicate one word longer,
                // included them.
                UnaryOp::Not => match v {
                    Value::Bool(b) => Value::Bool(!b),
                    Value::Empty => Value::Bool(true),
                    _ => Value::Empty,
                },
                UnaryOp::Exists => Value::Bool(!v.is_empty()),
                UnaryOp::NotExists => Value::Bool(v.is_empty()),
                UnaryOp::IsNull => Value::Bool(v.is_empty()),
                UnaryOp::IsNotNull => Value::Bool(!v.is_empty()),
            }
        }
        Expr::ScalarFunc(func, args) => {
            // `json_type` needs the raw PJ1 node, not a scalarized Value, so it
            // can tell a JSON `null` (node present, tag 0) from a missing path
            // (no node). Intercept it before the generic arg scalarization.
            if *func == ScalarFn::JsonType {
                return eval_json_type(args.first(), row, columns);
            }
            if *func == ScalarFn::JsonText {
                return eval_json_text(args.first(), row, columns);
            }
            let vals: Vec<Value> = args
                .iter()
                .map(|a| eval_expr_mode(a, row, columns, mode))
                .collect();
            eval_scalar_func(*func, &vals)
        }
        Expr::JsonPath { base, segments } => {
            let base_val = eval_expr_mode(base, row, columns, mode);
            match walk_json_path(&base_val, segments) {
                // Scalarize the addressed node per design 4.4. JSON `null` and
                // a missing path both collapse to `Empty` here (use `json_type`
                // to distinguish them).
                Some(node) => pj1_scalarize(node),
                None => Value::Empty,
            }
        }
        Expr::Case { whens, else_expr } => {
            for (condition, result) in whens {
                if eval_predicate_mode(condition, row, columns, mode) {
                    return eval_expr_mode(result, row, columns, mode);
                }
            }
            match else_expr {
                Some(e) => eval_expr_mode(e, row, columns, mode),
                None => Value::Empty,
            }
        }
        Expr::Cast(inner, cast_type) => {
            let val = eval_expr_mode(inner, row, columns, mode);
            eval_cast(val, *cast_type)
        }
        Expr::ValueLit(v) => v.clone(),
        Expr::FunctionCall(..) | Expr::Param(_) | Expr::Window { .. } | Expr::Null => Value::Empty,
    }
}

/// Walk `segments` over a JSON `base` value, returning the addressed PJ1 node
/// bytes (a borrow into `base`), or `None` if `base` is not a JSON document or
/// any segment misses. The returned slice is itself a self-contained PJ1
/// document (see [`powdb_storage::pj1`]), so it can be scalarized or walked
/// further with no re-basing.
fn walk_json_path<'a>(base: &'a Value, segments: &[PathSeg]) -> Option<&'a [u8]> {
    let Value::Json(bytes) = base else {
        // Missing column (`Empty`) or a base that is not a JSON document.
        return None;
    };
    let mut cur: &[u8] = bytes;
    for seg in segments {
        let pj = match seg {
            PathSeg::Key(k) => powdb_storage::pj1::PathSeg::Key(k.as_str()),
            PathSeg::Index(i) => powdb_storage::pj1::PathSeg::Index(*i),
        };
        cur = powdb_storage::pj1::pj1_get(cur, &pj)?;
    }
    Some(cur)
}

/// Scalarize a PJ1 node (a self-contained document slice) into a `Value` per
/// design 4.4:
///   - JSON string -> `Str`, integral number -> `Int`, other number -> `Float`,
///     bool -> `Bool`, object/array -> `Json` (owned sub-document copy),
///     JSON `null` -> `Empty`.
///
/// Reads only the node's documented leading tag byte and, for fixed scalars,
/// its fixed little-endian payload. Stored PJ1 is always canonical and
/// validated, so the defensive `Empty` fallbacks (truncated/reserved) are
/// unreachable in practice and, crucially, never panic.
fn pj1_scalarize(node: &[u8]) -> Value {
    match node.first() {
        // null (tag 0) and a missing path are indistinguishable after
        // scalarization — both are the empty set.
        Some(0) => Value::Empty,
        Some(1) => Value::Bool(false),
        Some(2) => Value::Bool(true),
        // int: [tag][i64 LE]
        Some(3) if node.len() >= 9 => {
            Value::Int(i64::from_le_bytes(node[1..9].try_into().unwrap()))
        }
        // float: [tag][f64 LE]
        Some(4) if node.len() >= 9 => {
            Value::Float(f64::from_le_bytes(node[1..9].try_into().unwrap()))
        }
        // string: [tag][len u32 LE][UTF-8]
        Some(5) if node.len() >= 5 => {
            let len = u32::from_le_bytes(node[1..5].try_into().unwrap()) as usize;
            match node
                .get(5..5 + len)
                .and_then(|b| std::str::from_utf8(b).ok())
            {
                Some(s) => Value::Str(s.to_string()),
                None => Value::Empty,
            }
        }
        // array (6) / object (7): return the owned sub-document.
        Some(6) | Some(7) => Value::Json(node.to_vec().into_boxed_slice()),
        // Truncated scalar, reserved tag, or empty slice: never panic.
        _ => Value::Empty,
    }
}

/// The `json_type(expr)` scalar: `'null'|'string'|'number'|'bool'|'object'|
/// 'array'` for the addressed JSON node, or `Empty` when the path is missing.
/// Operates on the raw PJ1 node (not a scalarized Value) so it can distinguish
/// a JSON `null` (returns `'null'`) from a missing path (returns `Empty`).
fn eval_json_type(arg: Option<&Expr>, row: &[Value], columns: &[String]) -> Value {
    let Some(arg) = arg else {
        return Value::Empty;
    };
    // Resolve the raw node: for a `->` path, walk without scalarizing so a
    // present JSON null survives; for any other expression, a `Value::Json`
    // IS a node and anything else is treated as missing.
    let node: Option<Vec<u8>> = match arg {
        Expr::JsonPath { base, segments } => {
            let base_val = eval_expr(base, row, columns);
            walk_json_path(&base_val, segments).map(|n| n.to_vec())
        }
        other => match eval_expr(other, row, columns) {
            Value::Json(b) => Some(b.into_vec()),
            _ => None,
        },
    };
    match node.as_deref().and_then(<[u8]>::first) {
        Some(0) => Value::Str("null".into()),
        Some(1) | Some(2) => Value::Str("bool".into()),
        Some(3) | Some(4) => Value::Str("number".into()),
        Some(5) => Value::Str("string".into()),
        Some(6) => Value::Str("array".into()),
        Some(7) => Value::Str("object".into()),
        // Missing path (no node) or a defensive truncated/reserved node.
        _ => Value::Empty,
    }
}

/// SQL `->>` semantics over the raw addressed PJ1 node. Strings are returned
/// without JSON quotes; numbers and booleans use canonical JSON spelling;
/// objects and arrays return canonical JSON text. Missing paths and JSON null
/// both map to `Empty`.
fn eval_json_text(arg: Option<&Expr>, row: &[Value], columns: &[String]) -> Value {
    let Some(arg) = arg else {
        return Value::Empty;
    };
    let node: Option<Vec<u8>> = match arg {
        Expr::JsonPath { base, segments } => {
            let base_val = eval_expr(base, row, columns);
            walk_json_path(&base_val, segments).map(|node| node.to_vec())
        }
        other => match eval_expr(other, row, columns) {
            Value::Json(bytes) => Some(bytes.into_vec()),
            _ => None,
        },
    };
    let Some(node) = node else {
        return Value::Empty;
    };
    match node.first().copied() {
        Some(0) => Value::Empty,
        Some(5) => pj1_scalarize(&node),
        Some(1..=4) | Some(6) | Some(7) => powdb_storage::pj1::pj1_to_text(&node)
            .map(Value::Str)
            .unwrap_or(Value::Empty),
        _ => Value::Empty,
    }
}

pub(super) fn eval_predicate(expr: &Expr, row: &[Value], columns: &[String]) -> bool {
    eval_predicate_mode(expr, row, columns, CmpMode::Filter)
}

/// Evaluate a JOIN `ON` / residual condition. Join comparisons keep raw `Value`
/// semantics, so a join key equality still matches `Empty = Empty` (PowDB joins
/// on missing keys by design) rather than applying the filter Empty guard. See
/// `plan_exec/join.rs`.
pub(super) fn eval_join_predicate(expr: &Expr, row: &[Value], columns: &[String]) -> bool {
    eval_predicate_mode(expr, row, columns, CmpMode::Join)
}

pub(super) fn eval_predicate_mode(
    expr: &Expr,
    row: &[Value],
    columns: &[String],
    mode: CmpMode,
) -> bool {
    match eval_expr_mode(expr, row, columns, mode) {
        Value::Bool(b) => b,
        _ => false,
    }
}

fn eval_scalar_func(func: ScalarFn, args: &[Value]) -> Value {
    match func {
        ScalarFn::Upper => match args.first() {
            Some(Value::Str(s)) => Value::Str(s.to_uppercase()),
            _ => Value::Empty,
        },
        ScalarFn::Lower => match args.first() {
            Some(Value::Str(s)) => Value::Str(s.to_lowercase()),
            _ => Value::Empty,
        },
        // Characters, not UTF-8 bytes. `substring` and `like`'s `_` wildcard
        // both count characters, so counting bytes here made three string
        // operations disagree about the same string: `length("Zoe")` with a
        // diaeresis was 4 while `like "___"` matched it and `substring(s, 1, 3)`
        // returned all of it.
        //
        // A `bytes` value is measured in bytes, the only unit it has. It used
        // to fall through to `Empty`, so `length(.blob)` answered null on every
        // row with no error anywhere: a silent wrong answer for a question with
        // one obvious right answer. Operands that have no length at all are
        // refused before execution (`plan_exec::validate::length_type_error`)
        // whenever their type is fixed by the schema; this arm is what the
        // remaining un-typable ones (a cast, a bound parameter, a json path)
        // fall back to.
        ScalarFn::Length => match args.first() {
            Some(Value::Str(s)) => Value::Int(s.chars().count() as i64),
            Some(Value::Bytes(b)) => Value::Int(b.len() as i64),
            _ => Value::Empty,
        },
        ScalarFn::Trim => match args.first() {
            Some(Value::Str(s)) => Value::Str(s.trim().to_string()),
            _ => Value::Empty,
        },
        ScalarFn::Substring => {
            if args.len() < 3 {
                return Value::Empty;
            }
            match (&args[0], &args[1], &args[2]) {
                (Value::Str(s), Value::Int(start), Value::Int(len)) => {
                    // `*len as usize` turned a negative length into a number
                    // near `usize::MAX`, so `substring(.s, 2, -1)` returned the
                    // whole rest of the string instead of nothing. A negative
                    // length has no substring, which is missing, not everything.
                    let Ok(len) = usize::try_from(*len) else {
                        return Value::Empty;
                    };
                    // A start before the first character selects from the
                    // beginning of the string under the same cast; keep that,
                    // but reach it by saturation rather than by wrapping.
                    let start = usize::try_from(*start)
                        .unwrap_or(usize::MAX)
                        .saturating_sub(1); // 1-indexed
                    let sub: String = s.chars().skip(start).take(len).collect();
                    Value::Str(sub)
                }
                _ => Value::Empty,
            }
        }
        ScalarFn::Concat => {
            let mut result = String::new();
            for v in args {
                match v {
                    Value::Str(s) => result.push_str(s),
                    Value::Int(n) => result.push_str(&n.to_string()),
                    Value::Float(f) => result.push_str(&f.to_string()),
                    Value::Bool(b) => result.push_str(if *b { "true" } else { "false" }),
                    _ => {}
                }
            }
            Value::Str(result)
        }
        // Math functions
        // `i64::MIN.abs()` has no representable result: it panics under
        // overflow checks and wraps back to `i64::MIN` in release.
        ScalarFn::Abs => match args.first() {
            Some(Value::Int(n)) => n.checked_abs().map_or(Value::Empty, Value::Int),
            Some(Value::Float(f)) => Value::Float(f.abs()),
            _ => Value::Empty,
        },
        ScalarFn::Round => {
            let decimals = match args.get(1) {
                Some(Value::Int(d)) => *d,
                _ => 0,
            };
            match args.first() {
                Some(Value::Float(f)) => Value::Float(round_to_decimals(*f, decimals)),
                Some(Value::Int(n)) => Value::Int(*n),
                _ => Value::Empty,
            }
        }
        ScalarFn::Ceil => match args.first() {
            Some(Value::Float(f)) => Value::Float(f.ceil()),
            Some(Value::Int(n)) => Value::Int(*n),
            _ => Value::Empty,
        },
        ScalarFn::Floor => match args.first() {
            Some(Value::Float(f)) => Value::Float(f.floor()),
            Some(Value::Int(n)) => Value::Int(*n),
            _ => Value::Empty,
        },
        ScalarFn::Sqrt => match args.first() {
            Some(Value::Float(f)) if *f >= 0.0 => Value::Float(f.sqrt()),
            Some(Value::Int(n)) if *n >= 0 => Value::Float((*n as f64).sqrt()),
            _ => Value::Empty,
        },
        ScalarFn::Pow => match (args.first(), args.get(1)) {
            (Some(Value::Float(base)), Some(Value::Float(exp))) => Value::Float(base.powf(*exp)),
            (Some(Value::Float(base)), Some(Value::Int(exp))) => {
                Value::Float(pow_int_exponent(*base, *exp))
            }
            (Some(Value::Int(base)), Some(Value::Int(exp))) => {
                if *exp >= 0 && *exp <= u32::MAX as i64 {
                    match base.checked_pow(*exp as u32) {
                        Some(v) => Value::Int(v),
                        None => Value::Float(pow_int_exponent(*base as f64, *exp)),
                    }
                } else {
                    Value::Float(pow_int_exponent(*base as f64, *exp))
                }
            }
            (Some(Value::Int(base)), Some(Value::Float(exp))) => {
                Value::Float((*base as f64).powf(*exp))
            }
            _ => Value::Empty,
        },
        // Date/time functions
        ScalarFn::Now => {
            use std::time::{SystemTime, UNIX_EPOCH};
            let micros = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_micros() as i64;
            Value::DateTime(micros)
        }
        ScalarFn::Extract => {
            // extract("part", datetime_expr)
            let part = match args.first() {
                Some(Value::Str(s)) => s.as_str(),
                _ => return Value::Empty,
            };
            let micros = match args.get(1) {
                Some(Value::DateTime(m)) => *m,
                Some(Value::Int(m)) => *m, // treat raw int as micros
                _ => return Value::Empty,
            };
            datetime_extract(part, micros)
        }
        ScalarFn::DateAdd => {
            // date_add(datetime_expr, amount, "unit")
            let micros = match args.first() {
                Some(Value::DateTime(m)) => *m,
                Some(Value::Int(m)) => *m,
                _ => return Value::Empty,
            };
            let amount = match args.get(1) {
                Some(Value::Int(n)) => *n,
                _ => return Value::Empty,
            };
            let unit = match args.get(2) {
                Some(Value::Str(s)) => s.as_str(),
                _ => return Value::Empty,
            };
            let Some(factor) = date_unit_micros(unit) else {
                return Value::Empty;
            };
            // Both steps used to be unchecked: `date_add(.ts, 9223372036854775807,
            // "day")` panicked under overflow checks (a remote abort with
            // `panic = "abort"`) and wrapped to a bogus timestamp in release.
            // A literal amount that overflows the unit multiply is refused by
            // `validate_column_references` before any row is read;
            // an amount or base that only overflows for some rows cannot be typed
            // statically, so it yields the empty set like every other date_add
            // bail-out above.
            match amount
                .checked_mul(factor)
                .and_then(|delta| micros.checked_add(delta))
            {
                Some(result) => Value::DateTime(result),
                None => Value::Empty,
            }
        }
        ScalarFn::DateDiff => {
            // date_diff(dt1, dt2, "unit")
            let m1 = match args.first() {
                Some(Value::DateTime(m)) => *m,
                Some(Value::Int(m)) => *m,
                _ => return Value::Empty,
            };
            let m2 = match args.get(1) {
                Some(Value::DateTime(m)) => *m,
                Some(Value::Int(m)) => *m,
                _ => return Value::Empty,
            };
            let unit = match args.get(2) {
                Some(Value::Str(s)) => s.as_str(),
                _ => return Value::Empty,
            };
            let Some(factor) = date_unit_micros(unit) else {
                return Value::Empty;
            };
            // Two stored timestamps a full i64 range apart overflow the
            // subtraction, which panics under overflow checks; the difference is
            // not representable, so the result is the empty set.
            match m1.checked_sub(m2) {
                Some(diff) => Value::Int(diff / factor),
                None => Value::Empty,
            }
        }
        // `json_type` is intercepted in `eval_expr` (it needs the raw PJ1 node,
        // not a scalarized Value); it never reaches this Value-based dispatch.
        ScalarFn::JsonType | ScalarFn::JsonText => Value::Empty,
    }
}

/// `round(value, decimals)` that cannot answer with a non-finite number.
///
/// The decimal count used to be narrowed with `*d as i32`, which is a silent
/// truncation rather than a range check: `round(.f, 2147483647)` raised 10 to
/// an infinite power, `value * inf` was inf, and `inf / inf` was NaN. That NaN
/// did not stay inside one answer, because `update` writes a projected value
/// into the column, after which the row compared inconsistently on every access
/// path and `max()` reported NaN while `min()` skipped it.
///
/// Every degenerate scaling factor has a known answer, so each is returned
/// directly instead of being computed through a value f64 cannot hold: rounding
/// to more decimals than an f64 carries is the identity, and rounding to a
/// magnitude larger than the value itself is zero.
fn round_to_decimals(value: f64, decimals: i64) -> f64 {
    if !value.is_finite() {
        return value;
    }
    let Ok(decimals) = i32::try_from(decimals) else {
        return if decimals > 0 { value } else { 0.0 };
    };
    let factor = 10_f64.powi(decimals);
    if !factor.is_finite() {
        return value;
    }
    if factor == 0.0 {
        return 0.0;
    }
    let scaled = value * factor;
    if !scaled.is_finite() {
        // The value is already integral at this magnitude, so rounding it to
        // any number of decimals leaves it unchanged.
        return value;
    }
    let rounded = scaled.round() / factor;
    if rounded.is_finite() {
        rounded
    } else {
        value
    }
}

/// `base` raised to an integer exponent, without truncating the exponent.
/// `*exp as i32` wrapped, so `pow(2.0, 4294967298)` answered 4.0: not an
/// overflow, a different question silently answered. An exponent past `i32`
/// goes through `powf`, whose answer at that magnitude is zero or infinity,
/// which is the honest one.
fn pow_int_exponent(base: f64, exp: i64) -> f64 {
    match i32::try_from(exp) {
        Ok(exp) => base.powi(exp),
        Err(_) => base.powf(exp as f64),
    }
}

/// Microseconds in one `date_add` / `date_diff` unit, or `None` for a unit
/// spelling neither function accepts. Shared with the planner-side validation
/// that rejects a literal `date_add` amount whose unit multiply overflows
/// (`plan_exec/validate.rs`), so both agree on the accepted spellings.
pub(super) fn date_unit_micros(unit: &str) -> Option<i64> {
    match unit {
        "microsecond" | "microseconds" | "us" => Some(1),
        "millisecond" | "milliseconds" | "ms" => Some(1_000),
        "second" | "seconds" | "s" => Some(1_000_000),
        "minute" | "minutes" | "m" => Some(60_000_000),
        "hour" | "hours" | "h" => Some(3_600_000_000),
        "day" | "days" | "d" => Some(86_400_000_000),
        _ => None,
    }
}

/// Extract a component from a DateTime value (microseconds since epoch).
fn datetime_extract(part: &str, micros: i64) -> Value {
    // Convert micros to seconds + remainder for calendar calculations
    let total_secs = micros / 1_000_000;
    let micro_rem = micros % 1_000_000;

    // Simple civil calendar from Unix timestamp (no TZ — UTC assumed)
    let days_since_epoch = if total_secs >= 0 {
        total_secs / 86400
    } else {
        (total_secs - 86399) / 86400
    };
    let secs_of_day = total_secs - days_since_epoch * 86400;

    match part {
        "hour" => Value::Int(secs_of_day / 3600),
        "minute" => Value::Int((secs_of_day % 3600) / 60),
        "second" => Value::Int(secs_of_day % 60),
        "millisecond" => Value::Int(micro_rem / 1000),
        "microsecond" => Value::Int(micro_rem),
        "epoch" => Value::Int(total_secs),
        "year" | "month" | "day" => {
            // Civil date from days since 1970-01-01 (algorithm from Howard Hinnant)
            let z = days_since_epoch + 719468;
            let era = if z >= 0 { z } else { z - 146096 } / 146097;
            let doe = (z - era * 146097) as u32;
            let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
            let y = (yoe as i64) + era * 400;
            let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
            let mp = (5 * doy + 2) / 153;
            let d = doy - (153 * mp + 2) / 5 + 1;
            let m = if mp < 10 { mp + 3 } else { mp - 9 };
            let y = if m <= 2 { y + 1 } else { y };
            match part {
                "year" => Value::Int(y),
                "month" => Value::Int(m as i64),
                "day" => Value::Int(d as i64),
                _ => unreachable!(),
            }
        }
        _ => Value::Empty,
    }
}

/// Evaluate a CAST expression.
fn eval_cast(val: Value, target: CastType) -> Value {
    match target {
        CastType::Int => match val {
            Value::Int(n) => Value::Int(n),
            Value::Float(f) => Value::Int(f as i64),
            Value::Bool(b) => Value::Int(if b { 1 } else { 0 }),
            Value::Str(s) => s.parse::<i64>().map(Value::Int).unwrap_or(Value::Empty),
            Value::DateTime(m) => Value::Int(m),
            _ => Value::Empty,
        },
        CastType::Float => match val {
            Value::Float(f) => Value::Float(f),
            Value::Int(n) => Value::Float(n as f64),
            Value::Str(s) => s.parse::<f64>().map(Value::Float).unwrap_or(Value::Empty),
            Value::Bool(b) => Value::Float(if b { 1.0 } else { 0.0 }),
            _ => Value::Empty,
        },
        CastType::Str => match val {
            Value::Str(s) => Value::Str(s),
            Value::Int(n) => Value::Str(n.to_string()),
            Value::Float(f) => Value::Str(f.to_string()),
            Value::Bool(b) => Value::Str(b.to_string()),
            Value::DateTime(m) => Value::Str(m.to_string()),
            _ => Value::Empty,
        },
        CastType::Bool => match val {
            Value::Bool(b) => Value::Bool(b),
            Value::Int(n) => Value::Bool(n != 0),
            Value::Str(s) => match s.as_str() {
                "true" | "1" | "yes" => Value::Bool(true),
                "false" | "0" | "no" => Value::Bool(false),
                _ => Value::Empty,
            },
            _ => Value::Empty,
        },
        CastType::DateTime => match val {
            Value::DateTime(m) => Value::DateTime(m),
            Value::Int(m) => Value::DateTime(m),
            _ => Value::Empty,
        },
        CastType::Uuid => match val {
            Value::Uuid(u) => Value::Uuid(u),
            Value::Str(s) => parse_uuid_str(&s).map(Value::Uuid).unwrap_or(Value::Empty),
            _ => Value::Empty,
        },
        CastType::Bytes => match val {
            Value::Bytes(b) => Value::Bytes(b),
            Value::Str(s) => parse_hex_bytes(&s)
                .map(Value::Bytes)
                .unwrap_or(Value::Empty),
            _ => Value::Empty,
        },
    }
}

/// Ordering for a numeric pair whose two sides are different `Value` variants,
/// comparing what the numbers mean rather than what they are stored as.
/// Returns `None` for every other pairing so the caller falls through to the
/// normal `Value` comparison.
///
/// `Value::PartialEq` is deliberately strict per variant, because it has to
/// agree with `Value::Hash` and that is what GROUP BY, DISTINCT and the hash
/// joins key on. `Value::Ord` is not, and neither is the compiled predicate:
/// the compiled float leaf promotes an int literal to `f64` and compares with
/// `total_cmp`, and the compiled Int leaf reads a DateTime column's micros as
/// an i64. So a comparison OPERATOR evaluated generically has to do the same or
/// the answer depends on which physical path ran it, which is what
/// `.f = 1` did: true through the compiled predicate and false through the
/// generic evaluator over the same row.
///
/// Both pairings are the same rule for the same reason:
///
///   * **Int/Float** — compared EXACTLY, by numeric value, via
///     [`int_f64_cmp`]: no precision loss at any magnitude. Widening the int
///     with `as f64` is not an option here even though `Value::Ord` does it
///     for sorting: `i64::MAX as f64` rounds up to 2^63 exactly, so a lossy
///     rule lets `.id = 9223372036854775808.0` match a row holding
///     `i64::MAX` while the index machinery (which is exact) says nothing
///     matches, and the answer would depend on the access path. Exactness
///     also keeps the six operators a total order: leaving `=` strict while
///     `<` and `>=` were numeric made `.n < 1.0` false, `.n > 1.0` false,
///     `.n <= 1.0` true, `.n >= 1.0` true and `.n = 1.0` false, which is not
///     an order at all.
///   * **DateTime/Int** — a timestamp literal has no distinct spelling in
///     PowQL, so `.created_at > 1700000000000000` arrives as DateTime vs Int.
///     Without this the pair falls to `Value::Ord`'s type-discriminant tail and
///     every timestamp compares greater than every int.
///
/// A Float against a DateTime is deliberately NOT here. `Value::Ord` does not
/// name that pair either, so both evaluators fall to the same discriminant
/// comparison and agree with each other; making it numeric is a semantic change
/// to what a datetime literal means, which belongs with the temporal type work
/// rather than with keeping two evaluators in step.
///
/// The Int/Float rule applies in [`CmpMode::Filter`] only, because a JOIN is
/// not evaluated by this function alone: `plan_exec::join::hash_join` buckets
/// the build side in an `FxHashMap<Value, _>`, so a join KEY is matched by
/// `Value`'s own `Hash` and `PartialEq` and nothing here can change that. Making
/// the operator numeric in `Join` mode too would leave `on a.n = b.f` matching
/// nothing as the key of a hash join and matching numerically as a residual
/// conjunct of the same join, which is a worse answer than either rule applied
/// consistently. Joins therefore keep strict per-variant key equality, which is
/// what they already promised (`Empty = Empty` matches there too). Teaching them
/// cross-type keys means giving the hash side a canonical numeric key, which is
/// the `Value::Hash` change this deliberately does not make.
/// Whether `value` is the float that compares equal to nothing.
#[inline]
fn is_nan(value: &Value) -> bool {
    matches!(value, Value::Float(f) if f.is_nan())
}

fn cross_type_numeric_cmp(
    left: &Value,
    right: &Value,
    mode: CmpMode,
) -> Option<std::cmp::Ordering> {
    match (left, right) {
        (Value::DateTime(a), Value::Int(b)) => Some(a.cmp(b)),
        (Value::Int(a), Value::DateTime(b)) => Some(a.cmp(b)),
        (Value::Int(a), Value::Float(b)) if mode == CmpMode::Filter => Some(int_f64_cmp(*a, *b)),
        (Value::Float(a), Value::Int(b)) if mode == CmpMode::Filter => {
            Some(int_f64_cmp(*b, *a).reverse())
        }
        _ => None,
    }
}

/// Exact comparison of an `i64` against an `f64` by numeric value, with no
/// precision loss at any magnitude (the SQLite approach). Returns the ordering
/// of the int relative to the float.
///
/// Why not `(i as f64).total_cmp(&f)`: that widening is lossy above 2^53
/// (`i64::MAX as f64` rounds up to 2^63), so it would call `i64::MAX` equal
/// to `9223372036854775808.0` while the index-probe machinery, which is
/// exact, matches nothing. Every consumer of this rule (the generic
/// evaluator, the compiled JSON scalar leaves) must agree with the index
/// path, so the rule is exact everywhere.
///
/// NaN sorts above every number, matching `f64::total_cmp` and `Value::Ord`.
/// `-0.0` equals `0`, which `total_cmp` would not say; equality by numeric
/// value is the whole point of the rule.
pub(crate) fn int_f64_cmp(i: i64, f: f64) -> std::cmp::Ordering {
    use std::cmp::Ordering;
    if f.is_nan() {
        return Ordering::Less;
    }
    // 2^63 and -2^63 are exactly representable in f64; every i64 lies in
    // [-2^63, 2^63).
    if f >= 9_223_372_036_854_775_808.0 {
        return Ordering::Less;
    }
    if f < -9_223_372_036_854_775_808.0 {
        return Ordering::Greater;
    }
    // In range, truncation toward zero is exact. Above 2^53 an f64 has no
    // fractional part, so `t as f64` round-trips exactly there too; below
    // 2^53 every i64 in range is exactly representable.
    let t = f as i64;
    match i.cmp(&t) {
        Ordering::Equal => {
            let frac = f - t as f64;
            if frac > 0.0 {
                Ordering::Less
            } else if frac < 0.0 {
                Ordering::Greater
            } else {
                Ordering::Equal
            }
        }
        other => other,
    }
}

pub(super) fn eval_binop_mode(left: &Value, op: BinOp, right: &Value, mode: CmpMode) -> Value {
    // In `Filter` mode a missing (`Empty`) operand never matches an ordered or
    // equality / inequality comparison: the comparison is false, so the row is
    // excluded. This mirrors the compiled predicate leaves (`compiled.rs`:
    // Int/Float/StrEq/Json null-guard and never match Empty) and SQL NULL
    // semantics, keeping the generic and compiled paths in agreement regardless
    // of whether a predicate compiles. Presence is tested with `exists` /
    // `not exists`, not with a comparison.
    //
    // In `Join` mode the guard is skipped so JOIN key equality stays direct
    // `Value` equality (including `Empty = Empty`) — PowDB deliberately joins on
    // missing keys, and the hash and nested-loop join paths must agree.
    if mode == CmpMode::Filter
        && matches!(
            op,
            BinOp::Eq | BinOp::Neq | BinOp::Lt | BinOp::Gt | BinOp::Lte | BinOp::Gte
        )
        && (left.is_empty() || right.is_empty())
    {
        return Value::Bool(false);
    }
    // IEEE: NaN is unordered, so it is equal to nothing, less than nothing and
    // greater than nothing, and `!=` against it is true for every row including
    // the NaN row itself. `Value`'s own equality is `total_cmp`, which has to be
    // a total order because `Eq`/`Hash` are built on it and `order`, `group`,
    // `distinct` and the B-tree all need NaN in one definite place. Comparison
    // and ordering are different questions: only this one follows IEEE, which
    // is why the rule lives here rather than in `Value`. `Join` mode keeps
    // identity, so a join on a NaN key still matches, exactly as it does for a
    // missing key.
    if mode == CmpMode::Filter
        && matches!(
            op,
            BinOp::Eq | BinOp::Neq | BinOp::Lt | BinOp::Gt | BinOp::Lte | BinOp::Gte
        )
        && (is_nan(left) || is_nan(right))
    {
        return Value::Bool(op == BinOp::Neq);
    }
    // Numeric pairs whose two sides are different `Value` variants compare as
    // numbers, not as variants: see `cross_type_numeric_cmp` for why the six
    // comparison operators cannot use `Value::PartialEq` here and stay
    // consistent with each other, with `Value::Ord`, and with the compiled
    // predicate leaves.
    if let (Some(ordering), true) = (
        cross_type_numeric_cmp(left, right, mode),
        matches!(
            op,
            BinOp::Eq | BinOp::Neq | BinOp::Lt | BinOp::Gt | BinOp::Lte | BinOp::Gte
        ),
    ) {
        use std::cmp::Ordering as O;
        return Value::Bool(match op {
            BinOp::Eq => ordering == O::Equal,
            BinOp::Neq => ordering != O::Equal,
            BinOp::Lt => ordering == O::Less,
            BinOp::Gt => ordering == O::Greater,
            BinOp::Lte => ordering != O::Greater,
            _ => ordering != O::Less,
        });
    }
    // An ordered comparison between two different types has no meaningful
    // answer, and `Value::Ord`'s tail arm gives it one anyway: it falls back to
    // the type discriminant, so `.j->v > 99.5` returned the rows whose value was
    // the string "deep" and the bool true. The pairs that genuinely order across
    // types (Int/Float, DateTime/Int) were handled just above; every other pair
    // is false, which is what the typed-column comparisons are refused with at
    // plan time. `Join` mode keeps `Value::Ord` so a non-equi join's ordering
    // stays what the hash and nested-loop paths both already agree on.
    if mode == CmpMode::Filter
        && matches!(op, BinOp::Lt | BinOp::Gt | BinOp::Lte | BinOp::Gte)
        && left.type_id() != right.type_id()
    {
        return Value::Bool(false);
    }
    // A json document against a string compares as a document (either
    // orientation): the text is parsed to canonical PJ1 and byte-compared,
    // the same coercion `coerce_value` applies on insert. Statement literals
    // that fail to parse were already rejected by
    // `validate_column_references`; a runtime-typed string that is not JSON
    // (a cast, a scalar function result) simply equals no document. Only
    // `=` / `!=` coerce — documents have no order against text, and
    // validation refuses those shapes up front.
    if matches!(op, BinOp::Eq | BinOp::Neq) {
        if let (Value::Json(doc), Value::Str(text)) | (Value::Str(text), Value::Json(doc)) =
            (left, right)
        {
            let eq = powdb_storage::pj1::parse_json_text(text)
                .map(|canonical| canonical.as_slice() == &doc[..])
                .unwrap_or(false);
            return Value::Bool(if op == BinOp::Eq { eq } else { !eq });
        }
    }
    match op {
        BinOp::Eq => Value::Bool(left == right),
        BinOp::Neq => Value::Bool(left != right),
        BinOp::Lt => Value::Bool(left < right),
        BinOp::Gt => Value::Bool(left > right),
        BinOp::Lte => Value::Bool(left <= right),
        BinOp::Gte => Value::Bool(left >= right),
        BinOp::And => match (left, right) {
            (Value::Bool(a), Value::Bool(b)) => Value::Bool(*a && *b),
            _ => Value::Bool(false),
        },
        BinOp::Or => match (left, right) {
            (Value::Bool(a), Value::Bool(b)) => Value::Bool(*a || *b),
            _ => Value::Bool(false),
        },
        // Arithmetic is defined on numbers only. An operand whose type is known
        // before execution and is not a number (a datetime, str, bool, uuid,
        // bytes or json column, or a string / bool literal) is rejected as a
        // typed error by `validate_column_references`, so `.ts + 1` no longer
        // reaches here and quietly answers with the empty set. What still falls
        // through to the `_` arms is a MISSING operand, which propagates as
        // missing per SQL NULL semantics, and an operand whose type is only
        // known per row (a cast, a scalar function, a JSON path).
        // Integer overflow is an error, never a clamped number and never a
        // silent NULL. `saturating_add` answered `.big + 1` with `i64::MAX`,
        // which is a plausible-looking number that is not the sum; `Empty`
        // answered it with a missing value, which an `update` then wrote into a
        // required column. The aggregate accumulator refuses the same overflow
        // outright (`plan_exec::aggregate::agg_overflow_error`), so all four
        // operators now report through `arith_fault` and say the same thing
        // `sum` says.
        BinOp::Add => match (left, right) {
            (Value::Int(a), Value::Int(b)) => a
                .checked_add(*b)
                .map_or_else(|| overflow("a sum"), Value::Int),
            (Value::Float(a), Value::Float(b)) => Value::Float(a + b),
            (Value::Int(a), Value::Float(b)) => Value::Float(*a as f64 + b),
            (Value::Float(a), Value::Int(b)) => Value::Float(a + *b as f64),
            _ => Value::Empty,
        },
        BinOp::Sub => match (left, right) {
            (Value::Int(a), Value::Int(b)) => a
                .checked_sub(*b)
                .map_or_else(|| overflow("a difference"), Value::Int),
            (Value::Float(a), Value::Float(b)) => Value::Float(a - b),
            (Value::Int(a), Value::Float(b)) => Value::Float(*a as f64 - b),
            (Value::Float(a), Value::Int(b)) => Value::Float(a - *b as f64),
            _ => Value::Empty,
        },
        BinOp::Mul => match (left, right) {
            (Value::Int(a), Value::Int(b)) => a
                .checked_mul(*b)
                .map_or_else(|| overflow("a product"), Value::Int),
            (Value::Float(a), Value::Float(b)) => Value::Float(a * b),
            (Value::Int(a), Value::Float(b)) => Value::Float(*a as f64 * b),
            (Value::Float(a), Value::Int(b)) => Value::Float(a * *b as f64),
            _ => Value::Empty,
        },
        BinOp::Div => match (left, right) {
            // `checked_div` guards BOTH divide-by-zero AND the `i64::MIN / -1`
            // overflow case, which panics even in release builds (and with
            // `panic = "abort"` that is a remotely-craftable process crash).
            // Returning `Empty` on either matches the sibling arithmetic arms.
            // A literal zero divisor is a typed error at validation; only a
            // divisor that is zero for some rows reaches this guard.
            (Value::Int(a), Value::Int(b)) => {
                if *b == 0 {
                    divide_by_zero()
                } else {
                    // Still `checked_div`: `i64::MIN / -1` overflows and panics
                    // even in release builds, which under `panic = "abort"` is a
                    // remotely craftable process crash.
                    a.checked_div(*b)
                        .map_or_else(|| overflow("a quotient"), Value::Int)
                }
            }
            (Value::Float(a), Value::Float(b)) => Value::Float(a / b),
            (Value::Int(a), Value::Float(b)) => Value::Float(*a as f64 / b),
            (Value::Float(a), Value::Int(b)) => Value::Float(a / *b as f64),
            _ => Value::Empty,
        },
        BinOp::Like => match (left, right) {
            (Value::Str(text), Value::Str(pattern)) => Value::Bool(like_match(text, pattern)),
            _ => Value::Bool(false),
        },
    }
}

/// SQL LIKE pattern match. `%` matches any sequence (including empty),
/// `_` matches exactly one character. No escape character. Iterative
/// two-pointer with backtracking — O(n·m) time, O(1) stack (a recursive
/// matcher stack-overflows / backtracks exponentially on adversarial input).
pub(super) fn like_match(text: &str, pattern: &str) -> bool {
    let t: Vec<char> = text.chars().collect();
    let p: Vec<char> = pattern.chars().collect();
    let (mut ti, mut pi) = (0usize, 0usize);
    let mut star: Option<usize> = None; // index in p of the last '%'
    let mut star_ti = 0usize; // text index when that '%' was taken
    while ti < t.len() {
        // `%` must be tested before the literal branch: a literal `%` in the
        // TEXT would otherwise consume a pattern `%` as an ordinary character
        // and record no backtrack point (LIKE '%' then failed to match "%a").
        if pi < p.len() && p[pi] == '%' {
            star = Some(pi);
            star_ti = ti;
            pi += 1;
        } else if pi < p.len() && (p[pi] == '_' || p[pi] == t[ti]) {
            ti += 1;
            pi += 1;
        } else if let Some(s) = star {
            pi = s + 1;
            star_ti += 1;
            ti = star_ti;
        } else {
            return false;
        }
    }
    while pi < p.len() && p[pi] == '%' {
        pi += 1;
    }
    pi == p.len()
}

#[cfg(test)]
mod tests {
    use super::int_f64_cmp;
    use super::like_match;
    use std::cmp::Ordering;

    #[test]
    fn int_f64_cmp_is_exact_at_every_magnitude() {
        // The defect this pins: `i64::MAX as f64` rounds up to 2^63, so a
        // lossy rule calls i64::MAX equal to 9223372036854775808.0.
        assert_eq!(
            int_f64_cmp(i64::MAX, 9_223_372_036_854_775_808.0),
            Ordering::Less
        );
        assert_eq!(
            int_f64_cmp(i64::MIN, -9_223_372_036_854_775_808.0),
            Ordering::Equal,
            "-2^63 is exactly representable and exactly i64::MIN"
        );
        assert_eq!(int_f64_cmp(i64::MIN, -1e19), Ordering::Greater);
        assert_eq!(int_f64_cmp(i64::MAX, f64::INFINITY), Ordering::Less);
        assert_eq!(int_f64_cmp(i64::MIN, f64::NEG_INFINITY), Ordering::Greater);
        // 2^53 is the last f64-exact neighborhood; both sides of it compare
        // exactly.
        assert_eq!(
            int_f64_cmp(9_007_199_254_740_992, 9_007_199_254_740_992.0),
            Ordering::Equal
        );
        assert_eq!(
            int_f64_cmp(9_007_199_254_740_993, 9_007_199_254_740_992.0),
            Ordering::Greater,
            "2^53 + 1 must not collapse onto 2^53"
        );
        // Fractions order around the truncated integer.
        assert_eq!(int_f64_cmp(3, 3.5), Ordering::Less);
        assert_eq!(int_f64_cmp(4, 3.5), Ordering::Greater);
        assert_eq!(int_f64_cmp(-3, -3.5), Ordering::Greater);
        assert_eq!(int_f64_cmp(-4, -3.5), Ordering::Less);
        // Numeric equality, not bit equality: 0 equals -0.0.
        assert_eq!(int_f64_cmp(0, -0.0), Ordering::Equal);
        // NaN sorts above every number, matching total_cmp and Value::Ord.
        assert_eq!(int_f64_cmp(i64::MAX, f64::NAN), Ordering::Less);
    }

    #[test]
    fn test_like_match_correctness() {
        assert!(like_match("abc", "a%c"));
        assert!(like_match("abc", "a_c"));
        assert!(like_match("abc", "a%"));
        assert!(like_match("abc", "%b%"));
        assert!(like_match("abc", "abc"));
        assert!(!like_match("abc", "a%d"));
        assert!(like_match("", "%"));
        assert!(like_match("ax", "a_"));
        assert!(!like_match("a", "a_"));
    }

    #[test]
    fn test_like_match_percent_in_text_is_still_matched_by_wildcards() {
        // The defect this pins: the literal/underscore branch ran before the
        // `%` branch, so a pattern `%` landing on a literal `%` in the TEXT
        // was consumed as an ordinary character with no backtrack point
        // recorded. `LIKE '%'` must match every non-null string, including
        // strings that start with `%`.
        assert!(like_match("%a", "%"));
        assert!(like_match("%%", "%"));
        assert!(like_match("%", "%"));
        assert!(like_match("%", "%_"), "'%_' matches any 1+ char string");
        assert!(like_match("%abc", "%abc"));
        assert!(like_match("a%b", "a%b"));
        assert!(!like_match("", "%_"));
    }

    #[test]
    fn test_like_match_adversarial_no_overflow() {
        // A recursive / exponential matcher would overflow the stack or hang
        // here. The iterative two-pointer matcher returns quickly.
        let text = "a".repeat(50_000);
        assert!(!like_match(&text, "%a%a%a%b"));
    }
}