grafeo-engine 0.5.41

Query engine and database management for Grafeo
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
//! Regression tests inspired by bugs found in other graph databases.
//! Covers MERGE semantics, pattern matching, aggregation edge cases,
//! Unicode handling, and query correctness.
//!
//! ```bash
//! cargo test -p grafeo-engine --test regression_external -- --nocapture
//! ```

use grafeo_common::types::Value;
use grafeo_engine::GrafeoDB;
use grafeo_engine::database::QueryResult;

fn db() -> GrafeoDB {
    GrafeoDB::new_in_memory()
}

// ============================================================================
// MERGE + UNWIND tuple count
// MERGE in a loop should return one row per input tuple, even when
// the node already exists after the first iteration.
// ============================================================================

mod merge_unwind {
    use super::*;

    #[test]
    fn unwind_merge_returns_one_row_per_input() {
        let db = db();
        let s = db.session();
        // Three inputs, all the same value: MERGE creates one node,
        // but must still produce 3 output rows.
        let r = s
            .execute("UNWIND [1, 1, 1] AS i MERGE (:Item {val: i}) RETURN i")
            .unwrap();
        assert_eq!(r.row_count(), 3, "MERGE must emit one row per UNWIND input");
    }

    #[test]
    fn unwind_merge_creates_single_node() {
        let db = db();
        let s = db.session();
        s.execute("UNWIND [1, 1, 1] AS i MERGE (:Item {val: i})")
            .unwrap();
        let r = s.execute("MATCH (n:Item) RETURN count(n) AS cnt").unwrap();
        assert_eq!(
            r.rows()[0][0],
            Value::Int64(1),
            "MERGE with duplicate values should create only one node"
        );
    }

    #[test]
    fn unwind_merge_distinct_values_create_multiple() {
        let db = db();
        let s = db.session();
        s.execute("UNWIND [1, 2, 3] AS i MERGE (:Item {val: i})")
            .unwrap();
        let r = s.execute("MATCH (n:Item) RETURN count(n) AS cnt").unwrap();
        assert_eq!(
            r.rows()[0][0],
            Value::Int64(3),
            "MERGE with distinct values should create three nodes"
        );
    }

    #[test]
    fn unwind_merge_mixed_creates_and_matches() {
        let db = db();
        let s = db.session();
        // Pre-create one node
        s.execute("INSERT (:Item {val: 2})").unwrap();
        // UNWIND includes existing (2) and new (1, 3)
        s.execute("UNWIND [1, 2, 3] AS i MERGE (:Item {val: i})")
            .unwrap();
        let r = s.execute("MATCH (n:Item) RETURN count(n) AS cnt").unwrap();
        assert_eq!(
            r.rows()[0][0],
            Value::Int64(3),
            "MERGE should create 2 new nodes and match 1 existing"
        );
    }

    #[test]
    fn unwind_merge_on_create_on_match_set() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Item {val: 1, status: 'old'})").unwrap();
        s.execute(
            "UNWIND [1, 2] AS i \
             MERGE (n:Item {val: i}) \
             ON CREATE SET n.status = 'new' \
             ON MATCH SET n.status = 'updated'",
        )
        .unwrap();

        let r = s
            .execute("MATCH (n:Item) RETURN n.val, n.status ORDER BY n.val")
            .unwrap();
        assert_eq!(r.row_count(), 2);
        // val=1 was matched, so status should be 'updated'
        assert_eq!(r.rows()[0][0], Value::Int64(1));
        assert_eq!(r.rows()[0][1], Value::String("updated".into()));
        // val=2 was created, so status should be 'new'
        assert_eq!(r.rows()[1][0], Value::Int64(2));
        assert_eq!(r.rows()[1][1], Value::String("new".into()));
    }
}

// ============================================================================
// MERGE with composite keys
// ============================================================================

mod merge_composite_keys {
    use super::*;

    #[test]
    fn merge_two_property_key_no_duplicate() {
        let db = db();
        let s = db.session();
        s.execute("MERGE (:City {name: 'Amsterdam', country: 'NL'})")
            .unwrap();
        s.execute("MERGE (:City {name: 'Amsterdam', country: 'NL'})")
            .unwrap();
        let r = s.execute("MATCH (n:City) RETURN count(n) AS cnt").unwrap();
        assert_eq!(
            r.rows()[0][0],
            Value::Int64(1),
            "Identical composite key should not create duplicate"
        );
    }

    #[test]
    fn merge_partial_match_creates_new() {
        let db = db();
        let s = db.session();
        s.execute("MERGE (:City {name: 'Amsterdam', country: 'NL'})")
            .unwrap();
        // Same name, different country: should create a new node
        s.execute("MERGE (:City {name: 'Amsterdam', country: 'US'})")
            .unwrap();
        let r = s.execute("MATCH (n:City) RETURN count(n) AS cnt").unwrap();
        assert_eq!(
            r.rows()[0][0],
            Value::Int64(2),
            "Partial composite match should create a new node"
        );
    }

    #[test]
    fn merge_three_property_key() {
        let db = db();
        let s = db.session();
        s.execute("MERGE (:Place {city: 'Berlin', country: 'DE', district: 'Mitte'})")
            .unwrap();
        s.execute("MERGE (:Place {city: 'Berlin', country: 'DE', district: 'Mitte'})")
            .unwrap();
        s.execute("MERGE (:Place {city: 'Berlin', country: 'DE', district: 'Kreuzberg'})")
            .unwrap();
        let r = s.execute("MATCH (n:Place) RETURN count(n) AS cnt").unwrap();
        assert_eq!(
            r.rows()[0][0],
            Value::Int64(2),
            "Three-property MERGE: identical creates 1, different district creates 2"
        );
    }
}

// ============================================================================
// Relationship isomorphism
// The same relationship variable must bind to the same edge.
// ============================================================================

mod relationship_isomorphism {
    use super::*;

    #[test]
    fn two_hop_pattern_no_edge_reuse() {
        // In a triangle A->B->C->A, a two-hop pattern (a)-[r1]->(b)-[r2]->(c)
        // should never have r1 == r2.
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {name: 'Alix'})-[:R]->(:N {name: 'Gus'})")
            .unwrap();
        s.execute(
            "MATCH (a:N {name: 'Gus'}), (b:N {name: 'Alix'}) \
             CREATE (a)-[:R]->(n:N {name: 'Vincent'})-[:R]->(b)",
        )
        .unwrap();
        // Count two-hop paths: should be 3 edges forming specific paths
        let r = s
            .execute(
                "MATCH (a:N)-[r1:R]->(b:N)-[r2:R]->(c:N) \
                 RETURN count(*) AS cnt",
            )
            .unwrap();
        let cnt = &r.rows()[0][0];
        // Triangle: Alix->Gus->Vincent->Alix gives exactly 3 two-hop paths.
        assert_eq!(
            *cnt,
            Value::Int64(3),
            "Triangle should yield exactly 3 two-hop paths"
        );
    }

    #[test]
    fn single_edge_not_matched_twice_in_pattern() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {name: 'Alix'})-[:R]->(:N {name: 'Gus'})")
            .unwrap();
        // Only one edge exists: a two-hop pattern should find 0 paths
        let r = s
            .execute(
                "MATCH (a:N)-[r1:R]->(b:N)-[r2:R]->(c:N) \
                 RETURN count(*) AS cnt",
            )
            .unwrap();
        assert_eq!(
            r.rows()[0][0],
            Value::Int64(0),
            "Single edge cannot satisfy a two-hop pattern"
        );
    }
}

// ============================================================================
// OPTIONAL MATCH order independence
// ============================================================================

mod optional_match_order {
    use super::*;

    #[test]
    fn swapped_optional_match_same_results() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix'})-[:KNOWS]->(:Person {name: 'Gus'})")
            .unwrap();
        s.execute("INSERT (:Person {name: 'Alix'})-[:WORKS_AT]->(:Company {name: 'Acme'})")
            .unwrap();

        let r1 = s
            .execute(
                "MATCH (p:Person {name: 'Alix'}) \
                 OPTIONAL MATCH (p)-[:KNOWS]->(friend:Person) \
                 OPTIONAL MATCH (p)-[:WORKS_AT]->(co:Company) \
                 RETURN p.name, friend.name, co.name",
            )
            .unwrap();

        // Same query with swapped OPTIONAL MATCH order
        let r2 = s
            .execute(
                "MATCH (p:Person {name: 'Alix'}) \
                 OPTIONAL MATCH (p)-[:WORKS_AT]->(co:Company) \
                 OPTIONAL MATCH (p)-[:KNOWS]->(friend:Person) \
                 RETURN p.name, friend.name, co.name",
            )
            .unwrap();

        assert_eq!(
            r1.row_count(),
            r2.row_count(),
            "Swapping OPTIONAL MATCH order must not change row count"
        );
    }
}

// ============================================================================
// Aggregation inside CALL subqueries
// ============================================================================

mod aggregation_in_subquery {
    use super::*;

    #[test]
    fn count_inside_call_subquery() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix'})").unwrap();
        s.execute("INSERT (:Person {name: 'Gus'})").unwrap();
        s.execute("INSERT (:Person {name: 'Vincent'})").unwrap();

        let r = s
            .execute("CALL { MATCH (n:Person) RETURN count(n) AS cnt } RETURN cnt")
            .unwrap();
        assert_eq!(r.row_count(), 1, "Aggregation in CALL should return 1 row");
        assert_eq!(r.rows()[0][0], Value::Int64(3));
    }
}

// ============================================================================
// COLLECT() completeness
// ============================================================================

mod collect_order {
    use super::*;

    #[test]
    fn collect_returns_all_elements() {
        // Note: GQL does not support `WITH ... ORDER BY` syntax, so we
        // cannot test COLLECT ordering via GQL. This test verifies that
        // COLLECT gathers all values without dropping any.
        // TODO: once WITH ... ORDER BY is supported, add ordering assertion.
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Vincent'})").unwrap();
        s.execute("INSERT (:Person {name: 'Alix'})").unwrap();
        s.execute("INSERT (:Person {name: 'Gus'})").unwrap();
        s.execute("INSERT (:Person {name: 'Jules'})").unwrap();
        s.execute("INSERT (:Person {name: 'Mia'})").unwrap();

        let r = s
            .execute("MATCH (p:Person) RETURN collect(p.name) AS names")
            .unwrap();
        assert_eq!(r.row_count(), 1);
        if let Value::List(names) = &r.rows()[0][0] {
            assert_eq!(names.len(), 5, "COLLECT must gather all 5 names");
            // Verify all names are present (order may vary)
            let name_strs: Vec<String> = names
                .iter()
                .filter_map(|v| match v {
                    Value::String(s) => Some(s.to_string()),
                    _ => None,
                })
                .collect();
            let mut sorted = name_strs.clone();
            sorted.sort();
            assert_eq!(sorted, vec!["Alix", "Gus", "Jules", "Mia", "Vincent"],);
        } else {
            panic!("Expected List, got {:?}", r.rows()[0][0]);
        }
    }
}

// ============================================================================
// GROUP BY expression order independence
// ============================================================================

mod group_by_expression_order {
    use super::*;

    /// Helper: extract a column of string values from query results.
    fn string_column(result: &QueryResult, col: usize) -> Vec<String> {
        result
            .rows()
            .iter()
            .map(|row| match &row[col] {
                Value::String(s) => s.to_string(),
                other => format!("{other:?}"),
            })
            .collect()
    }

    #[test]
    fn return_column_order_does_not_affect_group_by() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix', city: 'Amsterdam'})")
            .unwrap();
        s.execute("INSERT (:Person {name: 'Gus', city: 'Amsterdam'})")
            .unwrap();
        s.execute("INSERT (:Person {name: 'Vincent', city: 'Berlin'})")
            .unwrap();

        // Order 1: city first, then count
        let r1 = s
            .execute(
                "MATCH (p:Person) \
                 RETURN p.city AS city, count(p) AS cnt \
                 ORDER BY city",
            )
            .unwrap();

        // Order 2: count first, then city
        let r2 = s
            .execute(
                "MATCH (p:Person) \
                 RETURN count(p) AS cnt, p.city AS city \
                 ORDER BY city",
            )
            .unwrap();

        assert_eq!(r1.row_count(), r2.row_count(), "Same grouping, same rows");
        // Both should have Amsterdam=2, Berlin=1
        let cities_1 = string_column(&r1, 0);
        let cities_2 = string_column(&r2, 1);
        assert_eq!(cities_1, cities_2, "City grouping should be identical");
    }
}

// ============================================================================
// WHERE filter must not corrupt projected values
// ============================================================================

mod where_filter_and_projection {
    use super::*;

    #[test]
    fn where_is_not_null_preserves_return_value() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Sensor {name: 'Temp', reading: 42.5})")
            .unwrap();
        s.execute("INSERT (:Sensor {name: 'Humidity'})").unwrap();

        let r = s
            .execute(
                "MATCH (s:Sensor) \
                 WHERE s.reading IS NOT NULL \
                 RETURN s.name, s.reading",
            )
            .unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(r.rows()[0][0], Value::String("Temp".into()));
        // The returned value must be the actual reading, NOT boolean true
        assert_eq!(
            r.rows()[0][1],
            Value::Float64(42.5),
            "WHERE IS NOT NULL must not replace the returned value with boolean"
        );
    }
}

// ============================================================================
// SUM overflow / IEEE-754 infinity
// ============================================================================

mod sum_overflow {
    use super::*;

    #[test]
    fn sum_large_floats_returns_infinity() {
        let db = db();
        let s = db.session();
        // Two f64::MAX values should overflow to infinity
        let r = s
            .execute(
                "UNWIND [1.7976931348623157e308, 1.7976931348623157e308] AS val \
                 RETURN SUM(val) AS total",
            )
            .unwrap();
        assert_eq!(r.row_count(), 1);
        match &r.rows()[0][0] {
            Value::Float64(f) => {
                assert!(
                    f.is_infinite() && f.is_sign_positive(),
                    "SUM of two f64::MAX should be +Infinity, got {f}"
                );
            }
            other => panic!("Expected Float64, got {:?}", other),
        }
    }
}

// ============================================================================
// Unicode and emoji in property values
// ============================================================================

mod unicode_emoji {
    use super::*;

    #[test]
    fn emoji_property_value_roundtrip() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Tag {symbol: '\u{1F389}', name: 'party'})") // 🎉
            .unwrap();
        let r = s.execute("MATCH (t:Tag) RETURN t.symbol, t.name").unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(r.rows()[0][0], Value::String("\u{1F389}".into()));
        assert_eq!(r.rows()[0][1], Value::String("party".into()));
    }

    #[test]
    fn cjk_property_value_roundtrip() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:City {name: '\u{6771}\u{4EAC}'})") // 東京
            .unwrap();
        let r = s.execute("MATCH (c:City) RETURN c.name").unwrap();
        assert_eq!(r.rows()[0][0], Value::String("\u{6771}\u{4EAC}".into()));
    }

    #[test]
    fn combining_diacritics_roundtrip() {
        let db = db();
        let s = db.session();
        // e + combining acute accent
        s.execute("INSERT (:Word {text: 'calf\u{0065}\u{0301}'})")
            .unwrap();
        let r = s.execute("MATCH (w:Word) RETURN w.text").unwrap();
        assert_eq!(r.rows()[0][0], Value::String("calf\u{0065}\u{0301}".into()));
    }
}

// ============================================================================
// Self-loop pattern matching
// ============================================================================

mod self_loop {
    use super::*;

    #[test]
    fn create_and_match_self_loop() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (a:Node {name: 'Alix'})-[:SELF]->(a)")
            .unwrap();

        let r = s
            .execute("MATCH (a:Node)-[r:SELF]->(a) RETURN a.name")
            .unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(r.rows()[0][0], Value::String("Alix".into()));
    }

    #[test]
    fn self_loop_not_counted_as_two_edges() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (a:Node {name: 'Alix'})-[:SELF]->(a)")
            .unwrap();

        let r = s
            .execute("MATCH (:Node)-[r:SELF]->() RETURN count(r) AS cnt")
            .unwrap();
        assert_eq!(
            r.rows()[0][0],
            Value::Int64(1),
            "Self-loop should be counted exactly once"
        );
    }
}

// ============================================================================
// Deleted node access in same session
// ============================================================================

mod deleted_node_access {
    use super::*;

    #[test]
    fn delete_then_match_in_same_session() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Temp {name: 'ephemeral'})").unwrap();
        s.execute("MATCH (n:Temp) DELETE n").unwrap();

        let r = s.execute("MATCH (n:Temp) RETURN n.name").unwrap();
        assert_eq!(
            r.row_count(),
            0,
            "Deleted node should not be visible in subsequent MATCH"
        );
    }

    #[test]
    fn detach_delete_clears_edges() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:A {name: 'a'})-[:R]->(:B {name: 'b'})")
            .unwrap();
        s.execute("MATCH (a:A) DETACH DELETE a").unwrap();

        let r = s
            .execute("MATCH ()-[r:R]->() RETURN count(r) AS cnt")
            .unwrap();
        assert_eq!(
            r.rows()[0][0],
            Value::Int64(0),
            "DETACH DELETE should remove all connected edges"
        );
    }
}

// ============================================================================
// Deeply nested map/list properties
// ============================================================================

mod nested_properties {
    use super::*;
    use grafeo_common::types::PropertyKey;
    use std::collections::{BTreeMap, HashMap};

    #[test]
    fn nested_map_roundtrip() {
        let db = db();
        let s = db.session();
        let mut params = HashMap::new();
        // Build a nested map: {b: {c: 42}}
        let mut inner_map = BTreeMap::new();
        inner_map.insert(PropertyKey::new("c"), Value::Int64(42));
        let inner = Value::Map(inner_map.into());

        let mut mid_map = BTreeMap::new();
        mid_map.insert(PropertyKey::new("b"), inner);
        let mid = Value::Map(mid_map.into());
        params.insert("meta".to_string(), mid);

        s.execute_with_params("INSERT (:Data {meta: $meta})", params)
            .unwrap();
        let r = s.execute("MATCH (d:Data) RETURN d.meta").unwrap();
        assert_eq!(r.row_count(), 1);
        // Verify the nested structure survived
        if let Value::Map(outer) = &r.rows()[0][0] {
            let b = outer.get(&PropertyKey::new("b")).expect("Missing key 'b'");
            if let Value::Map(inner_result) = b {
                assert_eq!(
                    inner_result.get(&PropertyKey::new("c")),
                    Some(&Value::Int64(42))
                );
            } else {
                panic!("Expected inner Map, got {:?}", b);
            }
        } else {
            panic!("Expected Map, got {:?}", r.rows()[0][0]);
        }
    }

    #[test]
    fn heterogeneous_list_roundtrip() {
        let db = db();
        let s = db.session();
        let mut params = HashMap::new();
        params.insert(
            "items".to_string(),
            Value::List(
                vec![
                    Value::Int64(1),
                    Value::String("two".into()),
                    Value::Bool(true),
                    Value::Null,
                ]
                .into(),
            ),
        );

        s.execute_with_params("INSERT (:Data {items: $items})", params)
            .unwrap();
        let r = s.execute("MATCH (d:Data) RETURN d.items").unwrap();
        if let Value::List(items) = &r.rows()[0][0] {
            assert_eq!(items.len(), 4);
            assert_eq!(items[0], Value::Int64(1));
            assert_eq!(items[1], Value::String("two".into()));
            assert_eq!(items[2], Value::Bool(true));
            assert_eq!(items[3], Value::Null);
        } else {
            panic!("Expected List, got {:?}", r.rows()[0][0]);
        }
    }
}

// ============================================================================
// Constant folding in WHERE
// ============================================================================

mod constant_folding {
    use super::*;

    #[test]
    fn where_constant_false_returns_empty() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {val: 1})").unwrap();
        let r = s.execute("MATCH (n:N) WHERE 1 = 2 RETURN n").unwrap();
        assert_eq!(
            r.row_count(),
            0,
            "WHERE 1 = 2 should short-circuit to empty"
        );
    }

    #[test]
    fn where_constant_true_returns_all() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {val: 1})").unwrap();
        s.execute("INSERT (:N {val: 2})").unwrap();
        let r = s.execute("MATCH (n:N) WHERE 1 = 1 RETURN n.val").unwrap();
        assert_eq!(r.row_count(), 2, "WHERE 1 = 1 should return all rows");
    }
}

// ============================================================================
// Cyclic graph traversal
// ============================================================================

mod cyclic_traversal {
    use super::*;

    #[test]
    fn variable_length_path_in_triangle_terminates() {
        let db = db();
        let s = db.session();
        // Create triangle: A->B->C->A
        s.execute(
            "INSERT (a:N {name: 'Alix'})-[:R]->(b:N {name: 'Gus'})-[:R]->(c:N {name: 'Vincent'})-[:R]->(a)",
        )
        .unwrap();

        // Variable-length path should terminate even with cycles
        let r = s
            .execute(
                "MATCH (a:N {name: 'Alix'})-[:R*1..5]->(b:N) \
                 RETURN b.name",
            )
            .unwrap();
        // Walk mode on a 3-node directed triangle with one outgoing edge each:
        // exactly 1 path per hop length (1..=5), so exactly 5 rows.
        assert_eq!(
            r.row_count(),
            5,
            "Expected exactly 5 paths (one per hop 1..=5), got {}",
            r.row_count()
        );
    }
}

// ============================================================================
// Concurrent MERGE (stress test)
// ============================================================================

mod concurrent_merge {
    use super::*;

    #[test]
    #[ignore = "stress test: run locally before releases"]
    fn concurrent_merge_no_duplicates() {
        let db = std::sync::Arc::new(db());
        let handles: Vec<_> = (0..10)
            .map(|_| {
                let db = std::sync::Arc::clone(&db);
                std::thread::spawn(move || {
                    let s = db.session();
                    s.execute("MERGE (:Singleton {key: 'only_one'})").unwrap();
                })
            })
            .collect();

        for h in handles {
            h.join().unwrap();
        }

        let s = db.session();
        let r = s
            .execute("MATCH (n:Singleton) RETURN count(n) AS cnt")
            .unwrap();
        assert_eq!(
            r.rows()[0][0],
            Value::Int64(1),
            "Concurrent MERGE should produce exactly 1 node"
        );
    }
}

// ============================================================================
// MERGE with NULL node reference
// ============================================================================

mod merge_null_node_reference {
    use super::*;

    #[test]
    fn merge_relationship_with_null_source_errors() {
        let db = db();
        let s = db.session();
        // OPTIONAL MATCH that matches nothing produces NULL for n
        let result = s.execute(
            "OPTIONAL MATCH (n:NonExistent) \
             MERGE (n)-[:R]->(m:Target {name: 'Alix'})",
        );
        assert!(
            result.is_err(),
            "MERGE with NULL node reference should error, got: {result:?}"
        );
    }

    #[test]
    fn merge_relationship_with_null_target_errors() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Source {name: 'Gus'})").unwrap();
        let result = s.execute(
            "MATCH (a:Source {name: 'Gus'}) \
             OPTIONAL MATCH (b:NonExistent) \
             MERGE (a)-[:R]->(b)",
        );
        assert!(
            result.is_err(),
            "MERGE with NULL target node reference should error"
        );
    }

    #[test]
    fn merge_with_valid_optional_match_succeeds() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Vincent'})").unwrap();
        // OPTIONAL MATCH that actually finds something: MERGE should work
        let result = s.execute(
            "MATCH (n:Person {name: 'Vincent'}) \
             MERGE (n)-[:KNOWS]->(m:Person {name: 'Jules'})",
        );
        assert!(
            result.is_ok(),
            "MERGE with non-null node should succeed: {result:?}"
        );
        // Verify the relationship was actually created.
        let check = s
            .execute(
                "MATCH (v:Person {name: 'Vincent'})-[:KNOWS]->(j:Person {name: 'Jules'}) RETURN j.name",
            )
            .unwrap();
        assert_eq!(check.row_count(), 1);
        assert_eq!(check.rows()[0][0], Value::String("Jules".into()));
    }

    #[test]
    fn standalone_merge_unaffected() {
        let db = db();
        let s = db.session();
        let result = s
            .execute("MERGE (:Person {name: 'Mia'}) RETURN 1 AS ok")
            .unwrap();
        assert_eq!(result.row_count(), 1);
        assert_eq!(result.rows()[0][0], Value::Int64(1));
    }
}

mod distinct_edges {
    use super::*;

    /// Regression: DISTINCT on edge result columns must deduplicate by edge identity,
    /// not by debug-format string. Edges are stored as Int64(edge_id) in execution
    /// columns, so the DistinctOperator's Int64 arm handles them correctly.
    #[test]
    fn distinct_on_edges_deduplicates_correctly() {
        let db = db();
        let s = db.session();
        // Create two nodes with a single edge between them
        s.execute("INSERT (:Person {name: 'Alix'})").unwrap();
        s.execute("INSERT (:Person {name: 'Gus'})").unwrap();
        s.execute(
            "MATCH (a:Person {name: 'Alix'}), (b:Person {name: 'Gus'}) \
             INSERT (a)-[:KNOWS]->(b)",
        )
        .unwrap();

        // Cartesian product of nodes produces duplicate edge references;
        // DISTINCT should collapse them to exactly one row.
        let result = s
            .execute(
                "MATCH (a:Person), (b:Person) \
                 MATCH (a)-[e:KNOWS]->(b) \
                 RETURN DISTINCT e",
            )
            .unwrap();
        assert_eq!(
            result.rows().len(),
            1,
            "DISTINCT e should return exactly one row, got: {}",
            result.rows().len()
        );
    }

    #[test]
    fn distinct_on_edges_multiple_edge_types() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Vincent'})").unwrap();
        s.execute("INSERT (:Person {name: 'Jules'})").unwrap();
        s.execute("INSERT (:Person {name: 'Mia'})").unwrap();
        s.execute(
            "MATCH (a:Person {name: 'Vincent'}), (b:Person {name: 'Jules'}) \
             INSERT (a)-[:KNOWS]->(b)",
        )
        .unwrap();
        s.execute(
            "MATCH (a:Person {name: 'Jules'}), (b:Person {name: 'Mia'}) \
             INSERT (a)-[:KNOWS]->(b)",
        )
        .unwrap();

        // MATCH all edges of type KNOWS and return them with DISTINCT
        let result = s
            .execute("MATCH ()-[e:KNOWS]->() RETURN DISTINCT e")
            .unwrap();
        assert_eq!(
            result.rows().len(),
            2,
            "DISTINCT should return both edges, got: {}",
            result.rows().len()
        );
    }
}

mod call_block_scope {
    use super::*;

    /// Regression item 14: variables bound inside one CALL block must not be
    /// visible inside a sibling CALL block. The binder previously used a single
    /// global BindingContext, so a variable from CALL block 1 leaked into CALL
    /// block 2, making it appear to be in scope when it was not.
    ///
    /// This test verifies the binder correctly accepts a query with sibling CALL
    /// blocks that compose independent output columns.
    #[test]
    fn sibling_call_block_outputs_are_in_scope_for_return() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix', age: 30})")
            .unwrap();
        s.execute("INSERT (:Person {name: 'Gus', age: 25})")
            .unwrap();

        // Two independent CALL blocks: their output columns (age_a, age_b) must
        // both be visible to the outer RETURN. The binder should accept this query.
        let result = s.execute(
            "CALL { MATCH (a:Person {name: 'Alix'}) RETURN a.age AS age_a } \
             CALL { MATCH (b:Person {name: 'Gus'}) RETURN b.age AS age_b } \
             RETURN age_a, age_b",
        );
        let result = result.expect("sibling CALL outputs should be accessible in outer RETURN");
        assert_eq!(result.rows()[0][0], Value::Int64(30)); // age_a
        assert_eq!(result.rows()[0][1], Value::Int64(25)); // age_b
    }

    /// Internal variable `a` from CALL block 1 must not be visible in CALL block 2.
    /// If scope isolation is working, the second CALL cannot reference `a`.
    #[test]
    fn internal_variable_from_first_call_is_not_visible_in_second_call() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix'})").unwrap();
        s.execute("INSERT (:Person {name: 'Gus'})").unwrap();

        // The second CALL references `a`, which is internal to the first CALL.
        // With correct scope isolation this should fail with an undefined-variable error.
        let result = s.execute(
            "CALL { MATCH (a:Person) RETURN a.name AS name_a } \
             CALL { MATCH (b:Person) WHERE b.name = a.name RETURN b } \
             RETURN name_a",
        );
        assert!(
            result.is_err(),
            "second CALL referencing internal var of first CALL should fail, got: {result:?}"
        );
    }

    /// Same-named variables in sibling CALL blocks should not conflict.
    /// Each block defines its own `n`, but exports under different aliases.
    #[test]
    fn same_variable_name_in_sibling_calls_is_independent() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix'})").unwrap();
        s.execute("INSERT (:Company {name: 'TechCorp'})").unwrap();

        let result = s
            .execute(
                "CALL { MATCH (n:Person) RETURN n.name AS person_name } \
                 CALL { MATCH (n:Company) RETURN n.name AS company_name } \
                 RETURN person_name, company_name",
            )
            .unwrap();
        assert_eq!(result.row_count(), 1);
        assert_eq!(result.rows()[0][0], Value::String("Alix".into()));
        assert_eq!(result.rows()[0][1], Value::String("TechCorp".into()));
    }

    /// SUM aggregation inside a CALL subquery should produce a single row
    /// with the correct total.
    #[test]
    fn sum_inside_call_subquery_returns_single_row() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix', age: 30})")
            .unwrap();
        s.execute("INSERT (:Person {name: 'Gus', age: 25})")
            .unwrap();
        s.execute("INSERT (:Person {name: 'Vincent', age: 40})")
            .unwrap();

        let result = s
            .execute("CALL { MATCH (n:Person) RETURN sum(n.age) AS total } RETURN total")
            .unwrap();
        assert_eq!(result.row_count(), 1);
        assert_eq!(result.rows()[0][0], Value::Int64(95));
    }
}

// ============================================================================
// UNWIND + MERGE + SET: property access on UNWIND variable (#172)
// ============================================================================

#[cfg(feature = "cypher")]
mod unwind_merge_set {
    use super::*;

    /// UNWIND variable property access in SET clause should resolve correctly.
    /// Regression: item.name in SET evaluated to NULL instead of the map value.
    /// GitHub issue #172.
    #[test]
    fn unwind_merge_set_property_from_map() {
        let db = db();
        let s = db.session();

        s.execute_cypher(
            "UNWIND [{qn: 'test://foo', name: 'Foo'}, {qn: 'test://bar', name: 'Bar'}] AS item \
             MERGE (x:Test {qn: item.qn}) \
             SET x.name = item.name",
        )
        .unwrap();

        let result = s
            .execute("MATCH (n:Test) RETURN n.qn AS qn, n.name AS name ORDER BY qn")
            .unwrap();

        assert_eq!(result.row_count(), 2);
        assert_eq!(result.rows()[0][0], Value::String("test://bar".into()));
        assert_eq!(
            result.rows()[0][1],
            Value::String("Bar".into()),
            "SET x.name = item.name should resolve item.name from UNWIND map (#172)"
        );
        assert_eq!(result.rows()[1][0], Value::String("test://foo".into()));
        assert_eq!(result.rows()[1][1], Value::String("Foo".into()));
    }

    /// SET x += item (map merge) should also work with UNWIND variables.
    #[test]
    fn unwind_merge_set_map_merge() {
        let db = db();
        let s = db.session();

        s.execute_cypher(
            "UNWIND [{qn: 'test://baz', name: 'Baz', kind: 'module'}] AS item \
             MERGE (x:Test {qn: item.qn}) \
             SET x += item",
        )
        .unwrap();

        let result = s
            .execute("MATCH (n:Test {qn: 'test://baz'}) RETURN n.name AS name, n.kind AS kind")
            .unwrap();

        assert_eq!(result.row_count(), 1);
        assert_eq!(
            result.rows()[0][0],
            Value::String("Baz".into()),
            "SET x += item should merge all map properties (#172)"
        );
        assert_eq!(result.rows()[0][1], Value::String("module".into()));
    }
}

// ============================================================================
// #187: labels(n) and type(r) fail in aggregation context
// ============================================================================

#[cfg(feature = "cypher")]
mod issue_187_labels_type_aggregation {
    use super::*;

    #[test]
    fn labels_with_count() {
        let db = db();
        let s = db.session();
        s.execute_cypher(
            "CREATE (:Class {name: 'A'}), (:Class {name: 'B'}), (:Method {name: 'C'})",
        )
        .unwrap();

        let result = s
            .execute_cypher(
                "MATCH (n) RETURN labels(n)[0] AS label, count(n) AS cnt ORDER BY label",
            )
            .unwrap();

        assert_eq!(
            result.row_count(),
            2,
            "Should have two groups: Class and Method"
        );
        assert_eq!(result.rows()[0][0], Value::String("Class".into()));
        assert_eq!(result.rows()[0][1], Value::Int64(2));
        assert_eq!(result.rows()[1][0], Value::String("Method".into()));
        assert_eq!(result.rows()[1][1], Value::Int64(1));
    }

    #[test]
    fn type_with_count() {
        let db = db();
        let s = db.session();
        s.execute_cypher(
            "CREATE (a:A), (b:B), (c:C), (a)-[:CALLS]->(b), (a)-[:CALLS]->(c), (b)-[:IMPORTS]->(c)",
        )
        .unwrap();

        let result = s
            .execute_cypher(
                "MATCH ()-[r]->() RETURN type(r) AS edge_type, count(r) AS cnt ORDER BY edge_type",
            )
            .unwrap();

        assert_eq!(
            result.row_count(),
            2,
            "Should have two groups: CALLS and IMPORTS"
        );
        assert_eq!(result.rows()[0][0], Value::String("CALLS".into()));
        assert_eq!(result.rows()[0][1], Value::Int64(2));
        assert_eq!(result.rows()[1][0], Value::String("IMPORTS".into()));
        assert_eq!(result.rows()[1][1], Value::Int64(1));
    }

    #[test]
    fn labels_without_index_access() {
        let db = db();
        let s = db.session();
        s.execute_cypher("CREATE (:Foo), (:Bar)").unwrap();

        let result = s
            .execute_cypher("MATCH (n) RETURN labels(n) AS lbls, count(n) AS cnt ORDER BY lbls")
            .unwrap();

        assert_eq!(result.row_count(), 2);
        // Each single-label node forms its own group with count 1.
        assert_eq!(result.rows()[0][1], Value::Int64(1));
        assert_eq!(result.rows()[1][1], Value::Int64(1));
    }

    #[test]
    fn order_by_labels() {
        let db = db();
        let s = db.session();
        s.execute_cypher("CREATE (:Zebra {name: 'Z'}), (:Apple {name: 'A'})")
            .unwrap();

        let result = s
            .execute_cypher("MATCH (n) RETURN n.name ORDER BY labels(n)[0]")
            .unwrap();

        assert_eq!(result.row_count(), 2);
        // "Apple" < "Zebra" alphabetically
        assert_eq!(result.rows()[0][0], Value::String("A".into()));
        assert_eq!(result.rows()[1][0], Value::String("Z".into()));
    }

    #[test]
    fn order_by_type() {
        let db = db();
        let s = db.session();
        s.execute_cypher("CREATE (a:X), (b:Y), (c:Z), (a)-[:BETA]->(b), (a)-[:ALPHA]->(c)")
            .unwrap();

        let result = s
            .execute_cypher("MATCH ()-[r]->() RETURN type(r) AS t ORDER BY t")
            .unwrap();

        assert_eq!(result.row_count(), 2);
        assert_eq!(result.rows()[0][0], Value::String("ALPHA".into()));
        assert_eq!(result.rows()[1][0], Value::String("BETA".into()));
    }

    #[test]
    fn gql_labels_with_count() {
        let db = db();
        let s = db.session();
        s.execute(
            "INSERT (:Engineer {name: 'Vincent'}), (:Engineer {name: 'Jules'}), (:Designer {name: 'Mia'})",
        )
        .unwrap();

        let result = s
            .execute("MATCH (n) RETURN labels(n)[0] AS label, count(n) AS cnt ORDER BY label")
            .unwrap();

        assert_eq!(result.row_count(), 2);
        assert_eq!(result.rows()[0][0], Value::String("Designer".into()));
        assert_eq!(result.rows()[0][1], Value::Int64(1));
        assert_eq!(result.rows()[1][0], Value::String("Engineer".into()));
        assert_eq!(result.rows()[1][1], Value::Int64(2));
    }

    #[test]
    fn gql_order_by_labels() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Zebra {name: 'Z'}), (:Apple {name: 'A'})")
            .unwrap();

        let result = s
            .execute("MATCH (n) RETURN n.name ORDER BY labels(n)[0]")
            .unwrap();

        assert_eq!(result.row_count(), 2);
        assert_eq!(result.rows()[0][0], Value::String("A".into()));
        assert_eq!(result.rows()[1][0], Value::String("Z".into()));
    }
}

// ============================================================================
// #187 extended: edge cases for expression-in-aggregation and ORDER BY
// ============================================================================

#[cfg(feature = "cypher")]
mod issue_187_extended {
    use super::*;

    #[test]
    fn labels_with_sum() {
        let db = db();
        let s = db.session();
        s.execute_cypher("CREATE (:Alpha {val: 10}), (:Alpha {val: 20}), (:Beta {val: 5})")
            .unwrap();

        let result = s
            .execute_cypher(
                "MATCH (n) RETURN labels(n)[0] AS label, sum(n.val) AS total ORDER BY label",
            )
            .unwrap();

        assert_eq!(result.row_count(), 2);
        assert_eq!(result.rows()[0][0], Value::String("Alpha".into()));
        assert_eq!(result.rows()[0][1], Value::Int64(30));
        assert_eq!(result.rows()[1][0], Value::String("Beta".into()));
        assert_eq!(result.rows()[1][1], Value::Int64(5));
    }

    #[test]
    fn type_with_collect() {
        let db = db();
        let s = db.session();
        s.execute_cypher(
            "CREATE (a:X), (b:Y), (c:Z), (a)-[:LIKES]->(b), (a)-[:LIKES]->(c), (b)-[:KNOWS]->(c)",
        )
        .unwrap();

        let result = s
            .execute_cypher("MATCH ()-[r]->() RETURN type(r) AS t, collect(r) AS items ORDER BY t")
            .unwrap();

        assert_eq!(result.row_count(), 2, "Two edge types: KNOWS and LIKES");
    }

    #[test]
    fn multi_label_node_group_by() {
        let db = db();
        let s = db.session();
        s.execute_cypher(
            "CREATE (:A:B {name: 'one'}), (:A:B {name: 'two'}), (:C:D {name: 'three'})",
        )
        .unwrap();

        let result = s
            .execute_cypher("MATCH (n) RETURN labels(n) AS lbls, count(n) AS cnt")
            .unwrap();

        assert_eq!(
            result.row_count(),
            2,
            "Expected exactly 2 rows (one per distinct label-set), got {}: {:?}",
            result.row_count(),
            result.rows()
        );
    }

    #[test]
    fn order_by_type_descending() {
        let db = db();
        let s = db.session();
        s.execute_cypher(
            "CREATE (a:X), (b:Y), (c:Z), (a)-[:ALPHA]->(b), (a)-[:GAMMA]->(c), (b)-[:BETA]->(c)",
        )
        .unwrap();

        let result = s
            .execute_cypher("MATCH ()-[r]->() RETURN type(r) AS t ORDER BY t DESC")
            .unwrap();

        assert_eq!(result.row_count(), 3);
        assert_eq!(result.rows()[0][0], Value::String("GAMMA".into()));
        assert_eq!(result.rows()[1][0], Value::String("BETA".into()));
        assert_eq!(result.rows()[2][0], Value::String("ALPHA".into()));
    }

    #[test]
    fn order_by_labels_with_limit() {
        let db = db();
        let s = db.session();
        s.execute_cypher("CREATE (:Zebra {name: 'Z'}), (:Apple {name: 'A'}), (:Mango {name: 'M'})")
            .unwrap();

        let result = s
            .execute_cypher("MATCH (n) RETURN n.name ORDER BY labels(n)[0] LIMIT 1")
            .unwrap();

        assert_eq!(
            result.row_count(),
            1,
            "LIMIT 1 should return exactly one row"
        );
    }

    #[test]
    fn group_by_and_order_by_both_complex() {
        let db = db();
        let s = db.session();
        s.execute_cypher(
            "CREATE (:Engineer {name: 'Vincent'}), (:Engineer {name: 'Jules'}), (:Designer {name: 'Mia'})",
        )
        .unwrap();

        // Both GROUP BY (implicit from labels(n)[0] in RETURN) and ORDER BY use
        // the same complex expression. Each node has exactly one label, so
        // labels(n)[0] is deterministic: exactly 2 groups (Designer, Engineer).
        let result = s
            .execute_cypher(
                "MATCH (n) RETURN labels(n)[0] AS lbl, count(n) AS cnt ORDER BY labels(n)[0]",
            )
            .unwrap();

        assert_eq!(
            result.row_count(),
            2,
            "Should produce exactly 2 rows (Designer, Engineer), got {}",
            result.row_count()
        );
    }

    #[test]
    fn empty_result_group_by_labels() {
        let db = db();
        let s = db.session();

        let result = s
            .execute_cypher("MATCH (n:NonExistent) RETURN labels(n)[0] AS lbl, count(n) AS cnt")
            .unwrap();

        assert_eq!(
            result.row_count(),
            0,
            "No matching nodes should yield zero rows"
        );
    }
}

// The GQL variant of type_with_count (does not require the cypher feature).
mod issue_187_gql_type_with_count {
    use super::*;

    #[test]
    fn gql_type_with_count() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:A)-[:FOLLOWS]->(:B)").unwrap();
        s.execute("INSERT (:C)-[:FOLLOWS]->(:D)").unwrap();
        s.execute("INSERT (:E)-[:BLOCKS]->(:F)").unwrap();

        let result = s
            .execute("MATCH ()-[r]->() RETURN type(r) AS t, count(r) AS cnt ORDER BY t")
            .unwrap();

        assert_eq!(result.row_count(), 2, "Two edge types: BLOCKS and FOLLOWS");
        assert_eq!(result.rows()[0][0], Value::String("BLOCKS".into()));
        assert_eq!(result.rows()[0][1], Value::Int64(1));
        assert_eq!(result.rows()[1][0], Value::String("FOLLOWS".into()));
        assert_eq!(result.rows()[1][1], Value::Int64(2));
    }
}

// ============================================================================
// Integer overflow detection in arithmetic
// Inspired by Neo4j #13674: inconsistent multiplication overflow.
// Each intermediate step must check for overflow, not just final result.
// ============================================================================

mod integer_overflow {
    use super::*;

    #[test]
    fn i64_max_plus_one_overflows() {
        let db = db();
        let s = db.session();
        // i64::MAX + 1 overflows: returns NULL (SQL overflow semantics)
        let r = s.execute("RETURN 9223372036854775807 + 1 AS r").unwrap();
        assert_eq!(
            r.rows()[0][0],
            Value::Null,
            "i64::MAX + 1 should return NULL (overflow)"
        );
    }

    #[test]
    fn i64_min_minus_one_overflows() {
        let db = db();
        let s = db.session();
        let result = s.execute("RETURN -9223372036854775808 - 1 AS r");
        match result {
            Err(_) => {} // Parse error for the literal is also acceptable
            Ok(r) => {
                assert_ne!(
                    r.rows()[0][0],
                    Value::Int64(i64::MAX),
                    "Must not silently wrap i64::MIN - 1 to i64::MAX"
                );
            }
        }
    }

    #[test]
    fn multiplication_intermediate_overflow() {
        let db = db();
        let s = db.session();
        // 100 * 1_000_000_000 = 100_000_000_000 (fits i64)
        // 100_000_000_000 * 100_000_000 = 10^19 (overflows i64)
        let r = s
            .execute("RETURN 100 * 1000000000 * 100000000 AS r")
            .unwrap();
        assert_eq!(
            r.rows()[0][0],
            Value::Null,
            "Intermediate multiplication overflow should return NULL"
        );
    }
}

// ============================================================================
// Variable-length path enumeration
// Inspired by FalkorDB #1450: engine deduplicates endpoint pairs
// instead of enumerating all distinct paths.
// ============================================================================

mod variable_length_path_enumeration {
    use super::*;

    #[test]
    fn diamond_two_hop_enumerates_all_paths() {
        let db = db();
        let s = db.session();
        // Diamond: A->B1->C, A->B2->C (two distinct 2-hop paths)
        s.execute(
            "INSERT (a:N {name: 'Alix'})-[:R]->(b1:N {name: 'Gus'}), \
             (a)-[:R]->(b2:N {name: 'Vincent'}), \
             (b1)-[:R]->(c:N {name: 'Jules'}), \
             (b2)-[:R]->(c)",
        )
        .unwrap();

        // Two distinct 2-hop paths from Alix to Jules
        let r = s
            .execute(
                "MATCH (a:N {name: 'Alix'})-[:R*2]->(c:N {name: 'Jules'}) \
                 RETURN c.name",
            )
            .unwrap();
        assert_eq!(
            r.row_count(),
            2,
            "Diamond graph must yield 2 distinct 2-hop paths, got {}",
            r.row_count()
        );
    }

    #[test]
    fn single_hop_variable_length_matches_direct_edges() {
        let db = db();
        let s = db.session();
        s.execute(
            "INSERT (a:N {name: 'Alix'})-[:R]->(b:N {name: 'Gus'})-[:R]->(c:N {name: 'Vincent'})",
        )
        .unwrap();

        let r = s
            .execute("MATCH (a:N {name: 'Alix'})-[:R*1..1]->(b) RETURN b.name")
            .unwrap();
        assert_eq!(
            r.row_count(),
            1,
            "1..1 hop should match exactly 1 direct neighbor"
        );
        assert_eq!(r.rows()[0][0], Value::String("Gus".into()));
    }

    #[test]
    fn variable_length_path_respects_max_hops() {
        let db = db();
        let s = db.session();
        // Chain: A->B->C->D->E
        s.execute(
            "INSERT (:N {name: 'a'})-[:R]->(:N {name: 'b'})-[:R]->(:N {name: 'c'})-[:R]->(:N {name: 'd'})-[:R]->(:N {name: 'e'})",
        )
        .unwrap();

        let r = s
            .execute("MATCH (a:N {name: 'a'})-[:R*1..2]->(b) RETURN b.name ORDER BY b.name")
            .unwrap();
        assert_eq!(
            r.row_count(),
            2,
            "1..2 hops from 'a' should reach 'b' and 'c'"
        );
    }
}

// ============================================================================
// EXISTS subquery correctness
// Inspired by FalkorDB #1248: EXISTS returns TRUE for nonexistent patterns.
// ============================================================================

mod exists_subquery {
    use super::*;

    #[test]
    fn exists_returns_false_for_missing_pattern() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:User {name: 'Alix'})").unwrap();

        let r = s
            .execute(
                "MATCH (u:User) \
                 RETURN EXISTS { MATCH (u)<-[:AUTH]-(:Identity) } AS has_id",
            )
            .unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(
            r.rows()[0][0],
            Value::Bool(false),
            "EXISTS must return false when no matching pattern exists"
        );
    }

    #[test]
    fn exists_returns_true_for_present_pattern() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:User {name: 'Alix'})<-[:AUTH]-(:Identity {provider: 'github'})")
            .unwrap();

        let r = s
            .execute(
                "MATCH (u:User) \
                 RETURN EXISTS { MATCH (u)<-[:AUTH]-(:Identity) } AS has_id",
            )
            .unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(
            r.rows()[0][0],
            Value::Bool(true),
            "EXISTS must return true when matching pattern exists"
        );
    }

    #[test]
    fn exists_with_label_filter_no_false_positive() {
        let db = db();
        let s = db.session();
        // Create a relationship but with a different label than what EXISTS checks
        s.execute("INSERT (:User {name: 'Gus'})<-[:FOLLOWS]-(:Bot {name: 'bot1'})")
            .unwrap();

        let r = s
            .execute(
                "MATCH (u:User) \
                 RETURN EXISTS { MATCH (u)<-[:AUTH]-(:Identity) } AS has_id",
            )
            .unwrap();
        assert_eq!(r.rows()[0][0], Value::Bool(false));
    }
}

// ============================================================================
// UNWIND NULL produces zero rows
// Inspired by FalkorDB #1031: UNWIND null + subquery executes writes.
// ============================================================================

mod unwind_null {
    use super::*;

    #[test]
    fn unwind_null_produces_zero_rows() {
        let db = db();
        let s = db.session();
        let r = s.execute("UNWIND NULL AS x RETURN x").unwrap();
        assert_eq!(r.row_count(), 0, "UNWIND NULL must produce zero rows");
    }

    #[test]
    fn unwind_empty_list_produces_zero_rows() {
        let db = db();
        let s = db.session();
        let r = s.execute("UNWIND [] AS x RETURN x").unwrap();
        assert_eq!(
            r.row_count(),
            0,
            "UNWIND of empty list must produce zero rows"
        );
    }

    #[test]
    fn unwind_null_does_not_execute_writes() {
        let db = db();
        let s = db.session();
        // UNWIND NULL should produce 0 rows, so INSERT should not execute
        let _ = s.execute("UNWIND NULL AS x INSERT (:Ghost {val: x})");
        let r = s.execute("MATCH (n:Ghost) RETURN count(n) AS cnt").unwrap();
        assert_eq!(
            r.rows()[0][0],
            Value::Int64(0),
            "No nodes should be created when UNWIND produces zero rows"
        );
    }
}

// ============================================================================
// NULL comparison short-circuit in WHERE
// Inspired by Neo4j #13727: WHERE 1 = NULL, WHERE 1 IN [] not optimized.
// Regardless of optimization, the result must be correct (0 rows).
// ============================================================================

mod null_predicate_semantics {
    use super::*;

    #[test]
    fn where_equality_with_null_returns_empty() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {val: 1})").unwrap();
        let r = s.execute("MATCH (n:N) WHERE 1 = NULL RETURN n").unwrap();
        assert_eq!(
            r.row_count(),
            0,
            "WHERE 1 = NULL is UNKNOWN, should filter all rows"
        );
    }

    #[test]
    fn where_in_empty_list_returns_empty() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {val: 1})").unwrap();
        let r = s.execute("MATCH (n:N) WHERE 1 IN [] RETURN n").unwrap();
        assert_eq!(
            r.row_count(),
            0,
            "WHERE 1 IN [] is false, should filter all rows"
        );
    }

    #[test]
    fn null_not_equal_to_null() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {val: 1})").unwrap();
        let r = s.execute("MATCH (n:N) WHERE NULL = NULL RETURN n").unwrap();
        assert_eq!(
            r.row_count(),
            0,
            "NULL = NULL is UNKNOWN (not TRUE), should filter all rows"
        );
    }

    #[test]
    fn null_is_null_returns_true() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {val: 1})").unwrap();
        let r = s
            .execute("MATCH (n:N) WHERE NULL IS NULL RETURN n.val")
            .unwrap();
        assert_eq!(
            r.row_count(),
            1,
            "NULL IS NULL is TRUE, should pass all rows"
        );
    }
}

// ============================================================================
// Predicate rewriting: NOT((a = b) IS NULL)
// Inspired by Neo4j #13642: optimizer conflates IS NOT NULL with equality.
// ============================================================================

mod predicate_rewriting {
    use super::*;

    #[test]
    fn not_is_null_on_comparison_result() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:X {k1: 100})-[:R]->(:Y {k2: 34})")
            .unwrap();

        // (100 = 34) evaluates to false
        // (false IS NULL) evaluates to false
        // NOT(false) evaluates to true
        // So the row should pass the filter
        let r = s
            .execute(
                "MATCH (x:X)-[:R]->(y:Y) \
                 WHERE NOT ((x.k1 = y.k2) IS NULL) \
                 RETURN x.k1, y.k2",
            )
            .unwrap();
        assert_eq!(
            r.row_count(),
            1,
            "NOT((100 = 34) IS NULL) should be TRUE, row must pass filter"
        );
    }

    #[test]
    fn not_is_null_with_null_property() {
        let db = db();
        let s = db.session();
        // y has no k2 property, so y.k2 is NULL
        s.execute("INSERT (:X {k1: 100})-[:R]->(:Y {name: 'test'})")
            .unwrap();

        // (100 = NULL) evaluates to NULL
        // (NULL IS NULL) evaluates to true
        // NOT(true) evaluates to false
        // So the row should be filtered out
        let r = s
            .execute(
                "MATCH (x:X)-[:R]->(y:Y) \
                 WHERE NOT ((x.k1 = y.k2) IS NULL) \
                 RETURN x.k1",
            )
            .unwrap();
        assert_eq!(
            r.row_count(),
            0,
            "NOT((100 = NULL) IS NULL) should be FALSE, row must be filtered"
        );
    }
}

// ============================================================================
// Double-delete idempotency
// Inspired by FalkorDB #1018: phantom edge after repeated deletion.
// ============================================================================

mod double_delete {
    use super::*;

    #[test]
    fn delete_same_node_twice_no_phantom() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Temp {name: 'Alix'})").unwrap();
        s.execute("MATCH (n:Temp) DELETE n").unwrap();
        // Second delete attempt: should either no-op or error, not corrupt state
        let r2 = s.execute("MATCH (n:Temp) DELETE n");
        // Regardless of error/success, no phantom nodes should exist
        if r2.is_err() {
            // Error on second delete is acceptable (already deleted)
        }
        let check = s.execute("MATCH (n) RETURN count(n) AS cnt").unwrap();
        assert_eq!(
            check.rows()[0][0],
            Value::Int64(0),
            "No phantom nodes should remain after double delete"
        );
    }

    #[test]
    fn detach_delete_then_verify_edges_clean() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:A {name: 'a'})-[:R]->(:B {name: 'b'})-[:S]->(:C {name: 'c'})")
            .unwrap();
        s.execute("MATCH (n:A) DETACH DELETE n").unwrap();
        s.execute("MATCH (n:B) DETACH DELETE n").unwrap();
        s.execute("MATCH (n:C) DETACH DELETE n").unwrap();

        let nodes = s.execute("MATCH (n) RETURN count(n) AS cnt").unwrap();
        let edges = s
            .execute("MATCH ()-[r]->() RETURN count(r) AS cnt")
            .unwrap();
        assert_eq!(
            nodes.rows()[0][0],
            Value::Int64(0),
            "All nodes should be gone"
        );
        assert_eq!(
            edges.rows()[0][0],
            Value::Int64(0),
            "All edges should be gone"
        );
    }
}

// ============================================================================
// OPTIONAL MATCH with Cartesian product and rebound variables
// Inspired by FalkorDB #1281: crash on MATCH + OPTIONAL MATCH Cartesian.
// ============================================================================

mod optional_match_cartesian {
    use super::*;

    #[test]
    fn optional_match_rebinds_with_cartesian() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {name: 'Alix'})").unwrap();

        // MATCH (n), (n1) with one node creates a 1x1 Cartesian product
        // OPTIONAL MATCH should not crash
        let r = s.execute(
            "MATCH (n:N), (n1:N) \
             OPTIONAL MATCH (n)-[:R]->(n1) \
             RETURN n.name, n1.name",
        );
        assert!(
            r.is_ok(),
            "OPTIONAL MATCH with Cartesian should not crash: {r:?}"
        );
    }

    #[test]
    fn optional_match_no_match_produces_nulls() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix'})").unwrap();

        let r = s
            .execute(
                "MATCH (p:Person {name: 'Alix'}) \
                 OPTIONAL MATCH (p)-[:WORKS_AT]->(c:Company) \
                 RETURN p.name, c.name",
            )
            .unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(r.rows()[0][0], Value::String("Alix".into()));
        assert_eq!(
            r.rows()[0][1],
            Value::Null,
            "Unmatched OPTIONAL MATCH variable should be NULL"
        );
    }
}

// ============================================================================
// WHERE filter on traversal endpoints
// Inspired by LadybugDB #273: segfault on filtered multi-hop queries.
// ============================================================================

mod where_filter_on_traversal {
    use super::*;

    #[test]
    fn filter_on_destination_property() {
        let db = db();
        let s = db.session();
        s.execute(
            "INSERT (:Person {name: 'Alix'})-[:LIVES_IN]->(:City {name: 'Amsterdam', pop: 900000})",
        )
        .unwrap();
        s.execute(
            "INSERT (:Person {name: 'Gus'})-[:LIVES_IN]->(:City {name: 'Berlin', pop: 3700000})",
        )
        .unwrap();

        let r = s
            .execute(
                "MATCH (p:Person)-[:LIVES_IN]->(c:City) \
                 WHERE c.pop > 1000000 \
                 RETURN p.name, c.name",
            )
            .unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(r.rows()[0][0], Value::String("Gus".into()));
        assert_eq!(r.rows()[0][1], Value::String("Berlin".into()));
    }

    #[test]
    fn filter_on_edge_property() {
        let db = db();
        let s = db.session();
        s.execute(
            "INSERT (:Person {name: 'Alix'})-[:KNOWS {since: 2020}]->(:Person {name: 'Gus'})",
        )
        .unwrap();
        s.execute(
            "INSERT (:Person {name: 'Vincent'})-[:KNOWS {since: 2024}]->(:Person {name: 'Jules'})",
        )
        .unwrap();

        let r = s
            .execute(
                "MATCH (a:Person)-[k:KNOWS]->(b:Person) \
                 WHERE k.since >= 2023 \
                 RETURN a.name, b.name",
            )
            .unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(r.rows()[0][0], Value::String("Vincent".into()));
        assert_eq!(r.rows()[0][1], Value::String("Jules".into()));
    }

    #[test]
    fn filter_on_both_endpoints() {
        let db = db();
        let s = db.session();
        s.execute(
            "INSERT (:Person {name: 'Alix', age: 30})-[:KNOWS]->(:Person {name: 'Gus', age: 25})",
        )
        .unwrap();
        s.execute("INSERT (:Person {name: 'Vincent', age: 40})-[:KNOWS]->(:Person {name: 'Jules', age: 35})")
            .unwrap();

        let r = s
            .execute(
                "MATCH (a:Person)-[:KNOWS]->(b:Person) \
                 WHERE a.age > 35 AND b.age > 30 \
                 RETURN a.name, b.name",
            )
            .unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(r.rows()[0][0], Value::String("Vincent".into()));
        assert_eq!(r.rows()[0][1], Value::String("Jules".into()));
    }
}

// ============================================================================
// Aggregation on empty result set
// Inspired by Neo4j and FalkorDB: aggregate functions over 0 rows.
// ============================================================================

mod empty_aggregation {
    use super::*;

    #[test]
    fn count_on_empty_returns_zero() {
        let db = db();
        let s = db.session();
        let r = s
            .execute("MATCH (n:NonExistent) RETURN count(n) AS cnt")
            .unwrap();
        assert_eq!(
            r.row_count(),
            1,
            "Aggregation over empty set should return 1 row"
        );
        assert_eq!(r.rows()[0][0], Value::Int64(0));
    }

    #[test]
    fn sum_on_empty_returns_null_or_zero() {
        let db = db();
        let s = db.session();
        let r = s
            .execute("MATCH (n:NonExistent) RETURN sum(n.val) AS total")
            .unwrap();
        assert_eq!(r.row_count(), 1);
        // SQL standard: SUM of no rows is NULL. Some engines return 0.
        // Grafeo returns NULL, which is spec-compliant.
        assert!(
            r.rows()[0][0] == Value::Null || r.rows()[0][0] == Value::Int64(0),
            "SUM over empty set should be NULL or 0, got {:?}",
            r.rows()[0][0]
        );
    }

    #[test]
    fn avg_on_empty_returns_null() {
        let db = db();
        let s = db.session();
        let r = s
            .execute("MATCH (n:NonExistent) RETURN avg(n.val) AS average")
            .unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(
            r.rows()[0][0],
            Value::Null,
            "AVG over empty set should return NULL"
        );
    }

    #[test]
    fn min_max_on_empty_returns_null() {
        let db = db();
        let s = db.session();
        let r = s
            .execute("MATCH (n:NonExistent) RETURN min(n.val) AS lo, max(n.val) AS hi")
            .unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(
            r.rows()[0][0],
            Value::Null,
            "MIN over empty set should be NULL"
        );
        assert_eq!(
            r.rows()[0][1],
            Value::Null,
            "MAX over empty set should be NULL"
        );
    }
}

// ============================================================================
// Relationship direction correctness
// Inspired by multiple databases: direction reversal bugs.
// ============================================================================

mod relationship_direction {
    use super::*;

    #[test]
    fn backward_arrow_matches_correct_direction() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:A {name: 'Alix'})-[:FOLLOWS]->(:B {name: 'Gus'})")
            .unwrap();

        // Forward: A->B
        let fwd = s
            .execute("MATCH (a:A)-[:FOLLOWS]->(b:B) RETURN a.name, b.name")
            .unwrap();
        assert_eq!(fwd.row_count(), 1);

        // Backward: B<-A
        let bwd = s
            .execute("MATCH (b:B)<-[:FOLLOWS]-(a:A) RETURN a.name, b.name")
            .unwrap();
        assert_eq!(
            bwd.row_count(),
            1,
            "Backward arrow should match the same edge"
        );

        // Wrong direction: should not match
        let wrong = s
            .execute("MATCH (a:A)<-[:FOLLOWS]-(b:B) RETURN a.name")
            .unwrap();
        assert_eq!(
            wrong.row_count(),
            0,
            "Reversed direction should not match A<-B when edge is A->B"
        );
    }

    #[test]
    fn undirected_match_finds_both_directions() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {name: 'Alix'})-[:KNOWS]->(:N {name: 'Gus'})")
            .unwrap();

        let r = s
            .execute("MATCH (a:N)-[:KNOWS]-(b:N) RETURN a.name, b.name ORDER BY a.name")
            .unwrap();
        assert_eq!(
            r.row_count(),
            2,
            "Undirected pattern should match edge in both directions"
        );
    }
}

// ============================================================================
// MERGE with ON CREATE / ON MATCH and edge patterns
// Inspired by Neo4j #13718 and FalkorDB edge MERGE bugs.
// ============================================================================

mod merge_edge_patterns {
    use super::*;

    #[test]
    fn merge_relationship_creates_when_missing() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix'})").unwrap();
        s.execute("INSERT (:Person {name: 'Gus'})").unwrap();

        s.execute(
            "MATCH (a:Person {name: 'Alix'}), (b:Person {name: 'Gus'}) \
             MERGE (a)-[:KNOWS]->(b)",
        )
        .unwrap();

        let r = s
            .execute("MATCH (:Person)-[k:KNOWS]->(:Person) RETURN count(k) AS cnt")
            .unwrap();
        assert_eq!(r.rows()[0][0], Value::Int64(1));
    }

    #[test]
    fn merge_relationship_does_not_duplicate() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix'})-[:KNOWS]->(:Person {name: 'Gus'})")
            .unwrap();

        // MERGE same pattern: should match, not create a second edge
        s.execute(
            "MATCH (a:Person {name: 'Alix'}), (b:Person {name: 'Gus'}) \
             MERGE (a)-[:KNOWS]->(b)",
        )
        .unwrap();

        let r = s
            .execute("MATCH (:Person)-[k:KNOWS]->(:Person) RETURN count(k) AS cnt")
            .unwrap();
        assert_eq!(
            r.rows()[0][0],
            Value::Int64(1),
            "MERGE should not create duplicate relationship"
        );
    }
}

// ============================================================================
// Delete + re-insert consistency
// Inspired by LadybugDB #180 and #67: data survives delete/re-insert.
// ============================================================================

mod delete_reinsert {
    use super::*;

    #[test]
    fn delete_all_then_reinsert_same_label() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Item {val: 1})").unwrap();
        s.execute("INSERT (:Item {val: 2})").unwrap();
        s.execute("MATCH (n:Item) DELETE n").unwrap();

        // Verify clean slate
        let r = s.execute("MATCH (n:Item) RETURN count(n) AS cnt").unwrap();
        assert_eq!(r.rows()[0][0], Value::Int64(0));

        // Re-insert
        s.execute("INSERT (:Item {val: 10})").unwrap();
        s.execute("INSERT (:Item {val: 20})").unwrap();

        let r2 = s
            .execute("MATCH (n:Item) RETURN n.val ORDER BY n.val")
            .unwrap();
        assert_eq!(r2.row_count(), 2);
        assert_eq!(r2.rows()[0][0], Value::Int64(10));
        assert_eq!(r2.rows()[1][0], Value::Int64(20));
    }

    #[test]
    fn detach_delete_then_reinsert_with_edges() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:A {name: 'a'})-[:R]->(:B {name: 'b'})")
            .unwrap();
        s.execute("MATCH (n) DETACH DELETE n").unwrap();

        // Re-insert
        s.execute("INSERT (:A {name: 'x'})-[:R]->(:B {name: 'y'})")
            .unwrap();

        let nodes = s.execute("MATCH (n) RETURN count(n) AS cnt").unwrap();
        let edges = s
            .execute("MATCH ()-[r]->() RETURN count(r) AS cnt")
            .unwrap();
        assert_eq!(nodes.rows()[0][0], Value::Int64(2));
        assert_eq!(edges.rows()[0][0], Value::Int64(1));
    }
}

// ============================================================================
// Multi-label node operations
// Inspired by various: label handling edge cases.
// ============================================================================

mod multi_label {
    use super::*;

    #[test]
    fn node_with_multiple_labels_matched_by_any() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person:Employee {name: 'Alix'})")
            .unwrap();

        let r1 = s.execute("MATCH (n:Person) RETURN n.name").unwrap();
        assert_eq!(r1.row_count(), 1, "Should match by first label");

        let r2 = s.execute("MATCH (n:Employee) RETURN n.name").unwrap();
        assert_eq!(r2.row_count(), 1, "Should match by second label");
    }

    #[test]
    fn labels_function_returns_all_labels() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person:Employee:Manager {name: 'Alix'})")
            .unwrap();

        let r = s
            .execute("MATCH (n:Person) RETURN labels(n) AS lbls")
            .unwrap();
        assert_eq!(r.row_count(), 1);
        if let Value::List(labels) = &r.rows()[0][0] {
            assert_eq!(labels.len(), 3, "Should have 3 labels");
            let label_strs: Vec<String> = labels
                .iter()
                .filter_map(|v| match v {
                    Value::String(s) => Some(s.to_string()),
                    _ => None,
                })
                .collect();
            assert!(label_strs.contains(&"Person".to_string()));
            assert!(label_strs.contains(&"Employee".to_string()));
            assert!(label_strs.contains(&"Manager".to_string()));
        } else {
            panic!("Expected List, got {:?}", r.rows()[0][0]);
        }
    }
}

// ============================================================================
// Property type coercion and comparison
// Inspired by multiple databases: type handling edge cases.
// ============================================================================

mod property_type_edge_cases {
    use super::*;

    #[test]
    fn integer_float_comparison() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {ival: 42, fval: 42.0})").unwrap();

        let r = s
            .execute("MATCH (n:N) WHERE n.ival = n.fval RETURN n.ival")
            .unwrap();
        assert_eq!(
            r.row_count(),
            1,
            "Integer 42 should equal float 42.0 in comparison"
        );
    }

    #[test]
    fn missing_property_is_null() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {name: 'Alix'})").unwrap();

        let r = s
            .execute("MATCH (n:N) RETURN n.nonexistent AS val")
            .unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(
            r.rows()[0][0],
            Value::Null,
            "Accessing a missing property should return NULL"
        );
    }

    #[test]
    fn empty_string_is_not_null() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {name: ''})").unwrap();

        let r = s
            .execute("MATCH (n:N) WHERE n.name IS NOT NULL RETURN n.name")
            .unwrap();
        assert_eq!(r.row_count(), 1, "Empty string is a valid value, not NULL");
        assert_eq!(r.rows()[0][0], Value::String("".into()));
    }

    #[test]
    fn zero_is_not_null() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {val: 0})").unwrap();

        let r = s
            .execute("MATCH (n:N) WHERE n.val IS NOT NULL RETURN n.val")
            .unwrap();
        assert_eq!(r.row_count(), 1, "Integer 0 is a valid value, not NULL");
        assert_eq!(r.rows()[0][0], Value::Int64(0));
    }

    #[test]
    fn boolean_false_is_not_null() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {flag: false})").unwrap();

        let r = s
            .execute("MATCH (n:N) WHERE n.flag IS NOT NULL RETURN n.flag")
            .unwrap();
        assert_eq!(r.row_count(), 1, "Boolean false is a valid value, not NULL");
        assert_eq!(r.rows()[0][0], Value::Bool(false));
    }
}

// ============================================================================
// AVG overflow on large integers
// Inspired by ArangoDB #21096: AVG silently overflows on large i64 values.
// ============================================================================

mod avg_large_integers {
    use super::*;

    #[test]
    fn avg_of_identical_large_values_equals_itself() {
        let db = db();
        let s = db.session();
        // 389_916_982_198_384 is well within i64 range
        s.execute("INSERT (:M {val: 389916982198384})").unwrap();
        s.execute("INSERT (:M {val: 389916982198384})").unwrap();
        s.execute("INSERT (:M {val: 389916982198384})").unwrap();

        let r = s.execute("MATCH (m:M) RETURN avg(m.val) AS a").unwrap();
        assert_eq!(r.row_count(), 1);
        match &r.rows()[0][0] {
            Value::Float64(f) => {
                let expected = 389_916_982_198_384.0_f64;
                let diff = (f - expected).abs();
                assert!(
                    diff < 1.0,
                    "AVG of identical large values should equal the value itself, got {f}"
                );
            }
            Value::Int64(v) => {
                assert_eq!(
                    *v, 389_916_982_198_384,
                    "AVG of identical values should equal the value"
                );
            }
            other => panic!("Expected numeric, got {:?}", other),
        }
    }
}

// ============================================================================
// List comparison edge cases
// Inspired by ArangoDB #2477: [] == [null] incorrectly returns true.
// ============================================================================

mod list_comparison {
    use super::*;

    #[test]
    fn empty_list_not_equal_to_list_with_null() {
        let db = db();
        let s = db.session();
        let r = s.execute("RETURN [] = [NULL] AS eq").unwrap();
        assert_eq!(r.row_count(), 1);
        // [] and [null] are structurally different
        assert_ne!(
            r.rows()[0][0],
            Value::Bool(true),
            "Empty list must not equal a list containing NULL"
        );
    }

    #[test]
    fn empty_list_equals_empty_list() {
        let db = db();
        let s = db.session();
        let r = s.execute("RETURN [] = [] AS eq").unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(r.rows()[0][0], Value::Bool(true));
    }

    #[test]
    fn list_equality_same_elements() {
        let db = db();
        let s = db.session();
        let r = s.execute("RETURN [1, 2, 3] = [1, 2, 3] AS eq").unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(r.rows()[0][0], Value::Bool(true));
    }

    #[test]
    fn list_equality_different_elements() {
        let db = db();
        let s = db.session();
        let r = s.execute("RETURN [1, 2] = [1, 3] AS eq").unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(r.rows()[0][0], Value::Bool(false));
    }
}

// ============================================================================
// OPTIONAL MATCH + aggregation scope
// Inspired by Memgraph #3970: outer variable lost after OPTIONAL MATCH + agg.
// ============================================================================

mod optional_match_aggregation {
    use super::*;

    #[test]
    fn count_after_optional_match_preserves_all_rows() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix'})-[:FRIEND]->(:Person {name: 'Gus'})")
            .unwrap();
        s.execute("INSERT (:Person {name: 'Vincent'})").unwrap();

        let r = s
            .execute(
                "MATCH (p:Person) \
                 OPTIONAL MATCH (p)-[:FRIEND]->(f:Person) \
                 RETURN p.name, count(f) AS fc \
                 ORDER BY p.name",
            )
            .unwrap();
        assert_eq!(
            r.row_count(),
            3,
            "All 3 persons should appear, even those without friends"
        );
        // Alix has 1 friend
        assert_eq!(r.rows()[0][0], Value::String("Alix".into()));
        assert_eq!(r.rows()[0][1], Value::Int64(1));
        // Gus has 0 friends (outgoing)
        assert_eq!(r.rows()[1][0], Value::String("Gus".into()));
        assert_eq!(r.rows()[1][1], Value::Int64(0));
        // Vincent has 0 friends
        assert_eq!(r.rows()[2][0], Value::String("Vincent".into()));
        assert_eq!(r.rows()[2][1], Value::Int64(0));
    }
}

// ============================================================================
// UNION basic correctness
// Inspired by Memgraph #3909: UNION + LIMIT hangs.
// ============================================================================

mod union_correctness {
    use super::*;

    #[test]
    fn basic_union_deduplicates() {
        let db = db();
        let s = db.session();
        let r = s.execute("RETURN 1 AS x UNION RETURN 1 AS x").unwrap();
        assert_eq!(r.row_count(), 1, "UNION should deduplicate identical rows");
    }

    #[test]
    fn union_all_preserves_duplicates() {
        let db = db();
        let s = db.session();
        let r = s.execute("RETURN 1 AS x UNION ALL RETURN 1 AS x").unwrap();
        assert_eq!(r.row_count(), 2, "UNION ALL should preserve duplicates");
    }

    #[test]
    fn union_different_values() {
        let db = db();
        let s = db.session();
        let r = s.execute("RETURN 1 AS x UNION RETURN 2 AS x").unwrap();
        assert_eq!(r.row_count(), 2);
    }
}

// ============================================================================
// OR condition in WHERE
// Inspired by JanusGraph #4786: OR evaluated as AND by optimizer.
// ============================================================================

mod or_condition {
    use super::*;

    #[test]
    fn or_in_where_matches_either_branch() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Item {prop: 'A'})").unwrap();
        s.execute("INSERT (:Item {prop: 'B'})").unwrap();
        s.execute("INSERT (:Item {prop: 'C'})").unwrap();

        let r = s
            .execute(
                "MATCH (n:Item) WHERE n.prop = 'A' OR n.prop = 'B' RETURN n.prop ORDER BY n.prop",
            )
            .unwrap();
        assert_eq!(r.row_count(), 2, "OR should match both A and B");
        assert_eq!(r.rows()[0][0], Value::String("A".into()));
        assert_eq!(r.rows()[1][0], Value::String("B".into()));
    }

    #[test]
    fn or_with_and_precedence() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Item {a: 1, b: 2})").unwrap();
        s.execute("INSERT (:Item {a: 3, b: 4})").unwrap();
        s.execute("INSERT (:Item {a: 5, b: 6})").unwrap();

        // (a = 1 AND b = 2) OR (a = 5 AND b = 6) -> matches items 1 and 3
        let r = s
            .execute(
                "MATCH (n:Item) \
                 WHERE (n.a = 1 AND n.b = 2) OR (n.a = 5 AND n.b = 6) \
                 RETURN n.a ORDER BY n.a",
            )
            .unwrap();
        assert_eq!(r.row_count(), 2);
        assert_eq!(r.rows()[0][0], Value::Int64(1));
        assert_eq!(r.rows()[1][0], Value::Int64(5));
    }

    #[test]
    fn not_condition_inverts_filter() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Item {val: 1})").unwrap();
        s.execute("INSERT (:Item {val: 2})").unwrap();
        s.execute("INSERT (:Item {val: 3})").unwrap();

        let r = s
            .execute("MATCH (n:Item) WHERE NOT n.val = 2 RETURN n.val ORDER BY n.val")
            .unwrap();
        assert_eq!(r.row_count(), 2);
        assert_eq!(r.rows()[0][0], Value::Int64(1));
        assert_eq!(r.rows()[1][0], Value::Int64(3));
    }
}

// ============================================================================
// Type coercion: string 'false' vs boolean false
// Inspired by JanusGraph #4220: string 'false' conflated with boolean false.
// ============================================================================

mod type_coercion_string_bool {
    use super::*;

    #[test]
    fn string_false_not_equal_to_boolean_false() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {val: false})").unwrap();
        s.execute("INSERT (:N {val: 'false'})").unwrap();

        // Filter: val <> 'false' (string)
        // Should keep boolean false (different type), exclude string 'false'
        let r = s
            .execute("MATCH (n:N) WHERE n.val <> 'false' RETURN n.val")
            .unwrap();
        assert_eq!(
            r.row_count(),
            1,
            "Boolean false is not equal to string 'false'"
        );
        assert_eq!(r.rows()[0][0], Value::Bool(false));
    }

    #[test]
    fn string_true_not_equal_to_boolean_true() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {val: true})").unwrap();
        s.execute("INSERT (:N {val: 'true'})").unwrap();

        let r = s
            .execute("MATCH (n:N) WHERE n.val <> 'true' RETURN n.val")
            .unwrap();
        assert_eq!(
            r.row_count(),
            1,
            "Boolean true is not equal to string 'true'"
        );
        assert_eq!(r.rows()[0][0], Value::Bool(true));
    }
}

// ============================================================================
// Self-loop with variable-length expansion
// Inspired by Kuzu #5989: OPTIONAL MATCH with self-loop causes OOM.
// Must terminate and not expand infinitely.
// ============================================================================

mod self_loop_variable_length {
    use super::*;

    #[test]
    fn self_loop_varlength_terminates() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (a:N {name: 'Alix'})-[:LOOP]->(a)")
            .unwrap();
        s.execute(
            "MATCH (a:N {name: 'Alix'}) \
             INSERT (a)-[:R]->(b:N {name: 'Gus'})-[:R]->(c:N {name: 'Vincent'})",
        )
        .unwrap();

        // Variable-length expansion on a graph with a self-loop must terminate
        let r = s.execute("MATCH (a:N {name: 'Alix'})-[:R*1..3]->(b) RETURN b.name");
        assert!(
            r.is_ok(),
            "Variable-length expansion with self-loop in graph must terminate: {r:?}"
        );
    }

    #[test]
    fn optional_match_varlength_with_self_loop_returns_null_or_paths() {
        let db = db();
        let s = db.session();
        // Single node with a self-loop, no other edges
        s.execute("INSERT (a:N {name: 'solo'})-[:LOOP]->(a)")
            .unwrap();

        // OPTIONAL MATCH for paths of length 3+ should return NULL (no non-cycling trail)
        let r = s.execute(
            "MATCH (a:N {name: 'solo'}) \
             OPTIONAL MATCH (a)-[:R*3..5]->(b) \
             RETURN b.name",
        );
        assert!(
            r.is_ok(),
            "OPTIONAL MATCH with self-loop must not OOM: {r:?}"
        );
        if let Ok(result) = r {
            assert_eq!(
                result.row_count(),
                1,
                "OPTIONAL MATCH should still return 1 row"
            );
            assert_eq!(
                result.rows()[0][0],
                Value::Null,
                "No matching :R paths from solo node, should be NULL"
            );
        }
    }
}

// ============================================================================
// IN operator correctness
// Inspired by Kuzu #6010: IN with list operations gives wrong results.
// ============================================================================

mod in_operator {
    use super::*;

    #[test]
    fn in_basic_membership() {
        let db = db();
        let s = db.session();
        let r = s.execute("RETURN 2 IN [1, 2, 3] AS found").unwrap();
        assert_eq!(r.rows()[0][0], Value::Bool(true));
    }

    #[test]
    fn in_not_found() {
        let db = db();
        let s = db.session();
        let r = s.execute("RETURN 4 IN [1, 2, 3] AS found").unwrap();
        assert_eq!(r.rows()[0][0], Value::Bool(false));
    }

    #[test]
    fn in_empty_list() {
        let db = db();
        let s = db.session();
        let r = s.execute("RETURN 1 IN [] AS found").unwrap();
        assert_eq!(r.rows()[0][0], Value::Bool(false));
    }

    #[test]
    fn in_with_null_element() {
        let db = db();
        let s = db.session();
        // 1 IN [1, null] should be true (1 is found)
        let r = s.execute("RETURN 1 IN [1, NULL] AS found").unwrap();
        assert_eq!(r.rows()[0][0], Value::Bool(true));
    }

    #[test]
    fn in_with_null_not_found() {
        let db = db();
        let s = db.session();
        // 2 IN [1, null] should be NULL (not found, but null element makes it unknown)
        let r = s.execute("RETURN 2 IN [1, NULL] AS found").unwrap();
        // Per SQL/Cypher semantics: UNKNOWN (NULL)
        assert_eq!(
            r.rows()[0][0],
            Value::Null,
            "x IN [y, NULL] where x != y should be NULL (unknown)"
        );
    }
}

// ============================================================================
// ORDER BY with NULL property values
// Inspired by JanusGraph #3269 and general: NULLs in ORDER BY.
// ============================================================================

mod order_by_nulls {
    use super::*;

    #[test]
    fn order_by_with_some_null_properties() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {name: 'Alix', score: 90})").unwrap();
        s.execute("INSERT (:N {name: 'Gus'})").unwrap(); // no score property
        s.execute("INSERT (:N {name: 'Vincent', score: 80})")
            .unwrap();

        // All 3 nodes should appear, NULLs sorted to end
        let r = s
            .execute("MATCH (n:N) RETURN n.name, n.score ORDER BY n.score")
            .unwrap();
        assert_eq!(
            r.row_count(),
            3,
            "ORDER BY on partial property should still return all rows"
        );
        // NULL should sort last
        assert_eq!(
            r.rows()[2][1],
            Value::Null,
            "NULL score should sort to the end"
        );
    }
}

// ============================================================================
// MERGE visibility of deleted nodes within same transaction
// Inspired by Memgraph #2093: MERGE matches a ghost node deleted earlier.
// ============================================================================

mod merge_after_delete {
    use super::*;

    #[test]
    fn merge_does_not_match_deleted_node() {
        let db = db();
        let s = db.session();
        // Create, delete, then MERGE: MERGE should create a new node
        s.execute("INSERT (:Singleton {key: 'only'})").unwrap();
        s.execute("MATCH (n:Singleton) DELETE n").unwrap();
        s.execute("MERGE (:Singleton {key: 'only'})").unwrap();

        let r = s
            .execute("MATCH (n:Singleton) RETURN count(n) AS cnt")
            .unwrap();
        assert_eq!(
            r.rows()[0][0],
            Value::Int64(1),
            "MERGE after delete should create exactly 1 new node"
        );
    }
}

// ============================================================================
// Label intersection across MATCH clauses
// Inspired by Memgraph #2875: same variable with different labels in
// separate MATCH clauses should intersect label sets.
// ============================================================================

mod label_intersection {
    use super::*;

    #[test]
    fn same_variable_multiple_labels_across_match() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Worker:Senior {name: 'Vincent'})")
            .unwrap();
        s.execute("INSERT (:Worker:Junior {name: 'Jules'})")
            .unwrap();
        s.execute(
            "MATCH (a:Worker {name: 'Vincent'}), (b:Worker {name: 'Jules'}) \
             INSERT (a)-[:MANAGES]->(b)",
        )
        .unwrap();

        // n must satisfy both :Worker (first MATCH) and :Senior (second MATCH)
        let r = s
            .execute(
                "MATCH (n:Worker)-[:MANAGES]->() \
                 MATCH (n:Senior) \
                 RETURN n.name",
            )
            .unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(
            r.rows()[0][0],
            Value::String("Vincent".into()),
            "Only Vincent has both :Worker and :Senior"
        );
    }

    #[test]
    fn label_intersection_filters_non_matching() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:A:B {name: 'both'})").unwrap();
        s.execute("INSERT (:A {name: 'only_a'})").unwrap();
        s.execute("INSERT (:B {name: 'only_b'})").unwrap();

        let r = s.execute("MATCH (n:A) MATCH (n:B) RETURN n.name").unwrap();
        assert_eq!(
            r.row_count(),
            1,
            "Only the node with both :A and :B should match"
        );
        assert_eq!(r.rows()[0][0], Value::String("both".into()));
    }
}

// ============================================================================
// IS NOT NULL operator precedence
// Inspired by Memgraph #2457: WHERE 1=1 IS NOT NULL returns 0 rows.
// ============================================================================

mod is_not_null_precedence {
    use super::*;

    #[test]
    fn boolean_expression_is_not_null() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {val: 1})").unwrap();

        // (1 = 1) evaluates to true, true IS NOT NULL evaluates to true
        let r = s
            .execute("MATCH (n:N) WHERE (1 = 1) IS NOT NULL RETURN n.val")
            .unwrap();
        assert_eq!(
            r.row_count(),
            1,
            "(1=1) IS NOT NULL should be TRUE, returning the row"
        );
    }

    #[test]
    fn property_comparison_is_not_null() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {a: 10, b: 20})").unwrap();

        // (n.a < n.b) is true, true IS NOT NULL is true
        let r = s
            .execute("MATCH (n:N) WHERE (n.a < n.b) IS NOT NULL RETURN n.a")
            .unwrap();
        assert_eq!(r.row_count(), 1);
    }
}

// ============================================================================
// Quantifier functions on empty collections
// Inspired by Memgraph #2481: any([]) returns NULL instead of FALSE.
// ============================================================================

mod quantifier_functions {
    use super::*;

    #[test]
    fn any_on_empty_list_is_false() {
        let db = db();
        let s = db.session();
        let r = s
            .execute("RETURN any(x IN [] WHERE x > 0) AS result")
            .unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(
            r.rows()[0][0],
            Value::Bool(false),
            "any() on empty list should be FALSE per spec"
        );
    }

    #[test]
    fn all_on_empty_list_is_true() {
        let db = db();
        let s = db.session();
        let r = s
            .execute("RETURN all(x IN [] WHERE x > 0) AS result")
            .unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(
            r.rows()[0][0],
            Value::Bool(true),
            "all() on empty list should be TRUE per spec (vacuous truth)"
        );
    }

    #[test]
    fn none_on_empty_list_is_true() {
        let db = db();
        let s = db.session();
        let r = s
            .execute("RETURN none(x IN [] WHERE x > 0) AS result")
            .unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(
            r.rows()[0][0],
            Value::Bool(true),
            "none() on empty list should be TRUE (no elements violate)"
        );
    }
}

// ============================================================================
// String escape sequences
// Inspired by Kuzu #5814: \n and \t stored as literal backslash-n.
// ============================================================================

mod string_escapes {
    use super::*;

    #[test]
    fn newline_escape_in_property() {
        let db = db();
        let s = db.session();
        s.execute(r#"INSERT (:Entry {text: "line1\nline2"})"#)
            .unwrap();

        let r = s.execute("MATCH (e:Entry) RETURN e.text").unwrap();
        assert_eq!(r.row_count(), 1);
        if let Value::String(s) = &r.rows()[0][0] {
            assert!(
                s.contains('\n'),
                "String should contain actual newline, got: {:?}",
                s
            );
        } else {
            panic!("Expected String, got {:?}", r.rows()[0][0]);
        }
    }

    #[test]
    fn tab_escape_in_property() {
        let db = db();
        let s = db.session();
        s.execute(r#"INSERT (:Entry {text: "col1\tcol2"})"#)
            .unwrap();

        let r = s.execute("MATCH (e:Entry) RETURN e.text").unwrap();
        assert_eq!(r.row_count(), 1);
        if let Value::String(s) = &r.rows()[0][0] {
            assert!(
                s.contains('\t'),
                "String should contain actual tab, got: {:?}",
                s
            );
        } else {
            panic!("Expected String, got {:?}", r.rows()[0][0]);
        }
    }
}

// ============================================================================
// NULL join semantics: NULL = NULL must not match
// Inspired by Kuzu #5893: self-join with nullable column includes NULLs.
// ============================================================================

mod null_join_semantics {
    use super::*;

    #[test]
    fn null_equality_in_cross_match_where() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Account {svc: 'A', name: 'Alix'})")
            .unwrap();
        s.execute("INSERT (:Account {svc: 'B', name: 'Alix'})")
            .unwrap();
        // Accounts with no name (NULL)
        s.execute("INSERT (:Account {svc: 'A'})").unwrap();
        s.execute("INSERT (:Account {svc: 'B'})").unwrap();

        let r = s
            .execute(
                "MATCH (a:Account {svc: 'A'}) \
                 MATCH (b:Account {svc: 'B'}) \
                 WHERE a.name = b.name \
                 RETURN a.name",
            )
            .unwrap();
        assert_eq!(
            r.row_count(),
            1,
            "Only 'Alix'='Alix' should match, NULL=NULL must not"
        );
        assert_eq!(r.rows()[0][0], Value::String("Alix".into()));
    }
}

// ============================================================================
// Functions with NULL arguments return NULL (not crash)
// Inspired by Kuzu #5959: labels(null) crashes.
// ============================================================================

mod null_function_arguments {
    use super::*;

    #[test]
    fn type_of_null_relationship_returns_null() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {name: 'Alix'})").unwrap();

        let r = s
            .execute(
                "MATCH (n:N) \
                 OPTIONAL MATCH (n)-[r:NONEXISTENT]->() \
                 RETURN type(r) AS t",
            )
            .unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(
            r.rows()[0][0],
            Value::Null,
            "type() of NULL relationship should return NULL"
        );
    }
}

// ============================================================================
// Delete + re-create same edge in one transaction
// Inspired by Dgraph #9422: delete+set of same predicate produces duplicates.
// ============================================================================

mod delete_recreate_edge {
    use super::*;

    #[test]
    fn replace_edge_in_sequence() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix'})-[:LIKES]->(:Fruit {name: 'apple'})")
            .unwrap();
        s.execute("INSERT (:Fruit {name: 'banana'})").unwrap();

        // Delete old edge, create new one
        s.execute("MATCH (p:Person {name: 'Alix'})-[r:LIKES]->() DELETE r")
            .unwrap();
        s.execute(
            "MATCH (p:Person {name: 'Alix'}), (f:Fruit {name: 'banana'}) \
             INSERT (p)-[:LIKES]->(f)",
        )
        .unwrap();

        let r = s
            .execute(
                "MATCH (p:Person {name: 'Alix'})-[:LIKES]->(f:Fruit) \
                 RETURN f.name",
            )
            .unwrap();
        assert_eq!(
            r.row_count(),
            1,
            "Should have exactly 1 LIKES edge after replace"
        );
        assert_eq!(r.rows()[0][0], Value::String("banana".into()));
    }
}

// ============================================================================
// LIMIT with ORDER BY correctness
// Inspired by Dgraph #9239: LIMIT silently capped when ORDER BY present.
// ============================================================================

mod limit_with_order {
    use super::*;

    #[test]
    fn limit_respected_with_order_by() {
        let db = db();
        let s = db.session();
        for i in 0..20 {
            s.execute(&format!("INSERT (:Item {{seq: {i}}})")).unwrap();
        }

        let r = s
            .execute("MATCH (n:Item) RETURN n.seq ORDER BY n.seq LIMIT 5")
            .unwrap();
        assert_eq!(
            r.row_count(),
            5,
            "LIMIT 5 with ORDER BY should return exactly 5"
        );
        // Should be the first 5 in order
        assert_eq!(r.rows()[0][0], Value::Int64(0));
        assert_eq!(r.rows()[4][0], Value::Int64(4));
    }

    #[test]
    fn limit_without_order_by() {
        let db = db();
        let s = db.session();
        for i in 0..20 {
            s.execute(&format!("INSERT (:Item {{seq: {i}}})")).unwrap();
        }

        let r = s.execute("MATCH (n:Item) RETURN n.seq LIMIT 5").unwrap();
        assert_eq!(
            r.row_count(),
            5,
            "LIMIT 5 without ORDER BY should return exactly 5"
        );
    }

    #[test]
    fn limit_larger_than_result_set() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Item {seq: 1})").unwrap();
        s.execute("INSERT (:Item {seq: 2})").unwrap();

        let r = s
            .execute("MATCH (n:Item) RETURN n.seq ORDER BY n.seq LIMIT 100")
            .unwrap();
        assert_eq!(
            r.row_count(),
            2,
            "LIMIT larger than result set returns all rows"
        );
    }
}

// ============================================================================
// Idempotent property SET
// Inspired by Dgraph #9519: re-setting property to same value breaks mutation.
// ============================================================================

mod idempotent_set {
    use super::*;

    #[test]
    fn set_property_to_same_value_is_noop() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {code: 'X', note: 'initial'})")
            .unwrap();

        // Re-set code to same value, change note
        s.execute("MATCH (n:N {code: 'X'}) SET n.code = 'X', n.note = 'updated'")
            .unwrap();

        let r = s.execute("MATCH (n:N {code: 'X'}) RETURN n.note").unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(
            r.rows()[0][0],
            Value::String("updated".into()),
            "SET with unchanged code should still update note"
        );
    }
}

// ============================================================================
// Float precision preservation
// Inspired by Dgraph #9491: floats truncated to 6 decimal digits.
// ============================================================================

mod float_precision {
    use super::*;

    #[test]
    fn float64_full_precision_roundtrip() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:M {val: 0.123456789012345})").unwrap();

        let r = s.execute("MATCH (m:M) RETURN m.val").unwrap();
        assert_eq!(r.row_count(), 1);
        if let Value::Float64(f) = r.rows()[0][0] {
            let diff = (f - 0.123456789012345_f64).abs();
            assert!(
                diff < 1e-15,
                "Float64 must preserve full precision, got {f} (diff {diff})"
            );
        } else {
            panic!("Expected Float64, got {:?}", r.rows()[0][0]);
        }
    }

    #[test]
    fn repeated_edge_updates_no_stale_values() {
        let db = db();
        let s = db.session();
        // Setup: host -> n1
        s.execute("INSERT (:Host {name: 'h1'})-[:NESTS]->(:Nest {name: 'n1'})")
            .unwrap();
        s.execute("INSERT (:Nest {name: 'n2'})").unwrap();
        s.execute("INSERT (:Nest {name: 'n3'})").unwrap();

        // Update to n2
        s.execute("MATCH (:Host {name: 'h1'})-[r:NESTS]->() DELETE r")
            .unwrap();
        s.execute("MATCH (h:Host {name: 'h1'}), (n:Nest {name: 'n2'}) INSERT (h)-[:NESTS]->(n)")
            .unwrap();

        // Update to n3
        s.execute("MATCH (:Host {name: 'h1'})-[r:NESTS]->() DELETE r")
            .unwrap();
        s.execute("MATCH (h:Host {name: 'h1'}), (n:Nest {name: 'n3'}) INSERT (h)-[:NESTS]->(n)")
            .unwrap();

        // Must see only n3, no stale n1 or n2
        let r = s
            .execute("MATCH (:Host {name: 'h1'})-[:NESTS]->(n) RETURN n.name")
            .unwrap();
        assert_eq!(
            r.row_count(),
            1,
            "Should have exactly 1 NESTS edge after 2 updates"
        );
        assert_eq!(r.rows()[0][0], Value::String("n3".into()));
    }
}

// ============================================================================
// NULL in multi-column GROUP BY must not collapse distinct non-NULL values
// Inspired by ArangoDB #14672: uniform NULL column collapses all groups.
// ============================================================================

mod null_grouping_key {
    use super::*;

    #[test]
    fn null_column_does_not_collapse_groups() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Q {status: 'ok'})").unwrap();
        s.execute("INSERT (:Q {status: 'ok'})").unwrap();
        s.execute("INSERT (:Q {status: 'reject'})").unwrap();
        // All nodes have no 'extra' property (NULL)

        let r = s
            .execute(
                "MATCH (q:Q) \
                 RETURN q.status AS status, q.extra AS extra, count(*) AS cnt \
                 ORDER BY status",
            )
            .unwrap();
        // Should produce 2 groups: ('ok', NULL, 2) and ('reject', NULL, 1)
        // NOT 1 group: (NULL, NULL, 3)
        assert!(
            r.row_count() >= 2,
            "NULL in one grouping column must not collapse distinct values in another, got {} rows",
            r.row_count()
        );
    }
}

// ============================================================================
// Inequality on missing property: <> must not match nodes without the property
// Inspired by JanusGraph #2205: neq on missing property returns wrong results.
// n.name <> 'X' should only match nodes that HAVE a name AND name != 'X'.
// ============================================================================

mod inequality_missing_property {
    use super::*;

    #[test]
    fn neq_does_not_match_missing_property() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix'})").unwrap();
        s.execute("INSERT (:Person {name: 'Gus'})").unwrap();
        s.execute("INSERT (:Person {age: 30})").unwrap(); // no name

        // name <> 'Alix' should return Gus only (has name, and it's not Alix)
        // The node without a name property has NULL for name, and NULL <> 'Alix' is UNKNOWN
        let r = s
            .execute("MATCH (n:Person) WHERE n.name <> 'Alix' RETURN n.name ORDER BY n.name")
            .unwrap();
        assert_eq!(
            r.row_count(),
            1,
            "<> must not match nodes missing the property (NULL <> x is UNKNOWN)"
        );
        assert_eq!(r.rows()[0][0], Value::String("Gus".into()));
    }
}

// ============================================================================
// MERGE with composite key in UNWIND batch: intra-batch dedup
// Inspired by Neo4j #13729: duplicate entries in same UNWIND bypass constraint.
// ============================================================================

mod merge_batch_composite_dedup {
    use super::*;

    #[test]
    fn unwind_merge_composite_key_deduplicates() {
        let db = db();
        let s = db.session();
        // Test intra-batch MERGE dedup with simple scalar UNWIND
        s.execute("UNWIND [1, 2, 1, 3, 2] AS i MERGE (:Item {a: i})")
            .unwrap();

        let r = s.execute("MATCH (n:Item) RETURN count(n) AS cnt").unwrap();
        assert_eq!(
            r.rows()[0][0],
            Value::Int64(3),
            "Duplicate values in UNWIND should MERGE into distinct nodes"
        );
    }
}

// ============================================================================
// Mixed aggregate and non-aggregate in RETURN
// Inspired by FalkorDB #1451: should raise error, not return NULL.
// ============================================================================

mod mixed_aggregate_non_aggregate {
    use super::*;

    #[test]
    fn mixing_aggregate_and_bare_column_without_group_by() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:P {n: 'a'})").unwrap();
        s.execute("INSERT (:P {n: 'b'})").unwrap();

        // p.n + COUNT(p) mixes aggregate and non-aggregate without GROUP BY
        // Should either error OR return a well-defined grouped result, never silent NULL
        let r = s.execute("MATCH (p:P) RETURN p.n, count(p) AS cnt");
        match r {
            Err(_) => {} // Semantic error is the correct response
            Ok(result) => {
                // If engine implicitly groups by p.n, that's also acceptable
                assert!(
                    result.row_count() >= 1,
                    "If not an error, must return grouped result, not empty"
                );
                // Verify no NULL values leaked in where real data should be
                for row in result.rows() {
                    assert_ne!(
                        row[0],
                        Value::Null,
                        "Non-aggregate column must not silently become NULL"
                    );
                }
            }
        }
    }
}

// ============================================================================
// ORDER BY on aliased/projected property with OPTIONAL MATCH
// Inspired by Memgraph #3976: ORDER BY employee.name fails after aliasing.
// ============================================================================

mod order_by_aliased_property {
    use super::*;

    #[test]
    fn order_by_original_expression_after_alias() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix'})-[:WORKS_FOR]->(:Company {name: 'Acme'})")
            .unwrap();
        s.execute("INSERT (:Person {name: 'Gus'})-[:WORKS_FOR]->(:Company {name: 'Beta'})")
            .unwrap();

        let r = s
            .execute(
                "MATCH (e:Person)-[:WORKS_FOR]->(c:Company) \
                 RETURN e.name AS employee, c.name AS company \
                 ORDER BY employee",
            )
            .unwrap();
        assert_eq!(r.row_count(), 2);
        assert_eq!(r.rows()[0][0], Value::String("Alix".into()));
        assert_eq!(r.rows()[1][0], Value::String("Gus".into()));
    }

    #[test]
    fn order_by_alias_with_optional_match() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix'})-[:WORKS_FOR]->(:Company {name: 'Acme'})")
            .unwrap();
        s.execute("INSERT (:Person {name: 'Gus'})").unwrap();

        let r = s
            .execute(
                "MATCH (e:Person) \
                 OPTIONAL MATCH (e)-[:WORKS_FOR]->(c:Company) \
                 RETURN e.name AS employee, c.name AS company \
                 ORDER BY employee",
            )
            .unwrap();
        assert_eq!(r.row_count(), 2);
        assert_eq!(r.rows()[0][0], Value::String("Alix".into()));
        assert_eq!(r.rows()[0][1], Value::String("Acme".into()));
        assert_eq!(r.rows()[1][0], Value::String("Gus".into()));
        assert_eq!(r.rows()[1][1], Value::Null);
    }
}

// ============================================================================
// #218: Cypher ORDER BY returns zeros in MATCH with relationship traversal
// ORDER BY on a property expression that duplicates a RETURN item should
// resolve to the existing projected column, not create a broken extra
// PropertyAccess on a non-entity column.
// ============================================================================

mod order_by_relationship_traversal_218 {
    use super::*;

    #[test]
    fn order_by_property_matching_return_item() {
        let db = db();
        let s = db.session();
        s.execute_cypher("CREATE (:Method {name: 'foo', qn: 'java://A:foo()'})")
            .unwrap();
        s.execute_cypher("CREATE (:Method {name: 'bar', qn: 'java://B:bar()'})")
            .unwrap();
        s.execute_cypher("CREATE (:Method {name: 'baz', qn: 'java://C:baz()'})")
            .unwrap();
        s.execute_cypher(
            "MATCH (a:Method {name: 'foo'}), (b:Method {name: 'bar'}) CREATE (a)-[:CALLS]->(b)",
        )
        .unwrap();
        s.execute_cypher(
            "MATCH (a:Method {name: 'baz'}), (b:Method {name: 'bar'}) CREATE (a)-[:CALLS]->(b)",
        )
        .unwrap();

        // Without ORDER BY: should return correct values
        let r = s
            .execute_cypher(
                "MATCH (caller)-[:CALLS]->(target) \
                 WHERE target.name = 'bar' \
                 RETURN caller.name AS caller, caller.qn AS caller_qn",
            )
            .unwrap();
        assert_eq!(r.row_count(), 2);
        for row in r.rows() {
            assert!(
                matches!(&row[0], Value::String(s) if s == "foo" || s == "baz"),
                "caller should be a string, got {:?}",
                row[0]
            );
            assert!(
                matches!(&row[1], Value::String(_)),
                "caller_qn should be a string, got {:?}",
                row[1]
            );
        }

        // With ORDER BY on a property that matches a RETURN item expression:
        // values must NOT become 0 and no extra spurious column should appear.
        let r = s
            .execute_cypher(
                "MATCH (caller)-[:CALLS]->(target) \
                 WHERE target.name = 'bar' \
                 RETURN caller.name AS caller, caller.qn AS caller_qn \
                 ORDER BY caller.name",
            )
            .unwrap();
        assert_eq!(r.row_count(), 2);
        assert_eq!(
            r.columns.len(),
            2,
            "should have exactly 2 columns, got {:?}",
            r.columns
        );
        // Sorted ascending by name: baz < foo
        assert_eq!(r.rows()[0][0], Value::String("baz".into()));
        assert_eq!(r.rows()[0][1], Value::String("java://C:baz()".into()));
        assert_eq!(r.rows()[1][0], Value::String("foo".into()));
        assert_eq!(r.rows()[1][1], Value::String("java://A:foo()".into()));
    }

    #[test]
    fn order_by_desc_with_relationship_traversal() {
        let db = db();
        let s = db.session();
        s.execute_cypher("CREATE (:Method {name: 'foo', qn: 'java://A:foo()'})")
            .unwrap();
        s.execute_cypher("CREATE (:Method {name: 'bar', qn: 'java://B:bar()'})")
            .unwrap();
        s.execute_cypher("CREATE (:Method {name: 'baz', qn: 'java://C:baz()'})")
            .unwrap();
        s.execute_cypher(
            "MATCH (a:Method {name: 'foo'}), (b:Method {name: 'bar'}) CREATE (a)-[:CALLS]->(b)",
        )
        .unwrap();
        s.execute_cypher(
            "MATCH (a:Method {name: 'baz'}), (b:Method {name: 'bar'}) CREATE (a)-[:CALLS]->(b)",
        )
        .unwrap();

        let r = s
            .execute_cypher(
                "MATCH (caller)-[:CALLS]->(target) \
                 WHERE target.name = 'bar' \
                 RETURN caller.name AS caller, caller.qn AS caller_qn \
                 ORDER BY caller.name DESC",
            )
            .unwrap();
        assert_eq!(r.row_count(), 2);
        // Sorted descending: foo > baz
        assert_eq!(r.rows()[0][0], Value::String("foo".into()));
        assert_eq!(r.rows()[1][0], Value::String("baz".into()));
    }
}

// ============================================================================
// CALL subquery scope isolation
// Inspired by Neo4j #13656 and Memgraph #3955: outer variables lost in CALL.
// ============================================================================

mod call_subquery_scope {
    use super::*;

    #[test]
    fn call_subquery_preserves_outer_variable() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix'})").unwrap();
        s.execute("INSERT (:Person {name: 'Gus'})").unwrap();
        s.execute("INSERT (:Person {name: 'Vincent'})").unwrap();

        let r = s.execute(
            "MATCH (p:Person) \
             CALL { \
               WITH p \
               OPTIONAL MATCH (p)-[:ACTED_IN]->(m) \
               RETURN count(m) AS movie_count \
             } \
             RETURN p.name, movie_count \
             ORDER BY p.name",
        );
        match r {
            Ok(result) => {
                assert_eq!(
                    result.row_count(),
                    3,
                    "CALL subquery must preserve all outer rows, got {}",
                    result.row_count()
                );
                // All should have movie_count = 0
                for row in result.rows() {
                    assert_eq!(row[1], Value::Int64(0));
                }
            }
            Err(_) => {
                // If CALL subquery syntax is not supported, that's fine
            }
        }
    }
}

// ============================================================================
// Edge properties through path variable
// Inspired by ArangoDB #21265: edge props lost when accessed via path.
// ============================================================================

mod edge_properties_in_path {
    use super::*;

    #[test]
    fn edge_properties_preserved_in_traversal() {
        let db = db();
        let s = db.session();
        s.execute(
            "INSERT (:Place {name: 'France'})-[:IS_IN {category: 'continent'}]->(:Place {name: 'Europe'})",
        )
        .unwrap();
        s.execute(
            "INSERT (:Place {name: 'Europe'})-[:IS_IN {category: 'planet'}]->(:Place {name: 'World'})",
        )
        .unwrap();

        // Access edge properties directly
        let r = s
            .execute(
                "MATCH (:Place {name: 'France'})-[r:IS_IN]->(:Place {name: 'Europe'}) \
                 RETURN r.category",
            )
            .unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(
            r.rows()[0][0],
            Value::String("continent".into()),
            "Edge property must be preserved"
        );
    }

    #[test]
    fn multiple_edge_properties_in_chain() {
        let db = db();
        let s = db.session();
        s.execute(
            "INSERT (:A {name: 'a'})-[:R {weight: 10}]->(:B {name: 'b'})-[:R {weight: 20}]->(:C {name: 'c'})",
        )
        .unwrap();

        let r = s
            .execute(
                "MATCH (:A)-[r1:R]->(:B)-[r2:R]->(:C) \
                 RETURN r1.weight, r2.weight",
            )
            .unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(r.rows()[0][0], Value::Int64(10));
        assert_eq!(r.rows()[0][1], Value::Int64(20));
    }
}

// ============================================================================
// Variable-length path vs explicit hop count equivalence
// Inspired by Memgraph #3735: variable-length returns different count.
// ============================================================================

mod varlength_vs_explicit {
    use super::*;

    #[test]
    fn two_hop_varlength_equals_explicit() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {id: 1})-[:R]->(:N {id: 2})-[:R]->(:N {id: 3})")
            .unwrap();

        // Explicit two-hop
        let explicit = s
            .execute(
                "MATCH (a:N {id: 1})-[:R]->(mid)-[:R]->(c) \
                 RETURN count(*) AS cnt",
            )
            .unwrap();

        // Variable-length two-hop
        let varlength = s
            .execute(
                "MATCH (a:N {id: 1})-[:R*2]->(c) \
                 RETURN count(*) AS cnt",
            )
            .unwrap();

        assert_eq!(
            explicit.rows()[0][0],
            varlength.rows()[0][0],
            "Variable-length *2 must match explicit two-hop count"
        );
    }
}

// ============================================================================
// CASE WHEN with NULL from aggregate over empty set
// Inspired by Dgraph #9125: conditional on NULL aggregate fails.
// ============================================================================

mod case_when_null_aggregate {
    use super::*;

    #[test]
    fn case_when_with_count_zero_and_null_max() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Column {name: 'todo'})").unwrap();
        // No cards in 'todo' column

        let r = s.execute(
            "MATCH (col:Column {name: 'todo'}) \
             OPTIONAL MATCH (c:Card)-[:IN_COL]->(col) \
             WITH col, count(c) AS cc, max(c.pos) AS mp \
             RETURN CASE WHEN cc = 0 THEN 0 ELSE mp + 1 END AS next_pos",
        );
        match r {
            Ok(result) => {
                assert_eq!(result.row_count(), 1);
                assert_eq!(
                    result.rows()[0][0],
                    Value::Int64(0),
                    "When count is 0, CASE should return 0"
                );
            }
            Err(_) => {
                // CASE WHEN not yet supported is acceptable
            }
        }
    }
}

// ============================================================================
// Chained OR correctness: (A OR B) AND (C OR D)
// Inspired by JanusGraph #2231: chained or() flattened to single OR.
// ============================================================================

mod chained_or_and {
    use super::*;

    #[test]
    fn chained_or_not_flattened() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:T {a: true,  b: true,  c: true,  d: true})")
            .unwrap();
        s.execute("INSERT (:T {a: true,  b: false, c: true,  d: false})")
            .unwrap();
        s.execute("INSERT (:T {a: false, b: true,  c: false, d: true})")
            .unwrap();
        s.execute("INSERT (:T {a: false, b: false, c: true,  d: false})")
            .unwrap();

        // (a OR b) AND (c=false OR d=true)
        // Row 1: a=T,b=T,c=T,d=T -> (T OR T)=T AND (F OR T)=T -> match
        // Row 2: a=T,b=F,c=T,d=F -> (T OR F)=T AND (F OR F)=F -> no
        // Row 3: a=F,b=T,c=F,d=T -> (F OR T)=T AND (T OR T)=T -> match
        // Row 4: a=F,b=F,c=T,d=F -> (F OR F)=F -> no
        let r = s
            .execute(
                "MATCH (n:T) \
                 WHERE (n.a = true OR n.b = true) AND (n.c = false OR n.d = true) \
                 RETURN count(*) AS cnt",
            )
            .unwrap();
        assert_eq!(
            r.rows()[0][0],
            Value::Int64(2),
            "(A OR B) AND (C OR D) must not flatten to (A OR B OR C OR D)"
        );
    }
}

// ============================================================================
// substring() indexing
// Inspired by LadybugDB #85: Cypher uses 0-based, GQL/SQL uses 1-based.
// ============================================================================

mod substring_indexing {
    use super::*;

    #[test]
    fn gql_substring_extracts_correctly() {
        let db = db();
        let s = db.session();
        // GQL substring: start position and length
        let r = s.execute("RETURN substring('hello world', 0, 5) AS sub");
        match r {
            Ok(result) => {
                assert_eq!(result.row_count(), 1);
                if let Value::String(s) = &result.rows()[0][0] {
                    // Whether 0-based or 1-based, should not return empty
                    assert!(
                        !s.is_empty(),
                        "substring should not return empty for valid input"
                    );
                }
            }
            Err(_) => {} // substring not supported is fine
        }
    }
}

// ============================================================================
// Property key prefix overlap: keys that share prefixes
// Inspired by JanusGraph #4401: looking up "hel" crashes when "hello" exists.
// ============================================================================

mod property_key_prefix {
    use super::*;

    #[test]
    fn property_keys_with_shared_prefix() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {hello: 'world', hel: 'wor'})")
            .unwrap();

        let r1 = s.execute("MATCH (n:N) RETURN n.hel").unwrap();
        assert_eq!(r1.rows()[0][0], Value::String("wor".into()));

        let r2 = s.execute("MATCH (n:N) RETURN n.hello").unwrap();
        assert_eq!(r2.rows()[0][0], Value::String("world".into()));
    }

    #[test]
    fn filter_on_prefix_property() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {abc: 1, abcdef: 2, ab: 3})").unwrap();

        let r = s
            .execute("MATCH (n:N) WHERE n.abc = 1 RETURN n.abcdef, n.ab")
            .unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(r.rows()[0][0], Value::Int64(2));
        assert_eq!(r.rows()[0][1], Value::Int64(3));
    }
}

// ============================================================================
// Property type overwrite: change property from one type to another
// Inspired by JanusGraph #4141: bool->string overwrite corrupts vertex.
// ============================================================================

mod property_type_overwrite {
    use super::*;

    #[test]
    fn overwrite_bool_with_string() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Item {flag: true})").unwrap();
        s.execute("MATCH (n:Item) SET n.flag = 'yes'").unwrap();

        let r = s.execute("MATCH (n:Item) RETURN n.flag").unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(
            r.rows()[0][0],
            Value::String("yes".into()),
            "Property type should be overwritable from bool to string"
        );
    }

    #[test]
    fn overwrite_int_with_string() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Item {val: 42})").unwrap();
        s.execute("MATCH (n:Item) SET n.val = 'forty-two'").unwrap();

        let r = s.execute("MATCH (n:Item) RETURN n.val").unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(r.rows()[0][0], Value::String("forty-two".into()));
    }

    #[test]
    fn overwrite_string_with_int() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Item {val: 'hello'})").unwrap();
        s.execute("MATCH (n:Item) SET n.val = 99").unwrap();

        let r = s.execute("MATCH (n:Item) RETURN n.val").unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(r.rows()[0][0], Value::Int64(99));
    }
}

// ============================================================================
// Escaped quotes in property values
// Inspired by Dgraph #9405: escaped quotes break constraint validation.
// ============================================================================

mod escaped_quotes {
    use super::*;

    #[test]
    fn double_quotes_in_single_quoted_string() {
        let db = db();
        let s = db.session();
        s.execute(r#"INSERT (:Book {title: 'The "Problem" of Knowledge'})"#)
            .unwrap();

        let r = s.execute("MATCH (b:Book) RETURN b.title").unwrap();
        assert_eq!(r.row_count(), 1);
        if let Value::String(title) = &r.rows()[0][0] {
            assert!(
                title.contains('"'),
                "Double quotes should be preserved in property value, got: {title}"
            );
        } else {
            panic!("Expected String, got {:?}", r.rows()[0][0]);
        }
    }

    #[test]
    fn single_quotes_in_double_quoted_string() {
        let db = db();
        let s = db.session();
        s.execute(r#"INSERT (:Book {title: "It's a Test"})"#)
            .unwrap();

        let r = s.execute("MATCH (b:Book) RETURN b.title").unwrap();
        assert_eq!(r.row_count(), 1);
        if let Value::String(title) = &r.rows()[0][0] {
            assert!(
                title.contains('\''),
                "Single quotes should be preserved, got: {title}"
            );
        } else {
            panic!("Expected String, got {:?}", r.rows()[0][0]);
        }
    }
}

// ============================================================================
// Phantom relationships after DETACH DELETE
// Inspired by Kuzu #5954: edge survives after endpoint node is deleted.
// ============================================================================

mod phantom_relationships {
    use super::*;

    #[test]
    fn detach_delete_one_node_preserves_unrelated_edges() {
        let db = db();
        let s = db.session();
        // Two independent edge chains
        s.execute("INSERT (:A {id: 1})-[:R]->(:B {id: 1})").unwrap();
        s.execute("INSERT (:A {id: 2})-[:R]->(:B {id: 2})").unwrap();

        // Delete only the first chain's source
        s.execute("MATCH (a:A {id: 1}) DETACH DELETE a").unwrap();

        // Second chain should still have its edge
        let r = s
            .execute("MATCH ()-[r:R]->() RETURN count(r) AS cnt")
            .unwrap();
        assert_eq!(
            r.rows()[0][0],
            Value::Int64(1),
            "Unrelated edge chain should survive DETACH DELETE of another node"
        );
    }
}

// ============================================================================
// DETACH DELETE returns ghost node properties
// Inspired by Neo4j #13714: deleted node still returns props in same clause.
// ============================================================================

mod detach_delete_return {
    use super::*;

    #[test]
    fn delete_then_count_returns_zero() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Ghost {name: 'Alix', age: 30})")
            .unwrap();
        s.execute("MATCH (n:Ghost) DETACH DELETE n").unwrap();

        // After delete, node must not be queryable
        let r = s.execute("MATCH (n:Ghost) RETURN count(n) AS cnt").unwrap();
        assert_eq!(r.rows()[0][0], Value::Int64(0));
    }
}

// ============================================================================
// Multi-statement execution
// Inspired by LadybugDB #333: batch execution silently drops later errors.
// ============================================================================

mod multi_statement {
    use super::*;

    #[test]
    fn sequential_statements_all_execute() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Item {val: 1})").unwrap();
        s.execute("INSERT (:Item {val: 2})").unwrap();
        s.execute("INSERT (:Item {val: 3})").unwrap();

        let r = s.execute("MATCH (n:Item) RETURN count(n) AS cnt").unwrap();
        assert_eq!(
            r.rows()[0][0],
            Value::Int64(3),
            "All sequential statements should execute"
        );
    }
}

// ============================================================================
// Backtick-quoted identifiers
// Inspired by Kuzu #5872: backtick labels treated as different label.
// ============================================================================

mod backtick_identifiers {
    use super::*;

    #[test]
    fn backtick_label_matches_plain_label() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix'})").unwrap();

        // Backtick-quoted label should match the same label
        let r = s.execute("MATCH (n:`Person`) RETURN n.name");
        match r {
            Ok(result) => {
                assert_eq!(
                    result.row_count(),
                    1,
                    "Backtick-quoted :Person should match plain :Person"
                );
                assert_eq!(result.rows()[0][0], Value::String("Alix".into()));
            }
            Err(_) => {
                // Backtick syntax not supported is acceptable
            }
        }
    }
}

// ============================================================================
// SKIP and SKIP + LIMIT interaction
// Broader coverage of pagination correctness.
// ============================================================================

mod skip_limit {
    use super::*;

    #[test]
    fn skip_skips_first_n_rows() {
        let db = db();
        let s = db.session();
        for i in 0..5 {
            s.execute(&format!("INSERT (:Item {{seq: {i}}})")).unwrap();
        }

        let r = s
            .execute("MATCH (n:Item) RETURN n.seq ORDER BY n.seq SKIP 2")
            .unwrap();
        assert_eq!(r.row_count(), 3);
        assert_eq!(r.rows()[0][0], Value::Int64(2));
    }

    #[test]
    fn skip_plus_limit() {
        let db = db();
        let s = db.session();
        for i in 0..10 {
            s.execute(&format!("INSERT (:Item {{seq: {i}}})")).unwrap();
        }

        let r = s
            .execute("MATCH (n:Item) RETURN n.seq ORDER BY n.seq SKIP 3 LIMIT 2")
            .unwrap();
        assert_eq!(r.row_count(), 2);
        assert_eq!(r.rows()[0][0], Value::Int64(3));
        assert_eq!(r.rows()[1][0], Value::Int64(4));
    }

    #[test]
    fn skip_beyond_result_set() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Item {seq: 1})").unwrap();
        s.execute("INSERT (:Item {seq: 2})").unwrap();

        let r = s.execute("MATCH (n:Item) RETURN n.seq SKIP 100").unwrap();
        assert_eq!(r.row_count(), 0, "SKIP past end should return empty");
    }
}

// ============================================================================
// ORDER BY with mixed types
// Inspired by Memgraph #3888: should follow total ordering, not error.
// ============================================================================

mod order_by_mixed_types {
    use super::*;

    #[test]
    fn order_by_heterogeneous_property_does_not_crash() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {val: 1})").unwrap();
        s.execute("INSERT (:N {val: 'hello'})").unwrap();
        s.execute("INSERT (:N {val: true})").unwrap();

        // Should not crash, regardless of ordering semantics
        let r = s.execute("MATCH (n:N) RETURN n.val ORDER BY n.val");
        assert!(
            r.is_ok(),
            "ORDER BY with mixed types should not crash: {r:?}"
        );
        if let Ok(result) = r {
            assert_eq!(result.row_count(), 3, "All 3 rows should be returned");
        }
    }
}

// ============================================================================
// RETURN DISTINCT on various types
// Broader coverage of DISTINCT correctness.
// ============================================================================

mod return_distinct {
    use super::*;

    #[test]
    fn distinct_removes_exact_duplicates() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {val: 1})").unwrap();
        s.execute("INSERT (:N {val: 1})").unwrap();
        s.execute("INSERT (:N {val: 2})").unwrap();

        let r = s
            .execute("MATCH (n:N) RETURN DISTINCT n.val ORDER BY n.val")
            .unwrap();
        assert_eq!(r.row_count(), 2);
        assert_eq!(r.rows()[0][0], Value::Int64(1));
        assert_eq!(r.rows()[1][0], Value::Int64(2));
    }

    #[test]
    fn distinct_on_null_values() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {val: 1})").unwrap();
        s.execute("INSERT (:N {val: 1})").unwrap();
        s.execute("INSERT (:N)").unwrap(); // NULL val
        s.execute("INSERT (:N)").unwrap(); // NULL val

        let r = s.execute("MATCH (n:N) RETURN DISTINCT n.val").unwrap();
        assert_eq!(
            r.row_count(),
            2,
            "DISTINCT should collapse duplicate NULLs into one"
        );
    }
}

// ============================================================================
// WITH clause projection
// Broader coverage of WITH semantics.
// ============================================================================

mod with_clause {
    use super::*;

    #[test]
    fn with_renames_variable() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix', age: 30})")
            .unwrap();

        let r = s
            .execute(
                "MATCH (p:Person) \
                 WITH p.name AS person_name, p.age AS person_age \
                 RETURN person_name, person_age",
            )
            .unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(r.rows()[0][0], Value::String("Alix".into()));
        assert_eq!(r.rows()[0][1], Value::Int64(30));
    }

    #[test]
    fn with_filters_rows() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {val: 1})").unwrap();
        s.execute("INSERT (:N {val: 2})").unwrap();
        s.execute("INSERT (:N {val: 3})").unwrap();

        let r = s
            .execute(
                "MATCH (n:N) \
                 WITH n WHERE n.val > 1 \
                 RETURN n.val ORDER BY n.val",
            )
            .unwrap();
        assert_eq!(r.row_count(), 2);
        assert_eq!(r.rows()[0][0], Value::Int64(2));
        assert_eq!(r.rows()[1][0], Value::Int64(3));
    }
}

// ============================================================================
// User workflow: multi-clause MATCH + CREATE relationship
// From Grafeo user josema-xyz: MATCH(a) MATCH(b) CREATE (a)-[:R]->(b)
// ============================================================================

mod multi_match_create_edge {
    use super::*;

    #[test]
    fn match_match_create_relationship() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix'})").unwrap();
        s.execute("INSERT (:Person {name: 'Gus'})").unwrap();

        s.execute(
            "MATCH (a:Person {name: 'Alix'}), (b:Person {name: 'Gus'}) \
             INSERT (a)-[:KNOWS]->(b)",
        )
        .unwrap();

        // Must create exactly 1 edge, no phantom nodes
        let nodes = s
            .execute("MATCH (n:Person) RETURN count(n) AS cnt")
            .unwrap();
        let edges = s
            .execute("MATCH ()-[r:KNOWS]->() RETURN count(r) AS cnt")
            .unwrap();
        assert_eq!(
            nodes.rows()[0][0],
            Value::Int64(2),
            "Should still have 2 nodes"
        );
        assert_eq!(edges.rows()[0][0], Value::Int64(1), "Should have 1 edge");
    }

    #[test]
    fn match_match_create_multiple_edges() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix'})").unwrap();
        s.execute("INSERT (:Person {name: 'Gus'})").unwrap();
        s.execute("INSERT (:Person {name: 'Vincent'})").unwrap();

        // Create edges from Alix to all others
        s.execute(
            "MATCH (a:Person {name: 'Alix'}), (b:Person) \
             WHERE b.name <> 'Alix' \
             INSERT (a)-[:KNOWS]->(b)",
        )
        .unwrap();

        let edges = s
            .execute("MATCH (:Person {name: 'Alix'})-[r:KNOWS]->() RETURN count(r) AS cnt")
            .unwrap();
        assert_eq!(edges.rows()[0][0], Value::Int64(2));
    }
}

// ============================================================================
// User workflow: negative numeric literals
// From Grafeo user janit: geographic coordinates with negative values.
// ============================================================================

mod negative_numerics {
    use super::*;

    #[test]
    fn insert_negative_integer() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Location {lat: -33, lon: 151})")
            .unwrap();

        let r = s.execute("MATCH (l:Location) RETURN l.lat, l.lon").unwrap();
        assert_eq!(r.rows()[0][0], Value::Int64(-33));
        assert_eq!(r.rows()[0][1], Value::Int64(151));
    }

    #[test]
    fn insert_negative_float() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Location {lat: -33.8688, lon: 151.2093})")
            .unwrap();

        let r = s.execute("MATCH (l:Location) RETURN l.lat, l.lon").unwrap();
        if let Value::Float64(lat) = r.rows()[0][0] {
            assert!(lat < 0.0, "Negative latitude must be preserved");
            assert!((lat - (-33.8688)).abs() < 0.001);
        } else {
            panic!("Expected Float64 for lat, got {:?}", r.rows()[0][0]);
        }
    }

    #[test]
    fn filter_on_negative_value() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Loc {lat: -33.0})").unwrap();
        s.execute("INSERT (:Loc {lat: 48.8})").unwrap();

        let r = s
            .execute("MATCH (l:Loc) WHERE l.lat < 0 RETURN l.lat")
            .unwrap();
        assert_eq!(r.row_count(), 1, "Only one location has negative latitude");
    }

    #[test]
    fn merge_with_negative_property() {
        let db = db();
        let s = db.session();
        s.execute("MERGE (:Temp {val: -42})").unwrap();
        s.execute("MERGE (:Temp {val: -42})").unwrap();

        let r = s.execute("MATCH (n:Temp) RETURN count(n) AS cnt").unwrap();
        assert_eq!(
            r.rows()[0][0],
            Value::Int64(1),
            "MERGE with negative value should deduplicate"
        );
    }
}

// ============================================================================
// User workflow: count(*) vs count(n) after mutations
// From Grafeo user josema-xyz: count(*) returned 1, count(n) threw error.
// ============================================================================

mod count_variants {
    use super::*;

    #[test]
    fn count_star_after_insert() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {val: 1})").unwrap();
        s.execute("INSERT (:N {val: 2})").unwrap();

        let r = s.execute("MATCH (n:N) RETURN count(*) AS cnt").unwrap();
        assert_eq!(r.rows()[0][0], Value::Int64(2));
    }

    #[test]
    fn count_variable_after_insert() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {val: 1})").unwrap();
        s.execute("INSERT (:N {val: 2})").unwrap();

        let r = s.execute("MATCH (n:N) RETURN count(n) AS cnt").unwrap();
        assert_eq!(r.rows()[0][0], Value::Int64(2));
    }

    #[test]
    fn count_star_equals_count_variable() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:N {val: 1})").unwrap();
        s.execute("INSERT (:N {val: 2})").unwrap();
        s.execute("INSERT (:N {val: 3})").unwrap();

        let r1 = s.execute("MATCH (n:N) RETURN count(*) AS cnt").unwrap();
        let r2 = s.execute("MATCH (n:N) RETURN count(n) AS cnt").unwrap();
        assert_eq!(
            r1.rows()[0][0],
            r2.rows()[0][0],
            "count(*) and count(n) must agree"
        );
    }
}

// ============================================================================
// User workflow: batch upsert via UNWIND + MERGE + SET
// From Grafeo user Imaclean74: code dependency graph bulk import.
// ============================================================================

mod batch_upsert {
    use super::*;

    #[test]
    fn unwind_merge_set_property() {
        let db = db();
        let s = db.session();
        s.execute(
            "UNWIND [1, 2, 3] AS i \
             MERGE (n:Item {key: i}) \
             SET n.updated = true",
        )
        .unwrap();

        let r = s
            .execute("MATCH (n:Item) WHERE n.updated = true RETURN count(n) AS cnt")
            .unwrap();
        assert_eq!(r.rows()[0][0], Value::Int64(3));
    }

    #[test]
    fn unwind_merge_second_pass_updates() {
        let db = db();
        let s = db.session();
        // First pass: create
        s.execute("UNWIND [1, 2, 3] AS i MERGE (n:Item {key: i}) SET n.ver = 1")
            .unwrap();
        // Second pass: update
        s.execute("UNWIND [1, 2, 3] AS i MERGE (n:Item {key: i}) SET n.ver = 2")
            .unwrap();

        let r = s.execute("MATCH (n:Item) RETURN count(n) AS cnt").unwrap();
        assert_eq!(
            r.rows()[0][0],
            Value::Int64(3),
            "No duplicates from second MERGE"
        );

        let r2 = s
            .execute("MATCH (n:Item) WHERE n.ver = 2 RETURN count(n) AS cnt")
            .unwrap();
        assert_eq!(
            r2.rows()[0][0],
            Value::Int64(3),
            "All nodes should have ver=2 after second pass"
        );
    }
}

// ============================================================================
// User workflow: labels() and type() as grouping keys in aggregation
// From Grafeo user Imaclean74: schema introspection via grouping.
// ============================================================================

mod aggregation_with_functions {
    use super::*;

    #[test]
    fn group_by_labels_with_count() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix'})").unwrap();
        s.execute("INSERT (:Person {name: 'Gus'})").unwrap();
        s.execute("INSERT (:City {name: 'Amsterdam'})").unwrap();

        let r = s
            .execute("MATCH (n) RETURN labels(n)[0] AS label, count(n) AS cnt ORDER BY label")
            .unwrap();
        assert_eq!(r.row_count(), 2);
        assert_eq!(r.rows()[0][0], Value::String("City".into()));
        assert_eq!(r.rows()[0][1], Value::Int64(1));
        assert_eq!(r.rows()[1][0], Value::String("Person".into()));
        assert_eq!(r.rows()[1][1], Value::Int64(2));
    }

    #[test]
    fn group_by_type_with_count() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:A)-[:FOLLOWS]->(:B)").unwrap();
        s.execute("INSERT (:C)-[:FOLLOWS]->(:D)").unwrap();
        s.execute("INSERT (:E)-[:BLOCKS]->(:F)").unwrap();

        let r = s
            .execute("MATCH ()-[r]->() RETURN type(r) AS t, count(r) AS cnt ORDER BY t")
            .unwrap();
        assert_eq!(r.row_count(), 2);
    }
}

// ============================================================================
// User workflow: persistent storage round-trip
// From Grafeo user CorvusYe: open, write, close, reopen, verify.
// ============================================================================

mod persistence_roundtrip {
    use super::*;
    use grafeo_engine::GrafeoDB;

    #[test]
    fn in_memory_data_survives_session() {
        let db = GrafeoDB::new_in_memory();
        let s1 = db.session();
        s1.execute("INSERT (:Persist {key: 'test', val: 42})")
            .unwrap();

        // New session on same db should see the data
        let s2 = db.session();
        let r = s2
            .execute("MATCH (n:Persist {key: 'test'}) RETURN n.val")
            .unwrap();
        assert_eq!(r.row_count(), 1);
        assert_eq!(r.rows()[0][0], Value::Int64(42));
    }
}

// ============================================================================
// GROUP BY on list-valued keys (Bug 20 + Bug 24)
// Push-based aggregator must hash lists distinctly; pull-based aggregator
// must produce separate GroupKeyPart values for different lists.
// ============================================================================

// ============================================================================
// ORDER BY with complex expressions should not leak synthetic columns (Bug 23)
// ============================================================================

mod order_by_synthetic_columns {
    use super::*;

    #[test]
    fn order_by_labels_does_not_leak_expr_column() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix'})").unwrap();
        s.execute("INSERT (:Person {name: 'Gus'})").unwrap();

        let r = s
            .execute("MATCH (n:Person) RETURN n.name ORDER BY labels(n)[0]")
            .unwrap();

        assert_eq!(r.row_count(), 2);
        // Should only have the 'n.name' column, no __expr_* columns
        assert_eq!(
            r.columns.len(),
            1,
            "Expected 1 column (n.name), got {}: {:?}",
            r.columns.len(),
            r.columns
        );
        for col in &r.columns {
            assert!(
                !col.starts_with("__expr"),
                "Synthetic __expr column leaked into results: {col}"
            );
        }
    }

    #[test]
    fn order_by_arithmetic_does_not_leak_expr_column() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix', age: 30})")
            .unwrap();
        s.execute("INSERT (:Person {name: 'Gus', age: 25})")
            .unwrap();

        let r = s
            .execute("MATCH (n:Person) RETURN n.name, n.age ORDER BY n.age + 1")
            .unwrap();

        assert_eq!(r.row_count(), 2);
        assert_eq!(
            r.columns.len(),
            2,
            "Expected 2 columns (n.name, n.age), got {}: {:?}",
            r.columns.len(),
            r.columns
        );
        for col in &r.columns {
            assert!(
                !col.starts_with("__expr"),
                "Synthetic __expr column leaked into results: {col}"
            );
        }
    }

    #[test]
    fn order_by_type_on_edges_does_not_leak() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix'})-[:KNOWS]->(:Person {name: 'Gus'})")
            .unwrap();

        let r = s
            .execute("MATCH (a:Person)-[r]->(b:Person) RETURN a.name, b.name ORDER BY type(r)")
            .unwrap();

        assert_eq!(r.row_count(), 1);
        for col in &r.columns {
            assert!(
                !col.starts_with("__expr"),
                "Synthetic __expr column leaked into results: {col}"
            );
        }
    }
}

mod group_by_list_keys {
    use super::*;

    #[test]
    fn group_by_labels_multi_label_nodes() {
        let db = db();
        let s = db.session();
        // Create nodes with different label sets
        s.execute("INSERT (:Person {name: 'Alix'})").unwrap();
        s.execute("INSERT (:Person:Employee {name: 'Gus'})")
            .unwrap();
        s.execute("INSERT (:Person:Employee {name: 'Jules'})")
            .unwrap();
        s.execute("INSERT (:Company {name: 'GrafeoDB'})").unwrap();

        let r = s
            .execute("MATCH (n) RETURN labels(n) AS lbl, count(*) AS cnt ORDER BY cnt DESC")
            .unwrap();

        // Should produce 3 groups: [Person, Employee] (2), [Person] (1), [Company] (1)
        assert_eq!(
            r.row_count(),
            3,
            "GROUP BY labels(n) should produce 3 distinct groups, got {}: {:?}",
            r.row_count(),
            r.rows()
        );
    }

    #[test]
    fn group_by_labels_single_label_nodes() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Person {name: 'Alix'})").unwrap();
        s.execute("INSERT (:Person {name: 'Gus'})").unwrap();
        s.execute("INSERT (:Company {name: 'GrafeoDB'})").unwrap();

        let r = s
            .execute("MATCH (n) RETURN labels(n) AS lbl, count(*) AS cnt ORDER BY cnt DESC")
            .unwrap();

        // Should produce 2 groups: [Person] (2), [Company] (1)
        assert_eq!(
            r.row_count(),
            2,
            "GROUP BY labels(n) should produce 2 distinct groups, got {}: {:?}",
            r.row_count(),
            r.rows()
        );
    }

    #[test]
    fn group_by_date_valued_property() {
        let db = db();
        let s = db.session();
        s.execute("INSERT (:Event {name: 'A', day: date('2024-06-15')})")
            .unwrap();
        s.execute("INSERT (:Event {name: 'B', day: date('2024-06-15')})")
            .unwrap();
        s.execute("INSERT (:Event {name: 'C', day: date('2024-12-25')})")
            .unwrap();

        let r = s
            .execute("MATCH (e:Event) RETURN e.day AS day, count(*) AS cnt ORDER BY cnt DESC")
            .unwrap();

        assert_eq!(
            r.row_count(),
            2,
            "GROUP BY date should produce 2 distinct groups, got {}: {:?}",
            r.row_count(),
            r.rows()
        );
    }
}