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
|
import collections
from contextlib import contextmanager
import csv
import operator
from sqlalchemy import CHAR
from sqlalchemy import column
from sqlalchemy import exc
from sqlalchemy import exc as sa_exc
from sqlalchemy import ForeignKey
from sqlalchemy import func
from sqlalchemy import INT
from sqlalchemy import Integer
from sqlalchemy import literal
from sqlalchemy import literal_column
from sqlalchemy import MetaData
from sqlalchemy import select
from sqlalchemy import sql
from sqlalchemy import String
from sqlalchemy import table
from sqlalchemy import testing
from sqlalchemy import text
from sqlalchemy import true
from sqlalchemy import tuple_
from sqlalchemy import type_coerce
from sqlalchemy import TypeDecorator
from sqlalchemy import util
from sqlalchemy import VARCHAR
from sqlalchemy.engine import cursor as _cursor
from sqlalchemy.engine import default
from sqlalchemy.engine import Row
from sqlalchemy.engine.result import SimpleResultMetaData
from sqlalchemy.engine.row import KEY_INTEGER_ONLY
from sqlalchemy.engine.row import KEY_OBJECTS_BUT_WARN
from sqlalchemy.engine.row import LegacyRow
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql import ColumnElement
from sqlalchemy.sql import expression
from sqlalchemy.sql import LABEL_STYLE_TABLENAME_PLUS_COL
from sqlalchemy.sql.selectable import LABEL_STYLE_NONE
from sqlalchemy.sql.selectable import TextualSelect
from sqlalchemy.sql.sqltypes import NULLTYPE
from sqlalchemy.sql.util import ClauseAdapter
from sqlalchemy.testing import assert_raises
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import assertions
from sqlalchemy.testing import engines
from sqlalchemy.testing import eq_
from sqlalchemy.testing import expect_raises_message
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import in_
from sqlalchemy.testing import is_
from sqlalchemy.testing import is_false
from sqlalchemy.testing import is_true
from sqlalchemy.testing import le_
from sqlalchemy.testing import mock
from sqlalchemy.testing import ne_
from sqlalchemy.testing import not_in
from sqlalchemy.testing.mock import Mock
from sqlalchemy.testing.mock import patch
from sqlalchemy.testing.schema import Column
from sqlalchemy.testing.schema import Table
from sqlalchemy.util import collections_abc
class CursorResultTest(fixtures.TablesTest):
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"users",
metadata,
Column(
"user_id", INT, primary_key=True, test_needs_autoincrement=True
),
Column("user_name", VARCHAR(20)),
test_needs_acid=True,
)
Table(
"addresses",
metadata,
Column(
"address_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("user_id", Integer, ForeignKey("users.user_id")),
Column("address", String(30)),
test_needs_acid=True,
)
Table(
"users2",
metadata,
Column("user_id", INT, primary_key=True),
Column("user_name", VARCHAR(20)),
test_needs_acid=True,
)
Table(
"test",
metadata,
Column("x", Integer, primary_key=True),
Column("y", String(50)),
)
@testing.variation(
"type_", ["text", "driversql", "core", "textstar", "driverstar"]
)
def test_freeze(self, type_, connection):
"""test #8963"""
users = self.tables.users
connection.execute(
users.insert(),
[
dict(user_id=1, user_name="john"),
dict(user_id=2, user_name="jack"),
],
)
if type_.core:
stmt = select(users).order_by(users.c.user_id)
else:
if "star" in type_.name:
stmt = "select * from users order by user_id"
else:
stmt = "select user_id, user_name from users order by user_id"
if "text" in type_.name:
stmt = text(stmt)
if "driver" in type_.name:
result = connection.exec_driver_sql(stmt)
else:
result = connection.execute(stmt)
frozen = result.freeze()
unfrozen = frozen()
eq_(unfrozen.keys(), ["user_id", "user_name"])
eq_(unfrozen.all(), [(1, "john"), (2, "jack")])
unfrozen = frozen()
eq_(
unfrozen.mappings().all(),
[
{"user_id": 1, "user_name": "john"},
{"user_id": 2, "user_name": "jack"},
],
)
def test_row_iteration(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
{"user_id": 7, "user_name": "jack"},
{"user_id": 8, "user_name": "ed"},
{"user_id": 9, "user_name": "fred"},
],
)
r = connection.execute(users.select())
rows = []
for row in r:
rows.append(row)
eq_(len(rows), 3)
def test_row_next(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
{"user_id": 7, "user_name": "jack"},
{"user_id": 8, "user_name": "ed"},
{"user_id": 9, "user_name": "fred"},
],
)
r = connection.execute(users.select())
rows = []
while True:
row = next(r, "foo")
if row == "foo":
break
rows.append(row)
eq_(len(rows), 3)
@testing.requires.subqueries
def test_anonymous_rows(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
{"user_id": 7, "user_name": "jack"},
{"user_id": 8, "user_name": "ed"},
{"user_id": 9, "user_name": "fred"},
],
)
sel = (
select(users.c.user_id)
.where(users.c.user_name == "jack")
.scalar_subquery()
)
for row in connection.execute(select(sel + 1, sel + 3)):
eq_(row._mapping["anon_1"], 8)
eq_(row._mapping["anon_2"], 10)
def test_row_comparison(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=7, user_name="jack"))
rp = connection.execute(users.select()).first()
eq_(rp, rp)
is_(not (rp != rp), True)
equal = (7, "jack")
eq_(rp, equal)
eq_(equal, rp)
is_((not (rp != equal)), True)
is_(not (equal != equal), True)
def endless():
while True:
yield 1
ne_(rp, endless())
ne_(endless(), rp)
# test that everything compares the same
# as it would against a tuple
for compare in [False, 8, endless(), "xyz", (7, "jack")]:
for op in [
operator.eq,
operator.ne,
operator.gt,
operator.lt,
operator.ge,
operator.le,
]:
try:
control = op(equal, compare)
except TypeError:
# Py3K raises TypeError for some invalid comparisons
assert_raises(TypeError, op, rp, compare)
else:
eq_(control, op(rp, compare))
try:
control = op(compare, equal)
except TypeError:
# Py3K raises TypeError for some invalid comparisons
assert_raises(TypeError, op, compare, rp)
else:
eq_(control, op(compare, rp))
@testing.provide_metadata
def test_column_label_overlap_fallback(self, connection):
content = Table("content", self.metadata, Column("type", String(30)))
bar = Table("bar", self.metadata, Column("content_type", String(30)))
self.metadata.create_all(connection)
connection.execute(content.insert().values(type="t1"))
row = connection.execute(
content.select().set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
).first()
in_(content.c.type, row._mapping)
not_in(bar.c.content_type, row._mapping)
not_in(bar.c.content_type, row._mapping)
row = connection.execute(
select(func.now().label("content_type"))
).first()
not_in(content.c.type, row._mapping)
not_in(bar.c.content_type, row._mapping)
def test_pickled_rows(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
{"user_id": 7, "user_name": "jack"},
{"user_id": 8, "user_name": "ed"},
{"user_id": 9, "user_name": "fred"},
],
)
for pickle in False, True:
for use_labels in False, True:
result = connection.execute(
users.select()
.order_by(users.c.user_id)
.set_label_style(
LABEL_STYLE_TABLENAME_PLUS_COL
if use_labels
else LABEL_STYLE_NONE
)
).fetchall()
if pickle:
result = util.pickle.loads(util.pickle.dumps(result))
eq_(result, [(7, "jack"), (8, "ed"), (9, "fred")])
if use_labels:
eq_(result[0]._mapping["users_user_id"], 7)
eq_(
list(result[0]._fields),
["users_user_id", "users_user_name"],
)
else:
eq_(result[0]._mapping["user_id"], 7)
eq_(list(result[0]._fields), ["user_id", "user_name"])
eq_(result[0][0], 7)
assert_raises(
exc.NoSuchColumnError, lambda: result[0]["fake key"]
)
assert_raises(
exc.NoSuchColumnError,
lambda: result[0]._mapping["fake key"],
)
def test_column_error_printing(self, connection):
result = connection.execute(select(1))
row = result.first()
class unprintable(object):
def __str__(self):
raise ValueError("nope")
msg = r"Could not locate column in row for column '%s'"
for accessor, repl in [
("x", "x"),
(Column("q", Integer), "q"),
(Column("q", Integer) + 12, r"q \+ :q_1"),
(unprintable(), "unprintable element.*"),
]:
assert_raises_message(
exc.NoSuchColumnError, msg % repl, result._getter, accessor
)
is_(result._getter(accessor, False), None)
assert_raises_message(
exc.NoSuchColumnError,
msg % repl,
lambda: row._mapping[accessor],
)
def test_fetchmany(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[{"user_id": i, "user_name": "n%d" % i} for i in range(7, 15)],
)
r = connection.execute(users.select())
rows = []
for row in r.fetchmany(size=2):
rows.append(row)
eq_(len(rows), 2)
def test_fetchmany_arraysize_default(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[{"user_id": i, "user_name": "n%d" % i} for i in range(1, 150)],
)
r = connection.execute(users.select())
arraysize = r.cursor.arraysize
rows = list(r.fetchmany())
eq_(len(rows), min(arraysize, 150))
def test_fetchmany_arraysize_set(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[{"user_id": i, "user_name": "n%d" % i} for i in range(7, 15)],
)
r = connection.execute(users.select())
r.cursor.arraysize = 4
rows = list(r.fetchmany())
eq_(len(rows), 4)
def test_column_slices(self, connection):
users = self.tables.users
addresses = self.tables.addresses
connection.execute(users.insert(), dict(user_id=1, user_name="john"))
connection.execute(users.insert(), dict(user_id=2, user_name="jack"))
connection.execute(
addresses.insert(),
dict(address_id=1, user_id=2, address="foo@bar.com"),
)
r = connection.execute(text("select * from addresses")).first()
eq_(r[0:1], (1,))
eq_(r[1:], (2, "foo@bar.com"))
eq_(r[:-1], (1, 2))
def test_mappings(self, connection):
users = self.tables.users
addresses = self.tables.addresses
connection.execute(users.insert(), dict(user_id=1, user_name="john"))
connection.execute(users.insert(), dict(user_id=2, user_name="jack"))
connection.execute(
addresses.insert(),
dict(address_id=1, user_id=2, address="foo@bar.com"),
)
r = connection.execute(text("select * from addresses"))
eq_(
r.mappings().all(),
[{"address_id": 1, "user_id": 2, "address": "foo@bar.com"}],
)
def test_column_accessor_basic_compiled_mapping(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
dict(user_id=1, user_name="john"),
dict(user_id=2, user_name="jack"),
],
)
r = connection.execute(
users.select().where(users.c.user_id == 2)
).first()
eq_(r.user_id, 2)
eq_(r._mapping["user_id"], 2)
eq_(r._mapping[users.c.user_id], 2)
eq_(r.user_name, "jack")
eq_(r._mapping["user_name"], "jack")
eq_(r._mapping[users.c.user_name], "jack")
def test_column_accessor_basic_compiled_traditional(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
dict(user_id=1, user_name="john"),
dict(user_id=2, user_name="jack"),
],
)
r = connection.execute(
users.select().where(users.c.user_id == 2)
).first()
eq_(r.user_id, 2)
eq_(r._mapping["user_id"], 2)
eq_(r._mapping[users.c.user_id], 2)
eq_(r.user_name, "jack")
eq_(r._mapping["user_name"], "jack")
eq_(r._mapping[users.c.user_name], "jack")
@testing.combinations(
(select(literal_column("1").label("col1")), ("col1",)),
(
select(
literal_column("1").label("col1"),
literal_column("2").label("col2"),
),
("col1", "col2"),
),
argnames="sql,cols",
)
def test_compiled_star_doesnt_interfere_w_description(
self, connection, sql, cols
):
"""test #6665"""
row = connection.execute(
select("*").select_from(sql.subquery())
).first()
eq_(row._fields, cols)
eq_(row._mapping["col1"], 1)
def test_row_getitem_string(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
dict(user_id=1, user_name="john"),
dict(user_id=2, user_name="jack"),
],
)
r = connection.execute(
text("select * from users where user_id=2")
).first()
eq_(r._mapping["user_name"], "jack")
def test_column_accessor_basic_text(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
dict(user_id=1, user_name="john"),
dict(user_id=2, user_name="jack"),
],
)
r = connection.execute(
text("select * from users where user_id=2")
).first()
eq_(r.user_id, 2)
eq_(r.user_name, "jack")
eq_(r._mapping["user_id"], 2)
eq_(r.user_name, "jack")
eq_(r._mapping["user_name"], "jack")
def test_column_accessor_text_colexplicit(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
dict(user_id=1, user_name="john"),
dict(user_id=2, user_name="jack"),
],
)
r = connection.execute(
text("select * from users where user_id=2").columns(
users.c.user_id, users.c.user_name
)
).first()
eq_(r.user_id, 2)
eq_(r._mapping["user_id"], 2)
eq_(r._mapping[users.c.user_id], 2)
eq_(r.user_name, "jack")
eq_(r._mapping["user_name"], "jack")
eq_(r._mapping[users.c.user_name], "jack")
def test_column_accessor_textual_select(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
dict(user_id=1, user_name="john"),
dict(user_id=2, user_name="jack"),
],
)
# this will create column() objects inside
# the select(), these need to match on name anyway
r = connection.execute(
select(column("user_id"), column("user_name"))
.select_from(table("users"))
.where(text("user_id=2"))
).first()
# keyed access works in many ways
eq_(r.user_id, 2)
eq_(r.user_name, "jack")
eq_(r._mapping["user_id"], 2)
eq_(r.user_name, "jack")
eq_(r._mapping["user_name"], "jack")
def test_column_accessor_dotted_union(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="john"))
# test a little sqlite < 3.10.0 weirdness - with the UNION,
# cols come back as "users.user_id" in cursor.description
r = connection.execute(
text(
"select users.user_id, users.user_name "
"from users "
"UNION select users.user_id, "
"users.user_name from users"
)
).first()
eq_(r._mapping["user_id"], 1)
eq_(r._mapping["user_name"], "john")
eq_(list(r._fields), ["user_id", "user_name"])
def test_column_accessor_sqlite_raw(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="john"))
r = connection.execute(
text(
"select users.user_id, users.user_name "
"from users "
"UNION select users.user_id, "
"users.user_name from users",
).execution_options(sqlite_raw_colnames=True)
).first()
if testing.against("sqlite < 3.10.0"):
not_in("user_id", r)
not_in("user_name", r)
eq_(r["users.user_id"], 1)
eq_(r["users.user_name"], "john")
eq_(list(r._fields), ["users.user_id", "users.user_name"])
else:
not_in("users.user_id", r._mapping)
not_in("users.user_name", r._mapping)
eq_(r._mapping["user_id"], 1)
eq_(r._mapping["user_name"], "john")
eq_(list(r._fields), ["user_id", "user_name"])
def test_column_accessor_sqlite_translated(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="john"))
r = connection.execute(
text(
"select users.user_id, users.user_name "
"from users "
"UNION select users.user_id, "
"users.user_name from users",
)
).first()
eq_(r._mapping["user_id"], 1)
eq_(r._mapping["user_name"], "john")
if testing.against("sqlite < 3.10.0"):
eq_(r._mapping["users.user_id"], 1)
eq_(r._mapping["users.user_name"], "john")
else:
not_in("users.user_id", r._mapping)
not_in("users.user_name", r._mapping)
eq_(list(r._fields), ["user_id", "user_name"])
def test_column_accessor_labels_w_dots(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="john"))
# test using literal tablename.colname
r = connection.execute(
text(
'select users.user_id AS "users.user_id", '
'users.user_name AS "users.user_name" '
"from users",
).execution_options(sqlite_raw_colnames=True)
).first()
eq_(r._mapping["users.user_id"], 1)
eq_(r._mapping["users.user_name"], "john")
not_in("user_name", r._mapping)
eq_(list(r._fields), ["users.user_id", "users.user_name"])
def test_column_accessor_unary(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="john"))
# unary expressions
r = connection.execute(
select(users.c.user_name.distinct()).order_by(users.c.user_name)
).first()
eq_(r._mapping[users.c.user_name], "john")
eq_(r.user_name, "john")
@testing.fixture
def _ab_row_fixture(self, connection):
r = connection.execute(
select(literal(1).label("a"), literal(2).label("b"))
).first()
return r
def test_named_tuple_access(self, _ab_row_fixture):
r = _ab_row_fixture
eq_(r.a, 1)
eq_(r.b, 2)
def test_named_tuple_missing_attr(self, _ab_row_fixture):
r = _ab_row_fixture
with expect_raises_message(
AttributeError, "Could not locate column in row for column 'c'"
):
r.c
def test_named_tuple_no_delete_present(self, _ab_row_fixture):
r = _ab_row_fixture
with expect_raises_message(AttributeError, "can't delete attribute"):
del r.a
def test_named_tuple_no_delete_missing(self, _ab_row_fixture):
r = _ab_row_fixture
# including for non-existent attributes
with expect_raises_message(AttributeError, "can't delete attribute"):
del r.c
def test_named_tuple_no_assign_present(self, _ab_row_fixture):
r = _ab_row_fixture
with expect_raises_message(AttributeError, "can't set attribute"):
r.a = 5
with expect_raises_message(AttributeError, "can't set attribute"):
r.a += 5
def test_named_tuple_no_assign_missing(self, _ab_row_fixture):
r = _ab_row_fixture
# including for non-existent attributes
with expect_raises_message(AttributeError, "can't set attribute"):
r.c = 5
def test_named_tuple_no_self_assign_missing(self, _ab_row_fixture):
r = _ab_row_fixture
with expect_raises_message(
AttributeError, "Could not locate column in row for column 'c'"
):
r.c += 5
def test_mapping_tuple_readonly_errors(self, connection):
r = connection.execute(
select(literal(1).label("a"), literal(2).label("b"))
).first()
r = r._mapping
eq_(r["a"], 1)
eq_(r["b"], 2)
with expect_raises_message(
KeyError, "Could not locate column in row for column 'c'"
):
r["c"]
with expect_raises_message(
TypeError, "'RowMapping' object does not support item assignment"
):
r["a"] = 5
with expect_raises_message(
TypeError, "'RowMapping' object does not support item assignment"
):
r["a"] += 5
def test_column_accessor_err(self, connection):
r = connection.execute(select(1)).first()
assert_raises_message(
AttributeError,
"Could not locate column in row for column 'foo'",
getattr,
r,
"foo",
)
assert_raises_message(
KeyError,
"Could not locate column in row for column 'foo'",
lambda: r._mapping["foo"],
)
@testing.skip_if("+aiosqlite", "unknown issue")
@testing.combinations(
(True,),
(False,),
argnames="future",
)
def test_graceful_fetch_on_non_rows(self, future):
"""test that calling fetchone() etc. on a result that doesn't
return rows fails gracefully.
"""
# these proxies don't work with no cursor.description present.
# so they don't apply to this test at the moment.
# result.FullyBufferedCursorResult,
# result.BufferedRowCursorResult,
# result.BufferedColumnCursorResult
users = self.tables.users
conn = testing.db.connect()
if future:
conn = conn.execution_options(future_result=True)
keys_lambda = lambda r: r.keys() # noqa: E731
for meth in [
lambda r: r.fetchone(),
lambda r: r.fetchall(),
lambda r: r.first(),
lambda r: r.scalar(),
lambda r: r.fetchmany(),
lambda r: r._getter("user"),
keys_lambda,
lambda r: r.columns("user"),
lambda r: r.cursor_strategy.fetchone(r, r.cursor),
]:
trans = conn.begin()
result = conn.execute(users.insert(), dict(user_id=1))
if not future and meth is keys_lambda:
with testing.expect_deprecated(
r"Calling the .keys\(\) method on a result set that does "
r"not return rows is deprecated"
):
eq_(meth(result), [])
else:
assert_raises_message(
exc.ResourceClosedError,
"This result object does not return rows. "
"It has been closed automatically.",
meth,
result,
)
trans.rollback()
def test_fetchone_til_end(self, connection):
result = connection.exec_driver_sql("select * from users")
eq_(result.fetchone(), None)
eq_(result.fetchone(), None)
eq_(result.fetchone(), None)
result.close()
assert_raises_message(
exc.ResourceClosedError,
"This result object is closed.",
result.fetchone,
)
def test_row_case_sensitive(self, connection):
row = connection.execute(
select(
literal_column("1").label("case_insensitive"),
literal_column("2").label("CaseSensitive"),
)
).first()
eq_(list(row._fields), ["case_insensitive", "CaseSensitive"])
in_("case_insensitive", row._keymap)
in_("CaseSensitive", row._keymap)
not_in("casesensitive", row._keymap)
eq_(row._mapping["case_insensitive"], 1)
eq_(row._mapping["CaseSensitive"], 2)
assert_raises(KeyError, lambda: row._mapping["Case_insensitive"])
assert_raises(KeyError, lambda: row._mapping["casesensitive"])
def test_row_case_sensitive_unoptimized(self, testing_engine):
with testing_engine().connect() as ins_conn:
row = ins_conn.execute(
select(
literal_column("1").label("case_insensitive"),
literal_column("2").label("CaseSensitive"),
text("3 AS screw_up_the_cols"),
)
).first()
eq_(
list(row._fields),
["case_insensitive", "CaseSensitive", "screw_up_the_cols"],
)
in_("case_insensitive", row._keymap)
in_("CaseSensitive", row._keymap)
not_in("casesensitive", row._keymap)
eq_(row._mapping["case_insensitive"], 1)
eq_(row._mapping["CaseSensitive"], 2)
eq_(row._mapping["screw_up_the_cols"], 3)
assert_raises(KeyError, lambda: row._mapping["Case_insensitive"])
assert_raises(KeyError, lambda: row._mapping["casesensitive"])
assert_raises(KeyError, lambda: row._mapping["screw_UP_the_cols"])
def test_row_as_args(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="john"))
r = connection.execute(
users.select().where(users.c.user_id == 1)
).first()
connection.execute(users.delete())
connection.execute(users.insert(), r._mapping)
eq_(connection.execute(users.select()).fetchall(), [(1, "john")])
@testing.requires.tuple_in
def test_row_tuple_interpretation(self, connection):
"""test #7292"""
users = self.tables.users
connection.execute(
users.insert(),
[
dict(user_id=1, user_name="u1"),
dict(user_id=2, user_name="u2"),
dict(user_id=3, user_name="u3"),
],
)
rows = connection.execute(
select(users.c.user_id, users.c.user_name)
).all()
# was previously needed
# rows = [(x, y) for x, y in rows]
new_stmt = (
select(users)
.where(tuple_(users.c.user_id, users.c.user_name).in_(rows))
.order_by(users.c.user_id)
)
eq_(
connection.execute(new_stmt).all(),
[(1, "u1"), (2, "u2"), (3, "u3")],
)
def test_result_as_args(self, connection):
users = self.tables.users
users2 = self.tables.users2
connection.execute(
users.insert(),
[
dict(user_id=1, user_name="john"),
dict(user_id=2, user_name="ed"),
],
)
r = connection.execute(users.select())
connection.execute(users2.insert(), [row._mapping for row in r])
eq_(
connection.execute(
users2.select().order_by(users2.c.user_id)
).fetchall(),
[(1, "john"), (2, "ed")],
)
connection.execute(users2.delete())
r = connection.execute(users.select())
connection.execute(users2.insert(), [row._mapping for row in r])
eq_(
connection.execute(
users2.select().order_by(users2.c.user_id)
).fetchall(),
[(1, "john"), (2, "ed")],
)
@testing.requires.duplicate_names_in_cursor_description
def test_ambiguous_column(self, connection):
users = self.tables.users
addresses = self.tables.addresses
connection.execute(users.insert(), dict(user_id=1, user_name="john"))
result = connection.execute(
users.outerjoin(addresses)
.select()
.set_label_style(LABEL_STYLE_NONE)
)
r = result.first()
assert_raises_message(
exc.InvalidRequestError,
"Ambiguous column name",
lambda: r._mapping["user_id"],
)
assert_raises_message(
exc.InvalidRequestError,
"Ambiguous column name",
result._getter,
"user_id",
)
# pure positional targeting; users.c.user_id
# and addresses.c.user_id are known!
# works as of 1.1 issue #3501
eq_(r._mapping[users.c.user_id], 1)
eq_(r._mapping[addresses.c.user_id], None)
# try to trick it - fake_table isn't in the result!
# we get the correct error
fake_table = Table("fake", MetaData(), Column("user_id", Integer))
assert_raises_message(
exc.InvalidRequestError,
"Could not locate column in row for column 'fake.user_id'",
lambda: r._mapping[fake_table.c.user_id],
)
r = util.pickle.loads(util.pickle.dumps(r))
assert_raises_message(
exc.InvalidRequestError,
"Ambiguous column name",
lambda: r._mapping["user_id"],
)
@testing.requires.duplicate_names_in_cursor_description
def test_ambiguous_column_by_col(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="john"))
ua = users.alias()
u2 = users.alias()
result = connection.execute(
select(users.c.user_id, ua.c.user_id)
.select_from(users.join(ua, true()))
.set_label_style(LABEL_STYLE_NONE)
)
row = result.first()
# as of 1.1 issue #3501, we use pure positional
# targeting for the column objects here
eq_(row._mapping[users.c.user_id], 1)
eq_(row._mapping[ua.c.user_id], 1)
# this now works as of 1.1 issue #3501;
# previously this was stuck on "ambiguous column name"
assert_raises_message(
exc.InvalidRequestError,
"Could not locate column in row",
lambda: row._mapping[u2.c.user_id],
)
@testing.requires.duplicate_names_in_cursor_description
def test_ambiguous_column_contains(self, connection):
users = self.tables.users
addresses = self.tables.addresses
# ticket 2702. in 0.7 we'd get True, False.
# in 0.8, both columns are present so it's True;
# but when they're fetched you'll get the ambiguous error.
connection.execute(users.insert(), dict(user_id=1, user_name="john"))
result = connection.execute(
select(users.c.user_id, addresses.c.user_id).select_from(
users.outerjoin(addresses)
)
)
row = result.first()
eq_(
set(
[
users.c.user_id in row._mapping,
addresses.c.user_id in row._mapping,
]
),
set([True]),
)
@testing.combinations(
(("name_label", "*"), False),
(("*", "name_label"), False),
(("user_id", "name_label", "user_name"), False),
(("user_id", "name_label", "*", "user_name"), True),
argnames="cols,other_cols_are_ambiguous",
)
@testing.requires.select_star_mixed
def test_label_against_star(
self, connection, cols, other_cols_are_ambiguous
):
"""test #8536"""
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="john"))
stmt = select(
*[
text("*")
if colname == "*"
else users.c.user_name.label("name_label")
if colname == "name_label"
else users.c[colname]
for colname in cols
]
)
row = connection.execute(stmt).first()
eq_(row._mapping["name_label"], "john")
if other_cols_are_ambiguous:
with expect_raises_message(
exc.InvalidRequestError, "Ambiguous column name"
):
row._mapping["user_id"]
with expect_raises_message(
exc.InvalidRequestError, "Ambiguous column name"
):
row._mapping["user_name"]
else:
eq_(row._mapping["user_id"], 1)
eq_(row._mapping["user_name"], "john")
def test_loose_matching_one(self, connection):
users = self.tables.users
addresses = self.tables.addresses
connection.execute(users.insert(), {"user_id": 1, "user_name": "john"})
connection.execute(
addresses.insert(),
{"address_id": 1, "user_id": 1, "address": "email"},
)
# use some column labels in the SELECT
result = connection.execute(
TextualSelect(
text(
"select users.user_name AS users_user_name, "
"users.user_id AS user_id, "
"addresses.address_id AS address_id "
"FROM users JOIN addresses "
"ON users.user_id = addresses.user_id "
"WHERE users.user_id=1 "
),
[users.c.user_id, users.c.user_name, addresses.c.address_id],
positional=False,
)
)
row = result.first()
eq_(row._mapping[users.c.user_id], 1)
eq_(row._mapping[users.c.user_name], "john")
def test_loose_matching_two(self, connection):
users = self.tables.users
addresses = self.tables.addresses
connection.execute(users.insert(), {"user_id": 1, "user_name": "john"})
connection.execute(
addresses.insert(),
{"address_id": 1, "user_id": 1, "address": "email"},
)
# use some column labels in the SELECT
result = connection.execute(
TextualSelect(
text(
"select users.user_name AS users_user_name, "
"users.user_id AS user_id, "
"addresses.user_id "
"FROM users JOIN addresses "
"ON users.user_id = addresses.user_id "
"WHERE users.user_id=1 "
),
[users.c.user_id, users.c.user_name, addresses.c.user_id],
positional=False,
)
)
row = result.first()
assert_raises_message(
exc.InvalidRequestError,
"Ambiguous column name",
lambda: row._mapping[users.c.user_id],
)
assert_raises_message(
exc.InvalidRequestError,
"Ambiguous column name",
lambda: row._mapping[addresses.c.user_id],
)
eq_(row._mapping[users.c.user_name], "john")
def test_ambiguous_column_by_col_plus_label(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="john"))
result = connection.execute(
select(
users.c.user_id,
type_coerce(users.c.user_id, Integer).label("foo"),
)
)
row = result.first()
eq_(row._mapping[users.c.user_id], 1)
eq_(row[1], 1)
def test_fetch_partial_result_map(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=7, user_name="ed"))
t = text("select * from users").columns(user_name=String())
eq_(connection.execute(t).fetchall(), [(7, "ed")])
def test_fetch_unordered_result_map(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=7, user_name="ed"))
class Goofy1(TypeDecorator):
impl = String
cache_ok = True
def process_result_value(self, value, dialect):
return value + "a"
class Goofy2(TypeDecorator):
impl = String
cache_ok = True
def process_result_value(self, value, dialect):
return value + "b"
class Goofy3(TypeDecorator):
impl = String
cache_ok = True
def process_result_value(self, value, dialect):
return value + "c"
t = text(
"select user_name as a, user_name as b, "
"user_name as c from users"
).columns(a=Goofy1(), b=Goofy2(), c=Goofy3())
eq_(connection.execute(t).fetchall(), [("eda", "edb", "edc")])
@testing.requires.subqueries
def test_column_label_targeting(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=7, user_name="ed"))
for s in (
users.select().alias("foo"),
users.select().alias(users.name),
):
row = connection.execute(
s.select().set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
).first()
eq_(row._mapping[s.c.user_id], 7)
eq_(row._mapping[s.c.user_name], "ed")
@testing.requires.python3
def test_ro_mapping_py3k(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="foo"))
result = connection.execute(users.select())
row = result.first()
dict_row = row._asdict()
# dictionaries aren't ordered in Python 3 until 3.7
odict_row = collections.OrderedDict(
[("user_id", 1), ("user_name", "foo")]
)
eq_(dict_row, odict_row)
mapping_row = row._mapping
eq_(list(mapping_row), list(mapping_row.keys()))
eq_(odict_row.keys(), mapping_row.keys())
eq_(odict_row.values(), mapping_row.values())
eq_(odict_row.items(), mapping_row.items())
@testing.requires.python2
def test_ro_mapping_py2k(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="foo"))
result = connection.execute(users.select())
row = result.first()
dict_row = row._asdict()
odict_row = collections.OrderedDict(
[("user_id", 1), ("user_name", "foo")]
)
eq_(dict_row, odict_row)
mapping_row = row._mapping
eq_(list(mapping_row), list(mapping_row.keys()))
eq_(odict_row.keys(), list(mapping_row.keys()))
eq_(odict_row.values(), list(mapping_row.values()))
eq_(odict_row.items(), list(mapping_row.items()))
@testing.combinations(
(lambda result: result),
(lambda result: result.first(),),
(lambda result: result.first()._mapping),
argnames="get_object",
)
@testing.combinations(
(True,),
(False,),
argnames="future",
)
def test_keys(self, connection, get_object, future):
users = self.tables.users
addresses = self.tables.addresses
if future:
connection = connection.execution_options(future_result=True)
connection.execute(users.insert(), dict(user_id=1, user_name="foo"))
result = connection.execute(users.select())
obj = get_object(result)
# Row still has a .keys() method as well as LegacyRow
# as in 1.3.x, the KeyedTuple object also had a keys() method.
# it emits a 2.0 deprecation warning.
if isinstance(obj, Row):
with assertions.expect_deprecated_20("The Row.keys()"):
keys = obj.keys()
else:
keys = obj.keys()
# in 1.4, keys() is now a view that includes support for testing
# of columns and other objects
eq_(len(keys), 2)
eq_(list(keys), ["user_id", "user_name"])
eq_(keys, ["user_id", "user_name"])
ne_(keys, ["user_name", "user_id"])
in_("user_id", keys)
not_in("foo", keys)
in_(users.c.user_id, keys)
not_in(0, keys)
not_in(addresses.c.user_id, keys)
not_in(addresses.c.address, keys)
if isinstance(obj, Row):
eq_(obj._fields, ("user_id", "user_name"))
def test_row_mapping_keys(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="foo"))
result = connection.execute(users.select())
eq_(result.keys(), ["user_id", "user_name"])
row = result.first()
eq_(list(row._mapping.keys()), ["user_id", "user_name"])
eq_(row._fields, ("user_id", "user_name"))
with assertions.expect_deprecated_20("The Row.keys()"):
in_("user_id", row.keys())
with assertions.expect_deprecated_20("The Row.keys()"):
not_in("foo", row.keys())
with assertions.expect_deprecated_20("The Row.keys()"):
in_(users.c.user_id, row.keys())
def test_row_keys_legacy_dont_warn(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="foo"))
result = connection.execute(users.select())
row = result.first()
# DO NOT WARN DEPRECATED IN 1.x, ONLY 2.0 WARNING
with assertions.expect_deprecated_20("The Row.keys()"):
eq_(dict(row), {"user_id": 1, "user_name": "foo"})
with assertions.expect_deprecated_20("The Row.keys()"):
eq_(row.keys(), ["user_id", "user_name"])
def test_row_namedtuple_legacy_ok(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="foo"))
result = connection.execute(users.select())
row = result.first()
eq_(row.user_id, 1)
eq_(row.user_name, "foo")
def test_keys_anon_labels(self, connection):
"""test [ticket:3483]"""
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="foo"))
result = connection.execute(
select(
users.c.user_id,
users.c.user_name.label(None),
func.count(literal_column("1")),
).group_by(users.c.user_id, users.c.user_name)
)
eq_(result.keys(), ["user_id", "user_name_1", "count_1"])
row = result.first()
eq_(row._fields, ("user_id", "user_name_1", "count_1"))
eq_(list(row._mapping.keys()), ["user_id", "user_name_1", "count_1"])
def test_items(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="foo"))
r = connection.execute(users.select()).first()
eq_(
[(x[0].lower(), x[1]) for x in list(r._mapping.items())],
[("user_id", 1), ("user_name", "foo")],
)
def test_len(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="foo"))
r = connection.execute(users.select()).first()
eq_(len(r), 2)
r = connection.exec_driver_sql(
"select user_name, user_id from users"
).first()
eq_(len(r), 2)
r = connection.exec_driver_sql("select user_name from users").first()
eq_(len(r), 1)
def test_sorting_in_python(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
dict(user_id=1, user_name="foo"),
dict(user_id=2, user_name="bar"),
dict(user_id=3, user_name="def"),
],
)
rows = connection.execute(
users.select().order_by(users.c.user_name)
).fetchall()
eq_(rows, [(2, "bar"), (3, "def"), (1, "foo")])
eq_(sorted(rows), [(1, "foo"), (2, "bar"), (3, "def")])
def test_column_order_with_simple_query(self, connection):
# should return values in column definition order
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="foo"))
r = connection.execute(
users.select().where(users.c.user_id == 1)
).first()
eq_(r[0], 1)
eq_(r[1], "foo")
eq_([x.lower() for x in r._fields], ["user_id", "user_name"])
eq_(list(r._mapping.values()), [1, "foo"])
def test_column_order_with_text_query(self, connection):
# should return values in query order
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="foo"))
r = connection.exec_driver_sql(
"select user_name, user_id from users"
).first()
eq_(r[0], "foo")
eq_(r[1], 1)
eq_([x.lower() for x in r._fields], ["user_name", "user_id"])
eq_(list(r._mapping.values()), ["foo", 1])
@testing.crashes("oracle", "FIXME: unknown, verify not fails_on()")
@testing.crashes("firebird", "An identifier must begin with a letter")
@testing.provide_metadata
def test_column_accessor_shadow(self, connection):
shadowed = Table(
"test_shadowed",
self.metadata,
Column("shadow_id", INT, primary_key=True),
Column("shadow_name", VARCHAR(20)),
Column("parent", VARCHAR(20)),
Column("row", VARCHAR(40)),
Column("_parent", VARCHAR(20)),
Column("_row", VARCHAR(20)),
)
self.metadata.create_all(connection)
connection.execute(
shadowed.insert(),
dict(
shadow_id=1,
shadow_name="The Shadow",
parent="The Light",
row="Without light there is no shadow",
_parent="Hidden parent",
_row="Hidden row",
),
)
r = connection.execute(
shadowed.select().where(shadowed.c.shadow_id == 1)
).first()
eq_(r.shadow_id, 1)
eq_(r._mapping["shadow_id"], 1)
eq_(r._mapping[shadowed.c.shadow_id], 1)
eq_(r.shadow_name, "The Shadow")
eq_(r._mapping["shadow_name"], "The Shadow")
eq_(r._mapping[shadowed.c.shadow_name], "The Shadow")
eq_(r.parent, "The Light")
eq_(r._mapping["parent"], "The Light")
eq_(r._mapping[shadowed.c.parent], "The Light")
eq_(r.row, "Without light there is no shadow")
eq_(r._mapping["row"], "Without light there is no shadow")
eq_(r._mapping[shadowed.c.row], "Without light there is no shadow")
eq_(r._mapping["_parent"], "Hidden parent")
eq_(r._mapping["_row"], "Hidden row")
def test_nontuple_row(self):
"""ensure the C version of BaseRow handles
duck-type-dependent rows.
As of 1.4 they are converted internally to tuples in any case.
"""
class MyList(object):
def __init__(self, data):
self.internal_list = data
def __len__(self):
return len(self.internal_list)
def __getitem__(self, i):
return list.__getitem__(self.internal_list, i)
proxy = Row(
object(),
[None],
{"key": (0, None, "key"), 0: (0, None, "key")},
Row._default_key_style,
MyList(["value"]),
)
eq_(list(proxy), ["value"])
eq_(proxy[0], "value")
eq_(proxy._mapping["key"], "value")
def test_no_rowcount_on_selects_inserts(self, metadata, testing_engine):
"""assert that rowcount is only called on deletes and updates.
This because cursor.rowcount may can be expensive on some dialects
such as Firebird, however many dialects require it be called
before the cursor is closed.
"""
engine = testing_engine()
t = Table("t1", metadata, Column("data", String(10)))
metadata.create_all(engine)
with patch.object(
engine.dialect.execution_ctx_cls, "rowcount"
) as mock_rowcount:
with engine.begin() as conn:
mock_rowcount.__get__ = Mock()
conn.execute(
t.insert(),
[{"data": "d1"}, {"data": "d2"}, {"data": "d3"}],
)
eq_(len(mock_rowcount.__get__.mock_calls), 0)
eq_(
conn.execute(t.select()).fetchall(),
[("d1",), ("d2",), ("d3",)],
)
eq_(len(mock_rowcount.__get__.mock_calls), 0)
conn.execute(t.update(), {"data": "d4"})
eq_(len(mock_rowcount.__get__.mock_calls), 1)
conn.execute(t.delete())
eq_(len(mock_rowcount.__get__.mock_calls), 2)
def test_row_is_sequence(self):
row = Row(
object(),
[None],
{"key": (None, 0), 0: (None, 0)},
Row._default_key_style,
["value"],
)
is_true(isinstance(row, collections_abc.Sequence))
@testing.combinations((Row,), (LegacyRow,))
def test_row_special_names(self, row_cls):
metadata = SimpleResultMetaData(["key", "count", "index", "foo"])
row = row_cls(
metadata,
[None, None, None, None],
metadata._keymap,
row_cls._default_key_style,
["kv", "cv", "iv", "f"],
)
is_true(isinstance(row, collections_abc.Sequence))
eq_(row.key, "kv")
eq_(row.count, "cv")
eq_(row.index, "iv")
with assertions.expect_deprecated_20(
"Retrieving row members using strings or other non-integers "
"is deprecated; use row._mapping for a dictionary interface "
"to the row"
):
eq_(row["foo"], "f")
eq_(row["count"], "cv")
eq_(row["index"], "iv")
eq_(row._mapping["count"], "cv")
eq_(row._mapping["index"], "iv")
metadata = SimpleResultMetaData(["key", "q", "p"])
row = row_cls(
metadata,
[None, None, None],
metadata._keymap,
Row._default_key_style,
["kv", "cv", "iv"],
)
is_true(isinstance(row, collections_abc.Sequence))
eq_(row.key, "kv")
eq_(row.q, "cv")
eq_(row.p, "iv")
eq_(row.index("cv"), 1)
eq_(row.count("cv"), 1)
eq_(row.count("x"), 0)
@testing.combinations((Row,), (LegacyRow,))
def test_row_dict_behaviors_warn_mode(self, row_cls):
metadata = SimpleResultMetaData(
[
"a",
"b",
"count",
]
)
row = row_cls(
metadata,
[None, None, None],
metadata._keymap,
KEY_OBJECTS_BUT_WARN,
["av", "bv", "cv"],
)
# as of #6218, dict(row) and row["x"] work for
# both LegacyRow and Row, with 2.0 deprecation warnings
# for both
with assertions.expect_deprecated_20(
"Retrieving row members using strings or other non-integers "
"is deprecated; use row._mapping for a dictionary interface "
"to the row"
):
eq_(dict(row), {"a": "av", "b": "bv", "count": "cv"})
with assertions.expect_deprecated_20(
"Retrieving row members using strings or other non-integers "
"is deprecated; use row._mapping for a dictionary interface "
"to the row"
):
eq_(row["a"], "av")
eq_(row["count"], "cv")
# keys is keys
with assertions.expect_deprecated_20("The Row.keys()"):
eq_(list(row.keys()), ["a", "b", "count"])
def test_new_row_no_dict_behaviors(self):
"""This mode is not used currently but will be once we are in 2.0."""
metadata = SimpleResultMetaData(
[
"a",
"b",
"count",
]
)
row = Row(
metadata,
[None, None, None],
metadata._keymap,
KEY_INTEGER_ONLY,
["av", "bv", "cv"],
)
with assertions.expect_raises_message(
TypeError,
"TypeError: tuple indices must be integers or slices, not str",
):
with assertions.expect_deprecated_20("The Row.keys()"):
eq_(dict(row), {"a": "av", "b": "bv", "count": "cv"})
with assertions.expect_raises_message(
TypeError,
"TypeError: tuple indices must be integers or slices, not str",
):
eq_(row["a"], "av")
with assertions.expect_raises_message(
TypeError,
"TypeError: tuple indices must be integers or slices, not str",
):
eq_(row["count"], "cv")
# keys is keys
with assertions.expect_deprecated_20("The Row.keys()"):
eq_(list(row.keys()), ["a", "b", "count"])
def test_row_is_hashable(self):
row = Row(
object(),
[None, None, None],
{"key": (None, 0), 0: (None, 0)},
Row._default_key_style,
(1, "value", "foo"),
)
eq_(hash(row), hash((1, "value", "foo")))
@testing.provide_metadata
def test_row_getitem_indexes_compiled(self, connection):
values = Table(
"rp",
self.metadata,
Column("key", String(10), primary_key=True),
Column("value", String(10)),
)
values.create(connection)
connection.execute(values.insert(), dict(key="One", value="Uno"))
row = connection.execute(values.select()).first()
eq_(row._mapping["key"], "One")
eq_(row._mapping["value"], "Uno")
eq_(row[0], "One")
eq_(row[1], "Uno")
eq_(row[-2], "One")
eq_(row[-1], "Uno")
eq_(row[1:0:-1], ("Uno",))
@testing.only_on("sqlite")
def test_row_getitem_indexes_raw(self, connection):
row = connection.exec_driver_sql(
"select 'One' as key, 'Uno' as value"
).first()
eq_(row._mapping["key"], "One")
eq_(row._mapping["value"], "Uno")
eq_(row[0], "One")
eq_(row[1], "Uno")
eq_(row[-2], "One")
eq_(row[-1], "Uno")
eq_(row[1:0:-1], ("Uno",))
@testing.requires.cextensions
@testing.provide_metadata
def test_row_c_sequence_check(self, connection):
users = self.tables.users2
connection.execute(users.insert(), dict(user_id=1, user_name="Test"))
row = connection.execute(
users.select().where(users.c.user_id == 1)
).fetchone()
s = util.StringIO()
writer = csv.writer(s)
# csv performs PySequenceCheck call
writer.writerow(row)
assert s.getvalue().strip() == "1,Test"
@testing.requires.selectone
def test_empty_accessors(self, connection):
statements = [
(
"select 1",
[
lambda r: r.last_inserted_params(),
lambda r: r.last_updated_params(),
lambda r: r.prefetch_cols(),
lambda r: r.postfetch_cols(),
lambda r: r.inserted_primary_key,
],
"Statement is not a compiled expression construct.",
),
(
select(1),
[
lambda r: r.last_inserted_params(),
lambda r: r.inserted_primary_key,
],
r"Statement is not an insert\(\) expression construct.",
),
(
select(1),
[lambda r: r.last_updated_params()],
r"Statement is not an update\(\) expression construct.",
),
(
select(1),
[lambda r: r.prefetch_cols(), lambda r: r.postfetch_cols()],
r"Statement is not an insert\(\) "
r"or update\(\) expression construct.",
),
]
for stmt, meths, msg in statements:
if isinstance(stmt, str):
r = connection.exec_driver_sql(stmt)
else:
r = connection.execute(stmt)
try:
for meth in meths:
assert_raises_message(
sa_exc.InvalidRequestError, msg, meth, r
)
finally:
r.close()
@testing.requires.dbapi_lastrowid
def test_lastrowid(self, connection):
users = self.tables.users
r = connection.execute(
users.insert(), dict(user_id=1, user_name="Test")
)
eq_(r.lastrowid, r.context.get_lastrowid())
def test_raise_errors(self, connection):
users = self.tables.users
class Wrapper:
def __init__(self, context):
self.context = context
def __getattr__(self, name):
if name in ("rowcount", "get_lastrowid"):
raise Exception("canary")
return getattr(self.context, name)
r = connection.execute(
users.insert(), dict(user_id=1, user_name="Test")
)
r.context = Wrapper(r.context)
with expect_raises_message(Exception, "canary"):
r.rowcount
with expect_raises_message(Exception, "canary"):
r.lastrowid
@testing.combinations("plain", "mapping", "scalar", argnames="result_type")
@testing.combinations(
"stream_results", "yield_per", "yield_per_meth", argnames="optname"
)
@testing.combinations(10, 50, argnames="value")
@testing.combinations("meth", "stmt", argnames="send_opts_how")
def test_stream_options(
self,
connection,
optname,
value,
send_opts_how,
result_type,
close_result_when_finished,
):
table = self.tables.test
connection.execute(
table.insert(),
[{"x": i, "y": "t_%d" % i} for i in range(15, 3000)],
)
if optname == "stream_results":
opts = {"stream_results": True, "max_row_buffer": value}
elif optname == "yield_per":
opts = {"yield_per": value}
elif optname == "yield_per_meth":
opts = {"stream_results": True}
else:
assert False
if send_opts_how == "meth":
result = connection.execution_options(**opts).execute(
table.select()
)
elif send_opts_how == "stmt":
result = connection.execute(
table.select().execution_options(**opts)
)
else:
assert False
if result_type == "mapping":
result = result.mappings()
real_result = result._real_result
elif result_type == "scalar":
result = result.scalars()
real_result = result._real_result
else:
real_result = result
if optname == "yield_per_meth":
result = result.yield_per(value)
if result_type == "mapping" or result_type == "scalar":
real_result = result._real_result
else:
real_result = result
close_result_when_finished(result, consume=True)
if optname == "yield_per" and value is not None:
expected_opt = {
"stream_results": True,
"max_row_buffer": value,
"yield_per": value,
}
elif optname == "stream_results" and value is not None:
expected_opt = {
"stream_results": True,
"max_row_buffer": value,
}
else:
expected_opt = None
if expected_opt is not None:
eq_(real_result.context.execution_options, expected_opt)
if value is None:
assert isinstance(
real_result.cursor_strategy, _cursor.CursorFetchStrategy
)
return
assert isinstance(
real_result.cursor_strategy, _cursor.BufferedRowCursorFetchStrategy
)
eq_(real_result.cursor_strategy._max_row_buffer, value)
if optname == "yield_per" or optname == "yield_per_meth":
eq_(real_result.cursor_strategy._bufsize, value)
else:
eq_(real_result.cursor_strategy._bufsize, min(value, 5))
eq_(len(real_result.cursor_strategy._rowbuffer), 1)
next(result)
next(result)
if optname == "yield_per" or optname == "yield_per_meth":
eq_(len(real_result.cursor_strategy._rowbuffer), value - 1)
else:
# based on default growth of 5
eq_(len(real_result.cursor_strategy._rowbuffer), 4)
for i, row in enumerate(result):
if i == 186:
break
if optname == "yield_per" or optname == "yield_per_meth":
eq_(
len(real_result.cursor_strategy._rowbuffer),
value - (188 % value),
)
else:
# based on default growth of 5
eq_(
len(real_result.cursor_strategy._rowbuffer),
7 if value == 10 else 42,
)
if optname == "yield_per" or optname == "yield_per_meth":
# ensure partition is set up to same size
partition = next(result.partitions())
eq_(len(partition), value)
@testing.fixture
def autoclose_row_fixture(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
{"user_id": 1, "name": "u1"},
{"user_id": 2, "name": "u2"},
{"user_id": 3, "name": "u3"},
{"user_id": 4, "name": "u4"},
{"user_id": 5, "name": "u5"},
],
)
@testing.fixture(params=["plain", "scalars", "mapping"])
def result_fixture(self, request, connection):
users = self.tables.users
result_type = request.param
if result_type == "plain":
result = connection.execute(select(users))
elif result_type == "scalars":
result = connection.scalars(select(users))
elif result_type == "mapping":
result = connection.execute(select(users)).mappings()
else:
assert False
return result
def test_results_can_close(self, autoclose_row_fixture, result_fixture):
"""test #8710"""
r1 = result_fixture
is_false(r1.closed)
is_false(r1._soft_closed)
r1._soft_close()
is_false(r1.closed)
is_true(r1._soft_closed)
r1.close()
is_true(r1.closed)
is_true(r1._soft_closed)
def test_autoclose_rows_exhausted_plain(
self, connection, autoclose_row_fixture, result_fixture
):
result = result_fixture
assert not result._soft_closed
assert not result.closed
read_iterator = list(result)
eq_(len(read_iterator), 5)
assert result._soft_closed
assert not result.closed
result.close()
assert result.closed
class KeyTargetingTest(fixtures.TablesTest):
run_inserts = "once"
run_deletes = None
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"keyed1",
metadata,
Column("a", CHAR(2), key="b"),
Column("c", CHAR(2), key="q"),
)
Table("keyed2", metadata, Column("a", CHAR(2)), Column("b", CHAR(2)))
Table("keyed3", metadata, Column("a", CHAR(2)), Column("d", CHAR(2)))
Table("keyed4", metadata, Column("b", CHAR(2)), Column("q", CHAR(2)))
Table("content", metadata, Column("t", String(30), key="type"))
Table("bar", metadata, Column("ctype", String(30), key="content_type"))
if testing.requires.schemas.enabled:
Table(
"wschema",
metadata,
Column("a", CHAR(2), key="b"),
Column("c", CHAR(2), key="q"),
schema=testing.config.test_schema,
)
Table(
"users",
metadata,
Column("id", Integer, primary_key=True),
Column("team_id", metadata, ForeignKey("teams.id")),
)
Table(
"teams",
metadata,
Column("id", Integer, primary_key=True),
)
@classmethod
def insert_data(cls, connection):
conn = connection
conn.execute(cls.tables.keyed1.insert(), dict(b="a1", q="c1"))
conn.execute(cls.tables.keyed2.insert(), dict(a="a2", b="b2"))
conn.execute(cls.tables.keyed3.insert(), dict(a="a3", d="d3"))
conn.execute(cls.tables.keyed4.insert(), dict(b="b4", q="q4"))
conn.execute(cls.tables.content.insert(), dict(type="t1"))
conn.execute(cls.tables.teams.insert(), dict(id=1))
conn.execute(cls.tables.users.insert(), dict(id=1, team_id=1))
if testing.requires.schemas.enabled:
conn.execute(
cls.tables["%s.wschema" % testing.config.test_schema].insert(),
dict(b="a1", q="c1"),
)
@testing.requires.schemas
def test_keyed_accessor_wschema(self, connection):
keyed1 = self.tables["%s.wschema" % testing.config.test_schema]
row = connection.execute(keyed1.select()).first()
eq_(row.b, "a1")
eq_(row.q, "c1")
eq_(row.a, "a1")
eq_(row.c, "c1")
def test_keyed_accessor_single(self, connection):
keyed1 = self.tables.keyed1
row = connection.execute(keyed1.select()).first()
eq_(row.b, "a1")
eq_(row.q, "c1")
eq_(row.a, "a1")
eq_(row.c, "c1")
def test_keyed_accessor_single_labeled(self, connection):
keyed1 = self.tables.keyed1
row = connection.execute(
keyed1.select().set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
).first()
eq_(row.keyed1_b, "a1")
eq_(row.keyed1_q, "c1")
eq_(row.keyed1_a, "a1")
eq_(row.keyed1_c, "c1")
def _test_keyed_targeting_no_label_at_all(self, expression, conn):
lt = literal_column("2")
stmt = select(literal_column("1"), expression, lt).select_from(
self.tables.keyed1
)
row = conn.execute(stmt).first()
eq_(row._mapping[expression], "a1")
eq_(row._mapping[lt], 2)
# Postgresql for example has the key as "?column?", which dupes
# easily. we get around that because we know that "2" is unique
eq_(row._mapping["2"], 2)
def test_keyed_targeting_no_label_at_all_one(self, connection):
class not_named_max(expression.ColumnElement):
name = "not_named_max"
inherit_cache = True
@compiles(not_named_max)
def visit_max(element, compiler, **kw):
# explicit add
if "add_to_result_map" in kw:
kw["add_to_result_map"](None, None, (element,), NULLTYPE)
return "max(a)"
# assert that there is no "AS max_" or any label of any kind.
eq_(str(select(not_named_max())), "SELECT max(a)")
nnm = not_named_max()
self._test_keyed_targeting_no_label_at_all(nnm, connection)
def test_keyed_targeting_no_label_at_all_two(self, connection):
class not_named_max(expression.ColumnElement):
name = "not_named_max"
inherit_cache = True
@compiles(not_named_max)
def visit_max(element, compiler, **kw):
# we don't add to keymap here; compiler should be doing it
return "max(a)"
# assert that there is no "AS max_" or any label of any kind.
eq_(str(select(not_named_max())), "SELECT max(a)")
nnm = not_named_max()
self._test_keyed_targeting_no_label_at_all(nnm, connection)
def test_keyed_targeting_no_label_at_all_text(self, connection):
t1 = text("max(a)")
t2 = text("min(a)")
stmt = select(t1, t2).select_from(self.tables.keyed1)
row = connection.execute(stmt).first()
eq_(row._mapping[t1], "a1")
eq_(row._mapping[t2], "a1")
@testing.requires.duplicate_names_in_cursor_description
def test_keyed_accessor_composite_conflict_2(self, connection):
keyed1 = self.tables.keyed1
keyed2 = self.tables.keyed2
row = connection.execute(
select(keyed1, keyed2)
.select_from(keyed1.join(keyed2, true()))
.set_label_style(LABEL_STYLE_NONE)
).first()
# column access is unambiguous
eq_(row._mapping[self.tables.keyed2.c.b], "b2")
# row.a is ambiguous
assert_raises_message(
exc.InvalidRequestError, "Ambig", getattr, row, "a"
)
# for "b" we have kind of a choice. the name "b" is not ambiguous in
# cursor.description in this case. It is however ambiguous as far as
# the objects we have queried against, because keyed1.c.a has key="b"
# and keyed1.c.b is "b". historically this was allowed as
# non-ambiguous, however the column it targets changes based on
# whether or not the dupe is present so it's ambiguous
# eq_(row.b, "b2")
assert_raises_message(
exc.InvalidRequestError, "Ambig", getattr, row, "b"
)
# illustrate why row.b above is ambiguous, and not "b2"; because
# if we didn't have keyed2, now it matches row.a. a new column
# shouldn't be able to grab the value from a previous column.
row = connection.execute(select(keyed1)).first()
eq_(row.b, "a1")
def test_keyed_accessor_composite_conflict_2_fix_w_uselabels(
self, connection
):
keyed1 = self.tables.keyed1
keyed2 = self.tables.keyed2
row = connection.execute(
select(keyed1, keyed2)
.select_from(keyed1.join(keyed2, true()))
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
).first()
# column access is unambiguous
eq_(row._mapping[self.tables.keyed2.c.b], "b2")
eq_(row._mapping["keyed2_b"], "b2")
eq_(row._mapping["keyed1_a"], "a1")
def test_keyed_accessor_composite_names_precedent(self, connection):
keyed1 = self.tables.keyed1
keyed4 = self.tables.keyed4
row = connection.execute(
select(keyed1, keyed4).select_from(keyed1.join(keyed4, true()))
).first()
eq_(row.b, "b4")
eq_(row.q, "q4")
eq_(row.a, "a1")
eq_(row.c, "c1")
@testing.requires.duplicate_names_in_cursor_description
def test_keyed_accessor_composite_keys_precedent(self, connection):
keyed1 = self.tables.keyed1
keyed3 = self.tables.keyed3
row = connection.execute(
select(keyed1, keyed3)
.select_from(keyed1.join(keyed3, true()))
.set_label_style(LABEL_STYLE_NONE)
).first()
eq_(row.q, "c1")
# prior to 1.4 #4887, this raised an "ambiguous column name 'a'""
# message, because "b" is linked to "a" which is a dupe. but we know
# where "b" is in the row by position.
eq_(row.b, "a1")
# "a" is of course ambiguous
assert_raises_message(
exc.InvalidRequestError,
"Ambiguous column name 'a'",
getattr,
row,
"a",
)
eq_(row.d, "d3")
def test_keyed_accessor_composite_labeled(self, connection):
keyed1 = self.tables.keyed1
keyed2 = self.tables.keyed2
row = connection.execute(
select(keyed1, keyed2)
.select_from(keyed1.join(keyed2, true()))
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
).first()
eq_(row.keyed1_b, "a1")
eq_(row.keyed1_a, "a1")
eq_(row.keyed1_q, "c1")
eq_(row.keyed1_c, "c1")
eq_(row.keyed2_a, "a2")
eq_(row.keyed2_b, "b2")
assert_raises(KeyError, lambda: row["keyed2_c"])
assert_raises(KeyError, lambda: row["keyed2_q"])
assert_raises(KeyError, lambda: row._mapping["keyed2_c"])
assert_raises(KeyError, lambda: row._mapping["keyed2_q"])
def test_keyed_accessor_column_is_repeated_multiple_times(
self, connection
):
# test new logic added as a result of the combination of #4892 and
# #4887. We allow duplicate columns, but we also have special logic
# to disambiguate for the same column repeated, and as #4887 adds
# stricter ambiguous result column logic, the compiler has to know to
# not add these dupe columns to the result map, else they register as
# ambiguous.
keyed2 = self.tables.keyed2
keyed3 = self.tables.keyed3
stmt = (
select(
keyed2.c.a,
keyed3.c.a,
keyed2.c.a,
keyed2.c.a,
keyed3.c.a,
keyed3.c.a,
keyed3.c.d,
keyed3.c.d,
)
.select_from(keyed2.join(keyed3, true()))
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
)
result = connection.execute(stmt)
# ensure the result map is the same number of cols so we can
# use positional targeting
eq_(
[rec[0] for rec in result.context.compiled._result_columns],
[
"keyed2_a",
"keyed3_a",
"keyed2_a__1",
"keyed2_a__2",
"keyed3_a__1",
"keyed3_a__2",
"keyed3_d",
"keyed3_d__1",
],
)
row = result.first()
# keyed access will ignore the dupe cols
eq_(row._mapping[keyed2.c.a], "a2")
eq_(row._mapping[keyed3.c.a], "a3")
eq_(result._getter(keyed3.c.a)(row), "a3")
eq_(row._mapping[keyed3.c.d], "d3")
# however we can get everything positionally
eq_(row, ("a2", "a3", "a2", "a2", "a3", "a3", "d3", "d3"))
eq_(row[0], "a2")
eq_(row[1], "a3")
eq_(row[2], "a2")
eq_(row[3], "a2")
eq_(row[4], "a3")
eq_(row[5], "a3")
eq_(row[6], "d3")
eq_(row[7], "d3")
def test_columnclause_schema_column_one(self, connection):
# originally addressed by [ticket:2932], however liberalized
# Column-targeting rules are deprecated
a, b = sql.column("a"), sql.column("b")
stmt = select(a, b).select_from(table("keyed2"))
row = connection.execute(stmt).first()
in_(a, row._mapping)
in_(b, row._mapping)
def test_columnclause_schema_column_two(self, connection):
keyed2 = self.tables.keyed2
stmt = select(keyed2.c.a, keyed2.c.b)
row = connection.execute(stmt).first()
in_(keyed2.c.a, row._mapping)
in_(keyed2.c.b, row._mapping)
def test_columnclause_schema_column_three(self, connection):
# this is also addressed by [ticket:2932]
stmt = text("select a, b from keyed2").columns(a=CHAR, b=CHAR)
row = connection.execute(stmt).first()
in_(stmt.selected_columns.a, row._mapping)
in_(stmt.selected_columns.b, row._mapping)
def test_columnclause_schema_column_four(self, connection):
# originally addressed by [ticket:2932], however liberalized
# Column-targeting rules are deprecated
a, b = sql.column("keyed2_a"), sql.column("keyed2_b")
stmt = text("select a AS keyed2_a, b AS keyed2_b from keyed2").columns(
a, b
)
row = connection.execute(stmt).first()
in_(a, row._mapping)
in_(b, row._mapping)
in_(stmt.selected_columns.keyed2_a, row._mapping)
in_(stmt.selected_columns.keyed2_b, row._mapping)
def test_columnclause_schema_column_five(self, connection):
# this is also addressed by [ticket:2932]
stmt = text("select a AS keyed2_a, b AS keyed2_b from keyed2").columns(
keyed2_a=CHAR, keyed2_b=CHAR
)
row = connection.execute(stmt).first()
in_(stmt.selected_columns.keyed2_a, row._mapping)
in_(stmt.selected_columns.keyed2_b, row._mapping)
def _adapt_result_columns_fixture_one(self):
keyed1 = self.tables.keyed1
stmt = (
select(keyed1.c.b, keyed1.c.q.label("foo"))
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.subquery()
)
return select(stmt.c.keyed1_b, stmt.c.foo)
def _adapt_result_columns_fixture_two(self):
return text("select a AS keyed2_a, b AS keyed2_b from keyed2").columns(
column("keyed2_a", CHAR), column("keyed2_b", CHAR)
)
def _adapt_result_columns_fixture_three(self):
keyed1 = self.tables.keyed1
stmt = select(keyed1.c.b, keyed1.c.q.label("foo")).subquery()
return select(stmt.c.b, stmt.c.foo)
def _adapt_result_columns_fixture_four(self):
keyed1 = self.tables.keyed1
stmt1 = select(keyed1).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
a1 = keyed1.alias()
stmt2 = ClauseAdapter(a1).traverse(stmt1)
return stmt2
def _adapt_result_columns_fixture_five(self):
users, teams = self.tables("users", "teams")
return select(users.c.id, teams.c.id).select_from(
users.outerjoin(teams)
)
def _adapt_result_columns_fixture_six(self):
# this has _result_columns structure that is not ordered
# the same as the cursor.description.
return text("select a AS keyed2_a, b AS keyed2_b from keyed2").columns(
keyed2_b=CHAR,
keyed2_a=CHAR,
)
def _adapt_result_columns_fixture_seven(self):
# this has _result_columns structure that is not ordered
# the same as the cursor.description.
return text("select a AS keyed2_a, b AS keyed2_b from keyed2").columns(
keyed2_b=CHAR, bogus_col=CHAR
)
@testing.combinations(
_adapt_result_columns_fixture_one,
_adapt_result_columns_fixture_two,
_adapt_result_columns_fixture_three,
_adapt_result_columns_fixture_four,
_adapt_result_columns_fixture_five,
_adapt_result_columns_fixture_six,
_adapt_result_columns_fixture_seven,
argnames="stmt_fn",
)
def test_adapt_result_columns(self, connection, stmt_fn):
"""test adaptation of a CursorResultMetadata to another one.
This copies the _keymap from one to the other in terms of the
selected columns of a target selectable.
This is used by the statement caching process to re-use the
CursorResultMetadata from the cached statement against the same
statement sent separately.
"""
stmt1 = stmt_fn(self)
stmt2 = stmt_fn(self)
eq_(stmt1._generate_cache_key(), stmt2._generate_cache_key())
column_linkage = dict(
zip(stmt1.selected_columns, stmt2.selected_columns)
)
for i in range(2):
try:
result = connection.execute(stmt1)
mock_context = Mock(
compiled=result.context.compiled, invoked_statement=stmt2
)
existing_metadata = result._metadata
adapted_metadata = existing_metadata._adapt_to_context(
mock_context
)
eq_(existing_metadata.keys, adapted_metadata.keys)
for k in existing_metadata._keymap:
if isinstance(k, ColumnElement) and k in column_linkage:
other_k = column_linkage[k]
else:
other_k = k
is_(
existing_metadata._keymap[k],
adapted_metadata._keymap[other_k],
)
finally:
result.close()
@testing.combinations(
_adapt_result_columns_fixture_one,
_adapt_result_columns_fixture_two,
_adapt_result_columns_fixture_three,
_adapt_result_columns_fixture_four,
_adapt_result_columns_fixture_five,
_adapt_result_columns_fixture_six,
_adapt_result_columns_fixture_seven,
argnames="stmt_fn",
)
def test_adapt_result_columns_from_cache(self, connection, stmt_fn):
stmt1 = stmt_fn(self)
stmt2 = stmt_fn(self)
cache = {}
result = connection._execute_20(
stmt1,
execution_options={"compiled_cache": cache, "future_result": True},
)
result.close()
assert cache
result = connection._execute_20(
stmt2,
execution_options={"compiled_cache": cache, "future_result": True},
)
row = result.first()
for col in stmt2.selected_columns:
if "bogus" in col.name:
assert col not in row._mapping
else:
assert col in row._mapping
class PositionalTextTest(fixtures.TablesTest):
run_inserts = "once"
run_deletes = None
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"text1",
metadata,
Column("a", CHAR(2)),
Column("b", CHAR(2)),
Column("c", CHAR(2)),
Column("d", CHAR(2)),
)
@classmethod
def insert_data(cls, connection):
connection.execute(
cls.tables.text1.insert(),
[dict(a="a1", b="b1", c="c1", d="d1")],
)
def test_via_column(self, connection):
c1, c2, c3, c4 = column("q"), column("p"), column("r"), column("d")
stmt = text("select a, b, c, d from text1").columns(c1, c2, c3, c4)
result = connection.execute(stmt)
row = result.first()
eq_(row._mapping[c2], "b1")
eq_(row._mapping[c4], "d1")
eq_(row[1], "b1")
eq_(row._mapping["b"], "b1")
eq_(list(row._mapping.keys()), ["a", "b", "c", "d"])
eq_(row._fields, ("a", "b", "c", "d"))
eq_(row._mapping["r"], "c1")
eq_(row._mapping["d"], "d1")
def test_fewer_cols_than_sql_positional(self, connection):
c1, c2 = column("q"), column("p")
stmt = text("select a, b, c, d from text1").columns(c1, c2)
# no warning as this can be similar for non-positional
result = connection.execute(stmt)
row = result.first()
eq_(row._mapping[c1], "a1")
eq_(row._mapping["c"], "c1")
def test_fewer_cols_than_sql_non_positional(self, connection):
c1, c2 = column("a"), column("p")
stmt = text("select a, b, c, d from text1").columns(c2, c1, d=CHAR)
# no warning as this can be similar for non-positional
result = connection.execute(stmt)
row = result.first()
# c1 name matches, locates
eq_(row._mapping[c1], "a1")
eq_(row._mapping["c"], "c1")
# c2 name does not match, doesn't locate
assert_raises_message(
exc.NoSuchColumnError,
"in row for column 'p'",
lambda: row._mapping[c2],
)
def test_more_cols_than_sql_positional(self, connection):
c1, c2, c3, c4 = column("q"), column("p"), column("r"), column("d")
stmt = text("select a, b from text1").columns(c1, c2, c3, c4)
with assertions.expect_warnings(
r"Number of columns in textual SQL \(4\) is "
r"smaller than number of columns requested \(2\)"
):
result = connection.execute(stmt)
row = result.first()
eq_(row._mapping[c2], "b1")
assert_raises_message(
exc.NoSuchColumnError,
"in row for column 'r'",
lambda: row._mapping[c3],
)
def test_more_cols_than_sql_nonpositional(self, connection):
c1, c2, c3, c4 = column("b"), column("a"), column("r"), column("d")
stmt = TextualSelect(
text("select a, b from text1"), [c1, c2, c3, c4], positional=False
)
# no warning for non-positional
result = connection.execute(stmt)
row = result.first()
eq_(row._mapping[c1], "b1")
eq_(row._mapping[c2], "a1")
assert_raises_message(
exc.NoSuchColumnError,
"in row for column 'r'",
lambda: row._mapping[c3],
)
def test_more_cols_than_sql_nonpositional_labeled_cols(self, connection):
text1 = self.tables.text1
c1, c2, c3, c4 = text1.c.b, text1.c.a, column("r"), column("d")
# the compiler will enable loose matching for this statement
# so that column._label is taken into account
stmt = TextualSelect(
text("select a, b AS text1_b from text1"),
[c1, c2, c3, c4],
positional=False,
)
# no warning for non-positional
result = connection.execute(stmt)
row = result.first()
eq_(row._mapping[c1], "b1")
eq_(row._mapping[c2], "a1")
assert_raises_message(
exc.NoSuchColumnError,
"in row for column 'r'",
lambda: row._mapping[c3],
)
def test_dupe_col_obj(self, connection):
c1, c2, c3 = column("q"), column("p"), column("r")
stmt = text("select a, b, c, d from text1").columns(c1, c2, c3, c2)
assert_raises_message(
exc.InvalidRequestError,
"Duplicate column expression requested in "
"textual SQL: <.*.ColumnClause.*; p>",
connection.execute,
stmt,
)
def test_anon_aliased_unique(self, connection):
text1 = self.tables.text1
c1 = text1.c.a.label(None)
c2 = text1.alias().c.c
c3 = text1.alias().c.b
c4 = text1.alias().c.d.label(None)
stmt = text("select a, b, c, d from text1").columns(c1, c2, c3, c4)
result = connection.execute(stmt)
row = result.first()
eq_(row._mapping[c1], "a1")
eq_(row._mapping[c2], "b1")
eq_(row._mapping[c3], "c1")
eq_(row._mapping[c4], "d1")
# text1.c.b goes nowhere....because we hit key fallback
# but the text1.c.b doesn't derive from text1.c.c
assert_raises_message(
exc.NoSuchColumnError,
"Could not locate column in row for column 'text1.b'",
lambda: row._mapping[text1.c.b],
)
def test_anon_aliased_overlapping(self, connection):
text1 = self.tables.text1
c1 = text1.c.a.label(None)
c2 = text1.alias().c.a
c3 = text1.alias().c.a.label(None)
c4 = text1.c.a.label(None)
stmt = text("select a, b, c, d from text1").columns(c1, c2, c3, c4)
result = connection.execute(stmt)
row = result.first()
eq_(row._mapping[c1], "a1")
eq_(row._mapping[c2], "b1")
eq_(row._mapping[c3], "c1")
eq_(row._mapping[c4], "d1")
def test_anon_aliased_name_conflict(self, connection):
text1 = self.tables.text1
c1 = text1.c.a.label("a")
c2 = text1.alias().c.a
c3 = text1.alias().c.a.label("a")
c4 = text1.c.a.label("a")
# all cols are named "a". if we are positional, we don't care.
# this is new logic in 1.1
stmt = text("select a, b as a, c as a, d as a from text1").columns(
c1, c2, c3, c4
)
result = connection.execute(stmt)
row = result.first()
eq_(row._mapping[c1], "a1")
eq_(row._mapping[c2], "b1")
eq_(row._mapping[c3], "c1")
eq_(row._mapping[c4], "d1")
# fails, because we hit key fallback and find conflicts
# in columns that are presnet
assert_raises_message(
exc.NoSuchColumnError,
"Could not locate column in row for column 'text1.a'",
lambda: row._mapping[text1.c.a],
)
class AlternateCursorResultTest(fixtures.TablesTest):
__requires__ = ("sqlite",)
@classmethod
def setup_bind(cls):
cls.engine = engine = engines.testing_engine(
"sqlite://", options={"scope": "class"}
)
return engine
@classmethod
def define_tables(cls, metadata):
Table(
"test",
metadata,
Column("x", Integer, primary_key=True),
Column("y", String(50)),
)
@classmethod
def insert_data(cls, connection):
connection.execute(
cls.tables.test.insert(),
[{"x": i, "y": "t_%d" % i} for i in range(1, 12)],
)
@contextmanager
def _proxy_fixture(self, cls):
self.table = self.tables.test
class ExcCtx(default.DefaultExecutionContext):
def post_exec(self):
if cls is _cursor.CursorFetchStrategy:
pass
elif cls is _cursor.BufferedRowCursorFetchStrategy:
self.cursor_fetch_strategy = cls(
self.cursor, self.execution_options
)
elif cls is _cursor.FullyBufferedCursorFetchStrategy:
self.cursor_fetch_strategy = cls(
self.cursor,
self.cursor.description,
self.cursor.fetchall(),
)
else:
assert False
self.patcher = patch.object(
self.engine.dialect, "execution_ctx_cls", ExcCtx
)
with self.patcher:
yield
def _test_proxy(self, cls):
with self._proxy_fixture(cls):
rows = []
with self.engine.connect() as conn:
r = conn.execute(select(self.table))
assert isinstance(r.cursor_strategy, cls)
for i in range(5):
rows.append(r.fetchone())
eq_(rows, [(i, "t_%d" % i) for i in range(1, 6)])
rows = r.fetchmany(3)
eq_(rows, [(i, "t_%d" % i) for i in range(6, 9)])
rows = r.fetchall()
eq_(rows, [(i, "t_%d" % i) for i in range(9, 12)])
r = conn.execute(select(self.table))
rows = r.fetchmany(None)
eq_(rows[0], (1, "t_1"))
# number of rows here could be one, or the whole thing
assert len(rows) == 1 or len(rows) == 11
r = conn.execute(select(self.table).limit(1))
r.fetchone()
eq_(r.fetchone(), None)
r = conn.execute(select(self.table).limit(5))
rows = r.fetchmany(6)
eq_(rows, [(i, "t_%d" % i) for i in range(1, 6)])
# result keeps going just fine with blank results...
eq_(r.fetchmany(2), [])
eq_(r.fetchmany(2), [])
eq_(r.fetchall(), [])
eq_(r.fetchone(), None)
# until we close
r.close()
self._assert_result_closed(r)
r = conn.execute(select(self.table).limit(5))
eq_(r.first(), (1, "t_1"))
self._assert_result_closed(r)
r = conn.execute(select(self.table).limit(5))
eq_(r.scalar(), 1)
self._assert_result_closed(r)
def _assert_result_closed(self, r):
assert_raises_message(
sa_exc.ResourceClosedError, "object is closed", r.fetchone
)
assert_raises_message(
sa_exc.ResourceClosedError, "object is closed", r.fetchmany, 2
)
assert_raises_message(
sa_exc.ResourceClosedError, "object is closed", r.fetchall
)
def test_basic_plain(self):
self._test_proxy(_cursor.CursorFetchStrategy)
def test_basic_buffered_row_result_proxy(self):
self._test_proxy(_cursor.BufferedRowCursorFetchStrategy)
def test_basic_fully_buffered_result_proxy(self):
self._test_proxy(_cursor.FullyBufferedCursorFetchStrategy)
def test_basic_buffered_column_result_proxy(self):
self._test_proxy(_cursor.CursorFetchStrategy)
def test_resultprocessor_plain(self):
self._test_result_processor(_cursor.CursorFetchStrategy, False)
def test_resultprocessor_plain_cached(self):
self._test_result_processor(_cursor.CursorFetchStrategy, True)
def test_resultprocessor_buffered_row(self):
self._test_result_processor(
_cursor.BufferedRowCursorFetchStrategy, False
)
def test_resultprocessor_buffered_row_cached(self):
self._test_result_processor(
_cursor.BufferedRowCursorFetchStrategy, True
)
def test_resultprocessor_fully_buffered(self):
self._test_result_processor(
_cursor.FullyBufferedCursorFetchStrategy, False
)
def test_resultprocessor_fully_buffered_cached(self):
self._test_result_processor(
_cursor.FullyBufferedCursorFetchStrategy, True
)
def _test_result_processor(self, cls, use_cache):
class MyType(TypeDecorator):
impl = String()
cache_ok = True
def process_result_value(self, value, dialect):
return "HI " + value
with self._proxy_fixture(cls):
with self.engine.connect() as conn:
if use_cache:
cache = {}
conn = conn.execution_options(compiled_cache=cache)
stmt = select(literal("THERE", type_=MyType()))
for i in range(2):
r = conn.execute(stmt)
eq_(r.scalar(), "HI THERE")
@testing.fixture
def row_growth_fixture(self):
with self._proxy_fixture(_cursor.BufferedRowCursorFetchStrategy):
with self.engine.begin() as conn:
conn.execute(
self.table.insert(),
[{"x": i, "y": "t_%d" % i} for i in range(15, 3000)],
)
yield conn
@testing.combinations(
("no option", None, {0: 5, 1: 25, 9: 125, 135: 625, 274: 1000}),
("lt 1000", 27, {0: 5, 16: 27, 70: 27, 150: 27, 250: 27}),
(
"gt 1000",
1500,
{0: 5, 1: 25, 9: 125, 135: 625, 274: 1500, 1351: 1500},
),
(
"gt 1500",
2000,
{0: 5, 1: 25, 9: 125, 135: 625, 274: 2000, 1351: 2000},
),
id_="iaa",
argnames="max_row_buffer,checks",
)
def test_buffered_row_growth(
self, row_growth_fixture, max_row_buffer, checks
):
if max_row_buffer:
result = row_growth_fixture.execution_options(
max_row_buffer=max_row_buffer
).execute(self.table.select())
else:
result = row_growth_fixture.execute(self.table.select())
assertion = {}
max_size = max(checks.values())
for idx, row in enumerate(result, 0):
if idx in checks:
assertion[idx] = result.cursor_strategy._bufsize
le_(len(result.cursor_strategy._rowbuffer), max_size)
def test_buffered_fetchmany_fixed(self, row_growth_fixture):
"""The BufferedRow cursor strategy will defer to the fetchmany
size passed when given rather than using the buffer growth
heuristic.
"""
result = row_growth_fixture.execute(self.table.select())
eq_(len(result.cursor_strategy._rowbuffer), 1)
rows = result.fetchmany(300)
eq_(len(rows), 300)
eq_(len(result.cursor_strategy._rowbuffer), 0)
rows = result.fetchmany(300)
eq_(len(rows), 300)
eq_(len(result.cursor_strategy._rowbuffer), 0)
bufsize = result.cursor_strategy._bufsize
result.fetchone()
# the fetchone() caused it to buffer a full set of rows
eq_(len(result.cursor_strategy._rowbuffer), bufsize - 1)
# assert partitions uses fetchmany(), therefore controlling
# how the buffer is used
lens = []
for partition in result.partitions(180):
lens.append(len(partition))
eq_(len(result.cursor_strategy._rowbuffer), 0)
for lp in lens[0:-1]:
eq_(lp, 180)
def test_buffered_fetchmany_yield_per(self, connection):
table = self.tables.test
connection.execute(
table.insert(),
[{"x": i, "y": "t_%d" % i} for i in range(15, 3000)],
)
result = connection.execute(table.select())
assert isinstance(result.cursor_strategy, _cursor.CursorFetchStrategy)
result.fetchmany(5)
result = result.yield_per(100)
assert isinstance(
result.cursor_strategy, _cursor.BufferedRowCursorFetchStrategy
)
eq_(result.cursor_strategy._bufsize, 100)
eq_(result.cursor_strategy._growth_factor, 0)
eq_(len(result.cursor_strategy._rowbuffer), 0)
result.fetchone()
eq_(len(result.cursor_strategy._rowbuffer), 99)
for i, row in enumerate(result):
if i == 188:
break
# buffer of 98, plus buffer of 99 - 89, 10 rows
eq_(len(result.cursor_strategy._rowbuffer), 10)
for i, row in enumerate(result):
if i == 206:
break
eq_(i, 206)
def test_iterator_remains_unbroken(self, connection):
"""test related to #8710.
demonstrate that we can't close the cursor by catching
GeneratorExit inside of our iteration. Leaving the iterable
block using break, then picking up again, would be directly
impacted by this. So this provides a clear rationale for
providing context manager support for result objects.
"""
table = self.tables.test
connection.execute(
table.insert(),
[{"x": i, "y": "t_%d" % i} for i in range(15, 250)],
)
result = connection.execute(table.select())
result = result.yield_per(100)
for i, row in enumerate(result):
if i == 188:
# this will raise GeneratorExit inside the iterator.
# so we can't close the DBAPI cursor here, we have plenty
# more rows to yield
break
eq_(i, 188)
# demonstrate getting more rows
for i, row in enumerate(result, 188):
if i == 206:
break
eq_(i, 206)
@testing.combinations(True, False, argnames="close_on_init")
@testing.combinations(
"fetchone", "fetchmany", "fetchall", argnames="fetch_style"
)
def test_buffered_fetch_auto_soft_close(
self, connection, close_on_init, fetch_style
):
"""test #7274"""
table = self.tables.test
connection.execute(
table.insert(),
[{"x": i, "y": "t_%d" % i} for i in range(15, 30)],
)
result = connection.execute(table.select().limit(15))
assert isinstance(result.cursor_strategy, _cursor.CursorFetchStrategy)
if close_on_init:
# close_on_init - the initial buffering will exhaust the cursor,
# should soft close immediately
result = result.yield_per(30)
else:
# not close_on_init - soft close will occur after fetching an
# empty buffer
result = result.yield_per(5)
assert isinstance(
result.cursor_strategy, _cursor.BufferedRowCursorFetchStrategy
)
with mock.patch.object(result, "_soft_close") as soft_close:
if fetch_style == "fetchone":
while True:
row = result.fetchone()
if row:
eq_(soft_close.mock_calls, [])
else:
# fetchone() is also used by first(), scalar()
# and one() which want to embed a hard close in one
# step
eq_(soft_close.mock_calls, [mock.call(hard=False)])
break
elif fetch_style == "fetchmany":
while True:
rows = result.fetchmany(5)
if rows:
eq_(soft_close.mock_calls, [])
else:
eq_(soft_close.mock_calls, [mock.call()])
break
elif fetch_style == "fetchall":
rows = result.fetchall()
eq_(soft_close.mock_calls, [mock.call()])
else:
assert False
result.close()
def test_buffered_fetchmany_yield_per_all(self, connection):
table = self.tables.test
connection.execute(
table.insert(),
[{"x": i, "y": "t_%d" % i} for i in range(15, 500)],
)
result = connection.execute(table.select())
assert isinstance(result.cursor_strategy, _cursor.CursorFetchStrategy)
result.fetchmany(5)
result = result.yield_per(0)
assert isinstance(
result.cursor_strategy, _cursor.BufferedRowCursorFetchStrategy
)
eq_(result.cursor_strategy._bufsize, 0)
eq_(result.cursor_strategy._growth_factor, 0)
eq_(len(result.cursor_strategy._rowbuffer), 0)
result.fetchone()
eq_(len(result.cursor_strategy._rowbuffer), 490)
for i, row in enumerate(result):
if i == 188:
break
eq_(len(result.cursor_strategy._rowbuffer), 301)
# already buffered, so this doesn't change things
result.yield_per(10)
result.fetchmany(5)
eq_(len(result.cursor_strategy._rowbuffer), 296)
self._test_result_processor(
_cursor.BufferedRowCursorFetchStrategy, False
)
@testing.combinations(
_cursor.CursorFetchStrategy,
_cursor.BufferedRowCursorFetchStrategy,
# does not handle error in fetch
# _cursor.FullyBufferedCursorFetchStrategy,
argnames="strategy_cls",
)
@testing.combinations(
"fetchone",
"fetchmany",
"fetchmany_w_num",
"fetchall",
argnames="method_name",
)
def test_handle_error_in_fetch(self, strategy_cls, method_name):
class cursor(object):
def raise_(self):
raise IOError("random non-DBAPI error during cursor operation")
def fetchone(self):
self.raise_()
def fetchmany(self, num=None):
self.raise_()
def fetchall(self):
self.raise_()
def close(self):
self.raise_()
with self._proxy_fixture(strategy_cls):
with self.engine.connect() as conn:
r = conn.execute(select(self.table))
assert isinstance(r.cursor_strategy, strategy_cls)
with mock.patch.object(r, "cursor", cursor()):
with testing.expect_raises_message(
IOError, "random non-DBAPI"
):
if method_name == "fetchmany_w_num":
r.fetchmany(10)
else:
getattr(r, method_name)()
getattr(r, method_name)()
r.close()
def test_buffered_row_close_error_during_fetchone(self):
def raise_(**kw):
raise IOError("random non-DBAPI error during cursor operation")
with self._proxy_fixture(_cursor.BufferedRowCursorFetchStrategy):
with self.engine.connect() as conn:
r = conn.execute(select(self.table).limit(1))
r.fetchone()
with mock.patch.object(
r, "_soft_close", raise_
), testing.expect_raises_message(IOError, "random non-DBAPI"):
r.first()
r.close()
class MergeCursorResultTest(fixtures.TablesTest):
__backend__ = True
__requires__ = ("independent_cursors",)
@classmethod
def define_tables(cls, metadata):
Table(
"users",
metadata,
Column("user_id", INT, primary_key=True, autoincrement=False),
Column("user_name", VARCHAR(20)),
test_needs_acid=True,
)
@classmethod
def insert_data(cls, connection):
users = cls.tables.users
connection.execute(
users.insert(),
[
{"user_id": 7, "user_name": "u1"},
{"user_id": 8, "user_name": "u2"},
{"user_id": 9, "user_name": "u3"},
{"user_id": 10, "user_name": "u4"},
{"user_id": 11, "user_name": "u5"},
{"user_id": 12, "user_name": "u6"},
],
)
@testing.fixture
def merge_fixture(self):
users = self.tables.users
def results(connection):
r1 = connection.execute(
users.select()
.where(users.c.user_id.in_([7, 8]))
.order_by(users.c.user_id)
)
r2 = connection.execute(
users.select()
.where(users.c.user_id.in_([9]))
.order_by(users.c.user_id)
)
r3 = connection.execute(
users.select()
.where(users.c.user_id.in_([10, 11]))
.order_by(users.c.user_id)
)
r4 = connection.execute(
users.select()
.where(users.c.user_id.in_([12]))
.order_by(users.c.user_id)
)
return r1, r2, r3, r4
return results
def test_merge_results(self, connection, merge_fixture):
r1, r2, r3, r4 = merge_fixture(connection)
result = r1.merge(r2, r3, r4)
eq_(result.keys(), ["user_id", "user_name"])
row = result.fetchone()
eq_(row, (7, "u1"))
result.close()
def test_close(self, connection, merge_fixture):
r1, r2, r3, r4 = merge_fixture(connection)
result = r1.merge(r2, r3, r4)
for r in [result, r1, r2, r3, r4]:
assert not r.closed
result.close()
for r in [result, r1, r2, r3, r4]:
assert r.closed
def test_fetchall(self, connection, merge_fixture):
r1, r2, r3, r4 = merge_fixture(connection)
result = r1.merge(r2, r3, r4)
eq_(
result.fetchall(),
[
(7, "u1"),
(8, "u2"),
(9, "u3"),
(10, "u4"),
(11, "u5"),
(12, "u6"),
],
)
for r in [r1, r2, r3, r4]:
assert r._soft_closed
def test_first(self, connection, merge_fixture):
r1, r2, r3, r4 = merge_fixture(connection)
result = r1.merge(r2, r3, r4)
eq_(
result.first(),
(7, "u1"),
)
for r in [r1, r2, r3, r4]:
assert r.closed
def test_columns(self, connection, merge_fixture):
r1, r2, r3, r4 = merge_fixture(connection)
result = r1.merge(r2, r3, r4)
eq_(
result.columns("user_name").fetchmany(4),
[("u1",), ("u2",), ("u3",), ("u4",)],
)
result.close()
class GenerativeResultTest(fixtures.TablesTest):
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"users",
metadata,
Column("user_id", INT, primary_key=True, autoincrement=False),
Column("user_name", VARCHAR(20)),
Column("x", Integer),
Column("y", Integer),
test_needs_acid=True,
)
Table(
"users_autoinc",
metadata,
Column(
"user_id", INT, primary_key=True, test_needs_autoincrement=True
),
Column("user_name", VARCHAR(20)),
test_needs_acid=True,
)
def test_fetchall(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
{"user_id": 7, "user_name": "jack", "x": 1, "y": 2},
{"user_id": 8, "user_name": "ed", "x": 2, "y": 3},
{"user_id": 9, "user_name": "fred", "x": 15, "y": 20},
],
)
result = connection.execute(select(users).order_by(users.c.user_id))
eq_(
result.all(),
[(7, "jack", 1, 2), (8, "ed", 2, 3), (9, "fred", 15, 20)],
)
@testing.combinations(
((1, 0), [("jack", 7), ("ed", 8), ("fred", 9)]),
((3,), [(2,), (3,), (20,)]),
((-2, -1), [(1, 2), (2, 3), (15, 20)]),
argnames="columns, expected",
)
def test_columns(self, connection, columns, expected):
users = self.tables.users
connection.execute(
users.insert(),
[
{"user_id": 7, "user_name": "jack", "x": 1, "y": 2},
{"user_id": 8, "user_name": "ed", "x": 2, "y": 3},
{"user_id": 9, "user_name": "fred", "x": 15, "y": 20},
],
)
result = connection.execute(select(users).order_by(users.c.user_id))
all_ = result.columns(*columns).all()
eq_(all_, expected)
# ensure Row / LegacyRow comes out with .columns
assert type(all_[0]) is result._process_row
def test_columns_twice(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[{"user_id": 7, "user_name": "jack", "x": 1, "y": 2}],
)
result = connection.execute(select(users).order_by(users.c.user_id))
all_ = (
result.columns("x", "y", "user_name", "user_id")
.columns("user_name", "x")
.all()
)
eq_(all_, [("jack", 1)])
# ensure Row / LegacyRow comes out with .columns
assert type(all_[0]) is result._process_row
def test_columns_plus_getter(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[{"user_id": 7, "user_name": "jack", "x": 1, "y": 2}],
)
result = connection.execute(select(users).order_by(users.c.user_id))
result = result.columns("x", "y", "user_name")
getter = result._metadata._getter("y")
eq_(getter(result.first()), 2)
def test_partitions(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
{
"user_id": i,
"user_name": "user %s" % i,
"x": i * 5,
"y": i * 20,
}
for i in range(500)
],
)
result = connection.execute(select(users).order_by(users.c.user_id))
start = 0
for partition in result.columns(0, 1).partitions(20):
eq_(
partition,
[(i, "user %s" % i) for i in range(start, start + 20)],
)
start += 20
assert result._soft_closed
|