Skip to content

Cypher Execution API

grafito.cypher.executor.CypherExecutor

Executes Cypher query AST against a GrafitoDatabase.

Source code in grafito/cypher/executor.py
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
class CypherExecutor:
    """Executes Cypher query AST against a GrafitoDatabase."""

    def __init__(self, db: GrafitoDatabase):
        self.db = db

    def _make_evaluator(self, context: dict[str, Any]) -> ExpressionEvaluator:
        """Build an expression evaluator with pattern comprehension support."""
        return ExpressionEvaluator(context, pattern_matcher=self._pattern_comprehension_matcher)

    def _evaluate_properties(
        self,
        properties: dict[str, Any] | None,
        context: dict[str, Any] | None,
    ) -> dict[str, Any]:
        """Evaluate property map expressions against the current context."""
        if not properties:
            return {}
        evaluator = self._make_evaluator(context or {})
        evaluated: dict[str, Any] = {}
        for key, expr in properties.items():
            if isinstance(expr, Expression):
                evaluated[key] = evaluator.evaluate(expr)
            else:
                evaluated[key] = expr
        return evaluated

    def _pattern_comprehension_matcher(self, expr: PatternComprehension, context: dict[str, Any]) -> list[Any]:
        """Evaluate a pattern comprehension against the current context."""
        return self._evaluate_pattern_comprehension(expr, context)

    def _evaluate_pattern_comprehension(self, expr: PatternComprehension, context: dict[str, Any]) -> list[Any]:
        """Evaluate a pattern comprehension by matching the pattern and projecting results."""
        matches = self._match_pattern(expr.pattern)
        results = []

        for match in matches:
            if not self._pattern_bindings_match(context, match):
                continue

            merged = context.copy()
            merged.update(match)
            evaluator = self._make_evaluator(merged)

            if expr.where_expr is not None:
                try:
                    if not evaluator.evaluate(expr.where_expr):
                        continue
                except CypherExecutionError:
                    continue

            results.append(self._serialize_value(evaluator.evaluate(expr.projection)))

        return results

    def _pattern_bindings_match(self, context: dict[str, Any], match: dict[str, Any]) -> bool:
        """Check if matched variables are compatible with existing context bindings."""
        for name, value in match.items():
            if name not in context:
                continue
            if not self._same_entity(context[name], value):
                return False
        return True

    def _same_entity(self, left: Any, right: Any) -> bool:
        """Compare two bound entities by id when possible."""
        if left is right:
            return True
        left_id = self._entity_id(left)
        right_id = self._entity_id(right)
        if left_id is not None and right_id is not None:
            return left_id == right_id
        return left == right

    def _entity_id(self, value: Any) -> Any:
        """Extract an entity id from nodes/relationships or serialized dicts."""
        if hasattr(value, 'id'):
            return value.id
        if isinstance(value, dict) and 'id' in value:
            return value['id']
        return None

    def execute(self, query: Query) -> list[dict]:
        """Execute a query and return results.

        Args:
            query: Parsed Query AST

        Returns:
            List of result dictionaries

        Raises:
            CypherExecutionError: If execution fails
        """
        if query.union_clauses:
            return self._execute_union(query)

        if isinstance(query.clause, SubqueryClause):
            return self._execute_subquery(query.clause, [])
        if isinstance(query.clause, ProcedureCallClause):
            return self._execute_procedure_call(query.clause, [])

        # Check if multi-clause query (with WITH)
        if query.clauses:
            return self._execute_multi_clause(query.clauses, initial_results=None)

        # Single clause query
        if isinstance(query.clause, CreateClause):
            return self._execute_create(query.clause)
        elif isinstance(query.clause, MergeClause):
            return self._execute_merge(query.clause)
        elif isinstance(query.clause, MatchClause):
            return self._execute_match(query.clause)
        elif isinstance(query.clause, UnwindClause):
            return self._execute_unwind(query.clause, [{}])
        elif isinstance(query.clause, WithClause):
            return self._execute_with(query.clause, [{}])
        elif isinstance(query.clause, CreateIndexClause):
            return self._execute_create_index(query.clause)
        elif isinstance(query.clause, DropIndexClause):
            return self._execute_drop_index(query.clause)
        elif isinstance(query.clause, ShowIndexesClause):
            return self._execute_show_indexes(query.clause)
        elif isinstance(query.clause, CreateConstraintClause):
            return self._execute_create_constraint(query.clause)
        elif isinstance(query.clause, DropConstraintClause):
            return self._execute_drop_constraint(query.clause)
        elif isinstance(query.clause, ShowConstraintsClause):
            return self._execute_show_constraints(query.clause)
        elif isinstance(query.clause, ForeachClause):
            return self._execute_foreach(query.clause, [{}])
        else:
            raise CypherExecutionError(f"Unknown clause type: {type(query.clause)}")

    def _execute_union(self, query: Query) -> list[dict]:
        """Execute UNION/UNION ALL queries."""
        results = self.execute(Query(clause=query.clause, clauses=query.clauses))

        for union_clause in query.union_clauses:
            union_results = self.execute(union_clause.query)
            if union_clause.all:
                results.extend(union_results)
            else:
                results = self._union_distinct(results, union_results)

        return results

    def _union_distinct(self, left: list[dict], right: list[dict]) -> list[dict]:
        """Return union of two result sets with distinct rows."""
        seen = {self._freeze_result(row) for row in left}
        combined = left[:]
        for row in right:
            frozen = self._freeze_result(row)
            if frozen in seen:
                continue
            seen.add(frozen)
            combined.append(row)
        return combined

    def _freeze_result(self, value: Any) -> Any:
        """Convert results to hashable structures for UNION distinct."""
        if isinstance(value, dict):
            return tuple(sorted((k, self._freeze_result(v)) for k, v in value.items()))
        if isinstance(value, list):
            return tuple(self._freeze_result(v) for v in value)
        return value

    def _execute_multi_clause(self, clauses: list, initial_results: list[dict] | None = None) -> list[dict]:
        """Execute multi-clause query with WITH pipeline.

        Args:
            clauses: List of clause AST nodes (MATCH, WITH, etc.)

        Returns:
            Final result set

        The WITH clause acts as a pipeline:
        - MATCH (n) returns results
        - WITH filters/transforms those results
        - Next MATCH uses WITH results as context
        """
        results = initial_results if initial_results is not None else []

        for i, clause in enumerate(clauses):
            if not results and isinstance(
                clause,
                (WithClause, UnwindClause, LoadCsvClause, ProcedureCallClause, ForeachClause, SubqueryClause),
            ):
                results = [{}]
            if isinstance(clause, MatchClause):
                # Execute MATCH with current context
                new_results = self._execute_match(clause, context=results)
                results = new_results
            elif isinstance(clause, CreateClause):
                new_results = self._execute_create(clause, context=results if results else None)
                results = new_results
            elif isinstance(clause, MergeClause):
                # Execute MERGE
                new_results = self._execute_merge(clause, context=results if results else None)
                results = new_results
            elif isinstance(clause, WithClause):
                # Apply WITH transformation to current results
                results = self._execute_with(clause, results)
            elif isinstance(clause, UnwindClause):
                results = self._execute_unwind(clause, results)
            elif isinstance(clause, LoadCsvClause):
                results = self._execute_load_csv(clause, results)
            elif isinstance(clause, ForeachClause):
                results = self._execute_foreach(clause, results)
            elif isinstance(clause, SetClause):
                self._execute_set(results, clause)
            elif isinstance(clause, ReturnClause):
                results = self._apply_return(results, clause)
            elif isinstance(clause, SubqueryClause):
                results = self._execute_subquery(clause, results)
            elif isinstance(clause, ProcedureCallClause):
                results = self._execute_procedure_call(clause, results)
            else:
                raise CypherExecutionError(f"Unknown clause type in multi-clause query: {type(clause)}")

        return results

    def _execute_subquery(self, clause: SubqueryClause, input_results: list[dict]) -> list[dict]:
        """Execute CALL { ... } subquery with scoped variables."""
        if not input_results:
            input_results = [{}]

        output = []
        for row in input_results:
            sub_results = self._execute_query_with_context(clause.query, [row])
            for sub_row in sub_results:
                merged = row.copy()
                merged.update(sub_row)
                output.append(merged)

        return output

    def _execute_procedure_call(
        self,
        clause: ProcedureCallClause,
        input_results: list[dict],
    ) -> list[dict]:
        """Execute CALL procedure with optional YIELD projection."""
        if not input_results:
            input_results = [{}]

        output = []
        for row in input_results:
            evaluator = self._make_evaluator(row)
            args = [evaluator.evaluate(arg) for arg in clause.arguments]
            proc_results = self._invoke_procedure(clause.name, args)
            if not proc_results:
                continue
            for proc_row in proc_results:
                if clause.yield_items:
                    projected = {key: proc_row.get(key) for key in clause.yield_items}
                else:
                    projected = proc_row
                merged = row.copy()
                merged.update(projected)
                output.append(merged)
        return output

    def _invoke_procedure(self, name: str, args: list[Any]) -> list[dict]:
        """Dispatch supported procedures by name."""
        lower_name = name.lower()
        if lower_name == "db.vector.search":
            if len(args) < 2:
                raise CypherExecutionError("db.vector.search expects at least index and vector")
            index = args[0]
            vector = args[1]
            k = args[2] if len(args) > 2 else None
            options = args[3] if len(args) > 3 else None
            if not isinstance(index, str):
                raise CypherExecutionError("db.vector.search index must be a string")
            if not isinstance(vector, list):
                raise CypherExecutionError("db.vector.search vector must be a list")
            if options is not None and not isinstance(options, dict):
                raise CypherExecutionError("db.vector.search options must be a map")
            options = options or {}
            candidate_multiplier = options.get("candidate_multiplier")
            reranker_name = options.get("reranker")
            if candidate_multiplier is not None and not isinstance(candidate_multiplier, int):
                raise CypherExecutionError("db.vector.search candidate_multiplier must be an integer")
            if reranker_name is not None and not isinstance(reranker_name, str):
                raise CypherExecutionError("db.vector.search reranker must be a string")
            properties_filter = self._coerce_vector_properties_filter(options.get("properties"))
            rerank_flag = bool(options.get("rerank", False) or reranker_name is not None)
            results = self.db.semantic_search(
                vector,
                k=k,
                index=index,
                filter_labels=options.get("labels"),
                filter_props=properties_filter,
                rerank=rerank_flag,
                reranker=reranker_name,
                candidate_multiplier=candidate_multiplier,
            )
            return [{"node": row["node"], "score": row["score"]} for row in results]

        if lower_name == "db.uri_index.create":
            if len(args) < 1:
                raise CypherExecutionError("db.uri_index.create expects entity ('node' or 'relationship')")
            entity = args[0]
            unique = args[1] if len(args) > 1 else True
            name = args[2] if len(args) > 2 else None
            if not isinstance(entity, str):
                raise CypherExecutionError("db.uri_index.create entity must be a string")
            if unique is not None and not isinstance(unique, bool):
                raise CypherExecutionError("db.uri_index.create unique must be a boolean")
            if name is not None and not isinstance(name, str):
                raise CypherExecutionError("db.uri_index.create name must be a string")
            entity_lower = entity.lower()
            if entity_lower in {"node", "nodes"}:
                index_name = self.db.create_node_uri_index(unique=bool(unique), name=name)
            elif entity_lower in {"relationship", "relationships"}:
                index_name = self.db.create_relationship_uri_index(unique=bool(unique), name=name)
            else:
                raise CypherExecutionError("db.uri_index.create entity must be 'node' or 'relationship'")
            return [{"name": index_name}]

        if lower_name == "apoc.load.jsonarray":
            if len(args) != 1:
                raise CypherExecutionError("apoc.load.jsonArray expects 1 argument")
            source = args[0]
            if not isinstance(source, str):
                raise CypherExecutionError("apoc.load.jsonArray expects a string path or URL")
            data = self._load_json_from_source(source)
            if not isinstance(data, list):
                raise CypherExecutionError("apoc.load.jsonArray expects a JSON array")
            return [{"value": item} for item in data]

        if lower_name == "apoc.load.json":
            if len(args) != 1:
                raise CypherExecutionError("apoc.load.json expects 1 argument")
            source = args[0]
            if not isinstance(source, str):
                raise CypherExecutionError("apoc.load.json expects a string path or URL")
            data = self._load_json_from_source(source)
            if data is None:
                return []
            if isinstance(data, list):
                return [{"value": item} for item in data]
            return [{"value": data}]

        if lower_name == "apoc.load.jsonparams":
            if len(args) not in (3, 4):
                raise CypherExecutionError("apoc.load.jsonParams expects 3 or 4 arguments")
            source = args[0]
            params = args[1]
            headers = args[2]
            options = args[3] if len(args) == 4 else None
            if not isinstance(source, str):
                raise CypherExecutionError("apoc.load.jsonParams expects a string path or URL")
            if not isinstance(params, dict):
                raise CypherExecutionError("apoc.load.jsonParams expects a params map")
            if not isinstance(headers, dict):
                raise CypherExecutionError("apoc.load.jsonParams expects a headers map")
            if options is not None and not isinstance(options, dict):
                raise CypherExecutionError("apoc.load.jsonParams options must be a map")
            url = self._apply_query_params(source, params)
            data = self._load_json_from_source(url, headers=headers, options=options)
            if data is None:
                return []
            if isinstance(data, list):
                return [{"value": item} for item in data]
            return [{"value": data}]

        if lower_name == "apoc.import.json":
            if len(args) not in (1, 2):
                raise CypherExecutionError("apoc.import.json expects 1 or 2 arguments")
            source = args[0]
            options = args[1] if len(args) == 2 else None
            if not isinstance(source, (str, bytes, bytearray)):
                raise CypherExecutionError("apoc.import.json expects a string path/URL or bytes")
            if options is not None and not isinstance(options, dict):
                raise CypherExecutionError("apoc.import.json options must be a map")

            payload = self._load_import_text_with_options(source, options)
            if payload is None:
                return []
            entries = self._parse_import_payload(payload)

            id_field = (options or {}).get("idField", "id")
            labels_field = (options or {}).get("labelsField", "labels")
            props_field = (options or {}).get("propertiesField", "properties")
            rel_type_field = (options or {}).get("relTypeField", "label")
            start_field = (options or {}).get("startField", "start")
            end_field = (options or {}).get("endField", "end")
            type_field = (options or {}).get("typeField", "type")

            node_lookup: dict[Any, int] = {}
            created_nodes = 0
            created_rels = 0

            for entry in entries:
                if not isinstance(entry, dict):
                    raise CypherExecutionError("apoc.import.json entries must be objects")
                entry_type = entry.get(type_field)
                is_relationship = False
                if isinstance(entry_type, str) and entry_type.lower() in ("relationship", "rel", "edge"):
                    is_relationship = True
                if entry_type is None and (start_field in entry or end_field in entry):
                    is_relationship = True

                if not is_relationship:
                    labels = self._normalize_import_labels(entry.get(labels_field))
                    props = self._normalize_import_properties(entry.get(props_field))
                    node = self.db.create_node(labels=labels, properties=props)
                    created_nodes += 1
                    node_id = entry.get(id_field)
                    if node_id is not None:
                        node_lookup[node_id] = node.id
                    continue

                start_ref = self._resolve_import_ref(entry.get(start_field))
                end_ref = self._resolve_import_ref(entry.get(end_field))
                if start_ref is None or end_ref is None:
                    raise CypherExecutionError("apoc.import.json relationships need start/end")
                if start_ref not in node_lookup or end_ref not in node_lookup:
                    raise CypherExecutionError("apoc.import.json relationship references unknown nodes")
                rel_type = entry.get(rel_type_field) or entry.get("type") or "RELATED_TO"
                rel_props = self._normalize_import_properties(entry.get(props_field))
                self.db.create_relationship(
                    source_id=node_lookup[start_ref],
                    target_id=node_lookup[end_ref],
                    rel_type=str(rel_type),
                    properties=rel_props,
                )
                created_rels += 1

            return [{"nodes": created_nodes, "relationships": created_rels}]

        if lower_name == "apoc.load.html":
            if len(args) != 2:
                raise CypherExecutionError("apoc.load.html expects 2 arguments")
            source = args[0]
            selectors = args[1]
            if not isinstance(source, str):
                raise CypherExecutionError("apoc.load.html expects a string path or URL")
            if not isinstance(selectors, dict):
                raise CypherExecutionError("apoc.load.html expects a selector map")
            html = self._load_html_from_source(source)
            root = self._parse_html(html)
            value: dict[str, list[dict[str, Any]]] = {}
            for key, selector in selectors.items():
                if not isinstance(selector, str):
                    raise CypherExecutionError("apoc.load.html selectors must be strings")
                nodes = self._select_html_nodes(root, selector)
                value[key] = [{"text": node.text_content().strip()} for node in nodes]
            return [{"value": value}]

        if lower_name == "apoc.load.xml":
            if len(args) not in (2, 3):
                raise CypherExecutionError("apoc.load.xml expects 2 or 3 arguments")
            source = args[0]
            xpath = args[1]
            options = args[2] if len(args) == 3 else None
            if not isinstance(source, str):
                raise CypherExecutionError("apoc.load.xml expects a string path or URL")
            if not isinstance(xpath, str):
                raise CypherExecutionError("apoc.load.xml expects an XPath string")
            if options is not None and not isinstance(options, dict):
                raise CypherExecutionError("apoc.load.xml options must be a map")
            xml_payload = self._load_xml_from_source(source, options=options)
            if xml_payload is None:
                return []
            try:
                import xml.etree.ElementTree as ET
                root = ET.fromstring(xml_payload)
            except Exception as exc:
                raise CypherExecutionError(f"Failed to parse XML from {source}: {exc}") from exc
            if xpath.startswith("/"):
                xpath = f".{xpath}"
            matches = root.findall(xpath)
            return [{"value": self._element_to_dict(match)} for match in matches]

        if lower_name == "apoc.load.xmlparams":
            if len(args) not in (4, 5):
                raise CypherExecutionError("apoc.load.xmlParams expects 4 or 5 arguments")
            source = args[0]
            xpath = args[1]
            params = args[2]
            headers = args[3]
            options = args[4] if len(args) == 5 else None
            if not isinstance(source, str):
                raise CypherExecutionError("apoc.load.xmlParams expects a string path or URL")
            if not isinstance(xpath, str):
                raise CypherExecutionError("apoc.load.xmlParams expects an XPath string")
            if not isinstance(params, dict):
                raise CypherExecutionError("apoc.load.xmlParams expects a params map")
            if not isinstance(headers, dict):
                raise CypherExecutionError("apoc.load.xmlParams expects a headers map")
            if options is not None and not isinstance(options, dict):
                raise CypherExecutionError("apoc.load.xmlParams options must be a map")
            url = self._apply_query_params(source, params)
            xml_payload = self._load_xml_from_source(url, options=options)
            if xml_payload is None:
                return []
            try:
                import xml.etree.ElementTree as ET
                root = ET.fromstring(xml_payload)
            except Exception as exc:
                raise CypherExecutionError(f"Failed to parse XML from {source}: {exc}") from exc
            if xpath.startswith("/"):
                xpath = f".{xpath}"
            matches = root.findall(xpath)
            return [{"value": self._element_to_dict(match)} for match in matches]

        raise CypherExecutionError(f"Unknown procedure: {name}")

    def _load_json_from_source(
        self,
        source: str,
        headers: dict[str, str] | None = None,
        options: dict[str, Any] | None = None,
    ) -> Any:
        """Load JSON data from a URL or local file path."""
        archive_member = None
        if "!" in source:
            source, archive_member = source.split("!", 1)

        parsed = urllib.parse.urlparse(source)
        options = options or {}
        method = options.get("method") or "GET"
        payload = options.get("payload")
        timeout = options.get("timeout")
        retry = options.get("retry", 0)
        fail_on_error = options.get("failOnError", True)
        options_headers = options.get("headers")
        auth = options.get("auth")
        if timeout is not None and not isinstance(timeout, (int, float)):
            raise CypherExecutionError("apoc.load.jsonParams timeout must be a number")
        if retry is not None and not isinstance(retry, int):
            raise CypherExecutionError("apoc.load.jsonParams retry must be an integer")
        if options_headers is not None and not isinstance(options_headers, dict):
            raise CypherExecutionError("apoc.load.jsonParams headers must be a map")
        if not isinstance(fail_on_error, bool):
            raise CypherExecutionError("apoc.load.jsonParams failOnError must be a boolean")

        if parsed.scheme in ("http", "https"):
            cache_dir = os.getenv("GRAFITO_APOC_CACHE_DIR")
            cache_path = None
            can_cache = (
                method.upper() == "GET"
                and payload is None
                and not headers
                and not options_headers
                and not auth
                and not options.get("params")
            )
            if cache_dir and can_cache and archive_member is None:
                os.makedirs(cache_dir, exist_ok=True)
                url_hash = hashlib.sha256(source.encode("utf-8")).hexdigest()
                cache_path = os.path.join(cache_dir, f"{url_hash}.json")
            if cache_path and os.path.exists(cache_path):
                try:
                    with open(cache_path, encoding="utf-8") as handle:
                        payload = handle.read()
                except Exception as exc:
                    raise CypherExecutionError(
                        f"Failed to read cached JSON {cache_path}: {exc}"
                    ) from exc
            else:
                if archive_member is not None:
                    payload_bytes = self._load_bytes_from_source(
                        source,
                        "JSON",
                        headers=headers,
                        options=options,
                    )
                    if payload_bytes is None:
                        return None
                    payload = self._extract_json_from_archive(
                        payload_bytes,
                        source,
                        archive_member,
                    )
                else:
                    request_headers = {"User-Agent": "GrafitoCypher/0.1"}
                    if headers:
                        request_headers.update(headers)
                    if options_headers:
                        request_headers.update(options_headers)
                    if auth:
                        if isinstance(auth, dict):
                            user = auth.get("user") or auth.get("username")
                            password = auth.get("password") or auth.get("pass")
                            if user is None or password is None:
                                raise CypherExecutionError("apoc.load.jsonParams auth map needs user/password")
                            token = f"{user}:{password}".encode("utf-8")
                        elif isinstance(auth, str):
                            token = auth.encode("utf-8")
                        else:
                            raise CypherExecutionError("apoc.load.jsonParams auth must be a string or map")
                        request_headers["Authorization"] = f"Basic {base64.b64encode(token).decode('ascii')}"

                    data_bytes = None
                    if payload is not None:
                        if isinstance(payload, (dict, list)):
                            data_bytes = orjson.dumps(payload)
                            request_headers.setdefault("Content-Type", "application/json")
                        elif isinstance(payload, str):
                            data_bytes = payload.encode("utf-8")
                        elif isinstance(payload, bytes):
                            data_bytes = payload
                        else:
                            raise CypherExecutionError("apoc.load.jsonParams payload must be string, bytes, list, or map")

                    attempts = retry + 1 if retry is not None else 1
                    last_exc: Exception | None = None
                    for _ in range(attempts):
                        try:
                            request = urllib.request.Request(
                                source,
                                headers=request_headers,
                                data=data_bytes,
                                method=method.upper(),
                            )
                            with urllib.request.urlopen(request, timeout=timeout) as handle:
                                payload = handle.read().decode("utf-8")
                            last_exc = None
                            break
                        except Exception as exc:
                            last_exc = exc
                    if last_exc is not None:
                        if fail_on_error:
                            raise CypherExecutionError(
                                f"Failed to load JSON from {source}: {last_exc}"
                            ) from last_exc
                        return None

                if cache_path:
                    try:
                        with open(cache_path, "w", encoding="utf-8") as handle:
                            handle.write(payload)
                    except Exception:
                        pass
        else:
            path = source
            if parsed.scheme == "file":
                path = urllib.request.url2pathname(parsed.path)
            if not os.path.exists(path):
                raise CypherExecutionError(f"JSON file not found: {path}")
            try:
                if archive_member is not None:
                    with open(path, "rb") as handle:
                        payload_bytes = handle.read()
                    payload = self._extract_json_from_archive(
                        payload_bytes,
                        path,
                        archive_member,
                    )
                else:
                    with open(path, encoding="utf-8") as handle:
                        payload = handle.read()
            except Exception as exc:
                raise CypherExecutionError(f"Failed to read JSON file {path}: {exc}") from exc
        if payload is None:
            return None
        try:
            data = orjson.loads(payload)
        except orjson.JSONDecodeError as exc:
            cleaned = payload.lstrip("\ufeff")
            cleaned = re.sub(r",\s*(\]|\})", r"\1", cleaned)
            try:
                data = orjson.loads(cleaned)
            except orjson.JSONDecodeError as exc2:
                raise CypherExecutionError(
                    f"Invalid JSON payload from {source}: {exc}"
                ) from exc2
        return data

    def _load_html_from_source(self, source: str) -> str:
        """Load HTML content from a URL or local file path."""
        parsed = urllib.parse.urlparse(source)
        if parsed.scheme in ("http", "https"):
            try:
                request = urllib.request.Request(
                    source,
                    headers={"User-Agent": "GrafitoCypher/0.1"},
                )
                with urllib.request.urlopen(request) as handle:
                    return handle.read().decode("utf-8")
            except Exception as exc:
                raise CypherExecutionError(f"Failed to load HTML from {source}: {exc}") from exc
        path = source
        if parsed.scheme == "file":
            path = urllib.request.url2pathname(parsed.path)
        if not os.path.exists(path):
            raise CypherExecutionError(f"HTML file not found: {path}")
        try:
            with open(path, encoding="utf-8") as handle:
                return handle.read()
        except Exception as exc:
            raise CypherExecutionError(f"Failed to read HTML file {path}: {exc}") from exc

    def _load_bytes_from_source(
        self,
        source: str,
        kind: str,
        headers: dict[str, str] | None = None,
        options: dict[str, Any] | None = None,
    ) -> bytes | None:
        """Load raw bytes from a URL or local file path."""
        parsed = urllib.parse.urlparse(source)
        options = options or {}
        method = options.get("method") or "GET"
        payload = options.get("payload")
        timeout = options.get("timeout")
        retry = options.get("retry", 0)
        fail_on_error = options.get("failOnError", True)
        options_headers = options.get("headers")
        auth = options.get("auth")
        if timeout is not None and not isinstance(timeout, (int, float)):
            raise CypherExecutionError(f"apoc.load.{kind.lower()}Params timeout must be a number")
        if retry is not None and not isinstance(retry, int):
            raise CypherExecutionError(f"apoc.load.{kind.lower()}Params retry must be an integer")
        if options_headers is not None and not isinstance(options_headers, dict):
            raise CypherExecutionError(f"apoc.load.{kind.lower()}Params headers must be a map")
        if not isinstance(fail_on_error, bool):
            raise CypherExecutionError(f"apoc.load.{kind.lower()}Params failOnError must be a boolean")

        if parsed.scheme in ("http", "https"):
            request_headers = {"User-Agent": "GrafitoCypher/0.1"}
            if headers:
                request_headers.update(headers)
            if options_headers:
                request_headers.update(options_headers)
            if auth:
                if isinstance(auth, dict):
                    user = auth.get("user") or auth.get("username")
                    password = auth.get("password") or auth.get("pass")
                    if user is None or password is None:
                        raise CypherExecutionError(
                            f"apoc.load.{kind.lower()}Params auth map needs user/password"
                        )
                    token = f"{user}:{password}".encode("utf-8")
                elif isinstance(auth, str):
                    token = auth.encode("utf-8")
                else:
                    raise CypherExecutionError(
                        f"apoc.load.{kind.lower()}Params auth must be a string or map"
                    )
                request_headers["Authorization"] = f"Basic {base64.b64encode(token).decode('ascii')}"

            data_bytes = None
            if payload is not None:
                if isinstance(payload, (dict, list)):
                    data_bytes = orjson.dumps(payload)
                    request_headers.setdefault("Content-Type", "application/json")
                elif isinstance(payload, str):
                    data_bytes = payload.encode("utf-8")
                elif isinstance(payload, bytes):
                    data_bytes = payload
                else:
                    raise CypherExecutionError(
                        f"apoc.load.{kind.lower()}Params payload must be string, bytes, list, or map"
                    )

            attempts = retry + 1 if retry is not None else 1
            last_exc: Exception | None = None
            for _ in range(attempts):
                try:
                    request = urllib.request.Request(
                        source,
                        headers=request_headers,
                        data=data_bytes,
                        method=method.upper(),
                    )
                    with urllib.request.urlopen(request, timeout=timeout) as handle:
                        return handle.read()
                except Exception as exc:
                    last_exc = exc
            if last_exc is not None:
                if fail_on_error:
                    raise CypherExecutionError(
                        f"Failed to load {kind} from {source}: {last_exc}"
                    ) from last_exc
                return None
            return None
        path = source
        if parsed.scheme == "file":
            path = urllib.request.url2pathname(parsed.path)
        if not os.path.exists(path):
            raise CypherExecutionError(f"{kind} file not found: {path}")
        try:
            with open(path, "rb") as handle:
                return handle.read()
        except Exception as exc:
            raise CypherExecutionError(f"Failed to read {kind} file {path}: {exc}") from exc

    def _load_xml_from_source(self, source: str, options: dict[str, Any] | None = None) -> str | None:
        """Load XML content from a URL or local file path with optional compression."""
        payload = self._load_bytes_from_source(source, "XML", options=options)
        if payload is None:
            return None
        compression = None
        archive_path = None
        if options:
            compression = options.get("compression")
            archive_path = options.get("path") or options.get("fileName")
        if compression is None:
            lower_source = source.lower()
            if lower_source.endswith(".gz"):
                compression = "gzip"
            elif lower_source.endswith(".bz2"):
                compression = "bz2"
            elif lower_source.endswith(".xz") or lower_source.endswith(".lzma"):
                compression = "xz"
            elif lower_source.endswith(".zip"):
                compression = "zip"

        if compression:
            compression = str(compression).lower()
            if compression in ("gzip", "gz"):
                import gzip

                payload = gzip.decompress(payload)
            elif compression in ("bz2", "bzip2"):
                import bz2

                payload = bz2.decompress(payload)
            elif compression in ("xz", "lzma"):
                import lzma

                payload = lzma.decompress(payload)
            elif compression == "zip":
                import zipfile

                with zipfile.ZipFile(io.BytesIO(payload)) as archive:
                    members = archive.namelist()
                    if archive_path:
                        if archive_path not in members:
                            raise CypherExecutionError(
                                f"XML entry not found in zip archive: {archive_path}"
                            )
                        target = archive_path
                    else:
                        xml_members = [name for name in members if name.lower().endswith(".xml")]
                        target = xml_members[0] if xml_members else members[0]
                    payload = archive.read(target)
            else:
                raise CypherExecutionError(f"Unsupported XML compression: {compression}")

        try:
            return payload.decode("utf-8")
        except UnicodeDecodeError as exc:
            raise CypherExecutionError(f"Failed to decode XML from {source}: {exc}") from exc

    def _element_to_dict(self, element: Any) -> dict[str, Any]:
        """Convert an XML element to a nested dict structure."""
        result: dict[str, Any] = {"_tag": element.tag}
        if element.attrib:
            result["_attributes"] = dict(element.attrib)
        text = (element.text or "").strip()
        if text:
            result["_text"] = text
        for child in list(element):
            child_value = self._element_to_dict(child)
            key = child.tag
            if key in result:
                existing = result[key]
                if isinstance(existing, list):
                    existing.append(child_value)
                else:
                    result[key] = [existing, child_value]
            else:
                result[key] = child_value
        return result

    def _parse_html(self, html: str) -> _HtmlNode:
        """Parse HTML into a simple node tree."""
        parser = _HtmlTreeBuilder()
        parser.feed(html)
        parser.close()
        return parser.root

    def _parse_html_selector_segment(self, segment: str) -> tuple[str | None, list[str], int | None]:
        """Parse a minimal selector segment: tag(.class)*(:eq(n))?"""
        eq = None
        base = segment
        if ":eq(" in segment:
            base, eq_part = segment.split(":eq(", 1)
            if not eq_part.endswith(")"):
                raise CypherExecutionError(f"Unsupported HTML selector segment: {segment}")
            try:
                eq = int(eq_part[:-1])
            except ValueError as exc:
                raise CypherExecutionError(f"Unsupported HTML selector segment: {segment}") from exc

        base = base.strip()
        if not base:
            raise CypherExecutionError(f"Unsupported HTML selector segment: {segment}")

        parts = base.split(".")
        tag = parts[0] or None
        classes = [part for part in parts[1:] if part]

        name_pattern = re.compile(r"^[a-zA-Z0-9_-]+$")
        if tag and not name_pattern.match(tag):
            raise CypherExecutionError(f"Unsupported HTML selector segment: {segment}")
        for cls in classes:
            if not name_pattern.match(cls):
                raise CypherExecutionError(f"Unsupported HTML selector segment: {segment}")

        return tag.lower() if tag else None, classes, eq

    def _select_html_nodes(self, root: _HtmlNode, selector: str) -> list[_HtmlNode]:
        """Select nodes using a minimal descendant-selector engine."""
        segments = [segment for segment in selector.split() if segment]
        if not segments:
            return []

        current = [root]
        for segment in segments:
            tag, classes, eq = self._parse_html_selector_segment(segment)
            matches: list[_HtmlNode] = []
            for base in current:
                stack = list(reversed(base.children))
                while stack:
                    node = stack.pop()
                    stack.extend(reversed(node.children))
                    if not self._html_node_matches(node, tag, classes, eq):
                        continue
                    matches.append(node)
            current = matches
        return current

    def _html_node_matches(
        self,
        node: _HtmlNode,
        tag: str | None,
        classes: list[str],
        eq: int | None,
    ) -> bool:
        """Match a node against a selector segment."""
        if tag and node.tag != tag:
            return False
        if classes:
            node_classes = node.classes()
            if any(cls not in node_classes for cls in classes):
                return False
        if eq is not None:
            if node.parent is None:
                return False
            siblings = [child for child in node.parent.children if child.tag == node.tag]
            try:
                index = siblings.index(node)
            except ValueError:
                return False
            if index != eq:
                return False
        return True

    def _coerce_vector_properties_filter(self, props: Any) -> Any:
        """Coerce Cypher map filters into PropertyFilter/PropertyFilterGroup."""
        if props is None:
            return None
        if isinstance(props, PropertyFilterGroup):
            return props
        if not isinstance(props, dict):
            raise CypherExecutionError("db.vector.search properties must be a map")

        logical_key = None
        if "$or" in props or "or" in props:
            logical_key = "$or" if "$or" in props else "or"
            operator = "OR"
        elif "$and" in props or "and" in props:
            logical_key = "$and" if "$and" in props else "and"
            operator = "AND"

        if logical_key is not None:
            if len(props) != 1:
                raise CypherExecutionError(
                    "Logical properties filter must only contain the operator key"
                )
            filters = props[logical_key]
            if not isinstance(filters, list):
                raise CypherExecutionError("Logical properties filter must be a list")
            dict_filters = [self._coerce_properties_map(item) for item in filters]
            return PropertyFilterGroup(operator, *dict_filters)

        return self._coerce_properties_map(props)

    def _apply_query_params(self, source: str, params: dict[str, Any]) -> str:
        """Apply query parameters to a URL."""
        parsed = urllib.parse.urlparse(source)
        if parsed.scheme not in ("http", "https"):
            return source
        query_items = urllib.parse.parse_qsl(parsed.query, keep_blank_values=True)
        for key, value in params.items():
            if isinstance(value, (list, tuple)):
                for item in value:
                    query_items.append((key, item))
            else:
                query_items.append((key, value))
        query = urllib.parse.urlencode(query_items, doseq=True)
        return urllib.parse.urlunparse(parsed._replace(query=query))

    def _extract_json_from_archive(self, payload: bytes, source: str, member: str) -> str:
        """Extract a JSON payload from a tar archive."""
        import tarfile

        lower_source = source.lower()
        if lower_source.endswith(".tgz") or lower_source.endswith(".tar.gz"):
            mode = "r:gz"
        elif lower_source.endswith(".tar.bz2") or lower_source.endswith(".tbz2"):
            mode = "r:bz2"
        elif lower_source.endswith(".tar.xz") or lower_source.endswith(".txz"):
            mode = "r:xz"
        elif lower_source.endswith(".tar"):
            mode = "r:"
        else:
            raise CypherExecutionError(
                f"Unsupported JSON archive type for {source}; expected .tar, .tgz, .tar.gz, .tar.bz2, or .tar.xz"
            )

        normalized_member = member.lstrip("./")
        with tarfile.open(fileobj=io.BytesIO(payload), mode=mode) as archive:
            for item in archive.getmembers():
                if item.isdir():
                    continue
                name = item.name.lstrip("./")
                if name == normalized_member:
                    handle = archive.extractfile(item)
                    if handle is None:
                        break
                    data = handle.read()
                    try:
                        return data.decode("utf-8")
                    except UnicodeDecodeError as exc:
                        raise CypherExecutionError(
                            f"Failed to decode JSON entry {member} from {source}: {exc}"
                        ) from exc
        raise CypherExecutionError(f"JSON entry not found in archive {source}: {member}")

    def _load_import_text(self, source: str) -> str | None:
        """Load raw text for JSON/JSONL import, supporting tar archives."""
        return self._load_import_text_with_options(source, None)

    def _load_import_text_with_options(self, source: Any, options: dict[str, Any] | None) -> str | None:
        """Load import payload from string/bytes with optional decompression."""
        if isinstance(source, (bytes, bytearray)):
            payload_bytes = bytes(source)
            return self._decode_import_payload(payload_bytes, "<memory>", options)

        if not isinstance(source, str):
            raise CypherExecutionError("apoc.import.json expects a string path/URL or bytes")

        archive_member = None
        if "!" in source:
            source, archive_member = source.split("!", 1)

        payload_bytes = self._load_bytes_from_source(source, "JSON")
        if payload_bytes is None:
            return None
        if archive_member is not None:
            return self._extract_json_from_archive(payload_bytes, source, archive_member)
        return self._decode_import_payload(payload_bytes, source, options)

    def _decode_import_payload(
        self,
        payload: bytes,
        source: str,
        options: dict[str, Any] | None,
    ) -> str:
        """Decode import payload, applying optional compression."""
        compression = None
        if options:
            compression = options.get("compression")
        if compression:
            payload = self._decompress_payload(payload, compression, options or {}, source)
        try:
            return payload.decode("utf-8")
        except UnicodeDecodeError as exc:
            raise CypherExecutionError(f"Failed to decode JSON from {source}: {exc}") from exc

    def _decompress_payload(
        self,
        payload: bytes,
        compression: str,
        options: dict[str, Any],
        source: str,
    ) -> bytes:
        """Decompress raw payload bytes based on compression option."""
        compression = str(compression).upper()
        if compression == "DEFLATE":
            import zlib

            return zlib.decompress(payload)
        if compression in ("GZIP", "GZ"):
            import gzip

            return gzip.decompress(payload)
        if compression in ("BZ2", "BZIP2"):
            import bz2

            return bz2.decompress(payload)
        if compression in ("XZ", "LZMA"):
            import lzma

            return lzma.decompress(payload)
        if compression == "ZIP":
            import zipfile

            path = options.get("path")
            with zipfile.ZipFile(io.BytesIO(payload)) as archive:
                members = archive.namelist()
                target = path or (members[0] if members else None)
                if target is None or target not in members:
                    raise CypherExecutionError(
                        f"JSON entry not found in zip archive {source}: {path}"
                    )
                return archive.read(target)
        raise CypherExecutionError(f"Unsupported compression type: {compression}")

    def _parse_import_payload(self, payload: str) -> list[dict[str, Any]]:
        """Parse JSON or JSONL payload into a list of entries."""
        try:
            data = orjson.loads(payload)
        except orjson.JSONDecodeError:
            entries: list[dict[str, Any]] = []
            for line in payload.splitlines():
                line = line.strip()
                if not line:
                    continue
                entries.append(orjson.loads(line))
            return entries

        if isinstance(data, list):
            return data
        if isinstance(data, dict):
            nodes = data.get("nodes") or []
            rels = data.get("relationships") or data.get("rels") or []
            if nodes or rels:
                return list(nodes) + list(rels)
            return [data]
        raise CypherExecutionError("apoc.import.json expects JSON object, array, or JSONL")

    def _normalize_import_labels(self, value: Any) -> list[str]:
        if value is None:
            return []
        if isinstance(value, list):
            return [str(item) for item in value]
        if isinstance(value, str):
            return [value]
        raise CypherExecutionError("apoc.import.json labels must be a string or list")

    def _normalize_import_properties(self, value: Any) -> dict[str, Any]:
        if value is None:
            return {}
        if isinstance(value, dict):
            return value
        raise CypherExecutionError("apoc.import.json properties must be a map")

    def _resolve_import_ref(self, value: Any) -> Any:
        if isinstance(value, dict):
            return value.get("id") or value.get("identity")
        return value

    def _coerce_properties_map(self, props: Any) -> dict:
        if not isinstance(props, dict):
            raise CypherExecutionError("Properties filter entries must be maps")
        coerced = {}
        for key, value in props.items():
            if isinstance(value, dict):
                coerced[key] = self._coerce_property_operator(value)
            else:
                coerced[key] = value
        return coerced

    def _coerce_property_operator(self, spec: dict) -> PropertyFilter:
        operator_map = {
            "gt": PropertyFilter.gt,
            "$gt": PropertyFilter.gt,
            "lt": PropertyFilter.lt,
            "$lt": PropertyFilter.lt,
            "gte": PropertyFilter.gte,
            "$gte": PropertyFilter.gte,
            "lte": PropertyFilter.lte,
            "$lte": PropertyFilter.lte,
            "ne": PropertyFilter.ne,
            "$ne": PropertyFilter.ne,
            "between": PropertyFilter.between,
            "$between": PropertyFilter.between,
            "contains": PropertyFilter.contains,
            "$contains": PropertyFilter.contains,
            "starts_with": PropertyFilter.starts_with,
            "$starts_with": PropertyFilter.starts_with,
            "ends_with": PropertyFilter.ends_with,
            "$ends_with": PropertyFilter.ends_with,
            "regex": PropertyFilter.regex,
            "$regex": PropertyFilter.regex,
        }

        case_sensitive = spec.get("case_sensitive")
        if case_sensitive is not None and not isinstance(case_sensitive, bool):
            raise CypherExecutionError("case_sensitive must be a boolean")

        operator_keys = [key for key in spec.keys() if key != "case_sensitive"]
        if len(operator_keys) != 1:
            raise CypherExecutionError("Property filter map must contain a single operator")

        op_key = operator_keys[0]
        if op_key not in operator_map:
            raise CypherExecutionError(f"Unsupported property filter operator: {op_key}")

        value = spec[op_key]
        if op_key in ("between", "$between"):
            if not isinstance(value, list) or len(value) != 2:
                raise CypherExecutionError("between expects a two-item list")
            return operator_map[op_key](value[0], value[1])

        if op_key in ("contains", "$contains", "starts_with", "$starts_with", "ends_with", "$ends_with"):
            if case_sensitive is None:
                return operator_map[op_key](value)
            return operator_map[op_key](value, case_sensitive=case_sensitive)

        return operator_map[op_key](value)

    def _execute_query_with_context(self, query: Query, initial_results: list[dict]) -> list[dict]:
        """Execute a query with initial results as context."""
        if query.union_clauses:
            return self._execute_union(query)

        if query.clauses:
            return self._execute_multi_clause(query.clauses, initial_results=initial_results)

        if isinstance(query.clause, WithClause):
            return self._execute_with(query.clause, initial_results)

        if isinstance(query.clause, SubqueryClause):
            return self._execute_subquery(query.clause, initial_results)
        if isinstance(query.clause, ProcedureCallClause):
            return self._execute_procedure_call(query.clause, initial_results)

        if isinstance(query.clause, UnwindClause):
            return self._execute_unwind(query.clause, initial_results)
        if isinstance(query.clause, LoadCsvClause):
            return self._execute_load_csv(query.clause, initial_results)

        if isinstance(query.clause, MatchClause):
            return self._execute_match(query.clause, context=initial_results)
        elif isinstance(query.clause, CreateClause):
            return self._execute_create(query.clause)
        elif isinstance(query.clause, MergeClause):
            return self._execute_merge(query.clause)
        else:
            raise CypherExecutionError(f"Unknown clause type: {type(query.clause)}")

    def _execute_unwind(self, clause: UnwindClause, input_results: list[dict]) -> list[dict]:
        """Execute UNWIND clause to expand a list into rows."""
        if not input_results:
            input_results = [{}]

        results = []
        for match in input_results:
            evaluator = self._make_evaluator(match)
            value = evaluator.evaluate(clause.list_expr)
            if value is None:
                continue
            if not isinstance(value, (list, tuple)):
                raise CypherExecutionError("UNWIND expects a list expression")
            for item in value:
                row = match.copy()
                row[clause.variable] = item
                results.append(row)
        return results

    def _execute_create(self, clause: CreateClause, context: list[dict] | None = None) -> list[dict]:
        """Execute CREATE clause.

        Supports:
        - Single node: CREATE (n:Person {name: 'Alice'})
        - Multiple nodes: CREATE (a:Person), (b:Person)
        - Nodes with relationships: CREATE (a:Person)-[r:KNOWS]->(b:Person)

        Args:
            clause: CreateClause AST node

        Returns:
            List with created entity info
        """
        if context:
            results = []
            for row in context:
                row_result = row.copy()
                for pattern in clause.patterns:
                    self._apply_create_pattern_with_context(pattern, row_result)
                results.append(row_result)
            return results

        results = []
        for pattern in clause.patterns:
            if len(pattern.elements) == 1 and pattern.elements[0].relationship is None:
                # Simple node creation: CREATE (n:Person)
                elem = pattern.elements[0]
                node_pattern = elem.node
                properties = self._evaluate_properties(node_pattern.properties, None)
                node = self.db.create_node(
                    labels=node_pattern.labels,
                    properties=properties
                )

                # Build result
                result = {}
                if node_pattern.variable:
                    result[node_pattern.variable] = node.to_dict()
                results.append(result if result else {'created': node.to_dict()})
            else:
                # Pattern with relationships: CREATE (a)-[r]->(b)
                result = self._create_pattern_with_relationships(pattern)
                results.append(result)

        return results

    def _create_pattern_with_relationships(self, pattern: Pattern, return_dicts: bool = True) -> dict:
        """Create nodes and relationships from a pattern.

        Args:
            pattern: Pattern AST node

        Returns:
            Dictionary with created nodes and relationships
        """
        if len(pattern.elements) != 2:
            raise CypherExecutionError(
                "Only single-hop relationship patterns supported in CREATE (e.g., (a)-[r]->(b))"
            )

        source_elem = pattern.elements[0]
        target_elem = pattern.elements[1]
        rel_pattern = source_elem.relationship

        if rel_pattern is None:
            raise CypherExecutionError("Invalid relationship pattern in CREATE")
        if rel_pattern.min_hops != 1 or rel_pattern.max_hops != 1:
            raise CypherExecutionError("Variable-length relationships are not supported in CREATE")

        # Create source node
        source_properties = self._evaluate_properties(source_elem.node.properties, None)
        source_node = self.db.create_node(
            labels=source_elem.node.labels,
            properties=source_properties
        )

        # Create target node
        target_properties = self._evaluate_properties(target_elem.node.properties, None)
        target_node = self.db.create_node(
            labels=target_elem.node.labels,
            properties=target_properties
        )

        # Create relationship
        # For CREATE, we ignore direction and always create outgoing from source to target
        rel_type = rel_pattern.rel_type if rel_pattern.rel_type else "RELATED_TO"
        rel_properties = self._evaluate_properties(rel_pattern.properties, None)
        relationship = self.db.create_relationship(
            source_id=source_node.id,
            target_id=target_node.id,
            rel_type=rel_type,
            properties=rel_properties
        )

        # Build result
        result = {}
        if source_elem.node.variable:
            result[source_elem.node.variable] = source_node.to_dict() if return_dicts else source_node
        if rel_pattern.variable:
            result[rel_pattern.variable] = relationship.to_dict() if return_dicts else relationship
        if target_elem.node.variable:
            result[target_elem.node.variable] = target_node.to_dict() if return_dicts else target_node

        return result

    def _apply_create_pattern_with_context(self, pattern: Pattern, row: dict) -> None:
        """Create nodes/relationships honoring existing bindings in row."""
        if len(pattern.elements) == 1 and pattern.elements[0].relationship is None:
            elem = pattern.elements[0]
            node_pattern = elem.node
            if node_pattern.variable and node_pattern.variable in row:
                return
            properties = self._evaluate_properties(node_pattern.properties, row)
            node = self.db.create_node(
                labels=node_pattern.labels,
                properties=properties
            )
            if node_pattern.variable:
                row[node_pattern.variable] = node
            return

        if len(pattern.elements) != 2:
            raise CypherExecutionError(
                "Only single-hop relationship patterns supported in CREATE (e.g., (a)-[r]->(b))"
            )

        source_elem = pattern.elements[0]
        target_elem = pattern.elements[1]
        rel_pattern = source_elem.relationship

        if rel_pattern is None:
            raise CypherExecutionError("Invalid relationship pattern in CREATE")
        if rel_pattern.min_hops != 1 or rel_pattern.max_hops != 1:
            raise CypherExecutionError("Variable-length relationships are not supported in CREATE")

        source_node = None
        if source_elem.node.variable:
            source_node = self._resolve_bound_node(row.get(source_elem.node.variable))
        if source_node is None:
            source_properties = self._evaluate_properties(source_elem.node.properties, row)
            source_node = self.db.create_node(
                labels=source_elem.node.labels,
                properties=source_properties
            )
            if source_elem.node.variable:
                row[source_elem.node.variable] = source_node

        target_node = None
        if target_elem.node.variable:
            target_node = self._resolve_bound_node(row.get(target_elem.node.variable))
        if target_node is None:
            target_properties = self._evaluate_properties(target_elem.node.properties, row)
            target_node = self.db.create_node(
                labels=target_elem.node.labels,
                properties=target_properties
            )
            if target_elem.node.variable:
                row[target_elem.node.variable] = target_node

        rel_type = rel_pattern.rel_type if rel_pattern.rel_type else "RELATED_TO"
        rel_properties = self._evaluate_properties(rel_pattern.properties, row)
        relationship = self.db.create_relationship(
            source_id=source_node.id,
            target_id=target_node.id,
            rel_type=rel_type,
            properties=rel_properties
        )

        if rel_pattern.variable:
            row[rel_pattern.variable] = relationship
        if pattern.variable:
            row[pattern.variable] = Path(nodes=[source_node, target_node], relationships=[relationship])

    def _resolve_bound_node(self, value: Any) -> Node | None:
        """Resolve a bound node from a context value."""
        if isinstance(value, Node):
            return value
        if isinstance(value, dict) and 'id' in value:
            return self.db.get_node(value['id'])
        return None

    def _execute_merge(
        self,
        clause: MergeClause,
        context: list[dict] | None = None
    ) -> list[dict]:
        """Execute MERGE clause (find or create pattern).

        MERGE is like an "upsert":
        1. Try to MATCH the pattern
        2. If found: run ON MATCH SET (if present)
        3. If not found: CREATE the pattern and run ON CREATE SET (if present)

        Args:
            clause: MergeClause AST node

        Returns:
            List with node/relationship info
        """
        def build_match_result(matches: list[dict], return_dicts: bool) -> dict:
            result: dict[str, Any] = {}
            for match in matches:
                for var_name, obj in match.items():
                    if return_dicts and hasattr(obj, 'to_dict'):
                        result[var_name] = obj.to_dict()
                    else:
                        result[var_name] = obj
                break
            return result

        def create_pattern_result(
            pattern: Pattern,
            row_context: dict[str, Any] | None,
            return_dicts: bool,
        ) -> dict:
            if len(pattern.elements) == 1 and pattern.elements[0].relationship is None:
                elem = pattern.elements[0]
                node_pattern = elem.node
                properties = self._evaluate_properties(node_pattern.properties, row_context)
                node = self.db.create_node(
                    labels=node_pattern.labels,
                    properties=properties
                )

                if clause.on_create_set:
                    match = {node_pattern.variable: node} if node_pattern.variable else {}
                    self._execute_set([match], clause.on_create_set)
                    node = self.db.get_node(node.id)

                result = {}
                if node_pattern.variable:
                    result[node_pattern.variable] = node.to_dict() if return_dicts else node
                return result if result else {'created': node.to_dict() if return_dicts else node}

            if row_context:
                source_elem = pattern.elements[0]
                target_elem = pattern.elements[1]
                rel_pattern = source_elem.relationship
                if rel_pattern is None:
                    raise CypherExecutionError("Invalid relationship pattern in MERGE")

                source_node = None
                if source_elem.node.variable and source_elem.node.variable in row_context:
                    source_node = self._resolve_bound_node(row_context.get(source_elem.node.variable))
                if source_node is None:
                    source_props = self._evaluate_properties(source_elem.node.properties, row_context)
                    source_node = self.db.create_node(
                        labels=source_elem.node.labels,
                        properties=source_props
                    )

                target_node = None
                if target_elem.node.variable and target_elem.node.variable in row_context:
                    target_node = self._resolve_bound_node(row_context.get(target_elem.node.variable))
                if target_node is None:
                    target_props = self._evaluate_properties(target_elem.node.properties, row_context)
                    target_node = self.db.create_node(
                        labels=target_elem.node.labels,
                        properties=target_props
                    )

                rel_type = rel_pattern.rel_type if rel_pattern.rel_type else "RELATED_TO"
                rel_props = self._evaluate_properties(rel_pattern.properties, row_context)

                existing_rels: list[Relationship] = []
                if rel_pattern.direction == "outgoing":
                    existing_rels = self.db.match_relationships(
                        source_id=source_node.id,
                        target_id=target_node.id,
                        rel_type=rel_type,
                        properties=rel_props if rel_props else None
                    )
                elif rel_pattern.direction == "incoming":
                    existing_rels = self.db.match_relationships(
                        source_id=target_node.id,
                        target_id=source_node.id,
                        rel_type=rel_type,
                        properties=rel_props if rel_props else None
                    )
                else:
                    existing_rels = self.db.match_relationships(
                        source_id=source_node.id,
                        target_id=target_node.id,
                        rel_type=rel_type,
                        properties=rel_props if rel_props else None
                    )
                    if not existing_rels:
                        existing_rels = self.db.match_relationships(
                            source_id=target_node.id,
                            target_id=source_node.id,
                            rel_type=rel_type,
                            properties=rel_props if rel_props else None
                        )

                if existing_rels:
                    rel = existing_rels[0]
                else:
                    rel = self.db.create_relationship(
                        source_id=source_node.id,
                        target_id=target_node.id,
                        rel_type=rel_type,
                        properties=rel_props
                    )

                created_result = {}
                if source_elem.node.variable:
                    created_result[source_elem.node.variable] = (
                        source_node.to_dict() if return_dicts else source_node
                    )
                if rel_pattern.variable:
                    created_result[rel_pattern.variable] = rel.to_dict() if return_dicts else rel
                if target_elem.node.variable:
                    created_result[target_elem.node.variable] = (
                        target_node.to_dict() if return_dicts else target_node
                    )
            else:
                created_result = self._create_pattern_with_relationships(
                    pattern,
                    return_dicts=return_dicts
                )

            if clause.on_create_set:
                match = {}
                for var_name, entity in created_result.items():
                    if hasattr(entity, 'labels'):
                        match[var_name] = entity
                    elif hasattr(entity, 'source_id'):
                        match[var_name] = entity
                    elif isinstance(entity, dict) and 'labels' in entity:
                        match[var_name] = self.db.get_node(entity['id'])
                    elif isinstance(entity, dict) and 'type' in entity:
                        match[var_name] = self.db.get_relationship(entity['id'])

                if match:
                    self._execute_set([match], clause.on_create_set)

                    if return_dicts:
                        for var_name, entity in match.items():
                            if hasattr(entity, 'to_dict'):
                                created_result[var_name] = entity.to_dict()

            return created_result

        if context:
            results = []
            for row in context:
                row_result = row.copy()
                for pattern in clause.patterns:
                    matches = [
                        match for match in self._match_pattern(pattern, context=row_result)
                        if self._pattern_bindings_match(row_result, match)
                    ]

                    if matches:
                        if clause.on_match_set:
                            self._execute_set(matches, clause.on_match_set)
                        merge_result = build_match_result(matches, return_dicts=False)
                    else:
                        merge_result = create_pattern_result(
                            pattern,
                            row_context=row_result,
                            return_dicts=False
                        )
                    row_result.update(merge_result)
                results.append(row_result)
            return results

        results = []
        for pattern in clause.patterns:
            matches = self._match_pattern(pattern)

            if matches:
                if clause.on_match_set:
                    self._execute_set(matches, clause.on_match_set)
                results.append(build_match_result(matches, return_dicts=True))
            else:
                results.append(create_pattern_result(pattern, row_context=None, return_dicts=True))

        return results

    def _execute_match(self, clause: MatchClause, context: list[dict] = None) -> list[dict]:
        """Execute MATCH clause with optional WHERE, DELETE, SET, RETURN, ORDER BY, SKIP, LIMIT.

        Args:
            clause: MatchClause AST node
            context: Optional context from previous WITH clause (not yet fully implemented)

        Returns:
            List of result dictionaries
        """
        pattern_vars = self._collect_pattern_variables(clause.patterns) if clause.optional else set()
        input_rows = context if context else [{}]
        matches = []

        for row in input_rows:
            property_filters = self._extract_property_filters(clause.where_clause, context=row)
            row_matches = [row]
            for pattern in clause.patterns:
                pattern_matches = []
                for partial in row_matches:
                    for match in self._match_pattern(pattern, property_filters, context=partial):
                        if not self._pattern_bindings_match(partial, match):
                            continue
                        merged = partial.copy()
                        merged.update(match)
                        pattern_matches.append(merged)
                row_matches = pattern_matches
                if not row_matches:
                    break

            if clause.where_clause:
                row_matches = self._filter_where(row_matches, clause.where_clause)

            if row_matches:
                matches.extend(row_matches)
            elif clause.optional:
                fallback = row.copy()
                for var in pattern_vars:
                    fallback.setdefault(var, None)
                matches.append(fallback)

        if clause.optional and not matches and not context:
            matches = [{var: None for var in pattern_vars}]

        # Apply DELETE if present (mutating operation)
        if clause.delete_clause:
            return self._execute_delete(matches, clause.delete_clause)

        # Apply SET if present (mutating operation)
        if clause.set_clause:
            self._execute_set(matches, clause.set_clause)

        # Apply REMOVE if present (mutating operation)
        if clause.remove_clause:
            self._execute_remove(matches, clause.remove_clause)

        # Apply ORDER BY BEFORE RETURN (needs access to Node objects)
        if clause.order_by_clause:
            matches = self._apply_order_by(matches, clause.order_by_clause)

        # Apply SKIP (before LIMIT and RETURN)
        if clause.skip_clause:
            matches = matches[clause.skip_clause.count:]

        # Apply LIMIT (on raw matches if no RETURN, or will be applied after RETURN)
        if clause.limit_clause and not clause.return_clause:
            matches = matches[:clause.limit_clause.count]

        # Apply RETURN projection if present
        if clause.return_clause:
            matches = self._apply_return(matches, clause.return_clause)
            # Apply LIMIT after RETURN if present
            if clause.limit_clause:
                matches = matches[:clause.limit_clause.count]

        return matches

    def _match_pattern(
        self,
        pattern: Pattern,
        property_filters: dict[str, dict[str, Any]] | None = None,
        context: dict[str, Any] | None = None
    ) -> list[dict]:
        """Match a pattern and return variable bindings.

        Args:
            pattern: Pattern AST node

        Returns:
            List of dictionaries mapping variables to matched entities
        """
        if isinstance(pattern, PatternFunction):
            return self._match_pattern_function(pattern)

        if len(pattern.elements) == 1 and pattern.elements[0].relationship is None:
            # Simple node pattern: (n:Label {props})
            return self._match_single_node(
                pattern.elements[0],
                path_variable=pattern.variable,
                property_filters=property_filters,
                context=context
            )
        else:
            # Relationship pattern: (a)-[r]->(b)
            return self._match_relationship_pattern(
                pattern,
                path_variable=pattern.variable,
                property_filters=property_filters,
                context=context
            )

    def _collect_pattern_variables(self, patterns: list[Pattern]) -> set[str]:
        """Collect variable names from patterns."""
        variables: set[str] = set()
        for pattern in patterns:
            if isinstance(pattern, PatternFunction):
                if pattern.variable:
                    variables.add(pattern.variable)
                for elem in pattern.pattern.elements:
                    if elem.node.variable:
                        variables.add(elem.node.variable)
                    if elem.relationship and elem.relationship.variable:
                        variables.add(elem.relationship.variable)
                continue
            if pattern.variable:
                variables.add(pattern.variable)
            for elem in pattern.elements:
                if elem.node.variable:
                    variables.add(elem.node.variable)
                if elem.relationship and elem.relationship.variable:
                    variables.add(elem.relationship.variable)
        return variables

    def _merge_property_filters(
        self,
        base: dict[str, Any],
        extra: dict[str, Any],
    ) -> dict[str, Any] | None:
        """Merge property filters, returning None when there is a conflict."""
        merged = dict(base)
        for key, value in extra.items():
            if key in merged and merged[key] != value:
                return None
            merged[key] = value
        return merged

    def _extract_property_filters(
        self,
        where_clause: WhereClause | None,
        context: dict[str, Any] | None = None,
    ) -> dict[str, dict[str, Any]]:
        """Extract equality filters from WHERE for simple pushdown."""
        if where_clause is None:
            return {}
        filters = self._collect_property_filters(where_clause.condition, context=context)
        return filters

    def _collect_property_filters(
        self,
        expr: Expression,
        context: dict[str, Any] | None = None
    ) -> dict[str, dict[str, Any]]:
        """Collect property = literal filters from AND-connected expressions."""
        if isinstance(expr, BinaryOp) and expr.operator == "AND":
            left = self._collect_property_filters(expr.left, context=context)
            right = self._collect_property_filters(expr.right, context=context)
            if not left:
                return right
            if not right:
                return left
            merged: dict[str, dict[str, Any]] = {}
            for var, props in left.items():
                merged[var] = dict(props)
            for var, props in right.items():
                if var not in merged:
                    merged[var] = dict(props)
                    continue
                merged_props = self._merge_property_filters(merged[var], props)
                if merged_props is None:
                    return {}
                merged[var] = merged_props
            return merged

        if isinstance(expr, BinaryOp) and expr.operator == "=":
            if isinstance(expr.left, PropertyAccess) and isinstance(expr.right, Literal):
                if expr.right.value is None:
                    return {}
                return {expr.left.variable: {expr.left.property: expr.right.value}}
            if isinstance(expr.right, PropertyAccess) and isinstance(expr.left, Literal):
                if expr.left.value is None:
                    return {}
                return {expr.right.variable: {expr.right.property: expr.left.value}}
            if context is not None:
                evaluator = self._make_evaluator(context)
                if isinstance(expr.left, PropertyAccess):
                    try:
                        value = evaluator.evaluate(expr.right)
                    except CypherExecutionError:
                        return {}
                    if value is None or isinstance(value, (Node, Relationship, list, dict)):
                        return {}
                    return {expr.left.variable: {expr.left.property: value}}
                if isinstance(expr.right, PropertyAccess):
                    try:
                        value = evaluator.evaluate(expr.left)
                    except CypherExecutionError:
                        return {}
                    if value is None or isinstance(value, (Node, Relationship, list, dict)):
                        return {}
                    return {expr.right.variable: {expr.right.property: value}}

        return {}

    def _match_pattern_function(self, pattern_func: PatternFunction) -> list[dict]:
        """Match shortestPath/allShortestPaths patterns."""
        inner = pattern_func.pattern
        if len(inner.elements) != 2:
            raise CypherExecutionError(
                f"{pattern_func.name} only supports a single relationship pattern"
            )

        source_elem = inner.elements[0]
        target_elem = inner.elements[1]
        rel_pattern = source_elem.relationship
        if rel_pattern is None:
            raise CypherExecutionError(
                f"{pattern_func.name} requires a relationship pattern"
            )

        source_properties = self._evaluate_properties(source_elem.node.properties, None)
        target_properties = self._evaluate_properties(target_elem.node.properties, None)
        rel_properties = self._evaluate_properties(rel_pattern.properties, None)

        start_nodes = self.db.match_nodes(
            labels=source_elem.node.labels if source_elem.node.labels else None,
            properties=source_properties if source_properties else None
        )
        end_nodes = self.db.match_nodes(
            labels=target_elem.node.labels if target_elem.node.labels else None,
            properties=target_properties if target_properties else None
        )

        all_paths = pattern_func.name == 'ALLSHORTESTPATHS'

        results = []
        for start_node in start_nodes:
            for end_node in end_nodes:
                paths = self._find_shortest_paths(
                    start_node,
                    end_node,
                    rel_pattern,
                    all_paths=all_paths,
                    rel_properties=rel_properties
                )
                for nodes_path, rels_path in paths:
                    bindings = {}
                    if source_elem.node.variable:
                        bindings[source_elem.node.variable] = start_node
                    if target_elem.node.variable:
                        bindings[target_elem.node.variable] = end_node
                    if rel_pattern.variable:
                        if rel_pattern.min_hops == 1 and rel_pattern.max_hops == 1:
                            bindings[rel_pattern.variable] = rels_path[0]
                        else:
                            bindings[rel_pattern.variable] = rels_path
                    if pattern_func.variable:
                        bindings[pattern_func.variable] = Path(
                            nodes=nodes_path,
                            relationships=rels_path
                        )
                    results.append(bindings)

        return results

    def _resolve_max_hops(self, rel_pattern: RelationshipPattern) -> int:
        """Resolve max hop limit for a relationship pattern."""
        max_hops = rel_pattern.max_hops
        if max_hops is None:
            max_hops = getattr(self.db, "cypher_max_hops", None)
            if not max_hops or max_hops <= 0:
                raise CypherExecutionError(
                    "Unbounded variable-length paths require a configured max hop limit"
                )
        return max_hops

    def _find_shortest_paths(
        self,
        start_node: Node,
        end_node: Node,
        rel_pattern: RelationshipPattern,
        all_paths: bool = False,
        rel_properties: dict[str, Any] | None = None
    ) -> list[tuple[list[Node], list[Relationship]]]:
        """Find shortest paths honoring relationship constraints."""
        min_hops = rel_pattern.min_hops
        max_hops = self._resolve_max_hops(rel_pattern)

        if start_node.id == end_node.id:
            if min_hops == 0:
                return [([start_node], [])]
            return []

        from collections import deque

        results: list[tuple[list[Node], list[Relationship]]] = []
        queue = deque([(start_node, [start_node], [], {start_node.id})])
        shortest_len = None

        while queue:
            current_node, nodes_path, rels_path, visited_ids = queue.popleft()
            depth = len(rels_path)

            if shortest_len is not None and depth >= shortest_len:
                continue
            if depth >= max_hops:
                continue

            for rel, next_node in self._get_next_relationships(
                current_node,
                rel_pattern,
                rel_properties=rel_properties
            ):
                if next_node.id in visited_ids:
                    continue
                new_nodes = nodes_path + [next_node]
                new_rels = rels_path + [rel]
                new_depth = depth + 1
                if new_depth > max_hops:
                    continue

                if next_node.id == end_node.id and new_depth >= min_hops:
                    if shortest_len is None or new_depth == shortest_len:
                        results.append((new_nodes, new_rels))
                        shortest_len = new_depth
                    elif new_depth < shortest_len:
                        results = [(new_nodes, new_rels)]
                        shortest_len = new_depth

                    if not all_paths:
                        return results[:1]

                if shortest_len is None or new_depth < shortest_len:
                    queue.append((next_node, new_nodes, new_rels, visited_ids | {next_node.id}))

        return results

    def _match_single_node(
        self,
        element: PatternElement,
        path_variable: str | None = None,
        property_filters: dict[str, dict[str, Any]] | None = None,
        context: dict[str, Any] | None = None,
    ) -> list[dict]:
        """Match a single node pattern.

        Args:
            element: PatternElement with node pattern only

        Returns:
            List of variable bindings
        """
        node_pattern = element.node
        if context and node_pattern.variable and node_pattern.variable in context:
            bound = self._resolve_bound_node(context.get(node_pattern.variable))
            if bound is None:
                return []
            evaluated_properties = self._evaluate_properties(node_pattern.properties, context)
            if not self._node_matches_pattern(bound, node_pattern, properties=evaluated_properties):
                return []
            result = {}
            result[node_pattern.variable] = bound
            if path_variable:
                result[path_variable] = Path(nodes=[bound], relationships=[])
            return [result]

        evaluated_properties = self._evaluate_properties(node_pattern.properties, context)
        merged_properties = evaluated_properties
        if property_filters and node_pattern.variable in property_filters:
            merged_properties = self._merge_property_filters(
                evaluated_properties,
                property_filters[node_pattern.variable]
            )
            if merged_properties is None:
                return []

        # Use match_nodes API
        nodes = self.db.match_nodes(
            labels=node_pattern.labels if node_pattern.labels else None,
            properties=merged_properties if merged_properties else None
        )

        # Build results
        results = []
        for node in nodes:
            result = {}
            if node_pattern.variable:
                result[node_pattern.variable] = node
            if path_variable:
                result[path_variable] = Path(nodes=[node], relationships=[])
            results.append(result)

        return results

    def _match_relationship_pattern(
        self,
        pattern: Pattern,
        path_variable: str | None = None,
        property_filters: dict[str, dict[str, Any]] | None = None,
        context: dict[str, Any] | None = None,
    ) -> list[dict]:
        """Match a relationship pattern like (a)-[r:TYPE]->(b).

        Args:
            pattern: Pattern with multiple elements connected by relationships

        Returns:
            List of variable bindings for (source, relationship, target) tuples
        """
        if len(pattern.elements) != 2:
            return self._match_multi_hop_relationship_pattern(
                pattern,
                path_variable=path_variable,
                context=context
            )

        source_elem = pattern.elements[0]
        target_elem = pattern.elements[1]
        rel_pattern = source_elem.relationship

        if rel_pattern is None:
            raise CypherExecutionError("Invalid relationship pattern")

        if rel_pattern.min_hops != 1 or rel_pattern.max_hops != 1:
            return self._match_variable_length_relationship_pattern(
                source_elem,
                target_elem,
                rel_pattern,
                path_variable=path_variable,
                context=context
            )

        filters = property_filters or {}
        source_properties = self._evaluate_properties(source_elem.node.properties, context)
        if source_elem.node.variable in filters:
            source_properties = self._merge_property_filters(
                source_properties,
                filters[source_elem.node.variable]
            )
            if source_properties is None:
                return []

        target_properties = self._evaluate_properties(target_elem.node.properties, context)
        if target_elem.node.variable in filters:
            target_properties = self._merge_property_filters(
                target_properties,
                filters[target_elem.node.variable]
            )
            if target_properties is None:
                return []

        rel_properties = self._evaluate_properties(rel_pattern.properties, context)
        if rel_pattern.variable and rel_pattern.variable in filters:
            rel_properties = self._merge_property_filters(
                rel_properties,
                filters[rel_pattern.variable]
            )
            if rel_properties is None:
                return []

        # Match source nodes
        source_nodes = None
        if context and source_elem.node.variable and source_elem.node.variable in context:
            bound_source = self._resolve_bound_node(context.get(source_elem.node.variable))
            if bound_source and self._node_matches_pattern(bound_source, source_elem.node, properties=source_properties):
                source_nodes = [bound_source]
            else:
                return []
        if source_nodes is None:
            source_nodes = self.db.match_nodes(
                labels=source_elem.node.labels if source_elem.node.labels else None,
                properties=source_properties if source_properties else None
            )

        target_ids = None
        if context and target_elem.node.variable and target_elem.node.variable in context:
            bound_target = self._resolve_bound_node(context.get(target_elem.node.variable))
            if bound_target and self._node_matches_pattern(bound_target, target_elem.node, properties=target_properties):
                target_ids = {bound_target.id}
            else:
                return []
        elif target_elem.node.labels or target_properties:
            target_nodes = self.db.match_nodes(
                labels=target_elem.node.labels if target_elem.node.labels else None,
                properties=target_properties if target_properties else None
            )
            target_ids = {node.id for node in target_nodes}

        # For each source node, find matching relationships
        results = []
        for source_node in source_nodes:
            # Get relationships based on direction
            if rel_pattern.direction == 'outgoing':
                rels = self.db.match_relationships(
                    source_id=source_node.id,
                    rel_type=rel_pattern.rel_type,
                    properties=rel_properties if rel_properties else None
                )
            elif rel_pattern.direction == 'incoming':
                rels = self.db.match_relationships(
                    target_id=source_node.id,
                    rel_type=rel_pattern.rel_type,
                    properties=rel_properties if rel_properties else None
                )
            else:  # 'both'
                outgoing = self.db.match_relationships(
                    source_id=source_node.id,
                    rel_type=rel_pattern.rel_type,
                    properties=rel_properties if rel_properties else None
                )
                incoming = self.db.match_relationships(
                    target_id=source_node.id,
                    rel_type=rel_pattern.rel_type,
                    properties=rel_properties if rel_properties else None
                )
                rels = outgoing + incoming

            # For each relationship, check target node matches
            for rel in rels:
                # Determine target node id based on direction
                if rel_pattern.direction == 'incoming':
                    target_id = rel.source_id
                else:
                    target_id = rel.target_id

                if target_ids is not None and target_id not in target_ids:
                    continue

                target_node = self.db.get_node(target_id)
                if target_node is None:
                    continue

                # Check if target matches pattern
                if target_elem.node.labels:
                    if not all(label in target_node.labels for label in target_elem.node.labels):
                        continue

                if target_properties:
                    props_match = all(
                        target_node.properties.get(k) == v
                        for k, v in target_properties.items()
                    )
                    if not props_match:
                        continue

                # Build result
                result = {}
                if source_elem.node.variable:
                    result[source_elem.node.variable] = source_node
                if rel_pattern.variable:
                    result[rel_pattern.variable] = rel
                if target_elem.node.variable:
                    result[target_elem.node.variable] = target_node
                if path_variable:
                    result[path_variable] = Path(nodes=[source_node, target_node], relationships=[rel])

                results.append(result)

        return results

    def _match_multi_hop_relationship_pattern(
        self,
        pattern: Pattern,
        path_variable: str | None = None,
        context: dict[str, Any] | None = None
    ) -> list[dict]:
        """Match multi-hop relationship patterns across a chain."""
        elements = pattern.elements
        if len(elements) < 2:
            return []

        first_elem = elements[0]
        first_properties = self._evaluate_properties(first_elem.node.properties, context)
        start_nodes = self.db.match_nodes(
            labels=first_elem.node.labels if first_elem.node.labels else None,
            properties=first_properties if first_properties else None
        )

        results = []

        for start_node in start_nodes:
            base_bindings = {}
            if first_elem.node.variable:
                base_bindings[first_elem.node.variable] = start_node

            def walk(
                index: int,
                current_node: Node,
                bindings: dict,
                node_path: list[Node],
                rel_path: list[Relationship]
            ) -> None:
                if index == len(elements) - 1:
                    if path_variable:
                        bindings[path_variable] = Path(
                            nodes=node_path.copy(),
                            relationships=rel_path.copy()
                        )
                    results.append(bindings)
                    return

                rel_pattern = elements[index].relationship
                if rel_pattern is None:
                    raise CypherExecutionError("Missing relationship in multi-hop pattern")

                next_node_pattern = elements[index + 1].node

                rel_properties = self._evaluate_properties(rel_pattern.properties, context)
                next_properties = self._evaluate_properties(next_node_pattern.properties, context)

                for next_node, rel_value, segment_nodes in self._expand_relationship_segment(
                    current_node,
                    rel_pattern,
                    next_node_pattern,
                    rel_properties=rel_properties,
                    target_properties=next_properties
                ):
                    if next_node_pattern.variable and context and next_node_pattern.variable in context:
                        bound_next = self._resolve_bound_node(context.get(next_node_pattern.variable))
                        if bound_next is None or bound_next.id != next_node.id:
                            continue
                    new_bindings = bindings.copy()
                    if rel_pattern.variable:
                        new_bindings[rel_pattern.variable] = rel_value
                    if next_node_pattern.variable:
                        new_bindings[next_node_pattern.variable] = next_node
                    if isinstance(rel_value, list):
                        new_rel_path = rel_path + rel_value
                    else:
                        new_rel_path = rel_path + [rel_value]
                    new_node_path = node_path + segment_nodes[1:]
                    walk(index + 1, next_node, new_bindings, new_node_path, new_rel_path)

            walk(0, start_node, base_bindings, [start_node], [])

        return results

    def _expand_relationship_segment(
        self,
        start_node: Node,
        rel_pattern: RelationshipPattern,
        target_pattern: NodePattern,
        rel_properties: dict[str, Any] | None = None,
        target_properties: dict[str, Any] | None = None
    ) -> list[tuple[Node, Any, list[Node]]]:
        """Expand a relationship segment to matching end nodes."""
        if rel_pattern.min_hops == 1 and rel_pattern.max_hops == 1:
            results = []
            for rel, next_node in self._get_next_relationships(
                start_node,
                rel_pattern,
                rel_properties=rel_properties
            ):
                if not self._node_matches_pattern(
                    next_node,
                    target_pattern,
                    properties=target_properties
                ):
                    continue
                results.append((next_node, rel, [start_node, next_node]))
            return results

        return self._expand_variable_length_segment(
            start_node,
            rel_pattern,
            target_pattern,
            rel_properties=rel_properties,
            target_properties=target_properties
        )

    def _expand_variable_length_segment(
        self,
        start_node: Node,
        rel_pattern: RelationshipPattern,
        target_pattern: NodePattern,
        rel_properties: dict[str, Any] | None = None,
        target_properties: dict[str, Any] | None = None
    ) -> list[tuple[Node, list[Relationship], list[Node]]]:
        """Expand a variable-length segment with DFS and hop limits."""
        min_hops = rel_pattern.min_hops
        max_hops = rel_pattern.max_hops

        if max_hops is None:
            max_hops = getattr(self.db, "cypher_max_hops", None)
            if not max_hops or max_hops <= 0:
                raise CypherExecutionError(
                    "Unbounded variable-length paths require a configured max hop limit"
                )

        results = []

        def dfs(
            current_node: Node,
            depth: int,
            rel_path: list[Relationship],
            node_path: list[Node],
            visited_ids: set[int]
        ):
            if depth >= min_hops and self._node_matches_pattern(
                current_node,
                target_pattern,
                properties=target_properties
            ):
                results.append((current_node, rel_path.copy(), node_path.copy()))

            if depth == max_hops:
                return

            for rel, next_node in self._get_next_relationships(
                current_node,
                rel_pattern,
                rel_properties=rel_properties
            ):
                if next_node.id in visited_ids:
                    continue
                visited_ids.add(next_node.id)
                rel_path.append(rel)
                node_path.append(next_node)
                dfs(next_node, depth + 1, rel_path, node_path, visited_ids)
                node_path.pop()
                rel_path.pop()
                visited_ids.remove(next_node.id)

        dfs(start_node, 0, [], [start_node], {start_node.id})

        return results

    def _match_variable_length_relationship_pattern(
        self,
        source_elem: PatternElement,
        target_elem: PatternElement,
        rel_pattern: RelationshipPattern,
        path_variable: str | None = None,
        context: dict[str, Any] | None = None
    ) -> list[dict]:
        """Match variable-length relationship pattern (e.g., [:TYPE*1..3])."""
        min_hops = rel_pattern.min_hops
        max_hops = rel_pattern.max_hops

        if max_hops is None:
            max_hops = getattr(self.db, "cypher_max_hops", None)
            if not max_hops or max_hops <= 0:
                raise CypherExecutionError(
                    "Unbounded variable-length paths require a configured max hop limit"
                )

        source_properties = self._evaluate_properties(source_elem.node.properties, context)
        target_properties = self._evaluate_properties(target_elem.node.properties, context)
        rel_properties = self._evaluate_properties(rel_pattern.properties, context)

        # Match source nodes
        source_nodes = None
        if context and source_elem.node.variable and source_elem.node.variable in context:
            bound_source = self._resolve_bound_node(context.get(source_elem.node.variable))
            if bound_source and self._node_matches_pattern(bound_source, source_elem.node, properties=source_properties):
                source_nodes = [bound_source]
            else:
                return []
        if source_nodes is None:
            source_nodes = self.db.match_nodes(
                labels=source_elem.node.labels if source_elem.node.labels else None,
                properties=source_properties if source_properties else None
            )
        bound_target = None
        if context and target_elem.node.variable and target_elem.node.variable in context:
            bound_target = self._resolve_bound_node(context.get(target_elem.node.variable))

        results = []

        for source_node in source_nodes:
            def dfs(current_node, depth, rel_path, node_path, visited_ids):
                if depth >= min_hops:
                    if self._node_matches_pattern(
                        current_node,
                        target_elem.node,
                        properties=target_properties
                    ):
                        if not bound_target or current_node.id == bound_target.id:
                            result = {}
                            if source_elem.node.variable:
                                result[source_elem.node.variable] = source_node
                            if target_elem.node.variable:
                                result[target_elem.node.variable] = current_node
                            if rel_pattern.variable:
                                result[rel_pattern.variable] = rel_path.copy()
                            if path_variable:
                                result[path_variable] = Path(
                                    nodes=node_path.copy(),
                                    relationships=rel_path.copy()
                                )
                            results.append(result)

                if depth == max_hops:
                    return

                for rel, next_node in self._get_next_relationships(
                    current_node,
                    rel_pattern,
                    rel_properties=rel_properties
                ):
                    if next_node.id in visited_ids:
                        continue
                    visited_ids.add(next_node.id)
                    rel_path.append(rel)
                    node_path.append(next_node)
                    dfs(next_node, depth + 1, rel_path, node_path, visited_ids)
                    node_path.pop()
                    rel_path.pop()
                    visited_ids.remove(next_node.id)

            dfs(source_node, 0, [], [source_node], {source_node.id})

        return results

    def _node_matches_pattern(
        self,
        node: Node,
        pattern: NodePattern,
        properties: dict[str, Any] | None = None
    ) -> bool:
        """Check if a node matches a node pattern (labels and properties)."""
        if pattern.labels:
            if not all(label in node.labels for label in pattern.labels):
                return False

        props = properties if properties is not None else pattern.properties
        if props:
            for key, value in props.items():
                if node.properties.get(key) != value:
                    return False

        return True

    def _get_next_relationships(
        self,
        current_node: Node,
        rel_pattern: RelationshipPattern,
        rel_properties: dict[str, Any] | None = None
    ) -> list[tuple[Relationship, Node]]:
        """Get relationships and next nodes for variable-length traversal."""
        results = []

        if rel_pattern.direction in ('outgoing', 'both'):
            rels = self.db.match_relationships(
                source_id=current_node.id,
                rel_type=rel_pattern.rel_type
            )
            for rel in rels:
                if not self._relationship_matches_pattern(rel, rel_pattern, rel_properties):
                    continue
                next_node = self.db.get_node(rel.target_id)
                if next_node:
                    results.append((rel, next_node))

        if rel_pattern.direction in ('incoming', 'both'):
            rels = self.db.match_relationships(
                target_id=current_node.id,
                rel_type=rel_pattern.rel_type
            )
            for rel in rels:
                if not self._relationship_matches_pattern(rel, rel_pattern, rel_properties):
                    continue
                next_node = self.db.get_node(rel.source_id)
                if next_node:
                    results.append((rel, next_node))

        return results

    def _relationship_matches_pattern(
        self,
        rel: Relationship,
        rel_pattern: RelationshipPattern,
        properties: dict[str, Any] | None = None
    ) -> bool:
        """Check if a relationship matches type/properties constraints."""
        if rel_pattern.rel_type and rel.type != rel_pattern.rel_type:
            return False

        props = properties if properties is not None else rel_pattern.properties
        if props:
            for key, value in props.items():
                if rel.properties.get(key) != value:
                    return False

        return True

    def _filter_where(self, matches: list[dict], where_clause: WhereClause) -> list[dict]:
        """Filter matches using WHERE clause.

        Args:
            matches: List of variable bindings
            where_clause: WhereClause AST node

        Returns:
            Filtered list of matches
        """
        filtered = []

        for match in matches:
            evaluator = self._make_evaluator(match)
            try:
                result = evaluator.evaluate(where_clause.condition)
                if result:
                    filtered.append(match)
            except CypherExecutionError:
                # Skip matches that fail evaluation
                continue

        return filtered

    def _apply_return(self, matches: list[dict], return_clause: ReturnClause) -> list[dict]:
        """Apply RETURN projection to matches.

        Args:
            matches: List of variable bindings
            return_clause: ReturnClause AST node

        Returns:
            Projected results
        """
        # Check if any return item is an aggregation function
        has_aggregation = any(isinstance(item.expression, FunctionCall) for item in return_clause.items)

        if has_aggregation:
            # Aggregation mode: return a single row with aggregated values
            return self._apply_aggregation_return(matches, return_clause)
        else:
            # Normal mode: return one row per match
            return self._apply_normal_return(matches, return_clause)

    def _format_property_key(self, expr: PropertyAccess | PropertyLookup) -> str:
        """Format property access expressions for result keys."""
        if isinstance(expr, PropertyAccess):
            return f"{expr.variable}.{expr.property}"
        return self._format_property_lookup(expr)

    def _format_property_lookup(self, expr: PropertyLookup) -> str:
        base = expr.base_expr
        if isinstance(base, PropertyAccess):
            base_key = f"{base.variable}.{base.property}"
        elif isinstance(base, PropertyLookup):
            base_key = self._format_property_lookup(base)
        elif isinstance(base, Variable):
            base_key = base.name
        else:
            base_key = str(base)
        return f"{base_key}.{expr.property}"

    def _apply_normal_return(self, matches: list[dict], return_clause: ReturnClause) -> list[dict]:
        """Apply non-aggregated RETURN projection."""
        results = []

        for match in matches:
            result = {}

            for item in return_clause.items:
                value = self._evaluate_return_expression(match, item.expression)

                if item.alias:
                    key = item.alias
                elif isinstance(item.expression, Variable):
                    key = item.expression.name
                elif isinstance(item.expression, (PropertyAccess, PropertyLookup)):
                    key = self._format_property_key(item.expression)
                else:
                    key = str(item.expression)

                result[key] = value

            results.append(result)

        if return_clause.distinct:
            return self._apply_distinct(results)
        return results

    def _apply_aggregation_return(self, matches: list[dict], return_clause: ReturnClause) -> list[dict]:
        """Apply aggregated RETURN projection (COUNT, SUM, AVG, MIN, MAX)."""
        result = {}

        for item in return_clause.items:
            if isinstance(item.expression, FunctionCall):
                # Evaluate aggregation function
                func_name = item.expression.function_name
                arguments = item.expression.arguments
                distinct = item.expression.distinct
                star = item.expression.star

                # Generate result key (e.g., "COUNT(n)" or "SUM(n.age)")
                if item.alias:
                    key = item.alias
                else:
                    distinct_prefix = "DISTINCT " if distinct else ""
                    if star:
                        key = f"{func_name}({distinct_prefix}*)"
                    elif len(arguments) == 1:
                        argument = arguments[0]
                        if isinstance(argument, Literal):
                            key = f"{func_name}({distinct_prefix}{argument.value})"
                        elif isinstance(argument, Variable):
                            key = f"{func_name}({distinct_prefix}{argument.name})"
                        elif isinstance(argument, PropertyAccess):
                            key = f"{func_name}({distinct_prefix}{argument.variable}.{argument.property})"
                        else:
                            key = func_name
                    else:
                        key = func_name

                # Calculate aggregation
                value = self._calculate_aggregation(func_name, arguments, matches, distinct, star)
                result[key] = value

            else:
                # Mixed aggregation and non-aggregation not fully supported yet
                # For now, just evaluate the expression on the first match
                if len(matches) > 0:
                    evaluator = self._make_evaluator(matches[0])
                    value = evaluator.evaluate(item.expression)
                else:
                    value = None

                key = item.alias if item.alias else str(item.expression)
                result[key] = value

        results = [result]
        if return_clause.distinct:
            return self._apply_distinct(results)
        return results

    def _apply_distinct(self, rows: list[dict]) -> list[dict]:
        """Remove duplicate rows while preserving order."""
        seen = set()
        distinct_rows = []
        for row in rows:
            frozen = self._freeze_result(row)
            if frozen in seen:
                continue
            seen.add(frozen)
            distinct_rows.append(row)
        return distinct_rows

    def _evaluate_return_expression(self, match: dict, expr: Any) -> Any:
        """Evaluate a RETURN expression against a match row."""
        if isinstance(expr, PatternComprehension):
            return self._evaluate_pattern_comprehension(expr, match)

        if isinstance(expr, Variable):
            var_name = expr.name
            if var_name in match:
                return self._serialize_value(match[var_name])
            return None

        if isinstance(expr, PropertyAccess):
            var_name = expr.variable
            prop_name = expr.property
            if var_name not in match:
                return None
            obj = match[var_name]
            if hasattr(obj, 'properties'):
                return obj.properties.get(prop_name)
            if isinstance(obj, dict):
                return obj.get(prop_name)
            return None

        evaluator = self._make_evaluator(match)
        value = evaluator.evaluate(expr)
        return self._serialize_value(value)

    def _serialize_value(self, value: Any) -> Any:
        """Convert model instances to dictionaries for output."""
        if hasattr(value, 'to_dict'):
            return value.to_dict()
        if isinstance(value, list):
            return [self._serialize_value(item) for item in value]
        if isinstance(value, dict):
            return {k: self._serialize_value(v) for k, v in value.items()}
        return value

    def _calculate_aggregation(
        self,
        func_name: str,
        arguments: list[Any],
        matches: list[dict],
        distinct: bool = False,
        star: bool = False,
    ) -> Any:
        """Calculate aggregation function value.

        Args:
            func_name: Function name (COUNT, SUM, AVG, MIN, MAX)
            argument: Expression to aggregate over (or None for COUNT(*))
            matches: List of variable bindings

        Returns:
            Aggregated value
        """
        if func_name != 'COUNT' and star:
            raise CypherExecutionError(f"{func_name}(*) is not supported")

        if func_name == 'COUNT':
            if star:
                # COUNT(*) - count all rows
                return len(matches)
            else:
                if not arguments:
                    raise CypherExecutionError("COUNT() expects an argument or *")
                # COUNT(expr) - count non-null values
                values = []
                for match in matches:
                    evaluator = self._make_evaluator(match)
                    try:
                        value = evaluator.evaluate(arguments[0]) if arguments else None
                        if value is not None:
                            values.append(value)
                    except:
                        pass
                if distinct:
                    values = self._distinct_values(values)
                return len(values)

        elif func_name in ('SUM', 'AVG', 'MIN', 'MAX', 'COLLECT', 'STDDEV', 'PERCENTILECONT'):
            if not arguments:
                raise CypherExecutionError(f"{func_name}() expects at least 1 argument")
            # Collect values
            values = []
            for match in matches:
                evaluator = self._make_evaluator(match)
                try:
                    value = evaluator.evaluate(arguments[0]) if arguments else None
                    if func_name == 'COLLECT':
                        values.append(value)
                    elif value is not None:
                        values.append(value)
                except:
                    pass

            if distinct:
                values = self._distinct_values(values)

            if func_name == 'COLLECT':
                return values

            if not values:
                return None

            if func_name == 'SUM':
                return sum(values)
            elif func_name == 'AVG':
                return sum(values) / len(values)
            elif func_name == 'MIN':
                return min(values)
            elif func_name == 'MAX':
                return max(values)
            elif func_name == 'STDDEV':
                if len(values) == 1:
                    return 0.0
                mean = sum(values) / len(values)
                variance = sum((value - mean) ** 2 for value in values) / len(values)
                return variance ** 0.5
            elif func_name == 'PERCENTILECONT':
                if len(arguments) < 2:
                    raise CypherExecutionError("PERCENTILECONT requires value and percentile")
                percentile = evaluator.evaluate(arguments[1])
                if percentile is None:
                    return None
                if not isinstance(percentile, (int, float)):
                    raise CypherExecutionError("PERCENTILECONT percentile must be a number")
                if percentile < 0 or percentile > 1:
                    raise CypherExecutionError("PERCENTILECONT percentile must be between 0 and 1")
                sorted_values = sorted(values)
                if len(sorted_values) == 1:
                    return float(sorted_values[0])
                index = percentile * (len(sorted_values) - 1)
                lower_index = int(index)
                upper_index = min(lower_index + 1, len(sorted_values) - 1)
                lower = sorted_values[lower_index]
                upper = sorted_values[upper_index]
                if lower_index == upper_index:
                    return float(lower)
                fraction = index - lower_index
                return lower + (upper - lower) * fraction

        raise CypherExecutionError(f"Unknown aggregation function: {func_name}")

    def _distinct_values(self, values: list[Any]) -> list[Any]:
        """Return distinct values preserving first occurrence order."""
        seen = set()
        distinct_values = []
        for value in values:
            frozen = self._freeze_result(value)
            if frozen in seen:
                continue
            seen.add(frozen)
            distinct_values.append(value)
        return distinct_values

    def _execute_delete(self, matches: list[dict], delete_clause) -> list[dict]:
        """Execute DELETE clause to delete nodes and relationships.

        Args:
            matches: List of variable bindings
            delete_clause: DeleteClause AST node

        Returns:
            List with count of deleted items
        """
        deleted_nodes = 0
        deleted_rels = 0

        for match in matches:
            for var_name in delete_clause.variables:
                if var_name not in match:
                    raise CypherExecutionError(f"Variable '{var_name}' not found for DELETE")

                obj = match[var_name]

                # Check if it's a Node or Relationship
                if hasattr(obj, 'source_id'):  # It's a Relationship
                    self.db.delete_relationship(obj.id)
                    deleted_rels += 1
                elif hasattr(obj, 'labels'):  # It's a Node
                    self.db.delete_node(obj.id)
                    deleted_nodes += 1
                else:
                    raise CypherExecutionError(
                        f"Variable '{var_name}' is not a node or relationship"
                    )

        return [{'deleted_nodes': deleted_nodes, 'deleted_relationships': deleted_rels}]

    def _execute_set(self, matches: list[dict], set_clause) -> None:
        """Execute SET clause to update node properties.

        Args:
            matches: List of variable bindings
            set_clause: SetClause AST node
        """
        for match in matches:
            for set_item in set_clause.items:
                var_name = set_item.variable
                prop_name = set_item.property

                if var_name not in match:
                    raise CypherExecutionError(f"Variable '{var_name}' not found for SET")

                obj = match[var_name]

                # Evaluate the value expression
                evaluator = self._make_evaluator(match)
                value = evaluator.evaluate(set_item.value)

                if prop_name is None:
                    if set_item.operator == "+=":
                        if not isinstance(value, dict):
                            raise CypherExecutionError("SET += expects a map value")
                        merged = obj.properties.copy()
                        merged.update(value)
                        self._apply_properties_update(obj, merged, replace=True)
                    elif set_item.operator == "=":
                        if not isinstance(value, dict):
                            raise CypherExecutionError("SET = expects a map value")
                        self._apply_properties_update(obj, value, replace=True)
                    else:
                        raise CypherExecutionError(f"Unsupported SET operator: {set_item.operator}")
                else:
                    new_properties = obj.properties.copy()
                    new_properties[prop_name] = value
                    self._apply_properties_update(obj, new_properties, replace=True)

    def _apply_properties_update(self, obj: Any, properties: dict, replace: bool) -> None:
        """Apply property updates to a node or relationship."""
        if not hasattr(obj, 'properties'):
            raise CypherExecutionError("SET target does not have properties")
        if hasattr(obj, 'labels'):
            if replace:
                self.db.replace_node_properties(obj.id, properties)
            else:
                self.db.update_node_properties(obj.id, properties)
            obj.properties = properties
            return
        if hasattr(obj, 'source_id'):
            if replace:
                self.db.replace_relationship_properties(obj.id, properties)
            else:
                self.db.update_relationship_properties(obj.id, properties)
            obj.properties = properties
            return
        raise CypherExecutionError("SET target is not a node or relationship")

    def _execute_load_csv(self, clause: LoadCsvClause, input_results: list[dict]) -> list[dict]:
        """Execute LOAD CSV clause to produce rows."""
        if not input_results:
            input_results = [{}]

        output = []
        for row in input_results:
            evaluator = self._make_evaluator(row)
            source = evaluator.evaluate(clause.source)
            if not isinstance(source, str):
                raise CypherExecutionError("LOAD CSV source must be a string")

            rows = self._read_csv_rows(source, clause.with_headers)
            for csv_row in rows:
                merged = row.copy()
                merged[clause.variable] = csv_row
                output.append(merged)
        return output

    def _read_csv_rows(self, source: str, with_headers: bool) -> list[Any]:
        """Read CSV rows from a URL or local path."""
        if source.startswith("http://") or source.startswith("https://"):
            with urllib.request.urlopen(source) as response:
                data = response.read().decode("utf-8")
            handle = io.StringIO(data)
            return self._parse_csv(handle, with_headers)

        if source.startswith("file://"):
            source = source[len("file://"):]
        if not os.path.exists(source):
            raise CypherExecutionError(f"LOAD CSV file not found: {source}")
        with open(source, "r", encoding="utf-8") as handle:
            data = handle.read()
        return self._parse_csv(io.StringIO(data), with_headers)

    def _parse_csv(self, handle, with_headers: bool) -> list[Any]:
        if with_headers:
            reader = csv.DictReader(handle)
            cleaned_rows = []
            for row in reader:
                cleaned = {key: value for key, value in row.items() if isinstance(key, str)}
                cleaned_rows.append(cleaned)
            return cleaned_rows
        reader = csv.reader(handle)
        return [list(row) for row in reader]

    def _execute_remove(self, matches: list[dict], remove_clause) -> None:
        """Execute REMOVE clause to remove properties or labels from nodes.

        Args:
            matches: List of variable bindings
            remove_clause: RemoveClause AST node

        Supports:
            REMOVE n.property  - Remove a property
            REMOVE n:Label     - Remove a label
        """
        for match in matches:
            for remove_item in remove_clause.items:
                var_name = remove_item.variable

                if var_name not in match:
                    raise CypherExecutionError(f"Variable '{var_name}' not found for REMOVE")

                obj = match[var_name]

                if not hasattr(obj, 'labels'):  # Must be a Node
                    raise CypherExecutionError(
                        f"REMOVE is only supported for nodes, not relationships"
                    )

                if remove_item.property:
                    # Remove property: REMOVE n.age
                    prop_name = remove_item.property

                    # Check if property exists
                    if prop_name not in obj.properties:
                        # Property doesn't exist - silently continue (Neo4j behavior)
                        continue

                    # Remove from properties dict
                    new_properties = obj.properties.copy()
                    del new_properties[prop_name]

                    # Update in database (direct SQL since update_node_properties does merge)
                    properties_json = orjson.dumps(new_properties).decode('utf-8')
                    self.db.conn.execute(
                        "UPDATE nodes SET properties = ? WHERE id = ?",
                        (properties_json, obj.id)
                    )
                    if not self.db._in_transaction:
                        self.db.conn.commit()

                    # Update object in memory
                    obj.properties = new_properties

                elif remove_item.label:
                    # Remove label: REMOVE n:OldLabel
                    label_name = remove_item.label

                    # Check if label exists
                    if label_name not in obj.labels:
                        # Label doesn't exist - silently continue (Neo4j behavior)
                        continue

                    # Remove label using database API
                    self.db.remove_labels(obj.id, [label_name])
                    # Update object in memory
                    obj.labels = [l for l in obj.labels if l != label_name]

                else:
                    raise CypherExecutionError(
                        f"REMOVE item must have either property or label"
                    )

    def _apply_order_by(self, matches: list[dict], order_by_clause) -> list[dict]:
        """Apply ORDER BY clause to sort results.

        Args:
            matches: List of result dictionaries
            order_by_clause: OrderByClause AST node

        Returns:
            Sorted list of results
        """
        def get_sort_key(match):
            """Generate sort key tuple for a match."""
            keys = []
            for item in order_by_clause.items:
                # Evaluate the expression for this match
                evaluator = self._make_evaluator(match)
                try:
                    value = evaluator.evaluate(item.expression)
                    # Handle None values (sort to end)
                    if value is None:
                        # Use a large value for None so it sorts to the end
                        value = (float('inf'),)
                    else:
                        # For DESC, negate numeric values or use reverse wrapper
                        if not item.ascending:
                            # Wrap value so it sorts in reverse
                            if isinstance(value, (int, float)):
                                value = (-value,)
                            else:
                                # For strings, we can't easily negate, so use a wrapper
                                value = (ReverseWrapper(value),)
                        else:
                            value = (value,)
                    keys.append(value)
                except:
                    # If evaluation fails, treat as None (end of list)
                    keys.append((float('inf'),))
            return tuple(keys)

        # Sort without reverse - direction is handled in the key
        sorted_matches = sorted(matches, key=get_sort_key)

        return sorted_matches

    def _execute_with(self, clause: WithClause, input_results: list[dict]) -> list[dict]:
        """Execute WITH clause as a pipeline stage.

        Args:
            clause: WithClause AST node
            input_results: Results from previous stage

        Returns:
            Transformed/filtered results

        The WITH clause:
        1. Projects specific items from input (like RETURN)
        2. Can apply WHERE filter
        3. Can apply ORDER BY, SKIP, LIMIT
        4. Results pass to next stage
        """
        if not input_results:
            return []

        has_aggregation = any(
            isinstance(item.expression, FunctionCall)
            for item in clause.items
        )

        # Apply WHERE against the full input rows to allow aliases in WITH
        if clause.where_clause:
            filtered_input = []
            for match in input_results:
                evaluator = self._make_evaluator(match)
                try:
                    if evaluator.evaluate(clause.where_clause.condition):
                        filtered_input.append(match)
                except:
                    pass
            input_results = filtered_input

        if has_aggregation:
            result = {}
            for item in clause.items:
                if isinstance(item.expression, FunctionCall):
                    value = self._calculate_aggregation(
                        item.expression.function_name,
                        item.expression.arguments,
                        input_results,
                        item.expression.distinct,
                        item.expression.star
                    )
                else:
                    evaluator = self._make_evaluator(input_results[0])
                    value = evaluator.evaluate(item.expression)

                if item.alias:
                    result[item.alias] = value
                elif isinstance(item.expression, FunctionCall):
                    distinct_prefix = "DISTINCT " if item.expression.distinct else ""
                    if item.expression.star:
                        key = f"{item.expression.function_name}({distinct_prefix}*)"
                    elif item.expression.arguments and isinstance(item.expression.arguments[0], PropertyAccess):
                        arg = item.expression.arguments[0]
                        key = f"{item.expression.function_name}({distinct_prefix}{arg.variable}.{arg.property})"
                    else:
                        key = f"{item.expression.function_name}({distinct_prefix}...)"
                    result[key] = value
                else:
                    result[str(item.expression)] = value

            projected_results = [result]
        else:
            projected_results = []
            for match in input_results:
                result = {}
                for item in clause.items:
                    evaluator = self._make_evaluator(match)

                    if isinstance(item.expression, (PropertyAccess, PropertyLookup)):
                        value = evaluator.evaluate(item.expression)
                    elif isinstance(item.expression, Variable):
                        var_name = item.expression.name
                        value = match.get(var_name)
                    else:
                        value = evaluator.evaluate(item.expression)

                    if item.alias:
                        result[item.alias] = value
                    elif isinstance(item.expression, (PropertyAccess, PropertyLookup)):
                        key = self._format_property_key(item.expression)
                        result[key] = value
                    elif isinstance(item.expression, Variable):
                        result[item.expression.name] = value
                    else:
                        result[str(item.expression)] = value

                projected_results.append(result)

        if clause.distinct:
            projected_results = self._apply_distinct(projected_results)

        if clause.order_by_clause:
            projected_results = self._apply_order_by(projected_results, clause.order_by_clause)

        if clause.skip_clause:
            projected_results = projected_results[clause.skip_clause.count:]

        if clause.limit_clause:
            projected_results = projected_results[:clause.limit_clause.count]

        if clause.return_clause:
            projected_results = self._apply_normal_return(projected_results, clause.return_clause)

        return projected_results

    def _execute_create_index(self, clause: CreateIndexClause) -> list[dict]:
        """Execute CREATE INDEX clause."""
        if clause.entity == "node":
            name = self.db.create_node_index(clause.label_or_type, clause.property, unique=clause.unique)
        else:
            name = self.db.create_relationship_index(clause.label_or_type, clause.property, unique=clause.unique)
        return [{"name": name}]

    def _execute_drop_index(self, clause: DropIndexClause) -> list[dict]:
        """Execute DROP INDEX clause."""
        self.db.drop_index(clause.name)
        return []

    def _execute_show_indexes(self, clause: ShowIndexesClause) -> list[dict]:
        """Execute SHOW INDEXES clause."""
        indexes = self.db.list_indexes()
        if clause.where_expr is None:
            return indexes
        filtered = []
        for index in indexes:
            evaluator = self._make_evaluator(index)
            try:
                if evaluator.evaluate(clause.where_expr):
                    filtered.append(index)
            except CypherExecutionError:
                continue
        return filtered

    def _execute_create_constraint(self, clause: CreateConstraintClause) -> list[dict]:
        """Execute CREATE CONSTRAINT clause."""
        if clause.constraint_type == "UNIQUE":
            if clause.entity == "node":
                name = self.db.create_node_uniqueness_constraint(
                    clause.label_or_type, clause.property, clause.name, clause.if_not_exists
                )
            else:
                name = self.db.create_relationship_uniqueness_constraint(
                    clause.label_or_type, clause.property, clause.name, clause.if_not_exists
                )
        elif clause.constraint_type == "EXISTS":
            if clause.entity == "node":
                name = self.db.create_node_existence_constraint(
                    clause.label_or_type, clause.property, clause.name, clause.if_not_exists
                )
            else:
                name = self.db.create_relationship_existence_constraint(
                    clause.label_or_type, clause.property, clause.name, clause.if_not_exists
                )
        else:
            if clause.entity == "node":
                name = self.db.create_node_type_constraint(
                    clause.label_or_type, clause.property, clause.type_name or "", clause.name, clause.if_not_exists
                )
            else:
                name = self.db.create_relationship_type_constraint(
                    clause.label_or_type, clause.property, clause.type_name or "", clause.name, clause.if_not_exists
                )
        return [{"name": name}]

    def _execute_drop_constraint(self, clause: DropConstraintClause) -> list[dict]:
        """Execute DROP CONSTRAINT clause."""
        self.db.drop_constraint(clause.name, clause.if_exists)
        return []

    def _execute_show_constraints(self, clause: ShowConstraintsClause) -> list[dict]:
        """Execute SHOW CONSTRAINTS clause."""
        constraints = self.db.list_constraints()
        if clause.where_expr is None:
            return constraints
        filtered = []
        for constraint in constraints:
            evaluator = self._make_evaluator(constraint)
            try:
                if evaluator.evaluate(clause.where_expr):
                    filtered.append(constraint)
            except CypherExecutionError:
                continue
        return filtered

    def _execute_foreach(self, clause: ForeachClause, input_results: list[dict]) -> list[dict]:
        """Execute FOREACH clause for updates."""
        if not input_results:
            input_results = [{}]

        for row in input_results:
            evaluator = self._make_evaluator(row)
            values = evaluator.evaluate(clause.list_expr)
            if values is None:
                values = []
            if not isinstance(values, (list, tuple)):
                raise CypherExecutionError("FOREACH list expression must be a list")
            for item in values:
                local_row = row.copy()
                local_row[clause.variable] = item
                for action in clause.actions:
                    if isinstance(action, CreateClause):
                        created = self._execute_create(action, context=[local_row])
                        if created:
                            local_row.update(created[0])
                    elif isinstance(action, MergeClause):
                        merged = self._execute_merge(action, context=[local_row])
                        if merged:
                            local_row.update(merged[0])
                    elif isinstance(action, SetClause):
                        self._execute_set([local_row], action)
                    elif isinstance(action, RemoveClause):
                        self._execute_remove([local_row], action)
                    elif isinstance(action, DeleteClause):
                        self._execute_delete([local_row], action)
                    else:
                        raise CypherExecutionError(
                            f"Unsupported FOREACH action: {type(action)}"
                        )

        return input_results

    # =========================================================================
    # Dump / Restore
    # =========================================================================

    def dump(self, file_path: str) -> None:
        """Dump the entire database to a Cypher script file.

        The generated script uses a temporary `_dump_id` property on nodes
        to link relationships during restore. This property is removed at
        the end of the script.

        Args:
            file_path: Path to the output .cypher file.
        """
        with open(file_path, "w", encoding="utf-8") as f:
            f.write("// Grafito Database Dump\n")
            f.write("// Generated automatically - do not edit manually\n\n")

            # Constraints
            constraints = self.db.list_constraints()
            if constraints:
                f.write("// Constraints\n")
                for c in constraints:
                    entity = c["entity"]
                    label_or_type = c["label_or_type"]
                    prop = c["property"]
                    ctype = c["type"]
                    type_name = c.get("type_name")

                    if entity == "node":
                        pattern = f"(n:{label_or_type})"
                        require_expr = f"n.{prop}"
                    else:
                        pattern = f"()-[r:{label_or_type}]-()"
                        require_expr = f"r.{prop}"

                    if ctype == "UNIQUE":
                        f.write(f"CREATE CONSTRAINT FOR {pattern} REQUIRE {require_expr} IS UNIQUE;\n")
                    elif ctype == "EXISTS":
                        f.write(f"CREATE CONSTRAINT FOR {pattern} REQUIRE {require_expr} IS NOT NULL;\n")
                    elif ctype == "TYPE" and type_name:
                        f.write(f"CREATE CONSTRAINT FOR {pattern} REQUIRE {require_expr} IS {type_name};\n")
                f.write("\n")

            # Indexes
            indexes = self.db.list_indexes()
            if indexes:
                f.write("// Indexes\n")
                for idx in indexes:
                    entity = idx["entity"]
                    label_or_type = idx["label_or_type"] or "Node"
                    prop = idx["property"]
                    unique = idx.get("unique", False)

                    unique_kw = "UNIQUE " if unique else ""
                    if entity == "node":
                        f.write(f"CREATE {unique_kw}INDEX FOR (n:{label_or_type}) ON (n.{prop});\n")
                    else:
                        f.write(f"CREATE {unique_kw}INDEX FOR ()-[r:{label_or_type}]-() ON (r.{prop});\n")
                f.write("\n")

            # Nodes
            all_nodes = self.db.match_nodes()
            if all_nodes:
                f.write("// Nodes\n")
                for node in all_nodes:
                    labels_str = ":".join(node.labels) if node.labels else ""
                    props = dict(node.properties)
                    props["_dump_id"] = node.id
                    props_str = self._format_properties(props)
                    if labels_str:
                        f.write(f"CREATE (:{labels_str} {props_str});\n")
                    else:
                        f.write(f"CREATE ({props_str});\n")
                f.write("\n")

            # Relationships
            all_rels = self.db.match_relationships()
            if all_rels:
                f.write("// Relationships\n")
                for rel in all_rels:
                    props_str = self._format_properties(rel.properties) if rel.properties else ""
                    rel_part = f"[:{rel.type}]" if not props_str else f"[:{rel.type} {props_str}]"
                    f.write(
                        f"MATCH (a), (b) WHERE a._dump_id = {rel.source_id} AND b._dump_id = {rel.target_id} "
                        f"CREATE (a)-{rel_part}->(b);\n"
                    )
                f.write("\n")

            # Cleanup _dump_id
            if all_nodes:
                f.write("// Cleanup\n")
                f.write("MATCH (n) REMOVE n._dump_id;\n")

    def restore(self, file_path: str, clear_existing: bool = True) -> None:
        """Restore the database from a Cypher script file.

        The script is fully parsed before any data is modified. If parsing
        fails, the database remains unchanged.

        Args:
            file_path: Path to the .cypher file.
            clear_existing: If True, delete all existing data before restore.

        Raises:
            CypherSyntaxError: If any statement in the script is invalid.
        """
        from .lexer import Lexer
        from .parser import Parser

        with open(file_path, "r", encoding="utf-8") as f:
            script = f.read()

        # Split statements
        statements = self.db._split_cypher_statements(script)

        # Parse all statements first (validation)
        parsed = []
        for stmt in statements:
            # Remove comment lines from within the statement
            lines = [line for line in stmt.split('\n') if not line.strip().startswith('//')]
            stmt = '\n'.join(lines).strip()
            if not stmt:
                continue
            lexer = Lexer(stmt)
            tokens = lexer.tokenize()
            parser = Parser(tokens)
            ast = parser.parse()
            parsed.append(ast)

        # Clear existing data if requested
        if clear_existing:
            for rel in self.db.match_relationships():
                self.db.delete_relationship(rel.id)
            for node in self.db.match_nodes():
                self.db.delete_node(node.id)
            for constraint in self.db.list_constraints():
                self.db.drop_constraint(constraint["name"], if_exists=True)
            for idx in self.db.list_indexes():
                self.db.drop_index(idx["name"])

        # Execute parsed statements
        for ast in parsed:
            self.execute(ast)

    def _format_properties(self, props: dict) -> str:
        """Format a properties dict as a Cypher map literal."""
        if not props:
            return "{}"
        parts = []
        for k, v in props.items():
            parts.append(f"{k}: {self._format_value(v)}")
        return "{" + ", ".join(parts) + "}"

    def _format_value(self, value) -> str:
        """Format a Python value as a Cypher literal."""
        if value is None:
            return "null"
        if isinstance(value, bool):
            return "true" if value else "false"
        if isinstance(value, str):
            escaped = value.replace("\\", "\\\\").replace("'", "\\'")
            return f"'{escaped}'"
        if isinstance(value, (int, float)):
            return repr(value)
        if isinstance(value, list):
            items = ", ".join(self._format_value(v) for v in value)
            return f"[{items}]"
        if isinstance(value, dict):
            parts = [f"{k}: {self._format_value(v)}" for k, v in value.items()]
            return "{" + ", ".join(parts) + "}"
        return repr(value)

dump(file_path)

Dump the entire database to a Cypher script file.

The generated script uses a temporary _dump_id property on nodes to link relationships during restore. This property is removed at the end of the script.

Parameters:

Name Type Description Default
file_path str

Path to the output .cypher file.

required
Source code in grafito/cypher/executor.py
def dump(self, file_path: str) -> None:
    """Dump the entire database to a Cypher script file.

    The generated script uses a temporary `_dump_id` property on nodes
    to link relationships during restore. This property is removed at
    the end of the script.

    Args:
        file_path: Path to the output .cypher file.
    """
    with open(file_path, "w", encoding="utf-8") as f:
        f.write("// Grafito Database Dump\n")
        f.write("// Generated automatically - do not edit manually\n\n")

        # Constraints
        constraints = self.db.list_constraints()
        if constraints:
            f.write("// Constraints\n")
            for c in constraints:
                entity = c["entity"]
                label_or_type = c["label_or_type"]
                prop = c["property"]
                ctype = c["type"]
                type_name = c.get("type_name")

                if entity == "node":
                    pattern = f"(n:{label_or_type})"
                    require_expr = f"n.{prop}"
                else:
                    pattern = f"()-[r:{label_or_type}]-()"
                    require_expr = f"r.{prop}"

                if ctype == "UNIQUE":
                    f.write(f"CREATE CONSTRAINT FOR {pattern} REQUIRE {require_expr} IS UNIQUE;\n")
                elif ctype == "EXISTS":
                    f.write(f"CREATE CONSTRAINT FOR {pattern} REQUIRE {require_expr} IS NOT NULL;\n")
                elif ctype == "TYPE" and type_name:
                    f.write(f"CREATE CONSTRAINT FOR {pattern} REQUIRE {require_expr} IS {type_name};\n")
            f.write("\n")

        # Indexes
        indexes = self.db.list_indexes()
        if indexes:
            f.write("// Indexes\n")
            for idx in indexes:
                entity = idx["entity"]
                label_or_type = idx["label_or_type"] or "Node"
                prop = idx["property"]
                unique = idx.get("unique", False)

                unique_kw = "UNIQUE " if unique else ""
                if entity == "node":
                    f.write(f"CREATE {unique_kw}INDEX FOR (n:{label_or_type}) ON (n.{prop});\n")
                else:
                    f.write(f"CREATE {unique_kw}INDEX FOR ()-[r:{label_or_type}]-() ON (r.{prop});\n")
            f.write("\n")

        # Nodes
        all_nodes = self.db.match_nodes()
        if all_nodes:
            f.write("// Nodes\n")
            for node in all_nodes:
                labels_str = ":".join(node.labels) if node.labels else ""
                props = dict(node.properties)
                props["_dump_id"] = node.id
                props_str = self._format_properties(props)
                if labels_str:
                    f.write(f"CREATE (:{labels_str} {props_str});\n")
                else:
                    f.write(f"CREATE ({props_str});\n")
            f.write("\n")

        # Relationships
        all_rels = self.db.match_relationships()
        if all_rels:
            f.write("// Relationships\n")
            for rel in all_rels:
                props_str = self._format_properties(rel.properties) if rel.properties else ""
                rel_part = f"[:{rel.type}]" if not props_str else f"[:{rel.type} {props_str}]"
                f.write(
                    f"MATCH (a), (b) WHERE a._dump_id = {rel.source_id} AND b._dump_id = {rel.target_id} "
                    f"CREATE (a)-{rel_part}->(b);\n"
                )
            f.write("\n")

        # Cleanup _dump_id
        if all_nodes:
            f.write("// Cleanup\n")
            f.write("MATCH (n) REMOVE n._dump_id;\n")

execute(query)

Execute a query and return results.

Parameters:

Name Type Description Default
query Query

Parsed Query AST

required

Returns:

Type Description
list[dict]

List of result dictionaries

Raises:

Type Description
CypherExecutionError

If execution fails

Source code in grafito/cypher/executor.py
def execute(self, query: Query) -> list[dict]:
    """Execute a query and return results.

    Args:
        query: Parsed Query AST

    Returns:
        List of result dictionaries

    Raises:
        CypherExecutionError: If execution fails
    """
    if query.union_clauses:
        return self._execute_union(query)

    if isinstance(query.clause, SubqueryClause):
        return self._execute_subquery(query.clause, [])
    if isinstance(query.clause, ProcedureCallClause):
        return self._execute_procedure_call(query.clause, [])

    # Check if multi-clause query (with WITH)
    if query.clauses:
        return self._execute_multi_clause(query.clauses, initial_results=None)

    # Single clause query
    if isinstance(query.clause, CreateClause):
        return self._execute_create(query.clause)
    elif isinstance(query.clause, MergeClause):
        return self._execute_merge(query.clause)
    elif isinstance(query.clause, MatchClause):
        return self._execute_match(query.clause)
    elif isinstance(query.clause, UnwindClause):
        return self._execute_unwind(query.clause, [{}])
    elif isinstance(query.clause, WithClause):
        return self._execute_with(query.clause, [{}])
    elif isinstance(query.clause, CreateIndexClause):
        return self._execute_create_index(query.clause)
    elif isinstance(query.clause, DropIndexClause):
        return self._execute_drop_index(query.clause)
    elif isinstance(query.clause, ShowIndexesClause):
        return self._execute_show_indexes(query.clause)
    elif isinstance(query.clause, CreateConstraintClause):
        return self._execute_create_constraint(query.clause)
    elif isinstance(query.clause, DropConstraintClause):
        return self._execute_drop_constraint(query.clause)
    elif isinstance(query.clause, ShowConstraintsClause):
        return self._execute_show_constraints(query.clause)
    elif isinstance(query.clause, ForeachClause):
        return self._execute_foreach(query.clause, [{}])
    else:
        raise CypherExecutionError(f"Unknown clause type: {type(query.clause)}")

restore(file_path, clear_existing=True)

Restore the database from a Cypher script file.

The script is fully parsed before any data is modified. If parsing fails, the database remains unchanged.

Parameters:

Name Type Description Default
file_path str

Path to the .cypher file.

required
clear_existing bool

If True, delete all existing data before restore.

True

Raises:

Type Description
CypherSyntaxError

If any statement in the script is invalid.

Source code in grafito/cypher/executor.py
def restore(self, file_path: str, clear_existing: bool = True) -> None:
    """Restore the database from a Cypher script file.

    The script is fully parsed before any data is modified. If parsing
    fails, the database remains unchanged.

    Args:
        file_path: Path to the .cypher file.
        clear_existing: If True, delete all existing data before restore.

    Raises:
        CypherSyntaxError: If any statement in the script is invalid.
    """
    from .lexer import Lexer
    from .parser import Parser

    with open(file_path, "r", encoding="utf-8") as f:
        script = f.read()

    # Split statements
    statements = self.db._split_cypher_statements(script)

    # Parse all statements first (validation)
    parsed = []
    for stmt in statements:
        # Remove comment lines from within the statement
        lines = [line for line in stmt.split('\n') if not line.strip().startswith('//')]
        stmt = '\n'.join(lines).strip()
        if not stmt:
            continue
        lexer = Lexer(stmt)
        tokens = lexer.tokenize()
        parser = Parser(tokens)
        ast = parser.parse()
        parsed.append(ast)

    # Clear existing data if requested
    if clear_existing:
        for rel in self.db.match_relationships():
            self.db.delete_relationship(rel.id)
        for node in self.db.match_nodes():
            self.db.delete_node(node.id)
        for constraint in self.db.list_constraints():
            self.db.drop_constraint(constraint["name"], if_exists=True)
        for idx in self.db.list_indexes():
            self.db.drop_index(idx["name"])

    # Execute parsed statements
    for ast in parsed:
        self.execute(ast)