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
|
import contextlib
import functools
import itertools
import uuid
from sqlalchemy import and_
from sqlalchemy import ARRAY
from sqlalchemy import bindparam
from sqlalchemy import DateTime
from sqlalchemy import event
from sqlalchemy import exc
from sqlalchemy import ForeignKey
from sqlalchemy import func
from sqlalchemy import Identity
from sqlalchemy import insert
from sqlalchemy import insert_sentinel
from sqlalchemy import INT
from sqlalchemy import Integer
from sqlalchemy import literal
from sqlalchemy import MetaData
from sqlalchemy import select
from sqlalchemy import Sequence
from sqlalchemy import sql
from sqlalchemy import String
from sqlalchemy import testing
from sqlalchemy import TypeDecorator
from sqlalchemy import Uuid
from sqlalchemy import VARCHAR
from sqlalchemy.engine import cursor as _cursor
from sqlalchemy.sql.compiler import InsertmanyvaluesSentinelOpts
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import config
from sqlalchemy.testing import eq_
from sqlalchemy.testing import expect_raises
from sqlalchemy.testing import expect_raises_message
from sqlalchemy.testing import expect_warnings
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import is_
from sqlalchemy.testing import mock
from sqlalchemy.testing import provision
from sqlalchemy.testing.fixtures import insertmanyvalues_fixture
from sqlalchemy.testing.provision import normalize_sequence
from sqlalchemy.testing.schema import Column
from sqlalchemy.testing.schema import Table
class ExpectExpr:
def __init__(self, element):
self.element = element
def __clause_element__(self):
return self.element
class InsertExecTest(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,
)
@testing.requires.multivalues_inserts
@testing.combinations("string", "column", "expect", argnames="keytype")
def test_multivalues_insert(self, connection, keytype):
users = self.tables.users
if keytype == "string":
user_id, user_name = "user_id", "user_name"
elif keytype == "column":
user_id, user_name = users.c.user_id, users.c.user_name
elif keytype == "expect":
user_id, user_name = ExpectExpr(users.c.user_id), ExpectExpr(
users.c.user_name
)
else:
assert False
connection.execute(
users.insert().values(
[
{user_id: 7, user_name: "jack"},
{user_id: 8, user_name: "ed"},
]
)
)
rows = connection.execute(
users.select().order_by(users.c.user_id)
).all()
eq_(rows[0], (7, "jack"))
eq_(rows[1], (8, "ed"))
connection.execute(users.insert().values([(9, "jack"), (10, "ed")]))
rows = connection.execute(
users.select().order_by(users.c.user_id)
).all()
eq_(rows[2], (9, "jack"))
eq_(rows[3], (10, "ed"))
def test_insert_heterogeneous_params(self, connection):
"""test that executemany parameters are asserted to match the
parameter set of the first."""
users = self.tables.users
assert_raises_message(
exc.StatementError,
r"\(sqlalchemy.exc.InvalidRequestError\) A value is required for "
"bind parameter 'user_name', in "
"parameter group 2\n"
r"\[SQL: u?INSERT INTO users",
connection.execute,
users.insert(),
[
{"user_id": 7, "user_name": "jack"},
{"user_id": 8, "user_name": "ed"},
{"user_id": 9},
],
)
# this succeeds however. We aren't yet doing
# a length check on all subsequent parameters.
connection.execute(
users.insert(),
[
{"user_id": 7},
{"user_id": 8, "user_name": "ed"},
{"user_id": 9},
],
)
def _test_lastrow_accessor(self, connection, table_, values, assertvalues):
"""Tests the inserted_primary_key and lastrow_has_id() functions."""
def insert_values(table_, values):
"""
Inserts a row into a table, returns the full list of values
INSERTed including defaults that fired off on the DB side and
detects rows that had defaults and post-fetches.
"""
# verify implicit_returning is working
if (
connection.dialect.insert_returning
and table_.implicit_returning
and not connection.dialect.postfetch_lastrowid
):
ins = table_.insert()
comp = ins.compile(connection, column_keys=list(values))
if not set(values).issuperset(
c.key for c in table_.primary_key
):
is_(bool(comp.returning), True)
result = connection.execute(table_.insert(), values)
ret = values.copy()
ipk = result.inserted_primary_key
for col, id_ in zip(table_.primary_key, ipk):
ret[col.key] = id_
if result.lastrow_has_defaults():
criterion = and_(
*[
col == id_
for col, id_ in zip(
table_.primary_key, result.inserted_primary_key
)
]
)
row = connection.execute(
table_.select().where(criterion)
).first()
for c in table_.c:
ret[c.key] = row._mapping[c]
return ret, ipk
table_.create(connection, checkfirst=True)
i, ipk = insert_values(table_, values)
eq_(i, assertvalues)
# named tuple tests
for col in table_.primary_key:
eq_(getattr(ipk, col.key), assertvalues[col.key])
eq_(ipk._mapping[col.key], assertvalues[col.key])
eq_(ipk._fields, tuple([col.key for col in table_.primary_key]))
@testing.requires.supports_autoincrement_w_composite_pk
@testing.combinations(
(True, testing.requires.insert_returning),
(False,),
argnames="implicit_returning",
)
def test_lastrow_accessor_one(
self, metadata, connection, implicit_returning
):
self._test_lastrow_accessor(
connection,
Table(
"t1",
metadata,
Column(
"id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("foo", String(30), primary_key=True),
implicit_returning=implicit_returning,
),
{"foo": "hi"},
{"id": 1, "foo": "hi"},
)
@testing.requires.supports_autoincrement_w_composite_pk
@testing.combinations(
(True, testing.requires.insert_returning),
(False,),
argnames="implicit_returning",
)
def test_lastrow_accessor_two(
self, metadata, connection, implicit_returning
):
self._test_lastrow_accessor(
connection,
Table(
"t2",
metadata,
Column(
"id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("foo", String(30), primary_key=True),
Column("bar", String(30), server_default="hi"),
implicit_returning=implicit_returning,
),
{"foo": "hi"},
{"id": 1, "foo": "hi", "bar": "hi"},
)
@testing.combinations(
(True, testing.requires.insert_returning),
(False,),
argnames="implicit_returning",
)
def test_lastrow_accessor_three(
self, metadata, connection, implicit_returning
):
self._test_lastrow_accessor(
connection,
Table(
"t3",
metadata,
Column("id", String(40), primary_key=True),
Column("foo", String(30), primary_key=True),
Column("bar", String(30)),
implicit_returning=implicit_returning,
),
{"id": "hi", "foo": "thisisfoo", "bar": "thisisbar"},
{"id": "hi", "foo": "thisisfoo", "bar": "thisisbar"},
)
@testing.requires.sequences
@testing.combinations(
(True, testing.requires.insert_returning),
(False,),
argnames="implicit_returning",
)
def test_lastrow_accessor_four(
self, metadata, connection, implicit_returning
):
self._test_lastrow_accessor(
connection,
Table(
"t4",
metadata,
Column(
"id",
Integer,
normalize_sequence(
config, Sequence("t4_id_seq", optional=True)
),
primary_key=True,
),
Column("foo", String(30), primary_key=True),
Column("bar", String(30), server_default="hi"),
implicit_returning=implicit_returning,
),
{"foo": "hi", "id": 1},
{"id": 1, "foo": "hi", "bar": "hi"},
)
@testing.requires.sequences
@testing.combinations(
(True, testing.requires.insert_returning),
(False,),
argnames="implicit_returning",
)
def test_lastrow_accessor_four_a(
self, metadata, connection, implicit_returning
):
self._test_lastrow_accessor(
connection,
Table(
"t4",
metadata,
Column(
"id",
Integer,
normalize_sequence(config, Sequence("t4_id_seq")),
primary_key=True,
),
Column("foo", String(30)),
implicit_returning=implicit_returning,
),
{"foo": "hi"},
{"id": 1, "foo": "hi"},
)
@testing.combinations(
(True, testing.requires.insert_returning),
(False,),
argnames="implicit_returning",
)
def test_lastrow_accessor_five(
self, metadata, connection, implicit_returning
):
self._test_lastrow_accessor(
connection,
Table(
"t5",
metadata,
Column("id", String(10), primary_key=True),
Column("bar", String(30), server_default="hi"),
implicit_returning=implicit_returning,
),
{"id": "id1"},
{"id": "id1", "bar": "hi"},
)
@testing.requires.supports_autoincrement_w_composite_pk
@testing.combinations(
(True, testing.requires.insert_returning),
(False,),
argnames="implicit_returning",
)
def test_lastrow_accessor_six(
self, metadata, connection, implicit_returning
):
self._test_lastrow_accessor(
connection,
Table(
"t6",
metadata,
Column(
"id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("bar", Integer, primary_key=True),
implicit_returning=implicit_returning,
),
{"bar": 0},
{"id": 1, "bar": 0},
)
# TODO: why not in the sqlite suite?
@testing.only_on("sqlite+pysqlite")
def test_lastrowid_zero(self, metadata, connection):
from sqlalchemy.dialects import sqlite
class ExcCtx(sqlite.base.SQLiteExecutionContext):
def get_lastrowid(self):
return 0
t = Table(
"t",
self.metadata,
Column("x", Integer, primary_key=True),
Column("y", Integer),
implicit_returning=False,
)
t.create(connection)
with mock.patch.object(
connection.dialect, "execution_ctx_cls", ExcCtx
):
r = connection.execute(t.insert().values(y=5))
eq_(r.inserted_primary_key, (0,))
@testing.requires.supports_autoincrement_w_composite_pk
def test_misordered_lastrow(self, connection, metadata):
related = Table(
"related",
metadata,
Column("id", Integer, primary_key=True),
mysql_engine="MyISAM",
mariadb_engine="MyISAM",
)
t6 = Table(
"t6",
metadata,
Column(
"manual_id",
Integer,
ForeignKey("related.id"),
primary_key=True,
),
Column(
"auto_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
mysql_engine="MyISAM",
mariadb_engine="MyISAM",
)
metadata.create_all(connection)
r = connection.execute(related.insert().values(id=12))
id_ = r.inserted_primary_key[0]
eq_(id_, 12)
r = connection.execute(t6.insert().values(manual_id=id_))
eq_(r.inserted_primary_key, (12, 1))
def test_implicit_id_insert_select_columns(self, connection):
users = self.tables.users
stmt = users.insert().from_select(
(users.c.user_id, users.c.user_name),
users.select().where(users.c.user_id == 20),
)
r = connection.execute(stmt)
eq_(r.inserted_primary_key, (None,))
def test_implicit_id_insert_select_keys(self, connection):
users = self.tables.users
stmt = users.insert().from_select(
["user_id", "user_name"],
users.select().where(users.c.user_id == 20),
)
r = connection.execute(stmt)
eq_(r.inserted_primary_key, (None,))
@testing.requires.empty_inserts
@testing.requires.insert_returning
def test_no_inserted_pk_on_returning(
self, connection, close_result_when_finished
):
users = self.tables.users
result = connection.execute(
users.insert().returning(users.c.user_id, users.c.user_name)
)
close_result_when_finished(result)
assert_raises_message(
exc.InvalidRequestError,
r"Can't call inserted_primary_key when returning\(\) is used.",
getattr,
result,
"inserted_primary_key",
)
class TableInsertTest(fixtures.TablesTest):
"""test for consistent insert behavior across dialects
regarding the inline() method, values() method, lower-case 't' tables.
"""
run_create_tables = "each"
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"foo",
metadata,
Column(
"id",
Integer,
normalize_sequence(config, Sequence("t_id_seq")),
primary_key=True,
),
Column("data", String(50)),
Column("x", Integer),
)
Table(
"foo_no_seq",
metadata,
# note this will have full AUTO INCREMENT on MariaDB
# whereas "foo" will not due to sequence support
Column(
"id",
Integer,
primary_key=True,
),
Column("data", String(50)),
Column("x", Integer),
)
def _fixture(self, types=True):
if types:
t = sql.table(
"foo",
sql.column("id", Integer),
sql.column("data", String),
sql.column("x", Integer),
)
else:
t = sql.table(
"foo", sql.column("id"), sql.column("data"), sql.column("x")
)
return t
def _test(
self,
connection,
stmt,
row,
returning=None,
inserted_primary_key=False,
table=None,
parameters=None,
):
if parameters is not None:
r = connection.execute(stmt, parameters)
else:
r = connection.execute(stmt)
if returning:
returned = r.first()
eq_(returned, returning)
elif inserted_primary_key is not False:
eq_(r.inserted_primary_key, inserted_primary_key)
if table is None:
table = self.tables.foo
eq_(connection.execute(table.select()).first(), row)
def _test_multi(self, connection, stmt, rows, data):
connection.execute(stmt, rows)
eq_(
connection.execute(
self.tables.foo.select().order_by(self.tables.foo.c.id)
).all(),
data,
)
@testing.requires.sequences
def test_explicit_sequence(self, connection):
t = self._fixture()
self._test(
connection,
t.insert().values(
id=func.next_value(
normalize_sequence(config, Sequence("t_id_seq"))
),
data="data",
x=5,
),
(testing.db.dialect.default_sequence_base, "data", 5),
)
def test_uppercase(self, connection):
t = self.tables.foo
self._test(
connection,
t.insert().values(id=1, data="data", x=5),
(1, "data", 5),
inserted_primary_key=(1,),
)
def test_uppercase_inline(self, connection):
t = self.tables.foo
self._test(
connection,
t.insert().inline().values(id=1, data="data", x=5),
(1, "data", 5),
inserted_primary_key=(1,),
)
@testing.crashes(
"mssql+pyodbc",
"Pyodbc + SQL Server + Py3K, some decimal handling issue",
)
def test_uppercase_inline_implicit(self, connection):
t = self.tables.foo
self._test(
connection,
t.insert().inline().values(data="data", x=5),
(1, "data", 5),
inserted_primary_key=(None,),
)
def test_uppercase_implicit(self, connection):
t = self.tables.foo
self._test(
connection,
t.insert().values(data="data", x=5),
(testing.db.dialect.default_sequence_base, "data", 5),
inserted_primary_key=(testing.db.dialect.default_sequence_base,),
)
def test_uppercase_direct_params(self, connection):
t = self.tables.foo
self._test(
connection,
t.insert().values(id=1, data="data", x=5),
(1, "data", 5),
inserted_primary_key=(1,),
)
@testing.requires.insert_returning
def test_uppercase_direct_params_returning(self, connection):
t = self.tables.foo
self._test(
connection,
t.insert().values(id=1, data="data", x=5).returning(t.c.id, t.c.x),
(1, "data", 5),
returning=(1, 5),
)
@testing.requires.sql_expressions_inserted_as_primary_key
def test_sql_expr_lastrowid(self, connection):
# see also test.orm.test_unitofwork.py
# ClauseAttributesTest.test_insert_pk_expression
t = self.tables.foo_no_seq
self._test(
connection,
t.insert().values(id=literal(5) + 10, data="data", x=5),
(15, "data", 5),
inserted_primary_key=(15,),
table=self.tables.foo_no_seq,
)
def test_direct_params(self, connection):
t = self._fixture()
self._test(
connection,
t.insert().values(id=1, data="data", x=5),
(1, "data", 5),
inserted_primary_key=(),
)
@testing.requires.insert_returning
def test_direct_params_returning(self, connection):
t = self._fixture()
self._test(
connection,
t.insert().values(id=1, data="data", x=5).returning(t.c.id, t.c.x),
(testing.db.dialect.default_sequence_base, "data", 5),
returning=(testing.db.dialect.default_sequence_base, 5),
)
# there's a non optional Sequence in the metadata, which if the dialect
# supports sequences, it means the CREATE TABLE should *not* have
# autoincrement, so the INSERT below would fail because the "t" fixture
# does not indicate the Sequence
@testing.fails_if(testing.requires.sequences)
@testing.requires.emulated_lastrowid
def test_implicit_pk(self, connection):
t = self._fixture()
self._test(
connection,
t.insert().values(data="data", x=5),
(testing.db.dialect.default_sequence_base, "data", 5),
inserted_primary_key=(),
)
@testing.fails_if(testing.requires.sequences)
@testing.requires.emulated_lastrowid
def test_implicit_pk_multi_rows(self, connection):
t = self._fixture()
self._test_multi(
connection,
t.insert(),
[
{"data": "d1", "x": 5},
{"data": "d2", "x": 6},
{"data": "d3", "x": 7},
],
[(1, "d1", 5), (2, "d2", 6), (3, "d3", 7)],
)
@testing.fails_if(testing.requires.sequences)
@testing.requires.emulated_lastrowid
def test_implicit_pk_inline(self, connection):
t = self._fixture()
self._test(
connection,
t.insert().inline().values(data="data", x=5),
(testing.db.dialect.default_sequence_base, "data", 5),
inserted_primary_key=(),
)
@testing.requires.database_discards_null_for_autoincrement
def test_explicit_null_pk_values_db_ignores_it(self, connection):
"""test new use case in #7998"""
# NOTE: this use case uses cursor.lastrowid on SQLite, MySQL, MariaDB,
# however when SQLAlchemy 2.0 adds support for RETURNING to SQLite
# and MariaDB, it should work there as well.
t = self.tables.foo_no_seq
self._test(
connection,
t.insert().values(id=None, data="data", x=5),
(testing.db.dialect.default_sequence_base, "data", 5),
inserted_primary_key=(testing.db.dialect.default_sequence_base,),
table=t,
)
@testing.requires.database_discards_null_for_autoincrement
def test_explicit_null_pk_params_db_ignores_it(self, connection):
"""test new use case in #7998"""
# NOTE: this use case uses cursor.lastrowid on SQLite, MySQL, MariaDB,
# however when SQLAlchemy 2.0 adds support for RETURNING to SQLite
# and MariaDB, it should work there as well.
t = self.tables.foo_no_seq
self._test(
connection,
t.insert(),
(testing.db.dialect.default_sequence_base, "data", 5),
inserted_primary_key=(testing.db.dialect.default_sequence_base,),
table=t,
parameters=dict(id=None, data="data", x=5),
)
class InsertManyValuesTest(fixtures.RemovesEvents, fixtures.TablesTest):
__backend__ = True
__requires__ = ("insertmanyvalues",)
@classmethod
def define_tables(cls, metadata):
Table(
"data",
metadata,
Column("id", Integer, primary_key=True),
Column("x", String(50)),
Column("y", String(50)),
Column("z", Integer, server_default="5"),
)
Table(
"Unitéble2",
metadata,
Column("méil", Integer, primary_key=True),
Column("\u6e2c\u8a66", Integer),
)
Table(
"extra_table",
metadata,
Column("id", Integer, primary_key=True),
Column("x_value", String(50)),
Column("y_value", String(50)),
)
Table(
"uniq_cons",
metadata,
Column("id", Integer, primary_key=True),
Column("data", String(50), unique=True),
)
@testing.variation("use_returning", [True, False])
def test_returning_integrity_error(self, connection, use_returning):
"""test for #11532"""
stmt = self.tables.uniq_cons.insert()
if use_returning:
stmt = stmt.returning(self.tables.uniq_cons.c.id)
# pymssql thought it would be funny to use OperationalError for
# a unique key violation.
with expect_raises((exc.IntegrityError, exc.OperationalError)):
connection.execute(
stmt, [{"data": "the data"}, {"data": "the data"}]
)
def test_insert_unicode_keys(self, connection):
table = self.tables["Unitéble2"]
stmt = table.insert().returning(table.c["méil"])
connection.execute(
stmt,
[
{"méil": 1, "\u6e2c\u8a66": 1},
{"méil": 2, "\u6e2c\u8a66": 2},
{"méil": 3, "\u6e2c\u8a66": 3},
],
)
eq_(connection.execute(table.select()).all(), [(1, 1), (2, 2), (3, 3)])
@testing.variation("preserve_rowcount", [True, False])
def test_insert_returning_values(self, connection, preserve_rowcount):
t = self.tables.data
conn = connection
page_size = conn.dialect.insertmanyvalues_page_size or 100
data = [
{"x": "x%d" % i, "y": "y%d" % i}
for i in range(1, page_size * 2 + 27)
]
if preserve_rowcount:
eo = {"preserve_rowcount": True}
else:
eo = {}
result = conn.execute(
t.insert().returning(t.c.x, t.c.y), data, execution_options=eo
)
eq_([tup[0] for tup in result.cursor.description], ["x", "y"])
eq_(result.keys(), ["x", "y"])
assert t.c.x in result.keys()
assert t.c.id not in result.keys()
assert not result._soft_closed
assert isinstance(
result.cursor_strategy,
_cursor.FullyBufferedCursorFetchStrategy,
)
assert not result.closed
eq_(result.mappings().all(), data)
assert result._soft_closed
# assert result.closed
assert result.cursor is None
if preserve_rowcount:
eq_(result.rowcount, len(data))
def test_insert_returning_preexecute_pk(self, metadata, connection):
counter = itertools.count(1)
t = Table(
"t",
self.metadata,
Column(
"id",
Integer,
primary_key=True,
default=lambda: next(counter),
),
Column("data", Integer),
)
metadata.create_all(connection)
result = connection.execute(
t.insert().return_defaults(),
[{"data": 1}, {"data": 2}, {"data": 3}],
)
eq_(result.inserted_primary_key_rows, [(1,), (2,), (3,)])
@testing.requires.ctes_on_dml
@testing.variation("add_expr_returning", [True, False])
def test_insert_w_bindparam_in_nested_insert(
self, connection, add_expr_returning
):
"""test related to #9173"""
data, extra_table = self.tables("data", "extra_table")
inst = (
extra_table.insert()
.values(x_value="x", y_value="y")
.returning(extra_table.c.id)
.cte("inst")
)
stmt = (
data.insert()
.values(x="the x", z=select(inst.c.id).scalar_subquery())
.add_cte(inst)
)
if add_expr_returning:
stmt = stmt.returning(data.c.id, data.c.y + " returned y")
else:
stmt = stmt.returning(data.c.id)
result = connection.execute(
stmt,
[
{"y": "y1"},
{"y": "y2"},
{"y": "y3"},
],
)
result_rows = result.all()
ids = [row[0] for row in result_rows]
extra_row = connection.execute(
select(extra_table).order_by(extra_table.c.id)
).one()
extra_row_id = extra_row[0]
eq_(extra_row, (extra_row_id, "x", "y"))
eq_(
connection.execute(select(data).order_by(data.c.id)).all(),
[
(ids[0], "the x", "y1", extra_row_id),
(ids[1], "the x", "y2", extra_row_id),
(ids[2], "the x", "y3", extra_row_id),
],
)
@testing.requires.provisioned_upsert
def test_upsert_w_returning(self, connection):
"""test cases that will execise SQL similar to that of
test/orm/dml/test_bulk_statements.py
"""
data = self.tables.data
initial_data = [
{"x": "x1", "y": "y1", "z": 4},
{"x": "x2", "y": "y2", "z": 8},
]
ids = connection.scalars(
data.insert().returning(data.c.id), initial_data
).all()
upsert_data = [
{
"id": ids[0],
"x": "x1",
"y": "y1",
},
{
"id": 32,
"x": "x19",
"y": "y7",
},
{
"id": ids[1],
"x": "x5",
"y": "y6",
},
{
"id": 28,
"x": "x9",
"y": "y15",
},
]
stmt = provision.upsert(
config,
data,
(data,),
set_lambda=lambda inserted: {"x": inserted.x + " upserted"},
)
result = connection.execute(stmt, upsert_data)
eq_(
result.all(),
[
(ids[0], "x1 upserted", "y1", 4),
(32, "x19", "y7", 5),
(ids[1], "x5 upserted", "y2", 8),
(28, "x9", "y15", 5),
],
)
@testing.combinations(True, False, argnames="use_returning")
@testing.combinations(1, 2, argnames="num_embedded_params")
@testing.combinations(True, False, argnames="use_whereclause")
@testing.crashes(
"+mariadbconnector",
"returning crashes, regular executemany malfunctions",
)
def test_insert_w_bindparam_in_subq(
self, connection, use_returning, num_embedded_params, use_whereclause
):
"""test #8639
see also test_insert_w_bindparam_in_nested_insert
"""
t = self.tables.data
extra = self.tables.extra_table
conn = connection
connection.execute(
extra.insert(),
[
{"x_value": "p1", "y_value": "yv1"},
{"x_value": "p2", "y_value": "yv2"},
{"x_value": "p1_p1", "y_value": "yv3"},
{"x_value": "p2_p2", "y_value": "yv4"},
],
)
if num_embedded_params == 1:
if use_whereclause:
scalar_subq = select(bindparam("paramname")).scalar_subquery()
params = [
{"paramname": "p1_p1", "y": "y1"},
{"paramname": "p2_p2", "y": "y2"},
]
else:
scalar_subq = (
select(extra.c.x_value)
.where(extra.c.y_value == bindparam("y_value"))
.scalar_subquery()
)
params = [
{"y_value": "yv3", "y": "y1"},
{"y_value": "yv4", "y": "y2"},
]
elif num_embedded_params == 2:
if use_whereclause:
scalar_subq = (
select(
bindparam("paramname1", type_=String) + extra.c.x_value
)
.where(extra.c.y_value == bindparam("y_value"))
.scalar_subquery()
)
params = [
{"paramname1": "p1_", "y_value": "yv1", "y": "y1"},
{"paramname1": "p2_", "y_value": "yv2", "y": "y2"},
]
else:
scalar_subq = select(
bindparam("paramname1", type_=String)
+ bindparam("paramname2", type_=String)
).scalar_subquery()
params = [
{"paramname1": "p1_", "paramname2": "p1", "y": "y1"},
{"paramname1": "p2_", "paramname2": "p2", "y": "y2"},
]
else:
assert False
stmt = t.insert().values(x=scalar_subq)
if use_returning:
stmt = stmt.returning(t.c["x", "y"])
result = conn.execute(stmt, params)
if use_returning:
eq_(result.all(), [("p1_p1", "y1"), ("p2_p2", "y2")])
result = conn.execute(select(t.c["x", "y"]))
eq_(result.all(), [("p1_p1", "y1"), ("p2_p2", "y2")])
@testing.variation("preserve_rowcount", [True, False])
def test_insert_returning_defaults(self, connection, preserve_rowcount):
t = self.tables.data
if preserve_rowcount:
conn = connection.execution_options(preserve_rowcount=True)
else:
conn = connection
result = conn.execute(t.insert(), {"x": "x0", "y": "y0"})
first_pk = result.inserted_primary_key[0]
page_size = conn.dialect.insertmanyvalues_page_size or 100
total_rows = page_size * 5 + 27
data = [{"x": "x%d" % i, "y": "y%d" % i} for i in range(1, total_rows)]
result = conn.execute(t.insert().returning(t.c.id, t.c.z), data)
eq_(
result.all(),
[(pk, 5) for pk in range(1 + first_pk, total_rows + first_pk)],
)
if preserve_rowcount:
eq_(result.rowcount, total_rows - 1) # range starts from 1
def test_insert_return_pks_default_values(self, connection):
"""test sending multiple, empty rows into an INSERT and getting primary
key values back.
This has to use a format that indicates at least one DEFAULT in
multiple parameter sets, i.e. "INSERT INTO table (anycol) VALUES
(DEFAULT) (DEFAULT) (DEFAULT) ... RETURNING col"
if the database doesnt support this (like SQLite, mssql), it
actually runs the statement that many times on the cursor.
This is much less efficient, but is still more efficient than
how it worked previously where we'd run the statement that many
times anyway.
There's ways to make it work for those, such as on SQLite
we can use "INSERT INTO table (pk_col) VALUES (NULL) RETURNING pk_col",
but that assumes an autoincrement pk_col, not clear how this
could be produced generically.
"""
t = self.tables.data
conn = connection
result = conn.execute(t.insert(), {"x": "x0", "y": "y0"})
first_pk = result.inserted_primary_key[0]
page_size = conn.dialect.insertmanyvalues_page_size or 100
total_rows = page_size * 2 + 27
data = [{} for i in range(1, total_rows)]
result = conn.execute(t.insert().returning(t.c.id), data)
eq_(
result.all(),
[(pk,) for pk in range(1 + first_pk, total_rows + first_pk)],
)
@testing.combinations(None, 100, 329, argnames="batchsize")
@testing.combinations(
"engine",
"conn_execution_option",
"exec_execution_option",
"stmt_execution_option",
argnames="paramtype",
)
def test_page_size_adjustment(self, testing_engine, batchsize, paramtype):
t = self.tables.data
if paramtype == "engine" and batchsize is not None:
e = testing_engine(
options={
"insertmanyvalues_page_size": batchsize,
},
)
# sqlite, since this is a new engine, re-create the table
if not testing.requires.independent_connections.enabled:
t.create(e, checkfirst=True)
else:
e = testing.db
totalnum = 1275
data = [{"x": "x%d" % i, "y": "y%d" % i} for i in range(1, totalnum)]
insert_count = 0
with e.begin() as conn:
@event.listens_for(conn, "before_cursor_execute")
def go(conn, cursor, statement, parameters, context, executemany):
nonlocal insert_count
if statement.startswith("INSERT"):
insert_count += 1
stmt = t.insert()
if batchsize is None or paramtype == "engine":
conn.execute(stmt.returning(t.c.id), data)
elif paramtype == "conn_execution_option":
conn = conn.execution_options(
insertmanyvalues_page_size=batchsize
)
conn.execute(stmt.returning(t.c.id), data)
elif paramtype == "stmt_execution_option":
stmt = stmt.execution_options(
insertmanyvalues_page_size=batchsize
)
conn.execute(stmt.returning(t.c.id), data)
elif paramtype == "exec_execution_option":
conn.execute(
stmt.returning(t.c.id),
data,
execution_options=dict(
insertmanyvalues_page_size=batchsize
),
)
else:
assert False
assert_batchsize = batchsize or 1000
eq_(
insert_count,
totalnum // assert_batchsize
+ (1 if totalnum % assert_batchsize else 0),
)
def test_disabled(self, testing_engine):
e = testing_engine(
options={"use_insertmanyvalues": False},
share_pool=True,
transfer_staticpool=True,
)
totalnum = 1275
data = [{"x": "x%d" % i, "y": "y%d" % i} for i in range(1, totalnum)]
t = self.tables.data
with e.begin() as conn:
stmt = t.insert()
with expect_raises_message(
exc.StatementError,
"with current server capabilities does not support "
"INSERT..RETURNING when executemany",
):
conn.execute(stmt.returning(t.c.id), data)
class IMVSentinelTest(fixtures.TestBase):
__backend__ = True
__requires__ = ("insert_returning",)
def _expect_downgrade_warnings(
self,
*,
warn_for_downgrades,
sort_by_parameter_order,
separate_sentinel=False,
server_autoincrement=False,
client_side_pk=False,
autoincrement_is_sequence=False,
connection=None,
):
if connection:
dialect = connection.dialect
else:
dialect = testing.db.dialect
if (
sort_by_parameter_order
and warn_for_downgrades
and dialect.use_insertmanyvalues
):
if (
not separate_sentinel
and (
server_autoincrement
and (
not (
dialect.insertmanyvalues_implicit_sentinel # noqa: E501
& InsertmanyvaluesSentinelOpts.ANY_AUTOINCREMENT
)
or (
autoincrement_is_sequence
and not (
dialect.insertmanyvalues_implicit_sentinel # noqa: E501
& InsertmanyvaluesSentinelOpts.SEQUENCE
)
)
)
)
or (
not separate_sentinel
and not server_autoincrement
and not client_side_pk
)
):
return expect_warnings(
"Batches were downgraded",
)
return contextlib.nullcontext()
@testing.variation
def sort_by_parameter_order(self):
return [True, False]
@testing.variation
def warn_for_downgrades(self):
return [True, False]
@testing.variation
def randomize_returning(self):
return [True, False]
@testing.requires.insertmanyvalues
def test_fixture_randomizing(self, connection, metadata):
t = Table(
"t",
metadata,
Column("id", Integer, Identity(), primary_key=True),
Column("data", String(50)),
)
metadata.create_all(connection)
insertmanyvalues_fixture(connection, randomize_rows=True)
results = set()
for i in range(15):
result = connection.execute(
insert(t).returning(t.c.data, sort_by_parameter_order=False),
[{"data": "d1"}, {"data": "d2"}, {"data": "d3"}],
)
hashed_result = tuple(result.all())
results.add(hashed_result)
if len(results) > 1:
return
else:
assert False, "got same order every time for 15 tries"
@testing.only_on("postgresql>=13")
@testing.variation("downgrade", [True, False])
def test_fixture_downgraded(self, connection, metadata, downgrade):
t = Table(
"t",
metadata,
Column(
"id",
Uuid(),
server_default=func.gen_random_uuid(),
primary_key=True,
),
Column("data", String(50)),
)
metadata.create_all(connection)
r1 = connection.execute(
insert(t).returning(t.c.data, sort_by_parameter_order=True),
[{"data": "d1"}, {"data": "d2"}, {"data": "d3"}],
)
eq_(r1.all(), [("d1",), ("d2",), ("d3",)])
if downgrade:
insertmanyvalues_fixture(connection, warn_on_downgraded=True)
with self._expect_downgrade_warnings(
warn_for_downgrades=True,
sort_by_parameter_order=True,
):
connection.execute(
insert(t).returning(
t.c.data, sort_by_parameter_order=True
),
[{"data": "d1"}, {"data": "d2"}, {"data": "d3"}],
)
else:
# run a plain test to help ensure the fixture doesn't leak to
# other tests
r1 = connection.execute(
insert(t).returning(t.c.data, sort_by_parameter_order=True),
[{"data": "d1"}, {"data": "d2"}, {"data": "d3"}],
)
eq_(r1.all(), [("d1",), ("d2",), ("d3",)])
@testing.variation(
"sequence_type",
[
("sequence", testing.requires.sequences),
("identity", testing.requires.identity_columns),
],
)
@testing.variation("increment", ["positive", "negative", "implicit"])
@testing.variation("explicit_sentinel", [True, False])
def test_invalid_identities(
self,
metadata,
connection,
warn_for_downgrades,
randomize_returning,
sort_by_parameter_order,
sequence_type: testing.Variation,
increment: testing.Variation,
explicit_sentinel,
):
if sequence_type.sequence:
seq_cls = functools.partial(Sequence, name="t1_id_seq")
elif sequence_type.identity:
seq_cls = Identity
else:
sequence_type.fail()
if increment.implicit:
sequence = seq_cls(start=1)
elif increment.positive:
sequence = seq_cls(start=1, increment=1)
elif increment.negative:
sequence = seq_cls(start=-1, increment=-1)
else:
increment.fail()
t1 = Table(
"t1",
metadata,
Column(
"id",
Integer,
sequence,
primary_key=True,
insert_sentinel=bool(explicit_sentinel),
),
Column("data", String(50)),
)
metadata.create_all(connection)
fixtures.insertmanyvalues_fixture(
connection,
randomize_rows=bool(randomize_returning),
warn_on_downgraded=bool(warn_for_downgrades),
)
stmt = insert(t1).returning(
t1.c.id,
t1.c.data,
sort_by_parameter_order=bool(sort_by_parameter_order),
)
data = [{"data": f"d{i}"} for i in range(10)]
use_imv = testing.db.dialect.use_insertmanyvalues
if (
use_imv
and increment.negative
and explicit_sentinel
and sort_by_parameter_order
):
with expect_raises_message(
exc.InvalidRequestError,
rf"Can't use "
rf"{'SEQUENCE' if sequence_type.sequence else 'IDENTITY'} "
rf"default with negative increment",
):
connection.execute(stmt, data)
return
elif (
use_imv
and explicit_sentinel
and sort_by_parameter_order
and sequence_type.sequence
and not (
testing.db.dialect.insertmanyvalues_implicit_sentinel
& InsertmanyvaluesSentinelOpts.SEQUENCE
)
):
with expect_raises_message(
exc.InvalidRequestError,
r"Column t1.id can't be explicitly marked as a sentinel "
r"column .* as the particular type of default generation",
):
connection.execute(stmt, data)
return
with self._expect_downgrade_warnings(
warn_for_downgrades=warn_for_downgrades,
sort_by_parameter_order=sort_by_parameter_order,
server_autoincrement=not increment.negative,
autoincrement_is_sequence=sequence_type.sequence,
):
result = connection.execute(stmt, data)
if sort_by_parameter_order:
coll = list
else:
coll = set
if increment.negative:
expected_data = [(-1 - i, f"d{i}") for i in range(10)]
else:
expected_data = [(i + 1, f"d{i}") for i in range(10)]
eq_(
coll(result),
coll(expected_data),
)
@testing.requires.sequences
@testing.variation("explicit_sentinel", [True, False])
@testing.variation("sequence_actually_translates", [True, False])
@testing.variation("the_table_translates", [True, False])
def test_sequence_schema_translate(
self,
metadata,
connection,
explicit_sentinel,
warn_for_downgrades,
randomize_returning,
sort_by_parameter_order,
sequence_actually_translates,
the_table_translates,
):
"""test #11157"""
# so there's a bit of a bug which is that functions has_table()
# and has_sequence() do not take schema translate map into account,
# at all. So on MySQL, where we dont have transactional DDL, the
# DROP for Table / Sequence does not really work for all test runs
# when the schema is set to a "to be translated" kind of name.
# so, make a Table/Sequence with fixed schema name for the CREATE,
# then use a different object for the test that has a translate
# schema name
Table(
"t1",
metadata,
Column(
"id",
Integer,
Sequence("some_seq", start=1, schema=config.test_schema),
primary_key=True,
insert_sentinel=bool(explicit_sentinel),
),
Column("data", String(50)),
schema=config.test_schema if the_table_translates else None,
)
metadata.create_all(connection)
if sequence_actually_translates:
connection = connection.execution_options(
schema_translate_map={
"should_be_translated": config.test_schema
}
)
sequence = Sequence(
"some_seq", start=1, schema="should_be_translated"
)
else:
connection = connection.execution_options(
schema_translate_map={"foo": "bar"}
)
sequence = Sequence("some_seq", start=1, schema=config.test_schema)
m2 = MetaData()
t1 = Table(
"t1",
m2,
Column(
"id",
Integer,
sequence,
primary_key=True,
insert_sentinel=bool(explicit_sentinel),
),
Column("data", String(50)),
schema=(
"should_be_translated"
if sequence_actually_translates and the_table_translates
else config.test_schema if the_table_translates else None
),
)
fixtures.insertmanyvalues_fixture(
connection,
randomize_rows=bool(randomize_returning),
warn_on_downgraded=bool(warn_for_downgrades),
)
stmt = insert(t1).returning(
t1.c.id,
t1.c.data,
sort_by_parameter_order=bool(sort_by_parameter_order),
)
data = [{"data": f"d{i}"} for i in range(10)]
use_imv = testing.db.dialect.use_insertmanyvalues
if (
use_imv
and explicit_sentinel
and sort_by_parameter_order
and not (
testing.db.dialect.insertmanyvalues_implicit_sentinel
& InsertmanyvaluesSentinelOpts.SEQUENCE
)
):
with expect_raises_message(
exc.InvalidRequestError,
r"Column t1.id can't be explicitly marked as a sentinel "
r"column .* as the particular type of default generation",
):
connection.execute(stmt, data)
return
with self._expect_downgrade_warnings(
warn_for_downgrades=warn_for_downgrades,
sort_by_parameter_order=sort_by_parameter_order,
server_autoincrement=True,
autoincrement_is_sequence=True,
):
result = connection.execute(stmt, data)
if sort_by_parameter_order:
coll = list
else:
coll = set
expected_data = [(i + 1, f"d{i}") for i in range(10)]
eq_(
coll(result),
coll(expected_data),
)
@testing.combinations(
Integer(),
String(50),
(ARRAY(Integer()), testing.requires.array_type),
DateTime(),
Uuid(),
Uuid(native_uuid=False),
argnames="datatype",
)
def test_inserts_w_all_nulls(
self, connection, metadata, sort_by_parameter_order, datatype
):
"""this test is geared towards the INSERT..SELECT VALUES case,
where if the VALUES have all NULL for some column, PostgreSQL assumes
the datatype must be TEXT and throws for other table datatypes. So an
additional layer of casts is applied to the SELECT p0,p1, p2... part of
the statement for all datatypes unconditionally. Even though the VALUES
clause also has bind casts for selected datatypes, this NULL handling
is needed even for simple datatypes. We'd prefer not to render bind
casts for all possible datatypes as that affects other kinds of
statements as well and also is very verbose for insertmanyvalues.
"""
t = Table(
"t",
metadata,
Column("id", Integer, Identity(), primary_key=True),
Column("data", datatype),
)
metadata.create_all(connection)
result = connection.execute(
insert(t).returning(
t.c.id,
sort_by_parameter_order=bool(sort_by_parameter_order),
),
[{"data": None}, {"data": None}, {"data": None}],
)
eq_(set(result), {(1,), (2,), (3,)})
@testing.variation("pk_type", ["autoinc", "clientside"])
@testing.variation("add_sentinel", ["none", "clientside", "sentinel"])
def test_imv_w_additional_values(
self,
metadata,
connection,
sort_by_parameter_order,
pk_type: testing.Variation,
randomize_returning,
warn_for_downgrades,
add_sentinel,
):
if pk_type.autoinc:
pk_col = Column("id", Integer(), Identity(), primary_key=True)
elif pk_type.clientside:
pk_col = Column("id", Uuid(), default=uuid.uuid4, primary_key=True)
else:
pk_type.fail()
if add_sentinel.clientside:
extra_col = insert_sentinel(
"sentinel", type_=Uuid(), default=uuid.uuid4
)
elif add_sentinel.sentinel:
extra_col = insert_sentinel("sentinel")
else:
extra_col = Column("sentinel", Integer())
t1 = Table(
"t1",
metadata,
pk_col,
Column("data", String(30)),
Column("moredata", String(30)),
extra_col,
Column(
"has_server_default",
String(50),
server_default="some_server_default",
),
)
metadata.create_all(connection)
fixtures.insertmanyvalues_fixture(
connection,
randomize_rows=bool(randomize_returning),
warn_on_downgraded=bool(warn_for_downgrades),
)
stmt = (
insert(t1)
.values(moredata="more data")
.returning(
t1.c.data,
t1.c.moredata,
t1.c.has_server_default,
sort_by_parameter_order=bool(sort_by_parameter_order),
)
)
data = [{"data": f"d{i}"} for i in range(10)]
with self._expect_downgrade_warnings(
warn_for_downgrades=warn_for_downgrades,
sort_by_parameter_order=sort_by_parameter_order,
separate_sentinel=not add_sentinel.none,
server_autoincrement=pk_type.autoinc,
client_side_pk=pk_type.clientside,
):
result = connection.execute(stmt, data)
if sort_by_parameter_order:
coll = list
else:
coll = set
eq_(
coll(result),
coll(
[
(f"d{i}", "more data", "some_server_default")
for i in range(10)
]
),
)
def test_sentinel_incorrect_rowcount(
self, metadata, connection, sort_by_parameter_order
):
"""test assertions to ensure sentinel values don't have duplicates"""
uuids = [uuid.uuid4() for i in range(10)]
# make some dupes
uuids[3] = uuids[5]
uuids[9] = uuids[5]
t1 = Table(
"data",
metadata,
Column("id", Integer, Identity(), primary_key=True),
Column("data", String(50)),
insert_sentinel(
"uuids",
Uuid(),
default=functools.partial(next, iter(uuids)),
),
)
metadata.create_all(connection)
stmt = insert(t1).returning(
t1.c.data,
t1.c.uuids,
sort_by_parameter_order=bool(sort_by_parameter_order),
)
data = [{"data": f"d{i}"} for i in range(10)]
if testing.db.dialect.use_insertmanyvalues and sort_by_parameter_order:
with expect_raises_message(
exc.InvalidRequestError,
"Sentinel-keyed result set did not produce correct "
"number of rows 10; produced 8.",
):
connection.execute(stmt, data)
else:
result = connection.execute(stmt, data)
eq_(
set(result.all()),
{(f"d{i}", uuids[i]) for i in range(10)},
)
@testing.variation("resolve_sentinel_values", [True, False])
def test_sentinel_cant_match_keys(
self,
metadata,
connection,
sort_by_parameter_order,
resolve_sentinel_values,
):
"""test assertions to ensure sentinel values passed in parameter
structures can be identified when they come back in cursor.fetchall().
Sentinels are now matched based on the data on the outside of the
type, that is, before the bind, and after the result.
"""
class UnsymmetricDataType(TypeDecorator):
cache_ok = True
impl = String
def bind_expression(self, bindparam):
return func.lower(bindparam)
if resolve_sentinel_values:
def process_result_value(self, value, dialect):
return value.replace("upper", "UPPER")
t1 = Table(
"data",
metadata,
Column("id", Integer, Identity(), primary_key=True),
Column("data", String(50)),
insert_sentinel("unsym", UnsymmetricDataType(10)),
)
metadata.create_all(connection)
stmt = insert(t1).returning(
t1.c.data,
t1.c.unsym,
sort_by_parameter_order=bool(sort_by_parameter_order),
)
data = [{"data": f"d{i}", "unsym": f"UPPER_d{i}"} for i in range(10)]
if (
testing.db.dialect.use_insertmanyvalues
and sort_by_parameter_order
and not resolve_sentinel_values
):
with expect_raises_message(
exc.InvalidRequestError,
r"Can't match sentinel values in result set to parameter "
r"sets; key 'UPPER_d.' was not found.",
):
connection.execute(stmt, data)
else:
result = connection.execute(stmt, data)
if resolve_sentinel_values:
eq_(
set(result.all()),
{(f"d{i}", f"UPPER_d{i}") for i in range(10)},
)
else:
eq_(
set(result.all()),
{(f"d{i}", f"upper_d{i}") for i in range(10)},
)
@testing.variation("add_insert_sentinel", [True, False])
def test_sentinel_insert_default_pk_only(
self,
metadata,
connection,
sort_by_parameter_order,
add_insert_sentinel,
):
t1 = Table(
"data",
metadata,
Column(
"id",
Integer,
Identity(),
insert_sentinel=bool(add_insert_sentinel),
primary_key=True,
),
Column("data", String(50)),
)
metadata.create_all(connection)
fixtures.insertmanyvalues_fixture(
connection, randomize_rows=True, warn_on_downgraded=False
)
stmt = insert(t1).returning(
t1.c.id,
sort_by_parameter_order=bool(sort_by_parameter_order),
)
data = [{} for i in range(3)]
if (
testing.db.dialect.use_insertmanyvalues
and add_insert_sentinel
and sort_by_parameter_order
and not (
testing.db.dialect.insertmanyvalues_implicit_sentinel
& InsertmanyvaluesSentinelOpts.ANY_AUTOINCREMENT
)
):
with expect_raises_message(
exc.InvalidRequestError,
"Column data.id can't be explicitly marked as a "
f"sentinel column when using the {testing.db.dialect.name} "
"dialect",
):
connection.execute(stmt, data)
return
else:
result = connection.execute(stmt, data)
if sort_by_parameter_order:
# if we used a client side default function, or we had no sentinel
# at all, we're sorted
coll = list
else:
# otherwise we are not, we randomized the order in any case
coll = set
eq_(
coll(result),
coll(
[
(1,),
(2,),
(3,),
]
),
)
@testing.only_on("postgresql>=13")
@testing.variation("default_type", ["server_side", "client_side"])
@testing.variation("add_insert_sentinel", [True, False])
def test_no_sentinel_on_non_int_ss_function(
self,
metadata,
connection,
add_insert_sentinel,
default_type,
sort_by_parameter_order,
):
t1 = Table(
"data",
metadata,
Column(
"id",
Uuid(),
server_default=(
func.gen_random_uuid()
if default_type.server_side
else None
),
default=uuid.uuid4 if default_type.client_side else None,
primary_key=True,
insert_sentinel=bool(add_insert_sentinel),
),
Column("data", String(50)),
)
metadata.create_all(connection)
fixtures.insertmanyvalues_fixture(
connection, randomize_rows=True, warn_on_downgraded=False
)
stmt = insert(t1).returning(
t1.c.data,
sort_by_parameter_order=bool(sort_by_parameter_order),
)
data = [
{"data": "d1"},
{"data": "d2"},
{"data": "d3"},
]
if (
default_type.server_side
and add_insert_sentinel
and sort_by_parameter_order
):
with expect_raises_message(
exc.InvalidRequestError,
r"Column data.id can't be a sentinel column because it uses "
r"an explicit server side default that's not the Identity\(\)",
):
connection.execute(stmt, data)
return
else:
result = connection.execute(stmt, data)
if sort_by_parameter_order:
# if we used a client side default function, or we had no sentinel
# at all, we're sorted
coll = list
else:
# otherwise we are not, we randomized the order in any case
coll = set
eq_(
coll(result),
coll(
[
("d1",),
("d2",),
("d3",),
]
),
)
@testing.variation(
"pk_type",
[
("plain_autoinc", testing.requires.autoincrement_without_sequence),
("sequence", testing.requires.sequences),
("identity", testing.requires.identity_columns),
],
)
@testing.variation(
"sentinel",
[
"none", # passes because we automatically downgrade
# for no sentinel col
"implicit_not_omitted",
"implicit_omitted",
"explicit",
"explicit_but_nullable",
"default_uuid",
"default_string_uuid",
("identity", testing.requires.multiple_identity_columns),
("sequence", testing.requires.sequences),
],
)
def test_sentinel_col_configurations(
self,
pk_type: testing.Variation,
sentinel: testing.Variation,
sort_by_parameter_order,
randomize_returning,
metadata,
connection,
):
if pk_type.plain_autoinc:
pk_col = Column("id", Integer, primary_key=True)
elif pk_type.sequence:
pk_col = Column(
"id",
Integer,
Sequence("result_id_seq", start=1),
primary_key=True,
)
elif pk_type.identity:
pk_col = Column("id", Integer, Identity(), primary_key=True)
else:
pk_type.fail()
if sentinel.implicit_not_omitted or sentinel.implicit_omitted:
_sentinel = insert_sentinel(
"sentinel",
omit_from_statements=bool(sentinel.implicit_omitted),
)
elif sentinel.explicit:
_sentinel = Column(
"some_uuid", Uuid(), nullable=False, insert_sentinel=True
)
elif sentinel.explicit_but_nullable:
_sentinel = Column("some_uuid", Uuid(), insert_sentinel=True)
elif sentinel.default_uuid or sentinel.default_string_uuid:
_sentinel = Column(
"some_uuid",
Uuid(native_uuid=bool(sentinel.default_uuid)),
insert_sentinel=True,
default=uuid.uuid4,
)
elif sentinel.identity:
_sentinel = Column(
"some_identity",
Integer,
Identity(),
insert_sentinel=True,
)
elif sentinel.sequence:
_sentinel = Column(
"some_identity",
Integer,
Sequence("some_id_seq", start=1),
insert_sentinel=True,
)
else:
_sentinel = Column("some_uuid", Uuid())
t = Table("t", metadata, pk_col, Column("data", String(50)), _sentinel)
metadata.create_all(connection)
fixtures.insertmanyvalues_fixture(
connection,
randomize_rows=bool(randomize_returning),
warn_on_downgraded=True,
)
stmt = insert(t).returning(
pk_col,
t.c.data,
sort_by_parameter_order=bool(sort_by_parameter_order),
)
if sentinel.explicit:
data = [
{"data": f"d{i}", "some_uuid": uuid.uuid4()}
for i in range(150)
]
else:
data = [{"data": f"d{i}"} for i in range(150)]
expect_sentinel_use = (
sort_by_parameter_order
and testing.db.dialect.insert_returning
and testing.db.dialect.use_insertmanyvalues
)
if sentinel.explicit_but_nullable and expect_sentinel_use:
with expect_raises_message(
exc.InvalidRequestError,
"Column t.some_uuid has been marked as a sentinel column "
"with no default generation function; it at least needs to "
"be marked nullable=False",
):
connection.execute(stmt, data)
return
elif (
expect_sentinel_use
and sentinel.sequence
and not (
testing.db.dialect.insertmanyvalues_implicit_sentinel
& InsertmanyvaluesSentinelOpts.SEQUENCE
)
):
with expect_raises_message(
exc.InvalidRequestError,
"Column t.some_identity can't be explicitly marked as a "
f"sentinel column when using the {testing.db.dialect.name} "
"dialect",
):
connection.execute(stmt, data)
return
elif (
sentinel.none
and expect_sentinel_use
and stmt.compile(
dialect=testing.db.dialect
)._get_sentinel_column_for_table(t)
is None
):
with expect_warnings(
"Batches were downgraded for sorted INSERT",
):
result = connection.execute(stmt, data)
else:
result = connection.execute(stmt, data)
if sort_by_parameter_order:
eq_(list(result), [(i + 1, f"d{i}") for i in range(150)])
else:
eq_(set(result), {(i + 1, f"d{i}") for i in range(150)})
@testing.variation(
"return_type", ["include_sentinel", "default_only", "return_defaults"]
)
@testing.variation("add_sentinel_flag_to_col", [True, False])
@testing.variation("native_uuid", [True, False])
@testing.variation("as_uuid", [True, False])
def test_sentinel_on_non_autoinc_primary_key(
self,
metadata,
connection,
return_type: testing.Variation,
sort_by_parameter_order,
randomize_returning,
add_sentinel_flag_to_col,
native_uuid,
as_uuid,
):
uuids = [uuid.uuid4() for i in range(10)]
if not as_uuid:
uuids = [str(u) for u in uuids]
_some_uuids = iter(uuids)
t1 = Table(
"data",
metadata,
Column(
"id",
Uuid(native_uuid=bool(native_uuid), as_uuid=bool(as_uuid)),
default=functools.partial(next, _some_uuids),
primary_key=True,
insert_sentinel=bool(add_sentinel_flag_to_col),
),
Column("data", String(50)),
Column(
"has_server_default",
String(30),
server_default="some_server_default",
),
)
fixtures.insertmanyvalues_fixture(
connection,
randomize_rows=bool(randomize_returning),
warn_on_downgraded=True,
)
if sort_by_parameter_order:
collection_cls = list
else:
collection_cls = set
metadata.create_all(connection)
if sort_by_parameter_order:
kw = {"sort_by_parameter_order": True}
else:
kw = {}
if return_type.include_sentinel:
stmt = t1.insert().returning(
t1.c.id, t1.c.data, t1.c.has_server_default, **kw
)
elif return_type.default_only:
stmt = t1.insert().returning(
t1.c.data, t1.c.has_server_default, **kw
)
elif return_type.return_defaults:
stmt = t1.insert().return_defaults(**kw)
else:
return_type.fail()
r = connection.execute(
stmt,
[{"data": f"d{i}"} for i in range(1, 6)],
)
if return_type.include_sentinel:
eq_(r.keys(), ["id", "data", "has_server_default"])
eq_(
collection_cls(r),
collection_cls(
[
(uuids[i], f"d{i + 1}", "some_server_default")
for i in range(5)
]
),
)
elif return_type.default_only:
eq_(r.keys(), ["data", "has_server_default"])
eq_(
collection_cls(r),
collection_cls(
[
(
f"d{i + 1}",
"some_server_default",
)
for i in range(5)
]
),
)
elif return_type.return_defaults:
eq_(r.keys(), ["has_server_default"])
eq_(r.inserted_primary_key_rows, [(uuids[i],) for i in range(5)])
eq_(
r.returned_defaults_rows,
[
("some_server_default",),
("some_server_default",),
("some_server_default",),
("some_server_default",),
("some_server_default",),
],
)
eq_(r.all(), [])
else:
return_type.fail()
@testing.variation("native_uuid", [True, False])
@testing.variation("as_uuid", [True, False])
def test_client_composite_pk(
self,
metadata,
connection,
randomize_returning,
sort_by_parameter_order,
warn_for_downgrades,
native_uuid,
as_uuid,
):
uuids = [uuid.uuid4() for i in range(10)]
if not as_uuid:
uuids = [str(u) for u in uuids]
t1 = Table(
"data",
metadata,
Column(
"id1",
Uuid(as_uuid=bool(as_uuid), native_uuid=bool(native_uuid)),
default=functools.partial(next, iter(uuids)),
primary_key=True,
),
Column(
"id2",
# note this is testing that plain populated PK cols
# also qualify as sentinels since they have to be there
String(30),
primary_key=True,
),
Column("data", String(50)),
Column(
"has_server_default",
String(30),
server_default="some_server_default",
),
)
metadata.create_all(connection)
fixtures.insertmanyvalues_fixture(
connection,
randomize_rows=bool(randomize_returning),
warn_on_downgraded=bool(warn_for_downgrades),
)
result = connection.execute(
insert(t1).returning(
t1.c.id1,
t1.c.id2,
t1.c.data,
t1.c.has_server_default,
sort_by_parameter_order=bool(sort_by_parameter_order),
),
[{"id2": f"id{i}", "data": f"d{i}"} for i in range(10)],
)
if sort_by_parameter_order:
coll = list
else:
coll = set
eq_(
coll(result),
coll(
[
(uuids[i], f"id{i}", f"d{i}", "some_server_default")
for i in range(10)
]
),
)
@testing.variation("add_sentinel", [True, False])
@testing.variation(
"set_identity", [(True, testing.requires.identity_columns), False]
)
def test_no_pk(
self,
metadata,
connection,
randomize_returning,
sort_by_parameter_order,
warn_for_downgrades,
add_sentinel,
set_identity,
):
if set_identity:
id_col = Column("id", Integer(), Identity())
else:
id_col = Column("id", Integer())
uuids = [uuid.uuid4() for i in range(10)]
sentinel_col = Column(
"unique_id",
Uuid,
default=functools.partial(next, iter(uuids)),
insert_sentinel=bool(add_sentinel),
)
t1 = Table(
"nopk",
metadata,
id_col,
Column("data", String(50)),
sentinel_col,
Column(
"has_server_default",
String(30),
server_default="some_server_default",
),
)
metadata.create_all(connection)
fixtures.insertmanyvalues_fixture(
connection,
randomize_rows=bool(randomize_returning),
warn_on_downgraded=bool(warn_for_downgrades),
)
stmt = insert(t1).returning(
t1.c.id,
t1.c.data,
t1.c.has_server_default,
sort_by_parameter_order=bool(sort_by_parameter_order),
)
if not set_identity:
data = [{"id": i + 1, "data": f"d{i}"} for i in range(10)]
else:
data = [{"data": f"d{i}"} for i in range(10)]
with self._expect_downgrade_warnings(
warn_for_downgrades=warn_for_downgrades,
sort_by_parameter_order=sort_by_parameter_order,
separate_sentinel=add_sentinel,
):
result = connection.execute(stmt, data)
if sort_by_parameter_order:
coll = list
else:
coll = set
eq_(
coll(result),
coll([(i + 1, f"d{i}", "some_server_default") for i in range(10)]),
)
@testing.variation("add_sentinel_to_col", [True, False])
@testing.variation(
"set_autoincrement", [True, (False, testing.skip_if("mariadb"))]
)
def test_hybrid_client_composite_pk(
self,
metadata,
connection,
randomize_returning,
sort_by_parameter_order,
warn_for_downgrades,
add_sentinel_to_col,
set_autoincrement,
):
"""test a pk that is part server generated part client generated.
The server generated col by itself can be the sentinel. if it's
part of the PK and is autoincrement=True then it is automatically
used as such. if not, there's a graceful downgrade.
"""
t1 = Table(
"data",
metadata,
Column(
"idint",
Integer,
Identity(),
autoincrement=True if set_autoincrement else "auto",
primary_key=True,
insert_sentinel=bool(add_sentinel_to_col),
),
Column(
"idstr",
String(30),
primary_key=True,
),
Column("data", String(50)),
Column(
"has_server_default",
String(30),
server_default="some_server_default",
),
)
no_autoincrement = (
not testing.requires.supports_autoincrement_w_composite_pk.enabled # noqa: E501
)
if set_autoincrement and no_autoincrement:
with expect_raises_message(
exc.CompileError,
r".*SQLite does not support autoincrement for "
"composite primary keys",
):
metadata.create_all(connection)
return
else:
metadata.create_all(connection)
fixtures.insertmanyvalues_fixture(
connection,
randomize_rows=bool(randomize_returning),
warn_on_downgraded=bool(warn_for_downgrades),
)
stmt = insert(t1).returning(
t1.c.idint,
t1.c.idstr,
t1.c.data,
t1.c.has_server_default,
sort_by_parameter_order=bool(sort_by_parameter_order),
)
if no_autoincrement:
data = [
{"idint": i + 1, "idstr": f"id{i}", "data": f"d{i}"}
for i in range(10)
]
else:
data = [{"idstr": f"id{i}", "data": f"d{i}"} for i in range(10)]
if (
testing.db.dialect.use_insertmanyvalues
and add_sentinel_to_col
and sort_by_parameter_order
and not (
testing.db.dialect.insertmanyvalues_implicit_sentinel
& InsertmanyvaluesSentinelOpts.ANY_AUTOINCREMENT
)
):
with expect_raises_message(
exc.InvalidRequestError,
"Column data.idint can't be explicitly marked as a sentinel "
"column when using the sqlite dialect",
):
result = connection.execute(stmt, data)
return
with self._expect_downgrade_warnings(
warn_for_downgrades=warn_for_downgrades,
sort_by_parameter_order=sort_by_parameter_order,
separate_sentinel=not set_autoincrement and add_sentinel_to_col,
server_autoincrement=set_autoincrement,
):
result = connection.execute(stmt, data)
if sort_by_parameter_order:
coll = list
else:
coll = set
eq_(
coll(result),
coll(
[
(i + 1, f"id{i}", f"d{i}", "some_server_default")
for i in range(10)
]
),
)
@testing.variation("composite_pk", [True, False])
@testing.only_on(
[
"+psycopg",
"+psycopg2",
"+pysqlite",
"+mysqlclient",
"+cx_oracle",
"+oracledb",
]
)
def test_failure_mode_if_i_dont_send_value(
self, metadata, connection, sort_by_parameter_order, composite_pk
):
"""test that we get a regular integrity error if a required
PK value was not sent, that is, imv does not get in the way
"""
t1 = Table(
"data",
metadata,
Column("id", String(30), primary_key=True),
Column("data", String(50)),
Column(
"has_server_default",
String(30),
server_default="some_server_default",
),
)
if composite_pk:
t1.append_column(Column("uid", Uuid(), default=uuid.uuid4))
metadata.create_all(connection)
with expect_warnings(
r".*but has no Python-side or server-side default ",
):
with expect_raises(exc.IntegrityError):
connection.execute(
insert(t1).returning(
t1.c.id,
t1.c.data,
t1.c.has_server_default,
sort_by_parameter_order=bool(sort_by_parameter_order),
),
[{"data": f"d{i}"} for i in range(10)],
)
@testing.variation("add_sentinel_flag_to_col", [True, False])
@testing.variation(
"return_type", ["include_sentinel", "default_only", "return_defaults"]
)
@testing.variation(
"sentinel_type",
[
("autoincrement", testing.requires.autoincrement_without_sequence),
"identity",
"sequence",
],
)
def test_implicit_autoincrement_sentinel(
self,
metadata,
connection,
return_type: testing.Variation,
sort_by_parameter_order,
randomize_returning,
sentinel_type,
add_sentinel_flag_to_col,
):
if sentinel_type.identity:
sentinel_args = [Identity()]
elif sentinel_type.sequence:
sentinel_args = [Sequence("id_seq", start=1)]
else:
sentinel_args = []
t1 = Table(
"data",
metadata,
Column(
"id",
Integer,
*sentinel_args,
primary_key=True,
insert_sentinel=bool(add_sentinel_flag_to_col),
),
Column("data", String(50)),
Column(
"has_server_default",
String(30),
server_default="some_server_default",
),
)
fixtures.insertmanyvalues_fixture(
connection,
randomize_rows=bool(randomize_returning),
warn_on_downgraded=False,
)
if sort_by_parameter_order:
collection_cls = list
else:
collection_cls = set
metadata.create_all(connection)
if sort_by_parameter_order:
kw = {"sort_by_parameter_order": True}
else:
kw = {}
if return_type.include_sentinel:
stmt = t1.insert().returning(
t1.c.id, t1.c.data, t1.c.has_server_default, **kw
)
elif return_type.default_only:
stmt = t1.insert().returning(
t1.c.data, t1.c.has_server_default, **kw
)
elif return_type.return_defaults:
stmt = t1.insert().return_defaults(**kw)
else:
return_type.fail()
if (
testing.db.dialect.use_insertmanyvalues
and add_sentinel_flag_to_col
and sort_by_parameter_order
and (
not (
testing.db.dialect.insertmanyvalues_implicit_sentinel
& InsertmanyvaluesSentinelOpts.ANY_AUTOINCREMENT
)
or (
# currently a SQL Server case, we dont yet render a
# syntax for SQL Server sequence w/ deterministic
# ordering. The INSERT..SELECT could be restructured
# further to support this at a later time however
# sequences with SQL Server are very unusual.
sentinel_type.sequence
and not (
testing.db.dialect.insertmanyvalues_implicit_sentinel
& InsertmanyvaluesSentinelOpts.SEQUENCE
)
)
)
):
with expect_raises_message(
exc.InvalidRequestError,
"Column data.id can't be explicitly marked as a "
f"sentinel column when using the {testing.db.dialect.name} "
"dialect",
):
connection.execute(
stmt,
[{"data": f"d{i}"} for i in range(1, 6)],
)
return
else:
r = connection.execute(
stmt,
[{"data": f"d{i}"} for i in range(1, 6)],
)
if return_type.include_sentinel:
eq_(r.keys(), ["id", "data", "has_server_default"])
eq_(
collection_cls(r),
collection_cls(
[(i, f"d{i}", "some_server_default") for i in range(1, 6)]
),
)
elif return_type.default_only:
eq_(r.keys(), ["data", "has_server_default"])
eq_(
collection_cls(r),
collection_cls(
[(f"d{i}", "some_server_default") for i in range(1, 6)]
),
)
elif return_type.return_defaults:
eq_(r.keys(), ["id", "has_server_default"])
eq_(
collection_cls(r.inserted_primary_key_rows),
collection_cls([(i + 1,) for i in range(5)]),
)
eq_(
collection_cls(r.returned_defaults_rows),
collection_cls(
[
(
1,
"some_server_default",
),
(
2,
"some_server_default",
),
(
3,
"some_server_default",
),
(
4,
"some_server_default",
),
(
5,
"some_server_default",
),
]
),
)
eq_(r.all(), [])
else:
return_type.fail()
@testing.variation("pk_type", ["serverside", "clientside"])
@testing.variation(
"sentinel_type",
[
"use_pk",
("use_pk_explicit", testing.skip_if("sqlite")),
"separate_uuid",
"separate_sentinel",
],
)
@testing.requires.provisioned_upsert
def test_upsert_downgrades(
self,
metadata,
connection,
pk_type: testing.Variation,
sort_by_parameter_order,
randomize_returning,
sentinel_type,
warn_for_downgrades,
):
if pk_type.serverside:
pk_col = Column(
"id",
Integer(),
primary_key=True,
insert_sentinel=bool(sentinel_type.use_pk_explicit),
)
elif pk_type.clientside:
pk_col = Column(
"id",
Uuid(),
default=uuid.uuid4,
primary_key=True,
insert_sentinel=bool(sentinel_type.use_pk_explicit),
)
else:
pk_type.fail()
if sentinel_type.separate_uuid:
extra_col = Column(
"sent_col",
Uuid(),
default=uuid.uuid4,
insert_sentinel=True,
nullable=False,
)
elif sentinel_type.separate_sentinel:
extra_col = insert_sentinel("sent_col")
else:
extra_col = Column("sent_col", Integer)
t1 = Table(
"upsert_table",
metadata,
pk_col,
Column("data", String(50)),
extra_col,
Column(
"has_server_default",
String(30),
server_default="some_server_default",
),
)
metadata.create_all(connection)
result = connection.execute(
insert(t1).returning(
t1.c.id, t1.c.data, sort_by_parameter_order=True
),
[{"data": "d1"}, {"data": "d2"}],
)
d1d2 = list(result)
if pk_type.serverside:
new_ids = [10, 15, 3]
elif pk_type.clientside:
new_ids = [uuid.uuid4() for i in range(3)]
else:
pk_type.fail()
upsert_data = [
{"id": d1d2[0][0], "data": "d1 new"},
{"id": new_ids[0], "data": "d10"},
{"id": new_ids[1], "data": "d15"},
{"id": d1d2[1][0], "data": "d2 new"},
{"id": new_ids[2], "data": "d3"},
]
fixtures.insertmanyvalues_fixture(
connection,
randomize_rows=bool(randomize_returning),
warn_on_downgraded=bool(warn_for_downgrades),
)
stmt = provision.upsert(
config,
t1,
(t1.c.data, t1.c.has_server_default),
set_lambda=lambda inserted: {
"data": inserted.data + " upserted",
},
sort_by_parameter_order=bool(sort_by_parameter_order),
)
with self._expect_downgrade_warnings(
warn_for_downgrades=warn_for_downgrades,
sort_by_parameter_order=sort_by_parameter_order,
):
result = connection.execute(stmt, upsert_data)
expected_data = [
("d1 new upserted", "some_server_default"),
("d10", "some_server_default"),
("d15", "some_server_default"),
("d2 new upserted", "some_server_default"),
("d3", "some_server_default"),
]
if sort_by_parameter_order:
coll = list
else:
coll = set
eq_(coll(result), coll(expected_data))
def test_auto_downgraded_non_mvi_dialect(
self,
metadata,
testing_engine,
randomize_returning,
warn_for_downgrades,
sort_by_parameter_order,
):
"""Accommodate the case of the dialect that supports RETURNING, but
does not support "multi values INSERT" syntax.
These dialects should still provide insertmanyvalues/returning
support, using downgraded batching.
For now, we are still keeping this entire thing "opt in" by requiring
that use_insertmanyvalues=True, which means we can't simplify the
ORM by not worrying about dialects where ordering is available or
not.
However, dialects that use RETURNING, but don't support INSERT VALUES
(..., ..., ...) can set themselves up like this::
class MyDialect(DefaultDialect):
use_insertmanyvalues = True
supports_multivalues_insert = False
This test runs for everyone **including** Oracle, where we
exercise Oracle using "insertmanyvalues" without "multivalues_insert".
"""
engine = testing_engine()
engine.connect().close()
engine.dialect.supports_multivalues_insert = False
engine.dialect.use_insertmanyvalues = True
uuids = [uuid.uuid4() for i in range(10)]
t1 = Table(
"t1",
metadata,
Column("id", Uuid(), default=functools.partial(next, iter(uuids))),
Column("data", String(50)),
)
metadata.create_all(engine)
with engine.connect() as conn:
fixtures.insertmanyvalues_fixture(
conn,
randomize_rows=bool(randomize_returning),
warn_on_downgraded=bool(warn_for_downgrades),
)
stmt = insert(t1).returning(
t1.c.id,
t1.c.data,
sort_by_parameter_order=bool(sort_by_parameter_order),
)
data = [{"data": f"d{i}"} for i in range(10)]
with self._expect_downgrade_warnings(
warn_for_downgrades=warn_for_downgrades,
sort_by_parameter_order=True, # will warn even if not sorted
connection=conn,
):
result = conn.execute(stmt, data)
expected_data = [(uuids[i], f"d{i}") for i in range(10)]
if sort_by_parameter_order:
coll = list
else:
coll = set
eq_(coll(result), coll(expected_data))
|