File size: 139,205 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 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 | diff --git a/dysql/__init__.py b/dysql/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..492ed753f2bef5ed18777a39eab6632440176c6c
--- /dev/null
+++ b/dysql/__init__.py
@@ -0,0 +1,60 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+# Public imports
+from .mappers import (
+ BaseMapper,
+ DbMapResult,
+ RecordCombiningMapper,
+ SingleRowMapper,
+ SingleColumnMapper,
+ SingleRowAndColumnMapper,
+ CountMapper,
+ KeyValueMapper,
+)
+from .query_utils import QueryData, QueryDataError, TemplateGenerators
+from .connections import (
+ sqlexists,
+ sqlquery,
+ sqlupdate,
+)
+from .databases import (
+ is_set_current_database_supported,
+ reset_current_database,
+ set_current_database,
+ set_database_init_hook,
+ set_default_connection_parameters,
+)
+from .multitenancy import use_database_tenant, tenant_database_manager
+from .exceptions import DBNotPreparedError
+
+
+__all__ = [
+ "BaseMapper",
+ "DbMapResult",
+ "RecordCombiningMapper",
+ "SingleRowMapper",
+ "SingleColumnMapper",
+ "SingleRowAndColumnMapper",
+ "CountMapper",
+ "KeyValueMapper",
+ "QueryData",
+ "QueryDataError",
+ "TemplateGenerators",
+ "sqlexists",
+ "sqlquery",
+ "sqlupdate",
+ "is_set_current_database_supported",
+ "reset_current_database",
+ "set_current_database",
+ "set_database_init_hook",
+ "set_default_connection_parameters",
+ "use_database_tenant",
+ "tenant_database_manager",
+ "DBNotPreparedError",
+]
diff --git a/dysql/annotations.py b/dysql/annotations.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a12d05f604c53466a5e3941a9141c873a2c9a21
--- /dev/null
+++ b/dysql/annotations.py
@@ -0,0 +1,31 @@
+"""
+Copyright 2023 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+from typing import TypeVar, Annotated
+
+from pydantic import BeforeValidator
+
+# pylint: disable=invalid-name
+T = TypeVar("T")
+
+
+def _transform_csv(value: str) -> T:
+ if not value:
+ return None
+
+ if isinstance(value, str):
+ return list(map(str.strip, value.split(",")))
+
+ if isinstance(value, list):
+ return value
+ # if we don't have a string or type T we aren't going to be able to transform it
+ return [value]
+
+
+# Annotation that helps transform a CSV string into a list of type T
+FromCSVToList = Annotated[T, BeforeValidator(_transform_csv)]
diff --git a/dysql/connections.py b/dysql/connections.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c30dd4ced04b3a681f6f6b9e4e7dbf346768131
--- /dev/null
+++ b/dysql/connections.py
@@ -0,0 +1,269 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+import logging
+import functools
+import inspect
+from typing import Type, Union
+
+import sqlalchemy
+
+from .databases import DatabaseContainerSingleton
+from .mappers import (
+ BaseMapper,
+ DbMapResult,
+ RecordCombiningMapper,
+)
+from .query_utils import get_query_data
+
+logger = logging.getLogger("database")
+
+# Always initialize a database container, it is never set again
+_DATABASE_CONTAINER = DatabaseContainerSingleton()
+
+
+class _ConnectionManager:
+ _connection: sqlalchemy.engine.base.Connection
+
+ # pylint: disable=unused-argument
+ def __init__(self, func, isolation_level, transaction, *args, **kwargs):
+ self._transaction = None
+
+ self._connection = (
+ _DATABASE_CONTAINER.current_database.engine.connect().execution_options(
+ isolation_level=isolation_level
+ )
+ )
+ if transaction:
+ self._transaction = self._connection.begin()
+
+ def __enter__(self):
+ self._connection.__enter__()
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ # Handle transaction committing/rollback before closing the connection
+ if exc_type:
+ logger.error(f"Encountered an error : {exc_val}")
+
+ # Roll back transaction if there is one
+ if self._transaction:
+ self._transaction.rollback()
+ elif self._transaction:
+ self._transaction.commit()
+
+ # Close the connection
+ self._connection.__exit__(exc_type, exc_val, exc_tb)
+
+ def execute_query(self, query, params=None) -> sqlalchemy.engine.CursorResult:
+ """
+ Executes the query through the connection with optional parameters.
+ :param query: The query to run
+ :param params: The parameters to use
+ :return: The result proxy object from sqlalchemy
+ """
+ if not params:
+ params = {}
+
+ if isinstance(params, DbMapResult):
+ params = params.raw()
+
+ return self._connection.execute(sqlalchemy.text(query), params)
+
+
+def sqlquery(
+ mapper: Union[BaseMapper, Type[BaseMapper]] = None,
+ isolation_level: str = "READ_COMMITTED",
+):
+ """
+ query allows for defining a parameterize select query that is then executed
+ :param mapper: a class extending from or an instance of BaseMapper, defaults to
+ RecordCombiningMapper
+ :param isolation_level: the isolation level to use for the transaction, defaults to
+ 'READ_COMMITTED'
+ :return: Depends on the mapper used, see mapper documentation for more details.
+
+ Examples::
+
+ # Uses the default RecordCombiningMapper, returns a list of results
+ @sqlquery()
+ def get_items(name, date):
+ return QueryData("SELECT item1, item2, ... FROM item join item_data ...
+ WHERE name=:name and date before :date"), {'name': name, 'date': date})
+
+ # Override the mapper to return a list of scalars
+ @sqlquery(mapper=SingleColumnMapper)
+ def get_items():
+ return QueryData("SELECT item1 FROM item join item_data ...")
+
+ # Override the mapper to return a single (first) result
+ @sqlquery(mapper=SingleRowMapper)
+ def get_items():
+ return QueryData("SELECT item1, item2, ... FROM item join item_data ...")
+
+ # Override the mapper to return a single result from the the first result
+ @sqlquery(mapper=CountMapper)
+ def get_count():
+ return QueryData("SELECT count(*) FROM item GROUP BY item1")
+ """
+
+ def decorator(func):
+ def handle_query(*args, **kwargs):
+ functools.wraps(func, handle_query)
+ actual_mapper = mapper
+ if not actual_mapper:
+ # Default to record combining mapper
+ actual_mapper = RecordCombiningMapper
+
+ # Handle mapper defined as a class
+ if inspect.isclass(actual_mapper):
+ actual_mapper = actual_mapper()
+
+ with _ConnectionManager(
+ func, isolation_level, False, *args, **kwargs
+ ) as conn_manager:
+ data = func(*args, **kwargs)
+ query, params = get_query_data(data)
+ records = conn_manager.execute_query(query, params)
+ return actual_mapper.map_records(records)
+
+ return handle_query
+
+ return decorator
+
+
+def sqlexists(isolation_level="READ_COMMITTED"):
+ """
+ exists query allows for defining a parameterize select query that is
+ wrapped in an exists clause and then executed
+ :param isolation_level: the isolation level to use for the transaction, defaults to
+ 'READ_COMMITTED'
+ :return: returns a True or False depending on the value returned from
+ the exists query. If Exists returns 1, True. otherwise, False
+ Examples::
+
+ @sqlexists
+ def get_items_exists(name, date):
+ return "SELECT 1 FROM item join item_data ...
+ WHERE name=:name and date before :date", { name=name, date=date}
+
+ @sqlexists
+ def get_items_exists():
+ return "SELECT 1 FROM item WHERE date before now()-100
+
+ """
+
+ def decorator(func):
+ def handle_query(*args, **kwargs):
+ functools.wraps(func, handle_query)
+ with _ConnectionManager(
+ func, isolation_level, False, *args, **kwargs
+ ) as conn_manager:
+ data = func(*args, **kwargs)
+ query, params = get_query_data(data)
+
+ query = query.lstrip()
+ if query.startswith("SELECT EXISTS"):
+ query = query.replace("SELECT EXISTS", "SELECT 1 WHERE EXISTS")
+ if not query.startswith("SELECT 1 WHERE EXISTS"):
+ query = f"SELECT 1 WHERE EXISTS ( {query} )"
+ result = conn_manager.execute_query(query, params).scalar()
+ return result == 1
+
+ return handle_query
+
+ return decorator
+
+
+def sqlupdate(
+ isolation_level="READ_COMMITTED",
+ disable_foreign_key_checks=False,
+ on_success=None,
+):
+ """
+ :param isolation_level should specify whether we can read data from transactions that are not
+ yet committed defaults to READ_COMMITTED
+ :param disable_foreign_key_checks Should be used with caution. Only use this if you have
+ confidence the data you are inserting is going to have everything it needs to satisfy
+ foreign_key_checks once all the data is applied. Foreign key checks are there to provide
+ our database with integrety
+
+ That being said, there are times when you are synchronizing data from another source that
+ you have data that may be difficult to sort ahead of time in order to avoid failing foreign
+ key constraints this flag helps to deal with cases where the logic may be unnecessarily
+ complex.
+
+ Note: this will work as expected when a normal transaction completes successfully and if a
+ transaction rolls back this will be left in a clean state as expected before executing
+ anything
+ Examples::
+
+ @sqlupdate
+ def insert_example(key_values)
+ return QueryData("INSERT INTO table(id, value) VALUES (:id, :value)", key_values)
+
+ @sqlupdate
+ def delete_example(ids)
+ return QueryData("DELETE FROM table WHERE id=:id", { "id": id })
+
+ @sqlupdate()
+ def insert_with_relations(get_last_insert_id = None):
+ yield QueryData("INSERT INTO table(value) VALUES (:value)", key_values)
+ id = get_last_insert_id()
+ yield "INSERT INTO relation_table(id, value) VALUES (:id, :value)", {
+ "id": id,
+ "value": "value"
+ })
+ """
+
+ def update_wrapper(func):
+ """
+ :param func: should return a tuple representing the query followed by the dictionary of key
+ values for query parameters
+ """
+
+ def handle_query(*args, **kwargs):
+ functools.wraps(func)
+ with _ConnectionManager(
+ func, isolation_level, True, *args, **kwargs
+ ) as conn_manager:
+ if disable_foreign_key_checks:
+ conn_manager.execute_query("SET FOREIGN_KEY_CHECKS=0")
+ last_insert_method = "get_last_insert_id"
+ if last_insert_method in inspect.signature(func).parameters:
+ kwargs[last_insert_method] = lambda: conn_manager.execute_query(
+ "SELECT LAST_INSERT_ID()"
+ ).scalar()
+ if inspect.isgeneratorfunction(func):
+ logger.debug("handling each query before committing transaction")
+
+ for data in func(*args, **kwargs):
+ query, params = get_query_data(data)
+ if isinstance(params, list):
+ for param in params:
+ conn_manager.execute_query(query, param)
+ else:
+ conn_manager.execute_query(query, params)
+ else:
+ data = func(*args, **kwargs)
+ query, params = get_query_data(data)
+ if isinstance(params, list):
+ raise Exception("Params must not be a list")
+ conn_manager.execute_query(query, params)
+
+ if disable_foreign_key_checks:
+ conn_manager.execute_query("SET FOREIGN_KEY_CHECKS=1")
+
+ if last_insert_method in kwargs:
+ del kwargs[last_insert_method]
+ if on_success:
+ on_success(*args, **kwargs)
+
+ return handle_query
+
+ return update_wrapper
diff --git a/dysql/databases.py b/dysql/databases.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c0213f8d177b0396703f2276dd56bf4489a6a22
--- /dev/null
+++ b/dysql/databases.py
@@ -0,0 +1,216 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+import contextvars
+import logging
+from collections import defaultdict
+from typing import Callable, Optional
+
+import sqlalchemy
+
+from .exceptions import DBNotPreparedError
+
+
+logger = logging.getLogger("database")
+
+_DEFAULT_CONNECTION_PARAMS_BY_KEY = defaultdict(dict)
+CURRENT_DATABASE_VAR = contextvars.ContextVar("dysql_current_database", default="")
+
+
+def set_database_init_hook(
+ hook_method: Callable[[Optional[str], sqlalchemy.engine.Engine], None],
+) -> None:
+ """
+ Sets an initialization hook whenever a new database is initialized. This method will receive the database name
+ (may be none) and the sqlalchemy engine as parameters.
+
+ :param hook_method: the hook method
+ """
+ Database.set_init_hook(hook_method)
+
+
+def is_set_current_database_supported() -> bool:
+ """
+ Deprecated, left in for backwards compatibility but always returns true.
+ :return: True
+ """
+ return True
+
+
+def set_current_database(database_key: str) -> None:
+ """
+ Sets the current database key, may be used for multitenancy. This is only supported on Python 3.7+. This uses
+ contextvars internally to set the name for the current async context.
+ :param database_key: the arbitrary database key to use for this async context
+ """
+ CURRENT_DATABASE_VAR.set(database_key)
+ logger.debug(f"Set current database to {database_key}")
+
+
+def reset_current_database() -> None:
+ """
+ Helper method to reset the current database to the default. Internally, this calls `set_current_database` with
+ an empty string.
+ """
+ set_current_database("")
+
+
+def _get_current_database_key() -> str:
+ """
+ The current database key, using contextvars (if on python 3.7+) or the default database key.
+ :return: The current database key
+ """
+ database: Optional[str] = None
+ if CURRENT_DATABASE_VAR:
+ database = CURRENT_DATABASE_VAR.get()
+ if not database and _DEFAULT_CONNECTION_PARAMS_BY_KEY:
+ # Get first database key
+ database = next(iter(_DEFAULT_CONNECTION_PARAMS_BY_KEY))
+ return database
+
+
+def _validate_param(name: str, value: str) -> None:
+ if not value:
+ raise DBNotPreparedError(
+ f'Database parameter "{name}" is not set or empty and is required'
+ )
+
+
+def set_default_connection_parameters(
+ host: str,
+ user: str,
+ password: str,
+ database: str,
+ database_key: Optional[str] = None,
+ port: int = 3306,
+ pool_size: int = 10,
+ pool_recycle: int = 3600,
+ echo_queries: bool = False,
+ charset: str = "utf8",
+ collation: Optional[str] = None,
+):
+ """
+ Initializes the parameters to use when connecting to the database. This is a subset of the parameters
+ used by sqlalchemy. These may be overridden by parameters provided in the QueryData, hence the "default".
+
+ :param host: the db host to try to connect to
+ :param user: user to connect to the database with
+ :param password: password for given user
+ :param database: database to connect to
+ :param database_key: optional database key that may be used for multitenant DBs, defaults to the database name
+ :param port: the port to connect to (default 3306)
+ :param pool_size: number of connections to maintain in the connection pool (default 10)
+ :param pool_recycle: amount of time to wait between resetting the connections
+ in the pool (default 3600)
+ :param echo_queries: this tells sqlalchemy to print the queries when set to True (default false)
+ :param charset: the charset for the sql engine to initialize with. (default utf8)
+ :param collation: the collation for the sql engine to initialize with. (default is not set)
+ :exception DBNotPrepareError: happens when required parameters are missing
+ """
+ _validate_param("host", host)
+ _validate_param("user", user)
+ _validate_param("password", password)
+ _validate_param("database", database)
+
+ if not database_key:
+ database_key = database
+ _DEFAULT_CONNECTION_PARAMS_BY_KEY[database_key].update(locals())
+
+
+class Database:
+ def __init__(self, database_key: Optional[str]) -> None:
+ self.database = database_key
+ # Engine is lazy-initialized
+ self._engine: Optional[sqlalchemy.engine.Engine] = None
+
+ @classmethod
+ def set_init_hook(
+ cls,
+ hook_method: Callable[[Optional[str], sqlalchemy.engine.Engine], None],
+ ) -> None:
+ cls.hook_method = hook_method
+
+ @property
+ def engine(self) -> sqlalchemy.engine.Engine:
+ if not self._engine:
+ connection_params = _DEFAULT_CONNECTION_PARAMS_BY_KEY.get(self.database, {})
+ if not connection_params:
+ raise DBNotPreparedError(
+ f"No connection parameters found for database key '{self.database}'"
+ )
+ user = connection_params.get("user")
+ password = connection_params.get("password")
+ database = connection_params.get("database")
+ host = connection_params.get("host")
+ port = connection_params.get("port")
+ charset = connection_params.get("charset")
+ collation = connection_params.get("collation")
+ collation_str = ""
+ if collation:
+ collation_str = f"&collation={collation}"
+
+ url = f"mysql+mysqlconnector://{user}:{password}@{host}:{port}/{database}?charset={charset}{collation_str}"
+ self._engine = sqlalchemy.create_engine(
+ url,
+ pool_recycle=connection_params.get("pool_recycle"),
+ pool_size=connection_params.get("pool_size"),
+ echo=connection_params.get("echo_queries"),
+ pool_pre_ping=True,
+ )
+ hook_method: Optional[
+ Callable[[Optional[str], sqlalchemy.engine.Engine], None]
+ ] = getattr(self.__class__, "hook_method", None)
+ if hook_method:
+ hook_method(database, self._engine)
+
+ return self._engine
+
+
+class DatabaseContainer(dict):
+ """
+ Implementation of a dictionary that always provides a Database class instance, even if the key is missing.
+ """
+
+ def __getitem__(self, database: Optional[str]) -> Database:
+ """
+ Override getitem to always return an instance of a database, which includes a lazy-initialized engine.
+ This also ensures that the database parameters have been initialized before attempting to retrieve a database.
+ :param database: the database name (may be null for the default database)
+ :return: a database instance
+ :raises DBNotPreparedError: when set_default_connection_parameters has not yet been called
+ """
+ if not _DEFAULT_CONNECTION_PARAMS_BY_KEY:
+ raise DBNotPreparedError(
+ "Unable to connect to a database, set_default_connection_parameters must first be called"
+ )
+
+ if not super().__contains__(database):
+ super().__setitem__(database, Database(database))
+ return super().__getitem__(database)
+
+ @property
+ def current_database(self) -> Database:
+ """
+ The current database instance, retrieved using contextvars (if python 3.7+) or the default database.
+ """
+ return self.__getitem__(_get_current_database_key())
+
+
+class DatabaseContainerSingleton(DatabaseContainer):
+ """
+ All instantiations of this class will result in the same instance every time due to the override of
+ the __new__ method.
+ """
+
+ def __new__(cls, *args, **kwargs) -> "DatabaseContainer":
+ instance = cls.__dict__.get("__instance__")
+ if instance is not None:
+ return instance
+ cls.__instance__ = instance = DatabaseContainer.__new__(cls)
+ instance.__init__(*args, **kwargs)
+ return instance
diff --git a/dysql/exceptions.py b/dysql/exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..19a86e1d679914ddae0692978c25ac2ab30df404
--- /dev/null
+++ b/dysql/exceptions.py
@@ -0,0 +1,13 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+
+class DBNotPreparedError(Exception):
+ """
+ DB Not Prepared Error
+ """
diff --git a/dysql/mappers.py b/dysql/mappers.py
new file mode 100644
index 0000000000000000000000000000000000000000..f560a6a97725f8e956c22c5b43ae213c834b76b5
--- /dev/null
+++ b/dysql/mappers.py
@@ -0,0 +1,268 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+# pylint: disable=too-few-public-methods
+
+import abc
+import logging
+from collections import OrderedDict, defaultdict
+from typing import Any, Optional, Type
+
+import sqlalchemy
+
+
+LOGGER = logging.getLogger(__name__)
+
+
+class MapperError(Exception):
+ pass
+
+
+class DbMapResultBase(abc.ABC):
+ @classmethod
+ def get_key_columns(cls):
+ return ["id"]
+
+ @classmethod
+ def create_instance(cls, *args, **kwargs) -> "DbMapResultBase":
+ """
+ Called instead of constructor, used to support different ways of
+ creating objects instead of constructors (if desired).
+ :return: an instance of the class
+ """
+ return cls(*args, **kwargs)
+
+ @abc.abstractmethod
+ def map_record(self, record: sqlalchemy.engine.Row) -> None:
+ """
+ Implements logic to handle the mapping of individual record objects from DB records.
+ :param record: a record row from the database
+ """
+
+ @abc.abstractmethod
+ def raw(self) -> dict:
+ """
+ Retrieves the raw data stored in this object as a dictionary.
+ :return: the dict representing the object data
+ """
+
+ @abc.abstractmethod
+ def has(self, field: str) -> bool:
+ """
+ Returns true if the field exists in the object.
+ :param field: the field to check
+ :return: True if the field exists, false otherwise
+ """
+
+ @abc.abstractmethod
+ def get(self, field: str, default: Any = None) -> Any:
+ """
+ Retrieves the value for the field, returning a default value if the field is not available.
+ :param field: the field to retrieve
+ :param default: the default value to return if the field is not available (defaults to None)
+ :return: the value of the field or the default value
+ """
+
+
+class DbMapResult(DbMapResultBase):
+ def __init__(self, **kwargs):
+ self.__dict__ = kwargs
+ # pylint: disable=invalid-name
+ if not self.__dict__.get("id"):
+ self.id = None
+
+ def __getitem__(self, field: str) -> Any:
+ return self.__dict__.get(field)
+
+ def __setitem__(self, field: str, value: Any) -> None:
+ self.__dict__[field] = value
+
+ def __str__(self) -> str:
+ return str(self.__dict__)
+
+ def map_record(self, record: sqlalchemy.engine.Row) -> None:
+ for column, value in record.items():
+ self[column] = value
+
+ def raw(self) -> dict:
+ def get_raw(value: Any) -> dict:
+ if isinstance(value, DbMapResultBase):
+ return value.raw()
+ return value
+
+ raw = {}
+ for key, value in self.__dict__.items():
+ if isinstance(value, list):
+ raw[key] = list(map(get_raw, value))
+ else:
+ raw[key] = get_raw(value)
+ # Remove the id field if it was never set
+ if raw.get("id") is None:
+ del raw["id"]
+ return raw
+
+ def has(self, field: str) -> bool:
+ return self.__dict__.get(field) is not None
+
+ def get(self, field: str, default: Any = None) -> Any:
+ return self.__dict__.get(field, default)
+
+
+class BaseMapper(metaclass=abc.ABCMeta):
+ """
+ Extend this class and implement the map_records method to map the results from a database query.
+ """
+
+ @abc.abstractmethod
+ def map_records(self, records: sqlalchemy.engine.CursorResult) -> Any:
+ pass
+
+
+class RecordCombiningMapper(BaseMapper):
+ """
+ Creates one or more mapped results from multiple records. This returns the same or less number
+ of results as there are records since it potentially combines multiple records with the same
+ identifier into a single result.
+
+ This depends on ``id`` being a column present in the records. If not, it will return a mapped
+ result for every row without combining records. Otherwise, a single result is returned for each
+ unique ``id`` value.
+ """
+
+ def __init__(self, record_mapper: Optional[Type[DbMapResultBase]] = DbMapResult):
+ """
+ :param record_mapper: what we are mapping records to.
+ """
+ self.record_mapper = record_mapper
+
+ def _get_lookup(self, record):
+ """
+ Return a lookup key based on a set of defined columns. if the id_columns aren't set we will look for an 'id'
+ column to maintain older expectations.
+ :param record:
+ :return: the value of the 'id' colum if id_columns are not set. the hash of the values from the id_colums.
+
+ Note: if the id_columns contain an invalid column, logs a warning and returns None
+ """
+ key_columns = self.record_mapper.get_key_columns()
+ if not key_columns:
+ # preserving older expectations
+ return None
+
+ values = []
+ for column in key_columns:
+ if column not in record:
+ # returning none because we don't want to make assumptions about how to handle a complex key
+ return None
+ values.append(record[column])
+ return hash(tuple(values))
+
+ def map_records(self, records: sqlalchemy.engine.CursorResult) -> Any:
+ if not self.record_mapper:
+ return records
+
+ current_results = OrderedDict()
+ current_num = 0
+ for record in records:
+ lookup = self._get_lookup(record)
+ if lookup:
+ if current_results.get(lookup) is None:
+ current_results[lookup] = self.record_mapper.create_instance()
+ current_results[lookup].map_record(record)
+ else:
+ current_results[current_num] = self.record_mapper.create_instance()
+ current_results[current_num].map_record(record)
+ current_num += 1
+
+ return list(v for k, v in current_results.items())
+
+
+class SingleRowMapper(BaseMapper):
+ """
+ Returns a single mapped result from one or more records. The first record is returned even if
+ there are multiple records from the database.
+ """
+
+ def __init__(self, record_mapper: Optional[Type[DbMapResultBase]] = DbMapResult):
+ self.record_mapper = record_mapper
+
+ def map_records(self, records: sqlalchemy.engine.CursorResult) -> Any:
+ if not self.record_mapper:
+ for record in records:
+ return record
+ return None
+
+ for record in records:
+ mapper = self.record_mapper.create_instance()
+ mapper.map_record(record)
+ return mapper
+ return None
+
+
+class SingleColumnMapper(BaseMapper):
+ """
+ Returns the first column value for each record from the database, even if multiple columns are
+ defined. This will return a list of scalar values.
+ """
+
+ def map_records(self, records: sqlalchemy.engine.CursorResult) -> Any:
+ results = []
+ for record in records:
+ for value in record.values():
+ results.append(value)
+ break
+ return results
+
+
+class SingleRowAndColumnMapper(BaseMapper):
+ """
+ Returns the first column in the first record from the database, even if multiple records or
+ columns exist. This will return a single scalar or None if there are no records.
+ """
+
+ def map_records(self, records: sqlalchemy.engine.CursorResult) -> Any:
+ for record in records:
+ for value in record.values():
+ return value
+ return None
+
+
+class CountMapper(SingleRowAndColumnMapper):
+ """
+ Alias for SingleRowAndColumnMapper, may be used to easily return the result of a count query.
+ """
+
+
+class KeyValueMapper(BaseMapper):
+ """
+ :param key_column can be specified to determine what field to map to as the key for are keyed values
+ :param value_column can be specified to help decide what column to add as a value
+ :param has_multiple_values_per_key is False by default but when True it tells the keyvalue mapper
+ the each key may have more than 1 result. this will returns a dictionary of lists when set
+
+ """
+
+ def __init__(self, key_column=0, value_column=1, has_multiple_values_per_key=False):
+ if key_column == value_column:
+ raise MapperError("key and value columns cannot be the same")
+
+ self.key_column = key_column
+ self.value_column = value_column
+ self.has_multiple_values_per_key = has_multiple_values_per_key
+
+ def map_records(self, records: sqlalchemy.engine.CursorResult) -> Any:
+ results = {}
+ if self.has_multiple_values_per_key:
+ results = defaultdict(list)
+ for record in records:
+ key = record[self.key_column]
+ value = record[self.value_column]
+ if self.has_multiple_values_per_key:
+ results[key].append(value)
+ else:
+ results[key] = value
+ return results
diff --git a/dysql/multitenancy.py b/dysql/multitenancy.py
new file mode 100644
index 0000000000000000000000000000000000000000..5cb8a769b7cbe3cc0847aef8b5ec6de6b0436988
--- /dev/null
+++ b/dysql/multitenancy.py
@@ -0,0 +1,69 @@
+"""
+Copyright 2025 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+import functools
+import logging
+from typing import Any, Callable, TypeVar
+from contextlib import contextmanager
+
+from dysql.exceptions import DBNotPreparedError
+from dysql import (
+ set_current_database,
+ reset_current_database,
+)
+
+LOGGER = logging.getLogger(__name__)
+
+F = TypeVar("F", bound=Callable[..., Any])
+
+
+@contextmanager
+def tenant_database_manager(database_key: str):
+ """
+ Context manager for temporarily switching to a different database.
+
+ :param database_key: the database key to switch to
+ :raises DBNotPreparedError: if the database key is not set
+ """
+ if not database_key:
+ raise DBNotPreparedError(
+ "Cannot switch to database tenant with empty database key"
+ )
+
+ try:
+ LOGGER.debug(f"Switching to database {database_key}")
+ set_current_database(database_key)
+ yield
+ except Exception as e:
+ LOGGER.error(f"Error while using database {database_key}: {e}")
+ raise
+ finally:
+ try:
+ reset_current_database()
+ LOGGER.debug(f"Reset database context from: {database_key}")
+ except Exception as e:
+ LOGGER.error(f"Error resetting database context: {e}")
+ # Don't re-raise here to avoid masking the original exception
+
+
+def use_database_tenant(database_key: str):
+ """
+ Decorator that switches to a specific database for the duration of the function call.
+ :param database_key: the database key to use
+ :return: the decorator function
+ """
+
+ def decorator(func: F) -> F:
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ with tenant_database_manager(database_key):
+ return func(*args, **kwargs)
+
+ return wrapper
+
+ return decorator
diff --git a/dysql/pydantic_mappers.py b/dysql/pydantic_mappers.py
new file mode 100644
index 0000000000000000000000000000000000000000..849ab85107547d474a8bc6968ba95703790845f3
--- /dev/null
+++ b/dysql/pydantic_mappers.py
@@ -0,0 +1,163 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+from typing import Any, Dict, Set
+
+import sqlalchemy
+from pydantic import BaseModel, TypeAdapter
+
+from .mappers import DbMapResultBase
+
+
+class DbMapResultModel(BaseModel, DbMapResultBase):
+ """
+ Pydantic model that allows for results to be mapped into annotated fields without explicitly
+ mapping each field. The metadata fields starting with "_" are special fields that allow lists, sets,
+ and dictionaries to be mapped correctly if more than one record is mapped to an instance.
+
+ Note that validation *does* occur the very first time map_record is called, but not on subsequent runs. Therefore
+ if you desire better validation for list, set, or dict fields, that must most likely be done outside of pydantic.
+
+ Additionally, lists, sets, and dicts will ignore null values from the database. Therefore you must provide default
+ values for these fields when used or else validation will fail.
+ """
+
+ # List fields that are aggregated into a string of comma seperated values with basic string splitting on commas
+ _csv_list_fields: Set[str] = set()
+ # List field that are json objects
+ _json_fields: Set[str] = set()
+ # List fields (type does not matter)
+ _list_fields: Set[str] = set()
+ # Set fields (type does not matter)
+ _set_fields: Set[str] = set()
+ # Dictionary key fields as DB field name => model field name
+ _dict_key_fields: Dict[str, str] = {}
+ # Dictionary value fields as model field name => DB field name (this is reversed from _dict_key_fields!)
+ _dict_value_mappings: Dict[str, str] = {}
+
+ @classmethod
+ def create_instance(cls, *args, **kwargs) -> "DbMapResultModel":
+ # Uses the construct method to prevent validation when mapping results
+ return cls.model_construct(*args, **kwargs)
+
+ def _map_json(self, current_dict: dict, record: sqlalchemy.engine.Row, field: str):
+ model_field = self.model_fields[field]
+ value = record[field]
+ if not value:
+ return
+ if not self._has_been_mapped():
+ current_dict[field] = TypeAdapter(model_field.annotation).validate_json(
+ value
+ )
+
+ def _map_list(self, current_dict: dict, record: sqlalchemy.engine.Row, field: str):
+ if record[field] is None:
+ # Do not map null entries into lists, this may cause problems in the future but it works
+ # around some other issues when fields are nullable
+ return
+ if self._has_been_mapped():
+ current_dict[field].append(record[field])
+ else:
+ current_dict[field] = [record[field]]
+
+ def _map_set(self, current_dict: dict, record: sqlalchemy.engine.Row, field: str):
+ if record[field] is None:
+ # See note above for lists
+ return
+ if self._has_been_mapped():
+ current_dict[field].add(record[field])
+ else:
+ current_dict[field] = {record[field]}
+
+ def _map_dict(self, current_dict: dict, record: sqlalchemy.engine.Row, field: str):
+ model_field_name = self._dict_key_fields[field]
+ value_field = self._dict_value_mappings[model_field_name]
+ if record[value_field] is None:
+ # See note above for lists
+ return
+ if self._has_been_mapped():
+ current_dict[model_field_name][record[field]] = record[value_field]
+ else:
+ current_dict[model_field_name] = {record[field]: record[value_field]}
+
+ def _map_list_from_string(
+ self, current_dict: dict, record: sqlalchemy.engine.Row, field: str
+ ):
+ list_string = record[field]
+ if not list_string:
+ # See note above for lists
+ return
+
+ # force it to be a string
+ list_string = str(list_string)
+ values_from_string = list(map(str.strip, list_string.split(",")))
+
+ model_field = self.model_fields[field]
+ # pre-validates the list we are expecting because we want to ensure all records are validated
+ values = TypeAdapter(model_field.annotation).validate_python(values_from_string)
+
+ if self._has_been_mapped() and current_dict[field]:
+ current_dict[field].extend(values)
+ else:
+ current_dict[field] = values
+
+ def map_record(self, record: sqlalchemy.engine.Row) -> None:
+ """
+ Implementation of map_record that handles the special "_" prefixed fields listed at the top of this class.
+ The following rules are used:
+ - If it is in the _csv_list_fields and is not none, extend the existing list
+ - If it is in the _list_fields and is not none, append it to the field specified
+ - If it is in the _set_fields and is not none, add it to the field specified
+ - If it is in the _dict_key_fields and is not none, add it to the field specified along with the value
+ from the _dict_value_mappings
+ - Else add it to the fields to bind to this model
+ - Remove all DB fields that are present in _dict_value_mappings since they were likely added above
+ :param record: the DB record
+ """
+ current_dict: dict = self.__dict__
+ for field in record.keys():
+ if field in self._list_fields:
+ self._map_list(current_dict, record, field)
+ elif field in self._csv_list_fields:
+ self._map_list_from_string(current_dict, record, field)
+ elif field in self._json_fields:
+ self._map_json(current_dict, record, field)
+ elif field in self._set_fields:
+ self._map_set(current_dict, record, field)
+ elif field in self._dict_key_fields:
+ self._map_dict(current_dict, record, field)
+ else:
+ # Ignore fields that should have already been set
+ if not self._has_been_mapped():
+ current_dict[field] = record[field]
+
+ # Remove all dict value fields (if present)
+ for db_field in self._dict_value_mappings.values():
+ current_dict.pop(db_field, None)
+ if self._has_been_mapped():
+ # At this point, just update the previous record
+ self.__dict__.update(current_dict)
+ else:
+ # Init takes care of validation and assigning values to each field with conversions in place, etc
+ self.__init__(**current_dict) # pylint: disable=unnecessary-dunder-call
+
+ def raw(self) -> dict:
+ return self.model_dump()
+
+ def has(self, field: str) -> bool:
+ return field in self.__dict__
+
+ def _has_been_mapped(self):
+ """
+ Tells if a record has already been mapped onto this class or not.
+ :return: True if map_record has already been called, False otherwise
+ """
+ return bool(self.model_fields_set)
+
+ def get(self, field: str, default: Any = None) -> Any:
+ return self.__dict__.get(field, default)
diff --git a/dysql/query_utils.py b/dysql/query_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..d81d94a1887f7f559a46835fe98598e06fa13096
--- /dev/null
+++ b/dysql/query_utils.py
@@ -0,0 +1,310 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+import re
+
+from typing import Iterable, Optional, Tuple, Union
+
+
+# group 0 - entire string
+# group 1 - empty space before template. this helps us ensure we add space to a template but only 1
+# group 2 - template keyword
+# group 3 - table_name
+# group 4 - column_name
+# group 5 - empty space after template. this helps us ensure we add space to a template after but
+# only 1
+LIST_TEMPLATE_REGEX = re.compile(
+ r"(( +)?{(in|not_in|values)__([A-Za-z_]+\.)?([A-Za-z_]+)}( +)?)"
+)
+
+
+class TemplateGenerators:
+ """
+ Functions in this class help to return a tuple which contains the query template along with
+ a dictionary of parameterized values for the query.
+ """
+
+ @classmethod
+ def get_template(cls, name: str):
+ if name == "in":
+ return cls.in_column
+ if name == "not_in":
+ return cls.not_in_column
+ if name == "values":
+ return cls.values
+ return None
+
+ @staticmethod
+ def in_column(
+ name: str,
+ values: Union[str, Iterable[str]],
+ legacy_key: str = None,
+ is_multi_column: bool = False,
+ ) -> Tuple[str, Optional[dict]]:
+ """
+ Returns query and params for using "IN" SQL queries.
+ :param name: the field name
+ :param values: the field values
+ :param legacy_key:
+ :param is_multi_column: needed when more than one field is being compared as part of the in statement
+ :return: a tuple of the query string and the params dictionary
+ """
+ if not values:
+ return "1 <> 1", None
+ key_name = TemplateGenerators._get_key(name, legacy_key, is_multi_column)
+ keys, values = TemplateGenerators._parameterize_list(key_name, values)
+ if is_multi_column:
+ keys = f"({keys})"
+ return f"{name} IN {keys}", values
+
+ @staticmethod
+ def in_multi_column(
+ name: str, values: Union[str, Iterable[str]], legacy_key: str = None
+ ):
+ """
+ A wrapper for in_column with is_multi_column set to true
+ """
+ return TemplateGenerators.in_column(name, values, legacy_key, True)
+
+ @staticmethod
+ def not_in_column(
+ name: str,
+ values: Union[str, Iterable[str]],
+ legacy_key: str = None,
+ is_multi_column: bool = False,
+ ) -> Tuple[str, Optional[dict]]:
+ """
+ Returns query and params for using "NOT IN" SQL queries.
+ :param name: the field name
+ :param values: the field values
+ :param legacy_key:
+ :param is_multi_column: needed when more than one field is being compared as part of the not in statement
+ :return: a tuple of the query string and the params dictionary
+ """
+ if not values:
+ return "1 = 1", None
+ key_name = TemplateGenerators._get_key(name, legacy_key, is_multi_column)
+ keys, values = TemplateGenerators._parameterize_list(key_name, values)
+ if is_multi_column:
+ keys = f"({keys})"
+ return f"{name} NOT IN {keys}", values
+
+ @staticmethod
+ def not_in_multi_column(
+ name: str, values: Union[str, Iterable[str]], legacy_key: str = None
+ ):
+ """
+ A wrapper for not_in_column with is_multi_column set to true
+ """
+ return TemplateGenerators.not_in_column(name, values, legacy_key, True)
+
+ @staticmethod
+ def values(
+ name: str,
+ values: Union[str, Iterable[str]],
+ legacy_key: str = None,
+ ) -> Tuple[str, Optional[dict]]:
+ """
+ Returns query and params for using "VALUES" SQL queries.
+ :param name: the field name
+ :param values: the values
+ :param legacy_key:
+ :return: a tuple of the query string and the params dictionary
+ """
+ if not values:
+ raise ListTemplateException(f"Must have values for {name} template")
+ key_name = TemplateGenerators._get_key(name, legacy_key, False)
+ keys, values = TemplateGenerators._parameterize_list(key_name, values)
+ return f"VALUES {keys}", values
+
+ @staticmethod
+ def _get_key(key: str, legacy_key: str, is_multi_column: bool) -> str:
+ key_name = key
+ if legacy_key:
+ key_name = legacy_key
+ if is_multi_column:
+ key_name = re.sub("[, ()]", "", key_name)
+ return key_name
+
+ @staticmethod
+ def _parameterize_inner_list(
+ key: str, values: Union[str, Iterable[str]]
+ ) -> Tuple[str, Optional[dict]]:
+ param_values = {}
+ parameterized_keys = []
+ if not isinstance(values, (list, tuple, set)):
+ param_values[key] = values
+ parameterized_keys.append(key)
+ else:
+ for index, value in enumerate(values):
+ parameterized_key = f"{key.replace('.', '_')}_{str(index)}"
+ param_values[parameterized_key] = value
+ parameterized_keys.append(parameterized_key)
+
+ return f"( :{', :'.join(parameterized_keys)} )", param_values
+
+ @staticmethod
+ def _parameterize_list(
+ key: str, values: Union[str, Iterable[str]]
+ ) -> Tuple[str, Optional[dict]]:
+ """
+ Build a string with parameterized values and a dictionary
+ with key value pairs matching the string parameters.
+ :return a tuple of the parameter string and the dictionary of parameter values
+ """
+ param_values = {}
+ param_inner_keys = []
+
+ if isinstance(values, str):
+ values = tuple((values,))
+
+ for index, value in enumerate(values):
+ if isinstance(value, tuple) or key.startswith("values"):
+ (
+ param_string,
+ inner_param_values,
+ ) = TemplateGenerators._parameterize_inner_list(
+ f"{key}_{str(index)}", value
+ )
+ param_values.update(inner_param_values)
+ param_inner_keys.append(param_string)
+ else:
+ return TemplateGenerators._parameterize_inner_list(key, values)
+
+ return ", ".join(param_inner_keys), param_values
+
+
+class ListTemplateException(Exception):
+ """
+ List Template Exception
+ """
+
+
+class QueryDataError(Exception):
+ """
+ This exception is thrown when we expect a QueryData object but end up with something different
+ """
+
+
+class QueryData:
+ # pylint: disable=too-few-public-methods
+ """
+ Query data is a wrapper class that allows us to pass back information for a query with more
+ information and specification. this helps to have template queries with template parameters but
+ to still have the ability to have query parameters that get parameterized on the query.
+ """
+
+ def __init__(
+ self,
+ query: str,
+ query_params: dict = None,
+ template_params: dict = None,
+ ):
+ """
+ Constructor.
+ :param query: the SQL query
+ :param query_params: object or list of objects containing values to apply to parameters
+
+ examples of a queryparams passed to a QueryData
+
+ Single Object
+ QueryData(
+ "SELECT * FROM table WHERE value_a=:value_a and value_b=:value_b",
+ query_params={'value_a': 1, 'value_b': 'b' }
+ )
+
+ List of Objects (Note: this will create a query for each object, it may not be possible or
+ even desirable but, using template_params will create a single query with the params)
+ QueryData(
+ "SELECT * FROM table WHERE value_a=:value_a` and value_b=:value_b",
+ query_params=[{'value_a': 1, 'value_b': 'b' }, {'value_a': 1, 'value_b': 'b' }]
+ )
+ :param template_params: these are templates that can be added to queries to generate a single
+ parameterized query.
+
+ examples of current list templates and transformations
+
+ "IN (... )"
+ QueryData(
+ "SELECT * FROM table where name {in__name}",
+ template_params={'in__name' : ['bob','tom','chic']}
+ )
+ {in__actor.name} -> actor.name IN ('bob', 'tom', ' ),
+
+ "NOT IN (... )"
+ QueryData(
+ "SELECT * FROM table wher name {in__name}",
+ template_params={'in__name' : ['bob','tom','chic']}
+ )
+ {not_in__actor.name} -> actor.name NOT IN ('name1','name2',...),
+
+ "VALUES (), (), ()..."
+ {values__actors} -> VALUES (a1.v1,a1.v2,a1.v3), (a1.v1,a1.v2,a1.v3),...
+ """
+ self.query = query
+ self.query_params = query_params
+ self.template_params = template_params
+
+
+def __validate_keys_clean_query(query, template_params):
+ validated_keys = []
+ for groups in re.findall(LIST_TEMPLATE_REGEX, query):
+ # check first group for the full key
+ key = f"{groups[2]}__{groups[3] if groups[3] else ''}{groups[4]}"
+ validated_keys.append(key)
+ missing_keys = []
+
+ # validate
+ if template_params is None or template_params.get(key) is None:
+ missing_keys.append(key)
+ elif key == "values" and len(template_params.get(key)) == 0:
+ missing_keys.append(key)
+
+ if len(missing_keys) > 0:
+ raise ListTemplateException(f"Missing template keys {missing_keys}")
+
+ # Clean whitespace as templates will add their own padding later on
+ query = query.replace(groups[0], groups[0].strip())
+ return query, validated_keys
+
+
+def __validate_query_and_params(data: QueryData) -> None:
+ if not isinstance(data, QueryData):
+ raise QueryDataError(
+ "SQL annotated methods must return an instance of QueryData for query information"
+ )
+
+
+def get_query_data(data: QueryData) -> Tuple[str, dict]:
+ """
+ Retrieves the query and parameters from a QueryData object.
+ :param data: the query data object
+ :return: a tuple of the query string and the params
+ """
+ __validate_query_and_params(data)
+
+ params = {}
+ query, validated_keys = __validate_keys_clean_query(
+ data.query, data.template_params
+ )
+
+ if data.query_params:
+ params.update(data.query_params)
+
+ for key in validated_keys:
+ list_template_key, column_name = tuple(key.split("__"))
+ template_to_use = TemplateGenerators.get_template(list_template_key)
+ template_query, param_dict = template_to_use(
+ column_name, data.template_params[key], legacy_key=key
+ )
+ if param_dict:
+ params.update(param_dict)
+ query_key = "{" + key + "}"
+ query = query.replace(query_key, f" {template_query} ")
+
+ return query, params
diff --git a/dysql/test/__init__.py b/dysql/test/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c728d6b57c3fb12322b9120698c97d970bee6fc3
--- /dev/null
+++ b/dysql/test/__init__.py
@@ -0,0 +1,55 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+from unittest.mock import Mock
+
+from dysql import set_default_connection_parameters, databases
+
+
+def setup_mock_engine(mock_create_engine):
+ """
+ build up the basics of a mock engine for the database
+ :return: mocked engine for use and manipulation in testing
+ """
+ mock_engine = Mock()
+ mock_engine.connect().execution_options().__enter__ = Mock()
+ mock_engine.connect().execution_options().__exit__ = Mock()
+ set_default_connection_parameters("fake", "user", "password", "test")
+
+ # Clear out the databases before attempting to mock anything
+ databases.DatabaseContainerSingleton().clear()
+ mock_create_engine.return_value = mock_engine
+ return mock_engine
+
+
+def verify_query_params(mock_engine, expected_query, expected_args):
+ verify_query(mock_engine, expected_query)
+ verify_query_args(mock_engine, expected_args)
+
+
+def verify_query(mock_engine, expected_query):
+ execute_call = (
+ mock_engine.connect.return_value.execution_options.return_value.execute
+ )
+ execute_call.assert_called()
+
+ query = execute_call.call_args[0][0].text
+ assert query == expected_query
+
+
+def verify_query_args(mock_engine, expected_args):
+ execute_call = (
+ mock_engine.connect.return_value.execution_options.return_value.execute
+ )
+ query_args = execute_call.call_args[0][1]
+
+ assert query_args
+ for expected_key in expected_args:
+ expected_value = expected_args[expected_key]
+ assert query_args.get(expected_key)
+ assert expected_value == query_args[expected_key]
diff --git a/dysql/test/conftest.py b/dysql/test/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8ddc3966643f63ba242456eb72b754b132a8cde
--- /dev/null
+++ b/dysql/test/conftest.py
@@ -0,0 +1,19 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+from unittest.mock import patch
+import pytest
+
+
+@pytest.fixture(name="mock_create_engine")
+def mock_create_engine_fixture():
+ create_mock = patch("dysql.databases.sqlalchemy.create_engine")
+ try:
+ yield create_mock.start()
+ finally:
+ create_mock.stop()
diff --git a/dysql/test/test_annotations.py b/dysql/test/test_annotations.py
new file mode 100644
index 0000000000000000000000000000000000000000..f01b6d23da2f639be26c9ba417f4d6a76c564000
--- /dev/null
+++ b/dysql/test/test_annotations.py
@@ -0,0 +1,68 @@
+"""
+Copyright 2023 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+from typing import List, Union
+
+import pytest
+from pydantic import BaseModel, ValidationError
+
+from dysql.annotations import FromCSVToList
+
+
+class StrCSVModel(BaseModel):
+ values: FromCSVToList[List[str]]
+
+
+class IntCSVModel(BaseModel):
+ values: FromCSVToList[List[int]]
+
+
+class NullableStrCSVModel(BaseModel):
+ values: FromCSVToList[Union[List[str], None]]
+
+
+class NullableIntCSVModel(BaseModel):
+ values: FromCSVToList[Union[List[int], None]]
+
+
+@pytest.mark.parametrize(
+ "cls, values, expected",
+ [
+ (StrCSVModel, "1,2,3", ["1", "2", "3"]),
+ (StrCSVModel, "a,b", ["a", "b"]),
+ (StrCSVModel, "a", ["a"]),
+ (NullableStrCSVModel, "", None),
+ (NullableStrCSVModel, None, None),
+ (StrCSVModel, ["a", "b"], ["a", "b"]),
+ (StrCSVModel, ["a", "b", "c"], ["a", "b", "c"]),
+ (IntCSVModel, "1,2,3", [1, 2, 3]),
+ (IntCSVModel, "1", [1]),
+ (NullableIntCSVModel, "", None),
+ (NullableIntCSVModel, None, None),
+ (IntCSVModel, ["1", "2", "3"], [1, 2, 3]),
+ (IntCSVModel, ["1", "2", "3", 4, 5], [1, 2, 3, 4, 5]),
+ ],
+)
+def test_from_csv_to_list(cls, values, expected):
+ assert expected == cls(values=values).values
+
+
+@pytest.mark.parametrize(
+ "cls, values",
+ [
+ (StrCSVModel, ""),
+ (StrCSVModel, None),
+ (IntCSVModel, "a,b,c"),
+ (IntCSVModel, ""),
+ (IntCSVModel, None),
+ (IntCSVModel, ["a", "b", "c"]),
+ ],
+)
+def test_from_csv_to_list_invalid(cls, values):
+ with pytest.raises(ValidationError):
+ cls(values=values)
diff --git a/dysql/test/test_database_initialization.py b/dysql/test/test_database_initialization.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c226f8a6d301dfdf0bdaf4f2effbdb8e5f1af5f
--- /dev/null
+++ b/dysql/test/test_database_initialization.py
@@ -0,0 +1,240 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+from unittest import mock
+
+import pytest
+
+import dysql.connections
+from dysql import (
+ sqlquery,
+ DBNotPreparedError,
+ set_default_connection_parameters,
+ QueryData,
+ set_database_init_hook,
+)
+from dysql.test import setup_mock_engine
+
+
+"""
+These tests reflect what can happen when dealing with a config passing in a value that may not
+have been set. There are some parameters that are absolutely necessary, if they aren't set we
+want to make sure we are warning the user in different ways.
+"""
+
+
+@sqlquery()
+def query():
+ """
+ This is used to call the code that would initialize the database on the first time.
+ If there were any failures this is where we would expect to see them.
+ """
+ return QueryData("SELECT * FROM table")
+
+
+@pytest.fixture(autouse=True, name="mock_engine")
+def fixture_mock_engine(mock_create_engine):
+ dysql.databases.DatabaseContainerSingleton().clear()
+ dysql.databases._DEFAULT_CONNECTION_PARAMS_BY_KEY.clear()
+
+ # Reset the database before the test
+ dysql.databases.reset_current_database()
+
+ yield setup_mock_engine(mock_create_engine)
+
+ # Reset database after the test as well
+ dysql.databases.reset_current_database()
+
+
+@pytest.fixture(autouse=True)
+def fixture_reset_init_hook():
+ yield
+ if hasattr(dysql.databases.Database, "hook_method"):
+ delattr(dysql.databases.Database, "hook_method")
+
+
+def test_nothing_set():
+ dysql.databases._DEFAULT_CONNECTION_PARAMS_BY_KEY.clear()
+ with pytest.raises(DBNotPreparedError) as error:
+ query()
+ assert (
+ str(error.value)
+ == "Unable to connect to a database, set_default_connection_parameters must first be called"
+ )
+
+
+@pytest.mark.parametrize(
+ "host, user, password, database, failed_field",
+ [
+ (None, "u", "p", "d", "host"),
+ ("", "u", "p", "d", "host"),
+ ("h", None, "p", "d", "user"),
+ ("h", "", "p", "d", "user"),
+ ("h", "u", None, "d", "password"),
+ ("h", "u", "", "d", "password"),
+ ("h", "u", "p", None, "database"),
+ ("h", "u", "p", "", "database"),
+ ],
+)
+def test_fields_required(host, user, password, database, failed_field):
+ with pytest.raises(DBNotPreparedError) as error:
+ set_default_connection_parameters(host, user, password, database)
+ assert (
+ str(error.value)
+ == f'Database parameter "{failed_field}" is not set or empty and is required'
+ )
+
+
+def test_minimal_credentials(mock_engine):
+ set_default_connection_parameters("h", "u", "p", "d")
+
+ mock_engine.connect().execution_options().execute.return_value = []
+ query()
+
+
+def test_init_hook(mock_engine):
+ init_hook = mock.MagicMock()
+ set_database_init_hook(init_hook)
+ set_default_connection_parameters("h", "u", "p", "d")
+ dysql.databases.set_current_database("d")
+
+ mock_engine.connect().execution_options().execute.return_value = []
+ query()
+ init_hook.assert_called_once_with("d", mock_engine)
+
+
+def test_init_hook_multiple_databases(mock_engine):
+ init_hook = mock.MagicMock()
+ set_database_init_hook(init_hook)
+ set_default_connection_parameters("h1", "u1", "p1", "d1")
+ set_default_connection_parameters("h2", "u2", "p2", "d2")
+
+ mock_engine.connect().execution_options().execute.return_value = []
+ query()
+ dysql.databases.set_current_database("d1")
+ query()
+ assert init_hook.call_args_list == [
+ mock.call("test", mock_engine),
+ mock.call("d1", mock_engine),
+ ]
+ dysql.databases.set_current_database("d2")
+ query()
+ assert init_hook.call_args_list == [
+ mock.call("test", mock_engine),
+ mock.call("d1", mock_engine),
+ mock.call("d2", mock_engine),
+ ]
+
+
+def test_current_database_default(mock_engine, mock_create_engine):
+ db_container = dysql.databases.DatabaseContainerSingleton()
+ assert len(db_container) == 0
+ mock_engine.connect().execution_options().execute.return_value = []
+ query()
+
+ # Only one database is initialized
+ assert len(db_container) == 1
+ assert "test" in db_container
+ assert db_container.current_database.database == "test"
+ mock_create_engine.assert_called_once_with(
+ "mysql+mysqlconnector://user:password@fake:3306/test?charset=utf8",
+ echo=False,
+ pool_pre_ping=True,
+ pool_recycle=3600,
+ pool_size=10,
+ )
+
+
+def test_different_charset_collation(mock_engine, mock_create_engine):
+ db_container = dysql.databases.DatabaseContainerSingleton()
+ set_default_connection_parameters(
+ "host",
+ "user",
+ "password",
+ "database",
+ charset="other",
+ collation="other_collation",
+ )
+ assert len(db_container) == 0
+ dysql.databases.set_current_database("database")
+ mock_engine.connect().execution_options().execute.return_value = []
+ query()
+
+ # Only one database is initialized
+ mock_create_engine.assert_called_once_with(
+ "mysql+mysqlconnector://user:password@host:3306/database?charset=other&collation=other_collation",
+ echo=False,
+ pool_pre_ping=True,
+ pool_recycle=3600,
+ pool_size=10,
+ )
+
+
+def test_is_set_current_database_supported():
+ # This test only asserts that true is always returned since this method is deprecated
+ assert dysql.databases.is_set_current_database_supported()
+
+
+def test_current_database_set(mock_engine, mock_create_engine):
+ db_container = dysql.databases.DatabaseContainerSingleton()
+ set_default_connection_parameters("h1", "u1", "p1", "d1", database_key="db1")
+ dysql.databases.set_current_database("db1")
+ mock_engine.connect().execution_options().execute.return_value = []
+ query()
+
+ assert len(db_container) == 1
+ assert "db1" in db_container
+ assert db_container.current_database.database == "db1"
+ mock_create_engine.assert_called_once_with(
+ "mysql+mysqlconnector://u1:p1@h1:3306/d1?charset=utf8",
+ echo=False,
+ pool_pre_ping=True,
+ pool_recycle=3600,
+ pool_size=10,
+ )
+
+
+def test_current_database_cached(mock_engine, mock_create_engine):
+ db_container = dysql.databases.DatabaseContainerSingleton()
+ mock_engine.connect().execution_options().execute.return_value = []
+ query()
+
+ assert len(db_container) == 1
+ assert "test" in db_container
+ assert db_container.current_database.database == "test"
+
+ set_default_connection_parameters("h1", "u1", "p1", "db1")
+ dysql.databases.set_current_database("db1")
+ query()
+ assert len(db_container) == 2
+ assert "test" in db_container
+ assert db_container.current_database.database == "db1"
+
+ # Set back to default
+ dysql.databases.reset_current_database()
+ query()
+ assert len(db_container) == 2
+ assert db_container.current_database.database == "test"
+
+ assert mock_create_engine.call_count == 2
+ assert mock_create_engine.call_args_list == [
+ mock.call(
+ "mysql+mysqlconnector://user:password@fake:3306/test?charset=utf8",
+ echo=False,
+ pool_pre_ping=True,
+ pool_recycle=3600,
+ pool_size=10,
+ ),
+ mock.call(
+ "mysql+mysqlconnector://u1:p1@h1:3306/db1?charset=utf8",
+ echo=False,
+ pool_pre_ping=True,
+ pool_recycle=3600,
+ pool_size=10,
+ ),
+ ]
diff --git a/dysql/test/test_mappers.py b/dysql/test/test_mappers.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc59893714eb77ed582f22850d44b7e3aa3daf32
--- /dev/null
+++ b/dysql/test/test_mappers.py
@@ -0,0 +1,227 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+import pytest
+
+from dysql import (
+ RecordCombiningMapper,
+ SingleRowMapper,
+ SingleColumnMapper,
+ SingleRowAndColumnMapper,
+ CountMapper,
+ KeyValueMapper,
+)
+from dysql.mappers import MapperError
+
+
+class TestMappers:
+ """
+ Test Mappers
+ """
+
+ @staticmethod
+ def _unwrap_results(results):
+ return [r.raw() for r in results]
+
+ def test_record_combining(self):
+ mapper = RecordCombiningMapper()
+ assert len(mapper.map_records([])) == 0
+ assert self._unwrap_results(mapper.map_records([{"a": 1, "b": 2}])) == [
+ {"a": 1, "b": 2}
+ ]
+ assert self._unwrap_results(
+ mapper.map_records(
+ [
+ {"id": 1, "a": 1, "b": 2},
+ {"id": 2, "a": 1, "b": 2},
+ {"id": 1, "c": 3},
+ ]
+ )
+ ) == [
+ {"id": 1, "a": 1, "b": 2, "c": 3},
+ {"id": 2, "a": 1, "b": 2},
+ ]
+
+ @staticmethod
+ def test_record_combining_no_record_mapper():
+ mapper = RecordCombiningMapper(record_mapper=None)
+ assert len(mapper.map_records([])) == 0
+ assert mapper.map_records([{"a": 1, "b": 2}]) == [{"a": 1, "b": 2}]
+ assert mapper.map_records(
+ [
+ {"id": 1, "a": 1, "b": 2},
+ {"id": 2, "a": 1, "b": 2},
+ {"id": 1, "c": 3},
+ ]
+ ) == [
+ {"id": 1, "a": 1, "b": 2},
+ {"id": 2, "a": 1, "b": 2},
+ {"id": 1, "c": 3},
+ ]
+
+ @staticmethod
+ def test_single_row():
+ mapper = SingleRowMapper()
+ assert mapper.map_records([]) is None
+ assert mapper.map_records([{"a": 1, "b": 2}]).raw() == {"a": 1, "b": 2}
+ assert mapper.map_records(
+ [
+ {"id": 1, "a": 1, "b": 2},
+ {"id": 2, "a": 1, "b": 2},
+ {"id": 1, "c": 3},
+ ]
+ ).raw() == {"id": 1, "a": 1, "b": 2}
+
+ @staticmethod
+ def test_single_row_no_record_mapper():
+ mapper = SingleRowMapper(record_mapper=None)
+ assert mapper.map_records([]) is None
+ assert mapper.map_records([{"a": 1, "b": 2}]) == {"a": 1, "b": 2}
+ assert mapper.map_records(
+ [
+ {"id": 1, "a": 1, "b": 2},
+ {"id": 2, "a": 1, "b": 2},
+ {"id": 1, "c": 3},
+ ]
+ ) == {"id": 1, "a": 1, "b": 2}
+
+ @staticmethod
+ def test_single_column():
+ mapper = SingleColumnMapper()
+ assert len(mapper.map_records([])) == 0
+ assert mapper.map_records([{"a": 1, "b": 2}]) == [1]
+ assert mapper.map_records(
+ [
+ {"id": "myid1", "a": 1, "b": 2},
+ {"id": "myid2", "a": 1, "b": 2},
+ {"id": "myid3", "c": 3},
+ ]
+ ) == ["myid1", "myid2", "myid3"]
+
+ @staticmethod
+ @pytest.mark.parametrize(
+ "mapper",
+ [
+ SingleRowAndColumnMapper(),
+ # Alias for the other one
+ CountMapper(),
+ ],
+ )
+ def test_single_column_and_row(mapper):
+ assert mapper.map_records([]) is None
+ assert mapper.map_records([{"a": 1, "b": 2}]) == 1
+ assert (
+ mapper.map_records(
+ [
+ {"id": "myid", "a": 1, "b": 2},
+ {"id": 2, "a": 1, "b": 2},
+ {"id": 1, "c": 3},
+ ]
+ )
+ == "myid"
+ )
+
+ @staticmethod
+ @pytest.mark.parametrize(
+ "mapper, expected",
+ [
+ (KeyValueMapper(), {"a": 4, "b": 7}),
+ (KeyValueMapper(key_column="column_named_something"), {"a": 4, "b": 7}),
+ (KeyValueMapper(value_column="column_with_some_value"), {"a": 4, "b": 7}),
+ (
+ KeyValueMapper(has_multiple_values_per_key=True),
+ {"a": [1, 2, 3, 4], "b": [3, 4, 5, 6, 7]},
+ ),
+ (
+ KeyValueMapper(
+ key_column="column_named_something",
+ has_multiple_values_per_key=True,
+ ),
+ {"a": [1, 2, 3, 4], "b": [3, 4, 5, 6, 7]},
+ ),
+ (
+ KeyValueMapper(
+ key_column="column_with_some_value",
+ value_column="column_named_something",
+ has_multiple_values_per_key=True,
+ ),
+ {
+ 1: ["a"],
+ 2: ["a"],
+ 3: ["a", "b"],
+ 4: ["a", "b"],
+ 5: ["b"],
+ 6: ["b"],
+ 7: ["b"],
+ },
+ ),
+ (
+ KeyValueMapper(
+ key_column="column_with_some_value",
+ value_column="column_named_something",
+ ),
+ {1: "a", 2: "a", 3: "b", 4: "b", 5: "b", 6: "b", 7: "b"},
+ ),
+ ],
+ )
+ def test_key_mapper_key_has_multiple(mapper, expected):
+ result = mapper.map_records(
+ [
+ HelperRow(
+ ("column_named_something", "column_with_some_value"), ["a", 1]
+ ),
+ HelperRow(
+ ("column_named_something", "column_with_some_value"), ["a", 2]
+ ),
+ HelperRow(
+ ("column_named_something", "column_with_some_value"), ["a", 3]
+ ),
+ HelperRow(
+ ("column_named_something", "column_with_some_value"), ["a", 4]
+ ),
+ HelperRow(
+ ("column_named_something", "column_with_some_value"), ["b", 3]
+ ),
+ HelperRow(
+ ("column_named_something", "column_with_some_value"), ["b", 4]
+ ),
+ HelperRow(
+ ("column_named_something", "column_with_some_value"), ["b", 5]
+ ),
+ HelperRow(
+ ("column_named_something", "column_with_some_value"), ["b", 6]
+ ),
+ HelperRow(
+ ("column_named_something", "column_with_some_value"), ["b", 7]
+ ),
+ ]
+ )
+ assert len(result) == len(expected)
+ assert result == expected
+
+ @staticmethod
+ def test_key_mapper_key_value_same():
+ with pytest.raises(
+ MapperError, match="key and value columns cannot be the same"
+ ):
+ KeyValueMapper(key_column="same", value_column="same")
+
+
+class HelperRow: # pylint: disable=too-few-public-methods
+ """
+ Helper class does the most basic functionality we see when accessing records passed in
+ """
+
+ def __init__(self, fields, values):
+ self.fields = fields
+ self.values = values
+
+ def __getitem__(self, key):
+ if isinstance(key, int):
+ return self.values[key]
+ return self.values[self.fields.index(key)]
diff --git a/dysql/test/test_mariadbmap_tojson.py b/dysql/test/test_mariadbmap_tojson.py
new file mode 100644
index 0000000000000000000000000000000000000000..5b3270e40361d7d819f6c91d8b003c6d6ec7415f
--- /dev/null
+++ b/dysql/test/test_mariadbmap_tojson.py
@@ -0,0 +1,47 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+import json
+import pytest
+
+from dysql import DbMapResult
+
+
+@pytest.mark.parametrize(
+ "name, expected_json, mariadb_map",
+ [
+ (
+ "basic",
+ '{"id": 1, "name": "test"}',
+ DbMapResult(id=1, name="test"),
+ ),
+ (
+ "basic_with_list",
+ '{"id": 1, "name": "test", "my_list": ["a", "b", "c"]}',
+ DbMapResult(id=1, name="test", my_list=["a", "b", "c"]),
+ ),
+ (
+ "inner_map",
+ '{"id": 1, "inner_map": {"id": 2, "name": "inner_test"}}',
+ DbMapResult(id=1, inner_map=DbMapResult(id=2, name="inner_test")),
+ ),
+ (
+ "inner_list_of_maps",
+ '{"id": 1, "inner_map_list": [{"id": 2, "name": "inner_test_2"}, {"id": 3, "name": "inner_test_3"}]}',
+ DbMapResult(
+ id=1,
+ inner_map_list=[
+ DbMapResult(id=2, name="inner_test_2"),
+ DbMapResult(id=3, name="inner_test_3"),
+ ],
+ ),
+ ),
+ ],
+)
+def test_raw_json_format(name, expected_json, mariadb_map):
+ assert json.dumps(mariadb_map.raw()) == expected_json, "error with " + name
diff --git a/dysql/test/test_pydantic_mappers.py b/dysql/test/test_pydantic_mappers.py
new file mode 100644
index 0000000000000000000000000000000000000000..b917d0e8498fcdfbc577be81b07aaa230c47f5b6
--- /dev/null
+++ b/dysql/test/test_pydantic_mappers.py
@@ -0,0 +1,291 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+import json
+from typing import Any, Dict, List, Set, Optional
+import pytest
+
+from pydantic import ValidationError
+
+from dysql import (
+ RecordCombiningMapper,
+ SingleRowMapper,
+)
+from dysql.pydantic_mappers import DbMapResultModel
+
+
+class ConversionDbModel(DbMapResultModel):
+ id: int
+ field_str: str
+ field_int: int
+ field_bool: bool
+
+
+class CombiningDbModel(DbMapResultModel):
+ _list_fields: Set[str] = {"list1"}
+ _set_fields: Set[str] = {"set1"}
+ _dict_key_fields: Dict[str, str] = {"key1": "dict1", "key2": "dict2"}
+ _dict_value_mappings: Dict[str, str] = {"dict1": "val1", "dict2": "val2"}
+
+ id: int = None
+ list1: List[str]
+ set1: Set[str] = set()
+ dict1: Dict[str, Any] = {}
+ dict2: Dict[str, int] = {}
+
+
+class DefaultListCombiningDbModel(CombiningDbModel):
+ list1: List[str] = []
+
+
+class ListWithStringsModel(DbMapResultModel):
+ _csv_list_fields: Set[str] = {"list1", "list2"}
+
+ id: int
+ list1: Optional[List[str]] = None
+ list2: List[int] = [] # help test empty list gets filled
+
+
+class JsonModel(DbMapResultModel):
+ _json_fields: Set[str] = {"json1", "json2"}
+
+ id: int
+ json1: dict
+ json2: Optional[dict] = None
+
+
+class MultiKeyModel(DbMapResultModel):
+ @classmethod
+ def get_key_columns(cls):
+ return ["a", "b"]
+
+ _list_fields = {"c"}
+ a: int
+ b: str
+ c: List[str]
+
+
+def _unwrap_results(results):
+ return [r.raw() for r in results]
+
+
+def test_field_conversion():
+ mapper = SingleRowMapper(record_mapper=ConversionDbModel)
+ assert mapper.map_records(
+ [
+ {"id": 1, "field_str": "str1", "field_int": 1, "field_bool": 1},
+ ]
+ ).raw() == {"id": 1, "field_str": "str1", "field_int": 1, "field_bool": True}
+
+
+def test_complex_object_record_combining():
+ mapper = RecordCombiningMapper(record_mapper=CombiningDbModel)
+ assert len(mapper.map_records([])) == 0
+ assert _unwrap_results(
+ mapper.map_records(
+ [
+ {
+ "id": 1,
+ "list1": "val1",
+ "set1": "val2",
+ "key1": "k1",
+ "val1": "v1",
+ "key2": "k3",
+ "val2": 3,
+ },
+ {"id": 2, "list1": "val1"},
+ {
+ "id": 1,
+ "list1": "val3",
+ "set1": "val4",
+ "key1": "k2",
+ "val1": "v2",
+ "key2": "k4",
+ "val2": 4,
+ },
+ ]
+ )
+ ) == [
+ {
+ "id": 1,
+ "list1": ["val1", "val3"],
+ "set1": {"val2", "val4"},
+ "dict1": {"k1": "v1", "k2": "v2"},
+ "dict2": {"k3": 3, "k4": 4},
+ },
+ {
+ "id": 2,
+ "list1": ["val1"],
+ "set1": set(),
+ "dict1": {},
+ "dict2": {},
+ },
+ ]
+
+
+def test_record_combining_multi_column_id():
+ mapper = RecordCombiningMapper(MultiKeyModel)
+ assert len(mapper.map_records([])) == 0
+ assert _unwrap_results(
+ mapper.map_records(
+ [
+ {"a": 1, "b": "test", "c": "one"},
+ {"a": 1, "b": "test", "c": "two"},
+ {"a": 1, "b": "test", "c": "three"},
+ {"a": 2, "b": "test", "c": "one"},
+ {"a": 2, "b": "test", "c": "two"},
+ {"a": 1, "b": "othertest", "c": "one"},
+ ]
+ )
+ ) == [
+ {"a": 1, "b": "test", "c": ["one", "two", "three"]},
+ {"a": 2, "b": "test", "c": ["one", "two"]},
+ {"a": 1, "b": "othertest", "c": ["one"]},
+ ]
+
+
+def test_complex_object_with_null_values():
+ mapper = SingleRowMapper(record_mapper=DefaultListCombiningDbModel)
+ assert mapper.map_records(
+ [
+ {"id": 1},
+ ]
+ ).raw() == {
+ "id": 1,
+ "list1": [],
+ "set1": set(),
+ "dict1": {},
+ "dict2": {},
+ }
+
+
+def test_csv_list_field():
+ mapper = SingleRowMapper(record_mapper=ListWithStringsModel)
+ assert mapper.map_records(
+ [{"id": 1, "list1": "a,b,c,d", "list2": "1,2,3,4"}]
+ ).raw() == {"id": 1, "list1": ["a", "b", "c", "d"], "list2": [1, 2, 3, 4]}
+
+
+def test_csv_list_field_single_value():
+ mapper = SingleRowMapper(record_mapper=ListWithStringsModel)
+ assert mapper.map_records([{"id": 1, "list1": "a", "list2": "1"}]).raw() == {
+ "id": 1,
+ "list1": ["a"],
+ "list2": [1],
+ }
+
+
+def test_csv_list_field_empty_string():
+ mapper = SingleRowMapper(record_mapper=ListWithStringsModel)
+ assert mapper.map_records([{"id": 1, "list1": "", "list2": ""}]).raw() == {
+ "id": 1,
+ "list1": None,
+ "list2": [],
+ }
+
+
+def test_csv_list_field_extends():
+ mapper = RecordCombiningMapper(record_mapper=ListWithStringsModel)
+ assert mapper.map_records(
+ [
+ {"id": 1, "list1": "a,b", "list2": "1,2"},
+ {"id": 1, "list1": "c,d", "list2": "3,4"},
+ ]
+ )[0].raw() == {"id": 1, "list1": ["a", "b", "c", "d"], "list2": [1, 2, 3, 4]}
+
+
+def test_csv_list_field_multiple_records_duplicates():
+ mapper = RecordCombiningMapper(record_mapper=ListWithStringsModel)
+ assert mapper.map_records(
+ [
+ {"id": 1, "list1": "a,b,c,d", "list2": "1,2,3,4"},
+ {"id": 1, "list1": "a,b,c,d", "list2": "1,2,3,4"},
+ ]
+ )[0].raw() == {
+ "id": 1,
+ "list1": ["a", "b", "c", "d", "a", "b", "c", "d"],
+ "list2": [1, 2, 3, 4, 1, 2, 3, 4],
+ }
+
+
+def test_csv_list_field_none_in_first_record():
+ mapper = RecordCombiningMapper(record_mapper=ListWithStringsModel)
+ assert mapper.map_records(
+ [
+ {"id": 1, "list1": "a,b,c,d", "list2": None},
+ {"id": 1, "list1": "e,f,g", "list2": "1,2,3,4"},
+ ]
+ )[0].raw() == {
+ "id": 1,
+ "list1": ["a", "b", "c", "d", "e", "f", "g"],
+ "list2": [1, 2, 3, 4],
+ }
+
+
+def test_csv_list_field_without_mapping_ignored():
+ mapper = SingleRowMapper(record_mapper=ListWithStringsModel)
+ assert mapper.map_records(
+ [{"id": 1, "list1": "a,b, c,d", "list2": "1,2,3,4", "list3": "x,y,z"}]
+ ).raw() == {"id": 1, "list1": ["a", "b", "c", "d"], "list2": [1, 2, 3, 4]}
+
+
+def test_csv_list_field_invalid_type():
+ mapper = RecordCombiningMapper(record_mapper=ListWithStringsModel)
+ with pytest.raises(ValidationError, match="1 validation error for list"):
+ mapper.map_records(
+ [
+ {"id": 1, "list1": "a,b", "list2": "1,2"},
+ {"id": 1, "list1": "c,d", "list2": "3,a"},
+ ]
+ )
+
+
+def test_json_field():
+ mapper = SingleRowMapper(record_mapper=JsonModel)
+ assert mapper.map_records(
+ [
+ {
+ "id": 1,
+ "json1": json.dumps(
+ {"a": 1, "b": 2, "c": {"x": 10, "y": 9, "z": {"deep": "value"}}}
+ ),
+ }
+ ]
+ ).model_dump() == {
+ "id": 1,
+ "json1": {"a": 1, "b": 2, "c": {"x": 10, "y": 9, "z": {"deep": "value"}}},
+ "json2": None,
+ }
+
+
+@pytest.mark.parametrize(
+ "json1, json2",
+ [
+ ('{ "json": value', None),
+ ('{ "json": value', '{ "json": value }'),
+ ('{ "json": value }', '{ "json": value'),
+ (None, '{ "json": value'),
+ ],
+)
+def test_invalid_json(json1, json2):
+ with pytest.raises(ValidationError, match="Invalid JSON"):
+ mapper = SingleRowMapper(record_mapper=JsonModel)
+ mapper.map_records([{"id": 1, "json1": json1, "json2": json2}])
+
+
+def test_json_none():
+ mapper = SingleRowMapper(record_mapper=JsonModel)
+ assert mapper.map_records(
+ [{"id": 1, "json1": '{ "first": "value" }', "json2": None}]
+ ).model_dump() == {
+ "id": 1,
+ "json1": {
+ "first": "value",
+ },
+ "json2": None,
+ }
diff --git a/dysql/test/test_sql_decorator.py b/dysql/test/test_sql_decorator.py
new file mode 100644
index 0000000000000000000000000000000000000000..c236dd06f5b85cf5eca0220263a0bb4efd659733
--- /dev/null
+++ b/dysql/test/test_sql_decorator.py
@@ -0,0 +1,399 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+import pytest
+
+from dysql import (
+ sqlupdate,
+ sqlquery,
+ DbMapResult,
+ CountMapper,
+ SingleRowMapper,
+ QueryData,
+ QueryDataError,
+)
+from dysql.test import setup_mock_engine
+
+
+class TestSqlSelectDecorator:
+ """
+ Test Sql Select Decorator
+ """
+
+ @staticmethod
+ @pytest.fixture
+ def mock_results():
+ return [
+ {
+ "id": 1,
+ "name": "jack",
+ "email": "jack@adobe.com",
+ "hobbies": ["golf", "bikes", "coding"],
+ },
+ {
+ "id": 2,
+ "name": "flora",
+ "email": "flora@adobe.com",
+ "hobbies": ["golf", "coding"],
+ },
+ {
+ "id": 3,
+ "name": "Terrence",
+ "email": "terrence@adobe.com",
+ "hobbies": ["coding", "watching tv", "hot dog eating contest"],
+ },
+ ]
+
+ @staticmethod
+ @pytest.fixture
+ def mock_engine(mock_results, mock_create_engine):
+ mock_engine = setup_mock_engine(mock_create_engine)
+ mock_engine.connect.return_value.execution_options.return_value.execute.return_value = mock_results
+ return mock_engine
+
+ @staticmethod
+ def test_non_query_data_fails(mock_create_engine):
+ # This argument forces the fixture setup
+ _ = mock_create_engine
+
+ @sqlquery()
+ def select_with_string():
+ return "SELECT"
+
+ with pytest.raises(QueryDataError):
+ select_with_string()
+
+ def test_map_not_specified(self, mock_results, mock_engine):
+ mock_engine.connect.return_value.execution_options.return_value.execute.return_value = mock_results
+ assert isinstance(list(self._select_all())[0], DbMapResult)
+
+ def test_single(self, mock_results, mock_engine):
+ mock_engine.connect.return_value.execution_options.return_value.execute.return_value = mock_results
+ result = self._select_single()
+ assert isinstance(result, DbMapResult)
+
+ def test_count(self, mock_engine):
+ mock_engine.connect.return_value.execution_options.return_value.execute.return_value = [
+ {"count": 2},
+ {"count": 3},
+ ]
+ assert self._select_count() == 2
+
+ def test_execute_no_params(self, mock_engine):
+ self._select_all()
+ mock_engine.connect.return_value.execution_options.return_value.execute.assert_called()
+ call_args = mock_engine.connect.return_value.execution_options.return_value.execute.call_args
+ assert call_args[0][0].text == "SELECT * FROM my_table"
+ assert call_args[0][1] == {}
+
+ def test_execute_params(self, mock_engine):
+ self._select_filtered(3)
+ mock_engine.connect.return_value.execution_options.return_value.execute.assert_called()
+
+ call_args = mock_engine.connect.return_value.execution_options.return_value.execute.call_args
+ assert call_args[0][0].text == "SELECT * FROM my_table WHERE id=:id"
+ assert call_args[0][1] == {"id": 3}
+
+ def test_list_results_map(self, mock_results, mock_engine):
+ mock_engine.connect.return_value.execution_options.return_value.execute.return_value = [
+ mock_results[2]
+ ]
+ results = self._select_filtered(3)
+
+ assert len(results) == 1
+ assert len(list(results)[0].hobbies) == 3
+
+ def test_isolation_default(self, mock_engine):
+ mock_connect = mock_engine.connect.return_value.execution_options
+ self._select_all()
+ mock_connect.assert_called_with(isolation_level="READ_COMMITTED")
+
+ def test_isolation_default_read_uncommited(self, mock_engine):
+ mock_connect = mock_engine.connect.return_value.execution_options
+ self._select_uncommitted()
+ mock_connect.assert_called_with(isolation_level="READ_UNCOMMITTED")
+ mock_connect.return_value.execute.assert_called()
+
+ @staticmethod
+ @sqlquery()
+ def _select_all():
+ """
+ method is static just to help show you can use static methods if
+ you don't want to instantiate an instance of the class
+ """
+ return QueryData("SELECT * FROM my_table")
+
+ @staticmethod
+ @sqlquery(mapper=SingleRowMapper())
+ def _select_single():
+ return QueryData("SELECT * FROM my_table")
+
+ @staticmethod
+ @sqlquery(mapper=CountMapper)
+ def _select_count():
+ return QueryData("SELECT COUNT(*) FROM my_table")
+
+ @staticmethod
+ @sqlquery()
+ def _select_filtered(_id):
+ return QueryData(
+ "SELECT * FROM my_table WHERE id=:id", query_params={"id": _id}
+ )
+
+ @staticmethod
+ @sqlquery(isolation_level="READ_UNCOMMITTED")
+ def _select_uncommitted():
+ return QueryData("SELECT * FROM uncommitted")
+
+
+class TestSqlUpdateDecorator:
+ """
+ Test Sql Update Decorator
+ """
+
+ @staticmethod
+ @pytest.fixture
+ def mock_engine(mock_create_engine):
+ return setup_mock_engine(mock_create_engine)
+
+ @staticmethod
+ @pytest.fixture
+ def mock_connect(mock_engine):
+ return mock_engine.connect.return_value.execution_options
+
+ def test_isolation_default(self, mock_connect):
+ self._update_something({"id": 1, "value": "test"})
+ mock_connect.assert_called_with(isolation_level="READ_COMMITTED")
+
+ def test_isolation_default_read_uncommited(self, mock_connect):
+ self._update_something_uncommited_isolation({"id": 1, "value": "test"})
+ mock_connect.assert_called_with(isolation_level="READ_UNCOMMITTED")
+ mock_connect.return_value.begin.assert_called()
+ mock_connect.return_value.begin.return_value.commit.assert_called()
+ mock_connect.return_value.__exit__.assert_called()
+
+ def test_transaction(self, mock_connect):
+ self._update_something({"id": 1, "value": "test"})
+ mock_connect().begin.assert_called()
+ mock_connect().begin.return_value.commit.assert_called()
+ mock_connect().__exit__.assert_called()
+
+ def test_transaction_fails(self, mock_connect):
+ mock_connect().execute.side_effect = Exception("error")
+ with pytest.raises(Exception):
+ self._update_something({"id": 1, "value": "test"})
+ mock_connect().begin.return_value.commit.assert_not_called()
+ mock_connect().begin.return_value.rollback.assert_called()
+ mock_connect().__exit__.assert_called()
+
+ def test_execute_passes_values(self, mock_engine):
+ values = {"id": 1, "value": "test"}
+ self._update_something(values)
+
+ execute_call = (
+ mock_engine.connect.return_value.execution_options.return_value.execute
+ )
+ execute_call.assert_called()
+
+ execute_call_args = execute_call.call_args[0]
+ assert execute_call_args[0].text == "INSERT something"
+ assert values == execute_call_args[1]
+
+ def test_execute_query_values_none(self, mock_engine):
+ self._update_something(None)
+
+ execute_call = (
+ mock_engine.connect.return_value.execution_options.return_value.execute
+ )
+ execute_call.assert_called()
+
+ self._expect_args_list(execute_call.call_args_list[0], "INSERT something")
+
+ def test_execute_query_values_not_given(self, mock_engine):
+ # pylint: disable=unused-argument
+ self._update_something_no_params()
+
+ def test_execute_multi_yield(self, mock_connect):
+ expected_values = [
+ {"id": 1, "value": "test 1"},
+ {"id": 2, "value": "test 2"},
+ {"id": 3, "value": "test 3"},
+ ]
+ self._update_something_multi_yield(expected_values)
+
+ execute_call = mock_connect().execute
+ assert execute_call.call_count == 3
+
+ for call_args in execute_call.call_args_list:
+ self._expect_args_list(call_args, "INSERT something")
+
+ def test_execute_fails_list_if_multi_false(self):
+ expected_values = [
+ {"id": 1, "value": "test 1"},
+ {"id": 2, "value": "test 2"},
+ {"id": 3, "value": "test 3"},
+ ]
+ with pytest.raises(Exception):
+ self._update_list_when_multi_false(expected_values)
+
+ def test_execute_multi_yield_and_lists(self, mock_engine):
+ expected_values = [
+ {"id": 1, "value": "test 1"},
+ {"id": 2, "value": "test 2"},
+ {"id": 3, "value": "test 3"},
+ ]
+ other_expected_values = [
+ {"id": 5, "value": "test 5"},
+ {"id": 6, "value": "test 6"},
+ {"id": 7, "value": "test 7"},
+ ]
+ self._update_yield_with_lists(expected_values, other_expected_values)
+
+ execute_call = (
+ mock_engine.connect.return_value.execution_options.return_value.execute
+ )
+ assert execute_call.call_count == 2
+
+ self._expect_args_list(
+ execute_call.call_args_list[0],
+ "INSERT some VALUES ( :values__in_0_0, :values__in_0_1 ), ( :values__in_1_0, :values__in_1_1 ), "
+ "( :values__in_2_0, :values__in_2_1 ) ",
+ )
+ self._expect_args_list(
+ execute_call.call_args_list[1],
+ "INSERT some more VALUES ( :values__other_0_0, :values__other_0_1 ), "
+ "( :values__other_1_0, :values__other_1_1 ), ( :values__other_2_0, :values__other_2_1 ) ",
+ )
+
+ def test_execute_multi_yield_and_lists_some_no_params(self, mock_engine):
+ expected_values = [
+ {"id": 1, "value": "test 1"},
+ {"id": 2, "value": "test 2"},
+ {"id": 3, "value": "test 3"},
+ ]
+ self._update_yield_with_lists_some_no_params(expected_values)
+
+ execute_call = (
+ mock_engine.connect.return_value.execution_options.return_value.execute
+ )
+ assert execute_call.call_count == 4
+
+ self._expect_args_list(
+ execute_call.call_args_list[0],
+ "INSERT some VALUES ( :values__in_0_0, :values__in_0_1 ), ( :values__in_1_0, :values__in_1_1 ), "
+ "( :values__in_2_0, :values__in_2_1 ) ",
+ )
+ self._expect_args_list(execute_call.call_args_list[1], "UPDATE some more")
+ self._expect_args_list(execute_call.call_args_list[2], "UPDATE some more")
+ self._expect_args_list(execute_call.call_args_list[3], "DELETE some more")
+
+ def test_set_foreign_key_checks_default(self, mock_engine):
+ self._update_something_no_params()
+
+ execute_call = (
+ mock_engine.connect.return_value.execution_options.return_value.execute
+ )
+ assert execute_call.call_count == 1
+
+ def test_set_foreign_key_checks_true(self, mock_engine):
+ self._update_without_foreign_key_checks()
+
+ execute_call = (
+ mock_engine.connect.return_value.execution_options.return_value.execute
+ )
+ assert execute_call.call_count == 4
+ assert execute_call.call_args_list[0][0][0].text == "SET FOREIGN_KEY_CHECKS=0"
+ assert execute_call.call_args_list[-1][0][0].text == "SET FOREIGN_KEY_CHECKS=1"
+
+ @staticmethod
+ def _expect_args_list(call_args, expected_query):
+ assert expected_query == call_args[0][0].text
+
+ @staticmethod
+ @sqlupdate(disable_foreign_key_checks=True)
+ def _update_without_foreign_key_checks():
+ yield QueryData("INSERT B_RELIES_ON_A")
+ yield QueryData("INSERT A")
+
+ @staticmethod
+ @sqlupdate()
+ def _update_something(values):
+ return QueryData("INSERT something", query_params=values)
+
+ @staticmethod
+ @sqlupdate(isolation_level="READ_UNCOMMITTED")
+ def _update_something_uncommited_isolation(values):
+ return QueryData(f"INSERT WITH uncommitted {values}")
+
+ @staticmethod
+ @sqlupdate()
+ def _update_something_no_params():
+ return QueryData("INSERT something")
+
+ @staticmethod
+ @sqlupdate()
+ def _update_something_multi_yield(multiple_values):
+ for values in multiple_values:
+ yield QueryData("INSERT something", query_params=values)
+
+ @staticmethod
+ @sqlupdate()
+ def _update_something_return_list(multiple_values):
+ return QueryData("INSERT something", query_params=multiple_values)
+
+ @staticmethod
+ @sqlupdate()
+ def _update_list_when_multi_false(multiple_values):
+ return "INSERT something", multiple_values
+
+ @staticmethod
+ @sqlupdate()
+ def _update_yield_with_lists(multiple_values, other_values):
+ """
+ method is static just to help show you can use static methods if
+ you don't want to instantiate an instance of the class
+
+ NOTE:
+ """
+ yield QueryData(
+ "INSERT some {values__in}",
+ template_params=_get_template_params("values__in", multiple_values),
+ )
+ yield QueryData(
+ "INSERT some more {values__other}",
+ template_params=_get_template_params("values__other", other_values),
+ )
+
+ @staticmethod
+ @sqlupdate()
+ def _update_yield_with_lists_some_no_params(multiple_values):
+ """
+ method is static just to help show you can use static methods if
+ you don't want to instantiate an instance of the class
+ """
+ yield QueryData(
+ "INSERT some {values__in}",
+ template_params=_get_template_params("values__in", multiple_values),
+ )
+ yield QueryData("UPDATE some more")
+ yield QueryData("UPDATE some more")
+ yield QueryData("DELETE some more")
+
+
+def _get_template_params(key, values):
+ """
+ template parameters is handled here as an example of what you might end up
+ doing. usually data coming in is going to be a list
+
+ :param key: the template key we want to use to build our template with
+ :param values: the list of objects or mariadbmaps,
+ :return: a keyed list of tuples or mariadbmaps
+ """
+ if isinstance(values[0], DbMapResult):
+ return {key: values}
+ return {key: [(v["id"], v["value"]) for v in values]}
diff --git a/dysql/test/test_sql_exists_decorator.py b/dysql/test/test_sql_exists_decorator.py
new file mode 100644
index 0000000000000000000000000000000000000000..daf56a13c346e1957ab5580acb385035ad3ff102
--- /dev/null
+++ b/dysql/test/test_sql_exists_decorator.py
@@ -0,0 +1,165 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+from unittest.mock import Mock
+
+import pytest
+
+from dysql import sqlexists, QueryData
+from dysql.test import setup_mock_engine
+
+
+TRUE_QUERY = "SELECT 1 from table"
+TRUE_QUERY_PARAMS = "SELECT 1 from table where key=:key"
+FALSE_QUERY = "SELECT 1 from false_table "
+FALSE_QUERY_PARAMS = "SELECT 1 from table where key=:key"
+TRUE_PARAMS = {"key": 123}
+FALSE_PARAMS = {"key": 456}
+SELECT_EXISTS_QUERY = "SELECT 1 WHERE EXISTS ( {} )"
+SELECT_EXISTS_NO_WHERE_QUERY = "SELECT EXISTS ( {} )"
+EXISTS_QUERIES = {
+ "true": SELECT_EXISTS_QUERY.format(TRUE_QUERY),
+ "false": SELECT_EXISTS_QUERY.format(FALSE_QUERY),
+ "true_params": SELECT_EXISTS_QUERY.format(TRUE_QUERY_PARAMS),
+ "false_params": SELECT_EXISTS_QUERY.format(FALSE_QUERY_PARAMS),
+ "true_no_where": SELECT_EXISTS_NO_WHERE_QUERY.format(TRUE_QUERY),
+ "false_no_where": SELECT_EXISTS_NO_WHERE_QUERY.format(FALSE_QUERY),
+}
+
+
+@pytest.fixture(autouse=True)
+def mock_engine_fixture(mock_create_engine):
+ mock_engine = setup_mock_engine(mock_create_engine)
+ mock_engine.connect.return_value.execution_options.return_value.execute.side_effect = _check_query_and_return_result
+ mock_engine.connect().execution_options().__enter__ = Mock()
+ mock_engine.connect().execution_options().__exit__ = Mock()
+
+
+def test_exists_true():
+ assert _exists_true()
+
+
+def test_exists_false():
+ assert not _exists_false()
+
+
+def test_exists_true_params():
+ assert _exists_true_params()
+
+
+def test_exists_false_params():
+ assert not _exists_false_params()
+
+
+def test_exists_query_contains_with_exists_true():
+ """
+ this helps to test that if someone adds an exists statement, we don't add the exists
+ exists(exists()) will always give a 'true' result
+ """
+ # should match against the same query, should still match
+ assert _exists_specified("true")
+
+
+def test_exists_query_contains_with_exists_false():
+ """
+ this helps to test that if someone adds an exists statement, we don't add the exists
+ exists(exists()) will always give a 'true' result
+ """
+ # should match against the same query, should still match
+ assert not _exists_specified("false")
+
+
+def test_exists_without_where_true():
+ """
+ this helps avoid an issue discovered when using the 'utf8' charset, some queries with the exists
+ query would fail to decode the '0' returned with a query as just `SELECT EXISTS` but work as expected
+ when using `SELECT 1 WHERE EXISTS`
+ """
+ assert _select_exists_no_where_true()
+
+
+def test_exists_witohut_where_false():
+ """
+ this helps avoid an issue discovered when using the 'utf8' charset, some queries with the exists
+ query would fail to decode the '0' returned with a query as just `SELECT EXISTS` but work as expected
+ when using `SELECT 1 WHERE EXISTS`
+ """
+ assert not _select_exists_no_where_false()
+
+
+def test_exists_query_starts_with_exists_handles_whitespace():
+ """
+ this helps to test that if someone adds an exists statement, we don't add the exists
+ exists(exists()) will always give a 'true' result
+ """
+ # should trim the whitespace and match appropiately
+ assert _exists_whitespace()
+
+
+@sqlexists()
+def _select_exists_no_where_false():
+ return QueryData(EXISTS_QUERIES["false_no_where"])
+
+
+@sqlexists()
+def _select_exists_no_where_true():
+ return QueryData(EXISTS_QUERIES["true_no_where"])
+
+
+@sqlexists()
+def _exists_specified(key):
+ return QueryData(EXISTS_QUERIES[key])
+
+
+@sqlexists()
+def _exists_true():
+ return QueryData(TRUE_QUERY)
+
+
+@sqlexists()
+def _exists_false():
+ return QueryData(FALSE_QUERY)
+
+
+@sqlexists()
+def _exists_true_params():
+ return QueryData(TRUE_QUERY, TRUE_PARAMS)
+
+
+@sqlexists()
+def _exists_false_params():
+ return QueryData(FALSE_QUERY, FALSE_PARAMS)
+
+
+@sqlexists()
+def _exists_whitespace():
+ return QueryData(
+ """
+ """
+ + TRUE_QUERY
+ )
+
+
+def _check_query_and_return_result(query, params):
+ """
+ check that the query matches our expectations
+ and then set the return value for the scalar call.
+ scalar() returns either 1 or 0, 1 for true, 0 for false
+ """
+ assert query.text in list(EXISTS_QUERIES.values())
+ scalar_mock = Mock()
+ # default mock responses to true, then we only handle setting false responses
+ scalar_mock.scalar.return_value = 1
+ if query.text == EXISTS_QUERIES["true_params"]:
+ assert params.get("key") == 123
+ if query.text == EXISTS_QUERIES["false_params"]:
+ assert params.get("key") == 456
+ scalar_mock.scalar.return_value = 0
+ elif query.text == EXISTS_QUERIES["false"]:
+ scalar_mock.scalar.return_value = 0
+ return scalar_mock
diff --git a/dysql/test/test_sql_in_list_templates.py b/dysql/test/test_sql_in_list_templates.py
new file mode 100644
index 0000000000000000000000000000000000000000..a12531a4f7638524a120ef1832369d2a92650376
--- /dev/null
+++ b/dysql/test/test_sql_in_list_templates.py
@@ -0,0 +1,289 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+# pylint: disable=too-many-public-methods
+import pytest
+
+import dysql
+from dysql import QueryData, sqlquery
+from dysql.test import (
+ verify_query,
+ verify_query_args,
+ verify_query_params,
+ setup_mock_engine,
+)
+
+
+@pytest.fixture(name="mock_engine", autouse=True)
+def mock_engine_fixture(mock_create_engine):
+ mock_engine = setup_mock_engine(mock_create_engine)
+ mock_engine.connect().execution_options().execute.side_effect = lambda x, y: []
+ return mock_engine
+
+
+def test_list_in_numbers(mock_engine):
+ _query(
+ "SELECT * FROM table WHERE {in__column_a}",
+ template_params={"in__column_a": [1, 2, 3, 4]},
+ )
+ verify_query_params(
+ mock_engine,
+ "SELECT * FROM table WHERE column_a IN ( :in__column_a_0, :in__column_a_1, :in__column_a_2, :in__column_a_3 ) ",
+ {
+ "in__column_a_0": 1,
+ "in__column_a_1": 2,
+ "in__column_a_2": 3,
+ "in__column_a_3": 4,
+ },
+ )
+
+
+def test_list_in__strings(mock_engine):
+ _query(
+ "SELECT * FROM table WHERE {in__column_a}",
+ template_params={"in__column_a": ["a", "b", "c", "d"]},
+ )
+ verify_query_params(
+ mock_engine,
+ "SELECT * FROM table WHERE column_a IN ( :in__column_a_0, :in__column_a_1, :in__column_a_2, :in__column_a_3 ) ",
+ {
+ "in__column_a_0": "a",
+ "in__column_a_1": "b",
+ "in__column_a_2": "c",
+ "in__column_a_3": "d",
+ },
+ )
+
+
+def test_list_not_in_numbers(mock_engine):
+ _query(
+ "SELECT * FROM table WHERE {not_in__column_b}",
+ template_params={"not_in__column_b": [1, 2, 3, 4]},
+ )
+ verify_query_params(
+ mock_engine,
+ "SELECT * FROM table WHERE column_b NOT IN ( :not_in__column_b_0, :not_in__column_b_1, "
+ ":not_in__column_b_2, :not_in__column_b_3 ) ",
+ {
+ "not_in__column_b_0": 1,
+ "not_in__column_b_1": 2,
+ "not_in__column_b_2": 3,
+ "not_in__column_b_3": 4,
+ },
+ )
+
+
+def test_list_not_in_strings(mock_engine):
+ _query(
+ "SELECT * FROM table WHERE {not_in__column_b}",
+ template_params={"not_in__column_b": ["a", "b", "c", "d"]},
+ )
+ verify_query_params(
+ mock_engine,
+ "SELECT * FROM table WHERE column_b NOT IN ( :not_in__column_b_0, :not_in__column_b_1, "
+ ":not_in__column_b_2, :not_in__column_b_3 ) ",
+ {
+ "not_in__column_b_0": "a",
+ "not_in__column_b_1": "b",
+ "not_in__column_b_2": "c",
+ "not_in__column_b_3": "d",
+ },
+ )
+
+
+def test_list_in_handles_empty(mock_engine):
+ _query(
+ "SELECT * FROM table WHERE {in__column_a}", template_params={"in__column_a": []}
+ )
+ verify_query(mock_engine, "SELECT * FROM table WHERE 1 <> 1 ")
+
+
+def test_list_in_handles_no_param():
+ with pytest.raises(
+ dysql.query_utils.ListTemplateException, match="['in__column_a']"
+ ):
+ _query("SELECT * FROM table WHERE {in__column_a}")
+
+
+def test_list_in_multiple_lists(mock_engine):
+ _query(
+ "SELECT * FROM table WHERE {in__column_a} OR {in__column_b}",
+ template_params={"in__column_a": ["first", "second"], "in__column_b": [1, 2]},
+ )
+ verify_query(
+ mock_engine,
+ "SELECT * FROM table WHERE column_a IN ( :in__column_a_0, :in__column_a_1 ) "
+ "OR column_b IN ( :in__column_b_0, :in__column_b_1 ) ",
+ )
+
+
+def test_list_in_multiple_lists_one_empty(mock_engine):
+ _query(
+ "SELECT * FROM table WHERE {in__column_a} OR {in__column_b}",
+ template_params={"in__column_a": ["first", "second"], "in__column_b": []},
+ )
+ verify_query(
+ mock_engine,
+ "SELECT * FROM table WHERE column_a IN ( :in__column_a_0, :in__column_a_1 ) OR 1 <> 1 ",
+ )
+
+
+def test_list_in_multiple_lists_one_missing():
+ with pytest.raises(
+ dysql.query_utils.ListTemplateException, match="['in__column_a']"
+ ):
+ _query(
+ "SELECT * FROM table WHERE {in__column_a} OR {in__column_b} ",
+ template_params={"in__column_b": [1, 2]},
+ )
+
+
+def test_list_in_multiple_lists_all_missing():
+ with pytest.raises(
+ dysql.query_utils.ListTemplateException, match="['in__column_a','in__column_b']"
+ ):
+ _query("SELECT * FROM table WHERE {in__column_a} OR {in__column_b} ")
+
+
+def test_list_not_in_handles_empty(mock_engine):
+ _query(
+ "SELECT * FROM table WHERE {not_in__column_b}",
+ template_params={"not_in__column_b": []},
+ )
+ verify_query(mock_engine, "SELECT * FROM table WHERE 1 = 1 ")
+
+
+def test_list_not_in_handles_no_param():
+ with pytest.raises(
+ dysql.query_utils.ListTemplateException, match="['not_in__column_b']"
+ ):
+ _query("SELECT * FROM table WHERE {not_in__column_b} ")
+
+
+def test_list_gives_template_space_before(mock_engine):
+ _query(
+ "SELECT * FROM table WHERE{in__space}", template_params={"in__space": [9, 8]}
+ )
+ verify_query(
+ mock_engine,
+ "SELECT * FROM table WHERE space IN ( :in__space_0, :in__space_1 ) ",
+ )
+
+
+def test_list_gives_template_space_after(mock_engine):
+ _query(
+ "SELECT * FROM table WHERE {in__space}AND other_condition = 1",
+ template_params={"in__space": [9, 8]},
+ )
+ verify_query(
+ mock_engine,
+ "SELECT * FROM table WHERE space IN ( :in__space_0, :in__space_1 ) AND other_condition = 1",
+ )
+
+
+def test_list_gives_template_space_before_and_after(mock_engine):
+ _query(
+ "SELECT * FROM table WHERE{in__space}AND other_condition = 1",
+ template_params={"in__space": [9, 8]},
+ )
+ verify_query(
+ mock_engine,
+ "SELECT * FROM table WHERE space IN ( :in__space_0, :in__space_1 ) AND other_condition = 1",
+ )
+
+
+def test_in_contains_whitespace(mock_engine):
+ _query("{in__column_one}", template_params={"in__column_one": [1, 2]})
+ verify_query(
+ mock_engine, " column_one IN ( :in__column_one_0, :in__column_one_1 ) "
+ )
+
+
+def test_template_handles_table_qualifier(mock_engine):
+ """
+ when the table is specified with a dot separator, we need to split the table out of the
+ keyword and the keyword passed in should be passed in without the keyword
+
+ {in__table.column} -> {table}.{in__column} -> table.column IN (:in__column_0, :in__column_1)
+ :return:
+ """
+ _query(
+ "SELECT * FROM table WHERE {in__table.column}",
+ template_params={"in__table.column": [1, 2]},
+ )
+ verify_query(
+ mock_engine,
+ "SELECT * FROM table WHERE table.column IN ( :in__table_column_0, :in__table_column_1 ) ",
+ )
+ verify_query_args(mock_engine, {"in__table_column_0": 1, "in__table_column_1": 2})
+
+
+def test_template_handles_multiple_table_qualifier(mock_engine):
+ _query(
+ "SELECT * FROM table WHERE {in__table.column} AND {not_in__other_column}",
+ template_params={
+ "in__table.column": [1, 2],
+ "not_in__other_column": ["a", "b"],
+ },
+ )
+ verify_query(
+ mock_engine,
+ "SELECT * FROM table WHERE table.column IN ( :in__table_column_0, :in__table_column_1 ) "
+ "AND other_column NOT IN ( :not_in__other_column_0, :not_in__other_column_1 ) ",
+ )
+ verify_query_args(
+ mock_engine,
+ {
+ "in__table_column_0": 1,
+ "in__table_column_1": 2,
+ "not_in__other_column_0": "a",
+ "not_in__other_column_1": "b",
+ },
+ )
+
+
+def test_empty_in_contains_whitespace(mock_engine):
+ _query("{in__column_one}", template_params={"in__column_one": []})
+ verify_query(mock_engine, " 1 <> 1 ")
+
+
+def test_multiple_templates_same_column_diff_table(mock_engine):
+ template_params = {
+ "in__table.status": ["on", "off", "waiting"],
+ "in__other_table.status": ["success", "partial_success"],
+ }
+ expected_params_from_template = {
+ "in__table_status_0": "on",
+ "in__table_status_1": "off",
+ "in__table_status_2": "waiting",
+ "in__other_table_status_0": "success",
+ "in__other_table_status_1": "partial_success",
+ }
+
+ # writing each of these queries out to help see what we expect compared to
+ # the query we actually sent
+ _query(
+ "SELECT * FROM table WHERE {in__table.status} AND {in__other_table.status}",
+ template_params=template_params,
+ )
+ expected_query = (
+ "SELECT * FROM table WHERE table.status IN ( :in__table_status_0, :in__table_status_1, "
+ ":in__table_status_2 ) AND other_table.status IN ( :in__other_table_status_0, "
+ ":in__other_table_status_1 ) "
+ )
+
+ connection = mock_engine.connect.return_value.execution_options.return_value
+ execute_call = connection.execute
+ execute_call.assert_called_once()
+ assert execute_call.call_args[0][0].text == expected_query
+ assert execute_call.call_args[0][1] == expected_params_from_template
+
+
+@sqlquery()
+def _query(query, query_params=None, template_params=None):
+ return QueryData(query, query_params=query_params, template_params=template_params)
diff --git a/dysql/test/test_sql_insert_templates.py b/dysql/test/test_sql_insert_templates.py
new file mode 100644
index 0000000000000000000000000000000000000000..56eb5843657b31b9d8ec3cc684cf33082b448aba
--- /dev/null
+++ b/dysql/test/test_sql_insert_templates.py
@@ -0,0 +1,174 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+import pytest
+
+import dysql
+from dysql import QueryData, sqlupdate, QueryDataError
+from dysql.test import (
+ verify_query,
+ verify_query_args,
+ setup_mock_engine,
+)
+
+
+@pytest.fixture(name="mock_engine", autouse=True)
+def mock_engine_fixture(mock_create_engine):
+ initial_id = 0
+
+ def handle_execute(query=None, args=None):
+ nonlocal initial_id
+ if "INSERT INTO get_last(name)" in query.text:
+ initial_id += 1
+ if "SELECT LAST_INSERT_ID()" == query.text:
+ return type("Result", (), {"scalar": lambda: initial_id})
+ return []
+
+ mock_engine = setup_mock_engine(mock_create_engine)
+ execute_mock = mock_engine.connect().execution_options().execute
+ execute_mock.side_effect = handle_execute
+ return mock_engine
+
+
+def test_insert_non_query_data_fails():
+ @sqlupdate()
+ def select_with_string():
+ return "INSERT"
+
+ with pytest.raises(QueryDataError):
+ select_with_string()
+
+
+def test_insert_single_column(mock_engine):
+ insert_into_single_value(["Tom", "Jerry"])
+ verify_query(
+ mock_engine,
+ "INSERT INTO table(name) VALUES ( :values__name_col_0 ), ( :values__name_col_1 ) ",
+ )
+
+
+def test_insert_single_column_single_value(mock_engine):
+ insert_into_single_value("Tom")
+ verify_query(mock_engine, "INSERT INTO table(name) VALUES ( :values__name_col_0 ) ")
+
+
+def test_insert_single_value_empty():
+ with pytest.raises(
+ dysql.query_utils.ListTemplateException, match="['values_name_col']"
+ ):
+ insert_into_single_value([])
+
+
+def test_insert_single_value_no_key():
+ with pytest.raises(
+ dysql.query_utils.ListTemplateException, match="['values_name_col']"
+ ):
+ insert_into_single_value(None)
+
+
+def test_insert_multiple_values(mock_engine):
+ insert_into_multiple_values(
+ [
+ {"name": "Tom", "email": "tom@adobe.com"},
+ {"name": "Jerry", "email": "jerry@adobe.com"},
+ ]
+ )
+ verify_query(
+ mock_engine,
+ "INSERT INTO table(name, email) VALUES ( :values__users_0_0, :values__users_0_1 ), "
+ "( :values__users_1_0, :values__users_1_1 ) ",
+ )
+ verify_query_args(
+ mock_engine,
+ {
+ "values__users_0_0": "Tom",
+ "values__users_0_1": "tom@adobe.com",
+ "values__users_1_0": "Jerry",
+ "values__users_1_1": "jerry@adobe.com",
+ },
+ )
+
+
+@pytest.mark.parametrize(
+ "args",
+ [
+ ([("bob", "bob@email.com")]),
+ ([("bob", "bob@email.com"), ("tom", "tom@email.com")]),
+ None,
+ (),
+ ],
+)
+def test_insert_with_callback(args):
+ def callback(items):
+ assert items == args
+
+ @sqlupdate(on_success=callback)
+ def insert(items):
+ yield QueryData(f"INSERT INTO table(name, email) {items}")
+
+ insert(args)
+
+
+def test_insert_with_callack_not_called(mock_engine):
+ def callback():
+ assert False
+
+ @sqlupdate(on_success=callback)
+ def insert():
+ yield QueryData("INSERT INTO table(name, email)")
+
+ mock_engine.connect().execution_options.return_value.execute.side_effect = (
+ Exception()
+ )
+ with pytest.raises(Exception):
+ insert()
+
+
+@sqlupdate()
+def insert_into_multiple_values(users):
+ yield QueryData(
+ "INSERT INTO table(name, email) {values__users}",
+ template_params={"values__users": [(d["name"], d["email"]) for d in users]},
+ )
+
+
+@sqlupdate()
+def insert_into_single_value(names):
+ template_params = {}
+ if names is not None:
+ template_params = {"values__name_col": names}
+
+ return QueryData(
+ "INSERT INTO table(name) {values__name_col}", template_params=template_params
+ )
+
+
+def test_last_insert_id():
+ @sqlupdate()
+ def insert(get_last_insert_id=None):
+ yield QueryData("INSERT INTO get_last(name) VALUES ('Tom')")
+ assert get_last_insert_id
+ assert get_last_insert_id() == 1
+ yield QueryData("INSERT INTO get_last(name) VALUES ('Jerry')")
+ assert get_last_insert_id() == 2
+
+ insert()
+
+
+def test_last_insert_id_removed_before_callback():
+ def callback(**kwargs):
+ assert "get_last_insert_id" not in kwargs
+
+ @sqlupdate()
+ def insert(get_last_insert_id=None):
+ assert get_last_insert_id
+ yield QueryData("INSERT INTO get_last(name) VALUES ('Tom')")
+ yield QueryData("INSERT INTO get_last(name) VALUES ('Jerry')")
+ assert get_last_insert_id() == 2
+
+ insert()
diff --git a/dysql/test/test_template_generators.py b/dysql/test/test_template_generators.py
new file mode 100644
index 0000000000000000000000000000000000000000..9fc797f6febfff7b060d9eb05ff5376a822e5098
--- /dev/null
+++ b/dysql/test/test_template_generators.py
@@ -0,0 +1,222 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+import pytest
+
+from dysql.query_utils import TemplateGenerators, ListTemplateException
+
+
+class TestTemplatesGenerators:
+ """
+ Test we get templates back from Templates
+ """
+
+ number_values = [1, 2, 3, 4]
+ string_values = ["1", "2", "3", "4"]
+ set_values = {1, 2, 3, 4}
+ insert_values = [("ironman", 1), ("batman", 2)]
+ tuple_values = [(1, 2), (3, 4)]
+ query = "column_a IN ( :column_a_0, :column_a_1, :column_a_2, :column_a_3 )"
+
+ query_with_list_of_tuples = (
+ "(column_a, column_b) IN (( :column_acolumn_b_0_0, :column_acolumn_b_0_1 ), "
+ "( :column_acolumn_b_1_0, :column_acolumn_b_1_1 ))"
+ )
+ not_query_with_list_of_tuples = (
+ "(column_a, column_b) NOT IN (( :column_acolumn_b_0_0, :column_acolumn_b_0_1 ), "
+ "( :column_acolumn_b_1_0, :column_acolumn_b_1_1 ))"
+ )
+ query_with_table = "table.column_a IN ( :table_column_a_0, :table_column_a_1, :table_column_a_2, :table_column_a_3 )"
+ not_query = "column_a NOT IN ( :column_a_0, :column_a_1, :column_a_2, :column_a_3 )"
+ not_query_with_table = "table.column_a NOT IN ( :table_column_a_0, :table_column_a_1, :table_column_a_2, :table_column_a_3 )"
+
+ test_query_data = (
+ "template_function, column_name,column_values,expected_query",
+ [
+ (TemplateGenerators.in_column, "column_a", number_values, query),
+ (
+ TemplateGenerators.in_column,
+ "table.column_a",
+ number_values,
+ query_with_table,
+ ),
+ (
+ TemplateGenerators.in_column,
+ "table.column_a",
+ set_values,
+ query_with_table,
+ ),
+ (TemplateGenerators.in_column, "column_a", string_values, query),
+ (
+ TemplateGenerators.in_column,
+ "table.column_a",
+ string_values,
+ query_with_table,
+ ),
+ (TemplateGenerators.in_column, "column_a", [], "1 <> 1"),
+ (
+ TemplateGenerators.in_multi_column,
+ "(column_a, column_b)",
+ tuple_values,
+ query_with_list_of_tuples,
+ ),
+ (
+ TemplateGenerators.not_in_multi_column,
+ "(column_a, column_b)",
+ tuple_values,
+ not_query_with_list_of_tuples,
+ ),
+ (TemplateGenerators.not_in_column, "column_a", number_values, not_query),
+ (
+ TemplateGenerators.not_in_column,
+ "table.column_a",
+ number_values,
+ not_query_with_table,
+ ),
+ (TemplateGenerators.not_in_column, "column_a", string_values, not_query),
+ (
+ TemplateGenerators.not_in_column,
+ "table.column_a",
+ string_values,
+ not_query_with_table,
+ ),
+ (
+ TemplateGenerators.not_in_column,
+ "table.column_a",
+ set_values,
+ not_query_with_table,
+ ),
+ (TemplateGenerators.not_in_column, "column_a", [], "1 = 1"),
+ (
+ TemplateGenerators.values,
+ "someid",
+ insert_values,
+ "VALUES ( :someid_0_0, :someid_0_1 ), ( :someid_1_0, :someid_1_1 )",
+ ),
+ ],
+ )
+
+ parameter_numbers = {
+ "column_a_0": number_values[0],
+ "column_a_1": number_values[1],
+ "column_a_2": number_values[2],
+ "column_a_3": number_values[3],
+ }
+ with_table_parameter_numbers = {
+ "table_column_a_0": number_values[0],
+ "table_column_a_1": number_values[1],
+ "table_column_a_2": number_values[2],
+ "table_column_a_3": number_values[3],
+ }
+ parameter_strings = {
+ "column_a_0": string_values[0],
+ "column_a_1": string_values[1],
+ "column_a_2": string_values[2],
+ "column_a_3": string_values[3],
+ }
+ with_table_parameter_strings = {
+ "table_column_a_0": string_values[0],
+ "table_column_a_1": string_values[1],
+ "table_column_a_2": string_values[2],
+ "table_column_a_3": string_values[3],
+ }
+ test_params_data = (
+ "template_function, column_name,column_values,expected_params",
+ [
+ (
+ TemplateGenerators.in_column,
+ "column_a",
+ number_values,
+ parameter_numbers,
+ ),
+ (
+ TemplateGenerators.in_column,
+ "column_a",
+ set_values,
+ parameter_numbers,
+ ),
+ (
+ TemplateGenerators.in_column,
+ "table.column_a",
+ number_values,
+ with_table_parameter_numbers,
+ ),
+ (
+ TemplateGenerators.in_column,
+ "column_a",
+ string_values,
+ parameter_strings,
+ ),
+ (
+ TemplateGenerators.in_column,
+ "table.column_a",
+ string_values,
+ with_table_parameter_strings,
+ ),
+ (TemplateGenerators.in_column, "column_a", [], None),
+ (
+ TemplateGenerators.not_in_column,
+ "column_a",
+ number_values,
+ parameter_numbers,
+ ),
+ (
+ TemplateGenerators.not_in_column,
+ "table.column_a",
+ number_values,
+ with_table_parameter_numbers,
+ ),
+ (
+ TemplateGenerators.not_in_column,
+ "column_a",
+ string_values,
+ parameter_strings,
+ ),
+ (
+ TemplateGenerators.not_in_column,
+ "column_a",
+ set_values,
+ parameter_numbers,
+ ),
+ (
+ TemplateGenerators.not_in_column,
+ "table.column_a",
+ string_values,
+ with_table_parameter_strings,
+ ),
+ (TemplateGenerators.not_in_column, "column_a", [], None),
+ (
+ TemplateGenerators.values,
+ "someid",
+ insert_values,
+ {
+ "someid_0_0": insert_values[0][0],
+ "someid_0_1": insert_values[0][1],
+ "someid_1_0": insert_values[1][0],
+ "someid_1_1": insert_values[1][1],
+ },
+ ),
+ ],
+ )
+
+ @staticmethod
+ @pytest.mark.parametrize(*test_query_data)
+ def test_query(template_function, column_name, column_values, expected_query):
+ query, _ = template_function(column_name, column_values)
+ assert query == expected_query
+
+ @staticmethod
+ @pytest.mark.parametrize(*test_params_data)
+ def test_params(template_function, column_name, column_values, expected_params):
+ _, params = template_function(column_name, column_values)
+ assert params == expected_params
+
+ @staticmethod
+ def test_insert_none():
+ with pytest.raises(ListTemplateException):
+ TemplateGenerators.values("someid", None)
diff --git a/dysql/test/test_test_managers.py b/dysql/test/test_test_managers.py
new file mode 100644
index 0000000000000000000000000000000000000000..f52fdd9f4f0dc931377a1c486cda840e4e98c26c
--- /dev/null
+++ b/dysql/test/test_test_managers.py
@@ -0,0 +1,76 @@
+"""
+Copyright 2026 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+import pytest
+from unittest.mock import patch
+
+from dysql.test_managers import MariaDbTestManager
+
+
+class TestMariaDbTestManager:
+ """
+ Tests for MariaDbTestManager
+ """
+
+ @patch.object(MariaDbTestManager, "_run")
+ def test_create_test_db_without_schema(self, mock_run):
+ """Test that _create_test_db works without a schema_db_name"""
+ manager = MariaDbTestManager(db_name="test_db")
+ manager._create_test_db()
+
+ # Should have called _run twice (DROP and CREATE)
+ assert mock_run.call_count == 2
+
+ # Verify DROP command
+ drop_call = mock_run.call_args_list[0]
+ assert "DROP DATABASE IF EXISTS test_db" in drop_call[0][0]
+
+ # Verify CREATE command
+ create_call = mock_run.call_args_list[1]
+ assert "CREATE DATABASE IF NOT EXISTS test_db" in create_call[0][0]
+
+ @patch.object(MariaDbTestManager, "_run")
+ @pytest.mark.parametrize("command", ["--no-data", "--routines", "source_db"])
+ def test_create_test_includes_commands(self, mock_run, command):
+ """Test that _create_test_db includes --routines flag when copying schema"""
+ manager = MariaDbTestManager(db_name="test_db", schema_db_name="source_db")
+ manager._create_test_db()
+
+ # Should have called _run three times (DROP, CREATE, and mysqldump)
+ assert mock_run.call_count == 3
+
+ # Verify mysqldump command includes command
+ mysqldump_call = mock_run.call_args_list[2]
+ mysqldump_command = mysqldump_call[0][0]
+
+ assert "mariadb-dump" in mysqldump_command
+ assert command in mysqldump_command
+
+ @patch.object(MariaDbTestManager, "_run")
+ def test_create_test_db_mysqldump_command_format(self, mock_run):
+ """Test the exact format of the mysqldump command"""
+ manager = MariaDbTestManager(db_name="test_db", schema_db_name="source_db")
+ manager._create_test_db()
+
+ mysqldump_call = mock_run.call_args_list[2]
+ mysqldump_command = mysqldump_call[0][0]
+
+ # Verify the command has the correct structure
+ # mysqldump --no-data --routines -p{password} {schema_db_name} -h{host} | mariadb ...
+ assert "| mariadb" in mysqldump_command
+ assert "test_db" in mysqldump_command
+
+ @patch.object(MariaDbTestManager, "_run")
+ def test_tear_down_test_db(self, mock_run):
+ """Test that _tear_down_test_db drops the database"""
+ manager = MariaDbTestManager(db_name="test_db")
+ manager._tear_down_test_db()
+
+ assert mock_run.call_count == 1
+ drop_call = mock_run.call_args_list[0]
+ assert "DROP DATABASE IF EXISTS test_db" in drop_call[0][0]
diff --git a/dysql/test_managers.py b/dysql/test_managers.py
new file mode 100644
index 0000000000000000000000000000000000000000..21d8d998ed59adab403c0f0f44454f5c7d90d4ad
--- /dev/null
+++ b/dysql/test_managers.py
@@ -0,0 +1,236 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+import abc
+import logging
+import os
+import subprocess
+from time import sleep
+from typing import Optional
+
+from .connections import sqlquery
+from .databases import (
+ is_set_current_database_supported,
+ set_current_database,
+ set_default_connection_parameters,
+)
+from .mappers import CountMapper
+from .query_utils import QueryData
+
+LOGGER = logging.getLogger(__name__)
+
+
+class DbTestManagerBase(abc.ABC):
+ """
+ Base class for all test managers. See individual implementations for usage details.
+ """
+
+ # pylint: disable=too-many-instance-attributes
+
+ def __init__(
+ self,
+ host: str,
+ username: str,
+ password: str,
+ db_name: str,
+ schema_db_name: Optional[str],
+ docker_container: Optional[str] = None,
+ keep_db: bool = False,
+ **connection_defaults,
+ ): # pylint: disable=too-many-arguments
+ """
+ Constructor, any unknown kwargs are passed directly to set_default_connection_parameters.
+
+ :param host: the host to access the test database
+ :param username: the username to access the test database
+ :param password: the password to access the test database
+ :param db_name: the name of the test database
+ :param schema_db_name: the name of the DB to duplicate schema from (using mariadb-dump)
+ :param docker_container: the name of the docker container where the database is running (if in docker)
+ :param keep_db: This prevents teardown from removing the created database after running tests
+ which can be helpful in debugging
+ """
+ self.host = host
+ self.username = username
+ self.password = password
+ self.db_name = db_name
+ self.schema_db_name = schema_db_name
+ self.docker_container = docker_container
+ self.keep_db = keep_db
+ self.connection_defaults = connection_defaults
+ self.in_docker = self._is_running_in_docker()
+
+ @staticmethod
+ def _is_running_in_docker():
+ if os.path.exists("/.dockerenv"):
+ return True
+
+ if os.path.exists("/proc/1/cgroup"):
+ with open("/proc/1/cgroup", "rt", encoding="utf8") as fobj:
+ contents = fobj.read()
+ for marker in ("docker", "kubepod", "lxc"):
+ if marker in contents:
+ return True
+ return False
+
+ def __enter__(self):
+ LOGGER.debug(f"Setting up database : {self.db_name}")
+ # Set the host based on whether we are in buildrunner or not (to test locally)
+
+ self._create_test_db()
+ set_default_connection_parameters(
+ self.host,
+ self.username,
+ self.password,
+ self.db_name,
+ **self.connection_defaults,
+ )
+
+ # Set the database if supported by the python runtime
+ if is_set_current_database_supported():
+ set_current_database(self.db_name)
+
+ if self.schema_db_name:
+ self._wait_for_tables_exist()
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ if not self.keep_db:
+ LOGGER.debug(f"Tearing down database : {self.db_name}")
+ self._tear_down_test_db()
+
+ @abc.abstractmethod
+ def _create_test_db(self) -> None:
+ """
+ Must be overridden in implementing classes. Creates the test database from the self.schema_db_name
+ database (if present) or an empty database desired.
+ """
+
+ @abc.abstractmethod
+ def _get_tables_count(self, db_name: str) -> int:
+ """
+ Must be overridden in implementing classes. Retrieves the current table count for the database.
+ :param db_name: the database to retrieve the count for
+ :return: the number of tables present in the database
+ """
+
+ @abc.abstractmethod
+ def _tear_down_test_db(self) -> None:
+ """
+ Must be overridden in implementing classes. Tears down the test database.
+ """
+
+ def _wait_for_tables_exist(self) -> None:
+ """
+ Waits for the tables to exist in the new test database.
+ """
+ tables_exist = False
+ expected_count = self._get_tables_count(self.schema_db_name)
+ while not tables_exist:
+ sleep(0.25)
+ LOGGER.debug("Tables are still not ready")
+ actual_count = self._get_tables_count(self.db_name)
+ tables_exist = expected_count == actual_count
+
+ def _run(self, command: str) -> subprocess.CompletedProcess:
+ """
+ Runs a command, wrapping the command in docker commands if necessary.
+ :param command: the command to run
+ :return: the completed process information
+ """
+ if not self.in_docker:
+ command = f"docker exec {self.docker_container} bash -c '{command}'"
+
+ try:
+ LOGGER.debug(f"Executing : '{command}'")
+ completed_process = subprocess.run(
+ command, shell=True, timeout=30, check=True, capture_output=True
+ )
+ LOGGER.debug(f"Executed : {completed_process.stdout}")
+
+ return completed_process
+ except subprocess.CalledProcessError:
+ LOGGER.exception(f"Error handling command : {command}")
+ raise
+
+
+class MariaDbTestManager(DbTestManagerBase):
+ """
+ May be used in testing to copy and create a database and schema. This class works specifically with
+ Maria/MySQL databases.
+
+ Example:
+
+ @pytest.fixture(scope='module', autouse=True)
+ def setup_db(self):
+ # Pass in the database name and any optional params
+ with MariaDbTestManager(f'testdb_{self.__class__.__name__.lower()}'):
+ yield
+ """
+
+ # pylint: disable=too-few-public-methods
+
+ def __init__(
+ self,
+ db_name: str,
+ schema_db_name: Optional[str] = None,
+ echo_queries: bool = False,
+ keep_db: bool = False,
+ pool_size=3,
+ charset="utf8",
+ ): # pylint: disable=too-many-arguments
+ """
+ :param db_name: the name you want for your test database
+ :param schema_db_name: the name of the DB to duplicate schema from (using mariadb-dump)
+ :param echo_queries: True if you want to see queries
+ :param keep_db: This prevents teardown from removing the created DB after running tests
+ which can be helpful in debugging
+ :param charset: This allows you to override the default charset if you need something besides utf8
+ """
+ super().__init__(
+ os.getenv("MARIA_HOST", "localhost"),
+ os.getenv("MARIA_USERNAME", "root"),
+ os.getenv("MARIA_PASSWORD", "password"),
+ db_name,
+ schema_db_name,
+ port=3306,
+ echo_queries=echo_queries,
+ pool_size=pool_size,
+ docker_container=os.getenv("MARIA_CONTAINER_NAME", "mariadb"),
+ keep_db=keep_db,
+ charset=charset,
+ )
+
+ def _create_test_db(self) -> None:
+ self._run(
+ f'mariadb -p{self.password} -h{self.host} -N -e "DROP DATABASE IF EXISTS {self.db_name}"'
+ )
+ self._run(
+ f'mariadb -p{self.password} -h{self.host} -s -N -e "CREATE DATABASE IF NOT EXISTS {self.db_name}"'
+ )
+ if self.schema_db_name:
+ self._run(
+ f"mariadb-dump --no-data --routines -p{self.password} {self.schema_db_name} -h{self.host} "
+ f"| mariadb -p{self.password} {self.db_name} -h{self.host}"
+ )
+
+ def _tear_down_test_db(self) -> None:
+ self._run(
+ f'echo "DROP DATABASE IF EXISTS {self.db_name} " | mariadb -p{self.password} -h{self.host}'
+ )
+
+ @sqlquery(mapper=CountMapper())
+ def _get_tables_count(self, db_name: str) -> int:
+ # pylint: disable=unused-argument
+ return QueryData(
+ """
+ SELECT count(1)
+ FROM information_schema.TABLES
+ WHERE TABLE_SCHEMA=:db_name
+ """,
+ query_params={"db_name": db_name},
+ )
|