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
|
(** Tests for the relational engine *)
open Relational_engine
(* ============================================================================
Merkle Tree Tests
============================================================================ *)
let%test_unit "merkle: empty tree" =
let tree = Merkle.empty in
assert (Merkle.is_empty tree);
assert (Merkle.size tree = 0);
assert (Merkle.root_hash tree = None)
let%test_unit "merkle: insert single element" =
let tree = Merkle.empty in
let hash = "abc123" in
let tree = Merkle.insert hash tree in
assert (not (Merkle.is_empty tree));
assert (Merkle.size tree = 1);
assert (Merkle.member hash tree);
assert (Merkle.root_hash tree <> None)
let%test_unit "merkle: insert multiple elements" =
let tree = Merkle.empty in
let tree = Merkle.insert "hash1" tree in
let tree = Merkle.insert "hash2" tree in
let tree = Merkle.insert "hash3" tree in
assert (Merkle.size tree = 3);
assert (Merkle.member "hash1" tree);
assert (Merkle.member "hash2" tree);
assert (Merkle.member "hash3" tree);
assert (not (Merkle.member "hash4" tree))
let%test_unit "merkle: delete element" =
let tree = Merkle.empty in
let tree = Merkle.insert "hash1" tree in
let tree = Merkle.insert "hash2" tree in
assert (Merkle.size tree = 2);
let tree = Merkle.delete "hash1" tree in
assert (Merkle.size tree = 1);
assert (not (Merkle.member "hash1" tree));
assert (Merkle.member "hash2" tree)
let%test_unit "merkle: keys returns all elements" =
let tree = Merkle.empty in
let tree = Merkle.insert "c" tree in
let tree = Merkle.insert "a" tree in
let tree = Merkle.insert "b" tree in
let keys = Merkle.keys tree in
assert (List.length keys = 3);
assert (List.mem "a" keys);
assert (List.mem "b" keys);
assert (List.mem "c" keys)
let%test_unit "merkle: root hash changes on insert" =
let tree = Merkle.empty in
let tree1 = Merkle.insert "hash1" tree in
let root1 = Merkle.root_hash tree1 in
let tree2 = Merkle.insert "hash2" tree1 in
let root2 = Merkle.root_hash tree2 in
assert (root1 <> root2)
let%test_unit "merkle: same elements produce same root hash" =
let tree1 = Merkle.empty
|> Merkle.insert "a"
|> Merkle.insert "b" in
let tree2 = Merkle.empty
|> Merkle.insert "b"
|> Merkle.insert "a" in
assert (Merkle.root_hash tree1 = Merkle.root_hash tree2)
(* ============================================================================
Physical Storage Tests
============================================================================ *)
let%test_unit "storage: create and close" =
match Management.Physical.Memory.create () with
| Error _ -> assert false
| Ok storage ->
Management.Physical.Memory.close storage
let%test_unit "storage: store and load attribute" =
match Management.Physical.Memory.create () with
| Error _ -> assert false
| Ok storage ->
let value = Obj.magic 42 in
(match Management.Physical.Memory.store_attribute storage value with
| Error _ -> assert false
| Ok hash ->
(match Management.Physical.Memory.load_attribute storage hash with
| Error _ -> assert false
| Ok None -> assert false
| Ok (Some loaded) ->
assert ((Obj.magic loaded : int) = 42)));
Management.Physical.Memory.close storage
let%test_unit "storage: store and load raw bytes" =
match Management.Physical.Memory.create () with
| Error _ -> assert false
| Ok storage ->
let hash = "test_hash" in
let data = Bytes.of_string "hello world" in
(match Management.Physical.Memory.store_raw storage hash data with
| Error _ -> assert false
| Ok () ->
(match Management.Physical.Memory.load_raw storage hash with
| Error _ -> assert false
| Ok None -> assert false
| Ok (Some loaded) ->
assert (Bytes.equal loaded data)));
Management.Physical.Memory.close storage
let%test_unit "storage: exists check" =
match Management.Physical.Memory.create () with
| Error _ -> assert false
| Ok storage ->
let hash = "exists_test" in
let data = Bytes.of_string "data" in
(match Management.Physical.Memory.exists storage hash with
| Error _ -> assert false
| Ok exists -> assert (not exists));
(match Management.Physical.Memory.store_raw storage hash data with
| Error _ -> assert false
| Ok () ->
(match Management.Physical.Memory.exists storage hash with
| Error _ -> assert false
| Ok exists -> assert exists));
Management.Physical.Memory.close storage
let%test_unit "storage: transaction commit" =
match Management.Physical.Memory.create () with
| Error _ -> assert false
| Ok storage ->
let result = Management.Physical.Memory.with_transaction storage (fun () ->
let hash = "tx_test" in
let data = Bytes.of_string "tx_data" in
Management.Physical.Memory.store_raw storage hash data
) in
(match result with
| Error _ -> assert false
| Ok () ->
(match Management.Physical.Memory.exists storage "tx_test" with
| Error _ -> assert false
| Ok exists -> assert exists));
Management.Physical.Memory.close storage
(* ============================================================================
Database Tests
============================================================================ *)
let%test_unit "database: create empty" =
let db = Management.Database.empty ~name:"test_db" in
assert (db.name = "test_db");
assert (Merkle.is_empty db.tree);
assert (Management.Database.RelationMap.is_empty db.relations);
assert (db.history = [])
let%test_unit "database: add relation" =
let db = Management.Database.empty ~name:"test_db" in
(* Create a minimal relation for testing *)
let relation = Relation.make
~hash:(Some "rel_hash_1")
~name:"users"
~schema:Schema.empty
~tree:(Some Merkle.empty)
~constraints:None
~cardinality:(Conventions.Cardinality.Finite 0)
~generator:None
~membership_criteria:(fun _ -> true)
~provenance:Relation.Provenance.Undefined
~lineage:(Relation.Lineage.Base "users")
in
let db = Management.Database.add_relation db ~relation in
assert (Management.Database.has_relation db "users");
assert (Management.Database.get_relation_hash db "users" = Some "rel_hash_1");
assert (not (Management.Database.has_relation db "orders"))
let%test_unit "database: remove relation" =
let db = Management.Database.empty ~name:"test_db" in
let relation = Relation.make
~hash:(Some "hash1")
~name:"users"
~schema:Schema.empty
~tree:(Some Merkle.empty)
~constraints:None
~cardinality:(Conventions.Cardinality.Finite 0)
~generator:None
~membership_criteria:(fun _ -> true)
~provenance:Relation.Provenance.Undefined
~lineage:(Relation.Lineage.Base "users")
in
let db = Management.Database.add_relation db ~relation in
assert (Management.Database.has_relation db "users");
let db = Management.Database.remove_relation db ~name:"users" in
assert (not (Management.Database.has_relation db "users"))
let%test_unit "database: update relation" =
let db = Management.Database.empty ~name:"test_db" in
let relation = Relation.make
~hash:(Some "hash1")
~name:"users"
~schema:Schema.empty
~tree:(Some Merkle.empty)
~constraints:None
~cardinality:(Conventions.Cardinality.Finite 0)
~generator:None
~membership_criteria:(fun _ -> true)
~provenance:Relation.Provenance.Undefined
~lineage:(Relation.Lineage.Base "users")
in
let db = Management.Database.add_relation db ~relation in
let old_db_hash = db.hash in
let updated_relation = { relation with hash = Some "hash2" } in
let db = Management.Database.update_relation db ~relation:updated_relation in
assert (Management.Database.get_relation_hash db "users" = Some "hash2");
assert (db.hash <> old_db_hash);
assert (List.mem old_db_hash db.history)
let%test_unit "database: get relation names" =
let db = Management.Database.empty ~name:"test_db" in
let rel1 = Relation.make
~hash:(Some "h1")
~name:"users"
~schema:Schema.empty
~tree:(Some Merkle.empty)
~constraints:None
~cardinality:(Conventions.Cardinality.Finite 0)
~generator:None
~membership_criteria:(fun _ -> true)
~provenance:Relation.Provenance.Undefined
~lineage:(Relation.Lineage.Base "users")
in
let rel2 = Relation.make
~hash:(Some "h2")
~name:"orders"
~schema:Schema.empty
~tree:(Some Merkle.empty)
~constraints:None
~cardinality:(Conventions.Cardinality.Finite 0)
~generator:None
~membership_criteria:(fun _ -> true)
~provenance:Relation.Provenance.Undefined
~lineage:(Relation.Lineage.Base "orders")
in
let db = Management.Database.add_relation db ~relation:rel1 in
let db = Management.Database.add_relation db ~relation:rel2 in
let names = Management.Database.get_relation_names db in
assert (List.length names = 2);
assert (List.mem "users" names);
assert (List.mem "orders" names)
(* ============================================================================
Manipulation Tests (using Memory storage)
============================================================================ *)
(* Helper to create storage for tests *)
let with_storage f =
match Management.Physical.Memory.create () with
| Error _ -> assert false
| Ok storage ->
let result = f storage in
Management.Physical.Memory.close storage;
result
let%test_unit "manipulation: create database" =
with_storage (fun storage ->
match Manipulation.Memory.create_database storage ~name:"my_db" with
| Error _ -> assert false
| Ok db -> assert (db.name = "my_db"))
let%test_unit "manipulation: create relation" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test_db" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty
|> Schema.add "name" "string"
|> Schema.add "age" "integer" in
match Manipulation.Memory.create_relation storage db ~name:"users" ~schema with
| Error _ -> assert false
| Ok (db, relation) ->
assert (relation.name = "users");
assert (relation.schema = schema);
assert (Management.Database.has_relation db "users"))
let%test_unit "manipulation: create relation already exists" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test_db" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty in
match Manipulation.Memory.create_relation storage db ~name:"users" ~schema with
| Error _ -> assert false
| Ok (db, _) ->
match Manipulation.Memory.create_relation storage db ~name:"users" ~schema with
| Error (Manipulation.RelationAlreadyExists _) -> ()
| _ -> assert false)
let%test_unit "manipulation: retract relation" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test_db" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty in
match Manipulation.Memory.create_relation storage db ~name:"users" ~schema with
| Error _ -> assert false
| Ok (db, _) ->
assert (Management.Database.has_relation db "users");
match Manipulation.Memory.retract_relation storage db ~name:"users" with
| Error _ -> assert false
| Ok db ->
assert (not (Management.Database.has_relation db "users")))
let%test_unit "manipulation: create tuple with storage" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test_db" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty
|> Schema.add "name" "string" in
match Manipulation.Memory.create_relation storage db ~name:"users" ~schema with
| Error _ -> assert false
| Ok (db, relation) ->
let attrs = Tuple.AttributeMap.empty
|> Tuple.AttributeMap.add "name" { Attribute.value = Obj.magic "Alice" } in
let tuple : Tuple.materialized = { relation = "users"; attributes = attrs } in
match Manipulation.Memory.create_tuple storage db relation tuple with
| Error _ -> assert false
| Ok (_db, new_relation, _hash) ->
assert (Manipulation.Memory.tuple_count new_relation = 1))
let%test_unit "manipulation: create and load tuple" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test_db" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty
|> Schema.add "value" "integer" in
match Manipulation.Memory.create_relation storage db ~name:"numbers" ~schema with
| Error _ -> assert false
| Ok (db, relation) ->
let attrs = Tuple.AttributeMap.empty
|> Tuple.AttributeMap.add "value" { Attribute.value = Obj.magic 42 } in
let tuple : Tuple.materialized = { relation = "numbers"; attributes = attrs } in
match Manipulation.Memory.create_tuple storage db relation tuple with
| Error _ -> assert false
| Ok (_db, _relation, tuple_hash) ->
(* Now load the tuple back from storage *)
match Manipulation.Memory.load_tuple storage tuple_hash with
| Error _ -> assert false
| Ok None -> assert false
| Ok (Some loaded_tuple) ->
assert (loaded_tuple.relation = "numbers");
let loaded_value = Tuple.AttributeMap.find "value" loaded_tuple.attributes in
assert ((Obj.magic loaded_value.Attribute.value : int) = 42))
let%test_unit "manipulation: create multiple tuples with storage" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test_db" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty
|> Schema.add "id" "integer" in
match Manipulation.Memory.create_relation storage db ~name:"items" ~schema with
| Error _ -> assert false
| Ok (db, relation) ->
let make_tuple id =
let attrs = Tuple.AttributeMap.empty
|> Tuple.AttributeMap.add "id" { Attribute.value = Obj.magic id } in
({ Tuple.relation = "items"; attributes = attrs } : Tuple.materialized)
in
let tuples = [make_tuple 1; make_tuple 2; make_tuple 3] in
match Manipulation.Memory.create_tuples storage db relation tuples with
| Error _ -> assert false
| Ok (_db, new_relation, hashes) ->
assert (Manipulation.Memory.tuple_count new_relation = 3);
assert (List.length hashes = 3))
let%test_unit "manipulation: load multiple tuples" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test_db" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty
|> Schema.add "n" "integer" in
match Manipulation.Memory.create_relation storage db ~name:"test" ~schema with
| Error _ -> assert false
| Ok (db, relation) ->
let make_tuple n =
let attrs = Tuple.AttributeMap.empty
|> Tuple.AttributeMap.add "n" { Attribute.value = Obj.magic n } in
({ Tuple.relation = "test"; attributes = attrs } : Tuple.materialized)
in
match Manipulation.Memory.create_tuples storage db relation [make_tuple 10; make_tuple 20] with
| Error _ -> assert false
| Ok (_db, _relation, hashes) ->
match Manipulation.Memory.load_tuples storage hashes with
| Error _ -> assert false
| Ok loaded ->
assert (List.length loaded = 2);
let values = List.map (fun t ->
let attr = Tuple.AttributeMap.find "n" t.Tuple.attributes in
(Obj.magic attr.Attribute.value : int)
) loaded in
assert (List.mem 10 values);
assert (List.mem 20 values))
let%test_unit "manipulation: retract tuple" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test_db" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty
|> Schema.add "value" "integer" in
match Manipulation.Memory.create_relation storage db ~name:"numbers" ~schema with
| Error _ -> assert false
| Ok (db, relation) ->
let attrs = Tuple.AttributeMap.empty
|> Tuple.AttributeMap.add "value" { Attribute.value = Obj.magic 42 } in
let tuple : Tuple.materialized = { relation = "numbers"; attributes = attrs } in
match Manipulation.Memory.create_tuple storage db relation tuple with
| Error _ -> assert false
| Ok (db, relation, tuple_hash) ->
assert (Manipulation.Memory.tuple_count relation = 1);
match Manipulation.Memory.retract_tuple storage db relation ~tuple_hash with
| Error _ -> assert false
| Ok (_db, relation) ->
assert (Manipulation.Memory.tuple_count relation = 0);
(* Tuple data still exists in storage (append-only) *)
match Manipulation.Memory.load_tuple storage tuple_hash with
| Error _ -> assert false
| Ok None -> assert false
| Ok (Some _) -> () (* Data is still there *))
let%test_unit "manipulation: tuple hashes" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test_db" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty in
match Manipulation.Memory.create_relation storage db ~name:"test" ~schema with
| Error _ -> assert false
| Ok (db, relation) ->
let make_tuple n =
let attrs = Tuple.AttributeMap.empty
|> Tuple.AttributeMap.add "n" { Attribute.value = Obj.magic n } in
({ Tuple.relation = "test"; attributes = attrs } : Tuple.materialized)
in
match Manipulation.Memory.create_tuples storage db relation [make_tuple 1; make_tuple 2] with
| Error _ -> assert false
| Ok (_db, relation, _) ->
let hashes = Manipulation.Memory.tuple_hashes relation in
assert (List.length hashes = 2))
let%test_unit "manipulation: clear relation" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test_db" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty in
match Manipulation.Memory.create_relation storage db ~name:"test" ~schema with
| Error _ -> assert false
| Ok (db, relation) ->
let make_tuple n =
let attrs = Tuple.AttributeMap.empty
|> Tuple.AttributeMap.add "n" { Attribute.value = Obj.magic n } in
({ Tuple.relation = "test"; attributes = attrs } : Tuple.materialized)
in
match Manipulation.Memory.create_tuples storage db relation [make_tuple 1; make_tuple 2; make_tuple 3] with
| Error _ -> assert false
| Ok (db, relation, _) ->
assert (Manipulation.Memory.tuple_count relation = 3);
match Manipulation.Memory.clear_relation storage db relation with
| Error _ -> assert false
| Ok (_db, relation) ->
assert (Manipulation.Memory.tuple_count relation = 0))
let%test_unit "manipulation: duplicate tuple rejected" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test_db" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty
|> Schema.add "x" "integer" in
match Manipulation.Memory.create_relation storage db ~name:"test" ~schema with
| Error _ -> assert false
| Ok (db, relation) ->
let attrs = Tuple.AttributeMap.empty
|> Tuple.AttributeMap.add "x" { Attribute.value = Obj.magic 1 } in
let tuple : Tuple.materialized = { relation = "test"; attributes = attrs } in
match Manipulation.Memory.create_tuple storage db relation tuple with
| Error _ -> assert false
| Ok (db, relation, _) ->
(* Try to insert the same tuple again *)
match Manipulation.Memory.create_tuple storage db relation tuple with
| Error (Manipulation.DuplicateTuple _) -> ()
| _ -> assert false)
let%test_unit "manipulation: tuple_exists check" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test_db" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty in
match Manipulation.Memory.create_relation storage db ~name:"test" ~schema with
| Error _ -> assert false
| Ok (db, relation) ->
let attrs = Tuple.AttributeMap.empty
|> Tuple.AttributeMap.add "v" { Attribute.value = Obj.magic 99 } in
let tuple : Tuple.materialized = { relation = "test"; attributes = attrs } in
let tuple_hash = Manipulation.hash_tuple tuple in
assert (not (Manipulation.Memory.tuple_exists relation tuple_hash));
match Manipulation.Memory.create_tuple storage db relation tuple with
| Error _ -> assert false
| Ok (_db, relation, hash) ->
assert (hash = tuple_hash);
assert (Manipulation.Memory.tuple_exists relation tuple_hash))
let%test_unit "manipulation: hash_tuple deterministic" =
let attrs = Tuple.AttributeMap.empty
|> Tuple.AttributeMap.add "a" { Attribute.value = Obj.magic 1 }
|> Tuple.AttributeMap.add "b" { Attribute.value = Obj.magic 2 } in
let tuple : Tuple.materialized = { relation = "test"; attributes = attrs } in
let hash1 = Manipulation.hash_tuple tuple in
let hash2 = Manipulation.hash_tuple tuple in
assert (hash1 = hash2)
let%test_unit "manipulation: different tuples different hashes" =
let tuple1 : Tuple.materialized = {
relation = "test";
attributes = Tuple.AttributeMap.singleton "x" { Attribute.value = Obj.magic 1 }
} in
let tuple2 : Tuple.materialized = {
relation = "test";
attributes = Tuple.AttributeMap.singleton "x" { Attribute.value = Obj.magic 2 }
} in
let hash1 = Manipulation.hash_tuple tuple1 in
let hash2 = Manipulation.hash_tuple tuple2 in
assert (hash1 <> hash2)
let%test_unit "manipulation: get_relation from database" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test_db" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty
|> Schema.add "id" "integer" in
match Manipulation.Memory.create_relation storage db ~name:"items" ~schema with
| Error _ -> assert false
| Ok (db, _relation) ->
(* Now get the relation from the database *)
match Manipulation.Memory.get_relation db ~name:"items" with
| None -> assert false
| Some rel ->
assert (rel.name = "items");
assert (rel.schema = schema))
(* ============================================================================
Schema Persistence Tests
============================================================================ *)
let%test_unit "schema: persisted and loaded correctly" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test_db" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty
|> Schema.add "id" "integer"
|> Schema.add "name" "string"
|> Schema.add "email" "string" in
match Manipulation.Memory.create_relation storage db ~name:"users" ~schema with
| Error _ -> assert false
| Ok (db, _relation) ->
(* Get the relation hash *)
let rel_hash = Option.get (Management.Database.get_relation_hash db "users") in
(* Load the relation from storage *)
match Manipulation.Memory.load_relation storage rel_hash with
| Error _ -> assert false
| Ok None -> assert false
| Ok (Some loaded_rel) ->
(* Verify schema was persisted and loaded correctly *)
assert (loaded_rel.schema = schema);
assert (List.mem ("id", "integer") loaded_rel.schema);
assert (List.mem ("name", "string") loaded_rel.schema);
assert (List.mem ("email", "string") loaded_rel.schema))
(* ============================================================================
System Catalog Tests
============================================================================ *)
let%test_unit "catalog: create_database seeds 6 catalog relations" =
with_storage (fun storage ->
match Manipulation.Memory.create_database storage ~name:"test" with
| Error _ -> assert false
| Ok db ->
let catalog_names = Prelude.Catalog.catalog_relation_names in
List.iter (fun name ->
assert (Management.Database.has_relation db name)
) catalog_names)
let%test_unit "catalog: sakura:relation contains all 6 catalog names" =
with_storage (fun storage ->
match Manipulation.Memory.create_database storage ~name:"test" with
| Error _ -> assert false
| Ok db ->
let rel = match Manipulation.Memory.get_relation db ~name:"sakura:relation" with
| None -> assert false
| Some r -> r
in
assert (Manipulation.Memory.tuple_count rel = 6))
let%test_unit "catalog: sakura:on contains insert, update, delete" =
with_storage (fun storage ->
match Manipulation.Memory.create_database storage ~name:"test" with
| Error _ -> assert false
| Ok db ->
let on_rel = match Manipulation.Memory.get_relation db ~name:"sakura:on" with
| None -> assert false
| Some r -> r
in
assert (Manipulation.Memory.tuple_count on_rel = 3))
let%test_unit "catalog: sakura:timing contains immediate, deferred" =
with_storage (fun storage ->
match Manipulation.Memory.create_database storage ~name:"test" with
| Error _ -> assert false
| Ok db ->
let timing_rel = match Manipulation.Memory.get_relation db ~name:"sakura:timing" with
| None -> assert false
| Some r -> r
in
assert (Manipulation.Memory.tuple_count timing_rel = 2))
let%test_unit "catalog: sakura:domain seeded with 4 prelude domains" =
with_storage (fun storage ->
match Manipulation.Memory.create_database storage ~name:"test" with
| Error _ -> assert false
| Ok db ->
let dom_rel = match Manipulation.Memory.get_relation db ~name:"sakura:domain" with
| None -> assert false
| Some r -> r
in
assert (Manipulation.Memory.tuple_count dom_rel = 4))
let%test_unit "catalog: create_relation updates sakura:relation" =
with_storage (fun storage ->
match Manipulation.Memory.create_database storage ~name:"test" with
| Error _ -> assert false
| Ok db ->
let schema = Schema.empty |> Schema.add "id" "natural" in
let db = match Manipulation.Memory.create_relation storage db ~name:"employees" ~schema with
| Error _ -> assert false | Ok (db, _) -> db
in
let rel = match Manipulation.Memory.get_relation db ~name:"sakura:relation" with
| None -> assert false | Some r -> r
in
(* 6 catalog relations + 1 user relation *)
assert (Manipulation.Memory.tuple_count rel = 7))
let%test_unit "catalog: create_relation updates sakura:attribute" =
with_storage (fun storage ->
match Manipulation.Memory.create_database storage ~name:"test" with
| Error _ -> assert false
| Ok db ->
let schema = Schema.empty |> Schema.add "id" "natural" in
let db = match Manipulation.Memory.create_relation storage db ~name:"employees" ~schema with
| Error _ -> assert false | Ok (db, _) -> db
in
let attr_rel = match Manipulation.Memory.get_relation db ~name:"sakura:attribute" with
| None -> assert false | Some r -> r
in
(* catalog attribute tuples (sum of schema sizes of all 6 catalog relations) + 1 for employees *)
(* sakura:relation: 1, sakura:domain: 1, sakura:attribute: 3, sakura:constraint: 2,
sakura:on: 1, sakura:timing: 1 => 9 catalog attrs + 1 for employees = 10 *)
let count = Manipulation.Memory.tuple_count attr_rel in
assert (count = 10))
let%test_unit "catalog: retract_relation removes from sakura:relation" =
with_storage (fun storage ->
match Manipulation.Memory.create_database storage ~name:"test" with
| Error _ -> assert false
| Ok db ->
let schema = Schema.empty |> Schema.add "id" "natural" in
let db = match Manipulation.Memory.create_relation storage db ~name:"employees" ~schema with
| Error _ -> assert false | Ok (db, _) -> db
in
let db = match Manipulation.Memory.retract_relation storage db ~name:"employees" with
| Error _ -> assert false | Ok db -> db
in
let rel = match Manipulation.Memory.get_relation db ~name:"sakura:relation" with
| None -> assert false | Some r -> r
in
(* Back to 6 catalog relations *)
assert (Manipulation.Memory.tuple_count rel = 6))
let%test_unit "catalog: register_constraint inserts into sakura:constraint" =
with_storage (fun storage ->
match Manipulation.Memory.create_database storage ~name:"test" with
| Error _ -> assert false
| Ok db ->
let schema = Schema.empty |> Schema.add "id" "natural" in
let db = match Manipulation.Memory.create_relation storage db ~name:"orders" ~schema with
| Error _ -> assert false | Ok (db, _) -> db
in
let db = match Manipulation.Memory.register_constraint storage db
~constraint_name:"orders_id_positive"
~relation_name:"orders"
~body:(Constraint.And []) with
| Error _ -> assert false | Ok db -> db
in
let con_rel = match Manipulation.Memory.get_relation db ~name:"sakura:constraint" with
| None -> assert false | Some r -> r
in
assert (Manipulation.Memory.tuple_count con_rel = 1))
(* ============================================================================
Integration Tests
============================================================================ *)
let%test_unit "integration: full workflow with storage" =
with_storage (fun storage ->
(* Create database *)
let db = match Manipulation.Memory.create_database storage ~name:"shop" with
| Error _ -> assert false | Ok db -> db
in
(* Create products relation *)
let schema = Schema.empty
|> Schema.add "id" "integer"
|> Schema.add "name" "string"
|> Schema.add "price" "integer" in
let (db, products) = match Manipulation.Memory.create_relation storage db ~name:"products" ~schema with
| Error _ -> assert false
| Ok x -> x
in
(* Insert some products *)
let make_product id name price =
let attrs = Tuple.AttributeMap.empty
|> Tuple.AttributeMap.add "id" { Attribute.value = Obj.magic id }
|> Tuple.AttributeMap.add "name" { Attribute.value = Obj.magic name }
|> Tuple.AttributeMap.add "price" { Attribute.value = Obj.magic price } in
({ Tuple.relation = "products"; attributes = attrs } : Tuple.materialized)
in
let tuples = [
make_product 1 "Apple" 100;
make_product 2 "Banana" 50;
make_product 3 "Cherry" 200;
] in
let (db, products, hashes) = match Manipulation.Memory.create_tuples storage db products tuples with
| Error _ -> assert false
| Ok x -> x
in
assert (Manipulation.Memory.tuple_count products = 3);
assert (List.length hashes = 3);
(* Verify we can load all tuples back *)
(match Manipulation.Memory.load_tuples storage hashes with
| Error _ -> assert false
| Ok loaded -> assert (List.length loaded = 3));
(* Delete one product *)
let banana_hash = Manipulation.hash_tuple (make_product 2 "Banana" 50) in
let (_db, products) = match Manipulation.Memory.retract_tuple storage db products ~tuple_hash:banana_hash with
| Error _ -> assert false
| Ok x -> x
in
assert (Manipulation.Memory.tuple_count products = 2);
(* Verify remaining hashes *)
let remaining_hashes = Manipulation.Memory.tuple_hashes products in
assert (List.length remaining_hashes = 2);
assert (not (List.mem banana_hash remaining_hashes));
(* But banana data is still in storage (append-only) *)
match Manipulation.Memory.load_tuple storage banana_hash with
| Error _ -> assert false
| Ok None -> assert false
| Ok (Some loaded) ->
let name_attr = Tuple.AttributeMap.find "name" loaded.attributes in
assert ((Obj.magic name_attr.Attribute.value : string) = "Banana"))
let%test_unit "integration: database history tracking" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"versioned" with
| Error _ -> assert false | Ok db -> db
in
let initial_hash = db.hash in
let schema = Schema.empty in
let (db, _) = match Manipulation.Memory.create_relation storage db ~name:"rel1" ~schema with
| Error _ -> assert false
| Ok x -> x
in
(* After first change, initial hash should be in history *)
assert (db.hash <> initial_hash);
let hash_after_rel1 = db.hash in
let (db, _) = match Manipulation.Memory.create_relation storage db ~name:"rel2" ~schema with
| Error _ -> assert false
| Ok x -> x
in
(* After second change, previous hash should be in history *)
assert (db.hash <> hash_after_rel1);
assert (List.mem hash_after_rel1 db.history))
let%test_unit "integration: hash bubbles up correctly" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty in
let (db, relation) = match Manipulation.Memory.create_relation storage db ~name:"items" ~schema with
| Error _ -> assert false
| Ok x -> x
in
let db_hash_before = db.hash in
let rel_hash_before = relation.hash in
(* Insert a tuple *)
let attrs = Tuple.AttributeMap.empty
|> Tuple.AttributeMap.add "x" { Attribute.value = Obj.magic 1 } in
let tuple : Tuple.materialized = { relation = "items"; attributes = attrs } in
let (db, relation, _) = match Manipulation.Memory.create_tuple storage db relation tuple with
| Error _ -> assert false
| Ok x -> x
in
(* Relation hash should change *)
assert (relation.hash <> rel_hash_before);
(* Database hash should change *)
assert (db.hash <> db_hash_before);
(* Old database hash should be in history *)
assert (List.mem db_hash_before db.history);
(* Database's merkle tree should contain the new relation hash *)
match relation.hash with
| None -> assert false
| Some rel_hash ->
assert (Merkle.member rel_hash db.tree))
(* ============================================================================
Time-Travel / Branching Tests
============================================================================ *)
let%test_unit "branching: load database from historical hash" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty in
(* Create relation and add a tuple *)
let (db, relation) = match Manipulation.Memory.create_relation storage db ~name:"items" ~schema with
| Error _ -> assert false
| Ok x -> x
in
let attrs = Tuple.AttributeMap.empty
|> Tuple.AttributeMap.add "x" { Attribute.value = Obj.magic 1 } in
let tuple : Tuple.materialized = { relation = "items"; attributes = attrs } in
let (db, _relation, _) = match Manipulation.Memory.create_tuple storage db relation tuple with
| Error _ -> assert false
| Ok x -> x
in
(* Capture hash H1 - database with 1 tuple *)
let h1 = db.hash in
(* Add another tuple *)
let attrs2 = Tuple.AttributeMap.empty
|> Tuple.AttributeMap.add "x" { Attribute.value = Obj.magic 2 } in
let tuple2 : Tuple.materialized = { relation = "items"; attributes = attrs2 } in
(* Get relation from database - it's now integrated! *)
let relation = match Manipulation.Memory.get_relation db ~name:"items" with
| None -> assert false
| Some r -> r
in
let (db, _relation, _) = match Manipulation.Memory.create_tuple storage db relation tuple2 with
| Error _ -> assert false
| Ok x -> x
in
let h2 = db.hash in
assert (h1 <> h2);
(* Now load H1 from storage - should get database state with 1 tuple *)
match Manipulation.Memory.load_database storage h1 with
| Error _ -> assert false
| Ok None -> assert false
| Ok (Some loaded_db) ->
assert (loaded_db.hash = h1);
assert (loaded_db.name = "test");
(* The relation is now loaded directly in the database *)
match Manipulation.Memory.get_relation loaded_db ~name:"items" with
| None -> assert false
| Some loaded_rel ->
(* Should have 1 tuple *)
assert (Manipulation.Memory.tuple_count loaded_rel = 1))
let%test_unit "branching: branch from historical state" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty in
(* Create relation *)
let (db, relation) = match Manipulation.Memory.create_relation storage db ~name:"data" ~schema with
| Error _ -> assert false
| Ok x -> x
in
(* Add tuple A *)
let tuple_a : Tuple.materialized = {
relation = "data";
attributes = Tuple.AttributeMap.singleton "v" { Attribute.value = Obj.magic "A" }
} in
let (db, relation, _) = match Manipulation.Memory.create_tuple storage db relation tuple_a with
| Error _ -> assert false
| Ok x -> x
in
(* Capture H1 - state with tuple A *)
let h1 = db.hash in
(* Continue on main branch: add tuple B *)
let tuple_b : Tuple.materialized = {
relation = "data";
attributes = Tuple.AttributeMap.singleton "v" { Attribute.value = Obj.magic "B" }
} in
let (db_main, relation_main, _) = match Manipulation.Memory.create_tuple storage db relation tuple_b with
| Error _ -> assert false
| Ok x -> x
in
let h2 = db_main.hash in
(* Now branch from H1 and add tuple C instead *)
let db_branch = match Manipulation.Memory.load_database storage h1 with
| Error _ -> assert false
| Ok None -> assert false
| Ok (Some d) -> d
in
(* Relation is now loaded directly in the database *)
let relation_branch = match Manipulation.Memory.get_relation db_branch ~name:"data" with
| None -> assert false
| Some r -> r
in
let tuple_c : Tuple.materialized = {
relation = "data";
attributes = Tuple.AttributeMap.singleton "v" { Attribute.value = Obj.magic "C" }
} in
let (db_branch, _relation_branch, _) = match Manipulation.Memory.create_tuple storage db_branch relation_branch tuple_c with
| Error _ -> assert false
| Ok x -> x
in
let h3 = db_branch.hash in
(* Verify: H1, H2, H3 are all different *)
assert (h1 <> h2);
assert (h1 <> h3);
assert (h2 <> h3);
(* H2 (main branch) has tuples A and B *)
assert (Manipulation.Memory.tuple_count relation_main = 2);
(* H1 is still loadable and unchanged *)
match Manipulation.Memory.load_database storage h1 with
| Error _ -> assert false
| Ok None -> assert false
| Ok (Some loaded_h1) ->
match Manipulation.Memory.get_relation loaded_h1 ~name:"data" with
| None -> assert false
| Some r ->
assert (Manipulation.Memory.tuple_count r = 1))
let%test_unit "branching: full reconstruction from hash" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"shop" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty in
(* Create relation *)
let (db, relation) = match Manipulation.Memory.create_relation storage db ~name:"products" ~schema with
| Error _ -> assert false
| Ok x -> x
in
(* Add products *)
let make_product name =
{ Tuple.relation = "products";
attributes = Tuple.AttributeMap.singleton "name" { Attribute.value = Obj.magic name } }
in
let (db, _relation, _) = match Manipulation.Memory.create_tuples storage db relation
[make_product "Apple"; make_product "Banana"; make_product "Cherry"] with
| Error _ -> assert false
| Ok x -> x
in
let saved_hash = db.hash in
(* Now reconstruct everything from just the hash *)
match Manipulation.Memory.load_database storage saved_hash with
| Error _ -> assert false
| Ok None -> assert false
| Ok (Some loaded_db) ->
(* Relation is now loaded directly in the database *)
match Manipulation.Memory.get_relation loaded_db ~name:"products" with
| None -> assert false
| Some loaded_rel ->
(* Get tuple hashes from relation *)
let tuple_hashes = Manipulation.Memory.tuple_hashes loaded_rel in
assert (List.length tuple_hashes = 3);
(* Load all tuples *)
match Manipulation.Memory.load_tuples storage tuple_hashes with
| Error _ -> assert false
| Ok tuples ->
assert (List.length tuples = 3);
let names = List.map (fun t ->
let attr = Tuple.AttributeMap.find "name" t.Tuple.attributes in
(Obj.magic attr.Attribute.value : string)
) tuples in
assert (List.mem "Apple" names);
assert (List.mem "Banana" names);
assert (List.mem "Cherry" names))
(* ============================================================================
Algebra Tests
============================================================================ *)
(* Helper: build a materialized tuple with int attributes *)
let make_int_tuple relation pairs =
let attributes =
List.fold_left (fun acc (k, v) ->
Tuple.AttributeMap.add k { Attribute.value = Obj.repr (v : int) } acc)
Tuple.AttributeMap.empty pairs
in
(Tuple.Materialized { Tuple.relation; attributes } : Tuple.t)
(* Helper: build a stored relation with one integer column and given values *)
let stored_relation_with_ints storage db ~name ~attr values =
let schema = Schema.empty |> Schema.add attr "integer" in
let (db, rel) = match Manipulation.Memory.create_relation storage db ~name ~schema with
| Error _ -> assert false | Ok x -> x
in
let tuples = List.map (fun v ->
let attributes =
Tuple.AttributeMap.singleton attr { Attribute.value = Obj.repr (v : int) }
in
({ Tuple.relation = name; attributes } : Tuple.materialized)
) values in
let (db, rel, _) = match Manipulation.Memory.create_tuples storage db rel tuples with
| Error _ -> assert false | Ok x -> x
in
(db, rel)
let%test_unit "algebra: const_relation single tuple" =
with_storage (fun storage ->
let rel = Algebra.Memory.const_relation
[ "x", Obj.repr (42 : int);
"y", Obj.repr (99 : int) ] in
match Algebra.Memory.materialize storage rel with
| Error _ -> assert false
| Ok [tup] ->
let x: int = Obj.obj (Tuple.AttributeMap.find "x" tup.Tuple.attributes).Attribute.value in
assert (x = 42)
| Ok _ -> assert false)
let%test_unit "algebra: select_fn with predicate" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test_db" with
| Error _ -> assert false | Ok db -> db
in
let (_, rel) = stored_relation_with_ints storage db ~name:"nums" ~attr:"n" [1;2;3;4;5] in
let predicate = function
| Tuple.Materialized t ->
let v: int = Obj.obj (Tuple.AttributeMap.find "n" t.Tuple.attributes).Attribute.value in
v > 3
| _ -> false
in
match Algebra.Memory.select_fn storage predicate rel with
| Error _ -> assert false
| Ok result ->
match Algebra.Memory.materialize storage result with
| Error _ -> assert false
| Ok rows ->
assert (List.length rows = 2);
List.iter (fun t ->
let v: int = Obj.obj (Tuple.AttributeMap.find "n" t.Tuple.attributes).Attribute.value in
assert (v > 3)) rows)
let%test_unit "algebra: project restricts schema" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test_db" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty |> Schema.add "a" "integer" |> Schema.add "b" "integer" in
let (db, rel) = match Manipulation.Memory.create_relation storage db ~name:"ab" ~schema with
| Error _ -> assert false | Ok x -> x
in
let attrs = Tuple.AttributeMap.empty
|> Tuple.AttributeMap.add "a" { Attribute.value = Obj.repr (1 : int) }
|> Tuple.AttributeMap.add "b" { Attribute.value = Obj.repr (2 : int) } in
let (_, rel, _) = match Manipulation.Memory.create_tuple storage db rel
{ Tuple.relation = "ab"; attributes = attrs } with
| Error _ -> assert false | Ok x -> x
in
match Algebra.Memory.project storage ["a"] rel with
| Error _ -> assert false
| Ok projected ->
match Algebra.Memory.materialize storage projected with
| Error _ -> assert false
| Ok [t] ->
assert (Tuple.AttributeMap.mem "a" t.Tuple.attributes);
assert (not (Tuple.AttributeMap.mem "b" t.Tuple.attributes))
| Ok _ -> assert false)
let%test_unit "algebra: rename changes attr names" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test_db" with
| Error _ -> assert false | Ok db -> db
in
let (_, rel) = stored_relation_with_ints storage db ~name:"r" ~attr:"x" [7] in
match Algebra.Memory.rename storage [("x", "y")] rel with
| Error _ -> assert false
| Ok renamed ->
match Algebra.Memory.materialize storage renamed with
| Error _ -> assert false
| Ok [t] ->
assert (not (Tuple.AttributeMap.mem "x" t.Tuple.attributes));
assert (Tuple.AttributeMap.mem "y" t.Tuple.attributes);
let v: int = Obj.obj (Tuple.AttributeMap.find "y" t.Tuple.attributes).Attribute.value in
assert (v = 7)
| Ok _ -> assert false)
let%test_unit "algebra: equijoin merges matching tuples" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test_db" with
| Error _ -> assert false | Ok db -> db
in
(* left: {id=1, name="Alice"}, {id=2, name="Bob"} *)
let schema_l = Schema.empty |> Schema.add "id" "integer" |> Schema.add "name" "string" in
let (db, left) = match Manipulation.Memory.create_relation storage db ~name:"L" ~schema:schema_l with
| Error _ -> assert false | Ok x -> x
in
let make_left id name =
let attrs = Tuple.AttributeMap.empty
|> Tuple.AttributeMap.add "id" { Attribute.value = Obj.repr (id : int) }
|> Tuple.AttributeMap.add "name" { Attribute.value = Obj.repr (name : string) } in
({ Tuple.relation = "L"; attributes = attrs } : Tuple.materialized)
in
let (db, left, _) = match Manipulation.Memory.create_tuples storage db left
[make_left 1 "Alice"; make_left 2 "Bob"] with
| Error _ -> assert false | Ok x -> x
in
(* right: {id=1, score=100}, {id=3, score=999} *)
let schema_r = Schema.empty |> Schema.add "id" "integer" |> Schema.add "score" "integer" in
let (db, right) = match Manipulation.Memory.create_relation storage db ~name:"R" ~schema:schema_r with
| Error _ -> assert false | Ok x -> x
in
let make_right id score =
let attrs = Tuple.AttributeMap.empty
|> Tuple.AttributeMap.add "id" { Attribute.value = Obj.repr (id : int) }
|> Tuple.AttributeMap.add "score" { Attribute.value = Obj.repr (score : int) } in
({ Tuple.relation = "R"; attributes = attrs } : Tuple.materialized)
in
let (_, right, _) = match Manipulation.Memory.create_tuples storage db right
[make_right 1 100; make_right 3 999] with
| Error _ -> assert false | Ok x -> x
in
match Algebra.Memory.equijoin storage ["id"] left right with
| Error _ -> assert false
| Ok joined ->
match Algebra.Memory.materialize storage joined with
| Error _ -> assert false
| Ok rows ->
(* Only id=1 matches *)
assert (List.length rows = 1);
let t = List.hd rows in
let score: int = Obj.obj (Tuple.AttributeMap.find "score" t.Tuple.attributes).Attribute.value in
assert (score = 100))
let%test_unit "algebra: equijoin empty match" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test_db" with
| Error _ -> assert false | Ok db -> db
in
let (db, left) = stored_relation_with_ints storage db ~name:"L" ~attr:"id" [1;2] in
let (_, right) = stored_relation_with_ints storage db ~name:"R" ~attr:"id" [9;8] in
match Algebra.Memory.equijoin storage ["id"] left right with
| Error _ -> assert false
| Ok joined ->
match Algebra.Memory.materialize storage joined with
| Error _ -> assert false
| Ok rows -> assert (List.length rows = 0))
let%test_unit "algebra: union concatenates streams" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test_db" with
| Error _ -> assert false | Ok db -> db
in
let (db, r1) = stored_relation_with_ints storage db ~name:"A" ~attr:"n" [1;2] in
let (_, r2) = stored_relation_with_ints storage db ~name:"B" ~attr:"n" [3;4] in
match Algebra.Memory.union storage r1 r2 with
| Error _ -> assert false
| Ok unioned ->
match Algebra.Memory.materialize storage unioned with
| Error _ -> assert false
| Ok rows ->
assert (List.length rows = 4);
let vals = List.map (fun t ->
Obj.obj (Tuple.AttributeMap.find "n" t.Tuple.attributes).Attribute.value
) rows in
assert (List.mem 1 vals);
assert (List.mem 2 vals);
assert (List.mem 3 vals);
assert (List.mem 4 vals))
let%test_unit "algebra: diff removes right from left" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test_db" with
| Error _ -> assert false | Ok db -> db
in
let (db, r1) = stored_relation_with_ints storage db ~name:"A" ~attr:"n" [1;2;3] in
let (_, r2) = stored_relation_with_ints storage db ~name:"B" ~attr:"n" [2;3] in
match Algebra.Memory.diff storage r1 r2 with
| Error _ -> assert false
| Ok result ->
match Algebra.Memory.materialize storage result with
| Error _ -> assert false
| Ok rows ->
assert (List.length rows = 1);
let v: int = Obj.obj (Tuple.AttributeMap.find "n" (List.hd rows).Tuple.attributes).Attribute.value in
assert (v = 1))
let%test_unit "algebra: take limits output" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test_db" with
| Error _ -> assert false | Ok db -> db
in
let (_, rel) = stored_relation_with_ints storage db ~name:"big" ~attr:"n" [10;20;30;40;50] in
match Algebra.Memory.take storage 3 rel with
| Error _ -> assert false
| Ok result ->
match Algebra.Memory.materialize storage result with
| Error _ -> assert false
| Ok rows -> assert (List.length rows = 3))
(* ============================================================================
DRL Parser Tests
============================================================================ *)
let%test_unit "drl: parse Base" =
match Drl.Parser.of_string {|(Base "users")|} with
| Error _ -> assert false
| Ok (Drl.Ast.Base s) -> assert (s = "users")
| Ok _ -> assert false
let%test_unit "drl: parse Const" =
match Drl.Parser.of_string {|(Const (("age" (Int 18))))|} with
| Error _ -> assert false
| Ok (Drl.Ast.Const [("age", Drl.Ast.Int 18)]) -> ()
| Ok _ -> assert false
let%test_unit "drl: parse Join" =
match Drl.Parser.of_string {|(Join (id) (Base "L") (Base "R"))|} with
| Error _ -> assert false
| Ok (Drl.Ast.Join (["id"], Drl.Ast.Base "L", Drl.Ast.Base "R")) -> ()
| Ok _ -> assert false
let%test_unit "drl: parse Select" =
let s = {|(Select (Const (("age" (Int 18)))) (Base "users"))|} in
match Drl.Parser.of_string s with
| Error _ -> assert false
| Ok (Drl.Ast.Select (Drl.Ast.Const _, Drl.Ast.Base "users")) -> ()
| Ok _ -> assert false
(* ============================================================================
DRL Executor end-to-end Tests
============================================================================ *)
let%test_unit "drl: execute Base" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test_db" with
| Error _ -> assert false | Ok db -> db
in
let (db, _) = stored_relation_with_ints storage db ~name:"items" ~attr:"v" [10; 20] in
match Drl.Parser.of_string {|(Base "items")|} with
| Error _ -> assert false
| Ok query ->
match Drl.Executor.Memory.execute storage db query with
| Error _ -> assert false
| Ok rel ->
match Algebra.Memory.materialize storage rel with
| Error _ -> assert false
| Ok rows -> assert (List.length rows = 2))
let%test_unit "drl: execute Select+Const" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"test_db" with
| Error _ -> assert false | Ok db -> db
in
(* users: {age=18, name="Alice"}, {age=25, name="Bob"} *)
let schema = Schema.empty |> Schema.add "age" "integer" |> Schema.add "name" "string" in
let (db, users) = match Manipulation.Memory.create_relation storage db ~name:"users" ~schema with
| Error _ -> assert false | Ok x -> x
in
let make_user age name =
let attrs = Tuple.AttributeMap.empty
|> Tuple.AttributeMap.add "age" { Attribute.value = Obj.repr (age : int) }
|> Tuple.AttributeMap.add "name" { Attribute.value = Obj.repr (name : string) } in
({ Tuple.relation = "users"; attributes = attrs } : Tuple.materialized)
in
let (db, _, _) = match Manipulation.Memory.create_tuples storage db users
[make_user 18 "Alice"; make_user 25 "Bob"] with
| Error _ -> assert false | Ok x -> x
in
(* Query: select users where age = 18 *)
let s = {|(Select (Const (("age" (Int 18)))) (Base "users"))|} in
match Drl.Parser.of_string s with
| Error _ -> assert false
| Ok query ->
match Drl.Executor.Memory.execute storage db query with
| Error _ -> assert false
| Ok rel ->
match Algebra.Memory.materialize storage rel with
| Error _ -> assert false
| Ok rows ->
assert (List.length rows = 1);
let name_v: string =
Obj.obj (Tuple.AttributeMap.find "name" (List.hd rows).Tuple.attributes).Attribute.value
in
assert (name_v = "Alice"))
(* ============================================================================
Constraint System Tests
============================================================================ *)
(* ---------- Constraint construction ---------- *)
let%test_unit "constraint: vars_in MemberOf" =
let b =
Constraint.BindingMap.empty
|> Constraint.BindingMap.add "left" (Constraint.Var "x")
|> Constraint.BindingMap.add "right" (Constraint.Const (Obj.repr 10))
in
let c = Constraint.MemberOf { target = "less_than"; binding = b } in
let vars = Constraint.vars_in c in
assert (List.mem "x" vars);
assert (not (List.mem "right" vars))
let%test_unit "constraint: vars_in And" =
let b1 =
Constraint.BindingMap.singleton "left" (Constraint.Var "a")
in
let b2 =
Constraint.BindingMap.singleton "left" (Constraint.Var "b")
in
let c =
Constraint.And
[
Constraint.MemberOf { target = "t1"; binding = b1 };
Constraint.MemberOf { target = "t2"; binding = b2 };
]
in
let vars = Constraint.vars_in c in
assert (List.mem "a" vars);
assert (List.mem "b" vars)
let%test_unit "constraint: rename_vars" =
let b =
Constraint.BindingMap.singleton "left" (Constraint.Var "old_name")
in
let c = Constraint.MemberOf { target = "t"; binding = b } in
let c' = Constraint.rename_vars [ ("old_name", "new_name") ] c in
let vars = Constraint.vars_in c' in
assert (List.mem "new_name" vars);
assert (not (List.mem "old_name" vars))
let%test_unit "constraint: filter_by_attrs keeps relevant" =
let b =
Constraint.BindingMap.singleton "left" (Constraint.Var "x")
in
let c = Constraint.MemberOf { target = "t"; binding = b } in
assert (Constraint.filter_by_attrs [ "x" ] c <> None);
assert (Constraint.filter_by_attrs [ "y" ] c = None)
let%test_unit "constraint: merge named constraints" =
let b = Constraint.BindingMap.empty in
let cs1 = [ ("c1", Constraint.MemberOf { target = "t1"; binding = b }) ] in
let cs2 = [ ("c2", Constraint.MemberOf { target = "t2"; binding = b }) ] in
let merged = Constraint.merge cs1 cs2 in
assert (List.length merged = 2)
let%test_unit "constraint: merge duplicate names produces And" =
let b = Constraint.BindingMap.empty in
let c1 = Constraint.MemberOf { target = "t1"; binding = b } in
let c2 = Constraint.MemberOf { target = "t2"; binding = b } in
let merged = Constraint.merge [ ("shared", c1) ] [ ("shared", c2) ] in
assert (List.length merged = 1);
match List.assoc "shared" merged with
| Constraint.And _ -> ()
| _ -> assert false
(* ---------- Smart constructors ---------- *)
let%test_unit "constraint: and_ singleton" =
let b = Constraint.BindingMap.empty in
let c = Constraint.MemberOf { target = "t"; binding = b } in
match Constraint.and_ [ c ] with
| Constraint.MemberOf _ -> ()
| _ -> assert false
let%test_unit "constraint: or_ singleton" =
let b = Constraint.BindingMap.empty in
let c = Constraint.MemberOf { target = "t"; binding = b } in
match Constraint.or_ [ c ] with
| Constraint.MemberOf _ -> ()
| _ -> assert false
(* ---------- Comparison shorthands ---------- *)
let%test_unit "constraint: lt shorthand" =
match Constraint.lt ~left:(Var "x") ~right:(Const (Obj.repr 5)) with
| Constraint.MemberOf { target = "less_than"; _ } -> ()
| _ -> assert false
let%test_unit "constraint: between shorthand" =
match
Constraint.between ~value:(Var "x") ~low:(Const (Obj.repr 0))
~high:(Const (Obj.repr 100))
with
| Constraint.And [ _; _ ] -> ()
| _ -> assert false
(* ---------- Binding resolution ---------- *)
let%test_unit "constraint: bind resolves Var and Const" =
let b =
Constraint.BindingMap.empty
|> Constraint.BindingMap.add "left" (Constraint.Var "x")
|> Constraint.BindingMap.add "right" (Constraint.Const (Obj.repr 42))
in
let tuple : Tuple.materialized =
{
relation = "test";
attributes =
Tuple.AttributeMap.singleton "x" { Attribute.value = Obj.repr 10 };
}
in
let bound = Constraint.bind b tuple in
assert (List.length bound = 2);
let left_v : int = Obj.obj (List.assoc "left" bound) in
let right_v : int = Obj.obj (List.assoc "right" bound) in
assert (left_v = 10);
assert (right_v = 42)
(* ---------- Evaluation engine ---------- *)
let make_eval_ctx ?(relations = []) () : Constraint.eval_context =
{
check_membership =
(fun rel_name bound_pairs ->
match List.assoc_opt rel_name relations with
| None -> false
| Some checker -> checker bound_pairs);
iterate_finite =
(fun rel_name ->
match List.assoc_opt rel_name relations with
| None -> None
| Some _ -> Some []);
}
let%test_unit "constraint: evaluate MemberOf success" =
let ctx =
make_eval_ctx
~relations:[ ("my_rel", fun _pairs -> true) ]
()
in
let b = Constraint.BindingMap.empty in
let c = Constraint.MemberOf { target = "my_rel"; binding = b } in
let tuple : Tuple.materialized =
{ relation = "test"; attributes = Tuple.AttributeMap.empty }
in
match Constraint.evaluate ctx tuple c with
| Ok true -> ()
| _ -> assert false
let%test_unit "constraint: evaluate MemberOf failure" =
let ctx =
make_eval_ctx
~relations:[ ("my_rel", fun _pairs -> false) ]
()
in
let b = Constraint.BindingMap.empty in
let c = Constraint.MemberOf { target = "my_rel"; binding = b } in
let tuple : Tuple.materialized =
{ relation = "test"; attributes = Tuple.AttributeMap.empty }
in
match Constraint.evaluate ctx tuple c with
| Error (Constraint.MembershipFailed _) -> ()
| _ -> assert false
let%test_unit "constraint: evaluate And short-circuits" =
let call_count = ref 0 in
let ctx =
make_eval_ctx
~relations:
[
( "fail_rel",
fun _ ->
incr call_count;
false );
( "ok_rel",
fun _ ->
incr call_count;
true );
]
()
in
let b = Constraint.BindingMap.empty in
let c =
Constraint.And
[
Constraint.MemberOf { target = "fail_rel"; binding = b };
Constraint.MemberOf { target = "ok_rel"; binding = b };
]
in
let tuple : Tuple.materialized =
{ relation = "test"; attributes = Tuple.AttributeMap.empty }
in
(match Constraint.evaluate ctx tuple c with
| Error _ -> ()
| _ -> assert false);
(* Second branch should not have been called *)
assert (!call_count = 1)
let%test_unit "constraint: evaluate Or succeeds on first match" =
let ctx =
make_eval_ctx
~relations:
[
("a", fun _ -> false);
("b", fun _ -> true);
]
()
in
let b = Constraint.BindingMap.empty in
let c =
Constraint.Or
[
Constraint.MemberOf { target = "a"; binding = b };
Constraint.MemberOf { target = "b"; binding = b };
]
in
let tuple : Tuple.materialized =
{ relation = "test"; attributes = Tuple.AttributeMap.empty }
in
match Constraint.evaluate ctx tuple c with
| Ok true -> ()
| _ -> assert false
let%test_unit "constraint: evaluate Not negates" =
let ctx : Constraint.eval_context =
{
check_membership =
(fun rel_name _pairs ->
match rel_name with
| "universe" -> true
| "body_rel" -> false
| _ -> false);
iterate_finite = (fun _ -> None);
}
in
let b = Constraint.BindingMap.empty in
let c =
Constraint.Not
{
body = Constraint.MemberOf { target = "body_rel"; binding = b };
universe = "universe";
}
in
let tuple : Tuple.materialized =
{ relation = "test"; attributes = Tuple.AttributeMap.empty }
in
match Constraint.evaluate ctx tuple c with
| Ok true -> ()
| _ -> assert false
let%test_unit "constraint: evaluate Exists over finite relation" =
let ctx : Constraint.eval_context =
{
check_membership =
(fun _rel_name pairs ->
match List.assoc_opt "left" pairs, List.assoc_opt "right" pairs with
| Some l, Some r -> (Obj.obj l : int) < (Obj.obj r : int)
| _ -> false);
iterate_finite =
(fun rel_name ->
if rel_name = "small_set" then
Some
[
[ ("value", Obj.repr 1) ];
[ ("value", Obj.repr 5) ];
[ ("value", Obj.repr 10) ];
]
else None);
}
in
let b =
Constraint.BindingMap.empty
|> Constraint.BindingMap.add "left" (Constraint.Var "x")
|> Constraint.BindingMap.add "right" (Constraint.Var "value")
in
let c =
Constraint.Exists
{
variable = "value";
quantifier = "small_set";
body = Constraint.MemberOf { target = "less_than"; binding = b };
}
in
(* x=3, exists value in {1,5,10} where 3 < value => true (5 or 10 work) *)
let tuple : Tuple.materialized =
{
relation = "test";
attributes =
Tuple.AttributeMap.singleton "x" { Attribute.value = Obj.repr 3 };
}
in
match Constraint.evaluate ctx tuple c with
| Ok true -> ()
| _ -> assert false
let%test_unit "constraint: evaluate Forall fails when not all match" =
let ctx : Constraint.eval_context =
{
check_membership =
(fun _rel_name pairs ->
match List.assoc_opt "left" pairs, List.assoc_opt "right" pairs with
| Some l, Some r -> (Obj.obj l : int) < (Obj.obj r : int)
| _ -> false);
iterate_finite =
(fun rel_name ->
if rel_name = "small_set" then
Some
[
[ ("value", Obj.repr 1) ];
[ ("value", Obj.repr 5) ];
]
else None);
}
in
let b =
Constraint.BindingMap.empty
|> Constraint.BindingMap.add "left" (Constraint.Var "x")
|> Constraint.BindingMap.add "right" (Constraint.Var "value")
in
let c =
Constraint.Forall
{
variable = "value";
quantifier = "small_set";
body = Constraint.MemberOf { target = "less_than"; binding = b };
}
in
(* x=3, forall value in {1,5} where 3 < value => false (3 is not < 1) *)
let tuple : Tuple.materialized =
{
relation = "test";
attributes =
Tuple.AttributeMap.singleton "x" { Attribute.value = Obj.repr 3 };
}
in
match Constraint.evaluate ctx tuple c with
| Ok false -> ()
| _ -> assert false
let%test_unit "constraint: Forall unbounded quantifier errors" =
let ctx : Constraint.eval_context =
{
check_membership = (fun _ _ -> true);
iterate_finite = (fun _ -> None);
}
in
let b = Constraint.BindingMap.empty in
let c =
Constraint.Forall
{
variable = "v";
quantifier = "infinite_rel";
body = Constraint.MemberOf { target = "t"; binding = b };
}
in
let tuple : Tuple.materialized =
{ relation = "test"; attributes = Tuple.AttributeMap.empty }
in
match Constraint.evaluate ctx tuple c with
| Error (Constraint.UnboundedQuantifier _) -> ()
| _ -> assert false
(* ---------- Integrated constraint enforcement in manipulation ---------- *)
let%test_unit "constraint: create_tuple with passing constraint" =
with_storage (fun storage ->
let db =
match Manipulation.Memory.create_database storage ~name:"test" with
| Error _ -> assert false
| Ok db -> db
in
let schema = Schema.empty |> Schema.add "value" "natural" in
let db, _rel =
match
Manipulation.Memory.create_relation storage db ~name:"positives"
~schema
with
| Error _ -> assert false
| Ok x -> x
in
(* Register a constraint: value must be member of natural (always true for naturals) *)
let db =
match
Manipulation.Memory.register_constraint storage db
~constraint_name:"is_natural" ~relation_name:"positives"
~body:(Constraint.And [])
with
| Error _ -> assert false
| Ok db -> db
in
let rel =
match Manipulation.Memory.get_relation db ~name:"positives" with
| None -> assert false
| Some r -> r
in
let tuple : Tuple.materialized =
{
relation = "positives";
attributes =
Tuple.AttributeMap.singleton "value"
{ Attribute.value = Obj.repr 5 };
}
in
match Manipulation.Memory.create_tuple storage db rel tuple with
| Ok _ -> ()
| Error _ -> assert false)
let%test_unit "constraint: create_tuple with failing constraint" =
with_storage (fun storage ->
let db =
match Manipulation.Memory.create_database storage ~name:"test" with
| Error _ -> assert false
| Ok db -> db
in
let schema = Schema.empty |> Schema.add "value" "natural" in
let db, _rel =
match
Manipulation.Memory.create_relation storage db ~name:"checked"
~schema
with
| Error _ -> assert false
| Ok x -> x
in
(* Register a constraint that always fails: MemberOf a nonexistent relation *)
let db =
match
Manipulation.Memory.register_constraint storage db
~constraint_name:"impossible" ~relation_name:"checked"
~body:
(Constraint.MemberOf
{
target = "nonexistent_relation";
binding =
Constraint.BindingMap.singleton "x" (Constraint.Var "value");
})
with
| Error _ -> assert false
| Ok db -> db
in
let rel =
match Manipulation.Memory.get_relation db ~name:"checked" with
| None -> assert false
| Some r -> r
in
let tuple : Tuple.materialized =
{
relation = "checked";
attributes =
Tuple.AttributeMap.singleton "value"
{ Attribute.value = Obj.repr 5 };
}
in
match Manipulation.Memory.create_tuple storage db rel tuple with
| Error (Manipulation.ConstraintViolation _) -> ()
| _ -> assert false)
(* ---------- Scenario tests ported from Erlang ---------- *)
(* Scenario 1: Mutual exclusion between subtypes *)
let%test_unit "constraint scenario: mutual exclusion subtypes" =
with_storage (fun storage ->
let db =
match Manipulation.Memory.create_database storage ~name:"test" with
| Error _ -> assert false
| Ok db -> db
in
let schema = Schema.empty |> Schema.add "id" "natural" in
let db, _employee =
match
Manipulation.Memory.create_relation storage db ~name:"employee"
~schema
with
| Error _ -> assert false
| Ok x -> x
in
let db, _manager =
match
Manipulation.Memory.create_relation storage db ~name:"manager"
~schema
with
| Error _ -> assert false
| Ok x -> x
in
(* manager must NOT be in employee (mutual exclusion) *)
let body =
Constraint.Not
{
body =
Constraint.MemberOf
{
target = "employee";
binding =
Constraint.BindingMap.singleton "id" (Constraint.Var "id");
};
universe = "manager";
}
in
let db =
match
Manipulation.Memory.register_constraint storage db
~constraint_name:"not_employee" ~relation_name:"manager" ~body
with
| Error _ -> assert false
| Ok db -> db
in
(* Insert into employee first *)
let employee =
match Manipulation.Memory.get_relation db ~name:"employee" with
| None -> assert false
| Some r -> r
in
let emp_tuple : Tuple.materialized =
{
relation = "employee";
attributes =
Tuple.AttributeMap.singleton "id"
{ Attribute.value = Obj.repr 1 };
}
in
let db, _employee, _ =
match
Manipulation.Memory.create_tuple storage db employee emp_tuple
with
| Error _ -> assert false
| Ok x -> x
in
(* Now try to insert same id into manager — should fail *)
let manager =
match Manipulation.Memory.get_relation db ~name:"manager" with
| None -> assert false
| Some r -> r
in
let mgr_tuple : Tuple.materialized =
{
relation = "manager";
attributes =
Tuple.AttributeMap.singleton "id"
{ Attribute.value = Obj.repr 1 };
}
in
match Manipulation.Memory.create_tuple storage db manager mgr_tuple with
| Error (Manipulation.ConstraintViolation _) -> ()
| _ -> assert false)
(* Scenario 2: Foreign key constraint *)
let%test_unit "constraint scenario: foreign key" =
with_storage (fun storage ->
let db =
match Manipulation.Memory.create_database storage ~name:"test" with
| Error _ -> assert false
| Ok db -> db
in
let order_schema = Schema.empty |> Schema.add "order_id" "natural" in
let db, _orders =
match
Manipulation.Memory.create_relation storage db ~name:"orders"
~schema:order_schema
with
| Error _ -> assert false
| Ok x -> x
in
let item_schema =
Schema.empty |> Schema.add "item_id" "natural"
|> Schema.add "order_id" "natural"
in
let db, _items =
match
Manipulation.Memory.create_relation storage db ~name:"order_items"
~schema:item_schema
with
| Error _ -> assert false
| Ok x -> x
in
(* FK: order_items.order_id must exist in orders *)
let fk_body =
Constraint.MemberOf
{
target = "orders";
binding =
Constraint.BindingMap.singleton "order_id"
(Constraint.Var "order_id");
}
in
let db =
match
Manipulation.Memory.register_constraint storage db
~constraint_name:"fk_order" ~relation_name:"order_items"
~body:fk_body
with
| Error _ -> assert false
| Ok db -> db
in
(* Insert an order *)
let orders =
match Manipulation.Memory.get_relation db ~name:"orders" with
| None -> assert false
| Some r -> r
in
let order_tuple : Tuple.materialized =
{
relation = "orders";
attributes =
Tuple.AttributeMap.singleton "order_id"
{ Attribute.value = Obj.repr 100 };
}
in
let db, _orders, _ =
match
Manipulation.Memory.create_tuple storage db orders order_tuple
with
| Error _ -> assert false
| Ok x -> x
in
(* Insert item referencing valid order — should succeed *)
let items =
match Manipulation.Memory.get_relation db ~name:"order_items" with
| None -> assert false
| Some r -> r
in
let valid_item : Tuple.materialized =
{
relation = "order_items";
attributes =
Tuple.AttributeMap.of_list
[
("item_id", { Attribute.value = Obj.repr 1 });
("order_id", { Attribute.value = Obj.repr 100 });
];
}
in
let db, items, _ =
match
Manipulation.Memory.create_tuple storage db items valid_item
with
| Error _ -> assert false
| Ok x -> x
in
(* Insert item referencing nonexistent order — should fail *)
let invalid_item : Tuple.materialized =
{
relation = "order_items";
attributes =
Tuple.AttributeMap.of_list
[
("item_id", { Attribute.value = Obj.repr 2 });
("order_id", { Attribute.value = Obj.repr 999 });
];
}
in
match Manipulation.Memory.create_tuple storage db items invalid_item with
| Error (Manipulation.ConstraintViolation _) -> ()
| _ -> assert false)
(* Scenario 3: Self-reference (emp_id != mgr_id via not_equal comparison) *)
let%test_unit "constraint scenario: self-reference neq" =
with_storage (fun storage ->
let db =
match Manipulation.Memory.create_database storage ~name:"test" with
| Error _ -> assert false
| Ok db -> db
in
let schema =
Schema.empty |> Schema.add "emp_id" "natural"
|> Schema.add "mgr_id" "natural"
in
let db, _rel =
match
Manipulation.Memory.create_relation storage db ~name:"reports_to"
~schema
with
| Error _ -> assert false
| Ok x -> x
in
(* Register the not_equal comparison relation *)
let db, _ =
match
Manipulation.Memory.create_immutable_relation storage db
~name:"not_equal"
~schema:
(Schema.empty |> Schema.add "left" "natural"
|> Schema.add "right" "natural")
~generator:(fun _ -> Generator.Error "not enumerable")
~membership_criteria:(fun t ->
match t with
| Tuple.Materialized m -> (
match
( Tuple.AttributeMap.find_opt "left" m.attributes,
Tuple.AttributeMap.find_opt "right" m.attributes )
with
| Some l, Some r ->
(Obj.obj l.Attribute.value : int)
<> (Obj.obj r.Attribute.value : int)
| _ -> false)
| _ -> false)
~cardinality:Conventions.Cardinality.AlephZero
with
| Error _ -> assert false
| Ok x -> x
in
(* Constraint: emp_id != mgr_id via not_equal relation *)
let neq_body =
Constraint.neq ~left:(Var "emp_id") ~right:(Var "mgr_id")
in
let db =
match
Manipulation.Memory.register_constraint storage db
~constraint_name:"no_self_manage" ~relation_name:"reports_to"
~body:neq_body
with
| Error _ -> assert false
| Ok db -> db
in
let rel =
match Manipulation.Memory.get_relation db ~name:"reports_to" with
| None -> assert false
| Some r -> r
in
(* Insert (emp_id=1, mgr_id=2) — should succeed *)
let valid : Tuple.materialized =
{
relation = "reports_to";
attributes =
Tuple.AttributeMap.of_list
[
("emp_id", { Attribute.value = Obj.repr 1 });
("mgr_id", { Attribute.value = Obj.repr 2 });
];
}
in
let db, rel, _ =
match Manipulation.Memory.create_tuple storage db rel valid with
| Error _ -> assert false
| Ok x -> x
in
(* Insert (emp_id=3, mgr_id=3) — same person, should fail *)
let invalid : Tuple.materialized =
{
relation = "reports_to";
attributes =
Tuple.AttributeMap.of_list
[
("emp_id", { Attribute.value = Obj.repr 3 });
("mgr_id", { Attribute.value = Obj.repr 3 });
];
}
in
match Manipulation.Memory.create_tuple storage db rel invalid with
| Error (Manipulation.ConstraintViolation _) -> ()
| _ -> assert false)
(* Scenario 4: Mutual exclusion between open_ticket and closed_ticket *)
let%test_unit "constraint scenario: open vs closed ticket" =
with_storage (fun storage ->
let db =
match Manipulation.Memory.create_database storage ~name:"test" with
| Error _ -> assert false
| Ok db -> db
in
let schema = Schema.empty |> Schema.add "ticket_id" "natural" in
let db, _ =
match
Manipulation.Memory.create_relation storage db ~name:"open_ticket"
~schema
with
| Error _ -> assert false
| Ok x -> x
in
let db, _ =
match
Manipulation.Memory.create_relation storage db ~name:"closed_ticket"
~schema
with
| Error _ -> assert false
| Ok x -> x
in
(* open_ticket must not be in closed_ticket *)
let db =
match
Manipulation.Memory.register_constraint storage db
~constraint_name:"not_closed" ~relation_name:"open_ticket"
~body:
(Constraint.Not
{
body =
Constraint.MemberOf
{
target = "closed_ticket";
binding =
Constraint.BindingMap.singleton "ticket_id"
(Constraint.Var "ticket_id");
};
universe = "open_ticket";
})
with
| Error _ -> assert false
| Ok db -> db
in
(* Insert ticket 1 as closed *)
let closed =
match Manipulation.Memory.get_relation db ~name:"closed_ticket" with
| None -> assert false
| Some r -> r
in
let t1 : Tuple.materialized =
{
relation = "closed_ticket";
attributes =
Tuple.AttributeMap.singleton "ticket_id"
{ Attribute.value = Obj.repr 1 };
}
in
let db, _, _ =
match Manipulation.Memory.create_tuple storage db closed t1 with
| Error _ -> assert false
| Ok x -> x
in
(* Try to open same ticket — should fail *)
let open_ =
match Manipulation.Memory.get_relation db ~name:"open_ticket" with
| None -> assert false
| Some r -> r
in
let t1_open : Tuple.materialized =
{
relation = "open_ticket";
attributes =
Tuple.AttributeMap.singleton "ticket_id"
{ Attribute.value = Obj.repr 1 };
}
in
match Manipulation.Memory.create_tuple storage db open_ t1_open with
| Error (Manipulation.ConstraintViolation _) -> ()
| _ -> assert false)
(* Scenario 5: Weak entity dependency *)
let%test_unit "constraint scenario: weak entity dependency" =
with_storage (fun storage ->
let db =
match Manipulation.Memory.create_database storage ~name:"test" with
| Error _ -> assert false
| Ok db -> db
in
let parent_schema = Schema.empty |> Schema.add "parent_id" "natural" in
let db, _ =
match
Manipulation.Memory.create_relation storage db ~name:"parent"
~schema:parent_schema
with
| Error _ -> assert false
| Ok x -> x
in
let dep_schema =
Schema.empty |> Schema.add "dep_id" "natural"
|> Schema.add "parent_id" "natural"
in
let db, _ =
match
Manipulation.Memory.create_relation storage db ~name:"dependent"
~schema:dep_schema
with
| Error _ -> assert false
| Ok x -> x
in
(* dependent.parent_id must exist in parent *)
let db =
match
Manipulation.Memory.register_constraint storage db
~constraint_name:"parent_exists" ~relation_name:"dependent"
~body:
(Constraint.MemberOf
{
target = "parent";
binding =
Constraint.BindingMap.singleton "parent_id"
(Constraint.Var "parent_id");
})
with
| Error _ -> assert false
| Ok db -> db
in
(* Insert parent *)
let parent =
match Manipulation.Memory.get_relation db ~name:"parent" with
| None -> assert false
| Some r -> r
in
let pt : Tuple.materialized =
{
relation = "parent";
attributes =
Tuple.AttributeMap.singleton "parent_id"
{ Attribute.value = Obj.repr 10 };
}
in
let db, _, _ =
match Manipulation.Memory.create_tuple storage db parent pt with
| Error _ -> assert false
| Ok x -> x
in
(* Insert dependent with valid parent — succeeds *)
let dep =
match Manipulation.Memory.get_relation db ~name:"dependent" with
| None -> assert false
| Some r -> r
in
let valid_dep : Tuple.materialized =
{
relation = "dependent";
attributes =
Tuple.AttributeMap.of_list
[
("dep_id", { Attribute.value = Obj.repr 1 });
("parent_id", { Attribute.value = Obj.repr 10 });
];
}
in
let db, dep, _ =
match
Manipulation.Memory.create_tuple storage db dep valid_dep
with
| Error _ -> assert false
| Ok x -> x
in
(* Insert dependent with nonexistent parent — fails *)
let invalid_dep : Tuple.materialized =
{
relation = "dependent";
attributes =
Tuple.AttributeMap.of_list
[
("dep_id", { Attribute.value = Obj.repr 2 });
("parent_id", { Attribute.value = Obj.repr 999 });
];
}
in
match
Manipulation.Memory.create_tuple storage db dep invalid_dep
with
| Error (Manipulation.ConstraintViolation _) -> ()
| _ -> assert false)
(* Scenario 6: Algebra propagation — select preserves constraints *)
let%test_unit "constraint propagation: select preserves constraints" =
with_storage (fun storage ->
let db =
match Manipulation.Memory.create_database storage ~name:"test" with
| Error _ -> assert false
| Ok db -> db
in
let schema = Schema.empty |> Schema.add "x" "natural" in
let db, _rel =
match
Manipulation.Memory.create_relation storage db ~name:"constrained"
~schema
with
| Error _ -> assert false
| Ok x -> x
in
let db =
match
Manipulation.Memory.register_constraint storage db
~constraint_name:"c1" ~relation_name:"constrained"
~body:(Constraint.And [])
with
| Error _ -> assert false
| Ok db -> db
in
let rel =
match Manipulation.Memory.get_relation db ~name:"constrained" with
| None -> assert false
| Some r -> r
in
match
Algebra.Memory.select_fn storage (fun _ -> true) rel
with
| Error _ -> assert false
| Ok result ->
assert (result.Relation.constraints <> None))
(* Scenario 7: Algebra propagation — project filters constraints *)
let%test_unit "constraint propagation: project filters constraints" =
with_storage (fun storage ->
let db =
match Manipulation.Memory.create_database storage ~name:"test" with
| Error _ -> assert false
| Ok db -> db
in
let schema =
Schema.empty |> Schema.add "x" "natural" |> Schema.add "y" "natural"
in
let db, _rel =
match
Manipulation.Memory.create_relation storage db ~name:"xy" ~schema
with
| Error _ -> assert false
| Ok x -> x
in
(* Constraint on x only *)
let c_on_x =
Constraint.MemberOf
{
target = "some_rel";
binding =
Constraint.BindingMap.singleton "left" (Constraint.Var "x");
}
in
let db =
match
Manipulation.Memory.register_constraint storage db
~constraint_name:"x_only" ~relation_name:"xy" ~body:c_on_x
with
| Error _ -> assert false
| Ok db -> db
in
let rel =
match Manipulation.Memory.get_relation db ~name:"xy" with
| None -> assert false
| Some r -> r
in
(* Project to only "x" — constraint should survive *)
(match Algebra.Memory.project storage [ "x" ] rel with
| Error _ -> assert false
| Ok result -> assert (result.Relation.constraints <> None));
(* Project to only "y" — constraint referencing "x" should be dropped *)
match Algebra.Memory.project storage [ "y" ] rel with
| Error _ -> assert false
| Ok result -> assert (result.Relation.constraints = None))
(* ============================================================================
DML Sublanguage Tests
============================================================================ *)
(* Parse tests use canonical flat sexp format: (Constructor (field val) ...) *)
let%test_unit "dml: parse CreateDatabase" =
match Dml.Parser.of_string {|(CreateDatabase "shop")|} with
| Error _ -> assert false
| Ok stmt -> assert (stmt = Dml.Ast.CreateDatabase "shop")
let%test_unit "dml: parse RetractRelation" =
match Dml.Parser.of_string {|(RetractRelation "users")|} with
| Error _ -> assert false
| Ok stmt -> assert (stmt = Dml.Ast.RetractRelation "users")
let%test_unit "dml: parse ClearRelation" =
match Dml.Parser.of_string {|(ClearRelation "users")|} with
| Error _ -> assert false
| Ok stmt -> assert (stmt = Dml.Ast.ClearRelation "users")
let%test_unit "dml: round-trip InsertTuple" =
let src = Dml.Ast.InsertTuple {
relation = "users";
attributes = [("name", Drl.Ast.Str "Alice"); ("age", Drl.Ast.Int 30)]
} in
match Dml.Parser.of_string (Dml.Parser.to_string src) with
| Error _ -> assert false
| Ok parsed -> assert (parsed = src)
let%test_unit "dml: round-trip CreateRelation" =
let src = Dml.Ast.CreateRelation {
name = "users";
schema = [("name", "string"); ("age", "natural")]
} in
match Dml.Parser.of_string (Dml.Parser.to_string src) with
| Error _ -> assert false
| Ok parsed -> assert (parsed = src)
let%test_unit "dml: round-trip InsertTuples" =
let src = Dml.Ast.InsertTuples {
relation = "users";
tuples = [
[("name", Drl.Ast.Str "Alice"); ("age", Drl.Ast.Int 30)];
[("name", Drl.Ast.Str "Bob"); ("age", Drl.Ast.Int 25)];
]
} in
match Dml.Parser.of_string (Dml.Parser.to_string src) with
| Error _ -> assert false
| Ok parsed -> assert (parsed = src)
let%test_unit "dml: round-trip RegisterDomain" =
let src = Dml.Ast.RegisterDomain { name = "money"; cardinality = Dml.Ast.AlephZero } in
match Dml.Parser.of_string (Dml.Parser.to_string src) with
| Error _ -> assert false
| Ok parsed -> assert (parsed = src)
(* Executor tests construct AST directly — no dependency on sexp format *)
let%test_unit "dml: execute CreateDatabase" =
with_storage (fun storage ->
let db = Management.Database.empty ~name:"" in
let stmt = Dml.Ast.CreateDatabase "shop" in
match Dml.Executor.Memory.execute storage db stmt with
| Error _ -> assert false
| Ok db -> assert (db.name = "shop"))
let%test_unit "dml: execute CreateRelation" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"shop" with
| Error _ -> assert false | Ok db -> db
in
let stmt = Dml.Ast.CreateRelation { name = "users"; schema = [("name", "string"); ("age", "natural")] } in
match Dml.Executor.Memory.execute storage db stmt with
| Error _ -> assert false
| Ok db -> assert (Management.Database.has_relation db "users"))
let%test_unit "dml: execute InsertTuple" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"shop" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty |> Schema.add "name" "string" in
let db = match Manipulation.Memory.create_relation storage db ~name:"users" ~schema with
| Error _ -> assert false | Ok (db, _) -> db
in
let stmt = Dml.Ast.InsertTuple { relation = "users"; attributes = [("name", Drl.Ast.Str "Alice")] } in
match Dml.Executor.Memory.execute storage db stmt with
| Error _ -> assert false
| Ok db ->
let rel = match Management.Database.get_relation db "users" with
| None -> assert false | Some r -> r
in
assert (Manipulation.Memory.tuple_count rel = 1))
let%test_unit "dml: execute InsertTuples" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"shop" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty |> Schema.add "name" "string" in
let db = match Manipulation.Memory.create_relation storage db ~name:"users" ~schema with
| Error _ -> assert false | Ok (db, _) -> db
in
let stmt = Dml.Ast.InsertTuples {
relation = "users";
tuples = [[("name", Drl.Ast.Str "Alice")]; [("name", Drl.Ast.Str "Bob")]]
} in
match Dml.Executor.Memory.execute storage db stmt with
| Error _ -> assert false
| Ok db ->
let rel = match Management.Database.get_relation db "users" with
| None -> assert false | Some r -> r
in
assert (Manipulation.Memory.tuple_count rel = 2))
let%test_unit "dml: execute DeleteTuple" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"shop" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty |> Schema.add "name" "string" in
let db = match Manipulation.Memory.create_relation storage db ~name:"users" ~schema with
| Error _ -> assert false | Ok (db, _) -> db
in
let db = match Dml.Executor.Memory.execute storage db
(Dml.Ast.InsertTuple { relation = "users"; attributes = [("name", Drl.Ast.Str "Alice")] }) with
| Error _ -> assert false | Ok db -> db
in
let stmt = Dml.Ast.DeleteTuple { relation = "users"; attributes = [("name", Drl.Ast.Str "Alice")] } in
match Dml.Executor.Memory.execute storage db stmt with
| Error _ -> assert false
| Ok db ->
let rel = match Management.Database.get_relation db "users" with
| None -> assert false | Some r -> r
in
assert (Manipulation.Memory.tuple_count rel = 0))
let%test_unit "dml: execute RetractRelation" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"shop" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty in
let db = match Manipulation.Memory.create_relation storage db ~name:"users" ~schema with
| Error _ -> assert false | Ok (db, _) -> db
in
match Dml.Executor.Memory.execute storage db (Dml.Ast.RetractRelation "users") with
| Error _ -> assert false
| Ok db -> assert (not (Management.Database.has_relation db "users")))
let%test_unit "dml: execute ClearRelation" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"shop" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty |> Schema.add "name" "string" in
let db = match Manipulation.Memory.create_relation storage db ~name:"users" ~schema with
| Error _ -> assert false | Ok (db, _) -> db
in
let db = match Dml.Executor.Memory.execute storage db
(Dml.Ast.InsertTuples { relation = "users";
tuples = [[("name", Drl.Ast.Str "Alice")]; [("name", Drl.Ast.Str "Bob")]] }) with
| Error _ -> assert false | Ok db -> db
in
match Dml.Executor.Memory.execute storage db (Dml.Ast.ClearRelation "users") with
| Error _ -> assert false
| Ok db ->
let rel = match Management.Database.get_relation db "users" with
| None -> assert false | Some r -> r
in
assert (Manipulation.Memory.tuple_count rel = 0))
let%test_unit "dml: execute RegisterDomain" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"shop" with
| Error _ -> assert false | Ok db -> db
in
let stmt = Dml.Ast.RegisterDomain { name = "money"; cardinality = Dml.Ast.AlephZero } in
match Dml.Executor.Memory.execute storage db stmt with
| Error _ -> assert false
| Ok db -> assert (Management.Database.has_domain db "money"))
let%test_unit "dml: insert into nonexistent relation returns error" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"shop" with
| Error _ -> assert false | Ok db -> db
in
let stmt = Dml.Ast.InsertTuple { relation = "ghost"; attributes = [("x", Drl.Ast.Int 1)] } in
match Dml.Executor.Memory.execute storage db stmt with
| Error (Dml.Executor.Memory.RelationNotFound "ghost") -> ()
| _ -> assert false)
(* ============================================================================
DCL Sublanguage Tests
============================================================================ *)
let%test_unit "dcl: round-trip RegisterConstraint MemberOf" =
let src = Dcl.Ast.RegisterConstraint {
constraint_name = "fk_order";
relation_name = "order_items";
body = Dcl.Ast.MemberOf { target = "orders"; binding = [("order_id", Dcl.Ast.Var "order_id")] }
} in
match Dcl.Parser.of_string (Dcl.Parser.to_string src) with
| Error _ -> assert false
| Ok parsed -> assert (parsed = src)
let%test_unit "dcl: round-trip And constraint" =
let src = Dcl.Ast.RegisterConstraint {
constraint_name = "valid_range";
relation_name = "scores";
body = Dcl.Ast.And [
Dcl.Ast.MemberOf { target = "ge_zero";
binding = [("left", Dcl.Ast.Var "score"); ("right", Dcl.Ast.Const (Drl.Ast.Int 0))] };
Dcl.Ast.MemberOf { target = "le_hundred";
binding = [("left", Dcl.Ast.Var "score"); ("right", Dcl.Ast.Const (Drl.Ast.Int 100))] };
]
} in
match Dcl.Parser.of_string (Dcl.Parser.to_string src) with
| Error _ -> assert false
| Ok parsed -> assert (parsed = src)
let%test_unit "dcl: round-trip Not constraint" =
let src = Dcl.Ast.RegisterConstraint {
constraint_name = "not_closed";
relation_name = "open_ticket";
body = Dcl.Ast.Not {
body = Dcl.Ast.MemberOf { target = "closed_ticket";
binding = [("ticket_id", Dcl.Ast.Var "ticket_id")] };
universe = "open_ticket"
}
} in
match Dcl.Parser.of_string (Dcl.Parser.to_string src) with
| Error _ -> assert false
| Ok parsed -> assert (parsed = src)
let%test_unit "dcl: execute RegisterConstraint attaches constraint" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"shop" with
| Error _ -> assert false | Ok db -> db
in
let schema = Schema.empty |> Schema.add "order_id" "natural" in
let db = match Manipulation.Memory.create_relation storage db ~name:"order_items" ~schema with
| Error _ -> assert false | Ok (db, _) -> db
in
let stmt = Dcl.Ast.RegisterConstraint {
constraint_name = "fk_order";
relation_name = "order_items";
body = Dcl.Ast.MemberOf { target = "orders"; binding = [("order_id", Dcl.Ast.Var "order_id")] }
} in
match Dcl.Executor.Memory.execute storage db stmt with
| Error _ -> assert false
| Ok db ->
let rel = match Management.Database.get_relation db "order_items" with
| None -> assert false | Some r -> r
in
assert (rel.Relation.constraints <> None))
let%test_unit "dcl: FK constraint enforced on insert" =
with_storage (fun storage ->
let db = match Manipulation.Memory.create_database storage ~name:"shop" with
| Error _ -> assert false | Ok db -> db
in
let db = match Manipulation.Memory.create_relation storage db ~name:"orders"
~schema:(Schema.empty |> Schema.add "id" "natural") with
| Error _ -> assert false | Ok (db, _) -> db
in
(* Insert a valid order *)
let db = match Dml.Executor.Memory.execute storage db
(Dml.Ast.InsertTuple { relation = "orders"; attributes = [("id", Drl.Ast.Int 1)] }) with
| Error _ -> assert false | Ok db -> db
in
let db = match Manipulation.Memory.create_relation storage db ~name:"order_items"
~schema:(Schema.empty |> Schema.add "order_id" "natural") with
| Error _ -> assert false | Ok (db, _) -> db
in
(* Register FK: order_id in order_items must match id in orders *)
let db = match Dcl.Executor.Memory.execute storage db
(Dcl.Ast.RegisterConstraint {
constraint_name = "fk_order";
relation_name = "order_items";
body = Dcl.Ast.MemberOf { target = "orders"; binding = [("id", Dcl.Ast.Var "order_id")] }
}) with
| Error _ -> assert false | Ok db -> db
in
(* Valid insert: order_id=1 exists in orders *)
let db = match Dml.Executor.Memory.execute storage db
(Dml.Ast.InsertTuple { relation = "order_items"; attributes = [("order_id", Drl.Ast.Int 1)] }) with
| Error _ -> assert false | Ok db -> db
in
let rel = match Management.Database.get_relation db "order_items" with
| None -> assert false | Some r -> r
in
assert (Manipulation.Memory.tuple_count rel = 1);
(* Invalid insert: order_id=99 does not exist in orders *)
match Dml.Executor.Memory.execute storage db
(Dml.Ast.InsertTuple { relation = "order_items"; attributes = [("order_id", Drl.Ast.Int 99)] }) with
| Error (Dml.Executor.Memory.ManipulationError (Manipulation.ConstraintViolation _)) -> ()
| _ -> assert false)
|