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
//! The virtual database engine (VDBE).
//!
//! The VDBE is a register-based virtual machine that execute bytecode
//! instructions that represent SQL statements. When an application prepares
//! an SQL statement, the statement is compiled into a sequence of bytecode
//! instructions that perform the needed operations, such as reading or
//! writing to a b-tree, sorting, or aggregating data.
//!
//! The instruction set of the VDBE is similar to SQLite's instruction set,
//! but with the exception that bytecodes that perform I/O operations are
//! return execution back to the caller instead of blocking. This is because
//! Turso is designed for applications that need high concurrency such as
//! serverless runtimes. In addition, asynchronous I/O makes storage
//! disaggregation easier.
//!
//! You can find a full list of SQLite opcodes at:
//!
//! https://www.sqlite.org/opcode.html
use crate::translate::plan::BitSet;
use crate::types::{Extendable, Text};
use crate::{turso_assert, turso_assert_ne, turso_debug_assert, NonNan};
pub mod affinity;
pub mod array;
pub mod bloom_filter;
pub mod builder;
pub mod execute;
pub mod explain;
#[allow(dead_code)]
pub mod hash_table;
pub mod insn;
pub mod metrics;
pub mod rowset;
pub mod sorter;
pub mod vacuum;
pub mod value;
// for benchmarks
pub use crate::translate::collate::CollationSeq;
use crate::{
error::LimboError,
function::{AggFunc, FuncCtx},
mvcc::{database::CommitStateMachine, MvccClock},
numeric::Numeric,
return_if_io,
schema::Trigger,
state_machine::StateMachine,
translate::plan::TableReferences,
types::{IOCompletions, IOResult},
vdbe::{
execute::{
OpColumnState, OpDeleteState, OpDeleteSubState, OpDestroyState, OpIdxInsertState,
OpInitCdcVersionState, OpInsertState, OpInsertSubState, OpJournalModeState,
OpNewRowidState, OpNoConflictState, OpParseSchemaState, OpProgramState, OpRowIdState,
OpSeekState, OpTransactionState, VacuumIntoOpContext,
},
hash_table::HashTable,
metrics::StatementMetrics,
vacuum::VacuumInPlaceOpContext,
},
ValueRef, WalAutoActions,
};
use smallvec::SmallVec;
#[cfg(feature = "json")]
use crate::json::JsonCacheCell;
use crate::sync::RwLock;
use crate::{
storage::pager::Pager,
translate::plan::ResultSetColumn,
types::{AggContext, Cursor, ImmutableRecord, Value},
vdbe::{builder::CursorType, insn::Insn},
};
use crate::{
AtomicBool, CaptureDataChangesInfo, Connection, MvStore, Result, Statement, SyncMode,
TransactionState,
};
use branches::{mark_unlikely, unlikely};
use builder::{CursorKey, QueryMode};
use execute::{
InsnFunction, InsnFunctionStepResult, OpIdxDeleteState, OpIntegrityCheckState,
OpOpenEphemeralState,
};
use turso_parser::ast::ResolveType;
use crate::io::TempFile;
use crate::vdbe::bloom_filter::BloomFilter;
use crate::vdbe::rowset::RowSet;
use explain::{insn_to_row_with_comment, EXPLAIN_COLUMNS, EXPLAIN_QUERY_PLAN_COLUMNS};
use std::{
collections::HashMap,
num::NonZero,
ops::Deref,
sync::{
atomic::{AtomicI64, AtomicIsize, Ordering},
Arc,
},
task::Waker,
};
use tracing::{instrument, Level};
/// State machine for committing view deltas with I/O handling
#[derive(Debug, Clone)]
pub enum ViewDeltaCommitState {
NotStarted,
Processing {
views: Vec<String>, // view names (all materialized views have storage)
current_index: usize,
},
Done,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
/// Represents a target for a jump instruction.
/// Stores 32-bit ints to keep the enum word-sized.
pub enum BranchOffset {
/// A label is a named location in the program.
/// If there are references to it, it must always be resolved to an Offset
/// via `ProgramBuilder::preassign_label_to_next_insn` or
/// `ProgramBuilder::link_label_to_other_label`.
Label(u32),
/// An offset is a direct index into the instruction list.
Offset(InsnReference),
/// A placeholder is a temporary value to satisfy the compiler.
/// It must be set later.
Placeholder,
}
impl BranchOffset {
/// Returns true if the branch offset is an offset.
pub fn is_offset(&self) -> bool {
matches!(self, BranchOffset::Offset(_))
}
/// Returns the offset value. Panics if the branch offset is a label or placeholder.
pub fn as_offset_int(&self) -> InsnReference {
match self {
BranchOffset::Label(v) => unreachable!("Unresolved label: {}", v),
BranchOffset::Offset(v) => *v,
BranchOffset::Placeholder => unreachable!("Unresolved placeholder"),
}
}
/// Returns the branch offset as a signed integer.
/// Used in explain output, where we don't want to panic in case we have an unresolved
/// label or placeholder.
pub fn as_debug_int(&self) -> i32 {
match self {
BranchOffset::Label(v) => *v as i32,
BranchOffset::Offset(v) => *v as i32,
BranchOffset::Placeholder => i32::MAX,
}
}
}
pub type CursorID = usize;
pub type PageIdx = i64;
// Index of insn in list of insns
type InsnReference = u32;
#[derive(Debug)]
pub enum StepResult {
Done,
IO,
Row,
Interrupt,
Busy,
}
#[derive(Debug)]
#[allow(clippy::large_enum_variant)]
/// The commit state of the program.
/// There are two states:
/// - Ready: The program is ready to run the next instruction, or has shut down after
/// the last instruction.
/// - Committing: The program is committing a write transaction. It is waiting for the pager to finish flushing the cache to disk,
/// primarily to the WAL, but also possibly checkpointing the WAL to the database file.
enum CommitState {
Ready,
Committing,
/// Committing attached database pagers after main pager commit is done.
CommittingAttached,
CommittingMvcc {
state_machine: StateMachine<Box<CommitStateMachine<MvccClock>>>,
},
/// Committing MVCC transactions on attached databases after main MVCC commit is done.
CommittingAttachedMvcc {
state_machine: StateMachine<Box<CommitStateMachine<MvccClock>>>,
db_id: usize,
mv_store: Arc<MvStore>,
},
}
impl CommitState {
fn cleanup_mvcc_checkpoint_state(&mut self) {
match self {
CommitState::CommittingMvcc { state_machine } => {
state_machine.inner_mut().cleanup_mvcc_checkpoint_state()
}
CommitState::CommittingAttachedMvcc { state_machine, .. } => {
state_machine.inner_mut().cleanup_mvcc_checkpoint_state()
}
CommitState::Ready | CommitState::Committing | CommitState::CommittingAttached => {}
}
}
fn cleanup_abandoned_mvcc_commit(&mut self, connection: &Connection) {
match self {
CommitState::CommittingAttachedMvcc {
state_machine,
db_id: attached_db_id,
..
} if !state_machine.is_finalized() => {
if connection
.database_schemas()
.write()
.remove(attached_db_id)
.is_some()
{
connection.bump_prepare_context_generation();
}
}
CommitState::CommittingMvcc { state_machine } if !state_machine.is_finalized() => {}
_ => return, // no-op for already-finalized state machines and non-MVCC commit states
};
connection.rollback_attached_mvcc_txs(true);
connection.rollback_attached_wal_txns();
}
}
#[derive(Debug, Clone)]
pub enum Register {
Value(Value),
Aggregate(AggContext),
Record(ImmutableRecord),
}
impl Register {
#[inline]
pub const fn is_null(&self) -> bool {
matches!(self, Register::Value(Value::Null))
}
#[inline(always)]
/// Sets the value of the register to an integer,
/// reusing the existing Register::Value(Value::Numeric(Numeric::Integer(_))) if possible,
/// which is faster than always creating a new one.
pub fn set_int(&mut self, val: i64) {
match self {
Register::Value(Value::Numeric(Numeric::Integer(existing))) => {
*existing = val;
}
Register::Value(Value::Numeric(float)) => {
*float = Numeric::Integer(val);
}
Register::Value(other_value_kind) => {
*other_value_kind = Value::from_i64(val);
}
_ => {
*self = Register::Value(Value::from_i64(val));
}
}
}
/// Set the value of the register to a floating point,
/// reusing Register::Value(Value::Numeric(Numeric::Float(_))) if possible.
#[inline(always)]
pub fn set_float(&mut self, val: NonNan) {
match self {
Register::Value(Value::Numeric(Numeric::Float(existing))) => {
*existing = val;
}
Register::Value(Value::Numeric(integer)) => {
*integer = Numeric::Float(val);
}
Register::Value(other_value_kind) => {
*other_value_kind = Value::Numeric(Numeric::Float(val));
}
_ => {
*self = Register::Value(Value::Numeric(Numeric::Float(val)));
}
}
}
/// Set the value of the register to a Text,
/// reusing Register::Value(Value::Text(_)) buffer if possible.
#[inline]
pub fn set_text(&mut self, val: Text) {
match self {
Register::Value(Value::Text(existing)) => {
existing.do_extend(&val);
}
Register::Value(other_value_kind) => {
*other_value_kind = Value::Text(val);
}
_ => {
*self = Register::Value(Value::Text(val));
}
}
}
/// Set the value of the register to a blob,
/// reusing Register::Value(Value::Blob(_)) buffer if possible.
#[inline]
pub fn set_blob(&mut self, val: Vec<u8>) {
match self {
Register::Value(Value::Blob(existing)) => {
existing.do_extend(&val);
}
Register::Value(other_value_kind) => {
*other_value_kind = Value::Blob(val);
}
_ => {
*self = Register::Value(Value::Blob(val));
}
}
}
// Set the value of the register to NULL,
// reusing the existing Register::Value(Value::Null) if possible.
pub fn set_null(&mut self) {
match self {
Register::Value(Value::Null) => {}
Register::Value(other_value_kind) => {
*other_value_kind = Value::Null;
}
_ => {
*self = Register::Value(Value::Null);
}
}
}
/// Set the register to a generic Value, attempting to reuse backing allocation if compatible.
pub fn set_value(&mut self, val: Value) {
match self {
Register::Value(v) => {
*v = val;
}
_ => {
*self = Register::Value(val);
}
}
}
}
/// A row is a the list of registers that hold the values for a filtered row. This row is a pointer, therefore
/// after stepping again, row will be invalidated to be sure it doesn't point to somewhere unexpected.
#[derive(Debug)]
pub struct Row {
values: *const Register,
count: usize,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TxnCleanup {
None,
RollbackTxn,
/// begin_statement was called and statement is participating in an interactive transaction.
/// If statement is abandoned and/or dropped without an apparent error, we should rollback statement
/// to previous savepoint.
RollbackSavepoint,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ProgramExecutionState {
/// No steps of the program was executed
Init,
/// Program started execution but didn't reach any terminal state
Running,
/// Interrupt requested for the program
Interrupting,
/// Terminal state: program interrupted
Interrupted,
/// Terminal state: program finished successfully
Done,
/// Terminal state: program failed with error
Failed,
}
impl ProgramExecutionState {
pub const fn is_running(&self) -> bool {
matches!(
self,
ProgramExecutionState::Interrupting | ProgramExecutionState::Running
)
}
pub const fn is_terminal(&self) -> bool {
matches!(
self,
ProgramExecutionState::Interrupted
| ProgramExecutionState::Failed
| ProgramExecutionState::Done
)
}
}
/// Re-entrant state for [Insn::HashBuild].
/// Allows HashBuild to resume cleanly after async I/O without re-reading the row.
#[derive(Debug, Default)]
pub struct OpHashBuildState {
pub key_values: Vec<Value>,
pub key_idx: usize,
pub payload_values: Vec<Value>,
pub payload_idx: usize,
pub rowid: Option<i64>,
pub cursor_id: CursorID,
pub hash_table_id: usize,
pub key_start_reg: usize,
pub num_keys: usize,
}
/// Re-entrant state for [Insn::HashProbe].
/// Allows HashProbe to resume cleanly after async probe-row buffering I/O.
#[derive(Debug, Default)]
pub struct OpHashProbeState {
/// Cached probe key values to avoid re-reading from registers
pub probe_keys: Vec<Value>,
/// Hash table register being probed
pub hash_table_id: usize,
/// Partition index being loaded (if any)
pub partition_idx: usize,
/// Whether the probe row was already buffered for grace processing.
pub probe_buffered: bool,
}
enum ActiveOpState {
None,
Delete(OpDeleteState),
Destroy(OpDestroyState),
IdxDelete(OpIdxDeleteState),
IntegrityCheck(OpIntegrityCheckState),
OpenEphemeral(OpOpenEphemeralState),
Program(OpProgramState),
NewRowid(OpNewRowidState),
IdxInsert(OpIdxInsertState),
Insert(OpInsertState),
NoConflict(OpNoConflictState),
Column(OpColumnState),
RowId(OpRowIdState),
Transaction(OpTransactionState),
JournalMode(OpJournalModeState),
ParseSchema(OpParseSchemaState),
HashBuild(Option<OpHashBuildState>),
HashProbe(Option<OpHashProbeState>),
InitCdcVersion(OpInitCdcVersionState),
}
impl std::fmt::Debug for ActiveOpState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let name = match self {
ActiveOpState::None => "None",
ActiveOpState::Delete(_) => "Delete",
ActiveOpState::Destroy(_) => "Destroy",
ActiveOpState::IdxDelete(_) => "IdxDelete",
ActiveOpState::IntegrityCheck(_) => "IntegrityCheck",
ActiveOpState::OpenEphemeral(_) => "OpenEphemeral",
ActiveOpState::Program(_) => "Program",
ActiveOpState::NewRowid(_) => "NewRowid",
ActiveOpState::IdxInsert(_) => "IdxInsert",
ActiveOpState::Insert(_) => "Insert",
ActiveOpState::NoConflict(_) => "NoConflict",
ActiveOpState::Column(_) => "Column",
ActiveOpState::RowId(_) => "RowId",
ActiveOpState::Transaction(_) => "Transaction",
ActiveOpState::JournalMode(_) => "JournalMode",
ActiveOpState::ParseSchema(_) => "ParseSchema",
ActiveOpState::HashBuild(_) => "HashBuild",
ActiveOpState::HashProbe(_) => "HashProbe",
ActiveOpState::InitCdcVersion(_) => "InitCdcVersion",
};
f.write_str(name)
}
}
#[derive(Debug, Default)]
struct ActiveOpStateSlot {
state: ActiveOpState,
}
macro_rules! active_state_accessor {
($name:ident, $variant:ident, $ty:ty, $init:expr) => {
fn $name(&mut self) -> &mut $ty {
if matches!(self.state, ActiveOpState::None) {
self.state = ActiveOpState::$variant($init);
}
match &mut self.state {
ActiveOpState::$variant(state) => state,
state => unreachable!(
"active opcode state mismatch: expected {}, got {:?}",
stringify!($variant),
state
),
}
}
};
}
impl Default for ActiveOpState {
fn default() -> Self {
Self::None
}
}
impl ActiveOpStateSlot {
fn clear(&mut self) {
self.state = ActiveOpState::None;
}
active_state_accessor!(
delete,
Delete,
OpDeleteState,
OpDeleteState {
sub_state: OpDeleteSubState::MaybeCaptureRecord,
deleted_record: None,
}
);
active_state_accessor!(
destroy,
Destroy,
OpDestroyState,
OpDestroyState::CreateCursor
);
active_state_accessor!(
idx_delete,
IdxDelete,
OpIdxDeleteState,
OpIdxDeleteState::Seeking
);
active_state_accessor!(
integrity_check,
IntegrityCheck,
OpIntegrityCheckState,
OpIntegrityCheckState::Start
);
active_state_accessor!(
open_ephemeral,
OpenEphemeral,
OpOpenEphemeralState,
OpOpenEphemeralState::Start
);
active_state_accessor!(program, Program, OpProgramState, OpProgramState::Start);
active_state_accessor!(new_rowid, NewRowid, OpNewRowidState, OpNewRowidState::Start);
active_state_accessor!(
idx_insert,
IdxInsert,
OpIdxInsertState,
OpIdxInsertState::MaybeSeek
);
active_state_accessor!(
insert,
Insert,
OpInsertState,
OpInsertState {
sub_state: OpInsertSubState::MaybeCaptureRecord,
old_record: None,
is_noop_update: false,
}
);
active_state_accessor!(
no_conflict,
NoConflict,
OpNoConflictState,
OpNoConflictState::Start
);
active_state_accessor!(column, Column, OpColumnState, OpColumnState::Start);
active_state_accessor!(row_id, RowId, OpRowIdState, OpRowIdState::Start);
active_state_accessor!(
transaction,
Transaction,
OpTransactionState,
OpTransactionState::Start
);
active_state_accessor!(
journal_mode,
JournalMode,
OpJournalModeState,
OpJournalModeState::default()
);
active_state_accessor!(parse_schema, ParseSchema, OpParseSchemaState, None);
active_state_accessor!(hash_build, HashBuild, Option<OpHashBuildState>, None);
active_state_accessor!(hash_probe, HashProbe, Option<OpHashProbeState>, None);
active_state_accessor!(
init_cdc_version,
InitCdcVersion,
OpInitCdcVersionState,
None
);
fn program_ref(&self) -> Option<&OpProgramState> {
match &self.state {
ActiveOpState::Program(state) => Some(state),
_ => None,
}
}
fn program_mut(&mut self) -> Option<&mut OpProgramState> {
match &mut self.state {
ActiveOpState::Program(state) => Some(state),
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct DeferredSeekState {
pub index_cursor_id: CursorID,
pub table_cursor_id: CursorID,
}
pub(crate) enum VacuumOpState {
None,
IntoFile(Box<VacuumIntoOpContext>),
InPlace(Box<VacuumInPlaceOpContext>),
}
impl Default for VacuumOpState {
fn default() -> Self {
Self::None
}
}
/// The program state describes the environment in which the program executes.
pub struct ProgramState {
pub io_completions: Option<IOCompletions>,
pub pc: InsnReference,
pub(crate) cursors: Vec<Option<Cursor>>,
cursor_seqs: Vec<i64>,
registers: Box<[Register]>,
pub(crate) result_row: Option<Row>,
last_compare: Option<std::cmp::Ordering>,
deferred_seeks: Vec<Option<DeferredSeekState>>,
/// Indicate whether a coroutine has ended for a given yield register.
/// If an element is present, it means the coroutine with the given register number has ended.
ended_coroutine: Vec<u32>,
/// Indicate whether an [Insn::Once] instruction at a given program counter position has already been executed, well, once.
once: SmallVec<[u32; 4]>,
pub execution_state: ProgramExecutionState,
/// Per-execution statement deadline derived from the connection query timeout.
/// `None` means no timeout.
pub query_deadline: Option<crate::MonotonicInstant>,
pub parameters: Vec<Value>,
commit_state: CommitState,
#[cfg(feature = "json")]
json_cache: JsonCacheCell,
active_op_state: ActiveOpStateSlot,
seek_state: OpSeekState,
/// Metrics collected for the lifetime of this prepared statement.
pub metrics: StatementMetrics,
/// Current collation sequence set by OP_CollSeq instruction
current_collation: Option<CollationSeq>,
op_vacuum_state: VacuumOpState,
/// State machine for committing view deltas with I/O handling
view_delta_state: ViewDeltaCommitState,
/// Marker which tells about auto transaction cleanup necessary for that connection in case of reset
/// This is used when statement in auto-commit mode reseted after previous uncomplete execution - in which case we may need to rollback transaction started on previous attempt
pub(crate) auto_txn_cleanup: TxnCleanup,
pub explain_state: RwLock<ExplainState>,
/// Scratch buffer for [Insn::HashDistinct] to avoid per-row allocations.
distinct_key_values: Vec<Value>,
hash_tables: HashMap<usize, HashTable>,
/// TempFile handles for ephemeral cursors, keyed by cursor_id.
/// Dropping removes the temp file from disk.
ephemeral_temp_files: HashMap<usize, TempFile>,
/// Attached pagers that have open savepoints for statement rollback.
attached_savepoint_pagers: Vec<Arc<Pager>>,
/// Pending error to return after FAIL mode commit completes.
/// When a constraint error occurs with FAIL resolve type in autocommit mode,
/// we need to commit partial changes before returning the error.
pub(crate) pending_fail_error: Option<LimboError>,
/// Pending CDC info to apply after the program completes successfully.
/// Set by InitCdcVersion opcode, applied at Halt/Done so that if the
/// transaction rolls back, the connection's CDC state remains unchanged.
///
/// capture_data_changes has type Option<CaptureDataChangesInfo> (off mode is None)
/// so, for pending_cdc_info we wrap it in one more Option<...> layer to represent if mode changed during program execution
pub(crate) pending_cdc_info: Option<Option<CaptureDataChangesInfo>>,
/// Cached subprogram Statements keyed by the PC of the Program instruction.
/// Avoids re-allocating ProgramState on each trigger/FK-action fire.
pub(crate) subprogram_stmt_cache: HashMap<usize, Box<Statement>>,
/// RowSet objects stored by register index
rowsets: HashMap<usize, RowSet>,
/// Bloom filters stored by cursor ID for probabilistic set membership testing
/// Used to avoid unnecessary seeks on ephemeral indexes and hash tables
pub(crate) bloom_filters: HashMap<usize, BloomFilter>,
/// Number of deferred foreign key violations when the statement started.
/// When a statement subtransaction rolls back, the connection's deferred foreign key violations counter
/// is reset to this value.
fk_deferred_violations_when_stmt_started: AtomicIsize,
/// Number of immediate foreign key violations that occurred during the active statement. If nonzero,
/// the statement subtransactionwill roll back.
fk_immediate_violations_during_stmt: AtomicIsize,
uses_subjournal: bool,
/// Whether this statement is an active write inside an explicit transaction.
pub(crate) is_active_write: bool,
/// Whether begin_statement was called (savepoint + FK bookkeeping active).
has_stmt_transaction: bool,
pub n_change: AtomicI64,
}
impl std::fmt::Debug for Program {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Program").finish()
}
}
// See: https://github.com/tursodatabase/turso/issues/1552
// SAFETY: Rust cannot derive Send + Sync automatically mainly because of `Row` struct
// as it contains a `*const Register`.
// Program + Program State upholds Rust aliasing rules with `Row` by only giving out immutable references to
// the internal `result_row` and by invalidating the result row whenever the program is stepped.
unsafe impl Send for ProgramState {}
unsafe impl Sync for ProgramState {}
crate::assert::assert_send_sync!(ProgramState);
impl ProgramState {
pub fn new(max_registers: usize, max_cursors: usize) -> Self {
let cursors: Vec<Option<Cursor>> = (0..max_cursors).map(|_| None).collect();
let cursor_seqs = vec![0i64; max_cursors];
let registers = vec![Register::Value(Value::Null); max_registers].into_boxed_slice();
Self {
io_completions: None,
pc: 0,
cursors,
cursor_seqs,
registers,
result_row: None,
last_compare: None,
deferred_seeks: vec![None; max_cursors],
ended_coroutine: vec![],
once: SmallVec::<[u32; 4]>::new(),
execution_state: ProgramExecutionState::Init,
query_deadline: None,
parameters: Vec::new(),
commit_state: CommitState::Ready,
#[cfg(feature = "json")]
json_cache: JsonCacheCell::new(),
active_op_state: ActiveOpStateSlot::default(),
seek_state: OpSeekState::Start,
metrics: StatementMetrics::new(),
distinct_key_values: Vec::new(),
current_collation: None,
op_vacuum_state: VacuumOpState::None,
view_delta_state: ViewDeltaCommitState::NotStarted,
auto_txn_cleanup: TxnCleanup::None,
fk_deferred_violations_when_stmt_started: AtomicIsize::new(0),
fk_immediate_violations_during_stmt: AtomicIsize::new(0),
rowsets: HashMap::default(),
bloom_filters: HashMap::default(),
hash_tables: HashMap::default(),
ephemeral_temp_files: HashMap::default(),
uses_subjournal: false,
is_active_write: false,
has_stmt_transaction: false,
attached_savepoint_pagers: Vec::new(),
n_change: AtomicI64::new(0),
explain_state: RwLock::new(ExplainState::default()),
pending_fail_error: None,
pending_cdc_info: None,
subprogram_stmt_cache: HashMap::default(),
}
}
pub fn set_register(&mut self, idx: usize, value: Register) {
self.registers[idx] = value;
}
pub fn get_register(&self, idx: usize) -> &Register {
&self.registers[idx]
}
pub fn column_count(&self) -> usize {
self.registers.len()
}
pub fn column(&self, i: usize) -> Option<String> {
Some(format!("{:?}", self.registers[i]))
}
pub fn interrupt(&mut self) {
self.execution_state = ProgramExecutionState::Interrupting;
}
pub fn is_interrupted(&self) -> bool {
matches!(self.execution_state, ProgramExecutionState::Interrupting)
}
pub fn bind_at(&mut self, index: NonZero<usize>, value: Value) {
let i = index.get() - 1;
if i >= self.parameters.len() {
self.parameters.resize(i + 1, Value::Null);
}
let slot = &mut self.parameters[i];
match (slot, value) {
(Value::Null, Value::Null) => {}
(Value::Numeric(Numeric::Integer(existing)), Value::Numeric(Numeric::Integer(new))) => {
*existing = new
}
(Value::Numeric(Numeric::Float(existing)), Value::Numeric(Numeric::Float(new))) => {
*existing = new
}
(Value::Text(existing), Value::Text(new)) => existing.do_extend(&new),
(Value::Blob(existing), Value::Blob(new)) => existing.do_extend(&new),
(slot, value) => *slot = value,
}
}
pub fn clear_bindings(&mut self) {
self.parameters.clear();
}
pub fn get_parameter(&self, index: NonZero<usize>) -> Value {
let i = index.get() - 1;
self.parameters.get(i).cloned().unwrap_or(Value::Null)
}
pub fn reset(&mut self, max_registers: Option<usize>, max_cursors: Option<usize>) {
self.io_completions = None;
self.pc = 0;
if let Some(max_cursors) = max_cursors {
self.cursors.resize_with(max_cursors, || None);
self.cursor_seqs.resize(max_cursors, 0);
self.deferred_seeks.resize(max_cursors, None);
}
self.result_row = None;
if let Some(max_registers) = max_registers {
// into_vec and into_boxed_slice do not allocate
let mut registers = std::mem::take(&mut self.registers).into_vec();
// As we are dropping whatever is in the result row, we can be sure that no one is referencing values from `*const Register` inside `Row`.
registers.resize_with(max_registers, || Register::Value(Value::Null));
self.registers = registers.into_boxed_slice();
}
// reset cursors as they can have cached information which will be no longer relevant on next program execution
self.cursors.iter_mut().for_each(|c| {
let _ = c.take();
});
for r in self.registers.iter_mut() {
match r {
Register::Value(v) => *v = Value::Null,
_ => r.set_null(),
}
}
self.last_compare = None;
self.deferred_seeks.iter_mut().for_each(|s| *s = None);
self.ended_coroutine.clear();
self.once.clear();
self.execution_state = ProgramExecutionState::Init;
self.query_deadline = None;
self.current_collation = None;
#[cfg(feature = "json")]
self.json_cache.clear();
// A caller can reset or drop a statement after an MVCC auto-checkpoint
// has yielded I/O. Waiting for that I/O does not step the nested
// CheckpointStateMachine again, so release its checkpoint lock before
// replacing commit_state with Ready.
self.commit_state.cleanup_mvcc_checkpoint_state();
self.active_op_state.clear();
self.seek_state = OpSeekState::Start;
self.current_collation = None;
self.commit_state = CommitState::Ready;
self.op_vacuum_state = VacuumOpState::None;
self.view_delta_state = ViewDeltaCommitState::NotStarted;
self.auto_txn_cleanup = TxnCleanup::None;
self.fk_immediate_violations_during_stmt
.store(0, Ordering::SeqCst);
self.fk_deferred_violations_when_stmt_started
.store(0, Ordering::SeqCst);
self.rowsets.clear();
self.bloom_filters.clear();
self.hash_tables.clear();
self.ephemeral_temp_files.clear();
self.uses_subjournal = false;
self.is_active_write = false;
self.has_stmt_transaction = false;
self.distinct_key_values.clear();
self.attached_savepoint_pagers.clear();
self.n_change.store(0, Ordering::SeqCst);
*self.explain_state.write() = ExplainState::default();
self.pending_fail_error = None;
self.pending_cdc_info = None;
self.subprogram_stmt_cache.clear();
}
/// Whether this statement owns the implicit autocommit transaction it is
/// about to finish, including re-entry while its commit is in progress.
#[inline]
pub(crate) fn owns_auto_txn(&self) -> bool {
self.auto_txn_cleanup == TxnCleanup::RollbackTxn
|| !matches!(self.commit_state, CommitState::Ready)
}
#[inline]
pub fn record_rows_read(&mut self, count: u64) {
self.metrics.rows_read = self.metrics.rows_read.saturating_add(count);
}
#[inline]
pub fn record_rows_written(&mut self, count: u64) {
self.metrics.rows_written = self.metrics.rows_written.saturating_add(count);
}
pub(crate) fn metrics(&self) -> StatementMetrics {
let mut metrics = self.metrics.clone();
if let Some(OpProgramState::Step { statement, .. }) = self.active_op_state.program_ref() {
metrics.merge(&statement.metrics());
}
for statement in self.subprogram_stmt_cache.values() {
metrics.merge(&statement.metrics());
}
metrics
}
pub(crate) fn reset_metrics(&mut self) {
self.metrics.reset();
if let Some(OpProgramState::Step { statement, .. }) = self.active_op_state.program_mut() {
statement.reset_metrics();
}
for statement in self.subprogram_stmt_cache.values_mut() {
statement.reset_metrics();
}
}
pub(crate) fn reset_stmt_status(&mut self, counter: crate::statement::StatementStatusCounter) {
match counter {
crate::statement::StatementStatusCounter::FullscanStep => {
self.metrics.fullscan_steps = 0
}
crate::statement::StatementStatusCounter::Sort => self.metrics.sort_operations = 0,
crate::statement::StatementStatusCounter::VmStep => self.metrics.insn_executed = 0,
crate::statement::StatementStatusCounter::Reprepare => self.metrics.reprepares = 0,
crate::statement::StatementStatusCounter::RowsRead => self.metrics.rows_read = 0,
crate::statement::StatementStatusCounter::RowsWritten => self.metrics.rows_written = 0,
}
if let Some(OpProgramState::Step { statement, .. }) = self.active_op_state.program_mut() {
statement.reset_stmt_status(counter);
}
for statement in self.subprogram_stmt_cache.values_mut() {
statement.reset_stmt_status(counter);
}
}
pub fn get_cursor(&mut self, cursor_id: CursorID) -> &mut Cursor {
self.cursors
.get_mut(cursor_id)
.unwrap_or_else(|| panic!("cursor id {cursor_id} out of bounds"))
.as_mut()
.unwrap_or_else(|| panic!("cursor id {cursor_id} is None"))
}
/// Begin a statement subtransaction.
///
/// Creates a savepoint on the main DB's MvStore (or pager for WAL mode),
/// and snapshots FK violation counters for potential statement rollback.
/// Attached DB savepoints are opened per-DB in `op_transaction_inner`
/// when each DB's Transaction opcode is executed.
///
/// Pager/MVCC savepoints are only opened for write statements inside an
/// explicit transaction. In autocommit mode, a statement abort is a
/// transaction abort, so savepoints are unnecessary.
pub fn begin_statement(
&mut self,
connection: &Connection,
pager: &Arc<Pager>,
write: bool,
) -> Result<IOResult<()>> {
let in_explicit_txn = !connection.auto_commit.load(Ordering::SeqCst);
if write && in_explicit_txn {
// Check if MVCC is active - if so, use MVCC savepoints instead of pager savepoints
if let Some(mv_store) = connection.mv_store().as_ref() {
if let Some(tx_id) = connection.get_mv_tx_id() {
mv_store.begin_savepoint(tx_id);
}
} else {
// Non-MVCC mode: use pager savepoints
let db_size = return_if_io!(pager.with_header(|header| header.database_size.get()));
pager.open_subjournal()?;
pager.try_use_subjournal()?;
let result = pager.open_savepoint(db_size);
if result.is_err() {
pager.stop_use_subjournal();
}
result?;
self.uses_subjournal = true;
}
}
self.has_stmt_transaction = true;
// Store the deferred foreign key violations counter at the start of the statement.
// This is used to ensure that if an interactive transaction had deferred FK violations and a statement subtransaction rolls back,
// the deferred FK violations are not lost.
self.fk_deferred_violations_when_stmt_started.store(
connection.fk_deferred_violations.load(Ordering::Acquire),
Ordering::SeqCst,
);
// Reset the immediate foreign key violations counter to 0. If this is nonzero when the statement completes, the statement subtransaction will roll back.
self.fk_immediate_violations_during_stmt
.store(0, Ordering::Release);
Ok(IOResult::Done(()))
}
/// End a statement subtransaction.
///
/// Mirrors SQLite's vdbeCloseStatement (vdbeaux.c:3203-3248). Pager/MVCC
/// savepoint management and FK violation counter restoration are independent
/// concerns: pager savepoints may be skipped (e.g. autocommit optimization)
/// while FK bookkeeping still needs cleanup.
pub fn end_statement(
&mut self,
connection: &Connection,
pager: &Arc<Pager>,
end_statement: EndStatement,
) -> Result<()> {
if self.is_active_write {
connection.n_active_writes.fetch_sub(1, Ordering::SeqCst);
self.is_active_write = false;
}
// If begin_statement was never called, no savepoint/FK cleanup needed.
if !self.has_stmt_transaction {
return Ok(());
}
self.has_stmt_transaction = false;
// Drain attached pagers upfront so we can clean them up regardless of path.
let attached_pagers: Vec<Arc<Pager>> = self.attached_savepoint_pagers.drain(..).collect();
let result = match end_statement {
EndStatement::ReleaseSavepoint => {
if let Some(mv_store) = connection.mv_store().as_ref() {
if let Some(tx_id) = connection.get_mv_tx_id() {
mv_store.release_savepoint(tx_id);
}
connection.for_each_attached_mv_tx(|db_id, tx_id| {
if let Some(attached_mv) = connection.mv_store_for_db(db_id) {
attached_mv.release_savepoint(tx_id);
}
});
Ok(())
} else if self.uses_subjournal || !attached_pagers.is_empty() {
if self.uses_subjournal {
pager.release_savepoint()?;
}
for p in &attached_pagers {
p.release_savepoint()?;
}
Ok(())
} else {
Ok(())
}
}
EndStatement::RollbackSavepoint => {
// Rollback pager/MVCC savepoint if one was opened.
let pager_err = if let Some(mv_store) = connection.mv_store().as_ref() {
let mut err = None;
if let Some(tx_id) = connection.get_mv_tx_id() {
if let Err(e) = mv_store.rollback_first_savepoint(tx_id) {
err = Some(e);
}
}
connection.for_each_attached_mv_tx(|db_id, tx_id| {
if let Some(attached_mv) = connection.mv_store_for_db(db_id) {
if let Err(e) = attached_mv.rollback_first_savepoint(tx_id) {
if err.is_none() {
err = Some(e);
}
}
}
});
err
} else if self.uses_subjournal {
match pager.rollback_to_newest_savepoint() {
Ok(_) => {
let mut err = None;
for p in &attached_pagers {
if let Err(e) = p.rollback_to_newest_savepoint() {
err = Some(e);
break;
}
}
err
}
Err(e) => Some(e),
}
} else if !attached_pagers.is_empty() {
let mut err = None;
for p in &attached_pagers {
if let Err(e) = p.rollback_to_newest_savepoint() {
err = Some(e);
}
}
err
} else {
None
};
// Always restore FK violation counters on statement rollback,
// regardless of whether a pager savepoint was opened.
// Mirrors SQLite's vdbeCloseStatement (vdbeaux.c:3243-3246).
connection.fk_deferred_violations.store(
self.fk_deferred_violations_when_stmt_started
.load(Ordering::Acquire),
Ordering::SeqCst,
);
match pager_err {
Some(e) => Err(e),
None => Ok(()),
}
}
};
if self.uses_subjournal {
pager.stop_use_subjournal();
self.uses_subjournal = false;
}
for p in &attached_pagers {
p.stop_use_subjournal();
}
result
}
/// Gets or creates a bloom filter for the given cursor ID.
pub fn get_or_create_bloom_filter(&mut self, cursor_id: usize) -> &mut BloomFilter {
self.bloom_filters.entry(cursor_id).or_default()
}
/// Gets or creates a bloom filter with a specific capacity for the given cursor ID.
pub fn get_or_create_bloom_filter_with_capacity(
&mut self,
cursor_id: usize,
expected_items: u32,
false_positive_rate: f32,
) -> &mut BloomFilter {
self.bloom_filters
.entry(cursor_id)
.or_insert_with(|| BloomFilter::with_capacity(expected_items, false_positive_rate))
}
/// Gets an existing bloom filter for the given cursor ID.
pub fn get_bloom_filter(&self, cursor_id: usize) -> Option<&BloomFilter> {
self.bloom_filters.get(&cursor_id)
}
/// Gets a mutable reference to an existing bloom filter for the given cursor ID.
pub fn get_bloom_filter_mut(&mut self, cursor_id: usize) -> Option<&mut BloomFilter> {
self.bloom_filters.get_mut(&cursor_id)
}
/// Removes and drops the bloom filter for the given cursor ID.
pub fn remove_bloom_filter(&mut self, cursor_id: usize) {
self.bloom_filters.remove(&cursor_id);
}
/// Checks if a bloom filter exists for the given cursor ID.
pub fn has_bloom_filter(&self, cursor_id: usize) -> bool {
self.bloom_filters.contains_key(&cursor_id)
}
pub fn get_fk_immediate_violations_during_stmt(&self) -> isize {
self.fk_immediate_violations_during_stmt
.load(Ordering::Acquire)
}
pub fn increment_fk_immediate_violations_during_stmt(&self, v: isize) {
self.fk_immediate_violations_during_stmt
.fetch_add(v, Ordering::AcqRel);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Action to take at the end of a statement subtransaction.
pub enum EndStatement {
/// Release (commit) the savepoint -- effectively removing the savepoint as it is no longer needed for undo purposes.
ReleaseSavepoint,
/// Rollback (abort) to the newest savepoint: read pages from the subjournal and restore them to the page cache.
/// This is used to undo the changes made by the statement.
RollbackSavepoint,
}
impl Register {
pub fn get_value(&self) -> &Value {
match self {
Register::Value(v) => v,
Register::Record(r) => {
turso_assert!(!r.is_invalidated());
r.as_blob_value()
}
_ => panic!("register holds unexpected value: {self:?}"),
}
}
}
#[macro_export]
macro_rules! must_be_btree_cursor {
($cursor_id:expr, $cursor_ref:expr, $state:expr, $insn_name:expr) => {{
let (_, cursor_type) = $cursor_ref.get($cursor_id).unwrap();
if matches!(
cursor_type,
CursorType::BTreeTable(_)
| CursorType::BTreeIndex(_)
| CursorType::MaterializedView(_, _)
) {
$crate::get_cursor!($state, $cursor_id)
} else {
panic!("{} on unexpected cursor", $insn_name)
}
}};
}
/// Macro is necessary to help the borrow checker see we are only accessing state.cursor field
/// and nothing else
#[macro_export]
macro_rules! get_cursor {
($state:expr, $cursor_id:expr) => {
$state
.cursors
.get_mut($cursor_id)
.unwrap_or_else(|| panic!("cursor id {} out of bounds", $cursor_id))
.as_mut()
.unwrap_or_else(|| panic!("cursor id {} is None", $cursor_id))
};
}
/// Tracks the state of explain mode execution, including which subprograms need to be processed.
#[derive(Default)]
pub struct ExplainState {
/// Subprograms queued for explain output, processed after the parent program finishes.
pending: std::collections::VecDeque<Arc<PreparedProgram>>,
/// The subprogram currently being explained, if any.
current: Option<Arc<PreparedProgram>>,
}
#[derive(Debug, Clone)]
pub struct PreparedProgram {
pub max_registers: usize,
// we store original indices because we don't want to create new vec from
// ProgramBuilder
pub insns: Vec<(Insn, usize)>,
pub cursor_ref: Vec<(Option<CursorKey>, CursorType)>,
pub comments: Vec<(InsnReference, &'static str)>,
pub parameters: crate::parameters::Parameters,
pub change_cnt_on: bool,
/// Flag that detect if the sqlite statement will directly manipulate the database file.\
/// mirrors: https://sqlite.org/c3ref/stmt_readonly.html.
pub readonly: bool,
pub result_columns: Vec<ResultSetColumn>,
pub table_references: TableReferences,
pub sql: String,
/// Whether the statement needs to be wrapped in a statement subtransaction
/// when run as part of an interactive (non-autocommit) transaction.
/// See [crate::vdbe::builder::ProgramBuilder::is_multi_write] and [crate::vdbe::builder::ProgramBuilder::may_abort] for more details.
pub needs_stmt_subtransactions: Arc<AtomicBool>,
/// If this Program is a trigger subprogram, a ref to the trigger is stored here.
pub trigger: Option<Arc<Trigger>>,
/// Whether this program is a subprogram (trigger or FK action) that runs within a parent statement.
pub is_subprogram: bool,
/// Whether the program contains any trigger subprograms.
pub contains_trigger_subprograms: bool,
pub resolve_type: ResolveType,
pub prepare_context: PrepareContext,
/// Set of attached database indices that need write transactions.
pub write_databases: BitSet,
/// Set of attached database indices that need read transactions.
pub read_databases: BitSet,
}
#[derive(Clone)]
pub struct Program {
pub(crate) prepared: Arc<PreparedProgram>,
pub connection: Arc<Connection>,
}
/// Captures connection settings at statement preparation time for cache invalidation.
///
/// This struct is used to detect when a cached prepared statement needs to be recompiled
/// because relevant connection settings have changed. When `matches_connection()` returns
/// false, the statement will be automatically reprepared before execution.
///
/// # Adding New Fields
///
/// If you add a new setting to `Connection` that affects statement compilation or execution,
/// When adding a new connection setting that affects query compilation, you MUST call
/// `bump_prepare_context_generation()` in its setter so that prepared statements know
/// they need to be reprepared.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrepareContext {
/// Identity check: the prepared statement must belong to the same database.
database_ptr: usize,
/// Generation counter snapshot taken at prepare time. Compared against the
/// connection's current generation to detect setting changes (pragmas,
/// attach/detach, extension registration, etc.) without rebuilding the full
/// context on every step.
generation: u64,
}
impl PrepareContext {
pub fn from_connection(connection: &Connection) -> Self {
Self {
database_ptr: connection.database_ptr(),
generation: connection.prepare_context_generation(),
}
}
#[inline]
pub fn matches_connection(&self, connection: &Connection) -> bool {
self.database_ptr == connection.database_ptr()
&& self.generation == connection.prepare_context_generation()
}
}
impl PreparedProgram {
pub fn bind(self: Arc<Self>, connection: Arc<Connection>) -> Program {
Program {
prepared: self,
connection,
}
}
pub fn is_compatible_with(&self, connection: &Connection) -> bool {
self.prepare_context.matches_connection(connection)
}
#[inline]
pub const fn is_readonly(&self) -> bool {
self.readonly
}
}
impl Program {
#[inline]
pub fn prepared(&self) -> &Arc<PreparedProgram> {
&self.prepared
}
pub fn from_prepared(prepared: Arc<PreparedProgram>, connection: Arc<Connection>) -> Self {
Self {
prepared,
connection,
}
}
#[inline]
pub fn is_readonly(&self) -> bool {
self.prepared().is_readonly()
}
}
impl Program {
fn get_pager_from_database_index(&self, idx: &usize) -> Result<Arc<Pager>> {
self.connection.get_pager_from_database_index(idx)
}
#[inline]
fn maybe_request_interrupt<I>(&self, state: &mut ProgramState, io: &I) -> bool
where
I: crate::IO + ?Sized,
{
let connection_interrupt = self.connection.is_interrupted();
let hit_query_deadline = state
.query_deadline
.is_some_and(|deadline| io.current_time_monotonic() >= deadline);
let progress_interrupt = self
.connection
.should_interrupt_for_progress(state.metrics.vm_steps);
if connection_interrupt || hit_query_deadline || progress_interrupt {
state.interrupt();
}
state.is_interrupted()
}
#[turso_macros::trace_stack]
pub fn step(
&self,
state: &mut ProgramState,
pager: &Arc<Pager>,
query_mode: QueryMode,
waker: Option<&Waker>,
) -> Result<StepResult> {
state.execution_state = ProgramExecutionState::Running;
let result = match query_mode {
QueryMode::Normal => self.normal_step(state, pager, waker),
QueryMode::Explain => self.explain_step(state, pager),
QueryMode::ExplainQueryPlan => self.explain_query_plan_step(state, pager),
};
match &result {
Ok(StepResult::Done) => {
state.execution_state = ProgramExecutionState::Done;
}
Ok(StepResult::Interrupt) => {
state.execution_state = ProgramExecutionState::Interrupted;
}
Err(_) => {
state.execution_state = ProgramExecutionState::Failed;
}
_ => {}
}
result
}
fn explain_step(&self, state: &mut ProgramState, pager: &Arc<Pager>) -> Result<StepResult> {
turso_debug_assert!(state.column_count() == EXPLAIN_COLUMNS.len());
if self.connection.is_closed() {
let tx_state = self.connection.get_tx_state();
if let TransactionState::Write { .. } = tx_state {
pager.rollback_tx(&self.connection);
}
return Err(LimboError::InternalError("Connection closed".to_string()));
}
if self.maybe_request_interrupt(state, pager.io.as_ref()) {
return Ok(StepResult::Interrupt);
}
state.metrics.vm_steps = state.metrics.vm_steps.saturating_add(1);
let mut explain_state = state.explain_state.write();
// Advance to the next subprogram if the current one is finished
loop {
if let Some(ref current) = explain_state.current {
if (state.pc as usize) < current.insns.len() {
break;
}
} else if (state.pc as usize) < self.insns.len() {
break;
}
// Current program is done, pop next subprogram from queue
if let Some(next) = explain_state.pending.pop_front() {
explain_state.current = Some(next);
state.pc = 0;
} else {
explain_state.current = None;
return Ok(StepResult::Done);
}
}
let pc = state.pc as usize;
// Explain the current instruction from the active program.
// We collect subprograms separately to avoid borrow conflicts with explain_state.
let (row, subprogram) = if let Some(ref current) = explain_state.current {
let (insn, _) = ¤t.insns[pc];
let sub = if let Insn::Program {
program: prepared, ..
} = insn
{
Some(prepared.clone())
} else {
None
};
let comment = current
.comments
.iter()
.find(|(offset, _)| *offset == state.pc)
.map(|(_, c)| *c);
(insn_to_row_with_comment(current, insn, comment), sub)
} else {
let (insn, _) = &self.insns[pc];
let sub = if let Insn::Program {
program: prepared, ..
} = insn
{
Some(prepared.clone())
} else {
None
};
let comment = self
.comments
.iter()
.find(|(offset, _)| *offset == state.pc)
.map(|(_, c)| *c);
(insn_to_row_with_comment(self, insn, comment), sub)
};
if let Some(sub) = subprogram {
explain_state.pending.push_back(sub);
}
let (opcode, p1, p2, p3, p4, p5, comment) = row;
state.registers[0].set_int(state.pc as i64);
state.registers[1].set_value(Value::from_text(opcode));
state.registers[2].set_int(p1);
state.registers[3].set_int(p2);
state.registers[4].set_int(p3);
state.registers[5].set_value(p4);
state.registers[6].set_int(p5);
state.registers[7].set_value(Value::from_text(comment));
state.result_row = Some(Row {
values: &state.registers[0] as *const Register,
count: EXPLAIN_COLUMNS.len(),
});
state.pc += 1;
Ok(StepResult::Row)
}
fn explain_query_plan_step(
&self,
state: &mut ProgramState,
pager: &Arc<Pager>,
) -> Result<StepResult> {
turso_debug_assert!(state.column_count() == EXPLAIN_QUERY_PLAN_COLUMNS.len());
loop {
if self.connection.is_closed() {
// Connection is closed for whatever reason, rollback the transaction.
let state = self.connection.get_tx_state();
if let TransactionState::Write { .. } = state {
pager.rollback_tx(&self.connection);
}
return Err(LimboError::InternalError("Connection closed".to_string()));
}
if self.maybe_request_interrupt(state, pager.io.as_ref()) {
return Ok(StepResult::Interrupt);
}
// FIXME: do we need this?
state.metrics.vm_steps = state.metrics.vm_steps.saturating_add(1);
if state.pc as usize >= self.insns.len() {
return Ok(StepResult::Done);
}
let Insn::Explain { p1, p2, detail } = &self.insns[state.pc as usize].0 else {
state.pc += 1;
continue;
};
state.registers[0].set_int(*p1 as i64);
state.registers[1] =
Register::Value(Value::from_i64(p2.as_ref().map(|p| *p).unwrap_or(0) as i64));
state.registers[2].set_int(0);
state.registers[3].set_value(Value::from_text(detail.clone()));
state.result_row = Some(Row {
values: &state.registers[0] as *const Register,
count: EXPLAIN_QUERY_PLAN_COLUMNS.len(),
});
state.pc += 1;
return Ok(StepResult::Row);
}
}
#[instrument(skip_all, level = Level::DEBUG)]
fn normal_step(
&self,
state: &mut ProgramState,
pager: &Arc<Pager>,
waker: Option<&Waker>,
) -> Result<StepResult> {
let enable_tracing = tracing::enabled!(tracing::Level::TRACE);
loop {
if self.connection.is_closed() {
// Connection is closed for whatever reason, rollback the transaction.
let state = self.connection.get_tx_state();
if let TransactionState::Write { .. } = state {
pager.rollback_tx(&self.connection);
}
return Err(LimboError::InternalError("Connection closed".to_string()));
}
if self.maybe_request_interrupt(state, pager.io.as_ref()) {
self.abort(pager, None, state)?;
return Ok(StepResult::Interrupt);
}
if let Some(io) = &state.io_completions {
if !io.finished() {
io.set_waker(waker);
return Ok(StepResult::IO);
}
if let Some(err) = io.get_error() {
if pager.is_checkpointing() {
// Wrap IO errors that occurred during checkpointing in CheckpointFailed error,
// so that abort() knows not to try to rollback the transaction, because the transaction
// is already durable in the WAL and hence committed.
// This also lets the simulator know that it should shadow the results of the query because
// the write itself succeeded.
let checkpoint_err = LimboError::CheckpointFailed(err.to_string());
tracing::error!("Checkpoint failed: {checkpoint_err}");
if let Err(abort_err) = self.abort(pager, Some(&checkpoint_err), state) {
tracing::error!(
"Abort also failed during checkpoint error handling: {abort_err}"
);
}
return Err(checkpoint_err);
}
let err = err.into();
if let Err(abort_err) = self.abort(pager, Some(&err), state) {
tracing::error!("Abort failed during error handling: {abort_err}");
}
return Err(err);
}
state.io_completions = None;
}
// invalidate row
let _ = state.result_row.take();
let (insn, _) = &self.insns[state.pc as usize];
let insn_function = insn.to_function();
if enable_tracing {
trace_insn(self, state.pc as InsnReference, insn);
crate::stack::trace_remaining("program_step:opcode");
}
// Always increment VM steps for every loop iteration
state.metrics.vm_steps = state.metrics.vm_steps.saturating_add(1);
match insn_function(self, state, insn, pager) {
Ok(InsnFunctionStepResult::Step) => {
// Instruction completed, moving to next
state.metrics.insn_executed = state.metrics.insn_executed.saturating_add(1);
}
Ok(InsnFunctionStepResult::Done) => {
// Instruction completed execution
state.metrics.insn_executed = state.metrics.insn_executed.saturating_add(1);
state.auto_txn_cleanup = TxnCleanup::None;
return Ok(StepResult::Done);
}
Ok(InsnFunctionStepResult::IO(io)) => {
// Instruction not complete - waiting for I/O, will resume at same PC
io.set_waker(waker);
let is_yield = io.is_explicit_yield();
if is_yield {
// Yield: return control to the cooperative scheduler so
// other connections can make progress (e.g. release a
// contended lock). Don't store in io_completions —
// yields aren't pending I/O, so the instruction will
// simply re-execute on the next step.
return Ok(StepResult::IO);
}
let finished = io.finished();
state.io_completions = Some(io);
if !finished {
return Ok(StepResult::IO);
}
// just continue the outer loop if IO is finished so db will continue execution immediately
}
Ok(InsnFunctionStepResult::Row) => {
// Instruction completed (ResultRow already incremented PC)
state.metrics.insn_executed = state.metrics.insn_executed.saturating_add(1);
return Ok(StepResult::Row);
}
Err(LimboError::Busy) => {
// Instruction blocked - will retry at same PC
return Ok(StepResult::Busy);
}
Err(LimboError::BusySnapshot)
if self.connection.transaction_state.get() == TransactionState::None =>
{
// For interactive transactions that are already in a read transaction, retrying BusySnapshot is pointless
// because the snapshot will continue to be stale no matter how many times we retry.
// However, for auto-commits or BEGIN IMMEDIATE, failing to promote to write transaction means it was rolled
// back, so auto-retrying can be useful.
return Ok(StepResult::Busy);
}
Err(err) => {
if let Err(abort_err) = self.abort(pager, Some(&err), state) {
tracing::error!("Abort failed during error handling: {abort_err}");
}
return Err(err);
}
}
}
}
#[instrument(skip_all, level = Level::DEBUG)]
fn apply_view_deltas(
&self,
state: &mut ProgramState,
rollback: bool,
pager: &Arc<Pager>,
) -> Result<IOResult<()>> {
use crate::types::IOResult;
loop {
match &state.view_delta_state {
ViewDeltaCommitState::NotStarted => {
if self.connection.view_transaction_states.is_empty() {
return Ok(IOResult::Done(()));
}
if rollback {
// On rollback, just clear and done
self.connection.view_transaction_states.clear();
return Ok(IOResult::Done(()));
}
// Not a rollback - proceed with processing
let schema = self.connection.schema.read();
// Collect materialized views - they should all have storage
let mut views = Vec::new();
for view_name in self.connection.view_transaction_states.get_view_names() {
if let Some(view_mutex) = schema.get_materialized_view(&view_name) {
let view = view_mutex.lock();
let root_page = view.get_root_page();
// Materialized views should always have storage (root_page != 0)
turso_assert_ne!(
root_page, 0,
"Materialized view should have a root page",
{ "view_name": view_name }
);
views.push(view_name);
}
}
state.view_delta_state = ViewDeltaCommitState::Processing {
views,
current_index: 0,
};
}
ViewDeltaCommitState::Processing {
views,
current_index,
} => {
// At this point we know it's not a rollback
if *current_index >= views.len() {
// All done, clear the transaction states
self.connection.view_transaction_states.clear();
state.view_delta_state = ViewDeltaCommitState::Done;
return Ok(IOResult::Done(()));
}
let view_name = &views[*current_index];
let table_deltas = self
.connection
.view_transaction_states
.get(view_name)
.expect("view should have transaction state")
.get_table_deltas();
let schema = self.connection.schema.read();
if let Some(view_mutex) = schema.get_materialized_view(view_name) {
let mut view = view_mutex.lock();
// Create a DeltaSet from the per-table deltas
let mut delta_set = crate::incremental::compiler::DeltaSet::new();
for (table_name, delta) in table_deltas {
delta_set.insert(table_name, delta);
}
// Handle I/O from merge_delta - pass pager, circuit will create its own cursor
match view.merge_delta(delta_set, pager.clone())? {
IOResult::Done(_) => {
// Move to next view
state.view_delta_state = ViewDeltaCommitState::Processing {
views: views.clone(),
current_index: current_index + 1,
};
}
IOResult::IO(io) => {
// Return I/O, will resume at same index
return Ok(IOResult::IO(io));
}
}
}
}
ViewDeltaCommitState::Done => {
return Ok(IOResult::Done(()));
}
}
}
}
pub fn commit_txn(
&self,
pager: Arc<Pager>,
program_state: &mut ProgramState,
mv_store: Option<&Arc<MvStore>>,
rollback: bool,
) -> Result<IOResult<()>> {
// Apply view deltas with I/O handling
match self.apply_view_deltas(program_state, rollback, &pager)? {
IOResult::IO(io) => return Ok(IOResult::IO(io)),
IOResult::Done(_) => {}
}
// Reset state for next use
program_state.view_delta_state = ViewDeltaCommitState::NotStarted;
let tx_state = self.connection.get_tx_state();
if tx_state == TransactionState::None
&& matches!(program_state.commit_state, CommitState::Ready)
{
// No main transaction and no in-progress commit — check whether
// any attached/temp database still has an active transaction before
// bailing out. Defer these checks to here so the common case
// (active main transaction) doesn't pay for the lock reads.
let has_attached_mv_tx = self.connection.next_attached_mv_tx().is_some();
let has_attached_wal_tx =
self.connection
.with_all_attached_pagers_with_index(|pagers| {
pagers.iter().any(|(_, pager)| pager.holds_read_lock())
});
if !has_attached_mv_tx && !has_attached_wal_tx {
return Ok(IOResult::Done(()));
}
}
if self.connection.is_nested_stmt() {
// We don't want to commit on nested statements. Let parent handle it.
return Ok(IOResult::Done(()));
}
let res = if let Some(mv_store) = mv_store {
self.commit_txn_mvcc(pager, program_state, mv_store, rollback)
} else {
self.commit_txn_wal(pager, program_state, rollback)
}?;
if !res.is_io() {
if self.change_cnt_on {
self.connection
.set_changes(program_state.n_change.load(Ordering::SeqCst));
}
let transaction_finished = self.connection.auto_commit.load(Ordering::SeqCst)
&& self.connection.get_tx_state() == TransactionState::None;
if transaction_finished {
// Finalize the in-memory TEMP schema only when the outer
// transaction actually finishes. Updating the committed temp
// snapshot after every statement inside an explicit
// transaction would make a later full ROLLBACK restore
// uncommitted temp DDL.
if rollback {
self.connection.rollback_temp_schema();
} else {
self.connection.commit_temp_schema();
}
}
}
Ok(res)
}
fn commit_txn_wal(
&self,
pager: Arc<Pager>,
program_state: &mut ProgramState,
rollback: bool,
) -> Result<IOResult<()>> {
let connection = self.connection.clone();
let auto_commit = connection.auto_commit.load(Ordering::SeqCst);
let tx_state = connection.get_tx_state();
tracing::debug!(
"Halt auto_commit {}, commit_state={:?}, tx_state={:?}",
auto_commit,
program_state.commit_state,
tx_state,
);
if matches!(program_state.commit_state, CommitState::Committing) {
let TransactionState::Write { .. } = tx_state else {
unreachable!("invalid state for write commit step")
};
self.step_end_write_txn(&pager, &connection, program_state, rollback)
} else if matches!(program_state.commit_state, CommitState::CommittingAttached) {
// Re-entry after IO yield from attached pager commit.
match self.end_attached_write_txns(&connection, rollback)? {
IOResult::Done(_) => {
program_state.commit_state = CommitState::Ready;
if pager.holds_read_lock() {
pager.end_read_tx();
}
self.end_attached_read_txns(&connection);
Ok(IOResult::Done(()))
}
IOResult::IO(io) => Ok(IOResult::IO(io)),
}
} else if auto_commit {
match tx_state {
TransactionState::Write { .. } => {
self.step_end_write_txn(&pager, &connection, program_state, rollback)
}
TransactionState::Read => {
connection.set_tx_state(TransactionState::None);
// Commit any attached write transactions that were opened
// independently of the main connection's transaction state.
// (e.g., UPDATE aux0.t SET ... only needs Read on main DB
// but holds a write lock on the attached pager.)
match self.end_attached_write_txns(&connection, rollback)? {
IOResult::Done(_) => {}
IOResult::IO(io) => {
program_state.commit_state = CommitState::CommittingAttached;
return Ok(IOResult::IO(io));
}
}
pager.end_read_tx();
self.end_attached_read_txns(&connection);
Ok(IOResult::Done(()))
}
TransactionState::None => {
match self.end_attached_write_txns(&connection, rollback)? {
IOResult::Done(_) => {}
IOResult::IO(io) => {
program_state.commit_state = CommitState::CommittingAttached;
return Ok(IOResult::IO(io));
}
}
self.end_attached_read_txns(&connection);
Ok(IOResult::Done(()))
}
TransactionState::PendingUpgrade { .. } => {
panic!("Unexpected transaction state: {tx_state:?} during auto-commit",)
}
}
} else {
Ok(IOResult::Done(()))
}
}
/// Commit MVCC transactions across all databases in a multi-phase protocol:
///
/// 1. **Main DB MVCC** — commit the main database's MvStore transaction.
/// 2. **Attached MVCC** — commit each attached database's MvStore transaction.
/// 3. **Attached WAL** — flush dirty pages on attached databases that use WAL
/// (e.g. :memory: attached while main is MVCC).
///
/// **IMPORTANT**: This multi-phase commit is NOT atomic across databases.
/// A crash between phases can leave the main and attached databases in
/// inconsistent states (main committed, some attached DBs not committed).
/// This matches SQLite's WAL mode behavior — cross-file atomicity only
/// exists in legacy rollback journal mode, which we do not support.
fn commit_txn_mvcc(
&self,
pager: Arc<Pager>,
program_state: &mut ProgramState,
mv_store: &Arc<MvStore>,
rollback: bool,
) -> Result<IOResult<()>> {
let conn = self.connection.clone();
let auto_commit = conn.auto_commit.load(Ordering::SeqCst);
if !auto_commit {
return Ok(IOResult::Done(()));
}
// Phase 1: Commit main DB MVCC transaction
if matches!(program_state.commit_state, CommitState::Ready) {
if let Some(tx_id) = conn.get_mv_tx_id() {
let state_machine = mv_store.commit_tx(tx_id, &conn, crate::MAIN_DB_ID)?;
program_state.commit_state = CommitState::CommittingMvcc { state_machine };
}
// If no main MVCC tx, commit_state stays Ready and we fall
// through directly to phase 2 (the CommittingMvcc and
// CommittingAttachedMvcc checks will both miss).
}
if matches!(
program_state.commit_state,
CommitState::CommittingMvcc { .. }
) {
let CommitState::CommittingMvcc { state_machine } = &mut program_state.commit_state
else {
unreachable!()
};
match self.step_end_mvcc_txn(state_machine, mv_store)? {
IOResult::Done(_) => {
assert!(state_machine.is_finalized());
conn.set_mv_tx(None);
conn.set_tx_state(TransactionState::None);
pager.end_read_tx();
program_state.commit_state = CommitState::Ready;
// Fall through to attached phase
}
IOResult::IO(io) => return Ok(IOResult::IO(io)),
}
}
// Phase 2: Commit MVCC transactions on attached databases
// Resume an in-progress attached MVCC commit
if matches!(
program_state.commit_state,
CommitState::CommittingAttachedMvcc { .. }
) {
let (step_result, db_id) = {
let CommitState::CommittingAttachedMvcc {
state_machine,
db_id,
mv_store: ref attached_mv,
} = &mut program_state.commit_state
else {
unreachable!()
};
(state_machine.step(attached_mv)?, *db_id)
};
match step_result {
IOResult::Done(_) => {
let attached_pager = conn
.get_pager_from_database_index(&db_id)
.expect("attached MVCC transaction should always have a pager");
conn.publish_database_schema(db_id);
conn.set_mv_tx_for_db(db_id, None);
attached_pager.end_read_tx();
// Fall through to look for more
}
IOResult::IO(io) => return Ok(IOResult::IO(io)),
}
}
// Start/continue committing remaining attached MVCC transactions
loop {
let Some((db_id, tx_id, _mode)) = conn.next_attached_mv_tx() else {
break;
};
let Some(attached_mv_store) = conn.mv_store_for_db(db_id) else {
conn.set_mv_tx_for_db(db_id, None);
continue;
};
let mut state_machine = match attached_mv_store.commit_tx(tx_id, &conn, db_id) {
Ok(sm) => sm,
Err(e) => {
tracing::error!(
db_id,
"attached DB commit failed after main DB already committed; \
cross-database state is inconsistent: {e}"
);
// Rollback remaining uncommitted attached MVCC transactions
// so they don't block checkpointing until connection close.
conn.rollback_attached_mvcc_txs(true);
return Err(e);
}
};
match state_machine.step(&attached_mv_store)? {
IOResult::Done(_) => {
let attached_pager = conn
.get_pager_from_database_index(&db_id)
.expect("attached MVCC transaction should always have a pager");
conn.publish_database_schema(db_id);
conn.set_mv_tx_for_db(db_id, None);
attached_pager.end_read_tx();
continue;
}
IOResult::IO(io) => {
program_state.commit_state = CommitState::CommittingAttachedMvcc {
state_machine,
db_id,
mv_store: attached_mv_store,
};
return Ok(IOResult::IO(io));
}
}
}
// Phase 3: Commit WAL transactions on attached databases that don't use MVCC.
// When the main DB uses MVCC, we route through commit_txn_mvcc, but attached
// DBs may use WAL mode and need their dirty pages committed via the WAL path.
if matches!(program_state.commit_state, CommitState::CommittingAttached) {
// Re-entry after IO yield from attached WAL pager commit.
match self.end_attached_write_txns(&conn, rollback)? {
IOResult::Done(_) => {
program_state.commit_state = CommitState::Ready;
self.end_attached_read_txns(&conn);
return Ok(IOResult::Done(()));
}
IOResult::IO(io) => return Ok(IOResult::IO(io)),
}
}
match self.end_attached_write_txns(&conn, rollback)? {
IOResult::Done(_) => {}
IOResult::IO(io) => {
program_state.commit_state = CommitState::CommittingAttached;
return Ok(IOResult::IO(io));
}
}
self.end_attached_read_txns(&conn);
program_state.commit_state = CommitState::Ready;
Ok(IOResult::Done(()))
}
#[instrument(skip(self, pager, connection, program_state), level = Level::DEBUG)]
fn step_end_write_txn(
&self,
pager: &Arc<Pager>,
connection: &Connection,
program_state: &mut ProgramState,
rollback: bool,
) -> Result<IOResult<()>> {
let commit_state = &mut program_state.commit_state;
if matches!(commit_state, CommitState::CommittingAttached) {
// Resume committing attached pagers after IO yield.
match self.end_attached_write_txns(connection, rollback)? {
IOResult::Done(_) => {
*commit_state = CommitState::Ready;
}
IOResult::IO(io) => {
return Ok(IOResult::IO(io));
}
}
// Release read locks on attached pagers that only had read transactions
// (end_attached_write_txns only handles pagers with write locks).
self.end_attached_read_txns(connection);
return Ok(IOResult::Done(()));
}
let txn_finish_result = if !rollback {
pager.commit_tx(connection, true)
} else {
pager.rollback_tx(connection);
Ok(IOResult::Done(()))
};
tracing::debug!("txn_finish_result: {:?}", txn_finish_result);
match txn_finish_result? {
IOResult::Done(_) => {
// Main pager commit done, now commit attached database pagers
match self.end_attached_write_txns(connection, rollback)? {
IOResult::Done(_) => {
*commit_state = CommitState::Ready;
}
IOResult::IO(io) => {
*commit_state = CommitState::CommittingAttached;
return Ok(IOResult::IO(io));
}
}
}
IOResult::IO(io) => {
tracing::trace!("Cacheflush IO");
*commit_state = CommitState::Committing;
return Ok(IOResult::IO(io));
}
}
// Release read locks on attached pagers that only had read transactions
// (end_attached_write_txns only handles pagers with write locks).
self.end_attached_read_txns(connection);
Ok(IOResult::Done(()))
}
/// End write transactions on all attached databases that hold write locks.
/// Iterates ALL attached pagers (not just the current program's write_databases)
/// because in explicit transactions, the COMMIT statement's program may differ
/// from the statement that acquired the attached write lock.
/// On IO yield, already-committed pagers are skipped on re-entry via holds_write_lock().
fn end_attached_write_txns(
&self,
connection: &Connection,
rollback: bool,
) -> Result<IOResult<()>> {
connection.with_all_attached_pagers_with_index(|pagers| {
for (db_id, attached_pager) in pagers {
let db_id = *db_id;
// MVCC-enabled attached DBs are committed in commit_txn_mvcc phase 2
if connection.mv_store_for_db(db_id).is_some() {
continue;
}
if !attached_pager.holds_write_lock() {
continue;
}
if !rollback {
// Commit dirty pages to WAL, then end write+read transactions.
// We disable auto-checkpoint and avoid pager.commit_tx() since
// the checkpoint logic can leave read locks held.
match attached_pager.commit_dirty_pages(
WalAutoActions::empty(),
SyncMode::Normal,
false,
) {
Ok(IOResult::Done(_)) => {}
Ok(IOResult::IO(io)) => {
// IO pending — return so the caller can yield and re-enter.
// commit_dirty_pages tracks its own internal state, so calling
// it again on re-entry will resume correctly.
return Ok(IOResult::IO(io));
}
Err(e) => return Err(e),
}
// WAL commit succeeded — publish the connection-local schema
// changes to the shared Database so other connections can see them.
connection.publish_database_schema(db_id);
attached_pager.end_write_tx();
attached_pager.end_read_tx();
attached_pager.commit_dirty_pages_end();
} else {
// Discard any local schema changes on rollback
connection.database_schemas().write().remove(&db_id);
attached_pager.rollback_attached();
}
}
Ok(IOResult::Done(()))
})
}
/// End read transactions on all attached databases that had transactions started.
fn end_attached_read_txns(&self, connection: &Connection) {
connection.with_all_attached_pagers_with_index(|pagers| {
pagers.iter().for_each(|(db_id, attached_pager)| {
if connection.mv_store_for_db(*db_id).is_some() {
// MVCC-enabled attached DBs don't use WAL read transactions, so skip.
return;
}
if attached_pager.holds_write_lock() {
// Attached pager has a write lock, so its read transaction was ended by end_attached_write_txns: skip.
return;
}
if attached_pager.holds_read_lock() {
attached_pager.end_read_tx();
}
});
})
}
#[instrument(skip(self, commit_state, mv_store), level = Level::DEBUG)]
fn step_end_mvcc_txn(
&self,
commit_state: &mut StateMachine<Box<CommitStateMachine<MvccClock>>>,
mv_store: &Arc<MvStore>,
) -> Result<IOResult<()>> {
commit_state.step(mv_store)
}
/// Aborts the program due to various conditions (explicit error, interrupt or reset of unfinished statement) by rolling back the transaction
/// This method is no-op if program was already finished (either aborted or executed to completion)
/// Returns an error if cleanup operations (savepoint rollback/release) fail.
pub fn abort(
&self,
pager: &Arc<Pager>,
err: Option<&LimboError>,
state: &mut ProgramState,
) -> Result<()> {
fn capture_abort_error(
abort_error: &mut Option<LimboError>,
err: LimboError,
context: &str,
) {
tracing::error!("{context}: {err}");
if abort_error.is_none() {
*abort_error = Some(err);
}
}
let mut abort_error: Option<LimboError> = None;
// MVCC auto-checkpoint is owned by commit_state, not by normal_step().
// If its yielded I/O fails, normal_step sees the error before
// CommitStateMachine::Checkpoint gets another step, so the checkpoint
// state machine cannot run its own error cleanup. abort() is the first
// statement cleanup path that still owns that commit_state.
state.commit_state.cleanup_mvcc_checkpoint_state();
// If a CommitStateMachine was non-terminal when the program was
// aborted — Statement dropped mid-IO yield, or `?` propagated a Busy
// out of BeginCommitLogicalLog / SyncLogicalLog — release the locks
// it acquired (`pager_commit_lock`, `exclusive_tx`) and roll back the
// orphan tx. Without this the tx stays in `Preparing`, the next op on
// this connection trips a `turso_assert_eq!(Active)`, and any other
// writer parks forever on the leaked `pager_commit_lock`. The
// following err-match's no-rollback arms (Busy / TxError / etc.)
// would otherwise skip this cleanup.
state
.commit_state
.cleanup_abandoned_mvcc_commit(&self.connection);
// VACUUM (and VACUUM INTO) state can own internal helper statements whose drop path
// releases nested guards. Clean it before checking whether this program
// is itself nested; otherwise abort could skip top-level cleanup.
if let Err(err) = execute::cleanup_vacuum_state(&self.connection, state) {
capture_abort_error(
&mut abort_error,
err,
"Failed to clean up VACUUM state during abort",
);
}
// Only end trigger execution if the subprogram was actually running.
// Cached (pooled) statements may be dropped after their trigger execution
// was already ended by op_program; calling end again would pop the wrong
// entry from the executing_triggers stack.
if self.is_trigger_subprogram() && state.execution_state.is_running() {
self.connection.end_trigger_execution();
}
// Errors from nested statements are handled by the parent statement.
if !self.connection.is_nested_stmt() && !self.is_trigger_subprogram() {
let owns_auto_txn = state.owns_auto_txn();
if err.is_some() && !pager.is_checkpointing() {
// For ON CONFLICT FAIL, do NOT rollback the statement savepoint —
// changes made before the error should persist.
// For all other resolve types (ABORT, ROLLBACK, etc.), rollback the statement.
let is_fail_constraint = (matches!(err, Some(LimboError::Constraint(_)))
&& self.resolve_type == ResolveType::Fail)
|| matches!(err, Some(LimboError::Raise(ResolveType::Fail, _)));
if !is_fail_constraint {
if let Err(end_stmt_err) = state.end_statement(
&self.connection,
pager,
EndStatement::RollbackSavepoint,
) {
capture_abort_error(
&mut abort_error,
end_stmt_err,
"Failed to rollback statement savepoint during abort",
);
}
}
}
match err {
// Transaction errors, e.g. trying to start a nested transaction, do not cause a rollback.
Some(LimboError::TxError(_)) => {}
// Table locked errors, e.g. trying to checkpoint in an interactive transaction, do not cause a rollback.
Some(LimboError::TableLocked) => {}
// Busy errors do not cause a rollback.
Some(LimboError::Busy) => {}
// BusySnapshot errors do not cause a rollback either - user must rollback explicitly.
// BusySnapshot is distinct from Busy in that a busy_timeout or handler should not be
// used because it will not help - the snapshot is permanently stale and rollback is
// the only way out for this poor transaction.
Some(LimboError::BusySnapshot) => {}
// Schema updated errors do not cause a rollback; the statement will be reprepared and retried,
// and the caller is expected to handle transaction cleanup explicitly if needed.
Some(LimboError::SchemaUpdated) => {}
// Foreign key constraint errors: ON CONFLICT does NOT apply to FK violations.
// FK errors always behave like ABORT: rollback statement,
// rollback transaction in autocommit mode.
Some(LimboError::ForeignKeyConstraint(_)) => {
if owns_auto_txn {
self.rollback_current_txn(pager);
}
self.connection.set_changes_without_total(0);
}
// Constraint and RAISE errors: behavior depends on the effective resolve type.
// For normal constraints, the resolve type comes from the statement (ON CONFLICT).
// For RAISE errors, the resolve type is embedded in the error variant itself.
// - ROLLBACK: rollback the entire transaction regardless of autocommit mode
// - FAIL: don't rollback anything - changes persist, transaction stays active
// - ABORT (default): rollback statement, rollback txn if autocommit
Some(LimboError::Constraint(_)) | Some(LimboError::Raise(_, _)) => {
let effective_resolve = match err {
Some(LimboError::Raise(rt, _)) => *rt,
_ => self.resolve_type,
};
match effective_resolve {
ResolveType::Rollback => {
self.rollback_current_txn(pager);
// All deferred FK violations are undone by the full rollback.
self.connection.clear_deferred_foreign_key_violations();
}
ResolveType::Fail => {
// FAIL: Don't rollback the transaction.
// Changes made before the error persist.
if let Err(end_stmt_err) = state.end_statement(
&self.connection,
pager,
EndStatement::ReleaseSavepoint,
) {
capture_abort_error(
&mut abort_error,
end_stmt_err,
"Failed to release statement savepoint during abort",
);
}
if owns_auto_txn {
// Autocommit FAIL: commit partial changes.
// This matches halt()'s FAIL+autocommit path.
let mv_store = self.connection.mv_store();
if let Err(e) = execute::vtab_commit_all(&self.connection) {
capture_abort_error(
&mut abort_error,
e,
"vtab_commit_all failed during FAIL abort",
);
}
if let Err(e) = execute::index_method_pre_commit_all(state, pager) {
capture_abort_error(
&mut abort_error,
e,
"index_method_pre_commit_all failed during FAIL abort",
);
}
loop {
match self.commit_txn(
pager.clone(),
state,
mv_store.as_ref(),
false,
) {
Ok(IOResult::Done(_)) => break,
Ok(IOResult::IO(io)) => {
if let Err(e) = io.wait(pager.io.as_ref()) {
capture_abort_error(
&mut abort_error,
e,
"IO error during FAIL commit in abort",
);
break;
}
}
Err(e) => {
capture_abort_error(
&mut abort_error,
e,
"commit_txn failed during FAIL abort",
);
break;
}
}
}
}
}
_ => {
if owns_auto_txn {
self.rollback_current_txn(pager);
}
}
}
let last_change = match effective_resolve {
ResolveType::Fail => state.n_change.load(Ordering::SeqCst),
_ => 0,
};
self.connection.set_changes_without_total(last_change);
}
Some(LimboError::RaiseIgnore) => {
tracing::error!(
"BUG: RaiseIgnore reached abort() - should be caught by op_program"
);
debug_assert!(
false,
"RaiseIgnore should be caught by op_program, not reach abort"
);
}
_ => match state.auto_txn_cleanup {
TxnCleanup::RollbackTxn => {
self.rollback_current_txn(pager);
}
TxnCleanup::RollbackSavepoint => {
if owns_auto_txn {
self.rollback_current_txn(pager);
} else if err.is_none() && !pager.is_checkpointing() {
if let Err(end_stmt_err) = state.end_statement(
&self.connection,
pager,
EndStatement::RollbackSavepoint,
) {
capture_abort_error(
&mut abort_error,
end_stmt_err,
"Failed to rollback statement savepoint during abort",
);
}
}
}
TxnCleanup::None => {
if owns_auto_txn || (!self.connection.get_auto_commit() && err.is_some()) {
self.rollback_current_txn(pager);
}
}
},
}
}
if state.uses_subjournal {
pager.stop_use_subjournal();
state.uses_subjournal = false;
}
state.auto_txn_cleanup = TxnCleanup::None;
if let Some(err) = abort_error {
return Err(err);
}
Ok(())
}
fn rollback_current_txn(&self, pager: &Arc<Pager>) {
self.connection.rollback_current_txn_state(pager, true);
}
pub fn is_trigger_subprogram(&self) -> bool {
self.trigger.is_some() || self.is_subprogram
}
}
impl Deref for Program {
type Target = PreparedProgram;
fn deref(&self) -> &PreparedProgram {
&self.prepared
}
}
pub(crate) fn make_record(
registers: &[Register],
start_reg: &usize,
count: &usize,
) -> ImmutableRecord {
let regs = ®isters[*start_reg..*start_reg + *count];
ImmutableRecord::from_registers(regs, regs.len())
}
/// Split a register slice into an immutable ref and a mutable ref at two distinct indices.
pub(crate) fn split_registers(
registers: &mut [Register],
src: usize,
dst: usize,
) -> (&Register, &mut Register) {
debug_assert_ne!(src, dst, "split_registers: src and dst must differ");
if src < dst {
let (left, right) = registers.split_at_mut(dst);
(&left[src], &mut right[0])
} else {
let (left, right) = registers.split_at_mut(src);
(&right[0], &mut left[dst])
}
}
pub fn registers_to_ref_values<'a>(
registers: &'a [Register],
) -> impl ExactSizeIterator<Item = ValueRef<'a>> {
registers.iter().map(|reg| reg.get_value().as_ref())
}
#[instrument(skip(program), level = Level::DEBUG)]
fn trace_insn(program: &Program, addr: InsnReference, insn: &Insn) {
tracing::trace!(
"\n{}",
explain::insn_to_str(
program,
addr,
insn,
String::new(),
program
.comments
.iter()
.find(|(offset, _)| *offset == addr)
.map(|(_, comment)| comment)
.copied()
)
);
}
pub trait FromValueRow<'a> {
fn from_value(value: &'a Value) -> Result<Self>
where
Self: Sized + 'a;
}
impl<'a> FromValueRow<'a> for i64 {
fn from_value(value: &'a Value) -> Result<Self> {
match value {
Value::Numeric(Numeric::Integer(i)) => Ok(*i),
_ => Err(LimboError::ConversionError("Expected integer value".into())),
}
}
}
impl<'a> FromValueRow<'a> for f64 {
fn from_value(value: &'a Value) -> Result<Self> {
match value {
Value::Numeric(Numeric::Float(f)) => Ok(f64::from(*f)),
_ => Err(LimboError::ConversionError("Expected integer value".into())),
}
}
}
impl<'a> FromValueRow<'a> for String {
fn from_value(value: &'a Value) -> Result<Self> {
match value {
Value::Text(s) => Ok(s.as_str().to_string()),
_ => Err(LimboError::ConversionError("Expected text value".into())),
}
}
}
impl<'a> FromValueRow<'a> for &'a str {
fn from_value(value: &'a Value) -> Result<Self> {
match value {
Value::Text(s) => Ok(s.as_str()),
_ => Err(LimboError::ConversionError("Expected text value".into())),
}
}
}
impl<'a> FromValueRow<'a> for &'a Value {
fn from_value(value: &'a Value) -> Result<Self> {
Ok(value)
}
}
impl Row {
pub fn get<'a, T: FromValueRow<'a> + 'a>(&'a self, idx: usize) -> Result<T> {
let value = unsafe {
self.values
.add(idx)
.as_ref()
.expect("row value pointer should be valid")
};
let value = match value {
Register::Value(value) => value,
_ => unreachable!("a row should be formed of values only"),
};
T::from_value(value)
}
pub fn get_value(&self, idx: usize) -> &Value {
let value = unsafe {
self.values
.add(idx)
.as_ref()
.expect("row value pointer should be valid")
};
match value {
Register::Value(value) => value,
_ => unreachable!("a row should be formed of values only"),
}
}
pub fn get_values(&self) -> impl Iterator<Item = &Value> {
let values = unsafe { std::slice::from_raw_parts(self.values, self.count) };
// This should be ownedvalues
// TODO: add check for this
values.iter().map(|v| v.get_value())
}
pub fn len(&self) -> usize {
self.count
}
pub fn is_empty(&self) -> bool {
self.count == 0
}
}
/// Extension trait for `ValueIterator` that allows writing directly to a `Register`
/// without allocating intermediate `ValueRef` values.
pub trait ValueIteratorExt {
/// Skips `n` elements and writes the value directly to the register.
/// Returns `Some(Ok(()))` on success, `Some(Err(...))` on parse error,
/// or `None` if there are fewer than `n+1` elements.
fn nth_into_register(&mut self, n: usize, dest: &mut Register) -> Option<Result<()>>;
}
impl<'a> ValueIteratorExt for crate::types::ValueIterator<'a> {
#[inline(always)]
fn nth_into_register(&mut self, n: usize, dest: &mut Register) -> Option<Result<()>> {
use crate::storage::sqlite3_ondisk::read_varint;
use crate::types::{get_serial_type_size, Extendable, Text};
let mut header = self.header_section_ref();
let mut data = self.data_section_ref();
// Skip n elements
let mut data_sum = 0;
for _ in 0..n {
if header.is_empty() {
return None;
}
let (serial_type, bytes_read) = match read_varint(header) {
Ok(v) => v,
Err(e) => return Some(Err(e)),
};
header = &header[bytes_read..];
data_sum += match get_serial_type_size(serial_type) {
Ok(size) => size,
Err(e) => return Some(Err(e)),
};
}
if data_sum > data.len() {
return Some(Err(LimboError::Corrupt(
"Data section too small for indicated serial type size".into(),
)));
}
data = &data[data_sum..];
// Read the serial type for the target element
if header.is_empty() {
return None;
}
let (serial_type, bytes_read) = match read_varint(header) {
Ok(v) => v,
Err(e) => return Some(Err(e)),
};
// Update iterator state
self.set_header_section(&header[bytes_read..]);
// Decode directly into register based on serial type
match serial_type {
// NULL
0 => {
self.set_data_section(data);
dest.set_null();
}
// I8
1 => {
if unlikely(data.is_empty()) {
return Some(Err(LimboError::Corrupt("Invalid 1-byte int".into())));
}
self.set_data_section(&data[1..]);
dest.set_int(data[0] as i8 as i64);
}
// I16
2 => {
if unlikely(data.len() < 2) {
return Some(Err(LimboError::Corrupt("Invalid 2-byte int".into())));
}
self.set_data_section(&data[2..]);
dest.set_int(i16::from_be_bytes([data[0], data[1]]) as i64);
}
// I24
3 => {
if unlikely(data.len() < 3) {
return Some(Err(LimboError::Corrupt("Invalid 3-byte int".into())));
}
self.set_data_section(&data[3..]);
let sign_extension = if data[0] <= 0x7F { 0 } else { 0xFF };
dest.set_int(
i32::from_be_bytes([sign_extension, data[0], data[1], data[2]]) as i64,
);
}
// I32
4 => {
if unlikely(data.len() < 4) {
return Some(Err(LimboError::Corrupt("Invalid 4-byte int".into())));
}
self.set_data_section(&data[4..]);
dest.set_int(i32::from_be_bytes([data[0], data[1], data[2], data[3]]) as i64);
}
// I48
5 => {
if unlikely(data.len() < 6) {
return Some(Err(LimboError::Corrupt("Invalid 6-byte int".into())));
}
self.set_data_section(&data[6..]);
let sign_extension = if data[0] <= 0x7F { 0 } else { 0xFF };
dest.set_int(i64::from_be_bytes([
sign_extension,
sign_extension,
data[0],
data[1],
data[2],
data[3],
data[4],
data[5],
]));
}
// I64
6 => {
if unlikely(data.len() < 8) {
return Some(Err(LimboError::Corrupt("Invalid 8-byte int".into())));
}
self.set_data_section(&data[8..]);
dest.set_int(i64::from_be_bytes([
data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7],
]));
}
// F64
7 => {
if unlikely(data.len() < 8) {
return Some(Err(LimboError::Corrupt("Invalid 8-byte float".into())));
}
self.set_data_section(&data[8..]);
let val = f64::from_be_bytes([
data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7],
]);
if let Some(nn) = NonNan::new(val) {
dest.set_float(nn);
} else {
dest.set_null();
}
}
// CONST_INT0
8 => {
self.set_data_section(data);
dest.set_int(0);
}
// CONST_INT1
9 => {
self.set_data_section(data);
dest.set_int(1);
}
// Reserved
10 | 11 => {
mark_unlikely();
return Some(Err(LimboError::Corrupt(format!(
"Reserved serial type: {serial_type}"
))));
}
// BLOB (n >= 12 && n & 1 == 0)
n if n >= 12 && n & 1 == 0 => {
let content_size = ((n - 12) / 2) as usize;
if unlikely(data.len() < content_size) {
return Some(Err(LimboError::Corrupt("Invalid Blob value".into())));
}
self.set_data_section(&data[content_size..]);
let blob_data = &data[..content_size];
match dest {
Register::Value(Value::Blob(existing_blob)) => {
existing_blob.do_extend(&blob_data);
}
_ => {
dest.set_blob(blob_data.to_vec());
}
}
}
// TEXT (n >= 13 && n & 1 == 1)
n if n >= 13 && n & 1 == 1 => {
let content_size = ((n - 13) / 2) as usize;
if unlikely(data.len() < content_size) {
return Some(Err(LimboError::Corrupt("Invalid Text value".into())));
}
self.set_data_section(&data[content_size..]);
let text_data = &data[..content_size];
// SAFETY: TEXT serial type contains valid UTF-8
let text_str = if cfg!(debug_assertions) {
match std::str::from_utf8(text_data) {
Ok(s) => s,
Err(e) => {
return Some(Err(LimboError::InternalError(format!(
"Invalid UTF-8 in TEXT serial type: {e}"
))));
}
}
} else {
unsafe { std::str::from_utf8_unchecked(text_data) }
};
match dest {
Register::Value(Value::Text(existing_text)) => {
existing_text.do_extend(&text_str);
}
_ => {
dest.set_text(Text::new(text_str.to_string()));
}
}
}
_ => {
mark_unlikely();
return Some(Err(LimboError::Corrupt(format!(
"Invalid serial type: {serial_type}"
))));
}
}
Some(Ok(()))
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::panic::{catch_unwind, AssertUnwindSafe};
#[test]
fn active_opcode_helpers_initialize_defaults() {
let mut state = ProgramState::new(1, 0);
assert!(matches!(state.active_op_state.state, ActiveOpState::None));
assert!(matches!(
state.active_op_state.column(),
OpColumnState::Start
));
state.active_op_state.clear();
assert!(state.active_op_state.parse_schema().is_none());
}
#[test]
fn active_opcode_helpers_reject_mismatched_resumes() {
let mut state = ProgramState::new(1, 0);
*state.active_op_state.column() = OpColumnState::GetColumn;
let panic = catch_unwind(AssertUnwindSafe(|| {
let _ = state.active_op_state.parse_schema();
}));
assert!(panic.is_err(), "mismatched opcode resume should panic");
}
#[test]
fn seek_state_is_independent_from_active_opcode_slot() {
let mut state = ProgramState::new(1, 0);
*state.active_op_state.insert() = OpInsertState {
sub_state: OpInsertSubState::Seek,
old_record: None,
is_noop_update: false,
};
state.seek_state = OpSeekState::MoveLast;
assert!(matches!(
state.active_op_state.insert().sub_state,
OpInsertSubState::Seek
));
assert!(matches!(state.seek_state, OpSeekState::MoveLast));
}
}
/// Shuttle tests for validating the `unsafe impl Send + Sync for ProgramState` safety claims.
///
/// The safety claims are:
/// 1. `Row` contains a `*const Register` pointing into `ProgramState.registers`
/// 2. Only immutable references (`&Row`) are given out via `result_row.as_ref()`
/// 3. `result_row` is invalidated (via `.take()`) at the start of each step iteration
///
/// These tests verify that the implementation correctly upholds these invariants
/// under concurrent access patterns.
#[cfg(all(shuttle, test))]
mod shuttle_tests {
use super::*;
use crate::sync::Arc;
use crate::thread;
use crate::types::Value;
/// Creates a minimal ProgramState for testing.
fn create_test_state(num_registers: usize, num_cursors: usize) -> ProgramState {
ProgramState::new(num_registers, num_cursors)
}
/// Test that ProgramState can be safely sent between threads.
/// This validates the `unsafe impl Send for ProgramState` claim.
#[test]
fn shuttle_program_state_send() {
shuttle::check_random(
|| {
let mut state = create_test_state(10, 2);
// Write some data to registers
state.registers[0].set_int(42);
state.registers[1].set_text(Text::new("test".to_string()));
// Send state to another thread
let handle = thread::spawn(move || {
// Verify data is intact after send
assert!(matches!(
&state.registers[0],
Register::Value(Value::Numeric(Numeric::Integer(42)))
));
if let Register::Value(Value::Text(t)) = &state.registers[1] {
assert_eq!(t.as_str(), "test");
} else {
panic!("Expected text value");
}
// Modify in new thread
state.registers[2].set_int(100);
state
});
let state = handle.join().unwrap();
assert!(matches!(
&state.registers[2],
Register::Value(Value::Numeric(Numeric::Integer(100)))
));
},
1000,
);
}
/// Test that ProgramState with a set result_row can be safely sent.
/// The Row contains a raw pointer that must remain valid after the send.
#[test]
fn shuttle_program_state_send_with_row() {
shuttle::check_random(
|| {
let mut state = create_test_state(10, 2);
// Set up registers with test data
state.registers[0].set_int(1);
state.registers[1].set_int(2);
state.registers[2].set_int(3);
// Create a result_row pointing to registers
state.result_row = Some(Row {
values: &state.registers[0] as *const Register,
count: 3,
});
// Send to another thread - the pointer must remain valid
// because it points to memory owned by state (the registers Vec)
let handle = thread::spawn(move || {
// The row pointer should still be valid because registers moved with state
if let Some(row) = &state.result_row {
assert_eq!(row.len(), 3);
// Read through the pointer - this validates the pointer is still valid
let val = row.get::<i64>(0).unwrap();
assert_eq!(val, 1);
let val = row.get::<i64>(1).unwrap();
assert_eq!(val, 2);
let val = row.get::<i64>(2).unwrap();
assert_eq!(val, 3);
} else {
panic!("Expected result_row to be set");
}
state
});
let _ = handle.join().unwrap();
},
1000,
);
}
/// Test concurrent reads of result_row through shared reference.
/// This validates the `unsafe impl Sync for ProgramState` claim for read access.
#[test]
fn shuttle_program_state_sync_concurrent_reads() {
shuttle::check_random(
|| {
let mut state = create_test_state(10, 2);
// Set up registers
state.registers[0].set_int(42);
state.registers[1].set_int(43);
// Create result_row
state.result_row = Some(Row {
values: &state.registers[0] as *const Register,
count: 2,
});
let state = Arc::new(state);
let state2 = Arc::clone(&state);
let state3 = Arc::clone(&state);
// Multiple threads reading concurrently
let h1 = thread::spawn(move || {
if let Some(row) = &state.result_row {
let val = row.get::<i64>(0).unwrap();
assert_eq!(val, 42);
}
});
let h2 = thread::spawn(move || {
if let Some(row) = &state2.result_row {
let val = row.get::<i64>(1).unwrap();
assert_eq!(val, 43);
}
});
let h3 = thread::spawn(move || {
if let Some(row) = &state3.result_row {
assert_eq!(row.len(), 2);
}
});
h1.join().unwrap();
h2.join().unwrap();
h3.join().unwrap();
},
1000,
);
}
/// Test that Row values read through the pointer are consistent.
/// Multiple threads reading the same row values should see the same data.
#[test]
fn shuttle_row_pointer_consistency() {
shuttle::check_random(
|| {
let mut state = create_test_state(10, 2);
// Set up registers with distinct values
for i in 0..5 {
state.registers[i].set_int(i as i64 * 10);
}
state.result_row = Some(Row {
values: &state.registers[0] as *const Register,
count: 5,
});
let state = Arc::new(state);
let mut handles = vec![];
for _ in 0..4 {
let state_clone = Arc::clone(&state);
let h = thread::spawn(move || {
if let Some(row) = &state_clone.result_row {
// All threads should see the same values
for i in 0..5 {
let val = row.get::<i64>(i).unwrap();
assert_eq!(val, i as i64 * 10);
}
}
});
handles.push(h);
}
for h in handles {
h.join().unwrap();
}
},
1000,
);
}
/// Test the result_row invalidation pattern.
/// When result_row is taken (invalidated), concurrent reads should not see stale data.
/// This simulates the pattern used in `normal_step()` where `result_row.take()` is called.
#[test]
fn shuttle_result_row_invalidation() {
shuttle::check_random(
|| {
let mut state = create_test_state(10, 2);
state.registers[0].set_int(100);
state.result_row = Some(Row {
values: &state.registers[0] as *const Register,
count: 1,
});
// Simulate the invalidation pattern from normal_step
// In real code, this requires &mut self, so there's no concurrent access
let taken_row = state.result_row.take();
// After take(), result_row should be None
assert!(state.result_row.is_none());
// The taken row still holds valid data (until dropped)
if let Some(row) = taken_row {
let val = row.get::<i64>(0).unwrap();
assert_eq!(val, 100);
}
},
1000,
);
}
/// Test register modification after row invalidation.
/// This validates that modifying registers after take() is safe.
#[test]
fn shuttle_register_modification_after_invalidation() {
shuttle::check_random(
|| {
let mut state = create_test_state(10, 2);
state.registers[0].set_int(1);
state.result_row = Some(Row {
values: &state.registers[0] as *const Register,
count: 1,
});
// Invalidate row (simulating what normal_step does)
let _ = state.result_row.take();
// Now safe to modify registers
state.registers[0].set_int(999);
// Create new row pointing to modified registers
state.result_row = Some(Row {
values: &state.registers[0] as *const Register,
count: 1,
});
// New row should see new value
if let Some(row) = &state.result_row {
let val = row.get::<i64>(0).unwrap();
assert_eq!(val, 999);
}
},
1000,
);
}
/// Test sequential send-receive pattern (simulating async task scheduling).
/// ProgramState is moved between threads in a producer-consumer pattern.
#[test]
fn shuttle_sequential_thread_transfer() {
shuttle::check_random(
|| {
let mut state = create_test_state(10, 2);
state.registers[0].set_int(0);
// Thread 1: increment
let h1 = thread::spawn(move || {
if let Register::Value(Value::Numeric(Numeric::Integer(v))) =
&state.registers[0]
{
state.registers[0].set_int(v + 1);
}
state
});
let mut state = h1.join().unwrap();
// Thread 2: increment
let h2 = thread::spawn(move || {
if let Register::Value(Value::Numeric(Numeric::Integer(v))) =
&state.registers[0]
{
state.registers[0].set_int(v + 1);
}
state
});
let mut state = h2.join().unwrap();
// Thread 3: increment
let h3 = thread::spawn(move || {
if let Register::Value(Value::Numeric(Numeric::Integer(v))) =
&state.registers[0]
{
state.registers[0].set_int(v + 1);
}
state
});
let state = h3.join().unwrap();
// Final value should be 3
assert!(matches!(
&state.registers[0],
Register::Value(Value::Numeric(Numeric::Integer(3)))
));
},
1000,
);
}
/// Test that ProgramState can be wrapped in Arc for shared ownership.
/// This is the typical pattern for concurrent database operations.
#[test]
fn shuttle_arc_wrapped_state() {
shuttle::check_random(
|| {
let mut state = create_test_state(10, 2);
// Initialize with test data
for i in 0..5 {
state.registers[i].set_int(i as i64);
}
let state = Arc::new(state);
let mut handles = vec![];
// Multiple threads reading registers through Arc
for thread_id in 0u8..4 {
let state_clone = Arc::clone(&state);
let h = thread::spawn(move || {
// Each thread reads all registers
for i in 0..5 {
if let Register::Value(Value::Numeric(Numeric::Integer(v))) =
&state_clone.registers[i]
{
assert_eq!(*v, i as i64);
}
}
thread_id
});
handles.push(h);
}
for h in handles {
h.join().unwrap();
}
},
1000,
);
}
/// Test Row::get_values iterator under concurrent access.
#[test]
fn shuttle_row_get_values_concurrent() {
shuttle::check_random(
|| {
let mut state = create_test_state(10, 2);
state.registers[0].set_int(10);
state.registers[1].set_int(20);
state.registers[2].set_int(30);
state.result_row = Some(Row {
values: &state.registers[0] as *const Register,
count: 3,
});
let state = Arc::new(state);
let state2 = Arc::clone(&state);
let h1 = thread::spawn(move || {
if let Some(row) = &state.result_row {
let values: Vec<_> = row.get_values().collect();
assert_eq!(values.len(), 3);
}
});
let h2 = thread::spawn(move || {
if let Some(row) = &state2.result_row {
let mut sum = 0i64;
for val in row.get_values() {
if let Value::Numeric(Numeric::Integer(i)) = val {
sum += i;
}
}
assert_eq!(sum, 60); // 10 + 20 + 30
}
});
h1.join().unwrap();
h2.join().unwrap();
},
1000,
);
}
/// Stress test: Many threads reading from shared ProgramState.
#[test]
fn shuttle_stress_concurrent_reads() {
shuttle::check_random(
|| {
let mut state = create_test_state(20, 2);
// Fill registers with identifiable data
for i in 0..20 {
state.registers[i].set_int(i as i64 * 100);
}
state.result_row = Some(Row {
values: &state.registers[0] as *const Register,
count: 20,
});
let state = Arc::new(state);
let mut handles = vec![];
for thread_id in 0..6u8 {
let state_clone = Arc::clone(&state);
let h = thread::spawn(move || {
// Each thread reads different parts
let start = (thread_id as usize * 3) % 20;
if let Some(row) = &state_clone.result_row {
for i in 0..3 {
let idx = (start + i) % row.len();
let val = row.get::<i64>(idx).unwrap();
assert_eq!(val, idx as i64 * 100);
}
}
thread_id
});
handles.push(h);
}
for h in handles {
h.join().unwrap();
}
},
1000,
);
}
}