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
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
//! The execute_plan method and associated helpers.
use crate::ast::*;
use crate::plan::*;
use crate::result::{QueryError, QueryResult};
use powdb_storage::catalog::Catalog;
use powdb_storage::row::{decode_column, decode_row, patch_var_column_in_place, RowLayout};
use powdb_storage::types::*;
use std::cmp::Reverse;
use std::collections::BinaryHeap;
use super::compiled::*;
use super::eval::*;
use super::{check_join_limit, Engine, MAX_SORT_ROWS};
use powdb_storage::view::{ViewDef, ViewRegistry};
impl Engine {
pub fn execute_plan(&mut self, plan: &PlanNode) -> Result<QueryResult, QueryError> {
match plan {
PlanNode::SeqScan { table } => {
// Auto-refresh dirty materialized views on read.
if self.view_registry.is_dirty(table) {
self.refresh_view(table)?;
}
let schema = self
.catalog
.schema(table)
.ok_or_else(|| QueryError::TableNotFound(table.to_string()))?
.clone();
let columns: Vec<String> = schema.columns.iter().map(|c| c.name.clone()).collect();
let rows: Vec<Vec<Value>> = self
.catalog
.scan(table)
.map_err(|e| QueryError::StorageError(e.to_string()))?
.map(|(_, row)| row)
.collect();
Ok(QueryResult::Rows { columns, rows })
}
PlanNode::Filter { input, predicate } => {
// Materialize any IN-subqueries in the predicate before the
// scan loop — the closure can't call back into the engine.
// Correlated subqueries are left in place for per-row eval.
let materialized;
let predicate = if contains_subquery(predicate) {
materialized = self.materialize_subqueries(predicate)?;
&materialized
} else {
predicate
};
// Correlated subquery path: per-row materialisation.
if contains_subquery(predicate) {
let result = self.execute_plan(input)?;
return match result {
QueryResult::Rows { columns, rows } => {
let mut filtered = Vec::new();
for row in rows {
let row_pred =
self.materialize_correlated_for_row(predicate, &row, &columns)?;
if eval_predicate(&row_pred, &row, &columns) {
filtered.push(row);
}
}
Ok(QueryResult::Rows {
columns,
rows: filtered,
})
}
_ => Err("filter requires row input".into()),
};
}
// Fast path: fuse Filter + SeqScan into a zero-copy streaming
// loop. Uses decode_column() to evaluate the predicate on only
// the columns it references, avoiding heap allocations for
// String/Bytes columns that aren't part of the filter.
if let PlanNode::SeqScan { table } = input.as_ref() {
// Auto-refresh dirty materialized views.
if self.view_registry.is_dirty(table) {
self.refresh_view(table)?;
}
let schema = self
.catalog
.schema(table)
.ok_or_else(|| QueryError::TableNotFound(table.to_string()))?
.clone();
let columns: Vec<String> =
schema.columns.iter().map(|c| c.name.clone()).collect();
let fast = FastLayout::new(&schema);
let row_layout = RowLayout::new(&schema);
// Mission F: pre-size to skip the first 4 Vec doublings
// (4 → 8 → 16 → 32 → 64). On a 100K-row scan with 30%
// selectivity that's ~4 fewer reallocations + memcpys.
let mut rows: Vec<Vec<Value>> = Vec::with_capacity(64);
// Try compiled predicate for the filter check (handles
// int leaves, string-eq leaves, and And conjunctions).
if let Some(compiled) = compile_predicate(predicate, &columns, &fast, &schema) {
self.catalog
.for_each_row_raw(table, |_rid, data| {
if compiled(data) {
rows.push(decode_row(&schema, data));
}
})
.map_err(|e| QueryError::StorageError(e.to_string()))?;
} else {
let pred_cols = predicate_column_indices(predicate, &columns);
self.catalog
.for_each_row_raw(table, |_rid, data| {
let pred_row =
decode_selective(&schema, &row_layout, data, &pred_cols);
if eval_predicate(predicate, &pred_row, &columns) {
rows.push(decode_row(&schema, data));
}
})
.map_err(|e| QueryError::StorageError(e.to_string()))?;
}
return Ok(QueryResult::Rows { columns, rows });
}
// General path: materialise then filter.
let result = self.execute_plan(input)?;
match result {
QueryResult::Rows { columns, rows } => {
let filtered: Vec<Vec<Value>> = rows
.into_iter()
.filter(|row| eval_predicate(predicate, row, &columns))
.collect();
Ok(QueryResult::Rows {
columns,
rows: filtered,
})
}
_ => Err("filter requires row input".into()),
}
}
PlanNode::Project { input, fields } => {
// Fast path: Project over IndexScan — decode only projected
// columns from raw bytes instead of full decode_row.
if let PlanNode::IndexScan { table, column, key } = input.as_ref() {
let schema = self
.catalog
.schema(table)
.ok_or_else(|| QueryError::TableNotFound(table.to_string()))?
.clone();
let all_columns: Vec<String> =
schema.columns.iter().map(|c| c.name.clone()).collect();
let key_value = literal_to_value(key)?;
let tbl = self
.catalog
.get_table(table)
.ok_or_else(|| QueryError::TableNotFound(table.to_string()))?;
let proj_columns: Vec<String> = fields
.iter()
.map(|f| {
f.alias.clone().unwrap_or_else(|| match &f.expr {
Expr::Field(name) => name.clone(),
_ => "?".into(),
})
})
.collect();
// Determine which column indices the projection needs
let proj_indices: Vec<usize> = fields
.iter()
.filter_map(|f| {
if let Expr::Field(name) = &f.expr {
all_columns.iter().position(|c| c == name)
} else {
None
}
})
.collect();
if tbl.has_index(column) {
let layout = RowLayout::new(&schema);
let rids = tbl.index_lookup_all(column, &key_value);
let mut rows: Vec<Vec<Value>> = Vec::with_capacity(rids.len());
for rid in rids {
if let Some(data) = tbl.heap.get(rid) {
let row: Vec<Value> = proj_indices
.iter()
.map(|&ci| decode_column(&schema, &layout, &data, ci))
.collect();
rows.push(row);
}
}
return Ok(QueryResult::Rows {
columns: proj_columns,
rows,
});
}
}
// Fast path: Project(Limit(Sort(Filter(SeqScan)))) — bounded
// top-N heap. Decodes only the sort key + projected columns,
// keeps at most `limit` rows in a heap. Also handles the
// Project(Limit(Sort(SeqScan))) variant (no filter).
if let PlanNode::Limit {
input: inner,
count: limit_expr,
} = input.as_ref()
{
if let PlanNode::Sort {
input: sort_input,
keys,
} = inner.as_ref()
{
// Fast path only for single-key sorts
if keys.len() == 1 {
let sort_field = &keys[0].field;
let descending = keys[0].descending;
let limit = match limit_expr {
Expr::Literal(Literal::Int(v)) if *v >= 0 => *v as usize,
_ => usize::MAX,
};
let (table_opt, pred_opt): (Option<&str>, Option<&Expr>) =
match sort_input.as_ref() {
PlanNode::SeqScan { table } => (Some(table.as_str()), None),
PlanNode::Filter {
input: fi,
predicate,
} => {
if let PlanNode::SeqScan { table } = fi.as_ref() {
(Some(table.as_str()), Some(predicate))
} else {
(None, None)
}
}
_ => (None, None),
};
if let Some(table) = table_opt {
if let Some(result) = self.project_filter_sort_limit_fast(
table, fields, sort_field, descending, limit, pred_opt,
)? {
return Ok(result);
}
}
}
}
// Fast path: Project(Limit(Filter(SeqScan))) — stream,
// decode only projected columns, stop at limit.
if let PlanNode::Filter {
input: fi,
predicate,
} = inner.as_ref()
{
if let PlanNode::SeqScan { table } = fi.as_ref() {
let limit = match limit_expr {
Expr::Literal(Literal::Int(v)) if *v >= 0 => *v as usize,
_ => usize::MAX,
};
if let Some(result) = self.project_filter_limit_fast(
table,
fields,
limit,
Some(predicate),
)? {
return Ok(result);
}
}
}
// Fast path: Project(Limit(SeqScan)) — stream, no filter.
if let PlanNode::SeqScan { table } = inner.as_ref() {
let limit = match limit_expr {
Expr::Literal(Literal::Int(v)) if *v >= 0 => *v as usize,
_ => usize::MAX,
};
if let Some(result) =
self.project_filter_limit_fast(table, fields, limit, None)?
{
return Ok(result);
}
}
}
// Mission D4: Project(Filter(SeqScan)) without Limit. Reuses
// `project_filter_limit_fast` with limit = usize::MAX so the
// hot loop decodes only projected columns and uses the
// compiled predicate. Previously this fell through to the
// generic Filter branch which materialised every column via
// `decode_row` then re-projected — quadratic work.
//
// multi_col_and_filter (`U filter .age > 30 and .status =
// "active" { .name, .age }`) was 6.18ms (0.7x SQLite) and
// is the load-bearing workload for this fast path.
if let PlanNode::Filter {
input: fi,
predicate,
} = input.as_ref()
{
if let PlanNode::SeqScan { table } = fi.as_ref() {
if let Some(result) = self.project_filter_limit_fast(
table,
fields,
usize::MAX,
Some(predicate),
)? {
return Ok(result);
}
}
}
// Mission D4: Project(SeqScan) without Filter or Limit.
// Decode only projected columns; the previous fall-through
// built full Vec<Value> rows then re-projected.
if let PlanNode::SeqScan { table } = input.as_ref() {
if let Some(result) =
self.project_filter_limit_fast(table, fields, usize::MAX, None)?
{
return Ok(result);
}
}
let result = self.execute_plan(input)?;
match result {
QueryResult::Rows { columns, rows } => {
let proj_columns: Vec<String> = fields
.iter()
.map(|f| {
f.alias.clone().unwrap_or_else(|| match &f.expr {
Expr::Field(name) => name.clone(),
// Mission E1.2: `{ u.name }` projects as the
// qualified column name so callers can still
// disambiguate across the join output.
Expr::QualifiedField { qualifier, field } => {
format!("{qualifier}.{field}")
}
_ => "?".into(),
})
})
.collect();
let proj_rows: Vec<Vec<Value>> = rows
.iter()
.map(|row| {
fields
.iter()
.map(|f| eval_expr(&f.expr, row, &columns))
.collect()
})
.collect();
Ok(QueryResult::Rows {
columns: proj_columns,
rows: proj_rows,
})
}
_ => Err("project requires row input".into()),
}
}
PlanNode::Sort { input, keys } => {
let result = self.execute_plan(input)?;
match result {
QueryResult::Rows { columns, mut rows } => {
if rows.len() > MAX_SORT_ROWS {
return Err(QueryError::SortLimitExceeded);
}
let key_indices: Vec<(usize, bool)> = keys
.iter()
.map(|k| {
columns
.iter()
.position(|c| c == &k.field)
.map(|idx| (idx, k.descending))
.ok_or_else(|| QueryError::ColumnNotFound {
table: String::new(),
column: k.field.clone(),
})
})
.collect::<Result<_, QueryError>>()?;
rows.sort_by(|a, b| {
for &(col_idx, descending) in &key_indices {
let cmp = a[col_idx].cmp(&b[col_idx]);
let cmp = if descending { cmp.reverse() } else { cmp };
if cmp != std::cmp::Ordering::Equal {
return cmp;
}
}
std::cmp::Ordering::Equal
});
Ok(QueryResult::Rows { columns, rows })
}
_ => Err("sort requires row input".into()),
}
}
PlanNode::Limit { input, count } => {
let result = self.execute_plan(input)?;
let n = match count {
Expr::Literal(Literal::Int(v)) => *v as usize,
_ => return Err("limit must be integer literal".into()),
};
match result {
QueryResult::Rows { columns, rows } => Ok(QueryResult::Rows {
columns,
rows: rows.into_iter().take(n).collect(),
}),
_ => Err("limit requires row input".into()),
}
}
PlanNode::Offset { input, count } => {
let result = self.execute_plan(input)?;
let n = match count {
Expr::Literal(Literal::Int(v)) => *v as usize,
_ => return Err("offset must be integer literal".into()),
};
match result {
QueryResult::Rows { columns, rows } => Ok(QueryResult::Rows {
columns,
rows: rows.into_iter().skip(n).collect(),
}),
_ => Err("offset requires row input".into()),
}
}
PlanNode::Aggregate {
input,
function,
field,
} => {
// Fast path: count() over SeqScan — count rows without any decode
if *function == AggFunc::Count {
if let PlanNode::SeqScan { table } = input.as_ref() {
let mut count: i64 = 0;
self.catalog
.for_each_row_raw(table, |_rid, _data| {
count += 1;
})
.map_err(|e| QueryError::StorageError(e.to_string()))?;
return Ok(QueryResult::Scalar(Value::Int(count)));
}
// Fast path: count() over Filter(SeqScan) — try compiled
// predicate first, fall back to decode_column path.
if let PlanNode::Filter {
input: inner,
predicate,
} = input.as_ref()
{
if let PlanNode::SeqScan { table } = inner.as_ref() {
let schema = self
.catalog
.schema(table)
.ok_or_else(|| QueryError::TableNotFound(table.to_string()))?
.clone();
let columns: Vec<String> =
schema.columns.iter().map(|c| c.name.clone()).collect();
let fast = FastLayout::new(&schema);
let row_layout = RowLayout::new(&schema);
// Try compiled predicate (zero-allocation hot path).
// Handles int leaves, string-eq leaves, AND conjunctions.
if let Some(compiled) =
compile_predicate(predicate, &columns, &fast, &schema)
{
let mut count: i64 = 0;
self.catalog
.for_each_row_raw(table, |_rid, data| {
if compiled(data) {
count += 1;
}
})
.map_err(|e| QueryError::StorageError(e.to_string()))?;
return Ok(QueryResult::Scalar(Value::Int(count)));
}
// Fallback: decode predicate columns
let pred_cols = predicate_column_indices(predicate, &columns);
let mut count: i64 = 0;
self.catalog
.for_each_row_raw(table, |_rid, data| {
let pred_row =
decode_selective(&schema, &row_layout, data, &pred_cols);
if eval_predicate(predicate, &pred_row, &columns) {
count += 1;
}
})
.map_err(|e| QueryError::StorageError(e.to_string()))?;
return Ok(QueryResult::Scalar(Value::Int(count)));
}
}
}
// Fast path: sum/avg/min/max over a single fixed-size int
// column with an optional compiled filter predicate. Walks
// raw row bytes, zero allocation per row.
if matches!(
function,
AggFunc::Sum
| AggFunc::Avg
| AggFunc::Min
| AggFunc::Max
| AggFunc::CountDistinct
) {
if let Some(col) = field.as_ref() {
// Shape: Aggregate(SeqScan) or Aggregate(Filter(SeqScan))
let (table_opt, pred_opt): (Option<&str>, Option<&Expr>) =
match input.as_ref() {
PlanNode::SeqScan { table } => (Some(table.as_str()), None),
PlanNode::Filter {
input: inner,
predicate,
} => {
if let PlanNode::SeqScan { table } = inner.as_ref() {
(Some(table.as_str()), Some(predicate))
} else {
(None, None)
}
}
_ => (None, None),
};
if let Some(table) = table_opt {
if let Some(result) =
self.agg_single_col_fast(table, col, *function, pred_opt)?
{
return Ok(result);
}
}
}
}
// Fast path: Project(Limit(Filter(SeqScan))) — stream, decode
// only projected columns, stop once we hit the limit.
// (Handled in the Project branch; this branch only fires when
// the aggregate is the outer node.)
let result = self.execute_plan(input)?;
match result {
QueryResult::Rows { columns, rows } => {
match function {
AggFunc::Count => {
Ok(QueryResult::Scalar(Value::Int(rows.len() as i64)))
}
AggFunc::CountDistinct => {
let col = field.as_ref().ok_or("count distinct requires field")?;
let idx = columns
.iter()
.position(|c| c == col)
.ok_or("col not found")?;
let mut seen = std::collections::HashSet::new();
for row in &rows {
let v = &row[idx];
if !v.is_empty() {
seen.insert(v.clone());
}
}
Ok(QueryResult::Scalar(Value::Int(seen.len() as i64)))
}
AggFunc::Avg => {
let col = field.as_ref().ok_or("avg requires field")?;
let idx = columns
.iter()
.position(|c| c == col)
.ok_or("col not found")?;
let sum: f64 = rows
.iter()
.filter_map(|r| match &r[idx] {
Value::Int(v) => Some(*v as f64),
Value::Float(v) => Some(*v),
_ => None,
})
.sum();
let count = rows.len() as f64;
Ok(QueryResult::Scalar(Value::Float(sum / count)))
}
AggFunc::Sum => {
let col = field.as_ref().ok_or("sum requires field")?;
let idx = columns
.iter()
.position(|c| c == col)
.ok_or("col not found")?;
// Track int and float contributions separately so
// Float columns (and mixed Int/Float rows) don't get
// silently dropped as they did in the Int-only
// version. If any Float is present, the whole sum
// promotes to Float — matching Avg's semantics.
let mut int_sum: i64 = 0;
let mut float_sum: f64 = 0.0;
let mut saw_float = false;
for r in &rows {
match &r[idx] {
Value::Int(v) => int_sum += *v,
Value::Float(v) => {
float_sum += *v;
saw_float = true;
}
_ => {}
}
}
let result = if saw_float {
Value::Float(float_sum + int_sum as f64)
} else {
Value::Int(int_sum)
};
Ok(QueryResult::Scalar(result))
}
AggFunc::Min | AggFunc::Max => {
let col = field.as_ref().ok_or("min/max requires field")?;
let idx = columns
.iter()
.position(|c| c == col)
.ok_or("col not found")?;
let vals: Vec<&Value> = rows.iter().map(|r| &r[idx]).collect();
let result = if *function == AggFunc::Min {
vals.into_iter().min().cloned()
} else {
vals.into_iter().max().cloned()
};
Ok(QueryResult::Scalar(result.unwrap_or(Value::Empty)))
}
}
}
_ => Err("aggregate requires row input".into()),
}
}
PlanNode::Insert { table, assignments } => {
let values = {
let schema = self
.catalog
.schema(table)
.ok_or_else(|| QueryError::TableNotFound(table.to_string()))?;
let mut values = vec![Value::Empty; schema.columns.len()];
for a in assignments {
let idx = schema.column_index(&a.field).ok_or_else(|| {
QueryError::ColumnNotFound {
table: String::new(),
column: a.field.clone(),
}
})?;
let raw = literal_to_value(&a.value)?;
values[idx] = coerce_value(raw, &schema.columns[idx])?;
}
for col in &schema.columns {
if col.required && matches!(values[col.position as usize], Value::Empty) {
return Err(QueryError::Execution(format!(
"column '{}' is required but no value was provided",
col.name
)));
}
}
values
};
self.catalog
.insert(table, &values)
.map_err(|e| QueryError::StorageError(e.to_string()))?;
self.view_registry.mark_dependents_dirty(table);
Ok(QueryResult::Modified(1))
}
PlanNode::Upsert {
table,
key_column,
assignments,
on_conflict,
} => {
let (values, key_idx) = {
let schema = self
.catalog
.schema(table)
.ok_or_else(|| QueryError::TableNotFound(table.to_string()))?;
let mut values = vec![Value::Empty; schema.columns.len()];
for a in assignments {
let idx = schema.column_index(&a.field).ok_or_else(|| {
QueryError::ColumnNotFound {
table: String::new(),
column: a.field.clone(),
}
})?;
let raw = literal_to_value(&a.value)?;
values[idx] = coerce_value(raw, &schema.columns[idx])?;
}
for col in &schema.columns {
if col.required && matches!(values[col.position as usize], Value::Empty) {
return Err(QueryError::Execution(format!(
"column '{}' is required but no value was provided",
col.name
)));
}
}
let key_idx = schema
.column_index(key_column)
.ok_or_else(|| format!("key column '{key_column}' not found"))?;
(values, key_idx)
};
let key_value = values[key_idx].clone();
// Probe the index for a conflict.
let existing = {
let tbl = self
.catalog
.get_table(table)
.ok_or_else(|| QueryError::TableNotFound(table.to_string()))?;
if tbl.has_index(key_column) {
// Upsert key lookup: return the first match.
// For unique indexes this is the only match.
// For non-unique indexes on a key column, also
// just the first (upsert semantics).
let rids = tbl.index_lookup_all(key_column, &key_value);
rids.into_iter().next().and_then(|rid| {
tbl.heap
.get(rid)
.map(|data| (rid, decode_row(&tbl.schema, &data)))
})
} else {
// No index — linear scan for the key.
let mut found = None;
for (rid, row) in tbl.scan() {
if row[key_idx] == key_value {
found = Some((rid, row));
break;
}
}
found
}
};
if let Some((rid, mut existing_row)) = existing {
// Conflict: apply on_conflict assignments (or all non-key if empty).
let update_assignments = if on_conflict.is_empty() {
assignments
} else {
on_conflict
};
let changed_cols: Vec<usize> = {
let schema = self
.catalog
.schema(table)
.ok_or_else(|| QueryError::TableNotFound(table.to_string()))?;
let mut indices = Vec::new();
for a in update_assignments {
let idx = schema.column_index(&a.field).ok_or_else(|| {
QueryError::ColumnNotFound {
table: String::new(),
column: a.field.clone(),
}
})?;
if idx != key_idx {
existing_row[idx] = literal_to_value(&a.value)?;
indices.push(idx);
}
}
indices
};
self.catalog
.update_hinted(table, rid, &existing_row, Some(&changed_cols))
.map_err(|e| QueryError::StorageError(e.to_string()))?;
self.view_registry.mark_dependents_dirty(table);
Ok(QueryResult::Modified(1))
} else {
// No conflict: insert.
self.catalog
.insert(table, &values)
.map_err(|e| QueryError::StorageError(e.to_string()))?;
self.view_registry.mark_dependents_dirty(table);
Ok(QueryResult::Modified(1))
}
}
PlanNode::Update {
input,
table,
assignments,
} => {
// Mission C Phase 3: resolve assignments against a borrowed
// schema, then drop the borrow before the mutation loop.
// Try literal-only path first; fall back to per-row expression
// evaluation if any assignment contains a non-literal expression
// (e.g., `age := .age + 1`).
let (col_indices, literal_vals): (Vec<usize>, Option<Vec<Value>>) = {
let schema_ref = self
.catalog
.schema(table)
.ok_or_else(|| QueryError::TableNotFound(table.to_string()))?;
let indices: Vec<usize> = assignments
.iter()
.map(|a| {
schema_ref.column_index(&a.field).ok_or_else(|| {
QueryError::ColumnNotFound {
table: String::new(),
column: a.field.clone(),
}
})
})
.collect::<Result<_, _>>()?;
let vals: Result<Vec<Value>, _> = assignments
.iter()
.map(|a| literal_to_value(&a.value))
.collect();
(indices, vals.ok())
};
let resolved_assignments: Option<Vec<(usize, Value)>> =
literal_vals.map(|vals| col_indices.iter().copied().zip(vals).collect());
// Mission C Phase 2: the hint Table::update_hinted needs to
// decide whether to read the old row for index diff.
let changed_cols: Vec<usize> = col_indices.clone();
// ── Fused scan+update for Update(Filter(SeqScan)) ────────
// Perf sprint: instead of the two-pass collect-RIDs-then-loop
// pattern (which pays one ensure_hot per matched row on the
// second pass), fuse the predicate evaluation and in-place
// byte-level mutation into a single heap walk. Same idea as
// the fused scan_delete_matching path for deletes.
if let Some(ref resolved_assignments) = resolved_assignments {
if let PlanNode::Filter {
input: inner,
predicate,
} = input.as_ref()
{
if let PlanNode::SeqScan { table: t } = inner.as_ref() {
if t == table {
let fused_result = self.try_fused_scan_update(
table,
predicate,
resolved_assignments,
&changed_cols,
);
if let Some(result) = fused_result {
return result;
}
}
}
}
}
// Collect matching RowIds in a single pass.
let matching_rids = self.collect_rids_for_mutation(input, table)?;
// ── Literal-only fast paths ─────────────────────────────
if let Some(ref resolved_assignments) = resolved_assignments {
// Mission C Phase 4: in-place byte-patch fast path. If every
// assignment targets a fixed-size non-null column AND none of
// them is indexed, we can skip decode_row / Vec<Value> /
// encode_row_into entirely and patch the row's raw bytes on
// the hot page.
let fast_patch: Option<Vec<FastPatch>> = {
let tbl = self
.catalog
.get_table(table)
.ok_or_else(|| QueryError::TableNotFound(table.to_string()))?;
let schema = &tbl.schema;
let all_fixed_nonnull = resolved_assignments.iter().all(|(idx, val)| {
is_fixed_size(schema.columns[*idx].type_id) && !val.is_empty()
});
let no_indexed = !resolved_assignments
.iter()
.any(|(idx, _)| tbl.has_indexed_col(*idx));
if all_fixed_nonnull && no_indexed {
let layout = RowLayout::new(schema);
let bitmap_size = layout.bitmap_size();
let patches: Vec<FastPatch> = resolved_assignments
.iter()
.map(|(idx, val)| {
let fixed_off = layout
.fixed_offset(*idx)
.expect("is_fixed_size already checked");
let field_off = 2 + bitmap_size + fixed_off;
let bytes: FixedBytes = match val {
Value::Int(v) => FixedBytes::I64(v.to_le_bytes()),
Value::Float(v) => FixedBytes::F64(v.to_le_bytes()),
Value::Bool(v) => FixedBytes::Bool(if *v { 1 } else { 0 }),
Value::DateTime(v) => FixedBytes::I64(v.to_le_bytes()),
Value::Uuid(v) => FixedBytes::Uuid(*v),
_ => unreachable!("all_fixed_nonnull guard lied"),
};
FastPatch {
field_off,
bitmap_byte_off: 2 + idx / 8,
bit_mask: 1u8 << (idx % 8),
bytes,
}
})
.collect();
Some(patches)
} else {
None
}
};
if let Some(patches) = fast_patch {
let mut count = 0u64;
for rid in matching_rids {
// Mission B2: WAL-log every patch so crash
// recovery replays the update. Same mutation
// closure as before — the wrapper just sandwiches
// it between a hot-page read and a WAL append.
let ok = self
.catalog
.update_row_bytes_logged(table, rid, |row| {
for p in &patches {
row[p.bitmap_byte_off] &= !p.bit_mask;
let field_bytes = p.bytes.as_slice();
row[p.field_off..p.field_off + field_bytes.len()]
.copy_from_slice(field_bytes);
}
})
.map_err(|e| QueryError::StorageError(e.to_string()))?;
if ok {
count += 1;
}
}
self.view_registry.mark_dependents_dirty(table);
return Ok(QueryResult::Modified(count));
}
// Mission C Phase 10: var-column in-place shrink fast path.
let var_fast: Option<(usize, Option<Vec<u8>>)> = {
let tbl = self
.catalog
.get_table(table)
.ok_or_else(|| QueryError::TableNotFound(table.to_string()))?;
let schema = &tbl.schema;
let is_single = resolved_assignments.len() == 1;
let is_var_col = is_single
&& !is_fixed_size(schema.columns[resolved_assignments[0].0].type_id);
let no_indexed = !resolved_assignments
.iter()
.any(|(idx, _)| tbl.has_indexed_col(*idx));
if is_single && is_var_col && no_indexed {
let (idx, val) = &resolved_assignments[0];
let bytes_opt: Option<Vec<u8>> = match val {
Value::Str(s) => Some(s.as_bytes().to_vec()),
Value::Bytes(b) => Some(b.clone()),
Value::Empty => None,
_ => {
return Err(QueryError::TypeError(format!(
"cannot assign non-var value to var column '{}'",
schema.columns[*idx].name
)))
}
};
Some((*idx, bytes_opt))
} else {
None
}
};
if let Some((col_idx, new_bytes_opt)) = var_fast {
let new_bytes_ref: Option<&[u8]> = new_bytes_opt.as_deref();
let mut count = 0u64;
let mut fallback_rids: Vec<RowId> = Vec::new();
for rid in &matching_rids {
// Mission B2: logged variant so crash recovery
// replays the shrink. On a false return (row
// would have to grow), the rid is pushed to
// `fallback_rids` and the slower `update_hinted`
// path — which is already WAL-logged — picks it up.
let ok = self
.catalog
.patch_var_col_logged(table, *rid, col_idx, new_bytes_ref)
.map_err(|e| QueryError::StorageError(e.to_string()))?;
if ok {
count += 1;
} else {
fallback_rids.push(*rid);
}
}
for rid in fallback_rids {
let mut row = match self.catalog.get(table, rid) {
Some(r) => r,
None => continue,
};
for (idx, val) in resolved_assignments.iter() {
row[*idx] = val.clone();
}
self.catalog
.update_hinted(table, rid, &row, Some(&changed_cols))
.map_err(|e| QueryError::StorageError(e.to_string()))?;
count += 1;
}
self.view_registry.mark_dependents_dirty(table);
return Ok(QueryResult::Modified(count));
}
// Generic literal path: decode row, apply literal values.
let mut count = 0u64;
for rid in matching_rids {
let mut row = match self.catalog.get(table, rid) {
Some(r) => r,
None => continue,
};
for (idx, val) in resolved_assignments.iter() {
row[*idx] = val.clone();
}
self.catalog
.update_hinted(table, rid, &row, Some(&changed_cols))
.map_err(|e| QueryError::StorageError(e.to_string()))?;
count += 1;
}
self.view_registry.mark_dependents_dirty(table);
return Ok(QueryResult::Modified(count));
} // end if let Some(resolved_assignments)
// ── Expression-based update path ────────────────────────
// At least one assignment contains a non-literal expression
// (e.g., `age := .age + 1`). Evaluate per-row.
let col_names: Vec<String> = {
let schema_ref = self
.catalog
.schema(table)
.ok_or_else(|| QueryError::TableNotFound(table.to_string()))?;
schema_ref.columns.iter().map(|c| c.name.clone()).collect()
};
let mut count = 0u64;
for rid in matching_rids {
let mut row = match self.catalog.get(table, rid) {
Some(r) => r,
None => continue,
};
for (i, asgn) in assignments.iter().enumerate() {
let val = eval_expr(&asgn.value, &row, &col_names);
row[col_indices[i]] = val;
}
self.catalog
.update_hinted(table, rid, &row, Some(&changed_cols))
.map_err(|e| QueryError::StorageError(e.to_string()))?;
count += 1;
}
self.view_registry.mark_dependents_dirty(table);
Ok(QueryResult::Modified(count))
}
PlanNode::Delete { input, table } => {
// Mission C Phase 3: no schema clone — collect_rids_for_mutation
// looks up schema internally when it needs one, and the mutation
// loop doesn't need the schema at all.
//
// Mission C Phase 12: route bulk deletes through
// `Catalog::delete_many`, which batches the btree leaf
// compaction and shares one `ensure_hot` per row between
// the index-key extraction and the slot delete. On
// `delete_by_filter` (100K fixture, ~20K matches) that
// removes ~4ms of pure `Vec::remove` memmove from the btree
// maintenance phase.
//
// Mission C Phase 16: for the common `delete where ...`
// shape (Filter(SeqScan)) — and the rarer "delete
// everything" shape (SeqScan) — skip the two-pass
// `collect_rids_for_mutation` + `delete_many` flow entirely.
// The fused `scan_delete_matching` primitive walks the
// heap exactly once, paying one `ensure_hot` per page
// instead of per-row. That closes the last major gap on
// the bench's `delete_by_filter` workload.
if let PlanNode::Filter {
input: inner,
predicate,
} = input.as_ref()
{
if let PlanNode::SeqScan { table: t } = inner.as_ref() {
if t == table {
let schema = self
.catalog
.schema(table)
.ok_or_else(|| QueryError::TableNotFound(table.to_string()))?;
let columns: Vec<String> =
schema.columns.iter().map(|c| c.name.clone()).collect();
let fast = FastLayout::new(schema);
if let Some(compiled) =
compile_predicate(predicate, &columns, &fast, schema)
{
// Mission B2: logged variant so every
// matched rid hits the WAL during the
// single-pass scan. Structure of the
// fused scan is unchanged — only the
// hook closure now also appends.
let count = self
.catalog
.scan_delete_matching_logged(table, |data| compiled(data))
.map_err(|e| QueryError::StorageError(e.to_string()))?;
self.view_registry.mark_dependents_dirty(table);
return Ok(QueryResult::Modified(count));
}
}
}
} else if let PlanNode::SeqScan { table: t } = input.as_ref() {
if t == table {
// `delete from T` with no predicate — every live
// row matches. One pass is still the right shape.
// Mission B2: logged variant — see above.
let count = self
.catalog
.scan_delete_matching_logged(table, |_| true)
.map_err(|e| QueryError::StorageError(e.to_string()))?;
self.view_registry.mark_dependents_dirty(table);
return Ok(QueryResult::Modified(count));
}
}
let matching_rids = self.collect_rids_for_mutation(input, table)?;
let count = self
.catalog
.delete_many(table, &matching_rids)
.map_err(|e| QueryError::StorageError(e.to_string()))?;
self.view_registry.mark_dependents_dirty(table);
Ok(QueryResult::Modified(count))
}
PlanNode::AliasScan { table, alias } => {
// Mission E1.2: scan `table` and rename every output column
// to `alias.field`. Used as a join leaf so downstream
// NestedLoopJoin + Filter + Project nodes can resolve
// `Expr::QualifiedField` lookups by direct column-name match.
//
// We don't bother with a fused zero-copy loop here yet — the
// whole join path is nested-loop and correctness-first
// (Phase E1.3 will introduce hash join and at that point we
// can revisit whether to specialise AliasScan).
let schema = self
.catalog
.schema(table)
.ok_or_else(|| QueryError::TableNotFound(table.to_string()))?
.clone();
let columns: Vec<String> = schema
.columns
.iter()
.map(|c| format!("{alias}.{}", c.name))
.collect();
let rows: Vec<Vec<Value>> = self
.catalog
.scan(table)
.map_err(|e| QueryError::StorageError(e.to_string()))?
.map(|(_, row)| row)
.collect();
Ok(QueryResult::Rows { columns, rows })
}
PlanNode::NestedLoopJoin {
left,
right,
on,
kind,
} => {
// Materialise both sides. The executor ships two strategies:
// 1. Hash join (E1.3) — when the `on` predicate is a
// simple equi-predicate `left_col = right_col`, build a
// FxHashMap<Value, Vec<row_idx>> over the right side
// and probe with the left side. O(L + R) instead of
// O(L × R). Handles Inner and LeftOuter.
// 2. Nested loop (E1.2) — fallback for Cross, non-equi
// predicates, or `on` expressions that reference
// either side with something more complex than a
// QualifiedField.
let left_result = self.execute_plan(left)?;
let right_result = self.execute_plan(right)?;
let (left_columns, left_rows) = match left_result {
QueryResult::Rows { columns, rows } => (columns, rows),
_ => return Err("join left side must produce rows".into()),
};
let (right_columns, right_rows) = match right_result {
QueryResult::Rows { columns, rows } => (columns, rows),
_ => return Err("join right side must produce rows".into()),
};
// Hash-join fast path.
if !matches!(kind, JoinKind::Cross) {
if let Some(pred) = on {
if let Some((l_idx, r_idx)) =
try_extract_equi_join_keys(pred, &left_columns, &right_columns)
{
let result = hash_join(
left_columns,
left_rows,
right_columns,
right_rows,
l_idx,
r_idx,
*kind,
);
if let QueryResult::Rows { ref rows, .. } = result {
check_join_limit(rows.len())?;
}
return Ok(result);
}
}
}
// Nested-loop fallback.
let n_left = left_columns.len();
let n_right = right_columns.len();
let mut columns = Vec::with_capacity(n_left + n_right);
columns.extend(left_columns);
columns.extend(right_columns);
let mut rows: Vec<Vec<Value>> = Vec::with_capacity(left_rows.len());
let mut combined: Vec<Value> = Vec::with_capacity(n_left + n_right);
for left_row in &left_rows {
let mut matched = false;
for right_row in &right_rows {
combined.clear();
combined.extend_from_slice(left_row);
combined.extend_from_slice(right_row);
let keep = match kind {
JoinKind::Cross => true,
JoinKind::Inner | JoinKind::LeftOuter => match on {
Some(pred) => eval_predicate(pred, &combined, &columns),
// Missing `on` for non-cross joins is a
// parser error, but if it slips through we
// treat it as "match everything".
None => true,
},
// RightOuter is rewritten to LeftOuter by the
// planner, so we never see it here.
JoinKind::RightOuter => {
unreachable!("planner rewrites RightOuter to LeftOuter")
}
};
if keep {
rows.push(combined.clone());
check_join_limit(rows.len())?;
matched = true;
}
}
if !matched && matches!(kind, JoinKind::LeftOuter) {
let mut row = Vec::with_capacity(n_left + n_right);
row.extend_from_slice(left_row);
row.resize(n_left + n_right, Value::Empty);
rows.push(row);
check_join_limit(rows.len())?;
}
}
Ok(QueryResult::Rows { columns, rows })
}
PlanNode::Distinct { input } => {
let result = self.execute_plan(input)?;
match result {
QueryResult::Rows { columns, rows } => {
let mut seen = std::collections::HashSet::new();
let mut unique_rows = Vec::new();
for row in rows {
if seen.insert(row.clone()) {
unique_rows.push(row);
}
}
Ok(QueryResult::Rows {
columns,
rows: unique_rows,
})
}
other => Ok(other),
}
}
PlanNode::GroupBy {
input,
keys,
aggregates,
having,
} => {
let result = self.execute_plan(input)?;
match result {
QueryResult::Rows { columns, rows } => {
// Resolve key column indices.
let key_indices: Vec<usize> = keys
.iter()
.map(|k| {
columns
.iter()
.position(|c| c == k)
.ok_or_else(|| format!("group-by column '{k}' not found"))
})
.collect::<Result<Vec<_>, _>>()?;
// Resolve aggregate field indices. count(*) uses
// sentinel usize::MAX — compute_group_aggregate
// treats it as "count all rows in the group".
let agg_field_indices: Vec<usize> = aggregates
.iter()
.map(|a| {
if a.field == "*" {
Ok(usize::MAX)
} else {
columns.iter().position(|c| c == &a.field).ok_or_else(|| {
format!("aggregate column '{}' not found", a.field)
})
}
})
.collect::<Result<Vec<_>, _>>()?;
// Group rows by key values (preserving insertion order).
let mut group_map: rustc_hash::FxHashMap<Vec<Value>, usize> =
rustc_hash::FxHashMap::default();
let mut groups: Vec<(Vec<Value>, Vec<usize>)> = Vec::new();
for (ri, row) in rows.iter().enumerate() {
let key: Vec<Value> =
key_indices.iter().map(|&i| row[i].clone()).collect();
match group_map.get(&key) {
Some(&idx) => groups[idx].1.push(ri),
None => {
let idx = groups.len();
group_map.insert(key.clone(), idx);
groups.push((key, vec![ri]));
}
}
}
// Build output column names: keys ++ aggregate output names.
let mut out_columns: Vec<String> = keys.clone();
for agg in aggregates.iter() {
out_columns.push(agg.output_name.clone());
}
// Compute aggregates per group.
let mut out_rows: Vec<Vec<Value>> = Vec::with_capacity(groups.len());
for (key_vals, row_indices) in &groups {
let mut row = key_vals.clone();
for (ai, agg) in aggregates.iter().enumerate() {
let col_idx = agg_field_indices[ai];
let val = compute_group_aggregate(
agg.function,
&rows,
row_indices,
col_idx,
);
row.push(val);
}
out_rows.push(row);
}
// Apply HAVING filter.
if let Some(having_expr) = having {
out_rows.retain(|row| eval_predicate(having_expr, row, &out_columns));
}
Ok(QueryResult::Rows {
columns: out_columns,
rows: out_rows,
})
}
_ => Err("group by requires row input".into()),
}
}
PlanNode::CreateTable { name, fields } => {
let columns: Vec<ColumnDef> = fields
.iter()
.enumerate()
.map(
|(i, (fname, tname, req))| -> Result<ColumnDef, QueryError> {
Ok(ColumnDef {
name: fname.clone(),
type_id: type_name_to_id(tname).map_err(QueryError::TypeError)?,
required: *req,
position: i as u16,
})
},
)
.collect::<Result<Vec<_>, _>>()?;
let schema = Schema {
table_name: name.clone(),
columns,
};
self.catalog
.create_table(schema)
.map_err(|e| QueryError::StorageError(e.to_string()))?;
Ok(QueryResult::Created(name.clone()))
}
PlanNode::AlterTable { table, action } => match action {
AlterAction::AddColumn {
name,
type_name,
required,
} => {
let position = self
.catalog
.schema(table)
.ok_or_else(|| QueryError::TableNotFound(table.to_string()))?
.columns
.len() as u16;
let col = ColumnDef {
name: name.clone(),
type_id: type_name_to_id(type_name).map_err(QueryError::TypeError)?,
required: *required,
position,
};
self.catalog
.alter_table_add_column(table, col)
.map_err(|e| QueryError::StorageError(e.to_string()))?;
Ok(QueryResult::Executed {
message: format!("column '{name}' added to '{table}'"),
})
}
AlterAction::DropColumn { name } => {
self.catalog
.alter_table_drop_column(table, name)
.map_err(|e| QueryError::StorageError(e.to_string()))?;
Ok(QueryResult::Executed {
message: format!("column '{name}' dropped from '{table}'"),
})
}
AlterAction::AddIndex { column } => {
self.catalog
.create_index(table, column)
.map_err(|e| QueryError::StorageError(e.to_string()))?;
Ok(QueryResult::Executed {
message: format!("index on '{table}.{column}' created"),
})
}
},
PlanNode::DropTable { name } => {
self.catalog
.drop_table(name)
.map_err(|e| QueryError::StorageError(e.to_string()))?;
Ok(QueryResult::Executed {
message: format!("table '{name}' dropped"),
})
}
PlanNode::CreateView { name, query_text } => {
self.create_view(name, query_text)?;
Ok(QueryResult::Executed {
message: format!("materialized view '{name}' created"),
})
}
PlanNode::RefreshView { name } => {
self.refresh_view(name)?;
Ok(QueryResult::Executed {
message: format!("materialized view '{name}' refreshed"),
})
}
PlanNode::DropView { name } => {
self.drop_view(name)?;
Ok(QueryResult::Executed {
message: format!("materialized view '{name}' dropped"),
})
}
PlanNode::Window { input, windows } => {
let result = self.execute_plan(input)?;
execute_window(result, windows)
}
PlanNode::Union { left, right, all } => {
let left_result = self.execute_plan(left)?;
let right_result = self.execute_plan(right)?;
let (left_cols, left_rows) = match left_result {
QueryResult::Rows { columns, rows } => (columns, rows),
_ => return Err("UNION requires query results on left side".into()),
};
let (_, right_rows) = match right_result {
QueryResult::Rows { columns, rows } => (columns, rows),
_ => return Err("UNION requires query results on right side".into()),
};
let mut combined = left_rows;
if *all {
// UNION ALL — just concatenate.
combined.extend(right_rows);
} else {
// UNION — deduplicate using the same HashSet approach
// as DISTINCT. Value already implements Hash + Eq.
let mut seen = std::collections::HashSet::new();
for row in &combined {
seen.insert(row.clone());
}
for row in right_rows {
if seen.insert(row.clone()) {
combined.push(row);
}
}
}
Ok(QueryResult::Rows {
columns: left_cols,
rows: combined,
})
}
PlanNode::Explain { input } => {
let text = format_plan_tree(input, 0);
Ok(QueryResult::Rows {
columns: vec!["plan".to_string()],
rows: text
.lines()
.map(|line| vec![Value::Str(line.to_string())])
.collect(),
})
}
PlanNode::Begin => {
if self.in_transaction {
return Err(QueryError::Execution(
"already in a transaction (nested transactions not supported)".into(),
));
}
self.in_transaction = true;
Ok(QueryResult::Executed {
message: "transaction started".to_string(),
})
}
PlanNode::Commit => {
if !self.in_transaction {
return Err(QueryError::Execution(
"no active transaction to commit".into(),
));
}
self.in_transaction = false;
self.catalog
.sync_wal()
.map_err(|e| QueryError::StorageError(e.to_string()))?;
Ok(QueryResult::Executed {
message: "transaction committed".to_string(),
})
}
PlanNode::Rollback => {
if !self.in_transaction {
return Err(QueryError::Execution(
"no active transaction to roll back".into(),
));
}
self.in_transaction = false;
self.catalog
.rollback_to_last_sync()
.map_err(|e| QueryError::StorageError(e.to_string()))?;
if let Ok(mut cache) = self.plan_cache.lock() {
cache.clear();
}
self.view_registry = ViewRegistry::open(self.catalog.data_dir())
.unwrap_or_else(|_| ViewRegistry::new(self.catalog.data_dir()));
Ok(QueryResult::Executed {
message: "transaction rolled back".to_string(),
})
}
PlanNode::IndexScan { table, column, key } => {
let key_value = literal_to_value(key)?;
let tbl = self
.catalog
.get_table(table)
.ok_or_else(|| QueryError::TableNotFound(table.to_string()))?;
let columns: Vec<String> =
tbl.schema.columns.iter().map(|c| c.name.clone()).collect();
// Fast path: the table has a B-tree on this column.
// Uses index_lookup_all to return ALL matching rows for
// both unique and non-unique indexes.
if tbl.has_index(column) {
let rids = tbl.index_lookup_all(column, &key_value);
let mut rows: Vec<Vec<Value>> = Vec::with_capacity(rids.len());
for rid in rids {
if let Some(data) = tbl.heap.get(rid) {
rows.push(decode_row(&tbl.schema, &data));
}
}
return Ok(QueryResult::Rows { columns, rows });
}
// Fallback: no index on this column. The planner emits IndexScan
// eagerly (it has no visibility into which columns are indexed
// at plan time), so here we must behave like SeqScan+Filter on
// `.col = literal`: return *all* matching rows, not just the
// first one. A non-indexed column isn't necessarily unique.
// We compile the eq predicate once and stream without any
// per-row decode for non-matching rows.
let schema = &tbl.schema;
let fast = FastLayout::new(schema);
let synth_pred = Expr::BinaryOp(
Box::new(Expr::Field(column.clone())),
BinOp::Eq,
Box::new(key.clone()),
);
if let Some(compiled) = compile_predicate(&synth_pred, &columns, &fast, schema) {
// Mission F: skip the first 4 Vec doublings.
let mut rows: Vec<Vec<Value>> = Vec::with_capacity(64);
self.catalog
.for_each_row_raw(table, |_rid, data| {
if compiled(data) {
rows.push(decode_row(schema, data));
}
})
.map_err(|e| QueryError::StorageError(e.to_string()))?;
return Ok(QueryResult::Rows { columns, rows });
}
// Last resort: slow eq-check on materialised rows.
let col_idx =
schema
.column_index(column)
.ok_or_else(|| QueryError::ColumnNotFound {
table: String::new(),
column: column.clone(),
})?;
let rows: Vec<Vec<Value>> = tbl
.scan()
.filter_map(|(_, row)| {
if row[col_idx] == key_value {
Some(row)
} else {
None
}
})
.collect();
Ok(QueryResult::Rows { columns, rows })
}
PlanNode::RangeScan {
table,
column,
start,
end,
} => {
let tbl = self
.catalog
.get_table(table)
.ok_or_else(|| QueryError::TableNotFound(table.to_string()))?;
let columns: Vec<String> =
tbl.schema.columns.iter().map(|c| c.name.clone()).collect();
let schema = &tbl.schema;
let start_val = match start {
Some((expr, _)) => Some(literal_to_value(expr)?),
None => None,
};
let end_val = match end {
Some((expr, _)) => Some(literal_to_value(expr)?),
None => None,
};
let start_inclusive = start.as_ref().map(|(_, inc)| *inc).unwrap_or(true);
let end_inclusive = end.as_ref().map(|(_, inc)| *inc).unwrap_or(true);
// Range scans only use the btree fast path for unique indexes,
// because non-unique indexes store composite keys (column_value
// + RowId) that don't directly compare against raw column values.
if tbl.is_index_unique(column) == Some(true) {
if let Some(btree) = tbl.index(column) {
let hits: Vec<(Value, RowId)> = match (&start_val, &end_val) {
(Some(s), Some(e)) => btree.range(s, e).collect(),
(Some(s), None) => btree.range_from(s),
(None, Some(e)) => btree.range_to(e),
(None, None) => {
let rows: Vec<Vec<Value>> =
tbl.scan().map(|(_, row)| row).collect();
return Ok(QueryResult::Rows { columns, rows });
}
};
let mut rows: Vec<Vec<Value>> = Vec::with_capacity(hits.len());
for (key, rid) in hits {
if !start_inclusive {
if let Some(ref s) = start_val {
if &key == s {
continue;
}
}
}
if !end_inclusive {
if let Some(ref e) = end_val {
if &key == e {
continue;
}
}
}
if let Some(data) = tbl.heap.get(rid) {
rows.push(decode_row(schema, &data));
}
}
return Ok(QueryResult::Rows { columns, rows });
}
}
// Fallback: no index — synthesize range predicate and scan.
let fast = FastLayout::new(schema);
let synth = synthesize_range_predicate(column, start, end);
if let Some(compiled) = compile_predicate(&synth, &columns, &fast, schema) {
let mut rows: Vec<Vec<Value>> = Vec::with_capacity(64);
self.catalog
.for_each_row_raw(table, |_rid, data| {
if compiled(data) {
rows.push(decode_row(schema, data));
}
})
.map_err(|e| QueryError::StorageError(e.to_string()))?;
return Ok(QueryResult::Rows { columns, rows });
}
let col_idx =
schema
.column_index(column)
.ok_or_else(|| QueryError::ColumnNotFound {
table: String::new(),
column: column.clone(),
})?;
let rows: Vec<Vec<Value>> = tbl
.scan()
.filter(|(_, row)| {
range_matches(
&row[col_idx],
&start_val,
start_inclusive,
&end_val,
end_inclusive,
)
})
.map(|(_, row)| row)
.collect();
Ok(QueryResult::Rows { columns, rows })
}
}
}
// ─── Materialized view operations ──────────────────────────────────────
/// Create a materialized view: execute the source query, store results
/// in a new backing table, and register the view.
fn create_view(&mut self, name: &str, query_text: &str) -> Result<(), QueryError> {
if self.view_registry.is_view(name) {
return Err(QueryError::ViewError(format!(
"materialized view '{name}' already exists"
)));
}
// Execute the source query to get the result set.
let result = self.execute_powql(query_text)?;
let (columns, rows) = match result {
QueryResult::Rows { columns, rows } => (columns, rows),
_ => return Err("view source query must be a SELECT".into()),
};
// Derive a schema for the backing table from the query result columns.
let schema = self.derive_view_schema(name, &columns, &rows);
// Create the backing table and insert the result rows.
self.catalog
.create_table(schema)
.map_err(|e| QueryError::StorageError(e.to_string()))?;
for row in &rows {
self.catalog
.insert(name, row)
.map_err(|e| QueryError::StorageError(e.to_string()))?;
}
// Determine which base tables this view depends on by parsing the query.
let depends_on = self.extract_view_deps(query_text);
self.view_registry
.register(ViewDef {
name: name.to_string(),
query: query_text.to_string(),
depends_on,
dirty: false,
})
.map_err(|e| QueryError::StorageError(e.to_string()))?;
Ok(())
}
/// Refresh a materialized view: re-execute its source query and replace
/// the backing table's contents.
fn refresh_view(&mut self, name: &str) -> Result<(), QueryError> {
let def = self
.view_registry
.get(name)
.ok_or_else(|| format!("materialized view '{name}' not found"))?;
let query_text = def.query.clone();
// Execute the source query.
let result = self.execute_powql(&query_text)?;
let (_columns, rows) = match result {
QueryResult::Rows { columns, rows } => (columns, rows),
_ => return Err("view source query must be a SELECT".into()),
};
// Clear old data and insert fresh results. Mission B2: logged
// variant — view refreshes are a mutation and crash recovery
// must see them.
self.catalog
.scan_delete_matching_logged(name, |_| true)
.map_err(|e| QueryError::StorageError(e.to_string()))?;
for row in &rows {
self.catalog
.insert(name, row)
.map_err(|e| QueryError::StorageError(e.to_string()))?;
}
self.view_registry.mark_clean(name);
Ok(())
}
/// Drop a materialized view: remove the backing table and unregister.
fn drop_view(&mut self, name: &str) -> Result<(), QueryError> {
if !self.view_registry.is_view(name) {
return Err(QueryError::ViewError(format!(
"materialized view '{name}' not found"
)));
}
self.view_registry
.unregister(name)
.map_err(|e| QueryError::StorageError(e.to_string()))?;
self.catalog
.drop_table(name)
.map_err(|e| QueryError::StorageError(e.to_string()))?;
Ok(())
}
/// Derive a storage `Schema` for a view's backing table from query
/// result column names and the first row's types.
fn derive_view_schema(&self, name: &str, columns: &[String], rows: &[Vec<Value>]) -> Schema {
use powdb_storage::types::{ColumnDef, TypeId};
let cols: Vec<ColumnDef> = columns
.iter()
.enumerate()
.map(|(i, col_name)| {
let type_id = rows
.first()
.and_then(|row| row.get(i))
.map(|v| v.type_id())
.unwrap_or(TypeId::Str);
ColumnDef {
name: col_name.clone(),
type_id,
required: false,
position: i as u16,
}
})
.collect();
Schema {
table_name: name.to_string(),
columns: cols,
}
}
/// Extract base table dependencies from a view's source query by
/// parsing it and collecting the source table name.
fn extract_view_deps(&self, query_text: &str) -> Vec<String> {
use crate::parser::parse;
match parse(query_text) {
Ok(Statement::Query(q)) => {
let mut deps = vec![q.source.clone()];
for j in &q.joins {
deps.push(j.source.clone());
}
deps
}
_ => Vec::new(),
}
}
// ─── Specialized fast paths ─────────────────────────────────────────────
//
// These methods are helpers for the `execute_plan` match arms above.
// Each returns `Ok(Some(result))` when the fast path fires, `Ok(None)`
// when the shape isn't supported (caller falls back to generic code).
/// Aggregate sum/avg/min/max over a single fixed-size i64 column, with
/// an optional compiled filter predicate. Walks raw row bytes — zero
/// per-row allocation. Uses i128 accumulator for sum/avg overflow safety.
pub(super) fn agg_single_col_fast(
&self,
table: &str,
col: &str,
function: AggFunc,
predicate: Option<&Expr>,
) -> Result<Option<QueryResult>, QueryError> {
let schema = self
.catalog
.schema(table)
.ok_or_else(|| QueryError::TableNotFound(table.to_string()))?
.clone();
let columns: Vec<String> = schema.columns.iter().map(|c| c.name.clone()).collect();
let col_idx = match schema.column_index(col) {
Some(i) => i,
None => return Ok(None),
};
// Only fast-path fixed-size numeric columns (Int/Float) for
// sum/avg/min/max/count. Mission D10: Float parity — prior version
// bailed on Float columns, forcing them through the generic row-
// decoding path that allocated a Vec<Value> per row and dispatched
// on Value::cmp for every compare. f64 decode is structurally the
// same as i64 (load 8 bytes, cast), so the fast path handles both.
let col_type = schema.columns[col_idx].type_id;
if col_type != TypeId::Int && col_type != TypeId::Float {
return Ok(None);
}
let fast = FastLayout::new(&schema);
// Mission C Phase 20b: inline the numeric-column reader instead of
// building a `Box<dyn Fn>`. Eliminates 100K vtable dispatches per
// 100K-row agg scan — every reader call folds directly into the
// hot loop below.
let byte_offset = match fast.fixed_offsets[col_idx] {
Some(o) => o,
None => return Ok(None),
};
let bitmap_byte = col_idx / 8;
let bitmap_bit = (col_idx % 8) as u32;
let data_offset = 2 + fast.bitmap_size + byte_offset;
// Optional compiled filter.
let compiled_pred: Option<CompiledPredicate> = match predicate {
Some(pred) => match compile_predicate(pred, &columns, &fast, &schema) {
Some(c) => Some(c),
None => return Ok(None), // let generic path handle it
},
None => None,
};
// Mission C Phase 20b: specialize the inner loop per aggregate
// function. The previous version ran a `match function { ... }`
// *inside* the closure, which kept LLVM from producing optimal
// scalar code for each variant (agg_max regressed ~23% vs the
// baseline Box<dyn Fn> version even though per-row vtable cost
// should have been strictly lower). Pushing the match out of the
// hot loop lets each specialized body fold cleanly into
// `for_each_row_raw` and removes a captured `AggFunc` + match
// dispatch per row.
//
// Mission D10: same specialisation applies to the Float branch.
// For Min/Max we use `f64::total_cmp` so the result matches
// `Value::Ord` — this is the same ordering ORDER BY and the
// top-N sort fast path use, keeping semantics consistent across
// read paths (NaN compares as greatest, -0.0 < +0.0 for
// deterministic tie-breaking).
//
// Mission D11 Phase 1: each inner loop now splits on presence of
// a predicate (`if let Some(pred) = &compiled_pred`) so the hot
// body never re-tests `Option` per row, and reads column bytes
// via `read_i64_unchecked` / `read_f64_unchecked` helpers that
// drop two bounds checks per row (null bitmap byte + value
// slice). Safety is carried by the `FastLayout` invariant that
// `data_offset + 8 <= row_len` for any fixed-size column; see
// the helper doc comments. Hot loops are macro-generated so the
// with-pred / no-pred split can't drift between variants.
let result = match col_type {
TypeId::Int => match function {
AggFunc::Sum | AggFunc::Avg => {
let mut sum_i128: i128 = 0;
let mut count: i64 = 0;
agg_int_loop!(
self,
table,
compiled_pred,
bitmap_byte,
bitmap_bit,
data_offset,
|v: i64| {
count += 1;
sum_i128 += v as i128;
}
);
if matches!(function, AggFunc::Sum) {
let clamped = sum_i128.clamp(i64::MIN as i128, i64::MAX as i128) as i64;
QueryResult::Scalar(Value::Int(clamped))
} else if count == 0 {
QueryResult::Scalar(Value::Empty)
} else {
let avg = (sum_i128 as f64) / (count as f64);
QueryResult::Scalar(Value::Float(avg))
}
}
AggFunc::Min => {
let mut min_v: Option<i64> = None;
agg_int_loop!(
self,
table,
compiled_pred,
bitmap_byte,
bitmap_bit,
data_offset,
|v: i64| {
min_v = Some(match min_v {
Some(m) => m.min(v),
None => v,
});
}
);
QueryResult::Scalar(min_v.map(Value::Int).unwrap_or(Value::Empty))
}
AggFunc::Max => {
let mut max_v: Option<i64> = None;
agg_int_loop!(
self,
table,
compiled_pred,
bitmap_byte,
bitmap_bit,
data_offset,
|v: i64| {
max_v = Some(match max_v {
Some(m) => m.max(v),
None => v,
});
}
);
QueryResult::Scalar(max_v.map(Value::Int).unwrap_or(Value::Empty))
}
AggFunc::Count => {
let mut count: i64 = 0;
agg_int_loop!(
self,
table,
compiled_pred,
bitmap_byte,
bitmap_bit,
data_offset,
|_v: i64| {
count += 1;
}
);
QueryResult::Scalar(Value::Int(count))
}
AggFunc::CountDistinct => {
let mut seen = rustc_hash::FxHashSet::default();
agg_int_loop!(
self,
table,
compiled_pred,
bitmap_byte,
bitmap_bit,
data_offset,
|v: i64| {
seen.insert(v);
}
);
QueryResult::Scalar(Value::Int(seen.len() as i64))
}
},
TypeId::Float => match function {
AggFunc::Sum => {
// Use a single f64 accumulator. Naive summation is
// sufficient for MVP parity; if precision becomes an
// issue on long scans we can upgrade to Kahan–Neumaier
// compensated sum (~2x scalar cost, zero error growth).
let mut sum: f64 = 0.0;
agg_float_loop!(
self,
table,
compiled_pred,
bitmap_byte,
bitmap_bit,
data_offset,
|v: f64| {
sum += v;
}
);
QueryResult::Scalar(Value::Float(sum))
}
AggFunc::Avg => {
let mut sum: f64 = 0.0;
let mut count: i64 = 0;
agg_float_loop!(
self,
table,
compiled_pred,
bitmap_byte,
bitmap_bit,
data_offset,
|v: f64| {
sum += v;
count += 1;
}
);
if count == 0 {
QueryResult::Scalar(Value::Empty)
} else {
QueryResult::Scalar(Value::Float(sum / count as f64))
}
}
AggFunc::Min => {
// `total_cmp` for deterministic NaN handling (matches
// Value::Ord). NaN compares greatest, so Min will
// correctly ignore it in favour of any finite value.
let mut min_v: Option<f64> = None;
agg_float_loop!(
self,
table,
compiled_pred,
bitmap_byte,
bitmap_bit,
data_offset,
|v: f64| {
min_v = Some(match min_v {
Some(m) => {
if v.total_cmp(&m).is_lt() {
v
} else {
m
}
}
None => v,
});
}
);
QueryResult::Scalar(min_v.map(Value::Float).unwrap_or(Value::Empty))
}
AggFunc::Max => {
let mut max_v: Option<f64> = None;
agg_float_loop!(
self,
table,
compiled_pred,
bitmap_byte,
bitmap_bit,
data_offset,
|v: f64| {
max_v = Some(match max_v {
Some(m) => {
if v.total_cmp(&m).is_gt() {
v
} else {
m
}
}
None => v,
});
}
);
QueryResult::Scalar(max_v.map(Value::Float).unwrap_or(Value::Empty))
}
AggFunc::Count => {
let mut count: i64 = 0;
agg_float_loop!(
self,
table,
compiled_pred,
bitmap_byte,
bitmap_bit,
data_offset,
|_v: f64| {
count += 1;
}
);
QueryResult::Scalar(Value::Int(count))
}
AggFunc::CountDistinct => {
// Hash on `f64::to_bits` — matches `Value::Hash`, so
// distinct NaN bit patterns count as distinct and
// -0.0/+0.0 count as distinct. Consistent with how
// Float values are hashed in every other DISTINCT /
// GROUP BY path.
let mut seen = rustc_hash::FxHashSet::default();
agg_float_loop!(
self,
table,
compiled_pred,
bitmap_byte,
bitmap_bit,
data_offset,
|v: f64| {
seen.insert(v.to_bits());
}
);
QueryResult::Scalar(Value::Int(seen.len() as i64))
}
},
_ => unreachable!("type guard above restricts to Int/Float"),
};
Ok(Some(result))
}
/// `Project(Limit(Filter(SeqScan)))` and `Project(Limit(SeqScan))`.
/// Streams rows, decodes only projected columns, stops at the limit.
pub(super) fn project_filter_limit_fast(
&self,
table: &str,
fields: &[ProjectField],
limit: usize,
predicate: Option<&Expr>,
) -> Result<Option<QueryResult>, QueryError> {
let schema = self
.catalog
.schema(table)
.ok_or_else(|| QueryError::TableNotFound(table.to_string()))?
.clone();
let all_columns: Vec<String> = schema.columns.iter().map(|c| c.name.clone()).collect();
// Each projection field must be a simple `.field` reference for this
// fast path. Aliased or computed fields fall through.
let mut proj_indices: Vec<usize> = Vec::with_capacity(fields.len());
let mut proj_columns: Vec<String> = Vec::with_capacity(fields.len());
for f in fields {
let name = match &f.expr {
Expr::Field(n) => n.clone(),
_ => return Ok(None),
};
let idx = match all_columns.iter().position(|c| c == &name) {
Some(i) => i,
None => return Ok(None),
};
proj_indices.push(idx);
proj_columns.push(f.alias.clone().unwrap_or(name));
}
let fast = FastLayout::new(&schema);
let row_layout = RowLayout::new(&schema);
let compiled_pred: Option<CompiledPredicate> = match predicate {
Some(pred) => match compile_predicate(pred, &all_columns, &fast, &schema) {
Some(c) => Some(c),
None => return Ok(None),
},
None => None,
};
let mut out: Vec<Vec<Value>> = Vec::with_capacity(limit.min(1024));
// Mission D2: use try_for_each_row_raw to actually stop iterating
// once the limit is reached. The previous `done` flag only short-
// circuited the closure body, so a `limit 100` over 100K rows still
// walked all 100K slots — burning ~30x SQLite on scan_filter_project_top100.
self.catalog
.try_for_each_row_raw(table, |_rid, data| {
use std::ops::ControlFlow;
if let Some(ref pred) = compiled_pred {
if !pred(data) {
return ControlFlow::Continue(());
}
}
let row: Vec<Value> = proj_indices
.iter()
.map(|&ci| decode_column(&schema, &row_layout, data, ci))
.collect();
out.push(row);
if out.len() >= limit {
ControlFlow::Break(())
} else {
ControlFlow::Continue(())
}
})
.map_err(|e| QueryError::StorageError(e.to_string()))?;
Ok(Some(QueryResult::Rows {
columns: proj_columns,
rows: out,
}))
}
/// `Project(Limit(Sort(Filter(SeqScan))))` and `Project(Limit(Sort(SeqScan)))`.
/// Bounded top-N heap over the sort key. Only the sort key needs to be
/// read per row; projected columns are decoded only for the final
/// winning rows when the heap drains.
pub(super) fn project_filter_sort_limit_fast(
&self,
table: &str,
fields: &[ProjectField],
sort_field: &str,
descending: bool,
limit: usize,
predicate: Option<&Expr>,
) -> Result<Option<QueryResult>, QueryError> {
if limit == 0 {
// Degenerate case — empty result. Let the generic path handle it
// for proper column naming.
return Ok(None);
}
let schema = self
.catalog
.schema(table)
.ok_or_else(|| QueryError::TableNotFound(table.to_string()))?
.clone();
let all_columns: Vec<String> = schema.columns.iter().map(|c| c.name.clone()).collect();
// Sort key must be a fixed-size numeric column (Int or Float).
// Mission D10: extended from Int-only. Float sort keys use a
// sortable-u64 transform (see `f64_to_sortable_u64`) so the heap
// path stays keyed on `u64` and the whole branch shape is
// identical to the Int case — no new heap types, no `total_cmp`
// closures in the hot loop.
let sort_idx = match schema.column_index(sort_field) {
Some(i) => i,
None => return Ok(None),
};
let sort_col_type = schema.columns[sort_idx].type_id;
if sort_col_type != TypeId::Int && sort_col_type != TypeId::Float {
return Ok(None);
}
// Each projection field must be a simple `.field`.
let mut proj_indices: Vec<usize> = Vec::with_capacity(fields.len());
let mut proj_columns: Vec<String> = Vec::with_capacity(fields.len());
for f in fields {
let name = match &f.expr {
Expr::Field(n) => n.clone(),
_ => return Ok(None),
};
let idx = match all_columns.iter().position(|c| c == &name) {
Some(i) => i,
None => return Ok(None),
};
proj_indices.push(idx);
proj_columns.push(f.alias.clone().unwrap_or(name));
}
let fast = FastLayout::new(&schema);
let row_layout = RowLayout::new(&schema);
// Mission C Phase 20b: inline numeric-column reader (no Box<dyn Fn>).
let sort_byte_offset = match fast.fixed_offsets[sort_idx] {
Some(o) => o,
None => return Ok(None),
};
let sort_bitmap_byte = sort_idx / 8;
let sort_bitmap_bit = (sort_idx % 8) as u32;
let sort_data_offset = 2 + fast.bitmap_size + sort_byte_offset;
let compiled_pred: Option<CompiledPredicate> = match predicate {
Some(pred) => match compile_predicate(pred, &all_columns, &fast, &schema) {
Some(c) => Some(c),
None => return Ok(None),
},
None => None,
};
// Bounded top-N heap. For `order .x desc limit N`, we want the N
// largest values — use a min-heap so the smallest is at the top and
// can be popped when a better candidate arrives. For ascending, use
// a max-heap. We tie-break with a monotonic `seq` counter so the
// result is deterministic and stable.
//
// To keep this simple we maintain two typed heaps and pick by
// direction.
let drained: Vec<Vec<u8>> = match sort_col_type {
TypeId::Int => {
let mut seq: u64 = 0;
let mut heap_desc: BinaryHeap<Reverse<(i64, u64, Vec<u8>)>> =
BinaryHeap::with_capacity(limit);
let mut heap_asc: BinaryHeap<(i64, u64, Vec<u8>)> =
BinaryHeap::with_capacity(limit);
self.catalog
.for_each_row_raw(table, |_rid, data| {
if let Some(ref pred) = compiled_pred {
if !pred(data) {
return;
}
}
// Inlined int-column reader: null check + i64 decode.
if data.len() < sort_data_offset + 8 {
return;
}
let is_null = (data[2 + sort_bitmap_byte] >> sort_bitmap_bit) & 1 == 1;
if is_null {
return;
}
let key = i64::from_le_bytes(
data[sort_data_offset..sort_data_offset + 8]
.try_into()
.unwrap_or_else(|_| unreachable!()),
);
let id = seq;
seq += 1;
if descending {
if heap_desc.len() < limit {
heap_desc.push(Reverse((key, id, data.to_vec())));
} else if let Some(Reverse((top_key, _, _))) = heap_desc.peek() {
if key > *top_key {
heap_desc.pop();
heap_desc.push(Reverse((key, id, data.to_vec())));
}
}
} else if heap_asc.len() < limit {
heap_asc.push((key, id, data.to_vec()));
} else if let Some((top_key, _, _)) = heap_asc.peek() {
if key < *top_key {
heap_asc.pop();
heap_asc.push((key, id, data.to_vec()));
}
}
})
.map_err(|e| QueryError::StorageError(e.to_string()))?;
let mut drained: Vec<(i64, u64, Vec<u8>)> = if descending {
heap_desc.into_iter().map(|Reverse(t)| t).collect()
} else {
heap_asc.into_iter().collect()
};
if descending {
drained.sort_unstable_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
} else {
drained.sort_unstable_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
}
drained.into_iter().map(|(_, _, d)| d).collect()
}
TypeId::Float => {
// Novel angle: rather than introducing a `TotalF64` newtype
// with `Ord via total_cmp`, transform the f64 bit pattern
// into a sortable `u64` so `BinaryHeap<u64>` orders exactly
// like `f64::total_cmp` would. Classic trick: flip the sign
// bit on positives, flip all bits on negatives. Result:
// - NaN (sign=0) stays greatest, matching total_cmp
// - -0.0 sorts before +0.0, matching total_cmp
// - Hot loop is branch-cheap (one compare + one xor)
let mut seq: u64 = 0;
let mut heap_desc: BinaryHeap<Reverse<(u64, u64, Vec<u8>)>> =
BinaryHeap::with_capacity(limit);
let mut heap_asc: BinaryHeap<(u64, u64, Vec<u8>)> =
BinaryHeap::with_capacity(limit);
self.catalog
.for_each_row_raw(table, |_rid, data| {
if let Some(ref pred) = compiled_pred {
if !pred(data) {
return;
}
}
if data.len() < sort_data_offset + 8 {
return;
}
let is_null = (data[2 + sort_bitmap_byte] >> sort_bitmap_bit) & 1 == 1;
if is_null {
return;
}
let bits = u64::from_le_bytes(
data[sort_data_offset..sort_data_offset + 8]
.try_into()
.unwrap_or_else(|_| unreachable!()),
);
let key = f64_bits_to_sortable_u64(bits);
let id = seq;
seq += 1;
if descending {
if heap_desc.len() < limit {
heap_desc.push(Reverse((key, id, data.to_vec())));
} else if let Some(Reverse((top_key, _, _))) = heap_desc.peek() {
if key > *top_key {
heap_desc.pop();
heap_desc.push(Reverse((key, id, data.to_vec())));
}
}
} else if heap_asc.len() < limit {
heap_asc.push((key, id, data.to_vec()));
} else if let Some((top_key, _, _)) = heap_asc.peek() {
if key < *top_key {
heap_asc.pop();
heap_asc.push((key, id, data.to_vec()));
}
}
})
.map_err(|e| QueryError::StorageError(e.to_string()))?;
let mut drained: Vec<(u64, u64, Vec<u8>)> = if descending {
heap_desc.into_iter().map(|Reverse(t)| t).collect()
} else {
heap_asc.into_iter().collect()
};
if descending {
drained.sort_unstable_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
} else {
drained.sort_unstable_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
}
drained.into_iter().map(|(_, _, d)| d).collect()
}
_ => unreachable!("type guard above restricts to Int/Float"),
};
let rows: Vec<Vec<Value>> = drained
.into_iter()
.map(|data| {
proj_indices
.iter()
.map(|&ci| decode_column(&schema, &row_layout, &data, ci))
.collect()
})
.collect();
Ok(Some(QueryResult::Rows {
columns: proj_columns,
rows,
}))
}
/// Gather the RowIds that a mutation should operate on, without
/// materialising the full row set. Handles the shapes the planner emits
/// for update/delete: SeqScan, IndexScan, and Filter(SeqScan). Other
/// shapes fall back to `generic_rid_match`.
///
/// Perf sprint: try to fuse the predicate evaluation and in-place
/// byte-level mutation into a single heap walk. Returns `Some(result)`
/// if the fused path fired, `None` to fall through to the generic
/// two-pass code.
///
/// Covers two shapes:
/// 1. Fixed-width non-null literal assignments on non-indexed columns
/// → byte-patch every matched row in place (row length unchanged).
/// 2. Single var-col literal assignment on a non-indexed column
/// → `patch_var_column_in_place` on every matched row (may shrink);
/// rows that can't be patched in place are collected for fallback.
fn try_fused_scan_update(
&mut self,
table: &str,
predicate: &Expr,
resolved: &[(usize, Value)],
changed_cols: &[usize],
) -> Option<Result<QueryResult, QueryError>> {
// Build compiled predicate. Requires a schema borrow that must be
// dropped before we call scan_patch_matching_logged.
let compiled = {
let schema = self.catalog.schema(table)?;
let columns: Vec<String> = schema.columns.iter().map(|c| c.name.clone()).collect();
let fast = FastLayout::new(schema);
compile_predicate(predicate, &columns, &fast, schema)?
};
// ── Path 1: fixed-width fast patch ──────────────────────────
let fixed_patches: Option<Vec<FastPatch>> = {
let tbl = self.catalog.get_table(table)?;
let schema = &tbl.schema;
let all_fixed_nonnull = resolved
.iter()
.all(|(idx, val)| is_fixed_size(schema.columns[*idx].type_id) && !val.is_empty());
let no_indexed = !resolved.iter().any(|(idx, _)| tbl.has_indexed_col(*idx));
if all_fixed_nonnull && no_indexed {
let layout = RowLayout::new(schema);
let bitmap_size = layout.bitmap_size();
Some(
resolved
.iter()
.map(|(idx, val)| {
let fixed_off = layout
.fixed_offset(*idx)
.expect("is_fixed_size already checked");
let field_off = 2 + bitmap_size + fixed_off;
let bytes: FixedBytes = match val {
Value::Int(v) => FixedBytes::I64(v.to_le_bytes()),
Value::Float(v) => FixedBytes::F64(v.to_le_bytes()),
Value::Bool(v) => FixedBytes::Bool(if *v { 1 } else { 0 }),
Value::DateTime(v) => FixedBytes::I64(v.to_le_bytes()),
Value::Uuid(v) => FixedBytes::Uuid(*v),
_ => unreachable!("all_fixed_nonnull guard"),
};
FastPatch {
field_off,
bitmap_byte_off: 2 + idx / 8,
bit_mask: 1u8 << (idx % 8),
bytes,
}
})
.collect(),
)
} else {
None
}
};
if let Some(patches) = fixed_patches {
let result = self
.catalog
.scan_patch_matching_logged(table, compiled, |row| {
for p in &patches {
row[p.bitmap_byte_off] &= !p.bit_mask;
let field_bytes = p.bytes.as_slice();
row[p.field_off..p.field_off + field_bytes.len()]
.copy_from_slice(field_bytes);
}
Some(row.len() as u16)
})
.map_err(|e| e.to_string());
match result {
Ok((count, _)) => {
self.view_registry.mark_dependents_dirty(table);
return Some(Ok(QueryResult::Modified(count)));
}
Err(e) => return Some(Err(QueryError::Execution(e))),
}
}
// ── Path 2: single var-col shrink fast patch ────────────────
let var_patch: Option<(usize, Option<Vec<u8>>)> = {
let tbl = self.catalog.get_table(table)?;
let schema = &tbl.schema;
let is_single = resolved.len() == 1;
let is_var = is_single && !is_fixed_size(schema.columns[resolved[0].0].type_id);
let no_indexed = !resolved.iter().any(|(idx, _)| tbl.has_indexed_col(*idx));
if is_single && is_var && no_indexed {
let (idx, val) = &resolved[0];
let bytes_opt = match val {
Value::Str(s) => Some(s.as_bytes().to_vec()),
Value::Bytes(b) => Some(b.clone()),
Value::Empty => None,
_ => return None, // type mismatch, fall through
};
Some((*idx, bytes_opt))
} else {
None
}
};
if let Some((col_idx, ref new_bytes_opt)) = var_patch {
// Build a fresh RowLayout before the mutable borrow.
let layout = {
let schema = self.catalog.schema(table)?;
RowLayout::new(schema)
};
let new_bytes_ref: Option<&[u8]> = new_bytes_opt.as_deref();
let result = self
.catalog
.scan_patch_matching_logged(table, compiled, |row| {
patch_var_column_in_place(row, &layout, col_idx, new_bytes_ref)
})
.map_err(|e| e.to_string());
match result {
Ok((mut count, fallback_rids)) => {
// Handle rows where in-place patch failed (new > old).
for rid in fallback_rids {
let mut row = match self.catalog.get(table, rid) {
Some(r) => r,
None => continue,
};
for (idx, val) in resolved.iter() {
row[*idx] = val.clone();
}
self.catalog
.update_hinted(table, rid, &row, Some(changed_cols))
.map_err(|e| e.to_string())
.ok();
count += 1;
}
self.view_registry.mark_dependents_dirty(table);
return Some(Ok(QueryResult::Modified(count)));
}
Err(e) => return Some(Err(QueryError::Execution(e))),
}
}
None // no fused path applicable — fall through
}
/// Mission C Phase 3: schema is looked up via `self.catalog.schema(table)`
/// inside the branches that actually need it. Previously the caller had
/// to clone the full Schema (6+ String allocs) before every mutation just
/// so this function could borrow it — a cost the update/delete hot path
/// did not need.
fn collect_rids_for_mutation(
&mut self,
input: &PlanNode,
table: &str,
) -> Result<Vec<RowId>, QueryError> {
match input {
PlanNode::SeqScan { table: t } if t == table => {
// "Update/delete everything" — rare but legal.
let rids: Vec<RowId> = self
.catalog
.scan(table)
.map_err(|e| QueryError::StorageError(e.to_string()))?
.map(|(rid, _)| rid)
.collect();
Ok(rids)
}
PlanNode::IndexScan {
table: t,
column,
key,
} if t == table => {
let key_value = literal_to_value(key)?;
// Indexed case: single lookup, 0 or 1 rows.
// Mission D7: int-specialized fast path on int-keyed indexes
// (primary keys, created_at, etc.) — the common case for
// `update_by_pk` / `delete where id = ?`.
//
// Scope the `tbl` borrow so it's released before we fall
// through to the scan-based paths below (which reborrow
// `self.catalog`).
{
let tbl = self
.catalog
.get_table(table)
.ok_or_else(|| QueryError::TableNotFound(table.to_string()))?;
if tbl.has_index(column) {
let rids = tbl.index_lookup_all(column, &key_value);
return Ok(rids);
}
}
// No index: the planner folds `.col = literal` to IndexScan
// regardless of whether the column is actually unique. When
// there's no index we must behave like Filter(SeqScan) and
// return *all* matching RIDs — not just the first one.
let schema = self
.catalog
.schema(table)
.ok_or_else(|| QueryError::TableNotFound(table.to_string()))?;
let columns: Vec<String> = schema.columns.iter().map(|c| c.name.clone()).collect();
let fast = FastLayout::new(schema);
let synth = Expr::BinaryOp(
Box::new(Expr::Field(column.clone())),
BinOp::Eq,
Box::new(key.clone()),
);
if let Some(compiled) = compile_predicate(&synth, &columns, &fast, schema) {
// Mission F: skip the first 4 Vec doublings.
let mut rids: Vec<RowId> = Vec::with_capacity(64);
self.catalog
.for_each_row_raw(table, |rid, data| {
if compiled(data) {
rids.push(rid);
}
})
.map_err(|e| QueryError::StorageError(e.to_string()))?;
return Ok(rids);
}
// Fallback: decode each row, compare values.
let col_idx =
schema
.column_index(column)
.ok_or_else(|| QueryError::ColumnNotFound {
table: String::new(),
column: column.clone(),
})?;
let rids: Vec<RowId> = self
.catalog
.scan(table)
.map_err(|e| QueryError::StorageError(e.to_string()))?
.filter_map(|(rid, row)| {
if row[col_idx] == key_value {
Some(rid)
} else {
None
}
})
.collect();
Ok(rids)
}
PlanNode::Filter {
input: inner,
predicate,
} => {
if let PlanNode::SeqScan { table: t } = inner.as_ref() {
if t != table {
return self.generic_rid_match(input, table);
}
let schema = self
.catalog
.schema(table)
.ok_or_else(|| QueryError::TableNotFound(table.to_string()))?;
let columns: Vec<String> =
schema.columns.iter().map(|c| c.name.clone()).collect();
let fast = FastLayout::new(schema);
let row_layout = RowLayout::new(schema);
// Try compiled predicate first.
if let Some(compiled) = compile_predicate(predicate, &columns, &fast, schema) {
// Mission F: skip the first 4 Vec doublings.
let mut rids: Vec<RowId> = Vec::with_capacity(64);
self.catalog
.for_each_row_raw(table, |rid, data| {
if compiled(data) {
rids.push(rid);
}
})
.map_err(|e| QueryError::StorageError(e.to_string()))?;
return Ok(rids);
}
// Fallback: selective decode + eval.
let pred_cols = predicate_column_indices(predicate, &columns);
let mut rids: Vec<RowId> = Vec::with_capacity(64);
self.catalog
.for_each_row_raw(table, |rid, data| {
let pred_row = decode_selective(schema, &row_layout, data, &pred_cols);
if eval_predicate(predicate, &pred_row, &columns) {
rids.push(rid);
}
})
.map_err(|e| QueryError::StorageError(e.to_string()))?;
return Ok(rids);
}
self.generic_rid_match(input, table)
}
_ => self.generic_rid_match(input, table),
}
}
/// Last-ditch generic match: execute the plan, collect matching rows,
/// then find corresponding RowIds by value equality. This is the old
/// O(N*M) code path; only used when the plan shape is something exotic.
fn generic_rid_match(
&mut self,
input: &PlanNode,
table: &str,
) -> Result<Vec<RowId>, QueryError> {
let result = self.execute_plan(input)?;
let rows = match result {
QueryResult::Rows { rows, .. } => rows,
_ => return Err("mutation source must be rows".into()),
};
let matching: Vec<RowId> = self
.catalog
.scan(table)
.map_err(|e| QueryError::StorageError(e.to_string()))?
.filter(|(_, row)| rows.iter().any(|r| r == row))
.map(|(rid, _)| rid)
.collect();
Ok(matching)
}
}
pub(super) fn execute_window(
result: QueryResult,
windows: &[WindowDef],
) -> Result<QueryResult, QueryError> {
let (mut columns, mut rows) = match result {
QueryResult::Rows { columns, rows } => (columns, rows),
_ => return Err("window function requires row input".into()),
};
for wdef in windows {
// Resolve partition/order column indices against current columns.
let part_indices: Vec<usize> = wdef
.partition_by
.iter()
.map(|name| {
columns
.iter()
.position(|c| c == name)
.ok_or_else(|| format!("window partition column '{name}' not found"))
})
.collect::<Result<Vec<_>, _>>()?;
let ord_indices: Vec<(usize, bool)> = wdef
.order_by
.iter()
.map(|sk| {
columns
.iter()
.position(|c| c == &sk.field)
.map(|i| (i, sk.descending))
.ok_or_else(|| format!("window order column '{}' not found", sk.field))
})
.collect::<Result<Vec<_>, _>>()?;
// Resolve the argument column index (for aggregate windows).
let arg_col_idx: Option<usize> = if let Some(arg) = wdef.args.first() {
match arg {
Expr::Field(name) => {
if name == "*" {
None // count(*) style — no specific column
} else {
Some(
columns
.iter()
.position(|c| c == name)
.ok_or_else(|| format!("window arg column '{name}' not found"))?,
)
}
}
_ => None,
}
} else {
None
};
// Build a sort-index to sort rows by partition_by then order_by
// without actually reordering the original Vec (we need original
// order to write results back).
let n = rows.len();
let mut indices: Vec<usize> = (0..n).collect();
indices.sort_by(|&a, &b| {
// Compare partition keys first.
for &pi in &part_indices {
let cmp = rows[a][pi].cmp(&rows[b][pi]);
if cmp != std::cmp::Ordering::Equal {
return cmp;
}
}
// Then order keys.
for &(oi, desc) in &ord_indices {
let cmp = rows[a][oi].cmp(&rows[b][oi]);
if cmp != std::cmp::Ordering::Equal {
return if desc { cmp.reverse() } else { cmp };
}
}
std::cmp::Ordering::Equal
});
// Compute window values in sorted order, tracking partition boundaries.
let mut win_values: Vec<Value> = vec![Value::Empty; n];
let mut partition_start = 0usize;
// Running state for aggregate windows:
let mut running_count: i64 = 0;
let mut running_int_sum: i64 = 0;
let mut running_float_sum: f64 = 0.0;
let mut running_saw_float = false;
let mut running_min: Option<Value> = None;
let mut running_max: Option<Value> = None;
let mut rank_counter: i64 = 0;
let mut dense_rank_counter: i64 = 0;
let mut prev_order_key: Option<Vec<Value>> = None;
let mut same_rank_count: i64 = 0;
for sorted_pos in 0..n {
let row_idx = indices[sorted_pos];
// Detect partition boundary.
let new_partition = if sorted_pos == 0 {
true
} else {
let prev_row_idx = indices[sorted_pos - 1];
part_indices
.iter()
.any(|&pi| rows[row_idx][pi] != rows[prev_row_idx][pi])
};
if new_partition {
partition_start = sorted_pos;
running_count = 0;
running_int_sum = 0;
running_float_sum = 0.0;
running_saw_float = false;
running_min = None;
running_max = None;
rank_counter = 0;
dense_rank_counter = 0;
prev_order_key = None;
same_rank_count = 0;
}
// Extract current order key for rank tracking.
let current_order_key: Vec<Value> = ord_indices
.iter()
.map(|&(oi, _)| rows[row_idx][oi].clone())
.collect();
let same_as_prev = prev_order_key.as_ref() == Some(¤t_order_key);
let value = match wdef.function {
WindowFunc::RowNumber => Value::Int((sorted_pos - partition_start + 1) as i64),
WindowFunc::Rank => {
if same_as_prev {
same_rank_count += 1;
} else {
rank_counter += same_rank_count + 1;
same_rank_count = 0;
if rank_counter == 0 {
rank_counter = 1;
}
}
Value::Int(rank_counter)
}
WindowFunc::DenseRank => {
if !same_as_prev {
dense_rank_counter += 1;
}
Value::Int(dense_rank_counter)
}
WindowFunc::Sum => {
if let Some(ci) = arg_col_idx {
match &rows[row_idx][ci] {
Value::Int(v) => running_int_sum += v,
Value::Float(v) => {
running_float_sum += v;
running_saw_float = true;
}
_ => {}
}
}
if running_saw_float {
Value::Float(running_float_sum + running_int_sum as f64)
} else {
Value::Int(running_int_sum)
}
}
WindowFunc::Avg => {
if let Some(ci) = arg_col_idx {
match &rows[row_idx][ci] {
Value::Int(v) => {
running_float_sum += *v as f64;
running_count += 1;
}
Value::Float(v) => {
running_float_sum += v;
running_count += 1;
}
_ => {}
}
}
if running_count == 0 {
Value::Empty
} else {
Value::Float(running_float_sum / running_count as f64)
}
}
WindowFunc::Count => {
if let Some(ci) = arg_col_idx {
if !rows[row_idx][ci].is_empty() {
running_count += 1;
}
} else {
// count(*) — count all rows
running_count += 1;
}
Value::Int(running_count)
}
WindowFunc::Min => {
if let Some(ci) = arg_col_idx {
let v = &rows[row_idx][ci];
if !v.is_empty() {
running_min = Some(match &running_min {
None => v.clone(),
Some(cur) => {
if v < cur {
v.clone()
} else {
cur.clone()
}
}
});
}
}
running_min.clone().unwrap_or(Value::Empty)
}
WindowFunc::Max => {
if let Some(ci) = arg_col_idx {
let v = &rows[row_idx][ci];
if !v.is_empty() {
running_max = Some(match &running_max {
None => v.clone(),
Some(cur) => {
if v > cur {
v.clone()
} else {
cur.clone()
}
}
});
}
}
running_max.clone().unwrap_or(Value::Empty)
}
};
prev_order_key = Some(current_order_key);
win_values[row_idx] = value;
}
// Append the computed window column to each row.
for (ri, row) in rows.iter_mut().enumerate() {
row.push(win_values[ri].clone());
}
columns.push(wdef.output_name.clone());
}
Ok(QueryResult::Rows { columns, rows })
}
/// Mission E2b: compute one aggregate over a set of rows in a group.
pub(super) fn compute_group_aggregate(
func: AggFunc,
all_rows: &[Vec<Value>],
row_indices: &[usize],
col_idx: usize,
) -> Value {
match func {
AggFunc::Count => {
if col_idx == usize::MAX {
// count(*) — count all rows in the group.
return Value::Int(row_indices.len() as i64);
}
let count = row_indices
.iter()
.filter(|&&ri| !all_rows[ri][col_idx].is_empty())
.count();
Value::Int(count as i64)
}
AggFunc::CountDistinct => {
let mut seen = std::collections::HashSet::new();
for &ri in row_indices {
let v = &all_rows[ri][col_idx];
if !v.is_empty() {
seen.insert(v.clone());
}
}
Value::Int(seen.len() as i64)
}
AggFunc::Sum => {
// Mirror the scalar Sum path: accumulate int and float
// contributions separately and promote the final result to
// Float if any Float row was observed. Prevents silent
// drop of Float columns in GROUP BY aggregates.
let mut int_sum: i64 = 0;
let mut float_sum: f64 = 0.0;
let mut saw_float = false;
for &ri in row_indices {
match &all_rows[ri][col_idx] {
Value::Int(v) => int_sum += v,
Value::Float(v) => {
float_sum += *v;
saw_float = true;
}
_ => {}
}
}
if saw_float {
Value::Float(float_sum + int_sum as f64)
} else {
Value::Int(int_sum)
}
}
AggFunc::Avg => {
let mut sum = 0.0f64;
let mut count = 0usize;
for &ri in row_indices {
match &all_rows[ri][col_idx] {
Value::Int(v) => {
sum += *v as f64;
count += 1;
}
Value::Float(v) => {
sum += *v;
count += 1;
}
_ => {}
}
}
if count == 0 {
Value::Empty
} else {
Value::Float(sum / count as f64)
}
}
AggFunc::Min => row_indices
.iter()
.map(|&ri| &all_rows[ri][col_idx])
.filter(|v| !v.is_empty())
.min()
.cloned()
.unwrap_or(Value::Empty),
AggFunc::Max => row_indices
.iter()
.map(|&ri| &all_rows[ri][col_idx])
.filter(|v| !v.is_empty())
.max()
.cloned()
.unwrap_or(Value::Empty),
}
}
/// Mission E1.3: try to extract equi-join key indices from a join `on`
/// predicate. Returns `Some((left_col_idx, right_col_idx))` when the
/// predicate is exactly `L = R` (or `R = L`) and both sides resolve
/// cleanly — `L` to the left subtree's column list and `R` to the right
/// subtree's column list.
///
/// This is deliberately narrow. We only recognise the two shapes:
/// * `QualifiedField = QualifiedField` (`u.id = o.user_id`)
/// * `Field = Field` (`.id = .user_id`, unqualified)
///
/// Anything else — conjunctions, constants, function calls, or predicates
/// that touch the same side on both halves — falls through to the
/// nested-loop path unchanged.
pub(super) fn try_extract_equi_join_keys(
pred: &Expr,
left_columns: &[String],
right_columns: &[String],
) -> Option<(usize, usize)> {
let (lhs, op, rhs) = match pred {
Expr::BinaryOp(l, op, r) => (l.as_ref(), *op, r.as_ref()),
_ => return None,
};
if op != BinOp::Eq {
return None;
}
// Normal orientation: lhs in left, rhs in right.
if let (Some(li), Some(ri)) = (
resolve_side_column(lhs, left_columns),
resolve_side_column(rhs, right_columns),
) {
return Some((li, ri));
}
// Swapped: rhs in left, lhs in right. Both sides of `=` are
// commutative so this is safe.
if let (Some(li), Some(ri)) = (
resolve_side_column(rhs, left_columns),
resolve_side_column(lhs, right_columns),
) {
return Some((li, ri));
}
None
}
fn resolve_side_column(expr: &Expr, columns: &[String]) -> Option<usize> {
match expr {
Expr::QualifiedField { qualifier, field } => {
// Byte-level match so we don't allocate a fresh `format!` on
// every call — this runs once per plan, so allocation would be
// cheap, but the match is trivial enough to keep inline with
// the eval_expr version.
let q = qualifier.as_bytes();
let f = field.as_bytes();
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
})
}
Expr::Field(name) => columns.iter().position(|c| c == name),
_ => None,
}
}
/// Mission E1.3: O(L + R) hash join. Builds a `FxHashMap<Value, Vec<usize>>`
/// over the right (inner) side's join keys, then streams the left (outer)
/// side and for each probe row emits every combined row whose right-side
/// key matches. For `JoinKind::LeftOuter`, unmatched left rows are emitted
/// padded with `Value::Empty` on the right side.
///
/// The right side is always the build side. That choice is forced for
/// LeftOuter (the left side must stream so we can detect orphans), and
/// for Inner it's a reasonable default — left-deep plans tend to grow the
/// left side with each join, so the un-joined right leaf is often the
/// smaller of the two at each level.
pub(super) fn hash_join(
left_columns: Vec<String>,
left_rows: Vec<Vec<Value>>,
right_columns: Vec<String>,
right_rows: Vec<Vec<Value>>,
left_key_idx: usize,
right_key_idx: usize,
kind: JoinKind,
) -> QueryResult {
use rustc_hash::FxHashMap;
let n_left = left_columns.len();
let n_right = right_columns.len();
let mut columns = Vec::with_capacity(n_left + n_right);
columns.extend(left_columns);
columns.extend(right_columns);
// Build: right_key -> list of right-row indices. Pre-size to the row
// count so the map doesn't rehash mid-build.
let mut build: FxHashMap<Value, Vec<usize>> =
FxHashMap::with_capacity_and_hasher(right_rows.len(), Default::default());
for (i, row) in right_rows.iter().enumerate() {
// Skip Empty keys on the build side — they can never match under
// SQL semantics (NULL ≠ NULL) and would collapse all nullables to
// one bucket.
if matches!(row[right_key_idx], Value::Empty) {
continue;
}
build.entry(row[right_key_idx].clone()).or_default().push(i);
}
// Reasonable starting capacity — inner joins produce ≥ left_rows.len()
// rows in the common 1:1 case, left-outer always emits ≥ left_rows.len().
let mut rows: Vec<Vec<Value>> = Vec::with_capacity(left_rows.len());
for left_row in &left_rows {
let key = &left_row[left_key_idx];
let matched = if matches!(key, Value::Empty) {
None
} else {
build.get(key)
};
match matched {
Some(matches) if !matches.is_empty() => {
for &ri in matches {
let right_row = &right_rows[ri];
let mut combined = Vec::with_capacity(n_left + n_right);
combined.extend_from_slice(left_row);
combined.extend_from_slice(right_row);
rows.push(combined);
}
}
_ => {
if matches!(kind, JoinKind::LeftOuter) {
let mut row = Vec::with_capacity(n_left + n_right);
row.extend_from_slice(left_row);
row.resize(n_left + n_right, Value::Empty);
rows.push(row);
}
}
}
}
QueryResult::Rows { columns, rows }
}
/// Lower unindexed `RangeScan` nodes to `Filter(SeqScan)` so that all
/// downstream fast paths (count, project+limit, sort+limit, agg, update,
/// delete) continue to fire.
///
/// The planner emits `RangeScan` speculatively for every range inequality
/// (`.age > 30`) because it has no catalog access. When the column has a
/// B-tree index, `RangeScan` is the correct plan. When it doesn't, the
/// executor's `RangeScan` fallback materialises every matching row with
/// full `decode_row` — bypassing the compiled-predicate fast paths that
/// `Filter(SeqScan)` would trigger.
///
/// This pass runs once per query, before execution.
pub(super) fn lower_unindexed_range_scans(catalog: &Catalog, plan: &PlanNode) -> PlanNode {
match plan {
PlanNode::RangeScan {
table,
column,
start,
end,
} => {
if let Some(tbl) = catalog.get_table(table) {
// Keep RangeScan only for unique indexes — their btree
// stores raw column values. Non-unique indexes store
// composite keys that don't directly compare against
// column values, so lower them to Filter(SeqScan).
if tbl.is_index_unique(column) == Some(true) {
return plan.clone();
}
}
let pred = synthesize_range_predicate(column, start, end);
PlanNode::Filter {
input: Box::new(PlanNode::SeqScan {
table: table.clone(),
}),
predicate: pred,
}
}
PlanNode::Filter { input, predicate } => PlanNode::Filter {
input: Box::new(lower_unindexed_range_scans(catalog, input)),
predicate: predicate.clone(),
},
PlanNode::Project { input, fields } => PlanNode::Project {
input: Box::new(lower_unindexed_range_scans(catalog, input)),
fields: fields.clone(),
},
PlanNode::Sort { input, keys } => PlanNode::Sort {
input: Box::new(lower_unindexed_range_scans(catalog, input)),
keys: keys.clone(),
},
PlanNode::Limit { input, count } => PlanNode::Limit {
input: Box::new(lower_unindexed_range_scans(catalog, input)),
count: count.clone(),
},
PlanNode::Offset { input, count } => PlanNode::Offset {
input: Box::new(lower_unindexed_range_scans(catalog, input)),
count: count.clone(),
},
PlanNode::Aggregate {
input,
function,
field,
} => PlanNode::Aggregate {
input: Box::new(lower_unindexed_range_scans(catalog, input)),
function: *function,
field: field.clone(),
},
PlanNode::Distinct { input } => PlanNode::Distinct {
input: Box::new(lower_unindexed_range_scans(catalog, input)),
},
PlanNode::GroupBy {
input,
keys,
aggregates,
having,
} => PlanNode::GroupBy {
input: Box::new(lower_unindexed_range_scans(catalog, input)),
keys: keys.clone(),
aggregates: aggregates.clone(),
having: having.clone(),
},
PlanNode::Update {
input,
table,
assignments,
} => PlanNode::Update {
input: Box::new(lower_unindexed_range_scans(catalog, input)),
table: table.clone(),
assignments: assignments.clone(),
},
PlanNode::Delete { input, table } => PlanNode::Delete {
input: Box::new(lower_unindexed_range_scans(catalog, input)),
table: table.clone(),
},
PlanNode::Window { input, windows } => PlanNode::Window {
input: Box::new(lower_unindexed_range_scans(catalog, input)),
windows: windows.clone(),
},
PlanNode::Union { left, right, all } => PlanNode::Union {
left: Box::new(lower_unindexed_range_scans(catalog, left)),
right: Box::new(lower_unindexed_range_scans(catalog, right)),
all: *all,
},
PlanNode::Explain { input } => PlanNode::Explain {
input: Box::new(lower_unindexed_range_scans(catalog, input)),
},
PlanNode::NestedLoopJoin {
left,
right,
on,
kind,
} => PlanNode::NestedLoopJoin {
left: Box::new(lower_unindexed_range_scans(catalog, left)),
right: Box::new(lower_unindexed_range_scans(catalog, right)),
on: on.clone(),
kind: *kind,
},
// Leaf nodes: no children to recurse into.
_ => plan.clone(),
}
}
/// Synthesize a range predicate from RangeScan bounds for the fallback path.
pub(super) fn synthesize_range_predicate(
column: &str,
start: &Option<(Expr, bool)>,
end: &Option<(Expr, bool)>,
) -> Expr {
let lower = start.as_ref().map(|(expr, inclusive)| {
let op = if *inclusive { BinOp::Gte } else { BinOp::Gt };
Expr::BinaryOp(
Box::new(Expr::Field(column.to_string())),
op,
Box::new(expr.clone()),
)
});
let upper = end.as_ref().map(|(expr, inclusive)| {
let op = if *inclusive { BinOp::Lte } else { BinOp::Lt };
Expr::BinaryOp(
Box::new(Expr::Field(column.to_string())),
op,
Box::new(expr.clone()),
)
});
match (lower, upper) {
(Some(l), Some(u)) => Expr::BinaryOp(Box::new(l), BinOp::And, Box::new(u)),
(Some(l), None) => l,
(None, Some(u)) => u,
(None, None) => Expr::Literal(Literal::Bool(true)),
}
}
/// Check if a value falls within a range (used in last-resort decoded-row eval).
pub(super) fn range_matches(
val: &Value,
start: &Option<Value>,
start_inc: bool,
end: &Option<Value>,
end_inc: bool,
) -> bool {
if let Some(ref s) = start {
if start_inc {
if val < s {
return false;
}
} else if val <= s {
return false;
}
}
if let Some(ref e) = end {
if end_inc {
if val > e {
return false;
}
} else if val >= e {
return false;
}
}
true
}
/// Format a `PlanNode` tree as a human-readable, indented text
/// representation. Used by the `EXPLAIN` command.
pub(super) fn format_plan_tree(plan: &PlanNode, depth: usize) -> String {
let indent = " ".repeat(depth);
match plan {
PlanNode::SeqScan { table } => format!("{indent}SeqScan table={table}"),
PlanNode::AliasScan { table, alias } => {
format!("{indent}AliasScan table={table} alias={alias}")
}
PlanNode::IndexScan { table, column, key } => {
format!("{indent}IndexScan table={table} column={column} key={key:?}")
}
PlanNode::RangeScan {
table,
column,
start,
end,
} => {
let s = match start {
Some((expr, inc)) => {
let op = if *inc { ">=" } else { ">" };
format!("{op}{expr:?}")
}
None => "unbounded".to_string(),
};
let e = match end {
Some((expr, inc)) => {
let op = if *inc { "<=" } else { "<" };
format!("{op}{expr:?}")
}
None => "unbounded".to_string(),
};
format!("{indent}RangeScan table={table} column={column} [{s}, {e}]")
}
PlanNode::Filter { input, predicate } => {
let child = format_plan_tree(input, depth + 1);
format!("{indent}Filter predicate={predicate:?}\n{child}")
}
PlanNode::Project { input, fields } => {
let names: Vec<String> = fields
.iter()
.map(|f| match &f.alias {
Some(a) => format!("{a}: {:?}", f.expr),
None => format!("{:?}", f.expr),
})
.collect();
let child = format_plan_tree(input, depth + 1);
format!("{indent}Project fields=[{}]\n{child}", names.join(", "))
}
PlanNode::Sort { input, keys } => {
let ks: Vec<String> = keys
.iter()
.map(|k| {
if k.descending {
format!("{} desc", k.field)
} else {
k.field.clone()
}
})
.collect();
let child = format_plan_tree(input, depth + 1);
format!("{indent}Sort keys=[{}]\n{child}", ks.join(", "))
}
PlanNode::Limit { input, count } => {
let child = format_plan_tree(input, depth + 1);
format!("{indent}Limit count={count:?}\n{child}")
}
PlanNode::Offset { input, count } => {
let child = format_plan_tree(input, depth + 1);
format!("{indent}Offset count={count:?}\n{child}")
}
PlanNode::Aggregate {
input,
function,
field,
} => {
let f = field.as_deref().unwrap_or("*");
let child = format_plan_tree(input, depth + 1);
format!("{indent}Aggregate fn={function:?} field={f}\n{child}")
}
PlanNode::NestedLoopJoin {
left,
right,
on,
kind,
} => {
let left_child = format_plan_tree(left, depth + 1);
let right_child = format_plan_tree(right, depth + 1);
let on_str = match on {
Some(pred) => format!("{pred:?}"),
None => "none".to_string(),
};
format!("{indent}NestedLoopJoin kind={kind:?} on={on_str}\n{left_child}\n{right_child}")
}
PlanNode::Distinct { input } => {
let child = format_plan_tree(input, depth + 1);
format!("{indent}Distinct\n{child}")
}
PlanNode::GroupBy {
input,
keys,
aggregates,
having,
} => {
let agg_strs: Vec<String> = aggregates
.iter()
.map(|a| format!("{:?}({}) as {}", a.function, a.field, a.output_name))
.collect();
let having_str = match having {
Some(h) => format!(" having={h:?}"),
None => String::new(),
};
let child = format_plan_tree(input, depth + 1);
format!(
"{indent}GroupBy keys=[{}] aggs=[{}]{having_str}\n{child}",
keys.join(", "),
agg_strs.join(", "),
)
}
PlanNode::Insert { table, assignments } => {
let cols: Vec<&str> = assignments.iter().map(|a| a.field.as_str()).collect();
format!("{indent}Insert table={table} cols=[{}]", cols.join(", "))
}
PlanNode::Upsert {
table,
key_column,
assignments,
on_conflict,
} => {
let cols: Vec<&str> = assignments.iter().map(|a| a.field.as_str()).collect();
let conflict_cols: Vec<&str> = on_conflict.iter().map(|a| a.field.as_str()).collect();
if conflict_cols.is_empty() {
format!(
"{indent}Upsert table={table} key={key_column} cols=[{}]",
cols.join(", ")
)
} else {
format!(
"{indent}Upsert table={table} key={key_column} cols=[{}] on_conflict=[{}]",
cols.join(", "),
conflict_cols.join(", ")
)
}
}
PlanNode::Update {
input,
table,
assignments,
} => {
let cols: Vec<&str> = assignments.iter().map(|a| a.field.as_str()).collect();
let child = format_plan_tree(input, depth + 1);
format!(
"{indent}Update table={table} set=[{}]\n{child}",
cols.join(", ")
)
}
PlanNode::Delete { input, table } => {
let child = format_plan_tree(input, depth + 1);
format!("{indent}Delete table={table}\n{child}")
}
PlanNode::CreateTable { name, fields } => {
let fs: Vec<String> = fields
.iter()
.map(|(n, t, r)| {
if *r {
format!("{n}: {t} required")
} else {
format!("{n}: {t}")
}
})
.collect();
format!("{indent}CreateTable name={name} fields=[{}]", fs.join(", "))
}
PlanNode::AlterTable { table, action } => {
format!("{indent}AlterTable table={table} action={action:?}")
}
PlanNode::DropTable { name } => format!("{indent}DropTable name={name}"),
PlanNode::CreateView { name, .. } => format!("{indent}CreateView name={name}"),
PlanNode::RefreshView { name } => format!("{indent}RefreshView name={name}"),
PlanNode::DropView { name } => format!("{indent}DropView name={name}"),
PlanNode::Window { input, windows } => {
let ws: Vec<String> = windows
.iter()
.map(|w| format!("{:?} as {}", w.function, w.output_name))
.collect();
let child = format_plan_tree(input, depth + 1);
format!("{indent}Window fns=[{}]\n{child}", ws.join(", "))
}
PlanNode::Union { left, right, all } => {
let kind = if *all { "UNION ALL" } else { "UNION" };
let left_child = format_plan_tree(left, depth + 1);
let right_child = format_plan_tree(right, depth + 1);
format!("{indent}{kind}\n{left_child}\n{right_child}")
}
PlanNode::Explain { input } => {
let child = format_plan_tree(input, depth + 1);
format!("{indent}Explain\n{child}")
}
PlanNode::Begin => format!("{indent}Begin"),
PlanNode::Commit => format!("{indent}Commit"),
PlanNode::Rollback => format!("{indent}Rollback"),
}
}