File size: 123,596 Bytes
d086025 | 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 | diff --git a/docs/source/conf.py b/docs/source/conf.py
new file mode 100644
index 0000000000000000000000000000000000000000..95639318d100a5a4a568b326b99090aafbfbba36
--- /dev/null
+++ b/docs/source/conf.py
@@ -0,0 +1,56 @@
+# Configuration file for the Sphinx documentation builder.
+#
+# This file only contains a selection of the most common options. For a full
+# list see the documentation:
+# https://www.sphinx-doc.org/en/master/usage/configuration.html
+
+# -- Path setup --------------------------------------------------------------
+
+# If extensions (or modules to document with autodoc) are in another directory,
+# add these directories to sys.path here. If the directory is relative to the
+# documentation root, use os.path.abspath to make it absolute, like shown here.
+#
+import os
+import sys
+from cymple.version import __version__
+sys.path.insert(0, os.path.abspath('..'))
+
+
+# -- Project information -----------------------------------------------------
+
+project = 'Cymple'
+copyright = '2022, Accenture Labs Israel'
+author = 'Accenture Labs Israel'
+version = __version__
+release = __version__
+
+# -- General configuration ---------------------------------------------------
+
+# Add any Sphinx extension module names here, as strings. They can be
+# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
+# ones.
+extensions = [
+ "sphinx.ext.autodoc",
+ "sphinx.ext.autosummary",
+]
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# List of patterns, relative to source directory, that match files and
+# directories to ignore when looking for source files.
+# This pattern also affects html_static_path and html_extra_path.
+exclude_patterns = []
+
+
+# -- Options for HTML output -------------------------------------------------
+
+# The theme to use for HTML and HTML Help pages. See the documentation for
+# a list of builtin themes.
+#
+html_theme = 'sphinx_rtd_theme'
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = ['_static']
\ No newline at end of file
diff --git a/src/cymple/__init__.py b/src/cymple/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb7b8346ccd3fd826b8b636845d151db26a28280
--- /dev/null
+++ b/src/cymple/__init__.py
@@ -0,0 +1,7 @@
+"""Cymple - Cypher Modular Pythonic Language Extension
+A productivity enhancer for creating Cypher queries in Python
+"""
+
+from .version import __version__
+from .builder import QueryBuilder
+from .typedefs import Mapping
diff --git a/src/cymple/__main__.py b/src/cymple/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5e5261547e01fc89e5e6d60e3119d12c1fb7b1d
--- /dev/null
+++ b/src/cymple/__main__.py
@@ -0,0 +1,6 @@
+"""Package entrypoint when the package is run with -m option"""
+
+from .version import __version__
+
+if __name__ == '__main__':
+ print('Welcome to Cymple version ' + __version__)
diff --git a/src/cymple/builder.py b/src/cymple/builder.py
new file mode 100644
index 0000000000000000000000000000000000000000..bcc993eab90f41cf231b738e99425cdb0fcd007b
--- /dev/null
+++ b/src/cymple/builder.py
@@ -0,0 +1,1016 @@
+"""This is the Cymple query builder module."""
+
+# pylint: disable=R0901
+# pylint: disable=R0903
+# pylint: disable=W0102
+from typing import List, Union, Dict, Any
+from .typedefs import Mapping, Properties
+
+
+class Query():
+ """A general query-descripting class ."""
+
+ def __init__(self, query):
+ """Initialize the query object."""
+ self.query = query
+
+ def __str__(self) -> str:
+ """Implement the str() operator for the query builder."""
+ return self.query.strip()
+
+ def __add__(self, other):
+ """Implement the + operator for the query builder."""
+ return Query(self.query.strip() + ' ' + other.query.strip())
+
+ def __iadd__(self, other):
+ """Implement the += operator for the query builder."""
+ self.query = self.query.strip() + ' ' + other.query.strip()
+ return self
+
+ def get(self):
+ """Get the final query string ."""
+ return str(self)
+
+ def cypher(self, cypher_query_str):
+ """Concatenate a cypher query string"""
+ return AnyAvailable(self.query.strip() + ' ' + cypher_query_str.strip())
+
+
+class QueryStart(Query):
+ """A class for representing a "QUERY START" clause."""
+
+
+class Call(Query):
+ """A class for representing a "CALL" clause."""
+
+ def call(self):
+ """Concatenate the "CALL" clause.
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: CallAvailable
+ """
+ return CallAvailable(self.query + ' CALL')
+
+
+class Case(Query):
+ """A class for representing a "CASE" clause."""
+
+ def case(self, when_then_mapping: Dict[str, Union[List[str], str]], default_result: str, results_ref: str = None, test_expression: str = None):
+ """Concatenate a CASE clause to the query, to compare a single expression against multiple values or to express multiple conditional statements.
+
+ :param when_then_mapping: A dictionary such that a value represents a literal expression (or a list of
+ expressions) whose result will be compared to test_expression if given, else is evaluated to a BOOLEAN, and it's key represents the literal expression returned as output if the value matches test_expression if giver, or if the expression evaluates to TRUE.
+ :type when_then_mapping: Dict[str, Union[List[str], str]]
+ :param default_result: The expression to return if no value matches the test expression if given, or if all
+ expressions evaluated as FALSE.
+ :type default_result: str
+ :param results_ref: The reference name of the resulted returned values, plus any other desired reference names
+ to return., defaults to None
+ :type results_ref: str
+ :param test_expression: An expression to test the cases against. For example, 'n.name'. Optional., defaults to
+ None
+ :type test_expression: str
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: CaseAvailable
+ """
+ ret = " CASE"
+ if test_expression is not None:
+ ret += f" {test_expression}"
+ for then, when in when_then_mapping.items():
+ if type(when) is not list:
+ when = [when]
+ ret += f" WHEN {', '.join(when)} THEN {then}"
+ ret += f" ELSE {default_result} END"
+ if results_ref is not None:
+ ret += f" AS {results_ref}"
+ return CaseAvailable(self.query + ret)
+
+
+class CaseWhen(Query):
+ """A class for representing a "CASE WHEN" clause."""
+
+ def case_when(self, filters: dict, on_true: str, on_false: str, ref_name: str, comparison_operator: str = "=", boolean_operator: str = "AND", **kwargs):
+ """Concatenate a CASE WHEN clause to the query, created from a list of given property filters.
+
+ :param filters: A dict representing the set of properties to be filtered
+ :type filters: dict
+ :param on_true: The query to run when the predicate is true
+ :type on_true: str
+ :param on_false: The query to run when the predicate is false
+ :type on_false: str
+ :param ref_name: The name which is used to refer to the newly filtered object
+ :type ref_name: str
+ :param comparison_operator: A string operator, according to which the comparison between property values is
+ done, e.g. for "=", we get: property.name = property.value, defaults to "="
+ :type comparison_operator: str
+ :param boolean_operator: The boolean operator to apply between predicates, defaults to "AND"
+ :type boolean_operator: str
+ :param **kwargs: kwargs
+ :type **kwargs
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: CaseWhenAvailable
+ """
+ filt = ' CASE WHEN ' + Properties(filters).to_str(comparison_operator, boolean_operator, **kwargs)
+ filt += f' THEN {on_true} ELSE {on_false} END AS {ref_name}'
+ return CaseWhenAvailable(self.query + filt)
+
+
+class Create(Query):
+ """A class for representing a "CREATE" clause."""
+
+ def create(self):
+ """Concatenate the "CREATE" clause.
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: CreateAvailable
+ """
+ return CreateAvailable(self.query + ' CREATE')
+
+
+class Delete(Query):
+ """A class for representing a "DELETE" clause."""
+
+ def delete(self, ref_name: str):
+ """Concatenate a DELETE clause for a referenced instance from the DB.
+
+ :param ref_name: The reference name to be used for the delete operation
+ :type ref_name: str
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: DeleteAvailable
+ """
+ ret = f' DELETE {ref_name}'
+ return DeleteAvailable(self.query + ret)
+
+ def detach_delete(self, ref_name: str):
+ """Concatenate a DETACH DELETE clause for a referenced instance from the DB.
+
+ :param ref_name: The reference name to be used for the delete operation
+ :type ref_name: str
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: DeleteAvailable
+ """
+ ret = f' DETACH DELETE {ref_name}'
+ return DeleteAvailable(self.query + ret)
+
+
+class Limit(Query):
+ """A class for representing a "LIMIT" clause."""
+
+ def limit(self, limitation: Union[int, str]):
+ """Concatenate a limit statement.
+
+ :param limitation: A non-negative integer or a string of cypher expression that evaluates to a non-negative
+ integer (as long as it is not referring to any external variables)
+ :type limitation: Union[int, str]
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: LimitAvailable
+ """
+ ret = f" LIMIT {limitation}"
+ return LimitAvailable(self.query + ret)
+
+
+class Match(Query):
+ """A class for representing a "MATCH" clause."""
+
+ def match(self):
+ """Concatenate the "MATCH" clause.
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: MatchAvailable
+ """
+ return MatchAvailable(self.query + ' MATCH')
+
+ def match_optional(self):
+ """Concatenate the "MATCH" clause.
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: MatchAvailable
+ """
+ return MatchAvailable(self.query + ' OPTIONAL MATCH ')
+
+
+class Merge(Query):
+ """A class for representing a "MERGE" clause."""
+
+ def merge(self):
+ """Concatenate the "MERGE" clause.
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: MergeAvailable
+ """
+ return MergeAvailable(self.query + ' MERGE')
+
+
+class Node(Query):
+ """A class for representing a "NODE" clause."""
+
+ def node(self, labels: Union[List[str], str] = None, ref_name: str = None, properties: dict = None, **kwargs):
+ """Concatenate a graph Node, which may be filtered using any label/s and/or property/properties.
+
+ :param labels: The neo4j label (or list of labels) for that node, defaults to None
+ :type labels: Union[List[str], str]
+ :param ref_name: A reference name to be used later in the rest of the query, defaults to None
+ :type ref_name: str
+ :param properties: A dict representing the set of properties by which the nodes are filtered, defaults to None
+ :type properties: dict
+ :param **kwargs: kwargs
+ :type **kwargs
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: NodeAvailable
+ """
+ if not labels:
+ labels_string = ''
+ elif isinstance(labels, str):
+ labels_string = f': {labels}'
+ else:
+ labels_string = f': {": ".join(labels).strip()}'
+
+ if not properties:
+ property_string = ''
+ else:
+ property_string = f' {{{Properties(properties).to_str(**kwargs)}}}'
+
+ ref_name = ref_name or ''
+
+ query = self.query
+ if not (query.endswith('-') or query.endswith('>') or query.endswith('<')):
+ query += ' '
+
+ query += f'({ref_name}{labels_string}{property_string})'
+
+ if isinstance(self, MergeAvailable):
+ return NodeAfterMergeAvailable(query)
+
+ return NodeAvailable(query)
+
+
+class NodeAfterMerge(Query):
+ """A class for representing a "NODE AFTER MERGE" clause."""
+
+ def node(self, labels: Union[List[str], str] = None, ref_name: str = None, properties: dict = None, **kwargs):
+ """Concatenate a graph Node, which may be filtered using any label/s and/or property/properties.
+
+ :param labels: The neo4j label (or list of labels) for that node, defaults to None
+ :type labels: Union[List[str], str]
+ :param ref_name: A reference name to be used later in the rest of the query, defaults to None
+ :type ref_name: str
+ :param properties: A dict representing the set of properties by which the nodes are filtered, defaults to None
+ :type properties: dict
+ :param **kwargs: kwargs
+ :type **kwargs
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: NodeAfterMergeAvailable
+ """
+ if not labels:
+ labels_string = ''
+ elif isinstance(labels, str):
+ labels_string = f': {labels}'
+ else:
+ labels_string = f': {": ".join(labels).strip()}'
+
+ if not properties:
+ property_string = ''
+ else:
+ property_string = f' {{{Properties(properties).to_str(**kwargs)}}}'
+
+ ref_name = ref_name or ''
+
+ query = self.query
+ if not (query.endswith('-') or query.endswith('>') or query.endswith('<')):
+ query += ' '
+
+ query += f'({ref_name}{labels_string}{property_string})'
+
+ if isinstance(self, MergeAvailable):
+ return NodeAfterMergeAvailable(query)
+
+ return NodeAvailable(query)
+
+
+class OnCreate(Query):
+ """A class for representing a "ON CREATE" clause."""
+
+ def on_create(self):
+ """Concatenate the "ON CREATE" clause.
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: OnCreateAvailable
+ """
+ return OnCreateAvailable(self.query + ' ON CREATE')
+
+
+class OnMatch(Query):
+ """A class for representing a "ON MATCH" clause."""
+
+ def on_match(self):
+ """Concatenate the "ON MATCH" clause.
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: OnMatchAvailable
+ """
+ return OnMatchAvailable(self.query + ' ON MATCH')
+
+
+class OperatorEnd(Query):
+ """A class for representing a "OPERATOR END" clause."""
+
+ def operator_end(self):
+ """Concatenate the "OPERATOR END" clause.
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: OperatorEndAvailable
+ """
+ return OperatorEndAvailable(self.query + ' )')
+
+
+class OperatorStart(Query):
+ """A class for representing a "OPERATOR START" clause."""
+
+ def operator_start(self, operator: str, ref_name: str = None, args: dict = None):
+ """Concatenate an operator (e.g. ShortestPath), where its result may be given a name for future reference.
+
+ :param operator: The neo4j operator to be used (e.g. ShortestPath)
+ :type operator: str
+ :param ref_name: A reference name of the result, to be used later in the rest of the query, defaults to None
+ :type ref_name: str
+ :param args: A dict of arguments, to be passed to the operator function, defaults to None
+ :type args: dict
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: OperatorStartAvailable
+ """
+ result_name = '' if ref_name is None else f'{ref_name} = '
+ arguments = '' if args is None else f' {args}'
+
+ return OperatorStartAvailable(self.query + f' {result_name}{operator}({arguments}')
+
+
+class OrderBy(Query):
+ """A class for representing a "ORDER BY" clause."""
+
+ def order_by(self, sorting_properties: Union[str, List[str]], ascending: bool = True):
+ """Concatenate an order by statement.
+
+ :param sorting_properties: A string or a list of strings representing the properties based on which to sort.
+ :type sorting_properties: Union[str, List[str]]
+ :param ascending: Use ascending sorting (if false, uses descending)., defaults to True
+ :type ascending: bool
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: OrderByAvailable
+ """
+ if type(sorting_properties) != list:
+ sorting_properties = [sorting_properties]
+
+ ret = f" ORDER BY {', '.join(sorting_properties)}"
+ ret += " ASC" if ascending else " DESC"
+ return OrderByAvailable(self.query + ret)
+
+
+class Procedure(Query):
+ """A class for representing a "PROCEDURE" clause."""
+
+ def procedure(self, literal_procedure: str):
+ """Concatenate a literal procedure.
+
+ :param literal_procedure: A string that is evaluated to a cypher procedure
+ :type literal_procedure: str
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: ProcedureAvailable
+ """
+ ret = f" {literal_procedure}"
+ return ProcedureAvailable(self.query + ret)
+
+
+class Relation(Query):
+ """A class for representing a "RELATION" clause."""
+
+ def related(self, label: str = None, ref_name: str = None, properties: dict = None, min_hops: int = 1, max_hops: int = 1, **kwargs):
+ """Concatenate an undirectional (i.e. --) graph Relationship, which may be filtered.
+
+ :param label: The relationship label (type) in the DB, defaults to None
+ :type label: str
+ :param ref_name: A reference name to be used later in the rest of the query, defaults to None
+ :type ref_name: str
+ :param properties: A dict representing the set of properties by which the relationship is filtered, defaults to
+ None
+ :type properties: dict
+ :param min_hops: The minimal desired number of hops (set -1 for maximum boundary only), defaults to 1
+ :type min_hops: int
+ :param max_hops: The maximal desired number of hops (set -1 for minimal boundary only), defaults to 1
+ :type max_hops: int
+ :param **kwargs: kwargs
+ :type **kwargs
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: RelationAvailable
+ """
+ return RelationAvailable(self.query + self._directed_relation('none', label, ref_name, properties, min_hops, max_hops, **kwargs))
+
+ def related_to(self, label: str = None, ref_name: str = None, properties: dict = {}, min_hops: int = 1, max_hops: int = 1, **kwargs):
+ """Concatenate a forward (i.e. -->) graph Relationship, which may be filtered.
+
+ :param label: The relationship label (type) in the DB, defaults to None
+ :type label: str
+ :param ref_name: A reference name to be used later in the rest of the query, defaults to None
+ :type ref_name: str
+ :param properties: A dict representing the set of properties by which the relationship is filtered, defaults to
+ {}
+ :type properties: dict
+ :param min_hops: The minimal desired number of hops (set -1 for maximum boundary only), defaults to 1
+ :type min_hops: int
+ :param max_hops: The maximal desired number of hops (set -1 for minimal boundary only), defaults to 1
+ :type max_hops: int
+ :param **kwargs: kwargs
+ :type **kwargs
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: RelationAvailable
+ """
+ return RelationAvailable(self.query + self._directed_relation('forward', label, ref_name, properties, min_hops, max_hops, **kwargs))
+
+ def related_from(self, label: str = None, ref_name: str = None, properties: dict = {}, min_hops: int = 1, max_hops: int = 1, **kwargs):
+ """Concatenate a backward (i.e. <--) graph Relationship, which may be filtered.
+
+ :param label: The relationship label (type) in the DB, defaults to None
+ :type label: str
+ :param ref_name: A reference name to be used later in the rest of the query, defaults to None
+ :type ref_name: str
+ :param properties: A dict representing the set of properties by which the relationship is filtered, defaults to
+ {}
+ :type properties: dict
+ :param min_hops: The minimal desired number of hops (set -1 for maximum boundary only), defaults to 1
+ :type min_hops: int
+ :param max_hops: The maximal desired number of hops (set -1 for minimal boundary only), defaults to 1
+ :type max_hops: int
+ :param **kwargs: kwargs
+ :type **kwargs
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: RelationAvailable
+ """
+ return RelationAvailable(self.query + self._directed_relation('backward', label, ref_name, properties, min_hops, max_hops, **kwargs))
+
+ def _directed_relation(self, direction: str, label: str, ref_name: str = None, properties: dict = {}, min_hops: int = 1, max_hops: int = 1, **kwargs):
+ """Concatenate a graph Relationship (private method).
+
+ :param direction: The relationship direction, can one of 'forward', 'backward' - otherwise unidirectional
+ :type direction: str
+ :param label: The relationship label (type) in the DB
+ :type label: str
+ :param ref_name: A reference name to be used later in the rest of the query, defaults to None
+ :type ref_name: str
+ :param properties: A dict representing the set of properties by which the relationship is filtered, defaults to
+ {}
+ :type properties: dict
+ :param min_hops: The minimal desired number of hops (set -1 for maximum boundary only), defaults to 1
+ :type min_hops: int
+ :param max_hops: The maximal desired number of hops (set -1 for minimal boundary only), defaults to 1
+ :type max_hops: int
+ :param **kwargs: kwargs
+ :type **kwargs
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: RelationAvailable
+ """
+ min_hops_str = '' if min_hops == -1 else str(min_hops)
+ max_hops_str = '' if max_hops == -1 else str(max_hops)
+
+ relation_type = '' if label is None else f': {label}'
+ relation_ref_name = '' if ref_name is None else f'{ref_name}'
+ relation_properties = f' {{{Properties(properties).to_str(**kwargs)}}}' if properties else ''
+ if min_hops == 1 and max_hops == 1:
+ relation_length = ''
+ elif min_hops == -1 and max_hops == -1:
+ relation_length = '*'
+ elif min_hops == max_hops:
+ relation_length = f'*{min_hops_str}'
+ else:
+ relation_length = f'*{min_hops_str}..{max_hops_str}'
+
+ if relation_ref_name or relation_type or relation_length or relation_properties:
+ relation_str = f'[{relation_ref_name}{relation_type}{relation_length}{relation_properties}]'
+ else:
+ relation_str = ''
+
+ if direction == 'forward':
+ return f'-{relation_str}->'
+ if direction == 'backward':
+ return f'<-{relation_str}-'
+
+ return f'-{relation_str}-'
+
+
+class RelationAfterMerge(Query):
+ """A class for representing a "RELATION AFTER MERGE" clause."""
+
+ def related(self, label: str = None, ref_name: str = None, properties: dict = None, min_hops: int = 1, max_hops: int = 1, **kwargs):
+ """Concatenate an undirectional (i.e. --) graph Relationship, which may be filtered.
+
+ :param label: The relationship label (type) in the DB, defaults to None
+ :type label: str
+ :param ref_name: A reference name to be used later in the rest of the query, defaults to None
+ :type ref_name: str
+ :param properties: A dict representing the set of properties by which the relationship is filtered, defaults to
+ None
+ :type properties: dict
+ :param min_hops: The minimal desired number of hops (set -1 for maximum boundary only), defaults to 1
+ :type min_hops: int
+ :param max_hops: The maximal desired number of hops (set -1 for minimal boundary only), defaults to 1
+ :type max_hops: int
+ :param **kwargs: kwargs
+ :type **kwargs
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: RelationAfterMergeAvailable
+ """
+ return RelationAvailable(self.query + self._directed_relation('none', label, ref_name, properties, min_hops, max_hops, **kwargs))
+
+ def related_to(self, label: str = None, ref_name: str = None, properties: dict = {}, min_hops: int = 1, max_hops: int = 1, **kwargs):
+ """Concatenate a forward (i.e. -->) graph Relationship, which may be filtered.
+
+ :param label: The relationship label (type) in the DB, defaults to None
+ :type label: str
+ :param ref_name: A reference name to be used later in the rest of the query, defaults to None
+ :type ref_name: str
+ :param properties: A dict representing the set of properties by which the relationship is filtered, defaults to
+ {}
+ :type properties: dict
+ :param min_hops: The minimal desired number of hops (set -1 for maximum boundary only), defaults to 1
+ :type min_hops: int
+ :param max_hops: The maximal desired number of hops (set -1 for minimal boundary only), defaults to 1
+ :type max_hops: int
+ :param **kwargs: kwargs
+ :type **kwargs
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: RelationAfterMergeAvailable
+ """
+ return RelationAvailable(self.query + self._directed_relation('forward', label, ref_name, properties, min_hops, max_hops, **kwargs))
+
+ def related_from(self, label: str = None, ref_name: str = None, properties: dict = {}, min_hops: int = 1, max_hops: int = 1, **kwargs):
+ """Concatenate a backward (i.e. <--) graph Relationship, which may be filtered.
+
+ :param label: The relationship label (type) in the DB, defaults to None
+ :type label: str
+ :param ref_name: A reference name to be used later in the rest of the query, defaults to None
+ :type ref_name: str
+ :param properties: A dict representing the set of properties by which the relationship is filtered, defaults to
+ {}
+ :type properties: dict
+ :param min_hops: The minimal desired number of hops (set -1 for maximum boundary only), defaults to 1
+ :type min_hops: int
+ :param max_hops: The maximal desired number of hops (set -1 for minimal boundary only), defaults to 1
+ :type max_hops: int
+ :param **kwargs: kwargs
+ :type **kwargs
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: RelationAfterMergeAvailable
+ """
+ return RelationAvailable(self.query + self._directed_relation('backward', label, ref_name, properties, min_hops, max_hops, **kwargs))
+
+ def _directed_relation(self, direction: str, label: str, ref_name: str = None, properties: dict = {}, min_hops: int = 1, max_hops: int = 1, **kwargs):
+ """Concatenate a graph Relationship (private method).
+
+ :param direction: The relationship direction, can one of 'forward', 'backward' - otherwise unidirectional
+ :type direction: str
+ :param label: The relationship label (type) in the DB
+ :type label: str
+ :param ref_name: A reference name to be used later in the rest of the query, defaults to None
+ :type ref_name: str
+ :param properties: A dict representing the set of properties by which the relationship is filtered, defaults to
+ {}
+ :type properties: dict
+ :param min_hops: The minimal desired number of hops (set -1 for maximum boundary only), defaults to 1
+ :type min_hops: int
+ :param max_hops: The maximal desired number of hops (set -1 for minimal boundary only), defaults to 1
+ :type max_hops: int
+ :param **kwargs: kwargs
+ :type **kwargs
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: RelationAfterMergeAvailable
+ """
+ min_hops_str = '' if min_hops == -1 else str(min_hops)
+ max_hops_str = '' if max_hops == -1 else str(max_hops)
+
+ relation_type = '' if label is None else f': {label}'
+ relation_ref_name = '' if ref_name is None else f'{ref_name}'
+ relation_properties = f' {{{Properties(properties).to_str(**kwargs)}}}' if properties else ''
+ if min_hops == 1 and max_hops == 1:
+ relation_length = ''
+ elif min_hops == -1 and max_hops == -1:
+ relation_length = '*'
+ elif min_hops == max_hops:
+ relation_length = f'*{min_hops_str}'
+ else:
+ relation_length = f'*{min_hops_str}..{max_hops_str}'
+
+ if relation_ref_name or relation_type or relation_length or relation_properties:
+ relation_str = f'[{relation_ref_name}{relation_type}{relation_length}{relation_properties}]'
+ else:
+ relation_str = ''
+
+ if direction == 'forward':
+ return f'-{relation_str}->'
+ if direction == 'backward':
+ return f'<-{relation_str}-'
+
+ return f'-{relation_str}-'
+
+
+class Remove(Query):
+ """A class for representing a "REMOVE" clause."""
+
+ def remove(self, properties: Union[str, List[str]]):
+ """Concatenate a remove by statement.
+
+ :param properties: A string or a list of strings representing the properties to remove.
+ :type properties: Union[str, List[str]]
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: RemoveAvailable
+ """
+ if type(properties) != list:
+ properties = [properties]
+ ret = f" REMOVE {', '.join(properties)}"
+ return RemoveAvailable(self.query + ret)
+
+
+class Return(Query):
+ """A class for representing a "RETURN" clause."""
+
+ def return_literal(self, literal: str = None):
+ """Concatenate a literal RETURN statement.
+
+ :param literal: A Cypher string describing the objects to be returned, referencing name/names which were
+ defined earlier in the query, defaults to None
+ :type literal: str
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: ReturnAvailable
+ """
+ ret = f' RETURN'
+ if literal is not None:
+ ret += f' {literal}'
+
+ return ReturnAvailable(self.query + ret)
+
+ def return_mapping(self, mappings: List[Mapping]):
+ """Concatenate a RETURN statement for multiple objects.
+
+ :param mappings: The mapping (or a list of mappings) of db property names to code names, to be returned
+ :type mappings: List[Mapping]
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: ReturnAvailable
+ """
+ if not isinstance(mappings, list):
+ mappings = [mappings]
+
+ ret = ' RETURN ' + \
+ ', '.join(
+ f'{mapping[0]} AS {mapping[1]}' if mapping[1] else mapping[0].replace(".", "_")
+ for mapping in mappings)
+
+ return ReturnAvailable(self.query + ret)
+
+
+class Set(Query):
+ """A class for representing a "SET" clause."""
+
+ def set(self, properties: dict, escape_values: bool = True):
+ """Concatenate a SET clause, using the given properties map.
+
+ :param properties: A dict to be used to set the variables with their corresponding values
+ :type properties: dict
+ :param escape_values: Determines whether the properties values should be escaped or not, defaults to True
+ :type escape_values: bool
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: SetAvailable
+ """
+ if isinstance(properties, dict):
+ _properties = Properties(properties).to_str("=", ", ", escape_values)
+ else:
+ _properties = str(properties)
+
+ query = self.query + ' SET ' + _properties
+
+ if isinstance(self, NodeAfterMergeAvailable) or isinstance(self, OnCreateAvailable) or isinstance(self, OnMatchAvailable) or isinstance(self, SetAfterMergeAvailable):
+ return SetAfterMergeAvailable(query)
+
+ return SetAvailable(query)
+
+
+class SetAfterMerge(Query):
+ """A class for representing a "SET AFTER MERGE" clause."""
+
+ def set(self, properties: dict, escape_values: bool = True):
+ """Concatenate a SET clause, using the given properties map.
+
+ :param properties: A dict to be used to set the variables with their corresponding values
+ :type properties: dict
+ :param escape_values: Determines whether the properties values should be escaped or not, defaults to True
+ :type escape_values: bool
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: SetAfterMergeAvailable
+ """
+ if isinstance(properties, dict):
+ _properties = Properties(properties).to_str("=", ", ", escape_values)
+ else:
+ _properties = str(properties)
+
+ query = self.query + ' SET ' + _properties
+
+ if isinstance(self, NodeAfterMergeAvailable) or isinstance(self, OnCreateAvailable) or isinstance(self, OnMatchAvailable) or isinstance(self, SetAfterMergeAvailable):
+ return SetAfterMergeAvailable(query)
+
+ return SetAvailable(query)
+
+
+class Skip(Query):
+ """A class for representing a "SKIP" clause."""
+
+ def skip(self, skip_count: Union[int, str]):
+ """Concatenate a skip statement.
+
+ :param skip_count: A non-negative integer or a string of cypher expression that evaluates to a non-negative
+ integer (as long as it is not referring to any external variables)
+ :type skip_count: Union[int, str]
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: SkipAvailable
+ """
+ ret = f" SKIP {skip_count}"
+ return SkipAvailable(self.query + ret)
+
+
+class Union(Query):
+ """A class for representing a "UNION" clause."""
+
+ def union(self):
+ """Combines the results of two or more queries. Duplicates are removed.
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: UnionAvailable
+ """
+ return UnionAvailable(self.query + f' UNION')
+
+ def union_all(self):
+ """Combines the results of two or more queries including duplicates.
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: UnionAvailable
+ """
+ return UnionAvailable(self.query + f' UNION ALL')
+
+
+class Unwind(Query):
+ """A class for representing a "UNWIND" clause."""
+
+ def unwind(self, variables: str):
+ """Concatenate an UNWIND clause, keeping one or more variables given in 'variables' arg.
+
+ :param variables: A string refering to previously obtained variables, comma seperated
+ :type variables: str
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: UnwindAvailable
+ """
+ return UnwindAvailable(self.query + f' UNWIND {variables}')
+
+
+class Where(Query):
+ """A class for representing a "WHERE" clause."""
+
+ def where(self, name: str, comparison_operator: str, value: str, **kwargs):
+ """Concatenate a WHERE clause to the query, created as {name} {comparison_operator} {value}. E.g. x = 'abc'.
+
+ :param name: The name of the object which is to be used in the comparison
+ :type name: str
+ :param comparison_operator: A string operator, according to which the comparison between compared object and
+ the {value} is done, e.g. for "=", we get: {name} = {value}
+ :type comparison_operator: str
+ :param value: The value which is compared against
+ :type value: str
+ :param **kwargs: kwargs
+ :type **kwargs
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: WhereAvailable
+ """
+ return self.where_multiple({name: value}, comparison_operator, **kwargs)
+
+ def where_multiple(self, filters: dict, comparison_operator: str = "=", boolean_operator: str = ' AND ', **kwargs):
+ """Concatenate a WHERE clause to the query, created from a list of given property filters.
+
+ :param filters: A dict representing the set of properties to be filtered
+ :type filters: dict
+ :param comparison_operator: A string operator, according to which the comparison between property values is
+ done, e.g. for "=", we get: property.name = property.value, defaults to "="
+ :type comparison_operator: str
+ :param boolean_operator: The boolean operator to apply between predicates, defaults to ' AND '
+ :type boolean_operator: str
+ :param **kwargs: kwargs
+ :type **kwargs
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: WhereAvailable
+ """
+ filt = ' WHERE ' + Properties(filters).to_str(comparison_operator, boolean_operator, **kwargs)
+ return WhereAvailable(self.query + filt)
+
+ def where_literal(self, statement: str, **kwargs):
+ """Concatenate a literal WHERE clause to the query.
+
+ :param statement: A literal string of the required filter
+ :type statement: str
+ :param **kwargs: kwargs
+ :type **kwargs
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: WhereAvailable
+ """
+ filt = ' WHERE ' + statement
+ return WhereAvailable(self.query + filt)
+
+
+class With(Query):
+ """A class for representing a "WITH" clause."""
+
+ def with_(self, variables: str):
+ """Concatenate a WITH clause, keeping one or more variables given in 'variables' arg.
+
+ :param variables: A string refering to previously obtained variables, comma seperated
+ :type variables: str
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: WithAvailable
+ """
+ return WithAvailable(self.query + f' WITH {variables}')
+
+
+class Yield(Query):
+ """A class for representing a "YIELD" clause."""
+
+ def yield_(self, mappings: List[Mapping]):
+ """Concatenate a YIELD cluase, to yield a list of Mappings.
+
+ :param mappings: The list of mappings of db properties names to code names, to be yielded
+ :type mappings: List[Mapping]
+
+ :return: A Query object with a query that contains the new clause.
+ :rtype: YieldAvailable
+ """
+ if not isinstance(mappings, list):
+ mappings = [mappings]
+
+ query = ' YIELD ' + \
+ ', '.join(f'{mapping[0]} AS '
+ f'{mapping[1] if mapping[1] else mapping[0].replace(".", "_")}'
+ for mapping in mappings)
+ return YieldAvailable(self.query + query)
+
+
+class QueryStartAvailable(Match, Merge, Call, Create, With):
+ """A class decorator declares a QueryStart is available in the current query."""
+
+
+class CallAvailable(Procedure):
+ """A class decorator declares a Call is available in the current query."""
+
+
+class CaseAvailable(QueryStartAvailable, Unwind, Where, Set, Remove, CaseWhen, Return, Limit, Skip, OrderBy, Union):
+ """A class decorator declares a Case is available in the current query."""
+
+
+class CaseWhenAvailable(QueryStartAvailable, Unwind, Where, CaseWhen, Return, Set):
+ """A class decorator declares a CaseWhen is available in the current query."""
+
+
+class CreateAvailable(Node, Union):
+ """A class decorator declares a Create is available in the current query."""
+
+
+class DeleteAvailable(Return, CaseWhen, Union):
+ """A class decorator declares a Delete is available in the current query."""
+
+
+class LimitAvailable(QueryStartAvailable, Unwind, Where, CaseWhen, Return, Set, Skip, Union):
+ """A class decorator declares a Limit is available in the current query."""
+
+
+class MatchAvailable(Node, Return, OperatorStart):
+ """A class decorator declares a Match is available in the current query."""
+
+
+class MergeAvailable(NodeAfterMerge, Return, OperatorStart, Union):
+ """A class decorator declares a Merge is available in the current query."""
+
+
+class NodeAvailable(Relation, Return, Delete, Where, OperatorStart, OperatorEnd, Set, QueryStartAvailable, Merge, Remove):
+ """A class decorator declares a Node is available in the current query."""
+
+
+class NodeAfterMergeAvailable(RelationAfterMerge, Return, Delete, OperatorStart, OperatorEnd, SetAfterMerge, OnCreate, OnMatch, QueryStartAvailable):
+ """A class decorator declares a NodeAfterMerge is available in the current query."""
+
+
+class OnCreateAvailable(SetAfterMerge, OperatorStart):
+ """A class decorator declares a OnCreate is available in the current query."""
+
+
+class OnMatchAvailable(SetAfterMerge, OperatorStart):
+ """A class decorator declares a OnMatch is available in the current query."""
+
+
+class OperatorEndAvailable(QueryStartAvailable, Yield, With, Return):
+ """A class decorator declares a OperatorEnd is available in the current query."""
+
+
+class OperatorStartAvailable(QueryStartAvailable, Node, OperatorEnd):
+ """A class decorator declares a OperatorStart is available in the current query."""
+
+
+class OrderByAvailable(Limit, Skip, Union):
+ """A class decorator declares a OrderBy is available in the current query."""
+
+
+class ProcedureAvailable(Yield, Return, QueryStartAvailable, Union):
+ """A class decorator declares a Procedure is available in the current query."""
+
+
+class RelationAvailable(Node):
+ """A class decorator declares a Relation is available in the current query."""
+
+
+class RelationAfterMergeAvailable(NodeAfterMerge):
+ """A class decorator declares a RelationAfterMerge is available in the current query."""
+
+
+class RemoveAvailable(Set, Return, Union):
+ """A class decorator declares a Remove is available in the current query."""
+
+
+class ReturnAvailable(QueryStartAvailable, Unwind, Return, Limit, Skip, OrderBy, Union, CaseWhen, Case):
+ """A class decorator declares a Return is available in the current query."""
+
+
+class SetAvailable(QueryStartAvailable, Set, Remove, Unwind, Return, Union):
+ """A class decorator declares a Set is available in the current query."""
+
+
+class SetAfterMergeAvailable(QueryStartAvailable, OnCreate, OnMatch, SetAfterMerge, Unwind, Return, Union):
+ """A class decorator declares a SetAfterMerge is available in the current query."""
+
+
+class SkipAvailable(QueryStartAvailable, Unwind, Where, CaseWhen, Return, Set, Remove, Limit, Union):
+ """A class decorator declares a Skip is available in the current query."""
+
+
+class UnionAvailable(Call, Create, Delete, Match, Merge, Remove, Return, Set, Unwind, With):
+ """A class decorator declares a Union is available in the current query."""
+
+
+class UnwindAvailable(QueryStartAvailable, Unwind, Return, Create, Remove):
+ """A class decorator declares a Unwind is available in the current query."""
+
+
+class WhereAvailable(Return, Delete, Where, Set, Remove, OperatorStart, QueryStartAvailable):
+ """A class decorator declares a Where is available in the current query."""
+
+
+class WithAvailable(QueryStartAvailable, Unwind, Where, Set, Remove, CaseWhen, Return, Limit, Skip, OrderBy, Case):
+ """A class decorator declares a With is available in the current query."""
+
+
+class YieldAvailable(QueryStartAvailable, Node, Where, Return):
+ """A class decorator declares a Yield is available in the current query."""
+
+
+class AnyAvailable(Call, Case, CaseWhen, Create, Delete, Limit, Match, Merge, Node, NodeAfterMerge, OnCreate, OnMatch, OperatorEnd, OperatorStart, OrderBy, Procedure, QueryStart, Relation, RelationAfterMerge, Remove, Return, Set, SetAfterMerge, Skip, Union, Unwind, Where, With, Yield):
+ """A class decorator declares anything is available in the current query."""
+
+
+class QueryBuilder(QueryStartAvailable):
+ """The Query Builder's initial interface."""
+
+ def __init__(self) -> None:
+ """Initialize a query builder."""
+ super().__init__('')
+
+ def reset(self):
+ """Reset the query to an empty string."""
+ self.query = ''
+ return self
diff --git a/src/cymple/internal/finale.py b/src/cymple/internal/finale.py
new file mode 100644
index 0000000000000000000000000000000000000000..59e9b8412f8ea24a29f0f47cd04482cfa22765fa
--- /dev/null
+++ b/src/cymple/internal/finale.py
@@ -0,0 +1,11 @@
+class QueryBuilder(QueryStartAvailable):
+ """The Query Builder's initial interface."""
+
+ def __init__(self) -> None:
+ """Initialize a query builder."""
+ super().__init__('')
+
+ def reset(self):
+ """Reset the query to an empty string."""
+ self.query = ''
+ return self
diff --git a/src/cymple/internal/internal_renderer.py b/src/cymple/internal/internal_renderer.py
new file mode 100644
index 0000000000000000000000000000000000000000..86e44e2a0eeed31def96c2eafa87fd0ba493a302
--- /dev/null
+++ b/src/cymple/internal/internal_renderer.py
@@ -0,0 +1,181 @@
+"""Internal Rendering module, used for creating a new builder implementation."""
+
+import inspect
+import json
+import os
+import pathlib
+import preface
+import overloads
+
+query_class = getattr(preface, preface.Query.__name__)
+
+MAX_LINE_LEN = 120
+
+
+def _render_clause(declaration: dict):
+ main_output = ''
+ decorators_output = ''
+
+ clause_name = declaration['clause_name'].upper()
+ clause_name_title = declaration['clause_name'].title().replace(' ', '')
+
+ successors = declaration['successors']
+ avilability_class_str = f'class {clause_name_title}Available({", ".join(successors)}):' + '\n '
+ avilability_class_str += f'"""A class decorator declares a {clause_name_title} is available in the current query."""' + '\n\n'
+ decorators_output += avilability_class_str
+
+ main_output += f'class {clause_name_title}({query_class.__name__}):' + '\n '
+ main_output += f'"""A class for representing a "{clause_name}" clause."""' + '\n\n'
+
+ methods = declaration.get('methods')
+
+ if not methods and clause_name != 'QUERY START':
+ methods = [{'name': clause_name.replace(' ', '_')}]
+
+ for method in methods:
+ docstring_summary = method.get('docstring_summary', f'Concatenate the "{clause_name}" clause.')
+ method_name = method['name'].lower()
+ args = method.get('args')
+ args_str = 'self'
+
+ if not docstring_summary.endswith('.'):
+ docstring_summary = docstring_summary + '.'
+ docstring_summary += '\n '
+
+ docstring_params = ''
+ method_overload = None
+
+ if args:
+ for arg_name, arg_meta in args.items():
+ arg_description = arg_meta.get('description', '')
+ arg_type = arg_meta.get('type', '')
+ arg_default = arg_meta.get('default', '')
+ args_str += ', ' + \
+ f'{arg_name}{": " + arg_type if arg_type else ""}{" = " + arg_default if arg_default else ""}'
+
+ docstring_params += ':param ' + arg_name + (': ' + arg_description if arg_description else ': ' + arg_name) + (
+ f', defaults to {arg_default}' if arg_default else '') + '\n '
+ docstring_params += ':type ' + arg_name + \
+ (f': {arg_type}' if arg_type else '' + ', optional' if arg_default else '') + '\n '
+
+ try:
+ method_overload = getattr(overloads, method_name)
+ except Exception as ex:
+ print(f'Note: No overload to method "{method_name}" ({ex}).')
+
+ if method_overload:
+ try:
+ try:
+ method_overload.__doc__ = ''
+ except Exception as exc:
+ print(exc)
+
+ # overload = inspect.getsource(method_overload)
+ def_lines = inspect.getsourcelines(method_overload)[0]
+ overload = ''
+ flag = False
+ for line in def_lines:
+ if flag:
+ overload += line
+ elif line.strip().startswith(f'def {method_name}'):
+ flag = True
+
+ overload = overload.replace('\n', '\n ')
+
+ except Exception as ex:
+ print(f'Couldn\'t overload method "{method_name}". Exception: {ex}')
+ overload = ''
+ else:
+ overload = ''
+
+ main_output += f' def {method_name}({args_str}):' + '\n '
+ main_output += f'"""{docstring_summary}' + '\n '
+ main_output += f'{docstring_params}' + '\n ' if docstring_params else ''
+ main_output += f':return: A Query object with a query that contains the new clause.' + '\n '
+ main_output += f':rtype: {clause_name_title}Available' + '\n '
+ main_output += f'"""' + '\n '
+
+ if overload:
+ main_output += overload.strip()
+ else:
+ main_output += f'return {clause_name_title}Available(self.query + \' {clause_name}\')'
+
+ main_output += '\n\n'
+
+ lines = main_output.split('\n')
+ new_lines = []
+
+ for line in lines:
+ if len(line) >= MAX_LINE_LEN:
+ white_space_idx = 0
+ start_idx = 0
+
+ if ':param' in line:
+ start_idx = line.index(':param')
+
+ try:
+ while line.index(' ', white_space_idx + 1) < MAX_LINE_LEN:
+ white_space_idx = line.index(' ', white_space_idx + 1)
+ except:
+ pass
+
+ if start_idx > 0 and white_space_idx > start_idx:
+ new_lines.append(line[0:white_space_idx])
+ new_lines.append(' ' * start_idx + ' ' + line[white_space_idx+1:])
+ else:
+ new_lines.append(line)
+ else:
+ new_lines.append(line)
+
+ main_output = '\n'.join(new_lines)
+
+ return main_output, decorators_output, clause_name_title
+
+
+def render_builder_code():
+ """Main function to invoke to render a new builder implementation."""
+ clauses_output = '"""This is the Cymple query builder module."""\n\n'
+ clauses_output += '# pylint: disable=R0901\n'
+ clauses_output += '# pylint: disable=R0903\n'
+ clauses_output += '# pylint: disable=W0102\n'
+ clauses_output += 'from typing import List, Union, Dict, Any\n'
+ clauses_output += 'from .typedefs import Mapping, Properties\n\n'
+ clauses_output += inspect.getsource(query_class) + '\n\n'
+
+ decorators_output = '\n'
+
+ all_clauses_titles = set()
+
+ declarations_fps = os.listdir(os.path.join(os.path.dirname(__file__), 'declarations'))
+ declarations_fps.sort()
+
+ for file in declarations_fps:
+ if file.endswith('.json'):
+ path = os.path.join(os.path.dirname(__file__), 'declarations', file)
+
+ with open(path) as file:
+ declaration = json.load(file)
+ add_clause_output, add_decorators_output, clause_name_title = _render_clause(declaration)
+ clauses_output += add_clause_output
+ decorators_output += add_decorators_output
+ all_clauses_titles.add(clause_name_title)
+
+ any_clause_decorator_output = f'class AnyAvailable({", ".join(sorted(all_clauses_titles))}):' + '\n '
+ any_clause_decorator_output += f'"""A class decorator declares anything is available in the current query."""' + '\n\n'
+
+ with open(os.path.join(os.path.dirname(__file__), 'finale.py')) as file:
+ finale_output = file.read()
+
+ with open(os.path.join(os.path.dirname(__file__), '../builder.py'), 'w+') as file:
+ file.write(clauses_output)
+ file.write(decorators_output)
+ file.write(any_clause_decorator_output)
+ file.write(finale_output)
+
+ builder_path = os.path.join(pathlib.Path(__file__).parent.parent.resolve(), "builder.py")
+ os.system(
+ f'autopep8 {builder_path} --in-place --max-line-length {MAX_LINE_LEN}')
+
+
+if __name__ == '__main__':
+ render_builder_code()
diff --git a/src/cymple/internal/overloads/__init__.py b/src/cymple/internal/overloads/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4c28e87a347bf63726f3e046e737c8859322bca
--- /dev/null
+++ b/src/cymple/internal/overloads/__init__.py
@@ -0,0 +1,15 @@
+import sys
+import os
+import importlib
+import inspect
+
+
+overloads_module = sys.modules[__name__]
+
+for module_name in os.listdir(os.path.dirname(__file__)):
+ if module_name == '__init__.py' or module_name[-3:] != '.py':
+ continue
+ module = importlib.import_module(f'.{module_name[:-3]}', __name__)
+ funcs = inspect.getmembers(module, inspect.isfunction)
+ for name, func in funcs:
+ setattr(overloads_module, name, func)
diff --git a/src/cymple/internal/overloads/case.py b/src/cymple/internal/overloads/case.py
new file mode 100644
index 0000000000000000000000000000000000000000..a0c18ed35714b4c8ac88160d5968e99491bd5848
--- /dev/null
+++ b/src/cymple/internal/overloads/case.py
@@ -0,0 +1,15 @@
+from typing import Dict, List, Union
+
+
+def case(when_then_mapping: Dict[str, Union[List[str], str]], default_result: str, results_ref: str, test_expression: str = None):
+ ret = " CASE"
+ if test_expression is not None:
+ ret += f" {test_expression}"
+ for then, when in when_then_mapping.items():
+ if type(when) is not list:
+ when = [when]
+ ret += f" WHEN {', '.join(when)} THEN {then}"
+ ret += f" ELSE {default_result} END"
+ if results_ref is not None:
+ ret += f" AS {results_ref}"
+ return CaseAvailable(self.query + ret)
diff --git a/src/cymple/internal/overloads/case_when.py b/src/cymple/internal/overloads/case_when.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4f9fcba7b4dac4dede94a0ffa5093969438b181
--- /dev/null
+++ b/src/cymple/internal/overloads/case_when.py
@@ -0,0 +1,6 @@
+
+
+def case_when(self, filters: dict, on_true: str, on_false: str, ref_name: str, comparison_operator: str = '"', boolean_operator: str = 'AND', **kwargs):
+ filt = ' CASE WHEN ' + Properties(filters).to_str(comparison_operator, boolean_operator, **kwargs)
+ filt += f' THEN {on_true} ELSE {on_false} END AS {ref_name}'
+ return CaseWhenAvailable(self.query + filt)
diff --git a/src/cymple/internal/overloads/delete.py b/src/cymple/internal/overloads/delete.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bcee28af7a2409b5505615b1d99907b6e0009c4
--- /dev/null
+++ b/src/cymple/internal/overloads/delete.py
@@ -0,0 +1,8 @@
+def detach_delete(self, ref_name: str):
+ ret = f' DETACH DELETE {ref_name}'
+ return DeleteAvailable(self.query + ret)
+
+
+def delete(self, ref_name: str):
+ ret = f' DELETE {ref_name}'
+ return DeleteAvailable(self.query + ret)
diff --git a/src/cymple/internal/overloads/limit.py b/src/cymple/internal/overloads/limit.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a3b8aee6dd71335068990d79fefaa63ae9e8efa
--- /dev/null
+++ b/src/cymple/internal/overloads/limit.py
@@ -0,0 +1,6 @@
+from typing import Union
+
+
+def limit(self, limitation: Union[int, str]):
+ ret = f" LIMIT {limitation}"
+ return LimitAvailable(self.query + ret)
\ No newline at end of file
diff --git a/src/cymple/internal/overloads/match_optional.py b/src/cymple/internal/overloads/match_optional.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5de9c18e4b60c46c61fc04ca7dea668bf6fcaeb
--- /dev/null
+++ b/src/cymple/internal/overloads/match_optional.py
@@ -0,0 +1,2 @@
+def match_optional(self):
+ return MatchAvailable(self.query + ' OPTIONAL MATCH ')
diff --git a/src/cymple/internal/overloads/node.py b/src/cymple/internal/overloads/node.py
new file mode 100644
index 0000000000000000000000000000000000000000..cfe1036b5153fff82781ae302ac94440e6fc7785
--- /dev/null
+++ b/src/cymple/internal/overloads/node.py
@@ -0,0 +1,28 @@
+
+
+
+def node(self, labels=None, ref_name: str = None, properties: dict = None, **kwargs):
+ if not labels:
+ labels_string = ''
+ elif isinstance(labels, str):
+ labels_string = f': {labels}'
+ else:
+ labels_string = f': {": ".join(labels).strip()}'
+
+ if not properties:
+ property_string = ''
+ else:
+ property_string = f' {{{Properties(properties).to_str(**kwargs)}}}'
+
+ ref_name = ref_name or ''
+
+ query = self.query
+ if not (query.endswith('-') or query.endswith('>') or query.endswith('<')):
+ query += ' '
+
+ query += f'({ref_name}{labels_string}{property_string})'
+
+ if isinstance(self, MergeAvailable):
+ return NodeAfterMergeAvailable(query)
+
+ return NodeAvailable(query)
diff --git a/src/cymple/internal/overloads/operator_end.py b/src/cymple/internal/overloads/operator_end.py
new file mode 100644
index 0000000000000000000000000000000000000000..a0a32427d1aee8fcba83e3da7e06917a1758392f
--- /dev/null
+++ b/src/cymple/internal/overloads/operator_end.py
@@ -0,0 +1,2 @@
+def operator_end(self):
+ return OperatorEndAvailable(self.query + ' )')
diff --git a/src/cymple/internal/overloads/operator_start.py b/src/cymple/internal/overloads/operator_start.py
new file mode 100644
index 0000000000000000000000000000000000000000..14714c223a335500492500079242d32aa8551d1b
--- /dev/null
+++ b/src/cymple/internal/overloads/operator_start.py
@@ -0,0 +1,5 @@
+def operator_start(self, operator: str, ref_name: str = None, args: str = None):
+ result_name = '' if ref_name is None else f'{ref_name} = '
+ arguments = '' if args is None else f' {args}'
+
+ return OperatorStartAvailable(self.query + f' {result_name}{operator}({arguments}')
diff --git a/src/cymple/internal/overloads/order_by.py b/src/cymple/internal/overloads/order_by.py
new file mode 100644
index 0000000000000000000000000000000000000000..28195bedbd3379b08fea6ba0a1f7ca165d8c9213
--- /dev/null
+++ b/src/cymple/internal/overloads/order_by.py
@@ -0,0 +1,10 @@
+
+
+
+def order_by(sorting_properties, ascending=True):
+ if type(sorting_properties) != list:
+ sorting_properties = [sorting_properties]
+
+ ret = f" ORDER BY {', '.join(sorting_properties)}"
+ ret += " ASC" if ascending else " DESC"
+ return OrderByAvailable(self.query + ret)
diff --git a/src/cymple/internal/overloads/procedure.py b/src/cymple/internal/overloads/procedure.py
new file mode 100644
index 0000000000000000000000000000000000000000..c479046917bf383bbfe1f9085ff1d9de4dc81650
--- /dev/null
+++ b/src/cymple/internal/overloads/procedure.py
@@ -0,0 +1,3 @@
+def procedure(self, literal_procedure):
+ ret = f" {literal_procedure}"
+ return ProcedureAvailable(self.query + ret)
diff --git a/src/cymple/internal/overloads/relation.py b/src/cymple/internal/overloads/relation.py
new file mode 100644
index 0000000000000000000000000000000000000000..f243c6ab3ed3e9435959f6ea19b92cc25f3e0914
--- /dev/null
+++ b/src/cymple/internal/overloads/relation.py
@@ -0,0 +1,45 @@
+
+
+
+def related(self, label: str, ref_name: str = None, properties: dict = {}, min_hops: int = 1, max_hops: int = 1, **kwargs):
+ return RelationAvailable(self.query + self._directed_relation('none', label, ref_name, properties, min_hops, max_hops, **kwargs))
+
+
+def related_to(self, label: str, ref_name: str = None, properties: str = {}, min_hops: int = 1, max_hops: int = 1, **kwargs):
+ return RelationAvailable(self.query + self._directed_relation('forward', label, ref_name, properties, min_hops, max_hops, **kwargs))
+
+
+def related_from(self, label: str, ref_name: str = None, properties: str = {}, min_hops: int = 1, max_hops: int = 1, **kwargs):
+ return RelationAvailable(self.query + self._directed_relation('backward', label, ref_name, properties, min_hops, max_hops, **kwargs))
+
+
+def _directed_relation(self, direction: str, label: str, ref_name: str = None, properties: str = {}, min_hops: int = 1, max_hops: int = 1, **kwargs):
+ min_hops_str = '' if min_hops == -1 else str(min_hops)
+ max_hops_str = '' if max_hops == -1 else str(max_hops)
+
+ relation_type = '' if label is None else f': {label}'
+ relation_ref_name = '' if ref_name is None else f'{ref_name}'
+ relation_properties = f' {{{Properties(properties).to_str(**kwargs)}}}' if properties else ''
+ if min_hops == 1 and max_hops == 1:
+ relation_length = ''
+ elif min_hops == -1 and max_hops == -1:
+ relation_length = '*'
+ elif min_hops == max_hops:
+ relation_length = f'*{min_hops_str}'
+ else:
+ relation_length = f'*{min_hops_str}..{max_hops_str}'
+
+ if relation_ref_name or relation_type or relation_length or relation_properties:
+ relation_str = f'[{relation_ref_name}{relation_type}{relation_length}{relation_properties}]'
+ else:
+ relation_str = ''
+
+ if direction == 'forward':
+ return f'-{relation_str}->'
+ if direction == 'backward':
+ return f'<-{relation_str}-'
+
+ return f'-{relation_str}-'
+
+
+__all__ = ['related', 'related_to', 'related_from', '_directed_relation']
diff --git a/src/cymple/internal/overloads/remove.py b/src/cymple/internal/overloads/remove.py
new file mode 100644
index 0000000000000000000000000000000000000000..43b6f590ab27fcdd6b736d942128466eca5a4203
--- /dev/null
+++ b/src/cymple/internal/overloads/remove.py
@@ -0,0 +1,6 @@
+
+def remove(properties):
+ if type(properties) != list:
+ properties = [properties]
+ ret = f" REMOVE {', '.join(properties)}"
+ return RemoveAvailable(self.query + ret)
diff --git a/src/cymple/internal/overloads/returns.py b/src/cymple/internal/overloads/returns.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ddb571327cfb5d5697b58db2138c99c7371fa67
--- /dev/null
+++ b/src/cymple/internal/overloads/returns.py
@@ -0,0 +1,19 @@
+
+def return_literal(self, literal):
+ ret = f' RETURN'
+ if literal is not None:
+ ret += f' {literal}'
+
+ return ReturnAvailable(self.query + ret)
+
+
+def return_mapping(self, mappings):
+ if not isinstance(mappings, list):
+ mappings = [mappings]
+
+ ret = ' RETURN ' + \
+ ', '.join(
+ f'{mapping[0]} AS {mapping[1]}' if mapping[1] else mapping[0].replace(".", "_")
+ for mapping in mappings)
+
+ return ReturnAvailable(self.query + ret)
diff --git a/src/cymple/internal/overloads/set.py b/src/cymple/internal/overloads/set.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a874fdc525ef9b96afbf4e28361229eb5c8249a
--- /dev/null
+++ b/src/cymple/internal/overloads/set.py
@@ -0,0 +1,15 @@
+from typing import Union
+
+
+def set(self, properties: Union[str, dict], escape_values: bool = True):
+ if isinstance(properties, dict):
+ _properties = Properties(properties).to_str("=", ", ", escape_values)
+ else:
+ _properties = str(properties)
+
+ query = self.query + ' SET ' + _properties
+
+ if isinstance(self, NodeAfterMergeAvailable) or isinstance(self, OnCreateAvailable) or isinstance(self, OnMatchAvailable) or isinstance(self, SetAfterMergeAvailable):
+ return SetAfterMergeAvailable(query)
+
+ return SetAvailable(query)
diff --git a/src/cymple/internal/overloads/skip.py b/src/cymple/internal/overloads/skip.py
new file mode 100644
index 0000000000000000000000000000000000000000..cce9962435de7809bad83ab5308bd0d69af43a89
--- /dev/null
+++ b/src/cymple/internal/overloads/skip.py
@@ -0,0 +1,6 @@
+from typing import Union
+
+
+def skip(self, skip_count: Union[int, str]):
+ ret = f" SKIP {skip_count}"
+ return SkipAvailable(self.query + ret)
diff --git a/src/cymple/internal/overloads/union.py b/src/cymple/internal/overloads/union.py
new file mode 100644
index 0000000000000000000000000000000000000000..9fdbaaeb94f16d070da52273b8d660d978b2e62c
--- /dev/null
+++ b/src/cymple/internal/overloads/union.py
@@ -0,0 +1,6 @@
+def union(self):
+ return UnionAvailable(self.query + f' UNION')
+
+
+def union_all(self):
+ return UnionAvailable(self.query + f' UNION ALL')
\ No newline at end of file
diff --git a/src/cymple/internal/overloads/unwind.py b/src/cymple/internal/overloads/unwind.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9451b32cc738b0cb3766e8bf89523124f9d3ff1
--- /dev/null
+++ b/src/cymple/internal/overloads/unwind.py
@@ -0,0 +1,2 @@
+def unwind(self, variables: str):
+ return UnwindAvailable(self.query + f' UNWIND {variables}')
diff --git a/src/cymple/internal/overloads/where.py b/src/cymple/internal/overloads/where.py
new file mode 100644
index 0000000000000000000000000000000000000000..59a17d4fd036a8f9dbad5f4529779ee5d08a6dda
--- /dev/null
+++ b/src/cymple/internal/overloads/where.py
@@ -0,0 +1,14 @@
+from typing import Any
+
+
+
+def where_literal(self, statement: str, **kwargs):
+ filt = ' WHERE ' + statement
+ return WhereAvailable(self.query + filt)
+
+def where_multiple(self, filters: dict, comparison_operator: str = '=', boolean_operator: str = ' AND ', **kwargs):
+ filt = ' WHERE ' + Properties(filters).to_str(comparison_operator, boolean_operator, **kwargs)
+ return WhereAvailable(self.query + filt)
+
+def where(self, name: str, comparison_operator: str, value: Any, **kwargs):
+ return self.where_multiple({name: value}, comparison_operator, **kwargs)
diff --git a/src/cymple/internal/overloads/with_.py b/src/cymple/internal/overloads/with_.py
new file mode 100644
index 0000000000000000000000000000000000000000..b9d542131a22286945a609f99061f185d78e5552
--- /dev/null
+++ b/src/cymple/internal/overloads/with_.py
@@ -0,0 +1,2 @@
+def with_(self, variables: str):
+ return WithAvailable(self.query + f' WITH {variables}')
diff --git a/src/cymple/internal/overloads/yield_.py b/src/cymple/internal/overloads/yield_.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c7e9cd5f062ad003a59d85af04d365b512fe00b
--- /dev/null
+++ b/src/cymple/internal/overloads/yield_.py
@@ -0,0 +1,9 @@
+def yield_(self, mappings):
+ if not isinstance(mappings, list):
+ mappings = [mappings]
+
+ query = ' YIELD ' + \
+ ', '.join(f'{mapping[0]} AS '
+ f'{mapping[1] if mapping[1] else mapping[0].replace(".", "_")}'
+ for mapping in mappings)
+ return YieldAvailable(self.query + query)
diff --git a/src/cymple/internal/preface.py b/src/cymple/internal/preface.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ea35b0011a922bb1ff66daf675908252359e6aa
--- /dev/null
+++ b/src/cymple/internal/preface.py
@@ -0,0 +1,27 @@
+class Query():
+ """A general query-descripting class ."""
+
+ def __init__(self, query):
+ """Initialize the query object."""
+ self.query = query
+
+ def __str__(self) -> str:
+ """Implement the str() operator for the query builder."""
+ return self.query.strip()
+
+ def __add__(self, other):
+ """Implement the + operator for the query builder."""
+ return Query(self.query.strip() + ' ' + other.query.strip())
+
+ def __iadd__(self, other):
+ """Implement the += operator for the query builder."""
+ self.query = self.query.strip() + ' ' + other.query.strip()
+ return self
+
+ def get(self):
+ """Get the final query string ."""
+ return str(self)
+
+ def cypher(self, cypher_query_str):
+ """Concatenate a cypher query string"""
+ return AnyAvailable(self.query.strip() + ' ' + cypher_query_str.strip())
diff --git a/src/cymple/typedefs.py b/src/cymple/typedefs.py
new file mode 100644
index 0000000000000000000000000000000000000000..59de7882df3abf2f158672221abf324e72f79b7e
--- /dev/null
+++ b/src/cymple/typedefs.py
@@ -0,0 +1,36 @@
+"""Cymple's API type definitions."""
+from collections import namedtuple
+from typing import Any, List
+from dataclasses import dataclass
+
+Mapping = namedtuple('Mapping', ['ref_name', 'returned_name'], defaults=(None, None))
+
+
+class Properties(dict):
+ """A dict class storing a set of properties."""
+
+ @staticmethod
+ def _escape(string: str) -> str:
+ res = string.replace('\\', '\\\\').replace('"', '\\"').replace("'", "\\'").replace('\r', '\\r').replace('\n', '\\n')
+ return res
+
+ @staticmethod
+ def _format_value(value: Any, escape: bool) -> Any:
+ # Assigning a dict to a property is not supported by a neo4j graph
+ # if isinstance(value, dict):
+ # return str({sub_key: self._format_value(sub_value) for sub_key, sub_value in value.items()})
+ if escape and isinstance(value, str):
+ return f'"{Properties._escape(value)}"'
+ if value is None:
+ return 'null'
+
+ return value
+
+ def to_str(self, comparison_operator: str = ':', boolean_operator: str = ', ', escape: bool = True) -> str:
+ """Convert this Properties dicionarty to a serialied string suitable for a cypher query"""
+ pairs = [f'{key} {comparison_operator} {Properties._format_value(value, escape)}' for key, value in self.items()]
+ res = boolean_operator.join(pairs)
+ return res
+
+ def __str__(self) -> str:
+ return self.to_str()
diff --git a/src/cymple/version.py b/src/cymple/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..37d4ad1eab1228e9fb2ae00295b40601eb52751c
--- /dev/null
+++ b/src/cymple/version.py
@@ -0,0 +1,3 @@
+"""Version information for Cymple"""
+
+__version__: str = "0.12.0"
diff --git a/src/samples/basic.py b/src/samples/basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..d233d5ef32312339b4567fb895523c6fe670770d
--- /dev/null
+++ b/src/samples/basic.py
@@ -0,0 +1,95 @@
+
+from typing import Any, Dict, List, Union
+from cymple.builder import QueryBuilder
+
+
+
+def get_all_nodes_by_label(labels: Union[List[str], str], node_name: str = 'n'):
+ return (QueryBuilder()
+ .match()
+ .node(labels=labels, ref_name=node_name)
+ .return_literal(literal=node_name)
+ )
+
+
+def get_all_nodes_by_label_and_properties(labels: Union[List[str], str], properties: Dict[str, Any], node_name: str = 'n'):
+ return (QueryBuilder()
+ .match()
+ .node(labels=labels, ref_name=node_name, properties=properties)
+ .return_literal(literal=node_name)
+ )
+
+
+def get_all_paths(src_node_labels: Union[List[str], str], dst_node_labels: Union[List[str], str], relationship_type: str, path_name: str = 'p'):
+ return (QueryBuilder()
+ .match()
+ .operator_start(operator='', ref_name=path_name)
+ .node(labels=src_node_labels)
+ .related(label=relationship_type)
+ .node(labels=dst_node_labels)
+ .operator_end()
+ .return_literal(literal=path_name)
+ )
+
+
+def get_all_nodes_related_to_nodes(src_node_labels: Union[List[str], str], dst_node_labels: Union[List[str], str], relationship_type: str, dst_node_name: str = 'd'):
+ return (QueryBuilder()
+ .match()
+ .node(labels=src_node_labels)
+ .related(label=relationship_type)
+ .node(labels=dst_node_labels, ref_name=dst_node_name)
+ .return_literal(literal=dst_node_name)
+ )
+
+
+def get_all_nodes_related_by_fixed_num_of_hops(src_node_labels: Union[List[str], str], dst_node_labels: Union[List[str], str], num_hops: int, dst_node_name: str = 'd'):
+ return (QueryBuilder()
+ .match()
+ .node(labels=src_node_labels)
+ .related(min_hops=num_hops, max_hops=num_hops)
+ .node(labels=dst_node_labels, ref_name=dst_node_name)
+ .return_literal(literal=dst_node_name)
+ )
+
+
+def get_all_nodes_related_by_varying_num_of_hops(src_node_labels: Union[List[str], str], dst_node_labels: Union[List[str], str], min_hops: int, max_hops: int, dst_node_name: str = 'd'):
+ return (QueryBuilder()
+ .match()
+ .node(labels=src_node_labels)
+ .related(min_hops=min_hops, max_hops=max_hops)
+ .node(labels=dst_node_labels, ref_name=dst_node_name)
+ .return_literal(literal=dst_node_name)
+ )
+
+
+def get_nodes_with_pagination(node_labels: Union[List[str], str], node_name: str = 'n', offset: int = 0, limit: int = -1):
+ raise NotImplementedError()
+
+
+def create_node(node_labels: Union[List[str], str]):
+ raise NotImplementedError()
+
+
+def merge_node(node_labels: Union[List[str], str], properties: Dict[str, Any] = None):
+ return (QueryBuilder()
+ .merge()
+ .node(labels=node_labels, properties=properties)
+ )
+
+
+def create_relationship(relationship_type: str):
+ raise NotImplementedError()
+
+
+def merge_relationship(relationship_type: str, properties: Dict[str, Any] = None, src_node_labels: Union[List[str], str] = None,
+ dst_node_labels: Union[List[str], str] = None, src_node_properties: Dict[str, Any] = None, dst_node_properties: Dict[str, Any] = None):
+ return (QueryBuilder()
+ .match()
+ .node(labels=src_node_labels, properties=src_node_properties, ref_name='src')
+ .match()
+ .node(labels=dst_node_labels, properties=dst_node_properties, ref_name='dst')
+ .merge()
+ .node(ref_name='src')
+ .related_to(label=relationship_type, properties=properties)
+ .node(ref_name='dst')
+ )
diff --git a/src/samples/neo4j_config.py b/src/samples/neo4j_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..8bdffd3a32ebdf8d5feeed3687429d7bbbc78e3b
--- /dev/null
+++ b/src/samples/neo4j_config.py
@@ -0,0 +1,2 @@
+uri = 'bolt://127.0.0.1:7687'
+db_name = 'neo4j'
\ No newline at end of file
diff --git a/src/samples/neo4j_e2e.py b/src/samples/neo4j_e2e.py
new file mode 100644
index 0000000000000000000000000000000000000000..16444a4f176c86c6d9b9f84525d8f5c3d1873ae8
--- /dev/null
+++ b/src/samples/neo4j_e2e.py
@@ -0,0 +1,45 @@
+from cymple import QueryBuilder
+from samples.neo4j_helper import Neo4jDbSession, Neo4jQueryHelper
+from samples.neo4j_config import uri as neo4j_uri, db_name as neo4j_db
+
+helper: Neo4jQueryHelper
+builder: QueryBuilder
+
+label = 'Movie'
+property = 'name'
+reference = 'node'
+
+
+def init(neo4j_user, neo4j_password):
+ """Init this module by creating a session to the (neo4j) DB, creating a helper for running queries and a query builder"""
+ from neo4j import GraphDatabase
+
+ global helper
+ global builder
+
+ driver = GraphDatabase.driver(neo4j_uri, auth=(neo4j_user, neo4j_password))
+ session = Neo4jDbSession(driver=driver, db_name=neo4j_db)
+ helper = Neo4jQueryHelper(session)
+ builder = QueryBuilder()
+
+
+def read_movie_node(movie_name: str):
+ """Create a query for reading a node labeled 'Movie', with name given in movie_name"""
+ builder.reset()
+ query = str(builder
+ .match()
+ .node(labels=label, ref_name=reference, properties={property: movie_name})
+ .return_mapping((f'{reference}.{property}', property)))
+ results = helper.read(query)
+ return results[0].get(property) if results else None
+
+
+def write_movie_node(movie_name: str):
+ """Create a query for creating a node labeled 'Movie', with name given in movie_name"""
+ builder.reset()
+ query = str(builder
+ .merge()
+ .node(labels=label, ref_name=reference, properties={property: movie_name})
+ .return_mapping((f'{reference}.{property}', property)))
+ results = helper.write(query)
+ return results[0].get(property) if results else None
diff --git a/src/samples/neo4j_helper.py b/src/samples/neo4j_helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..967d4818a741404b915ec3fd4d77278423cba2f6
--- /dev/null
+++ b/src/samples/neo4j_helper.py
@@ -0,0 +1,93 @@
+from typing import Callable, Dict, List
+import logging
+
+logging.basicConfig(level=logging.INFO)
+
+
+class Neo4jDbSession:
+ """Context manager for a neo4j DB session."""
+
+ def __init__(self, driver, db_name: str):
+ self._db_name = db_name
+ self._driver = driver
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ self.close()
+
+ def close(self) -> None:
+ """Close the driver ."""
+ self._driver.close()
+
+ def read_transaction(self, transaction_function: Callable, query: str, parameters: Dict = None) -> List[Dict]:
+ """Perform a Read transaction on the database.
+
+ Args:
+ transaction_function (Callable): a function to be executed as a transaction on the DB
+ query (str): The actual query to be run
+ parameters (Dict, optional): Additional parameters to be used to run the query. Defaults to None.
+
+ Returns:
+ List[Dict]: A list of dictionary-represented objects as obtained by running the transaction
+ """
+ with self._driver.session(database=self._db_name) as session:
+ return session.read_transaction(transaction_function, query=query, parameters=parameters)
+
+ def write_transaction(self, transaction_function: Callable, query: str, parameters: Dict = None) -> List[Dict]:
+ """Perform a Write transaction on the database .
+
+ Args:
+ transaction_function (Callable): a function to be executed as a transaction on the DB
+ query (str): The actual query to be run
+ parameters (Dict, optional): Additional parameters to be used to run the query. Defaults to None.
+
+ Returns:
+ List[Dict]: A list of dictionary-represented objects as obtained by running the transaction
+ """
+ with self._driver.session(database=self._db_name) as session:
+ return session.write_transaction(transaction_function, query=query, parameters=parameters)
+
+
+class Neo4jQueryHelper():
+ """A helper class for running (Cypher) queries on a neo4j DB."""
+
+ @staticmethod
+ def run_query(t_x, query, parameters=None) -> List[Dict]:
+ """Transaction function to run a query against the database.
+
+ Returns:
+ List[Dict]: A list of dictionary-represented objects as obtained by running the query
+ """
+ res = t_x.run(query, parameters=parameters)
+ return res.data()
+
+ def __init__(self, session: Neo4jDbSession) -> None:
+ self.dbs = session
+
+ def read(self, query: str, parameters: Dict = None) -> List[Dict]:
+ """Run the given query against the database and returns the result as a Read operation.
+
+ Args:
+ query (str): a Cypher query to be run
+ parameters (Dict, optional): Additional parameters to be used to run the query. Defaults to None.
+
+ Returns:
+ List[Dict]: A list of dictionary-represented objects as obtained by running the query
+ """
+ logging.info('In %s, executing query: %s', self.read.__name__, query)
+ return self.dbs.read_transaction(self.run_query, query, parameters)
+
+ def write(self, query: str, parameters: Dict = None) -> List[Dict]:
+ """Run the given query against the database and returns the result as a Write operation.
+
+ Args:
+ query (str): a Cypher query to be run
+ parameters (Dict, optional): Additional parameters to be used to run the query. Defaults to None.
+
+ Returns:
+ List[Dict]: A list of dictionary-represented objects as obtained by running the query
+ """
+ logging.info('In %s, executing query: %s', self.write.__name__, query)
+ return self.dbs.write_transaction(self.run_query, query, parameters)
diff --git a/src/samples/version.py b/src/samples/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf14c7cf1dc349fc7a36304714844812d6466d39
--- /dev/null
+++ b/src/samples/version.py
@@ -0,0 +1,3 @@
+"""Version information for Cymple"""
+
+__version__: str = "0.4.2"
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c23018f5eacfda9fe079202d30b4b95072509d2f
--- /dev/null
+++ b/tests/__init__.py
@@ -0,0 +1 @@
+"""Test suite for the cymple package."""
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..7fa525725e33cbda3fe20dac6bda84b8de8b2404
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,22 @@
+from pytest import fixture
+
+
+def pytest_addoption(parser):
+ try:
+ parser.addoption('--e2e', action='store_true', default=False)
+ parser.addoption('--neo4j_user', action='store', default=None)
+ parser.addoption('--neo4j_password', action='store', default=None)
+ except Exception as ex:
+ print(ex)
+
+@fixture(scope='session')
+def is_run_e2e(pytestconfig) -> bool:
+ return pytestconfig.getoption('e2e')
+
+@fixture(scope='session')
+def neo4j_user(pytestconfig) -> bool:
+ return pytestconfig.getoption('neo4j_user')
+
+@fixture(scope='session')
+def neo4j_password(pytestconfig) -> bool:
+ return pytestconfig.getoption('neo4j_password')
diff --git a/tests/data/.gitkeep b/tests/data/.gitkeep
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tests/data/onto_types/labels.py b/tests/data/onto_types/labels.py
new file mode 100644
index 0000000000000000000000000000000000000000..fcf4939d7dc94e53d9877a43a51dcb2e02c80140
--- /dev/null
+++ b/tests/data/onto_types/labels.py
@@ -0,0 +1,14 @@
+from dataclasses import dataclass
+
+
+@dataclass
+class Labels:
+ Application: str = "Application"
+ CVEType: str = "CVEType"
+ CloudObject: str = "CloudObject"
+ Finding: str = "Finding"
+ FindingScan: str = "FindingScan"
+ FindingSourceType: str = "FindingSourceType"
+ FindingType: str = "FindingType"
+ ReferenceType: str = "ReferenceType"
+ ServiceType: str = "ServiceType"
diff --git a/tests/data/onto_types/properties.py b/tests/data/onto_types/properties.py
new file mode 100644
index 0000000000000000000000000000000000000000..deb0284d4cfe55099324664dd15ace67dbdd9256
--- /dev/null
+++ b/tests/data/onto_types/properties.py
@@ -0,0 +1,11 @@
+from dataclasses import dataclass
+
+
+@dataclass
+class Properties:
+ has_id: str = "has_id"
+ has_name: str = "has_name"
+ has_probability: str = "has_probability"
+ has_severity: str = "has_severity"
+ has_description: str = "has_description"
+ has_attack_scenario: str = "has_attack_scenario"
diff --git a/tests/data/onto_types/relations.py b/tests/data/onto_types/relations.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a1fad5e6e83ebac7a1c3827566b981198f9af21
--- /dev/null
+++ b/tests/data/onto_types/relations.py
@@ -0,0 +1,12 @@
+from dataclasses import dataclass
+
+
+@dataclass
+class Relations:
+ has_cloud_object: str = "has_cloud_object"
+ has_service: str = "has_service"
+ has_finding_type: str = "has_finding_type"
+ has_diagnosed_cloud_object: str = "has_diagnosed_cloud_object"
+ has_finding: str = "has_finding"
+ has_cve: str = "has_cve"
+ has_reference: str = "has_reference"
diff --git a/tests/e2e/.gitkeep b/tests/e2e/.gitkeep
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tests/e2e/test_e2e_samples.py b/tests/e2e/test_e2e_samples.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1eec7469dbe8213f9b2074fca5de00325022771
--- /dev/null
+++ b/tests/e2e/test_e2e_samples.py
@@ -0,0 +1,13 @@
+import pytest
+from samples import neo4j_e2e
+
+
+def test_neo4j_sample(is_run_e2e, neo4j_user, neo4j_password):
+ if not is_run_e2e:
+ pytest.skip('Use "pytest --e2e --neo4j_user <username> --neo4j_password <password>" to run this!')
+
+ movie_name = 'The Matrix'
+
+ neo4j_e2e.init(neo4j_user=neo4j_user, neo4j_password=neo4j_password)
+ assert neo4j_e2e.write_movie_node(movie_name) == movie_name
+ assert neo4j_e2e.read_movie_node(movie_name) == movie_name
diff --git a/tests/functional/__init__.py b/tests/functional/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tests/functional/test_functionality.py b/tests/functional/test_functionality.py
new file mode 100644
index 0000000000000000000000000000000000000000..421b4cd526c84fd9b6c6c066979d604e535b8d61
--- /dev/null
+++ b/tests/functional/test_functionality.py
@@ -0,0 +1,25 @@
+import inspect
+import pytest
+from cymple import QueryBuilder, builder
+
+any_available_clauses = [
+ ("cypher", {"cypher_query_str": ""})
+]
+
+
+@pytest.mark.parametrize("clause, params", any_available_clauses)
+def test_any_available(clause, params):
+ qb = QueryBuilder()
+ callables = [_callable for _callable in dir(getattr(qb.match(), clause)(*params))
+ if not _callable.startswith("__")]
+ builder_classes = [_class for _class in inspect.getmembers(
+ builder,
+ lambda member: inspect.isclass(member) and member.__module__ == builder.__name__
+ ) if not _class[0].lower().endswith("available") and _class[0].lower() != "querybuilder"]
+
+ missing_callables = set()
+ for _class in builder_classes:
+ missing_callables.update([
+ func for func in dir(_class[1]) if not func.startswith("__") and func not in callables
+ ])
+ assert not missing_callables
diff --git a/tests/integration/.gitkeep b/tests/integration/.gitkeep
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tests/unit/test_clauses.py b/tests/unit/test_clauses.py
new file mode 100644
index 0000000000000000000000000000000000000000..4dcca16b72ff9f8326614e657013d401a9ff7108
--- /dev/null
+++ b/tests/unit/test_clauses.py
@@ -0,0 +1,141 @@
+import pytest
+from cymple import QueryBuilder
+
+qb = QueryBuilder()
+
+rendered = {
+ '_RESET_': qb.reset(),
+ 'CALL': qb.reset().call().procedure("db.labels()"),
+ 'CASE WHEN': qb.reset().match().node(ref_name='n').with_('n').case_when({'n.name': 'Bob'}, 'true', 'false', 'my_boolean'),
+ 'DELETE': qb.reset().match().node(ref_name='n').delete('n'),
+ 'DETACH DELETE': qb.reset().match().node(ref_name='n').detach_delete('n'),
+ 'WHERE (single)': qb.reset().match().node(ref_name='n').where('n.name', '=', 'value'),
+ 'WHERE (multiple)': qb.reset().match().node(ref_name='n').where_multiple({'n.name': 'value', 'n.age': 20}),
+ 'WHERE (literal)': qb.reset().match().node(ref_name='n').where_literal('NOT exists(n)'),
+ 'MATCH': qb.reset().match(),
+ 'MATCH OPTIONAL': qb.reset().match_optional(),
+ 'MERGE': qb.reset().merge(),
+ 'NODE': qb.reset().match().node(['label1', 'label2'], 'node', {'name': 'Bob'}),
+ 'NODE MERGE': qb.reset().merge().node(labels=['label1', 'label2'], ref_name='n', properties={'name': 'Bob'}).related_to().node(ref_name='m'),
+ 'NODE (not escaping)': qb.reset().match().node(['label1', 'label2'], 'node', {'name': 'Bob'}, escape=False),
+ 'OPERATOR': qb.reset().match().operator_start('SHORTESTPATH', 'p', '(:A)-[*]-(:B)').operator_end(),
+ 'RELATION (forward)': qb.reset().match().node().related_to().node(),
+ 'RELATION (backward)': qb.reset().match().node().related_from().node(),
+ 'RELATION (unidirectional)': qb.reset().match().node().related().node(),
+ 'RELATION (variable length)': qb.reset().match().node().related(min_hops=1, max_hops=2).node(),
+ 'RELATION (variable length, empty)': qb.reset().match().node().related(min_hops=-1, max_hops=-1).node(),
+ 'RELATION (variable length, with label)': qb.reset().match().node().related(label='Relation', ref_name='rel', min_hops=1, max_hops=2).node(),
+ 'RETURN (literal)': qb.reset().match().node(ref_name='n').return_literal('n'),
+ 'RETURN (mapping)': qb.reset().match().node(ref_name='n').return_mapping(('n.name', 'name')),
+ 'RETURN (mapping, list)': qb.reset().match().node(ref_name='n').return_mapping([('n.name', 'name'), ('n.age', 'age')]),
+ 'SET': qb.reset().merge().node(ref_name='n').set({'n.name': 'Alice'}),
+ 'SET (not escaping)': qb.reset().merge().node(ref_name='n').set({'n.name': 'n.name + "!"'}, escape_values=False),
+ 'SET (string)': qb.reset().merge().node(ref_name='n').set('n.name = n.name + "!"'),
+ 'ON CREATE': qb.reset().merge().node(ref_name='n').on_create().set({'n.name': 'Bob'}),
+ 'ON MATCH': qb.reset().merge().node(ref_name='n').on_match().set({'n.name': 'Bob'}),
+ 'ON CREATE ON MATCH': qb.reset().merge().node(ref_name='n').on_create().set({'n.name': 'Bob'}).on_match().set({'n.name': 'Alice'}),
+ 'ON MATCH ON CREATE': qb.reset().merge().node(ref_name='n').on_match().set({'n.name': 'Bob'}).on_create().set({'n.name': 'Alice'}),
+ 'UNWIND': qb.reset().match().node(ref_name='n').with_('n').unwind('n'),
+ 'WITH': qb.reset().match().node(ref_name='a').with_('a,b'),
+ 'WITH (start)': qb.reset().with_('a').match().node(ref_name='a').with_('a,b'),
+ 'YIELD': qb.reset().call().procedure("db.labels()").yield_(("label", "label")).where("label", "CONTAINS", "User").return_literal("count(label) AS numLabels"),
+ 'YIELD (list)': qb.reset().call().procedure("db.labels()").yield_([('length(labels)', 'len'), ('count(label)', 'cnt')]),
+ 'LIMIT': qb.reset().match().node(ref_name='n').return_literal('n').limit(1),
+ 'LIMIT (expression)': qb.reset().match().node(ref_name='n').return_literal('n').limit("1 + toInteger(3 * rand())"),
+ 'LIMIT (with)': qb.reset().match().node(ref_name='n').with_('n').limit(1),
+ 'LIMIT (with set)': qb.reset().match().node(ref_name='n').with_('n').limit(1).set({'n.name': 'Bob'}),
+ 'CYPHER': qb.reset().match().node(ref_name='n').cypher("my cypher").limit(1),
+ 'SKIP': qb.reset().match().node(ref_name='n').return_literal('n').skip(1),
+ 'SKIP (expression)': qb.reset().match().node(ref_name='n').return_literal('n').skip("1 + toInteger(3 * rand())"),
+ 'SKIP (with)': qb.reset().match().node(ref_name='n').with_('n').skip(1),
+ 'SKIP (with set)': qb.reset().match().node(ref_name='n').with_('n').skip(1).set({'n.name': 'Bob'}),
+ 'ORDER BY': qb.match().node(ref_name='n').return_literal('n.name, n.age').order_by("elementId(n)"),
+ 'ORDER BY (List)': qb.match().node(ref_name='n').return_literal('n.name, n.age').order_by(
+ ["n.name", "keys(n)"]),
+ 'ORDER BY (Desc)': qb.match().node(ref_name='n').return_literal('n.name, n.age').order_by("n.name", False),
+ 'CREATE': qb.reset().create().node(ref_name='n').return_literal('n'),
+ 'REMOVE': qb.reset().match().node(ref_name='n').remove('n.name').return_literal('n.age, n.name'),
+ 'REMOVE (list)': qb.reset().match().node(ref_name='n').remove(['n.age', 'n.name']).return_literal('n.age, n.name'),
+ 'UNION': qb.match().node(ref_name='n', labels="Actor").return_mapping([('n.name', 'name')]).union().match().node(
+ ref_name='n', labels="Movie").return_mapping([('n.title', 'name')]),
+ 'UNION (all)': qb.match().node(ref_name='n', labels="Actor").return_mapping(
+ [('n.name', 'name')]).union_all().match().node(ref_name='n', labels="Movie").return_mapping([('n.title', 'name')]),
+ 'CASE (simple)': qb.match().node(ref_name="n", labels="Person").return_literal().case(when_then_mapping={"1": "'blue'", "2": ["'brown'", "'hazel'"]}, default_result="3", results_ref="result, n.eyes", test_expression="n.eyes"),
+ 'CASE (simple extended)': qb.match().node(ref_name="n", labels="Person").return_literal("n.name,").case(when_then_mapping={"'Unknown'": ["IS NULL", "IS NOT TYPED INTEGER | FLOAT"], "'Baby'": ["= 0", "= 1", "= 2"], "'Child'": "<= 13", "'Teenager'": "< 20", "'Young Adult'": "< 30", "'Immortal'": "> 1000"}, default_result="'Adult'", test_expression="n.age", results_ref="result"),
+ 'CASE (generic)': qb.match().node(ref_name="n", labels="Person").return_literal().case(when_then_mapping={"1": "n.eyes = 'blue'", "2": "n.age < 40"}, default_result="3", results_ref="result, n.eyes, n.age"),
+ 'CASE (null values)': qb.match().node(ref_name="n", labels="Person").return_literal("n.name,").case(when_then_mapping={"-1": "n.age IS NULL"}, default_result="n.age - 10", results_ref="age_10_years_ago"),
+ 'CASE (with set)': qb.match().node(ref_name="n", labels="Person").with_("n,").case(when_then_mapping={"1": "'blue'", "2": "'brown'"}, default_result="3", results_ref="colorCode", test_expression="n.eyes").set({"n.colorCode": "colorCode"}, escape_values=False).return_literal("n.name, n.colorCode")
+}
+
+expected = {
+ '_RESET_': '',
+ 'CALL': 'CALL db.labels()',
+ 'CASE WHEN': 'MATCH (n) WITH n CASE WHEN n.name = "Bob" THEN true ELSE false END AS my_boolean',
+ 'DELETE': 'MATCH (n) DELETE n',
+ 'DETACH DELETE': 'MATCH (n) DETACH DELETE n',
+ 'WHERE (single)': 'MATCH (n) WHERE n.name = "value"',
+ 'WHERE (multiple)': 'MATCH (n) WHERE n.name = "value" AND n.age = 20',
+ 'WHERE (literal)': 'MATCH (n) WHERE NOT exists(n)',
+ 'MATCH': 'MATCH',
+ 'MATCH OPTIONAL': 'OPTIONAL MATCH',
+ 'MERGE': 'MERGE',
+ 'NODE': 'MATCH (node: label1: label2 {name : "Bob"})',
+ 'NODE MERGE': 'MERGE (n: label1: label2 {name : "Bob"})-->(m)',
+ 'NODE (not escaping)': 'MATCH (node: label1: label2 {name : Bob})',
+ 'OPERATOR': 'MATCH p = SHORTESTPATH( (:A)-[*]-(:B) )',
+ 'RELATION (forward)': 'MATCH ()-->()',
+ 'RELATION (backward)': 'MATCH ()<--()',
+ 'RELATION (unidirectional)': 'MATCH ()--()',
+ 'RELATION (variable length)': 'MATCH ()-[*1..2]-()',
+ 'RELATION (variable length, empty)': 'MATCH ()-[*]-()',
+ 'RELATION (variable length, with label)': 'MATCH ()-[rel: Relation*1..2]-()',
+ 'RETURN (literal)': 'MATCH (n) RETURN n',
+ 'RETURN (mapping)': 'MATCH (n) RETURN n.name AS name',
+ 'RETURN (mapping, list)': 'MATCH (n) RETURN n.name AS name, n.age AS age',
+ 'SET': 'MERGE (n) SET n.name = "Alice"',
+ 'SET (not escaping)': 'MERGE (n) SET n.name = n.name + "!"',
+ 'SET (string)': 'MERGE (n) SET n.name = n.name + "!"',
+ 'ON CREATE': 'MERGE (n) ON CREATE SET n.name = "Bob"',
+ 'ON MATCH': 'MERGE (n) ON MATCH SET n.name = "Bob"',
+ 'ON CREATE ON MATCH': 'MERGE (n) ON CREATE SET n.name = "Bob" ON MATCH SET n.name = "Alice"',
+ 'ON MATCH ON CREATE': 'MERGE (n) ON MATCH SET n.name = "Bob" ON CREATE SET n.name = "Alice"',
+ 'UNWIND': 'MATCH (n) WITH n UNWIND n',
+ 'WITH': 'MATCH (a) WITH a,b',
+ 'WITH (start)': 'WITH a MATCH (a) WITH a,b',
+ 'YIELD': 'CALL db.labels() YIELD label AS label WHERE label CONTAINS "User" RETURN count(label) AS numLabels',
+ 'YIELD (list)': 'CALL db.labels() YIELD length(labels) AS len, count(label) AS cnt',
+ 'LIMIT': 'MATCH (n) RETURN n LIMIT 1',
+ 'LIMIT (expression)': 'MATCH (n) RETURN n LIMIT 1 + toInteger(3 * rand())',
+ 'LIMIT (with)': 'MATCH (n) WITH n LIMIT 1',
+ 'LIMIT (with set)': 'MATCH (n) WITH n LIMIT 1 SET n.name = "Bob"',
+ 'CYPHER': 'MATCH (n) my cypher LIMIT 1',
+ 'SKIP': 'MATCH (n) RETURN n SKIP 1',
+ 'SKIP (expression)': 'MATCH (n) RETURN n SKIP 1 + toInteger(3 * rand())',
+ 'SKIP (with)': 'MATCH (n) WITH n SKIP 1',
+ 'SKIP (with set)': 'MATCH (n) WITH n SKIP 1 SET n.name = "Bob"',
+ 'ORDER BY': 'MATCH (n) RETURN n.name, n.age ORDER BY elementId(n) ASC',
+ 'ORDER BY (List)': 'MATCH (n) RETURN n.name, n.age ORDER BY n.name, keys(n) ASC',
+ 'ORDER BY (Desc)': 'MATCH (n) RETURN n.name, n.age ORDER BY n.name DESC',
+ 'CREATE': 'CREATE (n) RETURN n',
+ 'REMOVE': 'MATCH (n) REMOVE n.name RETURN n.age, n.name',
+ 'REMOVE (list)': 'MATCH (n) REMOVE n.age, n.name RETURN n.age, n.name',
+ 'UNION': 'MATCH (n: Actor) RETURN n.name AS name UNION MATCH (n: Movie) RETURN n.title AS name',
+ 'UNION (all)': 'MATCH (n: Actor) RETURN n.name AS name UNION ALL MATCH (n: Movie) RETURN n.title AS name',
+ 'CASE (simple)': "MATCH (n: Person) RETURN CASE n.eyes WHEN 'blue' THEN 1 WHEN 'brown', 'hazel' THEN 2 ELSE 3 END"
+ " AS result, n.eyes",
+ 'CASE (simple extended)': "MATCH (n: Person) RETURN n.name, CASE n.age WHEN IS NULL, IS NOT TYPED INTEGER | FLOAT"
+ " THEN 'Unknown' WHEN = 0, = 1, = 2 THEN 'Baby' WHEN <= 13 THEN 'Child' WHEN < 20 THEN"
+ " 'Teenager' WHEN < 30 THEN 'Young Adult' WHEN > 1000 THEN 'Immortal' ELSE 'Adult' END"
+ " AS result",
+ 'CASE (generic)': "MATCH (n: Person) RETURN CASE WHEN n.eyes = 'blue' THEN 1 WHEN n.age < 40 THEN 2 ELSE 3 END"
+ " AS result, n.eyes, n.age",
+ 'CASE (null values)': "MATCH (n: Person) RETURN n.name, CASE WHEN n.age IS NULL THEN -1 ELSE n.age - 10 END"
+ " AS age_10_years_ago",
+ 'CASE (with set)': "MATCH (n: Person) WITH n, CASE n.eyes WHEN 'blue' THEN 1 WHEN 'brown' THEN 2 ELSE 3 END "
+ "AS colorCode SET n.colorCode = colorCode RETURN n.name, n.colorCode"
+}
+
+
+@pytest.mark.parametrize('clause', expected)
+def test_case(clause: str):
+ assert str(rendered[clause]) == expected[clause]
diff --git a/tests/unit/test_generated.py b/tests/unit/test_generated.py
new file mode 100644
index 0000000000000000000000000000000000000000..32668045c03288c52df11468b4dcae513a44de50
--- /dev/null
+++ b/tests/unit/test_generated.py
@@ -0,0 +1,33 @@
+import pytest
+from cymple import QueryBuilder
+
+qb = QueryBuilder()
+
+rendered = {
+ 'CASE_1': qb.reset().match().node(ref_name='p', labels='Person').return_mapping([('p.name', 'name'), ('CASE p.age WHEN 18 THEN "Young Adult" WHEN 65 THEN "Senior" ELSE "Adult" END', 'ageCategory')]),
+ 'CASE_2': qb.reset().match().node(ref_name='p', labels='Person').return_mapping([('p.name', 'name'), ('CASE WHEN p.age < 18 THEN "Minor" WHEN p.age >= 18 AND p.age < 65 THEN "Adult" ELSE "Senior" END', 'ageGroup')]),
+ 'CASE_3': qb.reset().match().node(ref_name='p', labels='Person').set({'p.category': 'CASE WHEN p.age < 18 THEN "Minor" WHEN p.age >= 18 AND p.age < 65 THEN "Adult" ELSE "Senior" END'}, escape_values=False).return_literal('p'),
+ 'CASE_4': qb.reset().match().node(ref_name='p', labels='Person').with_('p,').case(when_then_mapping={"\"America\"": "\"US\"", "\"North America\"": "\"Canada\""}, default_result="\"Other\"", results_ref='region', test_expression='p.country').return_literal('p.name, region'),
+ 'CASE_5': qb.reset().match().node(ref_name='p', labels='Person').return_mapping([('p.name', 'name'), ('CASE WHEN p.age < 18 THEN CASE p.age WHEN 0 THEN "Newborn" ELSE "Child" END WHEN p.age < 65 THEN "Adult" ELSE "Senior" END', 'lifeStage')]),
+ 'CASE_6': qb.reset().match().node(ref_name='p', labels='Person').return_mapping([('COUNT(CASE WHEN p.age < 18 THEN 1 END)', 'minors'), ('COUNT(CASE WHEN p.age >= 18 AND p.age < 65 THEN 1 END)', 'adults'), ('COUNT(CASE WHEN p.age >= 65 THEN 1 END)', 'seniors')]),
+ 'CASE_7': qb.reset().match().node(ref_name='p', labels='Person').where_literal('CASE WHEN p.age < 18 THEN false ELSE true END').return_literal('p'),
+ 'CASE_8': qb.reset().match().node(ref_name='p', labels='Person').return_mapping([('p.name', 'name'), ('p.age', 'age')]).order_by('CASE WHEN p.age < 18 THEN 1 WHEN p.age >= 18 AND p.age < 65 THEN 2 ELSE 3 END'),
+ 'CASE_9': qb.reset().match().node(ref_name='p', labels='Person').return_mapping([('p.name', 'name'), ('p.age', 'age'), ('CASE WHEN p.age < 18 THEN "Young " + p.name WHEN p.age >= 65 THEN "Senior " + p.name ELSE "Adult " + p.name END', 'titledName')])
+}
+
+expected = {
+ 'CASE_1': 'MATCH (p: Person) RETURN p.name AS name, CASE p.age WHEN 18 THEN "Young Adult" WHEN 65 THEN "Senior" ELSE "Adult" END AS ageCategory',
+ 'CASE_2': 'MATCH (p: Person) RETURN p.name AS name, CASE WHEN p.age < 18 THEN "Minor" WHEN p.age >= 18 AND p.age < 65 THEN "Adult" ELSE "Senior" END AS ageGroup',
+ 'CASE_3': 'MATCH (p: Person) SET p.category = CASE WHEN p.age < 18 THEN "Minor" WHEN p.age >= 18 AND p.age < 65 THEN "Adult" ELSE "Senior" END RETURN p',
+ 'CASE_4': 'MATCH (p: Person) WITH p, CASE p.country WHEN "US" THEN "America" WHEN "Canada" THEN "North America" ELSE "Other" END AS region RETURN p.name, region',
+ 'CASE_5': 'MATCH (p: Person) RETURN p.name AS name, CASE WHEN p.age < 18 THEN CASE p.age WHEN 0 THEN "Newborn" ELSE "Child" END WHEN p.age < 65 THEN "Adult" ELSE "Senior" END AS lifeStage',
+ 'CASE_6': 'MATCH (p: Person) RETURN COUNT(CASE WHEN p.age < 18 THEN 1 END) AS minors, COUNT(CASE WHEN p.age >= 18 AND p.age < 65 THEN 1 END) AS adults, COUNT(CASE WHEN p.age >= 65 THEN 1 END) AS seniors',
+ 'CASE_7': 'MATCH (p: Person) WHERE CASE WHEN p.age < 18 THEN false ELSE true END RETURN p',
+ 'CASE_8': 'MATCH (p: Person) RETURN p.name AS name, p.age AS age ORDER BY CASE WHEN p.age < 18 THEN 1 WHEN p.age >= 18 AND p.age < 65 THEN 2 ELSE 3 END ASC',
+ 'CASE_9': 'MATCH (p: Person) RETURN p.name AS name, p.age AS age, CASE WHEN p.age < 18 THEN "Young " + p.name WHEN p.age >= 65 THEN "Senior " + p.name ELSE "Adult " + p.name END AS titledName'
+}
+
+
+@pytest.mark.parametrize('clause', expected)
+def test_samples(clause: str):
+ assert str(rendered[clause]) == expected[clause]
diff --git a/tests/unit/test_real_use_cases.py b/tests/unit/test_real_use_cases.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b51db4f0f273b7bb23d8b8c81eaa4f1be17ade8
--- /dev/null
+++ b/tests/unit/test_real_use_cases.py
@@ -0,0 +1,396 @@
+from cymple import QueryBuilder
+
+from ..data.onto_types.labels import Labels
+from ..data.onto_types.properties import Properties
+from ..data.onto_types.relations import Relations
+
+
+def cypher_get_all_findings():
+ output_mapping = [('n', 'n')]
+ query = QueryBuilder().match().node(Labels.Finding, 'n').return_mapping(output_mapping).get()
+ return query
+
+
+def cypher_get_findings():
+ output_mapping = [(f'f.{Properties.has_id}', 'id'),
+ (f't.{Properties.has_probability}', 'probability'),
+ (f't.{Properties.has_severity}', 'severity'),
+ (f'ct.{Properties.has_id}', 'cve')]
+
+ query = (QueryBuilder().match()
+ .node(Labels.Finding, 'f')
+ .related_to(Relations.has_finding_type)
+ .node(Labels.FindingType, 't')
+ .related_to(Relations.has_cve)
+ .node(Labels.CVEType, 'ct')
+ .return_mapping(output_mapping)
+ .get())
+
+ return query
+
+
+def cypher_get_services():
+ output_mapping = [(f's.{Properties.has_id}', 'id'),
+ (f's.{Properties.has_name}', 'name')]
+
+ query = (QueryBuilder().match()
+ .node(Labels.ServiceType, 's')
+ .return_mapping(output_mapping)
+ .get())
+
+ return query
+
+
+def cypher_get_identities():
+ output_mapping = [(f'i.{Properties.has_id}', 'id'),
+ (f'i.{Properties.has_name}', 'name')]
+
+ query = (QueryBuilder().match()
+ .node(Labels.Identity, 'i')
+ .return_mapping(output_mapping)
+ .get())
+
+ return query
+
+
+def cypher_get_business_applications():
+ output_mapping = [(f'a.{Properties.has_id}', 'id'),
+ (f'a.{Properties.has_name}', 'name')]
+
+ query = (QueryBuilder().match()
+ .node(Labels.Application, 'a')
+ .return_mapping(output_mapping)
+ .get())
+
+ return query
+
+
+def cypher_get_finding_detailed(finding_id):
+ output_mapping = [(f'f.{Properties.has_id}', 'id'),
+ (f't.{Properties.has_probability}', 'probability'),
+ (f't.{Properties.has_severity}', 'severity'),
+ (f'ct.{Properties.has_id}', 'cve'),
+ (f't.{Properties.has_description}', 'description'),
+ (f't.{Properties.has_attack_scenario}', 'attack_scenario'),
+ (f't.recommendation', 'recommendations')]
+
+ query = (QueryBuilder().match()
+ .node(Labels.Finding, 'f', {Properties.has_id: finding_id})
+ .related_to(Relations.has_finding_type)
+ .node(Labels.FindingType, 't')
+ .related_to(Relations.has_cve)
+ .node(Labels.CVEType, 'ct')
+ .return_mapping(output_mapping)
+ .get())
+
+ return query
+
+
+def cypher_get_business_application(application_id):
+ output_mapping = [(f'a.{Properties.has_id}', 'id'),
+ (f'a.{Properties.has_name}', 'name')]
+
+ query = (QueryBuilder().match()
+ .node(Labels.Application, 'a', {Properties.has_id: application_id})
+ .return_mapping(output_mapping)
+ .get())
+
+ return query
+
+
+def cypher_get_references_for_finding(finding_id):
+ output_mapping = [(f'r.{Properties.has_description}', 'reference')]
+
+ query = (QueryBuilder().match()
+ .node(Labels.Finding, None, {Properties.has_id: finding_id})
+ .related_to(Relations.has_reference)
+ .node(Labels.ReferenceType, 'r')
+ .return_mapping(output_mapping)
+ .get())
+
+ return query
+
+
+def cypher_get_applications_for_finding(finding_id):
+ output_mapping = [(f'a.{Properties.has_name}', 'name')]
+
+ query = (QueryBuilder().match()
+ .node(Labels.Finding, None, {Properties.has_id: finding_id})
+ .related_to(Relations.has_cloud_object)
+ .node(Labels.Application, 'a')
+ .return_mapping(output_mapping)
+ .get())
+
+ return query
+
+
+def cypher_get_finding_type_details_per_id(id):
+ output_mapping = [(f'collect(t.{Properties.has_severity})', 'severities'),
+ (f'collect(t.{Properties.has_probability})', 'probabilities')]
+
+ query = (QueryBuilder().match()
+ .node(Labels.FindingType, 't')
+ .related_from(Relations.has_finding_type)
+ .node(Labels.Finding)
+ .related_to(Relations.has_cloud_object)
+ .node(Labels.CloudObject)
+ .related_to(Relations.has_service)
+ .node(None, None, {Properties.has_id: id})
+ .return_mapping(output_mapping)
+ .get())
+
+ return query
+
+
+def cypher_get_finding_details_for_application(application_id):
+ output_mapping = [(f'f.{Properties.has_id}', 'id'),
+ (f't.{Properties.has_probability}', 'probability'),
+ (f't.{Properties.has_severity}', 'severity'),
+ (f'ct.{Properties.has_id}', 'cve')]
+
+ query = (QueryBuilder().match()
+ .node(Labels.Application, None, {Properties.has_id: application_id})
+ .related_to(Relations.has_cloud_object)
+ .node(Labels.CloudObject)
+ .related_from(Relations.has_cloud_object)
+ .node(Labels.Finding, 'f')
+ .related_to(Relations.has_finding_type)
+ .node(Labels.FindingType, 't')
+ .related_to(Relations.has_cve)
+ .node(Labels.CVEType, 'ct')
+ .return_mapping(output_mapping)
+ .get())
+
+ return query
+
+
+def cypher_get_service_details_for_application(application_id):
+ output_mapping = [(f's.{Properties.has_id}', 'id'),
+ (f's.{Properties.has_name}', 'name')]
+
+ query = (QueryBuilder().match()
+ .node(Labels.Application, None, {Properties.has_id: application_id})
+ .related_to(Relations.has_cloud_object)
+ .node(Labels.CloudObject)
+ .related_to(Relations.has_service)
+ .node(Labels.ServiceType, 's')
+ .return_mapping(output_mapping)
+ .get())
+
+ return query
+
+
+def cypher_match_set_id(service_id):
+ query = (QueryBuilder().match()
+ .node(Labels.ServiceType, 's')
+ .set({Properties.has_id: service_id})
+ .return_literal('s')
+ .get())
+
+ return query
+
+
+def cypher_merge_on_match(service_id):
+ query = (QueryBuilder().merge()
+ .node(Labels.ServiceType, 's')
+ .on_match()
+ .set({Properties.has_id: service_id})
+ .return_literal('s')
+ .get())
+
+ return query
+
+
+def cypher_relationship_properties(service_id):
+ query = (QueryBuilder().match()
+ .node(Labels.Application)
+ .related_to(Relations.has_cloud_object)
+ .node(Labels.CloudObject)
+ .related_to(Relations.has_service, properties={Properties.has_id: service_id})
+ .node(Labels.ServiceType, 's', {Properties.has_id: service_id})
+ .return_literal('s')
+ .get())
+
+ return query
+
+
+def test_cypher_get_all_findings():
+ expected_query = f'MATCH (n: {Labels.Finding}) RETURN n AS n'
+ actual_query = cypher_get_all_findings()
+ assert actual_query == expected_query
+
+
+def test_cypher_get_findings():
+ expected_query = (
+ f'MATCH (f: {Labels.Finding})-[: {Relations.has_finding_type}]->'
+ f'(t: {Labels.FindingType})-[: {Relations.has_cve}]->(ct: {Labels.CVEType}) '
+ f'RETURN f.{Properties.has_id} AS id, t.{Properties.has_probability} AS probability, '
+ f't.{Properties.has_severity} AS severity, ct.{Properties.has_id} AS cve')
+ actual_query = cypher_get_findings()
+ assert actual_query == expected_query
+
+
+def test_cypher_get_services():
+ expected_query = (f'MATCH (s: {Labels.ServiceType}) '
+ f'RETURN s.{Properties.has_id} AS id, s.{Properties.has_name} AS name')
+ actual_query = cypher_get_services()
+ assert actual_query == expected_query
+
+
+def test_cypher_get_business_applications():
+ expected_query = (f'MATCH (a: {Labels.Application}) '
+ f'RETURN a.{Properties.has_id} AS id, a.{Properties.has_name} AS name')
+ actual_query = cypher_get_business_applications()
+ assert actual_query == expected_query
+
+
+def test_cypher_get_finding_detailed():
+ finding_id = 'THAT_is_MOCK_id'
+
+ expected_query = (
+ f'MATCH (f: {Labels.Finding} {{{Properties.has_id} : "{finding_id}"}})-'
+ f'[: {Relations.has_finding_type}]->(t: {Labels.FindingType})'
+ f'-[: {Relations.has_cve}]->(ct: {Labels.CVEType}) '
+ f'RETURN f.{Properties.has_id} AS id, '
+ f't.{Properties.has_probability} AS probability, '
+ f't.{Properties.has_severity} AS severity, ct.{Properties.has_id} AS cve, '
+ f't.{Properties.has_description} AS description, '
+ f't.{Properties.has_attack_scenario} AS attack_scenario, t.recommendation AS recommendations')
+
+ actual_query = cypher_get_finding_detailed(finding_id)
+ assert actual_query == expected_query
+
+
+def test_cypher_get_business_application():
+ application_id = 'THAT_is_MOCK_id'
+ expected_query = (f'MATCH (a: {Labels.Application} {{{Properties.has_id} : "{application_id}"}}) '
+ f'RETURN a.{Properties.has_id} AS id, a.{Properties.has_name} AS name')
+ actual_query = cypher_get_business_application(application_id)
+ assert actual_query == expected_query
+
+
+def test_cypher_get_references_for_finding():
+ finding_id = 'THAT_is_MOCK_id'
+
+ expected_query = (f'MATCH (: {Labels.Finding} {{{Properties.has_id} : "{finding_id}"}})'
+ f'-[: {Relations.has_reference}]->(r: {Labels.ReferenceType}) '
+ f'RETURN r.{Properties.has_description} AS reference')
+
+ actual_query = cypher_get_references_for_finding(finding_id)
+ assert actual_query == expected_query
+
+
+def test_cypher_get_applications_for_finding():
+ finding_id = 'THAT_is_MOCK_id'
+
+ expected_query = (
+ f'MATCH (: {Labels.Finding} {{{Properties.has_id} : "{finding_id}"}})'
+ f'-[: {Relations.has_cloud_object}]->(a: {Labels.Application}) '
+ f'RETURN a.{Properties.has_name} AS name')
+
+ actual_query = cypher_get_applications_for_finding(finding_id)
+ assert actual_query == expected_query
+
+
+def test_cypher_get_finding_type_details_for_service():
+ service_id = 'THAT_is_MOCK_id'
+
+ expected_query = (
+ f'MATCH (t: {Labels.FindingType})<-[: {Relations.has_finding_type}]-'
+ f'(: {Labels.Finding})-[: {Relations.has_cloud_object}]->'
+ f'(: {Labels.CloudObject})-[: {Relations.has_service}]->( {{{Properties.has_id} : "{service_id}"}}) '
+ f'RETURN collect(t.{Properties.has_severity}) AS severities, '
+ f'collect(t.{Properties.has_probability}) AS probabilities')
+
+ actual_query = cypher_get_finding_type_details_per_id(service_id)
+ assert actual_query == expected_query
+
+
+def test_cypher_match_set_id():
+ service_id = 'THAT_is_MOCK_id'
+
+ expected_query = f'MATCH (s: {Labels.ServiceType}) SET {Properties.has_id} = "{service_id}" RETURN s'
+
+ actual_query = cypher_match_set_id(service_id)
+ assert actual_query == expected_query
+
+
+def test_cypher_merge_on_match():
+ service_id = 'THAT_is_MOCK_id'
+
+ expected_query = f'MERGE (s: {Labels.ServiceType}) ON MATCH SET {Properties.has_id} = "{service_id}" RETURN s'
+
+ actual_query = cypher_merge_on_match(service_id)
+ assert actual_query == expected_query
+
+
+def test_cypher_relationship_properties():
+ service_id = 'THAT_is_MOCK_id'
+
+ expected_query = (
+ f'MATCH (: {Labels.Application})-[: {Relations.has_cloud_object}]->'
+ f'(: {Labels.CloudObject})-[: {Relations.has_service} {{{Properties.has_id} : "{service_id}"}}]->'
+ f'(s: {Labels.ServiceType} {{{Properties.has_id} : "{service_id}"}}) RETURN s')
+
+ actual_query = cypher_relationship_properties(service_id)
+ assert actual_query == expected_query
+
+def test_cypher_query_add():
+ service_id = 'THAT_is_MOCK_id'
+
+ expected_query = (
+ f'MATCH (: {Labels.Application})-[: {Relations.has_cloud_object}]->'
+ f'(: {Labels.CloudObject})-[: {Relations.has_service} {{{Properties.has_id} : "{service_id}"}}]->'
+ f'(s: {Labels.ServiceType} {{{Properties.has_id} : "{service_id}"}}) WITH s MATCH (s) RETURN s')
+
+ actual_query1 = (QueryBuilder().match()
+ .node(Labels.Application)
+ .related_to(Relations.has_cloud_object)
+ .node(Labels.CloudObject)
+ .related_to(Relations.has_service, properties={Properties.has_id: service_id})
+ .node(Labels.ServiceType, 's', {Properties.has_id: service_id})
+ .with_('s'))
+ actual_query2 = (QueryBuilder().match()
+ .node(ref_name='s')
+ .return_literal('s'))
+
+ actual_query = str(actual_query1 + actual_query2)
+ assert actual_query == expected_query
+
+ actual_query1 += actual_query2
+ actual_query = str(actual_query1)
+ assert actual_query == expected_query
+
+def test_cypher_set_unescaped_after_merge():
+ node_id = '1'
+
+ expected_query = (
+ f'MERGE (n: Node {{name : "test"}}) '
+ f'ON CREATE SET n.id = "{node_id}" '
+ f'ON MATCH SET n.id = n.id + "1" '
+ f'RETURN n')
+
+ actual_query = (QueryBuilder()
+ .merge()
+ .node('Node', 'n', {'name': 'test'})
+ .on_create().set({f'n.id': node_id})
+ .on_match().set({f'n.id': f'n.id + "1"'}, escape_values=False)
+ .return_literal('n')
+ .get())
+
+ assert actual_query == expected_query
+
+def test_multiple_where_1():
+ expected_query = 'MATCH (p) WHERE p.lock IS NULL OR p.value IS NULL'
+ actual_query = str(QueryBuilder().match().node(ref_name='p').where_multiple({'p.lock': 'NULL', 'p.value': 'NULL'}, 'IS', ' OR ', escape=False))
+ assert actual_query == expected_query
+
+def test_multiple_where_2():
+ expected_query = 'MATCH (n: Person) WHERE n.age=32 AND NOT n:Teacher'
+ actual_query = str(QueryBuilder().match().node('Person', ref_name='n').where_literal('n.age=32 AND NOT n:Teacher'))
+ assert actual_query == expected_query
+
+def test_with_list():
+ expected_query = 'MATCH (n) WITH n AS n_test WITH [n_test] AS n_list RETURN n_list AS n_test'
+ actual_query = str(QueryBuilder().match().node(ref_name='n').with_('n AS n_test').with_('[n_test] AS n_list').return_mapping(('n_list', 'n_test')))
+ assert actual_query == expected_query
\ No newline at end of file
diff --git a/tests/unit/test_samples.py b/tests/unit/test_samples.py
new file mode 100644
index 0000000000000000000000000000000000000000..81744f82623ad6459da9ef1e6f094f3c66d58e4d
--- /dev/null
+++ b/tests/unit/test_samples.py
@@ -0,0 +1,53 @@
+import pytest
+from src.samples import basic
+
+
+rendered = {
+ # Read Operations #
+ basic.get_all_nodes_by_label.__name__:
+ basic.get_all_nodes_by_label(labels='Movie', node_name='n'),
+ basic.get_all_nodes_by_label_and_properties.__name__:
+ basic.get_all_nodes_by_label_and_properties(labels='Movie', properties={'name': 'The Matrix'}, node_name='n'),
+ basic.get_all_paths.__name__:
+ basic.get_all_paths(src_node_labels='Movie', dst_node_labels='Director',
+ relationship_type='has_directed', path_name='path'),
+ basic.get_all_nodes_related_to_nodes.__name__:
+ basic.get_all_nodes_related_to_nodes(
+ src_node_labels='Movie', dst_node_labels='Director', relationship_type='has_directed', dst_node_name='director'),
+ basic.get_all_nodes_related_by_fixed_num_of_hops.__name__:
+ basic.get_all_nodes_related_by_fixed_num_of_hops(
+ src_node_labels='Movie', dst_node_labels='Director', num_hops=2, dst_node_name='director'),
+ basic.get_all_nodes_related_by_varying_num_of_hops.__name__:
+ basic.get_all_nodes_related_by_varying_num_of_hops(
+ src_node_labels='Movie', dst_node_labels='Director', min_hops=1, max_hops=3, dst_node_name='director'),
+ # Write Operations #
+ basic.merge_node.__name__:
+ basic.merge_node(node_labels='Movie', properties={'name': 'The Matrix Revolutions'}),
+ basic.merge_relationship.__name__:
+ basic.merge_relationship(relationship_type='has_sequel', src_node_labels='Movie', src_node_properties={'name': 'The Matrix'},
+ dst_node_labels='Movie', dst_node_properties={'name': 'The Matrix Revolutions'}),
+}
+
+expected = {
+ basic.get_all_nodes_by_label.__name__:
+ 'MATCH (n: Movie) RETURN n',
+ basic.get_all_nodes_by_label_and_properties.__name__:
+ 'MATCH (n: Movie {name : "The Matrix"}) RETURN n',
+ basic.get_all_paths.__name__:
+ 'MATCH path = ( (: Movie)-[: has_directed]-(: Director) ) RETURN path',
+ basic.get_all_nodes_related_to_nodes.__name__:
+ 'MATCH (: Movie)-[: has_directed]-(director: Director) RETURN director',
+ basic.get_all_nodes_related_by_fixed_num_of_hops.__name__:
+ 'MATCH (: Movie)-[*2]-(director: Director) RETURN director',
+ basic.get_all_nodes_related_by_varying_num_of_hops.__name__:
+ 'MATCH (: Movie)-[*1..3]-(director: Director) RETURN director',
+ basic.merge_node.__name__:
+ 'MERGE (: Movie {name : "The Matrix Revolutions"})',
+ basic.merge_relationship.__name__:
+ 'MATCH (src: Movie {name : "The Matrix"}) MATCH (dst: Movie {name : "The Matrix Revolutions"}) MERGE (src)-[: has_sequel]->(dst)',
+}
+
+
+@pytest.mark.parametrize('clause', expected)
+def test_samples(clause: str):
+ assert str(rendered[clause]) == expected[clause]
|