Source file sema.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
open Lwt.Syntax
module Row = Granary_encoding.Row
module Cat = Granary_catalog.Catalog
let sqlite_master_meta : Cat.table_meta =
{ Cat.name = "sqlite_master"
; Cat.storage =
Cat.Row
{ tree_id = -2; next_rowid = 0L; without_rowid = false; autoincrement = false }
; Cat.columns =
[ { Row.name = "type"
; Row.ty = Row.Text
; Row.not_null = false
; Row.primary_key = false
; Row.pk_desc = false
; Row.default = None
; Row.check_sql = None
; Row.generated_as = None
}
; { Row.name = "name"
; Row.ty = Row.Text
; Row.not_null = false
; Row.primary_key = false
; Row.pk_desc = false
; Row.default = None
; Row.check_sql = None
; Row.generated_as = None
}
; { Row.name = "tbl_name"
; Row.ty = Row.Text
; Row.not_null = false
; Row.primary_key = false
; Row.pk_desc = false
; Row.default = None
; Row.check_sql = None
; Row.generated_as = None
}
; { Row.name = "rootpage"
; Row.ty = Row.Integer
; Row.not_null = false
; Row.primary_key = false
; Row.pk_desc = false
; Row.default = None
; Row.check_sql = None
; Row.generated_as = None
}
; { Row.name = "sql"
; Row.ty = Row.Text
; Row.not_null = false
; Row.primary_key = false
; Row.pk_desc = false
; Row.default = None
; Row.check_sql = None
; Row.generated_as = None
}
]
; Cat.fk_constraints = []
}
;;
let sqlite_sequence_meta : Cat.table_meta =
{ Cat.name = "sqlite_sequence"
; Cat.storage =
Cat.Row
{ tree_id = -3; next_rowid = 0L; without_rowid = false; autoincrement = false }
; Cat.columns =
[ { Row.name = "name"
; Row.ty = Row.Text
; Row.not_null = false
; Row.primary_key = false
; Row.pk_desc = false
; Row.default = None
; Row.check_sql = None
; Row.generated_as = None
}
; { Row.name = "seq"
; Row.ty = Row.Integer
; Row.not_null = false
; Row.primary_key = false
; Row.pk_desc = false
; Row.default = None
; Row.check_sql = None
; Row.generated_as = None
}
]
; Cat.fk_constraints = []
}
;;
type binop =
| Eq
| Ne
| Lt
| Le
| Gt
| Ge
| Add
| Sub
| Mul
| Div
| And
| Or
| Concat
| Mod
| Bit_and
| Bit_or
| Lshift
| Rshift
| Like
| Glob
type bound_expr =
| BE_lit of Ast.literal
| BE_col of int
| BE_binop of binop * bound_expr * bound_expr
| BE_not of bound_expr
| BE_is_null of bound_expr
| BE_is_not_null of bound_expr
| BE_neg of bound_expr
| BE_bitnot of bound_expr
| BE_between of bound_expr * bound_expr * bound_expr
| BE_in of bound_expr * bound_expr list
| BE_func of Ast.scalar_func * bound_expr list
| BE_param of int
| BE_match of Cat.fts_table_meta * Fts_query.t
| BE_subquery of Ast.stmt
| BE_exists of Ast.stmt
| BE_in_select of bound_expr * Ast.stmt
| BE_case of
{ scrutinee : bound_expr option
; branches : (bound_expr * bound_expr) list
; else_ : bound_expr option
}
| BE_cast of bound_expr * Ast.ty
| BE_excluded_col of int
(** Reference to the i-th column of the proposed INSERT row (the 'excluded' pseudo-table). *)
| BE_window_slot of int
(** Reference to the i-th window function result appended after input columns by Op_window. *)
| BE_collate of bound_expr * Ast.collation (** expr COLLATE collation_name *)
type bound_order_key =
{ key : bound_expr
; dir : Ast.order_dir
; nulls : [ `Nulls_first | `Nulls_last ] option
}
type window_sema =
{ func : Ast.window_func
; args : bound_expr list
; partition_by : bound_expr list
; order_by : bound_order_key list
; frame : Ast.frame_spec option
}
type agg_spec =
{ func : Ast.agg_func
; col_ord : int option
}
type agg_proj_item =
| AP_group_col of int (** index into group_cols list *)
| AP_agg_slot of int
| AP_window_slot of int (** post-aggregate window function result *)
(** A bound JOIN clause. See sema.mli for layout details. *)
type bound_join =
{ kind : Ast.join_kind
; right_meta : Cat.table_meta
; on : bound_expr
; right_col_offset : int
}
type seq_write =
| Seq_set of
{ table : string
; seq : int64
}
| Seq_reset of { table : string option (** [None] = DELETE with no WHERE: reset all *) }
type bound_stmt =
| BS_no_op
| BS_col_create_table of
{ name : string
; columns : Row.column list
; if_not_exists : bool
}
| BS_create_table of
{ name : string
; columns : Row.column list
; uniq_idxs : (string * string list * Cat.idx_origin) list
; if_not_exists : bool
; fk_constraints :
(string list * string * string list * Cat.fk_action * Cat.fk_action * bool) list
(** [(local_cols, parent_table, parent_cols, on_delete, on_update, deferrable)] *)
; without_rowid : bool
; autoincrement : bool (** #299: INTEGER PRIMARY KEY AUTOINCREMENT. *)
}
| BS_insert of
{ table_meta : Cat.table_meta
; ordinals : int list
; values : bound_expr list list
; on_conflict : Ast.conflict_action option
; returning : bound_expr list
; upsert_update : (string list * (int * bound_expr) list) option
}
| BS_insert_select of
{ table_meta : Cat.table_meta
; ordinals : int list
; source : bound_stmt
; on_conflict : Ast.conflict_action option
}
| BS_select of
{ distinct : bool
; table_meta : Cat.table_meta
; proj : int list
; expr_proj : (bound_expr * string option) list
(** Non-empty when projection contains scalar functions (Phase 5)
or aliased expressions (Phase 11).
When non-empty, [proj] is empty and [expr_proj] governs the
output columns. *)
; where : bound_expr option
; order : bound_order_key list
; limit : int option
; offset : int option
; joins : bound_join list
; group_by : int list
; aggs : agg_spec list
; having : bound_expr option
; agg_proj : agg_proj_item list
; windows : window_sema list
; agg_windows : window_sema list
(** Window functions computed AFTER aggregation, over aggregated output rows. *)
}
| BS_create_index of
{ name : string
; table_meta : Cat.table_meta
; col_sqls : string list
; col_expr_flags : bool list
; where_expr : bound_expr option
; where_ast : Ast.expr option
; unique : bool
; if_not_exists : bool
}
| BS_update of
{ table_meta : Cat.table_meta
; assignments : (int * bound_expr) list
; where : bound_expr option
; order : bound_order_key list
; limit : int option
; offset : int option
; returning : bound_expr list
}
| BS_delete of
{ table_meta : Cat.table_meta
; where : bound_expr option
; order : bound_order_key list
; limit : int option
; offset : int option
; returning : bound_expr list
}
| BS_drop_table of
{ name : string
; table_meta : Cat.table_meta
}
| BS_drop_index of
{ name : string
; idx_info : Cat.index_info
}
| BS_seq_write of seq_write
(** #312.1: a supported write against the synthesized [sqlite_sequence]
table, executed as a [next_rowid] mutation. *)
| BS_begin
| BS_commit
| BS_rollback
| BS_savepoint of string
| BS_release of string
| BS_rollback_to of string
| BS_create_fts_table of
{ name : string
; columns : string list
}
| BS_fts_insert of
{ fts_meta : Cat.fts_table_meta
; col_names : string list
; col_values : bound_expr list
; rowid_value : bound_expr option (** #330: explicit [rowid], if given *)
}
| BS_fts_delete of
{ fts_meta : Cat.fts_table_meta
; where : bound_expr option
}
| BS_fts_seq_scan of
{ fts_meta : Cat.fts_table_meta
; where : bound_expr option
}
| BS_fts_match_scan of
{ fts_meta : Cat.fts_table_meta
; query : Fts_query.t
; proj : int list
; include_rank : bool
; snippets : Plan.snippet_spec list
}
| BS_pragma of { kind : Ast.pragma_kind }
| BS_vacuum
| BS_alter_table of
{ table_meta : Cat.table_meta
; action : Ast.alter_action
}
| BS_compound of
{ op : Ast.set_op
; left : bound_stmt
; right : bound_stmt
; order : bound_order_key list
(** ORDER BY bound at the compound level (applied after the set op).
Bound against the leftmost-arm's table_meta — the common case
where both arms expose the same column names. *)
; limit : int option
; offset : int option
}
| BS_const_select of { exprs : (bound_expr * string option) list }
| BS_with_cte of
{ name : string
; def : bound_stmt
; query : bound_stmt
; recursive : bool
}
| BS_create_view of
{ name : string
; query : Ast.stmt
}
| BS_create_reactive_view of
{ name : string
; query : Ast.stmt
; refresh : Ast.refresh_mode
}
| BS_drop_view of { name : string }
| BS_create_trigger of
{ name : string
; timing : Ast.trigger_timing
; event : Ast.trigger_event
; table : string
; when_ : Ast.expr option
; body : Ast.stmt list
}
| BS_drop_trigger of { name : string }
| BS_explain of
{ analyze : bool
; inner : bound_stmt
}
| BS_attach of
{ path : string
; schema : string
}
| BS_detach of { schema : string }
type error =
| Unknown_table of string
| Unknown_column of
{ table : string
; column : string
}
| Ambiguous_column of string
| Type_mismatch of
{ expected : Row.ty
; got : Row.ty
}
| Arity_mismatch of
{ expected : int
; got : int
}
| Already_exists of string
| Invalid_limit of string
| Unsupported of string
| Not_null_violation of string
| Unknown_index of string
let col_index (cols : Row.column list) name =
let rec go i = function
| [] -> None
| c :: _ when String.equal c.Row.name name -> Some i
| _ :: rest -> go (i + 1) rest
in
go 0 cols
;;
(** Convert an FTS table meta to a synthetic [Cat.table_meta] for use
with [bind_expr] (column resolution in WHERE/VALUES expressions). *)
let fts_as_table_meta (m : Cat.fts_table_meta) : Cat.table_meta =
let columns =
List.map
(fun name ->
Row.
{ name
; ty = Row.Text
; not_null = true
; primary_key = false
; pk_desc = false
; default = None
; check_sql = None
; generated_as = None
})
m.Cat.fts_columns
in
{ Cat.name = m.Cat.fts_name
; Cat.storage =
Cat.Row
{ tree_id = m.Cat.fts_content_tree
; next_rowid = 0L
; without_rowid = false
; autoincrement = false
}
; Cat.columns
; Cat.fk_constraints = []
}
;;
let lit_ty = function
| Ast.L_int _ -> Some Row.Integer
| Ast.L_text _ -> Some Row.Text
| Ast.L_null -> None
| Ast.L_real _ -> Some Row.Real
| Ast.L_blob _ -> Some Row.Blob
| Ast.L_current_timestamp | Ast.L_current_date | Ast.L_current_time ->
Some Row.Text
;;
let ty_equal (a : Row.ty) (b : Row.ty) =
match a, b with
| Row.Integer, Row.Integer -> true
| Row.Text, Row.Text -> true
| Row.Real, Row.Real -> true
| Row.Blob, Row.Blob -> true
| _, _ -> false
;;
let ast_binop_to_sema : Ast.binop -> binop = function
| Ast.Eq -> Eq
| Ast.Ne -> Ne
| Ast.Lt -> Lt
| Ast.Le -> Le
| Ast.Gt -> Gt
| Ast.Ge -> Ge
| Ast.Add -> Add
| Ast.Sub -> Sub
| Ast.Mul -> Mul
| Ast.Div -> Div
| Ast.And -> And
| Ast.Or -> Or
| Ast.Concat -> Concat
| Ast.Mod -> Mod
| Ast.Bit_and -> Bit_and
| Ast.Bit_or -> Bit_or
| Ast.Lshift -> Lshift
| Ast.Rshift -> Rshift
| Ast.Like -> Like
| Ast.Glob -> Glob
;;
let resolve_param ~param_counter ~named_params = function
| Ast.Param_anon ->
let i = !param_counter in
incr param_counter;
i
| Ast.Param_index n ->
let i = n - 1 in
if !param_counter <= i then param_counter := i + 1;
i
| Ast.Param_name name ->
(match Hashtbl.find_opt named_params name with
| Some i -> i
| None ->
let i = !param_counter in
incr param_counter;
Hashtbl.add named_params name i;
i)
;;
(** Arity check for a scalar function call. Shared by the three expression
binders ([bind_expr], [bind_expr_join], [bind_expr_agg]). *)
let scalar_func_arity_ok (func : Ast.scalar_func) (n : int) : bool =
match func with
| Ast.Fn_length | Ast.Fn_lower | Ast.Fn_upper | Ast.Fn_abs | Ast.Fn_typeof -> n = 1
| Ast.Fn_ifnull | Ast.Fn_instr -> n = 2
| Ast.Fn_coalesce -> n >= 1
| Ast.Fn_substr -> n = 2 || n = 3
| Ast.Fn_trim | Ast.Fn_ltrim | Ast.Fn_rtrim -> n = 1 || n = 2
| Ast.Fn_replace -> n = 3
| Ast.Fn_round -> n = 1 || n = 2
| Ast.Fn_date | Ast.Fn_time | Ast.Fn_datetime | Ast.Fn_julianday | Ast.Fn_unixepoch ->
n >= 1
| Ast.Fn_strftime -> n >= 2
| Ast.Fn_ceil
| Ast.Fn_floor
| Ast.Fn_sqrt
| Ast.Fn_exp
| Ast.Fn_ln
| Ast.Fn_sign
| Ast.Fn_sin
| Ast.Fn_cos
| Ast.Fn_tan
| Ast.Fn_asin
| Ast.Fn_acos
| Ast.Fn_atan
| Ast.Fn_degrees
| Ast.Fn_radians
| Ast.Fn_log2
| Ast.Fn_log10 -> n = 1
| Ast.Fn_pow | Ast.Fn_atan2 -> n = 2
| Ast.Fn_log -> n = 1 || n = 2
| Ast.Fn_trunc -> n = 1 || n = 2
| Ast.Fn_pi -> n = 0
| Ast.Fn_json_extract -> n = 2
| Ast.Fn_json_object -> n mod 2 = 0
| Ast.Fn_json_array -> true
| Ast.Fn_json_type -> n = 1 || n = 2
| Ast.Fn_json_valid -> n = 1
| Ast.Fn_json_set | Ast.Fn_json_insert | Ast.Fn_json_replace ->
n >= 3 && (n - 1) mod 2 = 0
| Ast.Fn_json_remove -> n >= 2
| Ast.Fn_hex | Ast.Fn_unicode | Ast.Fn_zeroblob -> n = 1
| Ast.Fn_char -> true
| Ast.Fn_printf -> n >= 1
| Ast.Fn_random -> n = 0
| Ast.Fn_randomblob -> n = 1
| Ast.Fn_changes -> n = 0
| Ast.Fn_last_insert_rowid -> n = 0
| Ast.Fn_total_changes -> n = 0
| Ast.Fn_sqlite_version -> n = 0
;;
(** Bind a scalar-function call given a [bind] callback for its arguments.
Shared by the three expression binders. *)
let bind_func ~bind (func : Ast.scalar_func) (args : Ast.expr list) =
let bound = List.map bind args in
let errors =
List.filter_map
(function
| Error e -> Some e
| Ok _ -> None)
bound
in
match errors with
| e :: _ -> Error e
| [] ->
let ok_args =
List.filter_map
(function
| Ok e -> Some e
| Error _ -> None)
bound
in
let n = List.length ok_args in
if not (scalar_func_arity_ok func n)
then
Error
(Arity_mismatch
{ expected =
(match func with
| Ast.Fn_ifnull -> 2
| _ -> 1)
; got = n
})
else Ok (BE_func (func, ok_args))
;;
(** Bind a CASE expression given a [bind] callback for its sub-expressions.
Shared by the three expression binders. *)
let bind_case ~bind ~scrutinee ~branches ~else_ =
let scrutinee_result =
match scrutinee with
| None -> Ok None
| Some e ->
(match bind e with
| Ok be -> Ok (Some be)
| Error e -> Error e)
in
match scrutinee_result with
| Error e -> Error e
| Ok bound_scr ->
let branch_results =
List.map
(fun (cond, res) ->
match bind cond, bind res with
| Ok bc, Ok br -> Ok (bc, br)
| Error e, _ -> Error e
| _, Error e -> Error e)
branches
in
let branch_errors =
List.filter_map
(function
| Error e -> Some e
| Ok _ -> None)
branch_results
in
(match branch_errors with
| e :: _ -> Error e
| [] ->
let bound_branches =
List.filter_map
(function
| Ok p -> Some p
| Error _ -> None)
branch_results
in
let else_result =
match else_ with
| None -> Ok None
| Some e ->
(match bind e with
| Ok be -> Ok (Some be)
| Error e -> Error e)
in
(match else_result with
| Error e -> Error e
| Ok bound_else ->
Ok
(BE_case
{ scrutinee = bound_scr; branches = bound_branches; else_ = bound_else })))
;;
let rec bind_expr ~param_counter ~named_params (meta : Cat.table_meta) = function
| Ast.E_lit l -> Ok (BE_lit l)
| Ast.E_col name ->
(match col_index meta.columns name with
| None -> Error (Unknown_column { table = meta.name; column = name })
| Some i -> Ok (BE_col i))
| Ast.E_tbl_col (_tbl, name) ->
(match col_index meta.columns name with
| None -> Error (Unknown_column { table = meta.name; column = name })
| Some i -> Ok (BE_col i))
| Ast.E_binop (op, a, b) ->
(match
( bind_expr ~param_counter ~named_params meta a
, bind_expr ~param_counter ~named_params meta b )
with
| Ok ba, Ok bb -> Ok (BE_binop (ast_binop_to_sema op, ba, bb))
| Error e, _ -> Error e
| Ok _, Error e -> Error e)
| Ast.E_not e ->
(match bind_expr ~param_counter ~named_params meta e with
| Ok be -> Ok (BE_not be)
| Error e -> Error e)
| Ast.E_is_null e ->
(match bind_expr ~param_counter ~named_params meta e with
| Ok be -> Ok (BE_is_null be)
| Error e -> Error e)
| Ast.E_is_not_null e ->
(match bind_expr ~param_counter ~named_params meta e with
| Ok be -> Ok (BE_is_not_null be)
| Error e -> Error e)
| Ast.E_neg e ->
(match bind_expr ~param_counter ~named_params meta e with
| Ok be -> Ok (BE_neg be)
| Error e -> Error e)
| Ast.E_bitnot e ->
(match bind_expr ~param_counter ~named_params meta e with
| Ok be -> Ok (BE_bitnot be)
| Error e -> Error e)
| Ast.E_between (x, lo, hi) ->
(match
( bind_expr ~param_counter ~named_params meta x
, bind_expr ~param_counter ~named_params meta lo
, bind_expr ~param_counter ~named_params meta hi )
with
| Ok bx, Ok blo, Ok bhi -> Ok (BE_between (bx, blo, bhi))
| Error e, _, _ | _, Error e, _ | _, _, Error e -> Error e)
| Ast.E_in (x, vals) ->
let bx = bind_expr ~param_counter ~named_params meta x in
let bvals = List.map (bind_expr ~param_counter ~named_params meta) vals in
let errors =
List.filter_map
(function
| Error e -> Some e
| Ok _ -> None)
bvals
in
(match bx, errors with
| Error e, _ -> Error e
| _, e :: _ -> Error e
| Ok bx', [] ->
let ok_vals =
List.filter_map
(function
| Ok v -> Some v
| Error _ -> None)
bvals
in
Ok (BE_in (bx', ok_vals)))
| Ast.E_param p -> Ok (BE_param (resolve_param ~param_counter ~named_params p))
| Ast.E_agg _ -> Error (Unsupported "aggregate in WHERE")
| Ast.E_func (func, args) ->
bind_func ~bind:(bind_expr ~param_counter ~named_params meta) func args
| Ast.E_match _ ->
Error (Unsupported "MATCH is only valid as a top-level WHERE clause on FTS tables")
| Ast.E_subquery inner -> Ok (BE_subquery inner)
| Ast.E_exists inner -> Ok (BE_exists inner)
| Ast.E_in_select (x, inner) ->
(match bind_expr ~param_counter ~named_params meta x with
| Error e -> Error e
| Ok bx -> Ok (BE_in_select (bx, inner)))
| Ast.E_case { scrutinee; branches; else_ } ->
bind_case
~bind:(bind_expr ~param_counter ~named_params meta)
~scrutinee
~branches
~else_
| Ast.E_cast (e, ty) ->
(match bind_expr ~param_counter ~named_params meta e with
| Ok be -> Ok (BE_cast (be, ty))
| Error e -> Error e)
| Ast.E_collate (e, c) ->
(match bind_expr ~param_counter ~named_params meta e with
| Ok be -> Ok (BE_collate (be, c))
| Error e -> Error e)
| Ast.E_window _ ->
Error (Unsupported "window functions not yet supported in single-table context")
| Ast.E_fts_snippet _ ->
Error (Unsupported "snippet() is only supported in FTS SELECT projection")
;;
let rec bind_expr_join
~param_counter
~named_params
~(tables : (Cat.table_meta * int * string option) list)
= function
| Ast.E_lit l -> Ok (BE_lit l)
| Ast.E_col name ->
let matches =
List.filter_map
(fun (tm, base, _alias) ->
match col_index tm.Cat.columns name with
| Some i -> Some (BE_col (base + i))
| None -> None)
tables
in
(match matches with
| [ be ] -> Ok be
| [] ->
let tm0, _, _ = List.hd tables in
Error (Unknown_column { table = tm0.Cat.name; column = name })
| _ :: _ -> Error (Ambiguous_column name))
| Ast.E_tbl_col (tbl, name) ->
(match
List.find_opt
(fun (tm, _, alias_opt) ->
String.equal tm.Cat.name tbl
||
match alias_opt with
| Some a -> String.equal tbl a
| None -> false)
tables
with
| None -> Error (Unknown_table tbl)
| Some (tm, base, _) ->
(match col_index tm.Cat.columns name with
| Some i -> Ok (BE_col (base + i))
| None -> Error (Unknown_column { table = tbl; column = name })))
| Ast.E_binop (op, a, b) ->
(match
( bind_expr_join ~param_counter ~named_params ~tables a
, bind_expr_join ~param_counter ~named_params ~tables b )
with
| Ok ba, Ok bb -> Ok (BE_binop (ast_binop_to_sema op, ba, bb))
| Error e, _ -> Error e
| Ok _, Error e -> Error e)
| Ast.E_not e ->
(match bind_expr_join ~param_counter ~named_params ~tables e with
| Ok be -> Ok (BE_not be)
| Error e -> Error e)
| Ast.E_is_null e ->
(match bind_expr_join ~param_counter ~named_params ~tables e with
| Ok be -> Ok (BE_is_null be)
| Error e -> Error e)
| Ast.E_is_not_null e ->
(match bind_expr_join ~param_counter ~named_params ~tables e with
| Ok be -> Ok (BE_is_not_null be)
| Error e -> Error e)
| Ast.E_neg e ->
(match bind_expr_join ~param_counter ~named_params ~tables e with
| Ok be -> Ok (BE_neg be)
| Error e -> Error e)
| Ast.E_bitnot e ->
(match bind_expr_join ~param_counter ~named_params ~tables e with
| Ok be -> Ok (BE_bitnot be)
| Error e -> Error e)
| Ast.E_between (x, lo, hi) ->
(match
( bind_expr_join ~param_counter ~named_params ~tables x
, bind_expr_join ~param_counter ~named_params ~tables lo
, bind_expr_join ~param_counter ~named_params ~tables hi )
with
| Ok bx, Ok blo, Ok bhi -> Ok (BE_between (bx, blo, bhi))
| Error e, _, _ | _, Error e, _ | _, _, Error e -> Error e)
| Ast.E_in (x, vals) ->
let bx = bind_expr_join ~param_counter ~named_params ~tables x in
let bvals = List.map (bind_expr_join ~param_counter ~named_params ~tables) vals in
let errors =
List.filter_map
(function
| Error e -> Some e
| Ok _ -> None)
bvals
in
(match bx, errors with
| Error e, _ -> Error e
| _, e :: _ -> Error e
| Ok bx', [] ->
let ok_vals =
List.filter_map
(function
| Ok v -> Some v
| Error _ -> None)
bvals
in
Ok (BE_in (bx', ok_vals)))
| Ast.E_param p -> Ok (BE_param (resolve_param ~param_counter ~named_params p))
| Ast.E_agg _ -> Error (Unsupported "aggregate in WHERE")
| Ast.E_func (func, args) ->
bind_func ~bind:(bind_expr_join ~param_counter ~named_params ~tables) func args
| Ast.E_match _ -> Error (Unsupported "MATCH in JOIN context")
| Ast.E_subquery inner -> Ok (BE_subquery inner)
| Ast.E_exists inner -> Ok (BE_exists inner)
| Ast.E_in_select (x, inner) ->
(match bind_expr_join ~param_counter ~named_params ~tables x with
| Error e -> Error e
| Ok bx -> Ok (BE_in_select (bx, inner)))
| Ast.E_case { scrutinee; branches; else_ } ->
bind_case
~bind:(bind_expr_join ~param_counter ~named_params ~tables)
~scrutinee
~branches
~else_
| Ast.E_cast (e, ty) ->
(match bind_expr_join ~param_counter ~named_params ~tables e with
| Ok be -> Ok (BE_cast (be, ty))
| Error e -> Error e)
| Ast.E_collate (e, c) ->
(match bind_expr_join ~param_counter ~named_params ~tables e with
| Ok be -> Ok (BE_collate (be, c))
| Error e -> Error e)
| Ast.E_window _ ->
Error (Unsupported "window functions not yet supported in join context")
| Ast.E_fts_snippet _ ->
Error (Unsupported "snippet() is only supported in FTS SELECT projection")
;;
(** Resolve a column reference into a [BE_col i] using a resolver
function. Used by [bind_expr_agg]. *)
type col_resolver =
{ resolve_unqual : string -> (int, error) result
; resolve_qual : string -> string -> (int, error) result
;
resolve_agg_arg : string -> (int, error) result
; resolve_agg_arg_qual : string -> string -> (int, error) result
}
(** Resolve the column ordinal of an aggregate-function argument (the input-row
column the aggregate consumes). [None] is the COUNT-star case. *)
let agg_col_ord
~(resolver : col_resolver)
(func : Ast.agg_func)
(arg_opt : Ast.expr option)
: (int option, error) result
=
match arg_opt with
| None ->
(match func with
| Ast.Agg_count -> Ok None
| _ -> Error (Unsupported "non-COUNT aggregate requires an argument"))
| Some (Ast.E_col name) ->
(match resolver.resolve_agg_arg name with
| Error e -> Error e
| Ok i -> Ok (Some i))
| Some (Ast.E_tbl_col (t, c)) ->
(match resolver.resolve_agg_arg_qual t c with
| Error e -> Error e
| Ok i -> Ok (Some i))
| Some _ -> Error (Unsupported "aggregate argument must be a column reference")
;;
(** Bind expression, collecting aggregates. Aggregates become
[BE_col (offset + slot)] referring to the aggregate output row.
[offset] is 1 when GROUP BY is present (slot 0 holds the group key)
and 0 otherwise. *)
let bind_expr_agg
~param_counter
~named_params
~(resolver : col_resolver)
~(offset : int)
(e : Ast.expr)
: (bound_expr * agg_spec list, error) result
=
let aggs = ref [] in
let add_agg spec =
let idx = List.length !aggs in
aggs := !aggs @ [ spec ];
idx
in
let rec go = function
| Ast.E_lit l -> Ok (BE_lit l)
| Ast.E_col name ->
(match resolver.resolve_unqual name with
| Error e -> Error e
| Ok i -> Ok (BE_col i))
| Ast.E_tbl_col (t, c) ->
(match resolver.resolve_qual t c with
| Error e -> Error e
| Ok i -> Ok (BE_col i))
| Ast.E_binop (op, a, b) ->
(match go a, go b with
| Ok ba, Ok bb -> Ok (BE_binop (ast_binop_to_sema op, ba, bb))
| Error e, _ -> Error e
| Ok _, Error e -> Error e)
| Ast.E_not e ->
(match go e with
| Ok be -> Ok (BE_not be)
| Error e -> Error e)
| Ast.E_is_null e ->
(match go e with
| Ok be -> Ok (BE_is_null be)
| Error e -> Error e)
| Ast.E_is_not_null e ->
(match go e with
| Ok be -> Ok (BE_is_not_null be)
| Error e -> Error e)
| Ast.E_neg e ->
(match go e with
| Ok be -> Ok (BE_neg be)
| Error e -> Error e)
| Ast.E_bitnot e ->
(match go e with
| Ok be -> Ok (BE_bitnot be)
| Error e -> Error e)
| Ast.E_between (x, lo, hi) ->
(match go x, go lo, go hi with
| Ok bx, Ok blo, Ok bhi -> Ok (BE_between (bx, blo, bhi))
| Error e, _, _ | _, Error e, _ | _, _, Error e -> Error e)
| Ast.E_in (x, vals) ->
let bx = go x in
let bvals = List.map go vals in
let errors =
List.filter_map
(function
| Error e -> Some e
| Ok _ -> None)
bvals
in
(match bx, errors with
| Error e, _ -> Error e
| _, e :: _ -> Error e
| Ok bx', [] ->
let ok_vals =
List.filter_map
(function
| Ok v -> Some v
| Error _ -> None)
bvals
in
Ok (BE_in (bx', ok_vals)))
| Ast.E_param p -> Ok (BE_param (resolve_param ~param_counter ~named_params p))
| Ast.E_agg (func, arg_opt) ->
(match agg_col_ord ~resolver func arg_opt with
| Error e -> Error e
| Ok col_ord ->
let slot = add_agg { func; col_ord } in
Ok (BE_col (offset + slot)))
| Ast.E_func (func, args) -> bind_func ~bind:go func args
| Ast.E_match _ ->
Error (Unsupported "MATCH is only valid as a top-level WHERE clause on FTS tables")
| Ast.E_subquery _ | Ast.E_exists _ | Ast.E_in_select _ ->
Error (Unsupported "subqueries are not supported in aggregate expressions")
| Ast.E_case { scrutinee; branches; else_ } ->
bind_case ~bind:go ~scrutinee ~branches ~else_
| Ast.E_cast (e, ty) ->
(match go e with
| Ok be -> Ok (BE_cast (be, ty))
| Error e -> Error e)
| Ast.E_collate (e, c) ->
(match go e with
| Ok be -> Ok (BE_collate (be, c))
| Error e -> Error e)
| Ast.E_window _ ->
Error (Unsupported "window functions not yet supported in aggregate context")
| Ast.E_fts_snippet _ ->
Error (Unsupported "snippet() is only supported in FTS SELECT projection")
in
match go e with
| Error e -> Error e
| Ok be -> Ok (be, !aggs)
;;
(** Check if any subquery node appears anywhere in a [bound_expr]. *)
let rec expr_has_subquery = function
| BE_subquery _ | BE_exists _ -> true
| BE_in_select _ -> true
| BE_binop (_, a, b) -> expr_has_subquery a || expr_has_subquery b
| BE_not e | BE_is_null e | BE_is_not_null e | BE_neg e | BE_bitnot e ->
expr_has_subquery e
| BE_between (x, lo, hi) ->
expr_has_subquery x || expr_has_subquery lo || expr_has_subquery hi
| BE_in (x, vals) -> expr_has_subquery x || List.exists expr_has_subquery vals
| BE_func (_, args) -> List.exists expr_has_subquery args
| BE_lit _ | BE_col _ | BE_param _ | BE_match _ -> false
| BE_case { scrutinee; branches; else_ } ->
(match scrutinee with
| Some e -> expr_has_subquery e
| None -> false)
|| List.exists (fun (c, r) -> expr_has_subquery c || expr_has_subquery r) branches
||
(match else_ with
| Some e -> expr_has_subquery e
| None -> false)
| BE_cast (e, _) -> expr_has_subquery e
| BE_collate (e, _) -> expr_has_subquery e
| BE_excluded_col _ -> false
| BE_window_slot _ -> false
;;
(** Check if any [E_agg] appears anywhere in an [expr]. *)
let rec expr_has_agg = function
| Ast.E_agg _ -> true
| Ast.E_lit _ | Ast.E_col _ | Ast.E_tbl_col _ | Ast.E_param _ | Ast.E_match _ -> false
| Ast.E_subquery _ | Ast.E_exists _ -> false
| Ast.E_in_select (x, _) -> expr_has_agg x
| Ast.E_binop (_, a, b) -> expr_has_agg a || expr_has_agg b
| Ast.E_not e | Ast.E_is_null e | Ast.E_is_not_null e | Ast.E_neg e | Ast.E_bitnot e ->
expr_has_agg e
| Ast.E_between (x, lo, hi) -> expr_has_agg x || expr_has_agg lo || expr_has_agg hi
| Ast.E_in (x, vals) -> expr_has_agg x || List.exists expr_has_agg vals
| Ast.E_func (_, args) -> List.exists expr_has_agg args
| Ast.E_case { scrutinee; branches; else_ } ->
(match scrutinee with
| Some e -> expr_has_agg e
| None -> false)
|| List.exists (fun (c, r) -> expr_has_agg c || expr_has_agg r) branches
||
(match else_ with
| Some e -> expr_has_agg e
| None -> false)
| Ast.E_cast (e, _) -> expr_has_agg e
| Ast.E_collate (e, _) -> expr_has_agg e
| Ast.E_window _ -> false
| Ast.E_fts_snippet _ -> false
;;
let rec expr_has_window = function
| Ast.E_window _ -> true
| Ast.E_binop (_, a, b) -> expr_has_window a || expr_has_window b
| Ast.E_not e | Ast.E_neg e | Ast.E_is_null e | Ast.E_is_not_null e | Ast.E_bitnot e ->
expr_has_window e
| Ast.E_between (x, lo, hi) ->
expr_has_window x || expr_has_window lo || expr_has_window hi
| Ast.E_in (x, vals) -> expr_has_window x || List.exists expr_has_window vals
| Ast.E_func (_, args) -> List.exists expr_has_window args
| Ast.E_case { scrutinee; branches; else_ } ->
(match scrutinee with
| Some e -> expr_has_window e
| None -> false)
|| List.exists (fun (c, r) -> expr_has_window c || expr_has_window r) branches
||
(match else_ with
| Some e -> expr_has_window e
| None -> false)
| Ast.E_cast (e, _) -> expr_has_window e
| Ast.E_collate (e, _) -> expr_has_window e
| _ -> false
;;
let rec check_expr_unsupported = function
| Ast.E_agg _
| Ast.E_match _
| Ast.E_subquery _
| Ast.E_exists _
| Ast.E_in_select _
| Ast.E_param _ -> true
| Ast.E_binop (_, a, b) -> check_expr_unsupported a || check_expr_unsupported b
| Ast.E_not e | Ast.E_is_null e | Ast.E_is_not_null e | Ast.E_neg e | Ast.E_bitnot e ->
check_expr_unsupported e
| Ast.E_between (x, lo, hi) ->
check_expr_unsupported x || check_expr_unsupported lo || check_expr_unsupported hi
| Ast.E_in (x, vals) ->
check_expr_unsupported x || List.exists check_expr_unsupported vals
| Ast.E_func (_, args) -> List.exists check_expr_unsupported args
| Ast.E_lit _ | Ast.E_col _ | Ast.E_tbl_col _ -> false
| Ast.E_case { scrutinee; branches; else_ } ->
(match scrutinee with
| Some e -> check_expr_unsupported e
| None -> false)
|| List.exists
(fun (c, r) -> check_expr_unsupported c || check_expr_unsupported r)
branches
||
(match else_ with
| Some e -> check_expr_unsupported e
| None -> false)
| Ast.E_cast _ -> false
| Ast.E_collate (e, _) -> check_expr_unsupported e
| Ast.E_window _ -> true
| Ast.E_fts_snippet _ -> true
;;
let column_of_def (c : Ast.column_def) : Row.column =
let ast_lit_to_dv : Ast.literal -> Row.default_value = function
| Ast.L_int n -> Row.DV_int n
| Ast.L_text s -> Row.DV_text s
| Ast.L_null -> Row.DV_null
| Ast.L_real f -> Row.DV_real f
| Ast.L_blob b -> Row.DV_blob b
| Ast.L_current_timestamp -> Row.DV_current_timestamp
| Ast.L_current_date -> Row.DV_current_date
| Ast.L_current_time -> Row.DV_current_time
in
Row.
{ name = c.name
; ty =
(match c.ty with
| Ast.Ty_int -> Row.Integer
| Ast.Ty_text -> Row.Text
| Ast.Ty_real -> Row.Real
| Ast.Ty_blob -> Row.Blob)
; not_null = c.not_null || c.primary_key
; primary_key = c.primary_key
; pk_desc = c.pk_desc
; default = Option.map ast_lit_to_dv c.default
; check_sql = Option.map Ast.expr_to_sql c.check
; generated_as =
Option.map (fun (e, s) -> Ast.expr_to_sql e, s = `Stored) c.generated_as
}
;;
let auto_unique_indexes ~name ~constraints ~columns ~rowid_alias_col_name =
let is_alias cols =
match rowid_alias_col_name, cols with
| Some n, [ c ] -> String.equal n c
| _ -> false
in
let tbl_uniq_idxs =
List.filter_map
(fun (i, tc) ->
match tc with
| Ast.TC_unique cols ->
Some
( Printf.sprintf "__uniq_%s_%s_%d" name (String.concat "_" cols) i
, cols
, `Implicit_unique )
| Ast.TC_primary_key { pk_cols = cols; _ } when is_alias cols -> None
| Ast.TC_primary_key { pk_cols = cols; _ } ->
Some
( Printf.sprintf "__pk_%s_%s_%d" name (String.concat "_" cols) i
, cols
, `Implicit_pk )
| Ast.TC_foreign_key _ -> None)
(List.mapi (fun i tc -> i, tc) constraints)
in
let col_pk_idxs =
List.filter_map
(fun (c : Ast.column_def) ->
if c.primary_key && not (is_alias [ c.name ])
then Some (Printf.sprintf "__pk_%s_%s" name c.name, [ c.name ], `Implicit_pk)
else None)
columns
in
tbl_uniq_idxs @ col_pk_idxs
;;
let mark_table_pk constraints row_cols =
List.fold_left
(fun cols c ->
match c with
| Ast.TC_primary_key { pk_cols = [ pk_col ]; _ } ->
List.map
(fun (col : Row.column) ->
if String.equal col.name pk_col
then { col with primary_key = true }
else col)
cols
| _ -> cols)
row_cols
constraints
;;
let cat ~columns ~constraints =
let col_fks_result =
List.fold_left
(fun acc (cd : Ast.column_def) ->
match acc with
| Error _ as e -> e
| Ok fks ->
(match cd.Ast.fk_ref with
| None -> Ok fks
| Some (parent_table, "", od, ou, def) ->
(match Cat.find_table_cached cat ~name:parent_table with
| None ->
Error
(Unsupported
(Printf.sprintf
"FOREIGN KEY on '%s': parent table '%s' not found"
cd.Ast.name
parent_table))
| Some parent_meta ->
if Cat.is_columnar parent_meta
then
Error
(Unsupported
(Printf.sprintf
"FOREIGN KEY on '%s': cannot reference columnar table '%s'"
cd.Ast.name
parent_table))
else (
match
List.find_opt
(fun (c : Row.column) -> c.primary_key)
parent_meta.Cat.columns
with
| None ->
Error
(Unsupported
(Printf.sprintf
"FOREIGN KEY on '%s': table '%s' has no PRIMARY KEY to \
infer column"
cd.Ast.name
parent_table))
| Some pk_col ->
Ok
(fks
@ [ [ cd.Ast.name ], parent_table, [ pk_col.name ], od, ou, def ]
)))
| Some (parent_table, parent_col, od, ou, def) ->
(match Cat.find_table_cached cat ~name:parent_table with
| Some parent_meta when Cat.is_columnar parent_meta ->
Error
(Unsupported
(Printf.sprintf
"FOREIGN KEY on '%s': cannot reference columnar table '%s'"
cd.Ast.name
parent_table))
| _ ->
Ok (fks @ [ [ cd.Ast.name ], parent_table, [ parent_col ], od, ou, def ]))))
(Ok [])
columns
in
match col_fks_result with
| Error e -> Error e
| Ok col_fks ->
let tbl_fks_result =
List.fold_left
(fun acc c ->
match acc with
| Error _ as e -> e
| Ok fks ->
(match c with
| Ast.TC_foreign_key
{ local_cols
; parent_table
; parent_cols
; on_delete
; on_update
; deferrable
} ->
(match Cat.find_table_cached cat ~name:parent_table with
| Some parent_meta when Cat.is_columnar parent_meta ->
Error
(Unsupported
(Printf.sprintf
"FOREIGN KEY constraint: cannot reference columnar table '%s'"
parent_table))
| _ ->
Ok
(fks
@ [ ( local_cols
, parent_table
, parent_cols
, on_delete
, on_update
, deferrable )
]))
| _ -> Ok fks))
(Ok [])
constraints
in
(match tbl_fks_result with
| Error e -> Error e
| Ok tbl_fks -> Ok (col_fks @ tbl_fks))
;;
let validate_without_rowid ~name ~without_rowid row_cols =
if not without_rowid
then Ok ()
else (
match List.filter (fun (c : Row.column) -> c.primary_key) row_cols with
| [] ->
Error
(Unsupported
(Printf.sprintf "WITHOUT ROWID table '%s' requires a PRIMARY KEY column" name))
| _ :: _ :: _ ->
Error
(Unsupported
(Printf.sprintf
"WITHOUT ROWID table '%s' must have exactly one PRIMARY KEY column \
(composite PKs not supported in phase 37)"
name))
| [ pk ] when pk.ty <> Row.Integer ->
Error
(Unsupported
(Printf.sprintf
"WITHOUT ROWID table '%s': PRIMARY KEY column '%s' must be INTEGER in \
phase 37"
name
pk.name))
| [ _ ] -> Ok ())
;;
let validate_autoincrement ~without_rowid (columns : Ast.column_def list) row_cols =
if not (List.exists (fun (c : Ast.column_def) -> c.autoincrement) columns)
then Ok false
else if without_rowid
then Error (Unsupported "AUTOINCREMENT not allowed on WITHOUT ROWID tables")
else (
match Cat.compute_rowid_alias_col row_cols ~without_rowid with
| Some i when (List.nth columns i).Ast.autoincrement -> Ok true
| _ -> Error (Unsupported "AUTOINCREMENT is only allowed on an INTEGER PRIMARY KEY"))
;;
let reject_reserved_name name =
if String.starts_with ~prefix:"sqlite_" (String.lowercase_ascii name)
then
Error (Unsupported (Printf.sprintf "object name reserved for internal use: %s" name))
else Ok ()
;;
let bind_create
cat
~name
~columns
~constraints
~if_not_exists
~without_rowid
~using_columnstore
=
match reject_reserved_name name with
| Error e -> Lwt.return (Error e)
| Ok () ->
if using_columnstore
then
let* existing = Cat.find_table cat ~name in
match existing with
| Some _ when not if_not_exists -> Lwt.return (Error (Already_exists name))
| Some _ ->
Lwt.return (Ok (BS_col_create_table { name; columns = []; if_not_exists = true }))
| None ->
Lwt.return
(Ok
(BS_col_create_table
{ name; columns = List.map column_of_def columns; if_not_exists }))
else
let* existing = Cat.find_table cat ~name in
(match existing with
| Some _ when not if_not_exists -> Lwt.return (Error (Already_exists name))
| Some _ ->
Lwt.return
(Ok
(BS_create_table
{ name
; columns = []
; uniq_idxs = []
; if_not_exists = true
; fk_constraints = []
; without_rowid
; autoincrement = false
}))
| None ->
let unsupported_check =
List.find_opt
(fun (c : Ast.column_def) ->
match c.check with
| None -> false
| Some e -> check_expr_unsupported e)
columns
in
(match unsupported_check with
| Some col ->
Lwt.return
(Error
(Unsupported
(Printf.sprintf
"CHECK constraint on column '%s' contains unsupported expression \
form (aggregates, subqueries, and parameters are not allowed)"
col.name)))
| None ->
let tc_ai_cols =
List.concat_map
(function
| Ast.TC_primary_key { pk_cols; autoincrement = true } -> pk_cols
| _ -> [])
constraints
in
let columns =
if tc_ai_cols = []
then columns
else
List.map
(fun (c : Ast.column_def) ->
if List.mem c.name tc_ai_cols
then { c with autoincrement = true }
else c)
columns
in
let row_cols = mark_table_pk constraints (List.map column_of_def columns) in
let rowid_alias_col_name =
Option.map
(fun i -> (List.nth row_cols i).Row.name)
(Cat.compute_rowid_alias_col row_cols ~without_rowid)
in
let uniq_idxs =
auto_unique_indexes ~name ~constraints ~columns ~rowid_alias_col_name
in
(match extract_fk_constraints cat ~columns ~constraints with
| Error e -> Lwt.return (Error e)
| Ok fk_constraints ->
(match validate_without_rowid ~name ~without_rowid row_cols with
| Error e -> Lwt.return (Error e)
| Ok () ->
(match validate_autoincrement ~without_rowid columns row_cols with
| Error e -> Lwt.return (Error e)
| Ok autoincrement ->
Lwt.return
(Ok
(BS_create_table
{ name
; columns = row_cols
; uniq_idxs
; if_not_exists
; fk_constraints
; without_rowid
; autoincrement
})))))))
;;
(** Convert a [Row.default_value] to a [bound_expr] suitable for INSERT planning. *)
let dv_to_bound_expr : Row.default_value -> bound_expr = function
| Row.DV_int n -> BE_lit (Ast.L_int n)
| Row.DV_text s -> BE_lit (Ast.L_text s)
| Row.DV_null -> BE_lit Ast.L_null
| Row.DV_real f -> BE_lit (Ast.L_real f)
| Row.DV_blob b -> BE_lit (Ast.L_blob b)
| Row.DV_current_timestamp -> BE_func (Ast.Fn_datetime, [ BE_lit (Ast.L_text "now") ])
| Row.DV_current_date -> BE_func (Ast.Fn_date, [ BE_lit (Ast.L_text "now") ])
| Row.DV_current_time -> BE_func (Ast.Fn_time, [ BE_lit (Ast.L_text "now") ])
;;
let bind_fts_insert cat ~param_counter ~named_params ~table ~columns ~values =
match Cat.find_fts cat table with
| None -> Lwt.return (Error (Unknown_table table))
| Some fts_meta ->
let fts_cols = fts_meta.Cat.fts_columns in
let columns = if columns = [] then fts_cols else columns in
let synth_meta = fts_as_table_meta fts_meta in
let bind_value_expr (e : Ast.expr) : (bound_expr, error) result =
match e with
| Ast.E_lit _ | Ast.E_neg _ | Ast.E_param _ ->
bind_expr ~param_counter ~named_params synth_meta e
| _ -> Error (Unsupported "complex expression in INSERT VALUES")
in
let n_cols = List.length columns in
let n_vals = List.length values in
if n_cols <> n_vals
then Lwt.return (Error (Arity_mismatch { expected = n_cols; got = n_vals }))
else (
let pairs = List.combine columns values in
let is_rowid c = String.lowercase_ascii c = "rowid" in
let rowid_pairs, content_pairs = List.partition (fun (c, _) -> is_rowid c) pairs in
let content_cols = List.map fst content_pairs in
let bad = List.find_opt (fun c -> not (List.mem c fts_cols)) content_cols in
match bad with
| Some col -> Lwt.return (Error (Unknown_column { table; column = col }))
| None ->
let rowid_value_res =
match rowid_pairs with
| [] -> Ok None
| [ (_, e) ] -> Result.map Option.some (bind_value_expr e)
| _ -> Error (Unsupported "rowid specified more than once in INSERT")
in
let content_results = List.map (fun (_, e) -> bind_value_expr e) content_pairs in
let errors =
List.filter_map
(function
| Error e -> Some e
| Ok _ -> None)
content_results
in
(match rowid_value_res, errors with
| Error e, _ -> Lwt.return (Error e)
| _, e :: _ -> Lwt.return (Error e)
| Ok rowid_value, [] ->
let col_values = List.filter_map Result.to_option content_results in
Lwt.return
(Ok
(BS_fts_insert
{ fts_meta; col_names = content_cols; col_values; rowid_value }))))
;;
let bind_returning_exprs
~param_counter
~named_params
(meta : Cat.table_meta)
(exprs : Ast.expr list)
=
List.fold_left
(fun acc re ->
match acc with
| Error _ -> acc
| Ok bexprs ->
(match bind_expr ~param_counter ~named_params meta re with
| Error e -> Error e
| Ok be ->
if expr_has_subquery be
then Error (Unsupported "subqueries in RETURNING are not supported")
else Ok (bexprs @ [ be ])))
(Ok [])
exprs
;;
let bind_upsert_rhs_expr
~param_counter
~named_params
(meta : Cat.table_meta)
(e : Ast.expr)
=
match e with
| Ast.E_tbl_col (tbl, col) when String.equal (String.uppercase_ascii tbl) "EXCLUDED" ->
(match col_index meta.columns col with
| None -> Error (Unknown_column { table = "excluded"; column = col })
| Some i -> Ok (BE_excluded_col i))
| other -> bind_expr ~param_counter ~named_params meta other
;;
let bind_upsert_assignments
~param_counter
~named_params
(meta : Cat.table_meta)
(assigns : (string * Ast.expr) list)
=
List.fold_left
(fun acc (col_name, rhs_expr) ->
match acc with
| Error _ -> acc
| Ok bound_list ->
(match col_index meta.columns col_name with
| None -> Error (Unknown_column { table = meta.name; column = col_name })
| Some i ->
(match bind_upsert_rhs_expr ~param_counter ~named_params meta rhs_expr with
| Error e -> Error e
| Ok be -> Ok (bound_list @ [ i, be ]))))
(Ok [])
assigns
;;
let bind_explicit_insert_cols
~param_counter
~named_params
~(meta : Cat.table_meta)
~table
~columns
row_vals
=
let bind_value_expr (e : Ast.expr) : (bound_expr, error) result =
match e with
| Ast.E_lit _ | Ast.E_neg _ | Ast.E_param _ ->
bind_expr ~param_counter ~named_params meta e
| _ -> Error (Unsupported "complex expression in INSERT VALUES")
in
List.fold_left2
(fun acc col_name expr_ast ->
match acc with
| Error _ -> acc
| Ok map ->
(match col_index meta.columns col_name with
| None -> Error (Unknown_column { table; column = col_name })
| Some i ->
let col = List.nth meta.columns i in
if col.Row.generated_as <> None
then
Error
(Unsupported
(Printf.sprintf
"cannot INSERT into generated column '%s'"
col.Row.name))
else (
match bind_value_expr expr_ast with
| Error e -> Error e
| Ok bexpr ->
(match bexpr with
| BE_param _ -> Ok (map @ [ i, bexpr ])
| BE_lit lit ->
let col = List.nth meta.columns i in
(match lit_ty lit with
| None -> Ok (map @ [ i, bexpr ])
| Some t ->
if ty_equal t col.ty
then Ok (map @ [ i, bexpr ])
else Error (Type_mismatch { expected = col.ty; got = t }))
| _ -> Ok (map @ [ i, bexpr ])))))
(Ok [])
columns
row_vals
;;
let bind_insert_row
~param_counter
~named_params
~(meta : Cat.table_meta)
~table
~columns
row_vals
=
let n_cols = List.length columns in
let n_vals = List.length row_vals in
if n_cols <> n_vals
then Error (Arity_mismatch { expected = n_cols; got = n_vals })
else (
match
bind_explicit_insert_cols
~param_counter
~named_params
~meta
~table
~columns
row_vals
with
| Error e -> Error e
| Ok explicit_map ->
let n_table_cols = List.length meta.columns in
let full_pairs =
List.init n_table_cols (fun i ->
let col = List.nth meta.columns i in
match List.assoc_opt i explicit_map with
| Some bexpr -> i, bexpr
| None ->
let bexpr =
match col.Row.default with
| Some dv -> dv_to_bound_expr dv
| None -> BE_lit Ast.L_null
in
i, bexpr)
in
let alias_col = Cat.rowid_alias_col meta in
let nn_result =
List.fold_left
(fun acc (i, bexpr) ->
match acc with
| Error _ -> acc
| Ok () ->
let col = List.nth meta.columns i in
(match bexpr with
| BE_lit Ast.L_null when col.Row.not_null && Some i <> alias_col ->
Error (Not_null_violation col.Row.name)
| _ -> Ok ()))
(Ok ())
full_pairs
in
(match nn_result with
| Error e -> Error e
| Ok () ->
let ordinals = List.map fst full_pairs in
let full_vals = List.map snd full_pairs in
Ok (ordinals, full_vals)))
;;
let finalize_insert
~param_counter
~named_params
~(meta : Cat.table_meta)
~on_conflict
~returning
~upsert_update
~ordinals
~all_vals
=
match bind_returning_exprs ~param_counter ~named_params meta returning with
| Error e -> Lwt.return (Error e)
| Ok ret_bound ->
let upsert_result =
match upsert_update with
| None -> Ok None
| Some Ast.{ conflict_cols; assignments } ->
(match bind_upsert_assignments ~param_counter ~named_params meta assignments with
| Error e -> Error e
| Ok bound_assigns -> Ok (Some (conflict_cols, bound_assigns)))
in
(match upsert_result with
| Error e -> Lwt.return (Error e)
| Ok bound_upsert ->
Lwt.return
(Ok
(BS_insert
{ table_meta = meta
; ordinals
; values = all_vals
; on_conflict
; returning = ret_bound
; upsert_update = bound_upsert
})))
;;
let bind_insert
cat
~param_counter
~named_params
~table
~columns
~values
~on_conflict
~returning
~upsert_update
=
let* meta_opt = Cat.find_table cat ~name:table in
match meta_opt with
| None ->
bind_fts_insert
cat
~param_counter
~named_params
~table
~columns
~values:(List.concat values)
| Some meta ->
let columns =
if columns = [] then List.map (fun c -> c.Row.name) meta.columns else columns
in
let rows_result =
List.fold_left
(fun acc row ->
match acc with
| Error e -> Error e
| Ok bound_rows ->
(match
bind_insert_row ~param_counter ~named_params ~meta ~table ~columns row
with
| Error e -> Error e
| Ok (ords, vals) -> Ok (bound_rows @ [ ords, vals ])))
(Ok [])
values
in
(match rows_result with
| Error e -> Lwt.return (Error e)
| Ok [] -> Lwt.return (Error (Unsupported "INSERT with empty VALUES list"))
| Ok ((ordinals, _) :: _ as bound_rows) ->
let all_vals = List.map snd bound_rows in
finalize_insert
~param_counter
~named_params
~meta
~on_conflict
~returning
~upsert_update
~ordinals
~all_vals)
;;
let fts_col_index (fts_meta : Cat.fts_table_meta) name =
let rec find i = function
| [] -> None
| c :: _ when String.equal c name -> Some i
| _ :: rest -> find (i + 1) rest
in
find 0 fts_meta.Cat.fts_columns
;;
let fts_proj_fold (fts_meta : Cat.fts_table_meta) exprs =
List.fold_left
(fun acc (e, _alias) ->
match acc with
| Error _ as err -> err
| Ok (ords, has_rank, snips) ->
(match e with
| Ast.E_col col_name ->
if String.equal (String.lowercase_ascii col_name) "rank"
then Ok (ords, true, snips)
else (
match fts_col_index fts_meta col_name with
| None ->
Error
(Unknown_column { table = fts_meta.Cat.fts_name; column = col_name })
| Some i -> Ok (ords @ [ i ], has_rank, snips))
| Ast.E_fts_snippet { table; col_idx; start_tag; end_tag; ellipsis; n_tokens }
->
if
not
(String.equal
(String.lowercase_ascii table)
(String.lowercase_ascii fts_meta.Cat.fts_name))
then Error (Unknown_table table)
else
Ok
( ords
, has_rank
, snips @ [ Plan.{ col_idx; start_tag; end_tag; ellipsis; n_tokens } ] )
| _ ->
Error
(Unsupported
"only column references and snippet() are supported in FTS SELECT")))
(Ok ([], false, []))
exprs
;;
let bind_fts_match_scan (fts_meta : Cat.fts_table_meta) ~query proj =
match proj with
| `All ->
let all_real_ords = List.mapi (fun i _ -> i) fts_meta.Cat.fts_columns in
Ok
(BS_fts_match_scan
{ fts_meta; query; proj = all_real_ords; include_rank = false; snippets = [] })
| `Cols names ->
let has_rank = List.exists (String.equal "rank") names in
let real_ords =
List.filter_map
(fun name ->
if String.equal name "rank" then None else fts_col_index fts_meta name)
names
in
Ok
(BS_fts_match_scan
{ fts_meta; query; proj = real_ords; include_rank = has_rank; snippets = [] })
| `Exprs exprs ->
(match fts_proj_fold fts_meta exprs with
| Error e -> Error e
| Ok (col_ords, include_rank, snippets) ->
Ok (BS_fts_match_scan { fts_meta; query; proj = col_ords; include_rank; snippets }))
;;
let bind_fts_seq_scan cat ~param_counter ~named_params ~table ~where ~proj =
match Cat.find_fts cat table with
| None -> Lwt.return (Error (Unknown_table table))
| Some fts_meta ->
(match where with
| Some (Ast.E_match (match_table, query_str)) ->
if not (String.equal match_table fts_meta.Cat.fts_name)
then Lwt.return (Error (Unknown_table match_table))
else (
match Fts_query.parse query_str with
| Error msg -> Lwt.return (Error (Unsupported ("FTS query parse error: " ^ msg)))
| Ok q -> Lwt.return (bind_fts_match_scan fts_meta ~query:q proj))
| _ ->
let synth_meta = fts_as_table_meta fts_meta in
let where_result =
match where with
| None -> Ok None
| Some e ->
(match bind_expr ~param_counter ~named_params synth_meta e with
| Ok be -> Ok (Some be)
| Error e -> Error e)
in
(match where_result with
| Error e -> Lwt.return (Error e)
| Ok bound_where ->
Lwt.return (Ok (BS_fts_seq_scan { fts_meta; where = bound_where }))))
;;
let ( let$ ) (r : ('a, error) result) (f : 'a -> ('b, error) result Lwt.t)
: ('b, error) result Lwt.t
=
match r with
| Error e -> Lwt.return (Error e)
| Ok x -> f x
;;
let select_find_pos lst v =
let rec go i = function
| [] -> None
| x :: _ when x = v -> Some i
| _ :: rest -> go (i + 1) rest
in
go 0 lst
;;
let select_proj_lookup
~(tables : (Cat.table_meta * int * string option) list)
~(meta : Cat.table_meta)
name
: (int, error) result
=
let hits =
List.filter_map
(fun (tm, base, _alias) ->
match col_index tm.Cat.columns name with
| Some i -> Some (base + i)
| None -> None)
tables
in
match hits with
| [ i ] -> Ok i
| [] -> Error (Unknown_column { table = meta.Cat.name; column = name })
| _ :: _ -> Error (Ambiguous_column name)
;;
let select_qual_lookup ~(tables : (Cat.table_meta * int * string option) list) t c
: (int, error) result
=
match
List.find_opt
(fun (tm, _, alias_opt) ->
String.equal tm.Cat.name t
||
match alias_opt with
| Some a -> String.equal t a
| None -> false)
tables
with
| None -> Error (Unknown_table t)
| Some (tm, base, _) ->
(match col_index tm.Cat.columns c with
| Some i -> Ok (base + i)
| None -> Error (Unknown_column { table = t; column = c }))
;;
let bind_select_group_cols
~(tables : (Cat.table_meta * int * string option) list)
~(meta : Cat.table_meta)
group_by
: (int list, error) result
=
let result =
List.fold_left
(fun acc (col_name, qualifier) ->
match acc with
| Error _ as e -> e
| Ok indices ->
(match qualifier with
| Some table ->
(match select_qual_lookup ~tables table col_name with
| Ok i -> Ok (i :: indices)
| Error e -> Error e)
| None ->
(match (select_proj_lookup ~tables ~meta) col_name with
| Ok i -> Ok (i :: indices)
| Error _ ->
let found =
List.find_map
(fun (tm, _, _) ->
match (select_qual_lookup ~tables) tm.Cat.name col_name with
| Ok i -> Some i
| Error _ -> None)
tables
in
(match found with
| Some i -> Ok (i :: indices)
| None -> Error (Unknown_column { table = ""; column = col_name })))))
(Ok [])
group_by
in
match result with
| Ok indices -> Ok (List.rev indices)
| Error _ as e -> e
;;
let rec bind_proj_ww ~bind_one ~windows_queue e =
if not (expr_has_window e)
then Lwt.return (bind_one e)
else (
match e with
| Ast.E_window { func; args; window } ->
bind_ww_window ~bind_one ~windows_queue func args window
| Ast.E_binop (op, a, b) ->
let* ba = bind_proj_ww ~bind_one ~windows_queue a in
let* bb = bind_proj_ww ~bind_one ~windows_queue b in
(match ba, bb with
| Ok ba', Ok bb' -> Lwt.return (Ok (BE_binop (ast_binop_to_sema op, ba', bb')))
| Error er, _ | _, Error er -> Lwt.return (Error er))
| Ast.E_not a ->
let* ba = bind_proj_ww ~bind_one ~windows_queue a in
Lwt.return (Result.map (fun x -> BE_not x) ba)
| Ast.E_neg a ->
let* ba = bind_proj_ww ~bind_one ~windows_queue a in
Lwt.return (Result.map (fun x -> BE_neg x) ba)
| Ast.E_is_null a ->
let* ba = bind_proj_ww ~bind_one ~windows_queue a in
Lwt.return (Result.map (fun x -> BE_is_null x) ba)
| Ast.E_is_not_null a ->
let* ba = bind_proj_ww ~bind_one ~windows_queue a in
Lwt.return (Result.map (fun x -> BE_is_not_null x) ba)
| Ast.E_bitnot a ->
let* ba = bind_proj_ww ~bind_one ~windows_queue a in
Lwt.return (Result.map (fun x -> BE_bitnot x) ba)
| Ast.E_between (x, lo, hi) ->
let* bx = bind_proj_ww ~bind_one ~windows_queue x in
let* blo = bind_proj_ww ~bind_one ~windows_queue lo in
let* bhi = bind_proj_ww ~bind_one ~windows_queue hi in
(match bx, blo, bhi with
| Ok x', Ok lo', Ok hi' -> Lwt.return (Ok (BE_between (x', lo', hi')))
| Error er, _, _ | _, Error er, _ | _, _, Error er -> Lwt.return (Error er))
| Ast.E_case { scrutinee; branches; else_ } ->
bind_ww_case ~bind_one ~windows_queue scrutinee branches else_
| Ast.E_func (f, fargs) ->
let* bargs =
Lwt_list.fold_left_s
(fun acc a ->
match acc with
| Error er -> Lwt.return (Error er)
| Ok bs ->
let* r = bind_proj_ww ~bind_one ~windows_queue a in
Lwt.return (Result.map (fun b -> bs @ [ b ]) r))
(Ok [])
fargs
in
Lwt.return (Result.map (fun ba -> BE_func (f, ba)) bargs)
| Ast.E_cast (e, ty) ->
let* be = bind_proj_ww ~bind_one ~windows_queue e in
Lwt.return (Result.map (fun x -> BE_cast (x, ty)) be)
| Ast.E_collate (e, c) ->
let* be = bind_proj_ww ~bind_one ~windows_queue e in
Lwt.return (Result.map (fun x -> BE_collate (x, c)) be)
| _ -> Lwt.return (bind_one e))
and bind_ww_window ~bind_one ~windows_queue func args window =
match window.Ast.frame with
| Some _
when match func with
| Ast.WF_agg _ -> false
| _ -> true ->
Lwt.return
(Error
(Unsupported
"ROWS/RANGE frame spec is only supported for aggregate window functions"))
| _ ->
let slot = Queue.length windows_queue in
let bind_list es =
List.fold_left
(fun acc_r ex ->
match acc_r with
| Error _ as err -> err
| Ok acc ->
(match bind_one ex with
| Error er -> Error er
| Ok be -> Ok (acc @ [ be ])))
(Ok [])
es
in
let bind_ok_list es =
List.fold_left
(fun acc_r (ok : Ast.order_key) ->
match acc_r with
| Error _ as err -> err
| Ok acc ->
(match bind_one ok.Ast.expr with
| Error er -> Error er
| Ok be ->
Ok (acc @ [ { key = be; dir = ok.Ast.dir; nulls = ok.Ast.nulls } ])))
(Ok [])
es
in
(match bind_list args with
| Error er -> Lwt.return (Error er)
| Ok bound_args ->
(match bind_list window.Ast.partition_by with
| Error er -> Lwt.return (Error er)
| Ok bound_pb ->
(match bind_ok_list window.Ast.order_by with
| Error er -> Lwt.return (Error er)
| Ok bound_ob ->
let ws =
{ func
; args = bound_args
; partition_by = bound_pb
; order_by = bound_ob
; frame = window.Ast.frame
}
in
Queue.push ws windows_queue;
Lwt.return (Ok (BE_window_slot slot)))))
and bind_ww_case ~bind_one ~windows_queue scrutinee branches else_ =
let* bscr =
match scrutinee with
| None -> Lwt.return (Ok None)
| Some e ->
let* r = bind_proj_ww ~bind_one ~windows_queue e in
Lwt.return (Result.map Option.some r)
in
let* bbranches =
Lwt_list.fold_left_s
(fun acc (c, r) ->
match acc with
| Error er -> Lwt.return (Error er)
| Ok bs ->
let* bc = bind_proj_ww ~bind_one ~windows_queue c in
let* br = bind_proj_ww ~bind_one ~windows_queue r in
(match bc, br with
| Ok c', Ok r' -> Lwt.return (Ok (bs @ [ c', r' ]))
| Error er, _ | _, Error er -> Lwt.return (Error er)))
(Ok [])
branches
in
let* belse_ =
match else_ with
| None -> Lwt.return (Ok None)
| Some e ->
let* r = bind_proj_ww ~bind_one ~windows_queue e in
Lwt.return (Result.map Option.some r)
in
match bscr, bbranches, belse_ with
| Ok scr, Ok brs, Ok el ->
Lwt.return (Ok (BE_case { scrutinee = scr; branches = brs; else_ = el }))
| Error er, _, _ | _, Error er, _ | _, _, Error er -> Lwt.return (Error er)
;;
let bind_unaggregated_proj
~param_counter
~named_params
~(tables : (Cat.table_meta * int * string option) list)
~(meta : Cat.table_meta)
proj
=
let bind_one e = bind_expr_join ~param_counter ~named_params ~tables e in
let windows_queue : window_sema Queue.t = Queue.create () in
let ords_result_lwt =
match proj with
| `All ->
let all_ords =
List.concat_map
(fun (tm, base, _alias) -> List.mapi (fun i _ -> base + i) tm.Cat.columns)
tables
in
Lwt.return (Ok (`Ords all_ords))
| `Cols names ->
Lwt.return
(List.fold_left
(fun acc name ->
match acc with
| Error _ -> acc
| Ok (`Exprs _) -> acc
| Ok (`Ords ords) ->
(match select_proj_lookup ~tables ~meta name with
| Error e -> Error e
| Ok i -> Ok (`Ords (ords @ [ i ]))))
(Ok (`Ords []))
names)
| `Exprs es ->
let* bound_list =
Lwt_list.map_s
(fun (e, alias) ->
let* r = bind_proj_ww ~bind_one ~windows_queue e in
Lwt.return
(match r with
| Ok be -> Ok (be, alias)
| Error e -> Error e))
es
in
let errors =
List.filter_map
(function
| Error e -> Some e
| Ok _ -> None)
bound_list
in
(match errors with
| e :: _ -> Lwt.return (Error e)
| [] ->
Lwt.return
(Ok
(`Exprs
(List.filter_map
(function
| Ok p -> Some p
| Error _ -> None)
bound_list))))
in
let* ords_result = ords_result_lwt in
let windows_list = Queue.fold (fun acc w -> acc @ [ w ]) [] windows_queue in
match ords_result with
| Error e -> Lwt.return (Error e)
| Ok (`Ords o) -> Lwt.return (Ok (o, [], [], [], windows_list, []))
| Ok (`Exprs bes) -> Lwt.return (Ok ([], [], [], bes, windows_list, []))
;;
let bind_post_agg
~(tables : (Cat.table_meta * int * string option) list)
~meta
~group_cols
~offset_for_aggs
~(acc_aggs : agg_spec list ref)
e
=
let rec go = function
| Ast.E_lit l -> Ok (BE_lit l)
| Ast.E_col name ->
(match (select_proj_lookup ~tables ~meta) name with
| Error e -> Error e
| Ok i ->
(match select_find_pos group_cols i with
| Some pos -> Ok (BE_col pos)
| None ->
Error
(Unsupported
(Printf.sprintf
"column '%s' must appear in GROUP BY to be referenced in a window \
function in this context"
name))))
| Ast.E_tbl_col (t, c) ->
(match (select_qual_lookup ~tables) t c with
| Error e -> Error e
| Ok i ->
(match select_find_pos group_cols i with
| Some pos -> Ok (BE_col pos)
| None ->
Error
(Unsupported
(Printf.sprintf
"column '%s.%s' must appear in GROUP BY to be referenced in a window \
function in this context"
t
c))))
| Ast.E_agg (func, arg_opt) ->
let col_ord_result : (int option, error) result =
match arg_opt with
| None ->
(match func with
| Ast.Agg_count -> Ok None
| _ -> Error (Unsupported "non-COUNT aggregate requires an argument"))
| Some (Ast.E_col name) ->
(match (select_proj_lookup ~tables ~meta) name with
| Error e -> Error e
| Ok i -> Ok (Some i))
| Some (Ast.E_tbl_col (t, c)) ->
(match (select_qual_lookup ~tables) t c with
| Error e -> Error e
| Ok i -> Ok (Some i))
| Some _ ->
Error
(Unsupported
"aggregate argument in window function must be a column reference")
in
(match col_ord_result with
| Error e -> Error e
| Ok co ->
let spec = { func; col_ord = co } in
let rec find_slot i = function
| [] ->
acc_aggs := !acc_aggs @ [ spec ];
List.length !acc_aggs - 1
| s :: _ when s.func = spec.func && s.col_ord = spec.col_ord -> i
| _ :: rest -> find_slot (i + 1) rest
in
let slot = find_slot 0 !acc_aggs in
Ok (BE_col (offset_for_aggs + slot)))
| Ast.E_neg e ->
(match go e with
| Ok be -> Ok (BE_neg be)
| Error e -> Error e)
| Ast.E_not e ->
(match go e with
| Ok be -> Ok (BE_not be)
| Error e -> Error e)
| Ast.E_binop (op, a, b) ->
(match go a, go b with
| Ok ba, Ok bb -> Ok (BE_binop (ast_binop_to_sema op, ba, bb))
| Error e, _ | _, Error e -> Error e)
| Ast.E_window _ -> Error (Unsupported "nested window functions not supported")
| _ ->
Error
(Unsupported
"only GROUP BY columns and aggregate expressions are supported in window \
function arguments in this context")
in
go e
;;
let project_window
~(tables : (Cat.table_meta * int * string option) list)
~meta
~group_cols
~offset_for_aggs
~(acc_aggs : agg_spec list ref)
~agg_windows_queue
func
args
window
: (agg_proj_item, error) result
=
let bind_list es =
List.fold_left
(fun acc_r ex ->
match acc_r with
| Error _ as err -> err
| Ok acc ->
(match
bind_post_agg ~tables ~meta ~group_cols ~offset_for_aggs ~acc_aggs ex
with
| Error er -> Error er
| Ok be -> Ok (acc @ [ be ])))
(Ok [])
es
in
let bind_ok_list (oks : Ast.order_key list) =
List.fold_left
(fun acc_r ok ->
match acc_r with
| Error _ as err -> err
| Ok acc ->
(match
bind_post_agg
~tables
~meta
~group_cols
~offset_for_aggs
~acc_aggs
ok.Ast.expr
with
| Error er -> Error er
| Ok be ->
let nulls = ok.Ast.nulls in
Ok (acc @ [ { key = be; dir = ok.Ast.dir; nulls } ])))
(Ok [])
oks
in
match bind_list args with
| Error er -> Error er
| Ok bound_args ->
(match bind_list window.Ast.partition_by with
| Error er -> Error er
| Ok bound_pb ->
(match bind_ok_list window.Ast.order_by with
| Error er -> Error er
| Ok bound_ob ->
let slot = Queue.length agg_windows_queue in
Queue.push
{ func
; args = bound_args
; partition_by = bound_pb
; order_by = bound_ob
; frame = window.Ast.frame
}
agg_windows_queue;
Ok (AP_window_slot slot)))
;;
let project_agg
~(tables : (Cat.table_meta * int * string option) list)
~meta
~add_agg
func
arg_opt
: (agg_proj_item, error) result
=
let validate_numeric col_ord =
let cols = List.concat_map (fun (tm, _, _) -> tm.Cat.columns) tables in
let col = List.nth cols col_ord in
match col.Row.ty with
| Row.Integer | Row.Real -> Ok ()
| _ -> Error (Type_mismatch { expected = Row.Real; got = col.ty })
in
let col_ord_result : (int option, error) result =
match arg_opt with
| None ->
(match func with
| Ast.Agg_count -> Ok None
| _ -> Error (Unsupported "non-COUNT aggregate requires an argument"))
| Some (Ast.E_col name) ->
(match (select_proj_lookup ~tables ~meta) name with
| Error e -> Error e
| Ok i -> Ok (Some i))
| Some (Ast.E_tbl_col (t, c)) ->
(match (select_qual_lookup ~tables) t c with
| Error e -> Error e
| Ok i -> Ok (Some i))
| Some _ -> Error (Unsupported "aggregate argument must be a column reference")
in
match col_ord_result with
| Error e -> Error e
| Ok co ->
let type_check =
match func, co with
| (Ast.Agg_sum | Ast.Agg_avg), Some i -> validate_numeric i
| _ -> Ok ()
in
(match type_check with
| Error e -> Error e
| Ok () ->
let slot = add_agg { func; col_ord = co } in
Ok (AP_agg_slot slot))
;;
let project_agg_item
~(tables : (Cat.table_meta * int * string option) list)
~meta
~group_cols
~offset_for_aggs
~add_agg
~acc_aggs
~agg_windows_queue
(e : Ast.expr)
: (agg_proj_item, error) result
=
match e with
| Ast.E_col name ->
(match select_proj_lookup ~tables ~meta name with
| Error e -> Error e
| Ok i ->
(match select_find_pos group_cols i with
| Some pos -> Ok (AP_group_col pos)
| None ->
Error
(Unsupported
(Printf.sprintf "column '%s' must appear in GROUP BY clause" name))))
| Ast.E_tbl_col (t, c) ->
(match select_qual_lookup ~tables t c with
| Error e -> Error e
| Ok i ->
(match select_find_pos group_cols i with
| Some pos -> Ok (AP_group_col pos)
| None ->
Error
(Unsupported
(Printf.sprintf "column '%s.%s' must appear in GROUP BY clause" t c))))
| Ast.E_agg (func, arg_opt) -> project_agg ~tables ~meta ~add_agg func arg_opt
| Ast.E_window { func; args; window } ->
project_window
~tables
~meta
~group_cols
~offset_for_aggs
~acc_aggs
~agg_windows_queue
func
args
window
| _ -> Error (Unsupported "complex expression in aggregated projection not supported")
;;
let bind_aggregated_proj
~(tables : (Cat.table_meta * int * string option) list)
~(meta : Cat.table_meta)
~group_cols
~offset_for_aggs
~is_aggregated
proj
=
let acc_aggs : agg_spec list ref = ref [] in
let agg_windows_queue : window_sema Queue.t = Queue.create () in
let add_agg spec =
let idx = List.length !acc_aggs in
acc_aggs := !acc_aggs @ [ spec ];
idx
in
let exprs_to_project : Ast.expr list =
match proj with
| `All -> []
| `Cols names -> List.map (fun n -> Ast.E_col n) names
| `Exprs es -> List.map fst es
in
if exprs_to_project = [] && proj = `All && is_aggregated
then
Lwt.return (Error (Unsupported "SELECT * with aggregates requires explicit columns"))
else (
let agg_proj_result =
List.fold_left
(fun acc e ->
match acc with
| Error _ -> acc
| Ok items ->
(match
project_agg_item
~tables
~meta
~group_cols
~offset_for_aggs
~add_agg
~acc_aggs
~agg_windows_queue
e
with
| Error e -> Error e
| Ok item -> Ok (items @ [ item ])))
(Ok [])
exprs_to_project
in
let agg_wins = Queue.fold (fun acc w -> acc @ [ w ]) [] agg_windows_queue in
Lwt.return
(match agg_proj_result with
| Error e -> Error e
| Ok items -> Ok ([], items, !acc_aggs, [], [], agg_wins)))
;;
let bind_select_joins
~param_counter
~named_params
~(meta : Cat.table_meta)
~table_alias
~n_left
(joined_pairs : (Ast.join_clause * Cat.table_meta) list)
: (bound_join list, error) result
=
let rec go acc tbl_acc offset = function
| [] -> Ok (List.rev acc)
| ((jc : Ast.join_clause), rm) :: rest ->
let tables_so_far = tbl_acc @ [ rm, offset, jc.Ast.alias ] in
(match
bind_expr_join ~param_counter ~named_params ~tables:tables_so_far jc.Ast.on
with
| Error e -> Error e
| Ok be ->
let bj =
{ kind = jc.Ast.kind; right_meta = rm; on = be; right_col_offset = offset }
in
go (bj :: acc) tables_so_far (offset + List.length rm.Cat.columns) rest)
in
go [] [ meta, 0, table_alias ] n_left joined_pairs
;;
let bind_select_having
~param_counter
~named_params
~(tables : (Cat.table_meta * int * string option) list)
~(meta : Cat.table_meta)
~group_cols
~offset_for_aggs
~proj_aggs
~is_aggregated
having
: (bound_expr option * agg_spec list, error) result
=
match having with
| None -> Ok (None, [])
| Some e ->
if not is_aggregated
then Error (Unsupported "HAVING requires GROUP BY or aggregate")
else (
let having_resolver_unqual name =
match (select_proj_lookup ~tables ~meta) name with
| Error e -> Error e
| Ok i ->
(match select_find_pos group_cols i with
| Some pos -> Ok pos
| None ->
Error
(Unsupported
(Printf.sprintf "HAVING references non-grouped column '%s'" name)))
in
let having_resolver_qual t c =
match (select_qual_lookup ~tables) t c with
| Error e -> Error e
| Ok i ->
(match select_find_pos group_cols i with
| Some pos -> Ok pos
| None ->
Error
(Unsupported
(Printf.sprintf "HAVING references non-grouped column '%s.%s'" t c)))
in
let having_resolver =
{ resolve_unqual = having_resolver_unqual
; resolve_qual = having_resolver_qual
;
resolve_agg_arg = select_proj_lookup ~tables ~meta
; resolve_agg_arg_qual = select_qual_lookup ~tables
}
in
let having_offset = offset_for_aggs + List.length proj_aggs in
match
bind_expr_agg
~param_counter
~named_params
~resolver:having_resolver
~offset:having_offset
e
with
| Error e -> Error e
| Ok (be, hagg) -> Ok (Some be, hagg))
;;
let bind_select_order
~param_counter
~named_params
~(tables : (Cat.table_meta * int * string option) list)
~(proj_exprs : (bound_expr * string option) list)
order
=
let alias_map : (string * bound_expr) list =
List.filter_map
(fun (be, alias_opt) -> Option.map (fun a -> a, be) alias_opt)
proj_exprs
in
let bind_order_expr e =
let base_result =
bind_expr_join ~param_counter ~named_params ~tables e
in
match base_result with
| Ok _ -> base_result
| Error _ ->
(match e with
| Ast.E_col name ->
(match List.assoc_opt name alias_map with
| Some be -> Ok be
| None -> base_result)
| _ -> base_result)
in
List.fold_left
(fun acc (ok : Ast.order_key) ->
match acc with
| Error _ -> acc
| Ok keys ->
(match bind_order_expr ok.Ast.expr with
| Error e -> Error e
| Ok key -> Ok (keys @ [ { key; dir = ok.Ast.dir; nulls = ok.Ast.nulls } ])))
(Ok [])
order
;;
let validate_limit_offset ~limit ~offset =
match limit with
| Some n when n < 0 -> Error (Invalid_limit "LIMIT must be non-negative")
| _ ->
(match offset with
| Some n when n < 0 -> Error (Invalid_limit "OFFSET must be non-negative")
| _ -> Ok (limit, offset))
;;
let bind_select_resolved
~param_counter
~named_params
~distinct
~proj
~where
~group_by
~having
~order
~limit
~offset
~(meta : Cat.table_meta)
~table_alias
~n_left
~tables
~joined_pairs
=
let is_aggregated =
(match proj with
| `All | `Cols _ -> false
| `Exprs es -> List.exists (fun (e, _) -> expr_has_agg e) es)
|| (match having with
| None -> false
| Some e -> expr_has_agg e)
|| group_by <> []
in
let$ group_cols = bind_select_group_cols ~tables ~meta group_by in
let offset_for_aggs = List.length group_cols in
let* proj_result =
if not is_aggregated
then bind_unaggregated_proj ~param_counter ~named_params ~tables ~meta proj
else
bind_aggregated_proj ~tables ~meta ~group_cols ~offset_for_aggs ~is_aggregated proj
in
let$ proj_ords, agg_proj_items, proj_aggs, proj_exprs, proj_windows, agg_wins =
proj_result
in
let$ bound_joins =
bind_select_joins ~param_counter ~named_params ~meta ~table_alias ~n_left joined_pairs
in
let$ bound_where =
match where with
| None -> Ok None
| Some e ->
(match bind_expr_join ~param_counter ~named_params ~tables e with
| Ok be -> Ok (Some be)
| Error e -> Error e)
in
let$ bound_having, having_aggs =
bind_select_having
~param_counter
~named_params
~tables
~meta
~group_cols
~offset_for_aggs
~proj_aggs
~is_aggregated
having
in
let all_aggs = proj_aggs @ having_aggs in
let$ bound_order =
bind_select_order ~param_counter ~named_params ~tables ~proj_exprs order
in
let$ valid_limit, valid_offset = validate_limit_offset ~limit ~offset in
Lwt.return
(Ok
(BS_select
{ distinct
; table_meta = meta
; proj = proj_ords
; expr_proj = proj_exprs
; where = bound_where
; order = bound_order
; limit = valid_limit
; offset = valid_offset
; joins = bound_joins
; group_by = group_cols
; aggs = all_aggs
; having = bound_having
; agg_proj = agg_proj_items
; windows = proj_windows
; agg_windows = agg_wins
}))
;;
let bind_select
cat
~param_counter
~named_params
~distinct
~proj
~table
~table_alias
~joins
~where
~group_by
~having
~order
~limit
~offset
=
let* meta_opt =
let tbl_lower = String.lowercase_ascii table in
if String.equal tbl_lower "sqlite_master" || String.equal tbl_lower "sqlite_schema"
then Lwt.return (Some sqlite_master_meta)
else if String.equal tbl_lower "sqlite_sequence"
then Lwt.return (Some sqlite_sequence_meta)
else Cat.find_table cat ~name:table
in
match meta_opt with
| None ->
(match joins, group_by, having, order, limit, offset with
| [], [], None, [], None, None ->
bind_fts_seq_scan cat ~param_counter ~named_params ~table ~where ~proj
| _ ->
(match Cat.find_fts cat table with
| None -> Lwt.return (Error (Unknown_table table))
| Some _ ->
Lwt.return (Error (Unsupported "FTS tables do not support this query form"))))
| Some meta ->
let* joined_pairs_result =
Lwt_list.fold_left_s
(fun acc (jc : Ast.join_clause) ->
match acc with
| Error e -> Lwt.return (Error e)
| Ok pairs ->
let* rm_opt = Cat.find_table cat ~name:jc.table in
(match rm_opt with
| None -> Lwt.return (Error (Unknown_table jc.table))
| Some rm -> Lwt.return (Ok (pairs @ [ jc, rm ]))))
(Ok [])
joins
in
let$ joined_pairs = joined_pairs_result in
let n_left = List.length meta.columns in
let tables, _ =
List.fold_left
(fun (acc, off) ((jc : Ast.join_clause), rm) ->
let n = List.length rm.Cat.columns in
acc @ [ rm, off, jc.Ast.alias ], off + n)
([ meta, 0, table_alias ], n_left)
joined_pairs
in
bind_select_resolved
~param_counter
~named_params
~distinct
~proj
~where
~group_by
~having
~order
~limit
~offset
~meta
~table_alias
~n_left
~tables
~joined_pairs
;;
let rec infer_type (cols : Row.column list) : bound_expr -> Row.ty option = function
| BE_lit l -> lit_ty l
| BE_col i ->
Some (List.nth cols i).Row.ty
| BE_not _ | BE_is_null _ | BE_is_not_null _ ->
Some Row.Integer
| BE_binop (op, a, b) ->
(match op with
| Eq | Ne | Lt | Le | Gt | Ge | And | Or -> Some Row.Integer
| Bit_and | Bit_or | Lshift | Rshift | Mod -> Some Row.Integer
| Like | Glob -> Some Row.Integer
| Concat -> Some Row.Text
| Add | Sub | Mul | Div ->
(match infer_type cols a, infer_type cols b with
| Some Row.Integer, Some Row.Integer -> Some Row.Integer
| Some Row.Real, _ | _, Some Row.Real -> Some Row.Real
| Some Row.Integer, None | None, Some Row.Integer -> None
| _ -> None))
| BE_neg e -> infer_type cols e
| BE_bitnot _ -> Some Row.Integer
| BE_between _ -> Some Row.Integer
| BE_in _ -> Some Row.Integer
| BE_func _ -> None
| BE_param _ -> None
| BE_match _ -> Some Row.Integer
| BE_subquery _ -> None
| BE_exists _ -> Some Row.Integer
| BE_in_select _ -> Some Row.Integer
| BE_case _ -> None
| BE_cast (_, ty) ->
Some
(match ty with
| Ast.Ty_int -> Row.Integer
| Ast.Ty_text -> Row.Text
| Ast.Ty_real -> Row.Real
| Ast.Ty_blob -> Row.Blob)
| BE_excluded_col _ -> None
| BE_window_slot _ -> None
| BE_collate (e, _) -> infer_type cols e
;;
let bind_create_index cat ~name ~table ~columns ~where_clause ~unique ~if_not_exists =
match reject_reserved_name name with
| Error e -> Lwt.return (Error e)
| Ok () ->
let* meta_opt = Cat.find_table cat ~name:table in
(match meta_opt with
| None -> Lwt.return (Error (Unknown_table table))
| Some meta ->
if Cat.is_columnar meta
then
Lwt.return
(Error
(Unsupported
(Printf.sprintf "cannot create index on columnar table '%s'" table)))
else (
let pc = ref 0 in
let np = Hashtbl.create 0 in
let col_results =
List.map
(fun col_ast ->
match bind_expr ~param_counter:pc ~named_params:np meta col_ast with
| Error e -> Error e
| Ok _ -> Ok col_ast )
columns
in
let errors =
List.filter_map
(function
| Error e -> Some e
| Ok _ -> None)
col_results
in
match errors with
| e :: _ -> Lwt.return (Error e)
| [] ->
let col_sqls, col_expr_flags =
List.split
(List.map
(fun col_ast ->
match col_ast with
| Ast.E_col cname | Ast.E_tbl_col (_, cname) -> cname, false
| _ -> Ast.expr_to_sql col_ast, true)
columns)
in
let where_result =
match where_clause with
| None -> Ok (None, None)
| Some w_ast ->
(match bind_expr ~param_counter:pc ~named_params:np meta w_ast with
| Error e -> Error e
| Ok bw -> Ok (Some bw, Some w_ast))
in
(match where_result with
| Error e -> Lwt.return (Error e)
| Ok (where_expr, where_ast) ->
(match Cat.find_index cat ~name with
| Some _ when not if_not_exists -> Lwt.return (Error (Already_exists name))
| _ ->
Lwt.return
(Ok
(BS_create_index
{ name
; table_meta = meta
; col_sqls
; col_expr_flags
; where_expr
; where_ast
; unique
; if_not_exists
}))))))
;;
let bind_order_keys
~param_counter
~named_params
(meta : Cat.table_meta)
(oks : Ast.order_key list)
=
List.fold_left
(fun acc_r ok ->
match acc_r with
| Error _ as e -> e
| Ok acc ->
(match bind_expr ~param_counter ~named_params meta ok.Ast.expr with
| Error e -> Error e
| Ok be -> Ok (acc @ [ { key = be; dir = ok.Ast.dir; nulls = ok.Ast.nulls } ])))
(Ok [])
oks
;;
let bind_update_assignments
~param_counter
~named_params
~(meta : Cat.table_meta)
~table
assignments
=
List.fold_left
(fun acc (col_name, expr_ast) ->
match acc with
| Error _ -> acc
| Ok bound_list ->
(match col_index meta.columns col_name with
| None -> Error (Unknown_column { table; column = col_name })
| Some i ->
let col = List.nth meta.columns i in
if col.Row.generated_as <> None
then
Error
(Unsupported
(Printf.sprintf "cannot UPDATE generated column '%s'" col.Row.name))
else if
col.Row.not_null && expr_ast = Ast.E_lit Ast.L_null
then Error (Not_null_violation col.Row.name)
else (
match bind_expr ~param_counter ~named_params meta expr_ast with
| Error e -> Error e
| Ok bexpr ->
(match infer_type meta.columns bexpr with
| None -> Ok (bound_list @ [ i, bexpr ])
| Some t ->
if ty_equal t col.ty
then Ok (bound_list @ [ i, bexpr ])
else Error (Type_mismatch { expected = col.ty; got = t })))))
(Ok [])
assignments
;;
let bind_update
cat
~param_counter
~named_params
~table
~assignments
~where
~order
~limit
~offset
~returning
=
let* meta_opt = Cat.find_table cat ~name:table in
match meta_opt with
| None -> Lwt.return (Error (Unknown_table table))
| Some meta ->
let assign_result =
bind_update_assignments ~param_counter ~named_params ~meta ~table assignments
in
(match assign_result with
| Error e -> Lwt.return (Error e)
| Ok bound_assigns ->
let where_result =
match where with
| None -> Ok None
| Some e ->
(match bind_expr ~param_counter ~named_params meta e with
| Ok be -> Ok (Some be)
| Error e -> Error e)
in
(match where_result with
| Error e -> Lwt.return (Error e)
| Ok bound_where ->
let has_subquery_in_where =
match bound_where with
| Some e -> expr_has_subquery e
| None -> false
in
let has_subquery_in_assign =
List.exists (fun (_, e) -> expr_has_subquery e) bound_assigns
in
if has_subquery_in_where || has_subquery_in_assign
then
Lwt.return
(Error (Unsupported "subqueries in UPDATE WHERE/SET are not supported"))
else (
let order_result = bind_order_keys ~param_counter ~named_params meta order in
match order_result with
| Error e -> Lwt.return (Error e)
| Ok bound_order ->
(match bind_returning_exprs ~param_counter ~named_params meta returning with
| Error e -> Lwt.return (Error e)
| Ok ret_bound ->
Lwt.return
(Ok
(BS_update
{ table_meta = meta
; assignments = bound_assigns
; where = bound_where
; order = bound_order
; limit
; offset
; returning = ret_bound
}))))))
;;
let bind_fts_delete cat ~param_counter ~named_params ~table ~where =
match Cat.find_fts cat table with
| None -> Lwt.return (Error (Unknown_table table))
| Some fts_meta ->
let synth_meta = fts_as_table_meta fts_meta in
let where_result =
match where with
| None -> Ok None
| Some e ->
(match bind_expr ~param_counter ~named_params synth_meta e with
| Ok be -> Ok (Some be)
| Error e -> Error e)
in
(match where_result with
| Error e -> Lwt.return (Error e)
| Ok bound_where -> Lwt.return (Ok (BS_fts_delete { fts_meta; where = bound_where })))
;;
let bind_delete
cat
~param_counter
~named_params
~table
~where
~order
~limit
~offset
~returning
=
let* meta_opt = Cat.find_table cat ~name:table in
match meta_opt with
| None ->
bind_fts_delete cat ~param_counter ~named_params ~table ~where
| Some meta ->
let where_result =
match where with
| None -> Ok None
| Some e ->
(match bind_expr ~param_counter ~named_params meta e with
| Ok be -> Ok (Some be)
| Error e -> Error e)
in
(match where_result with
| Error e -> Lwt.return (Error e)
| Ok bound_where ->
let has_subquery_in_where =
match bound_where with
| Some e -> expr_has_subquery e
| None -> false
in
if has_subquery_in_where
then
Lwt.return (Error (Unsupported "subqueries in DELETE WHERE are not supported"))
else (
let order_result = bind_order_keys ~param_counter ~named_params meta order in
match order_result with
| Error e -> Lwt.return (Error e)
| Ok bound_order ->
(match bind_returning_exprs ~param_counter ~named_params meta returning with
| Error e -> Lwt.return (Error e)
| Ok ret_bound ->
Lwt.return
(Ok
(BS_delete
{ table_meta = meta
; where = bound_where
; order = bound_order
; limit
; offset
; returning = ret_bound
})))))
;;
let is_sqlite_sequence table =
String.equal (String.lowercase_ascii table) "sqlite_sequence"
;;
let int_lit_of_expr = function
| Ast.E_lit (Ast.L_int n) -> Some n
| _ -> None
;;
let text_lit_of_expr = function
| Ast.E_lit (Ast.L_text s) -> Some s
| _ -> None
;;
let seq_ident_eq a b = String.equal (String.lowercase_ascii a) b
let seq_col_is col = function
| Ast.E_col c -> seq_ident_eq c col
| Ast.E_tbl_col (t, c) -> is_sqlite_sequence t && seq_ident_eq c col
| _ -> false
;;
let seq_where_name = function
| Some (Ast.E_binop (Ast.Eq, col, rhs)) when seq_col_is "name" col ->
text_lit_of_expr rhs
| Some (Ast.E_binop (Ast.Eq, lhs, col)) when seq_col_is "name" col ->
text_lit_of_expr lhs
| _ -> None
;;
let seq_unsupported what =
Lwt.return
(Error (Unsupported (Printf.sprintf "unsupported %s on sqlite_sequence" what)))
;;
let bind_seq_update ~assignments ~where ~order ~limit ~offset ~returning =
match assignments, order, limit, offset, returning with
| [ (col, seq_expr) ], [], None, None, [] when seq_ident_eq col "seq" ->
(match int_lit_of_expr seq_expr, seq_where_name where with
| Some seq, Some table -> Lwt.return (Ok (BS_seq_write (Seq_set { table; seq })))
| _ -> seq_unsupported "UPDATE")
| _ -> seq_unsupported "UPDATE"
;;
let bind_seq_delete ~where ~order ~limit ~offset ~returning =
match order, limit, offset, returning with
| [], None, None, [] ->
(match where with
| None -> Lwt.return (Ok (BS_seq_write (Seq_reset { table = None })))
| Some _ ->
(match seq_where_name where with
| Some table -> Lwt.return (Ok (BS_seq_write (Seq_reset { table = Some table })))
| None -> seq_unsupported "DELETE"))
| _ -> seq_unsupported "DELETE"
;;
let bind_seq_insert ~columns ~values ~on_conflict ~returning ~upsert_update =
let cols_ok =
match columns with
| [] -> true
| [ c1; c2 ] -> seq_ident_eq c1 "name" && seq_ident_eq c2 "seq"
| _ -> false
in
match cols_ok, on_conflict, returning, upsert_update, values with
| true, None, [], None, [ [ name_expr; seq_expr ] ] ->
(match text_lit_of_expr name_expr, int_lit_of_expr seq_expr with
| Some table, Some seq -> Lwt.return (Ok (BS_seq_write (Seq_set { table; seq })))
| _ -> seq_unsupported "INSERT")
| _ -> seq_unsupported "INSERT"
;;
let bind_add_column cat ~(table_meta : Cat.table_meta) ~action (col_def : Ast.column_def) =
let col_name = col_def.Ast.name in
let exists =
List.exists (fun c -> String.equal c.Row.name col_name) table_meta.Cat.columns
in
if exists
then Lwt.return (Error (Already_exists col_name))
else if
col_def.Ast.not_null
&& (col_def.Ast.default = None || col_def.Ast.default = Some Ast.L_null)
then
Lwt.return
(Error (Unsupported "ADD COLUMN with NOT NULL requires a non-NULL DEFAULT"))
else (
match col_def.Ast.fk_ref with
| None -> Lwt.return (Ok (BS_alter_table { table_meta; action }))
| Some (parent_table, parent_col, on_delete, on_update, deferrable) ->
let _ = on_delete, on_update, deferrable in
(match Cat.find_table_cached cat ~name:parent_table with
| None ->
Lwt.return
(Error
(Unsupported
(Printf.sprintf "REFERENCES: table '%s' does not exist" parent_table)))
| Some parent_meta ->
let actual_parent_col =
if parent_col = ""
then (
match
List.find_opt
(fun (c : Row.column) -> c.primary_key)
parent_meta.Cat.columns
with
| None -> None
| Some pk -> Some pk.Row.name)
else if
List.exists
(fun (c : Row.column) -> String.equal c.name parent_col)
parent_meta.Cat.columns
then Some parent_col
else None
in
(match actual_parent_col with
| None ->
Lwt.return
(Error
(Unsupported
(Printf.sprintf
"REFERENCES: column '%s' not found in '%s'"
parent_col
parent_table)))
| Some _ -> Lwt.return (Ok (BS_alter_table { table_meta; action })))))
;;
let bind_alter_table cat ~table ~action =
let* meta_opt = Cat.find_table cat ~name:table in
match meta_opt with
| None -> Lwt.return (Error (Unknown_table table))
| Some table_meta ->
if Cat.is_columnar table_meta
then
Lwt.return (Error (Unsupported "ALTER TABLE is not supported on columnar tables"))
else (
match action with
| Ast.AA_add_column col_def -> bind_add_column cat ~table_meta ~action col_def
| Ast.AA_rename_table new_name ->
(match reject_reserved_name new_name with
| Error e -> Lwt.return (Error e)
| Ok () -> Lwt.return (Ok (BS_alter_table { table_meta; action })))
| Ast.AA_rename_column (old_col, _new_col) ->
let exists =
List.exists (fun c -> String.equal c.Row.name old_col) table_meta.Cat.columns
in
if not exists
then Lwt.return (Error (Unknown_column { table; column = old_col }))
else Lwt.return (Ok (BS_alter_table { table_meta; action }))
| Ast.AA_drop_column col_name ->
let exists =
List.exists (fun c -> String.equal c.Row.name col_name) table_meta.Cat.columns
in
if not exists
then Lwt.return (Error (Unknown_column { table; column = col_name }))
else if List.length table_meta.Cat.columns <= 1
then Lwt.return (Error (Unsupported "cannot drop the only column of a table"))
else Lwt.return (Ok (BS_alter_table { table_meta; action })))
;;
let bind_drop_table cat ~name ~if_exists =
let* meta_opt = Cat.find_table cat ~name in
match meta_opt with
| None when if_exists -> Lwt.return (Ok BS_no_op)
| None -> Lwt.return (Error (Unknown_table name))
| Some table_meta -> Lwt.return (Ok (BS_drop_table { name; table_meta }))
;;
let bind_drop_index cat ~name ~if_exists =
match Cat.find_index cat ~name with
| None when if_exists -> Lwt.return (Ok BS_no_op)
| None -> Lwt.return (Error (Unknown_index name))
| Some idx_info -> Lwt.return (Ok (BS_drop_index { name; idx_info }))
;;
let pp_error fmt = function
| Unknown_table t -> Format.fprintf fmt "unknown table: %s" t
| Unknown_column { table; column } ->
Format.fprintf fmt "unknown column: %s.%s" table column
| Ambiguous_column col -> Format.fprintf fmt "ambiguous column: %s" col
| Type_mismatch { expected; got } ->
let ty_str = function
| Granary_encoding.Row.Integer -> "INTEGER"
| Granary_encoding.Row.Text -> "TEXT"
| Granary_encoding.Row.Real -> "REAL"
| Granary_encoding.Row.Blob -> "BLOB"
in
Format.fprintf fmt "type mismatch: expected %s, got %s" (ty_str expected) (ty_str got)
| Arity_mismatch { expected; got } ->
Format.fprintf fmt "arity mismatch: expected %d, got %d" expected got
| Already_exists name -> Format.fprintf fmt "already exists: %s" name
| Invalid_limit msg -> Format.fprintf fmt "invalid limit: %s" msg
| Unsupported msg -> Format.fprintf fmt "unsupported: %s" msg
| Not_null_violation col -> Format.fprintf fmt "NOT NULL violation: %s" col
| Unknown_index name -> Format.fprintf fmt "unknown index: %s" name
;;
let rec compound_col_count = function
| BS_select { proj; expr_proj; aggs; _ } ->
if aggs <> []
then List.length aggs
else if expr_proj <> []
then List.length expr_proj
else List.length proj
| BS_compound { left; _ } -> compound_col_count left
| BS_const_select { exprs } -> List.length exprs
| BS_with_cte { query; recursive = _; _ } -> compound_col_count query
| _ -> 0
;;
let rec leftmost_table_meta = function
| BS_select { table_meta; _ } -> Some table_meta
| BS_compound { left; _ } -> leftmost_table_meta left
| BS_with_cte { query; _ } -> leftmost_table_meta query
| _ -> None
;;
let rec col_names_of_bound_stmt bs =
let n = compound_col_count bs in
match bs with
| BS_select { expr_proj; proj; table_meta; agg_proj; _ } ->
if agg_proj <> []
then
List.mapi (fun i _ -> Printf.sprintf "col_%d" (i + 1)) agg_proj
else if expr_proj <> []
then
List.mapi
(fun i (_, alias_opt) ->
Option.value alias_opt ~default:(Printf.sprintf "col_%d" (i + 1)))
expr_proj
else
List.filter_map
(fun i ->
if i < List.length table_meta.Cat.columns
then Some (List.nth table_meta.Cat.columns i).Row.name
else None)
proj
| BS_compound { left; _ } -> col_names_of_bound_stmt left
| BS_with_cte { query; recursive = _; _ } -> col_names_of_bound_stmt query
| BS_const_select { exprs } ->
List.mapi
(fun i (_, alias_opt) ->
Option.value alias_opt ~default:(Printf.sprintf "col_%d" (i + 1)))
exprs
| _ -> List.init n (fun i -> Printf.sprintf "col_%d" (i + 1))
;;
(** Extract output column names from an AST SELECT stmt (best-effort; used for CTEs). *)
let rec col_names_of_ast_stmt = function
| Ast.S_select { proj; _ } ->
(match proj with
| `All -> []
| `Cols names -> names
| `Exprs items ->
List.mapi
(fun i (expr, alias_opt) ->
match alias_opt with
| Some a -> a
| None ->
(match expr with
| Ast.E_col name -> name
| Ast.E_tbl_col (_, name) -> name
| _ -> Printf.sprintf "col_%d" (i + 1)))
items)
| Ast.S_compound { left; _ } -> col_names_of_ast_stmt left
| Ast.S_const_select { exprs } ->
List.mapi
(fun i (expr, alias_opt) ->
match alias_opt with
| Some a -> a
| None ->
(match expr with
| Ast.E_col name -> name
| Ast.E_tbl_col (_, name) -> name
| _ -> Printf.sprintf "col_%d" (i + 1)))
exprs
| _ -> []
;;
let output_column_names ast bound =
let ast_names = col_names_of_ast_stmt ast in
let bound_names = col_names_of_bound_stmt bound in
let n = List.length bound_names in
List.init n (fun i ->
if i < List.length ast_names then List.nth ast_names i else List.nth bound_names i)
;;
let bind_const_select ~param_counter ~named_params exprs =
let dummy_meta : Cat.table_meta =
{ Cat.name = "__const__"
; Cat.storage =
Cat.Row
{ tree_id = 0; next_rowid = 0L; without_rowid = false; autoincrement = false }
; Cat.columns = []
; Cat.fk_constraints = []
}
in
let bound =
List.map
(fun (expr, alias) ->
match bind_expr ~param_counter ~named_params dummy_meta expr with
| Error e -> Error e
| Ok be -> Ok (be, alias))
exprs
in
let errors =
List.filter_map
(function
| Error e -> Some e
| Ok _ -> None)
bound
in
match errors with
| e :: _ -> Lwt.return (Error e)
| [] ->
let ok_exprs =
List.filter_map
(function
| Ok e -> Some e
| Error _ -> None)
bound
in
Lwt.return (Ok (BS_const_select { exprs = ok_exprs }))
;;
let derive_cte_meta ~name col_source_ast col_source : Cat.table_meta =
let col_names = output_column_names col_source_ast col_source in
let cte_cols =
List.map
(fun col_name ->
{ Row.name = col_name
; Row.ty = Row.Integer
; Row.not_null = false
; Row.primary_key = false
; Row.pk_desc = false
; Row.default = None
; Row.check_sql = None
; Row.generated_as = None
})
col_names
in
{ Cat.name
; Cat.storage =
Cat.Row
{ tree_id = -1; next_rowid = 0L; without_rowid = false; autoincrement = false }
; Cat.columns = cte_cols
; Cat.fk_constraints = []
}
;;
let rec bind_internal ?(views = Hashtbl.create 0) ~named_params ~param_counter cat stmt =
match stmt with
| Ast.S_create_table
{ name; columns; constraints; if_not_exists; without_rowid; using_columnstore } ->
bind_create
cat
~name
~columns
~constraints
~if_not_exists
~without_rowid
~using_columnstore
| Ast.S_insert { table; columns; values; on_conflict; returning; upsert_update }
when is_sqlite_sequence table ->
bind_seq_insert ~columns ~values ~on_conflict ~returning ~upsert_update
| Ast.S_insert { table; columns; values; on_conflict; returning; upsert_update } ->
bind_insert
cat
~param_counter
~named_params
~table
~columns
~values
~on_conflict
~returning
~upsert_update
| Ast.S_insert_select { table; columns; on_conflict; select } ->
bind_insert_select
~views
~named_params
~param_counter
cat
~table
~columns
~on_conflict
~select
| Ast.S_select
{ distinct
; proj
; table
; table_alias
; joins
; where
; group_by
; having
; order
; limit
; offset
} as sel ->
let* meta_opt = Cat.find_table cat ~name:table in
(match meta_opt with
| Some _ ->
bind_select
cat
~param_counter
~named_params
~distinct
~proj
~table
~table_alias
~joins
~where
~group_by
~having
~order
~limit
~offset
| None ->
(match Hashtbl.find_opt views table with
| Some view_def ->
bind_internal
~views
~named_params
~param_counter
cat
(Ast.S_with_cte
{ name = table; def = view_def; query = sel; recursive = false })
| None ->
bind_select
cat
~param_counter
~named_params
~distinct
~proj
~table
~table_alias
~joins
~where
~group_by
~having
~order
~limit
~offset))
| Ast.S_create_index { name; table; columns; where_clause; unique; if_not_exists } ->
bind_create_index cat ~name ~table ~columns ~where_clause ~unique ~if_not_exists
| Ast.S_update { table; assignments; where; order; limit; offset; returning }
when is_sqlite_sequence table ->
bind_seq_update ~assignments ~where ~order ~limit ~offset ~returning
| Ast.S_update { table; assignments; where; order; limit; offset; returning } ->
bind_update
cat
~param_counter
~named_params
~table
~assignments
~where
~order
~limit
~offset
~returning
| Ast.S_delete { table; where; order; limit; offset; returning }
when is_sqlite_sequence table ->
bind_seq_delete ~where ~order ~limit ~offset ~returning
| Ast.S_delete { table; where; order; limit; offset; returning } ->
bind_delete
cat
~param_counter
~named_params
~table
~where
~order
~limit
~offset
~returning
| Ast.S_drop_table { name; if_exists } -> bind_drop_table cat ~name ~if_exists
| Ast.S_drop_index { name; if_exists } -> bind_drop_index cat ~name ~if_exists
| Ast.S_alter_table { table; action } -> bind_alter_table cat ~table ~action
| Ast.S_begin -> Lwt.return (Ok BS_begin)
| Ast.S_commit -> Lwt.return (Ok BS_commit)
| Ast.S_rollback -> Lwt.return (Ok BS_rollback)
| Ast.S_savepoint name -> Lwt.return (Ok (BS_savepoint name))
| Ast.S_release name -> Lwt.return (Ok (BS_release name))
| Ast.S_rollback_to name -> Lwt.return (Ok (BS_rollback_to name))
| Ast.S_create_fts_table { name; columns } ->
(match reject_reserved_name name with
| Error e -> Lwt.return (Error e)
| Ok () ->
let* tbl = Cat.find_table cat ~name in
let fts_existing = Cat.find_fts cat name in
(match tbl, fts_existing with
| Some _, _ | _, Some _ -> Lwt.return (Error (Already_exists name))
| None, None -> Lwt.return (Ok (BS_create_fts_table { name; columns }))))
| Ast.S_pragma kind -> Lwt.return (Ok (BS_pragma { kind }))
| Ast.S_vacuum -> Lwt.return (Ok BS_vacuum)
| Ast.S_attach { path; schema } -> Lwt.return (Ok (BS_attach { path; schema }))
| Ast.S_detach { schema } -> Lwt.return (Ok (BS_detach { schema }))
| Ast.S_const_select { exprs } -> bind_const_select ~param_counter ~named_params exprs
| Ast.S_with_cte { name; def; query; recursive } ->
bind_with_cte ~views ~named_params ~param_counter cat ~name ~def ~query ~recursive
| Ast.S_create_view { name; query } ->
(match reject_reserved_name name with
| Error e -> Lwt.return (Error e)
| Ok () ->
let* bound_r = bind_internal ~views ~named_params ~param_counter cat query in
(match bound_r with
| Error e -> Lwt.return (Error e)
| Ok _ -> Lwt.return (Ok (BS_create_view { name; query }))))
| Ast.S_create_reactive_view { name; query; refresh } ->
(match reject_reserved_name name with
| Error e -> Lwt.return (Error e)
| Ok () ->
let* bound_r = bind_internal ~views ~named_params ~param_counter cat query in
(match bound_r with
| Error e -> Lwt.return (Error e)
| Ok _ -> Lwt.return (Ok (BS_create_reactive_view { name; query; refresh }))))
| Ast.S_drop_view { name; if_exists = _ } -> Lwt.return (Ok (BS_drop_view { name }))
| Ast.S_create_trigger { name; timing; event; table; when_; body } ->
(match reject_reserved_name name with
| Error e -> Lwt.return (Error e)
| Ok () ->
Lwt.return (Ok (BS_create_trigger { name; timing; event; table; when_; body })))
| Ast.S_drop_trigger { name; if_exists = _ } ->
Lwt.return (Ok (BS_drop_trigger { name }))
| Ast.S_explain { analyze; stmt = inner_ast } ->
let* r = bind_internal ~views ~named_params ~param_counter cat inner_ast in
(match r with
| Error e -> Lwt.return (Error e)
| Ok inner -> Lwt.return (Ok (BS_explain { analyze; inner })))
| Ast.S_compound { op; left; right; order; limit; offset } ->
bind_compound
~views
~named_params
~param_counter
cat
~op
~left
~right
~order
~limit
~offset
and bind_insert_select
~views
~named_params
~param_counter
cat
~table
~columns
~on_conflict
~select
=
let* table_meta_opt = Cat.find_table cat ~name:table in
match table_meta_opt with
| None -> Lwt.return (Error (Unknown_table table))
| Some table_meta ->
let ordinals_result =
if columns = []
then
Ok
(List.filter_map
Fun.id
(List.mapi
(fun i (c : Row.column) ->
match c.generated_as with
| Some _ -> None
| None -> Some i)
table_meta.Cat.columns))
else
List.fold_left
(fun acc col_name ->
match acc with
| Error _ as e -> e
| Ok ords ->
let rec fi i = function
| [] ->
Error
(Unknown_column { table = table_meta.Cat.name; column = col_name })
| (c : Row.column) :: _ when String.equal c.name col_name ->
Ok (ords @ [ i ])
| _ :: rest -> fi (i + 1) rest
in
fi 0 table_meta.Cat.columns)
(Ok [])
columns
in
(match ordinals_result with
| Error e -> Lwt.return (Error e)
| Ok ordinals ->
let* source_result =
bind_internal ~views ~named_params ~param_counter cat select
in
(match source_result with
| Error e -> Lwt.return (Error e)
| Ok source ->
Lwt.return (Ok (BS_insert_select { table_meta; ordinals; source; on_conflict }))))
and bind_with_cte ~views ~named_params ~param_counter cat ~name ~def ~query ~recursive =
let base_ast =
match recursive, def with
| true, Ast.S_compound { left; _ } -> Some left
| _ -> None
in
let col_source_ast =
match base_ast with
| Some b -> b
| None -> def
in
let* col_source_r =
bind_internal ~views ~named_params ~param_counter cat col_source_ast
in
match col_source_r with
| Error e -> Lwt.return (Error e)
| Ok col_source ->
let cte_meta = derive_cte_meta ~name col_source_ast col_source in
Cat.register_ephemeral cat cte_meta;
let* def_r =
if recursive
then bind_internal ~views ~named_params ~param_counter cat def
else Lwt.return (Ok col_source)
in
(match def_r with
| Error e ->
Cat.unregister_ephemeral cat ~name;
Lwt.return (Error e)
| Ok bound_def ->
let* query_r = bind_internal ~views ~named_params ~param_counter cat query in
Cat.unregister_ephemeral cat ~name;
(match query_r with
| Error e -> Lwt.return (Error e)
| Ok bound_query ->
Lwt.return
(Ok (BS_with_cte { name; def = bound_def; query = bound_query; recursive }))))
and bind_compound
~views
~named_params
~param_counter
cat
~op
~left
~right
~order
~limit
~offset
=
let* left_r = bind_internal ~views ~named_params ~param_counter cat left in
let* right_r = bind_internal ~views ~named_params ~param_counter cat right in
match left_r, right_r with
| Ok l, Ok r ->
let n_left = compound_col_count l in
let n_right = compound_col_count r in
if n_left <> n_right
then Lwt.return (Error (Arity_mismatch { expected = n_left; got = n_right }))
else (
let bound_order =
if order = []
then Ok []
else (
match leftmost_table_meta l with
| Some meta -> bind_order_keys ~param_counter ~named_params meta order
| None ->
Ok [])
in
match bound_order with
| Error e -> Lwt.return (Error e)
| Ok bo ->
Lwt.return
(Ok (BS_compound { op; left = l; right = r; order = bo; limit; offset })))
| Error e, _ | _, Error e -> Lwt.return (Error e)
;;
let bind ?(views : (string, Ast.stmt) Hashtbl.t = Hashtbl.create 0) cat ast =
let named_params : (string, int) Hashtbl.t = Hashtbl.create 4 in
let param_counter = ref 0 in
bind_internal ~views ~named_params ~param_counter cat ast
;;
let bind_returning_params
?(views : (string, Ast.stmt) Hashtbl.t = Hashtbl.create 0)
cat
ast
=
let named_params : (string, int) Hashtbl.t = Hashtbl.create 4 in
let param_counter = ref 0 in
let* result = bind_internal ~views ~named_params ~param_counter cat ast in
match result with
| Error e -> Lwt.return (Error e)
| Ok bs ->
let pairs = Hashtbl.fold (fun k v acc -> (k, v) :: acc) named_params [] in
Lwt.return (Ok (bs, pairs))
;;
[@@@ai_disclosure "ai-generated"]
[@@@ai_model "claude-opus-4-7"]
[@@@ai_provider "Anthropic"]