1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
Using the Session
—
SQLAlchemy 0.9 Documentation
</title>
<!-- begin iterate through SQLA + sphinx environment css_files -->
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="../_static/docs.css" type="text/css" />
<link rel="stylesheet" href="../_static/sphinx_paramlinks.css" type="text/css" />
<link rel="stylesheet" href="../_static/changelog.css" type="text/css" />
<!-- end iterate through SQLA + sphinx environment css_files -->
<!-- begin layout.mako headers -->
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../',
VERSION: '0.9.8',
COLLAPSE_MODINDEX: false,
FILE_SUFFIX: '.html'
};
</script>
<!-- begin iterate through sphinx environment script_files -->
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<!-- end iterate through sphinx environment script_files -->
<script type="text/javascript" src="../_static/detectmobile.js"></script>
<script type="text/javascript" src="../_static/init.js"></script>
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="top" title="SQLAlchemy 0.9 Documentation" href="../index.html" />
<link rel="up" title="SQLAlchemy ORM" href="index.html" />
<link rel="next" title="Querying" href="query.html" />
<link rel="prev" title="Mapping Class Inheritance Hierarchies" href="inheritance.html" />
<!-- end layout.mako headers -->
</head>
<body>
<div id="docs-container">
<div id="docs-top-navigation-container" class="body-background">
<div id="docs-header">
<div id="docs-version-header">
Release: <span class="version-num">0.9.8</span> | Release Date: October 13, 2014
</div>
<h1>SQLAlchemy 0.9 Documentation</h1>
</div>
</div>
<div id="docs-body-container">
<div id="fixed-sidebar" class="withsidebar">
<div id="docs-sidebar-popout">
<h3><a href="../index.html">SQLAlchemy 0.9 Documentation</a></h3>
<p id="sidebar-paginate">
<a href="index.html" title="SQLAlchemy ORM">Up</a> |
<a href="inheritance.html" title="Mapping Class Inheritance Hierarchies">Prev</a> |
<a href="query.html" title="Querying">Next</a>
</p>
<p id="sidebar-topnav">
<a href="../index.html">Contents</a> |
<a href="../genindex.html">Index</a>
</p>
<div id="sidebar-search">
<form class="search" action="../search.html" method="get">
<input type="text" name="q" size="12" /> <input type="submit" value="Search" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<div id="docs-sidebar">
<h3><a href="#">
Using the Session
</a></h3>
<ul>
<li><a class="reference internal" href="#">Using the Session</a><ul>
<li><a class="reference internal" href="#what-does-the-session-do">What does the Session do ?</a></li>
<li><a class="reference internal" href="#getting-a-session">Getting a Session</a><ul>
<li><a class="reference internal" href="#adding-additional-configuration-to-an-existing-sessionmaker">Adding Additional Configuration to an Existing sessionmaker()</a></li>
<li><a class="reference internal" href="#creating-ad-hoc-session-objects-with-alternate-arguments">Creating Ad-Hoc Session Objects with Alternate Arguments</a></li>
</ul>
</li>
<li><a class="reference internal" href="#id1">Using the Session</a><ul>
<li><a class="reference internal" href="#quickie-intro-to-object-states">Quickie Intro to Object States</a><ul>
<li><a class="reference internal" href="#getting-the-current-state-of-an-object">Getting the Current State of an Object</a></li>
</ul>
</li>
<li><a class="reference internal" href="#session-frequently-asked-questions">Session Frequently Asked Questions</a><ul>
<li><a class="reference internal" href="#when-do-i-make-a-sessionmaker">When do I make a <tt class="docutils literal"><span class="pre">sessionmaker</span></tt>?</a></li>
<li><a class="reference internal" href="#when-do-i-construct-a-session-when-do-i-commit-it-and-when-do-i-close-it">When do I construct a <tt class="docutils literal"><span class="pre">Session</span></tt>, when do I commit it, and when do I close it?</a></li>
<li><a class="reference internal" href="#is-the-session-a-cache">Is the Session a cache?</a></li>
<li><a class="reference internal" href="#how-can-i-get-the-session-for-a-certain-object">How can I get the <tt class="docutils literal"><span class="pre">Session</span></tt> for a certain object?</a></li>
<li><a class="reference internal" href="#is-the-session-thread-safe">Is the session thread-safe?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#querying">Querying</a></li>
<li><a class="reference internal" href="#adding-new-or-existing-items">Adding New or Existing Items</a></li>
<li><a class="reference internal" href="#merging">Merging</a><ul>
<li><a class="reference internal" href="#merge-tips">Merge Tips</a></li>
</ul>
</li>
<li><a class="reference internal" href="#deleting">Deleting</a><ul>
<li><a class="reference internal" href="#deleting-from-collections">Deleting from Collections</a></li>
<li><a class="reference internal" href="#deleting-based-on-filter-criterion">Deleting based on Filter Criterion</a></li>
</ul>
</li>
<li><a class="reference internal" href="#flushing">Flushing</a></li>
<li><a class="reference internal" href="#committing">Committing</a></li>
<li><a class="reference internal" href="#rolling-back">Rolling Back</a></li>
<li><a class="reference internal" href="#expunging">Expunging</a></li>
<li><a class="reference internal" href="#closing">Closing</a></li>
<li><a class="reference internal" href="#refreshing-expiring">Refreshing / Expiring</a><ul>
<li><a class="reference internal" href="#what-actually-loads">What Actually Loads</a></li>
<li><a class="reference internal" href="#when-to-expire-or-refresh">When to Expire or Refresh</a></li>
</ul>
</li>
<li><a class="reference internal" href="#session-attributes">Session Attributes</a></li>
</ul>
</li>
<li><a class="reference internal" href="#cascades">Cascades</a><ul>
<li><a class="reference internal" href="#save-update">save-update</a></li>
<li><a class="reference internal" href="#delete">delete</a></li>
<li><a class="reference internal" href="#delete-orphan">delete-orphan</a></li>
<li><a class="reference internal" href="#merge">merge</a></li>
<li><a class="reference internal" href="#refresh-expire">refresh-expire</a></li>
<li><a class="reference internal" href="#expunge">expunge</a></li>
<li><a class="reference internal" href="#controlling-cascade-on-backrefs">Controlling Cascade on Backrefs</a></li>
</ul>
</li>
<li><a class="reference internal" href="#managing-transactions">Managing Transactions</a><ul>
<li><a class="reference internal" href="#using-savepoint">Using SAVEPOINT</a></li>
<li><a class="reference internal" href="#autocommit-mode">Autocommit Mode</a><ul>
<li><a class="reference internal" href="#using-subtransactions-with-autocommit">Using Subtransactions with Autocommit</a></li>
</ul>
</li>
<li><a class="reference internal" href="#enabling-two-phase-commit">Enabling Two-Phase Commit</a></li>
</ul>
</li>
<li><a class="reference internal" href="#embedding-sql-insert-update-expressions-into-a-flush">Embedding SQL Insert/Update Expressions into a Flush</a></li>
<li><a class="reference internal" href="#using-sql-expressions-with-sessions">Using SQL Expressions with Sessions</a></li>
<li><a class="reference internal" href="#joining-a-session-into-an-external-transaction-such-as-for-test-suites">Joining a Session into an External Transaction (such as for test suites)</a></li>
<li><a class="reference internal" href="#contextual-thread-local-sessions">Contextual/Thread-local Sessions</a><ul>
<li><a class="reference internal" href="#implicit-method-access">Implicit Method Access</a></li>
<li><a class="reference internal" href="#thread-local-scope">Thread-Local Scope</a></li>
<li><a class="reference internal" href="#using-thread-local-scope-with-web-applications">Using Thread-Local Scope with Web Applications</a></li>
<li><a class="reference internal" href="#using-custom-created-scopes">Using Custom Created Scopes</a></li>
<li><a class="reference internal" href="#contextual-session-api">Contextual Session API</a></li>
</ul>
</li>
<li><a class="reference internal" href="#partitioning-strategies">Partitioning Strategies</a><ul>
<li><a class="reference internal" href="#simple-vertical-partitioning">Simple Vertical Partitioning</a></li>
<li><a class="reference internal" href="#custom-vertical-partitioning">Custom Vertical Partitioning</a></li>
<li><a class="reference internal" href="#horizontal-partitioning">Horizontal Partitioning</a></li>
</ul>
</li>
<li><a class="reference internal" href="#sessions-api">Sessions API</a><ul>
<li><a class="reference internal" href="#session-and-sessionmaker">Session and sessionmaker()</a></li>
<li><a class="reference internal" href="#session-utilites">Session Utilites</a></li>
<li><a class="reference internal" href="#attribute-and-state-management-utilities">Attribute and State Management Utilities</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<div id="docs-body" class="withsidebar" >
<div class="section" id="module-sqlalchemy.orm.session">
<span id="using-the-session"></span><span id="session-toplevel"></span><h1>Using the Session<a class="headerlink" href="#module-sqlalchemy.orm.session" title="Permalink to this headline">¶</a></h1>
<p>The <a class="reference internal" href="mapper_config.html#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">orm.mapper()</span></tt></a> function and <a class="reference internal" href="extensions/declarative.html#module-sqlalchemy.ext.declarative" title="sqlalchemy.ext.declarative"><tt class="xref py py-mod docutils literal"><span class="pre">declarative</span></tt></a> extensions
are the primary configurational interface for the ORM. Once mappings are
configured, the primary usage interface for persistence operations is the
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>.</p>
<div class="section" id="what-does-the-session-do">
<h2>What does the Session do ?<a class="headerlink" href="#what-does-the-session-do" title="Permalink to this headline">¶</a></h2>
<p>In the most general sense, the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> establishes all
conversations with the database and represents a “holding zone” for all the
objects which you’ve loaded or associated with it during its lifespan. It
provides the entrypoint to acquire a <a class="reference internal" href="query.html#sqlalchemy.orm.query.Query" title="sqlalchemy.orm.query.Query"><tt class="xref py py-class docutils literal"><span class="pre">Query</span></tt></a> object, which sends
queries to the database using the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> object’s current database
connection, populating result rows into objects that are then stored in the
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>, inside a structure called the <a class="reference external" href="http://martinfowler.com/eaaCatalog/identityMap.html">Identity Map</a> - a data structure
that maintains unique copies of each object, where “unique” means “only one
object with a particular primary key”.</p>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> begins in an essentially stateless form. Once queries
are issued or other objects are persisted with it, it requests a connection
resource from an <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> that is associated either with the
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> itself or with the mapped <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> objects being
operated upon. This connection represents an ongoing transaction, which
remains in effect until the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is instructed to commit or roll
back its pending state.</p>
<p>All changes to objects maintained by a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> are tracked - before
the database is queried again or before the current transaction is committed,
it <strong>flushes</strong> all pending changes to the database. This is known as the <a class="reference external" href="http://martinfowler.com/eaaCatalog/unitOfWork.html">Unit
of Work</a> pattern.</p>
<p>When using a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>, it’s important to note that the objects
which are associated with it are <strong>proxy objects</strong> to the transaction being
held by the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> - there are a variety of events that will cause
objects to re-access the database in order to keep synchronized. It is
possible to “detach” objects from a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>, and to continue using
them, though this practice has its caveats. It’s intended that
usually, you’d re-associate detached objects with another <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> when you
want to work with them again, so that they can resume their normal task of
representing database state.</p>
</div>
<div class="section" id="getting-a-session">
<span id="session-getting"></span><h2>Getting a Session<a class="headerlink" href="#getting-a-session" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is a regular Python class which can
be directly instantiated. However, to standardize how sessions are configured
and acquired, the <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> class is normally
used to create a top level <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
configuration which can then be used throughout an application without the
need to repeat the configurational arguments.</p>
<p>The usage of <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> is illustrated below:</p>
<div class="highlight-python+sql"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">create_engine</span>
<span class="kn">from</span> <span class="nn">sqlalchemy.orm</span> <span class="kn">import</span> <span class="n">sessionmaker</span>
<span class="c"># an Engine, which the Session will use for connection</span>
<span class="c"># resources</span>
<span class="n">some_engine</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">'postgresql://scott:tiger@localhost/'</span><span class="p">)</span>
<span class="c"># create a configured "Session" class</span>
<span class="n">Session</span> <span class="o">=</span> <span class="n">sessionmaker</span><span class="p">(</span><span class="n">bind</span><span class="o">=</span><span class="n">some_engine</span><span class="p">)</span>
<span class="c"># create a Session</span>
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
<span class="c"># work with sess</span>
<span class="n">myobject</span> <span class="o">=</span> <span class="n">MyObject</span><span class="p">(</span><span class="s">'foo'</span><span class="p">,</span> <span class="s">'bar'</span><span class="p">)</span>
<span class="n">session</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">myobject</span><span class="p">)</span>
<span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span></pre></div>
</div>
<p>Above, the <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> call creates a factory for us,
which we assign to the name <tt class="docutils literal"><span class="pre">Session</span></tt>. This factory, when
called, will create a new <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> object using the configurational
arguments we’ve given the factory. In this case, as is typical,
we’ve configured the factory to specify a particular <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> for
connection resources.</p>
<p>A typical setup will associate the <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> with an <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a>,
so that each <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> generated will use this <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a>
to acquire connection resources. This association can
be set up as in the example above, using the <tt class="docutils literal"><span class="pre">bind</span></tt> argument.</p>
<p>When you write your application, place the
<a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> factory at the global level. This
factory can then
be used by the rest of the applcation as the source of new <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
instances, keeping the configuration for how <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> objects
are constructed in one place.</p>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> factory can also be used in conjunction with
other helpers, which are passed a user-defined <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> that
is then maintained by the helper. Some of these helpers are discussed in the
section <a class="reference internal" href="#session-faq-whentocreate"><em>When do I construct a Session, when do I commit it, and when do I close it?</em></a>.</p>
<div class="section" id="adding-additional-configuration-to-an-existing-sessionmaker">
<h3>Adding Additional Configuration to an Existing sessionmaker()<a class="headerlink" href="#adding-additional-configuration-to-an-existing-sessionmaker" title="Permalink to this headline">¶</a></h3>
<p>A common scenario is where the <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> is invoked
at module import time, however the generation of one or more <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a>
instances to be associated with the <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> has not yet proceeded.
For this use case, the <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> construct offers the
<a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker.configure" title="sqlalchemy.orm.session.sessionmaker.configure"><tt class="xref py py-meth docutils literal"><span class="pre">sessionmaker.configure()</span></tt></a> method, which will place additional configuration
directives into an existing <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> that will take place
when the construct is invoked:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy.orm</span> <span class="kn">import</span> <span class="n">sessionmaker</span>
<span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">create_engine</span>
<span class="c"># configure Session class with desired options</span>
<span class="n">Session</span> <span class="o">=</span> <span class="n">sessionmaker</span><span class="p">()</span>
<span class="c"># later, we create the engine</span>
<span class="n">engine</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">'postgresql://...'</span><span class="p">)</span>
<span class="c"># associate it with our custom Session class</span>
<span class="n">Session</span><span class="o">.</span><span class="n">configure</span><span class="p">(</span><span class="n">bind</span><span class="o">=</span><span class="n">engine</span><span class="p">)</span>
<span class="c"># work with the session</span>
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span></pre></div>
</div>
</div>
<div class="section" id="creating-ad-hoc-session-objects-with-alternate-arguments">
<h3>Creating Ad-Hoc Session Objects with Alternate Arguments<a class="headerlink" href="#creating-ad-hoc-session-objects-with-alternate-arguments" title="Permalink to this headline">¶</a></h3>
<p>For the use case where an application needs to create a new <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> with
special arguments that deviate from what is normally used throughout the application,
such as a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> that binds to an alternate
source of connectivity, or a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> that should
have other arguments such as <tt class="docutils literal"><span class="pre">expire_on_commit</span></tt> established differently from
what most of the application wants, specific arguments can be passed to the
<a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> factory’s <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker.__call__" title="sqlalchemy.orm.session.sessionmaker.__call__"><tt class="xref py py-meth docutils literal"><span class="pre">sessionmaker.__call__()</span></tt></a> method.
These arguments will override whatever
configurations have already been placed, such as below, where a new <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
is constructed against a specific <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># at the module level, the global sessionmaker,</span>
<span class="c"># bound to a specific Engine</span>
<span class="n">Session</span> <span class="o">=</span> <span class="n">sessionmaker</span><span class="p">(</span><span class="n">bind</span><span class="o">=</span><span class="n">engine</span><span class="p">)</span>
<span class="c"># later, some unit of code wants to create a</span>
<span class="c"># Session that is bound to a specific Connection</span>
<span class="n">conn</span> <span class="o">=</span> <span class="n">engine</span><span class="o">.</span><span class="n">connect</span><span class="p">()</span>
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">(</span><span class="n">bind</span><span class="o">=</span><span class="n">conn</span><span class="p">)</span></pre></div>
</div>
<p>The typical rationale for the association of a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> with a specific
<a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> is that of a test fixture that maintains an external
transaction - see <a class="reference internal" href="#session-external-transaction"><em>Joining a Session into an External Transaction (such as for test suites)</em></a> for an example of this.</p>
</div>
</div>
<div class="section" id="id1">
<h2>Using the Session<a class="headerlink" href="#id1" title="Permalink to this headline">¶</a></h2>
<div class="section" id="quickie-intro-to-object-states">
<span id="session-object-states"></span><h3>Quickie Intro to Object States<a class="headerlink" href="#quickie-intro-to-object-states" title="Permalink to this headline">¶</a></h3>
<p>It’s helpful to know the states which an instance can have within a session:</p>
<ul class="simple">
<li><strong>Transient</strong> - an instance that’s not in a session, and is not saved to the
database; i.e. it has no database identity. The only relationship such an
object has to the ORM is that its class has a <tt class="docutils literal"><span class="pre">mapper()</span></tt> associated with
it.</li>
<li><strong>Pending</strong> - when you <a class="reference internal" href="#sqlalchemy.orm.session.Session.add" title="sqlalchemy.orm.session.Session.add"><tt class="xref py py-meth docutils literal"><span class="pre">add()</span></tt></a> a transient
instance, it becomes pending. It still wasn’t actually flushed to the
database yet, but it will be when the next flush occurs.</li>
<li><strong>Persistent</strong> - An instance which is present in the session and has a record
in the database. You get persistent instances by either flushing so that the
pending instances become persistent, or by querying the database for
existing instances (or moving persistent instances from other sessions into
your local session).</li>
<li><strong>Detached</strong> - an instance which has a record in the database, but is not in
any session. There’s nothing wrong with this, and you can use objects
normally when they’re detached, <strong>except</strong> they will not be able to issue
any SQL in order to load collections or attributes which are not yet loaded,
or were marked as “expired”.</li>
</ul>
<p>Knowing these states is important, since the
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> tries to be strict about ambiguous
operations (such as trying to save the same object to two different sessions
at the same time).</p>
<div class="section" id="getting-the-current-state-of-an-object">
<h4>Getting the Current State of an Object<a class="headerlink" href="#getting-the-current-state-of-an-object" title="Permalink to this headline">¶</a></h4>
<p>The actual state of any mapped object can be viewed at any time using
the <a class="reference internal" href="../core/inspection.html#sqlalchemy.inspection.inspect" title="sqlalchemy.inspection.inspect"><tt class="xref py py-func docutils literal"><span class="pre">inspect()</span></tt></a> system:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">inspect</span>
<span class="gp">>>> </span><span class="n">insp</span> <span class="o">=</span> <span class="n">inspect</span><span class="p">(</span><span class="n">my_object</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">insp</span><span class="o">.</span><span class="n">persistent</span>
<span class="go">True</span></pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p><a class="reference internal" href="internals.html#sqlalchemy.orm.state.InstanceState.transient" title="sqlalchemy.orm.state.InstanceState.transient"><tt class="xref py py-attr docutils literal"><span class="pre">InstanceState.transient</span></tt></a></p>
<p><a class="reference internal" href="internals.html#sqlalchemy.orm.state.InstanceState.pending" title="sqlalchemy.orm.state.InstanceState.pending"><tt class="xref py py-attr docutils literal"><span class="pre">InstanceState.pending</span></tt></a></p>
<p><a class="reference internal" href="internals.html#sqlalchemy.orm.state.InstanceState.persistent" title="sqlalchemy.orm.state.InstanceState.persistent"><tt class="xref py py-attr docutils literal"><span class="pre">InstanceState.persistent</span></tt></a></p>
<p class="last"><a class="reference internal" href="internals.html#sqlalchemy.orm.state.InstanceState.detached" title="sqlalchemy.orm.state.InstanceState.detached"><tt class="xref py py-attr docutils literal"><span class="pre">InstanceState.detached</span></tt></a></p>
</div>
</div>
</div>
<div class="section" id="session-frequently-asked-questions">
<span id="session-faq"></span><h3>Session Frequently Asked Questions<a class="headerlink" href="#session-frequently-asked-questions" title="Permalink to this headline">¶</a></h3>
<div class="section" id="when-do-i-make-a-sessionmaker">
<h4>When do I make a <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a>?<a class="headerlink" href="#when-do-i-make-a-sessionmaker" title="Permalink to this headline">¶</a></h4>
<p>Just one time, somewhere in your application’s global scope. It should be
looked upon as part of your application’s configuration. If your
application has three .py files in a package, you could, for example,
place the <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> line in your <tt class="docutils literal"><span class="pre">__init__.py</span></tt> file; from
that point on your other modules say “from mypackage import Session”. That
way, everyone else just uses <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session()</span></tt></a>,
and the configuration of that session is controlled by that central point.</p>
<p>If your application starts up, does imports, but does not know what
database it’s going to be connecting to, you can bind the
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> at the “class” level to the
engine later on, using <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker.configure" title="sqlalchemy.orm.session.sessionmaker.configure"><tt class="xref py py-meth docutils literal"><span class="pre">sessionmaker.configure()</span></tt></a>.</p>
<p>In the examples in this section, we will frequently show the
<a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> being created right above the line where we actually
invoke <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>. But that’s just for
example’s sake! In reality, the <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> would be somewhere
at the module level. The calls to instantiate <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
would then be placed at the point in the application where database
conversations begin.</p>
</div>
<div class="section" id="when-do-i-construct-a-session-when-do-i-commit-it-and-when-do-i-close-it">
<span id="session-faq-whentocreate"></span><h4>When do I construct a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>, when do I commit it, and when do I close it?<a class="headerlink" href="#when-do-i-construct-a-session-when-do-i-commit-it-and-when-do-i-close-it" title="Permalink to this headline">¶</a></h4>
<div class="topic">
<p class="topic-title first">tl;dr;</p>
<p>As a general rule, keep the lifecycle of the session <strong>separate and
external</strong> from functions and objects that access and/or manipulate
database data.</p>
</div>
<p>A <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is typically constructed at the beginning of a logical
operation where database access is potentially anticipated.</p>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>, whenever it is used to talk to the database,
begins a database transaction as soon as it starts communicating.
Assuming the <tt class="docutils literal"><span class="pre">autocommit</span></tt> flag is left at its recommended default
of <tt class="docutils literal"><span class="pre">False</span></tt>, this transaction remains in progress until the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
is rolled back, committed, or closed. The <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> will
begin a new transaction if it is used again, subsequent to the previous
transaction ending; from this it follows that the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
is capable of having a lifespan across many transactions, though only
one at a time. We refer to these two concepts as <strong>transaction scope</strong>
and <strong>session scope</strong>.</p>
<p>The implication here is that the SQLAlchemy ORM is encouraging the
developer to establish these two scopes in their application,
including not only when the scopes begin and end, but also the
expanse of those scopes, for example should a single
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> instance be local to the execution flow within a
function or method, should it be a global object used by the
entire application, or somewhere in between these two.</p>
<p>The burden placed on the developer to determine this scope is one
area where the SQLAlchemy ORM necessarily has a strong opinion
about how the database should be used. The <a class="reference internal" href="../glossary.html#term-unit-of-work"><em class="xref std std-term">unit of work</em></a> pattern
is specifically one of accumulating changes over time and flushing
them periodically, keeping in-memory state in sync with what’s
known to be present in a local transaction. This pattern is only
effective when meaningful transaction scopes are in place.</p>
<p>It’s usually not very hard to determine the best points at which
to begin and end the scope of a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>, though the wide
variety of application architectures possible can introduce
challenging situations.</p>
<p>A common choice is to tear down the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> at the same
time the transaction ends, meaning the transaction and session scopes
are the same. This is a great choice to start out with as it
removes the need to consider session scope as separate from transaction
scope.</p>
<p>While there’s no one-size-fits-all recommendation for how transaction
scope should be determined, there are common patterns. Especially
if one is writing a web application, the choice is pretty much established.</p>
<p>A web application is the easiest case because such an appication is already
constructed around a single, consistent scope - this is the <strong>request</strong>,
which represents an incoming request from a browser, the processing
of that request to formulate a response, and finally the delivery of that
response back to the client. Integrating web applications with the
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is then the straightforward task of linking the
scope of the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> to that of the request. The <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
can be established as the request begins, or using a <em class="xref std std-term">lazy initialization</em>
pattern which establishes one as soon as it is needed. The request
then proceeds, with some system in place where application logic can access
the current <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> in a manner associated with how the actual
request object is accessed. As the request ends, the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
is torn down as well, usually through the usage of event hooks provided
by the web framework. The transaction used by the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
may also be committed at this point, or alternatively the application may
opt for an explicit commit pattern, only committing for those requests
where one is warranted, but still always tearing down the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
unconditionally at the end.</p>
<p>Some web frameworks include infrastructure to assist in the task
of aligning the lifespan of a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> with that of a web request.
This includes products such as <a class="reference external" href="http://packages.python.org/Flask-SQLAlchemy/">Flask-SQLAlchemy</a>,
for usage in conjunction with the Flask web framework,
and <a class="reference external" href="http://pypi.python.org/pypi/zope.sqlalchemy">Zope-SQLAlchemy</a>,
typically used with the Pyramid framework.
SQLAlchemy recommends that these products be used as available.</p>
<p>In those situations where the integration libraries are not
provided or are insufficient, SQLAlchemy includes its own “helper” class known as
<a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a>. A tutorial on the usage of this object
is at <a class="reference internal" href="#unitofwork-contextual"><em>Contextual/Thread-local Sessions</em></a>. It provides both a quick way
to associate a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> with the current thread, as well as
patterns to associate <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> objects with other kinds of
scopes.</p>
<p>As mentioned before, for non-web applications there is no one clear
pattern, as applications themselves don’t have just one pattern
of architecture. The best strategy is to attempt to demarcate
“operations”, points at which a particular thread begins to perform
a series of operations for some period of time, which can be committed
at the end. Some examples:</p>
<ul class="simple">
<li>A background daemon which spawns off child forks
would want to create a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> local to each child
process, work with that <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> through the life of the “job”
that the fork is handling, then tear it down when the job is completed.</li>
<li>For a command-line script, the application would create a single, global
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> that is established when the program begins to do its
work, and commits it right as the program is completing its task.</li>
<li>For a GUI interface-driven application, the scope of the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
may best be within the scope of a user-generated event, such as a button
push. Or, the scope may correspond to explicit user interaction, such as
the user “opening” a series of records, then “saving” them.</li>
</ul>
<p>As a general rule, the application should manage the lifecycle of the
session <em>externally</em> to functions that deal with specific data. This is a
fundamental separation of concerns which keeps data-specific operations
agnostic of the context in which they access and manipulate that data.</p>
<p>E.g. <strong>don’t do this</strong>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c">### this is the **wrong way to do it** ###</span>
<span class="k">class</span> <span class="nc">ThingOne</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">go</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">FooBar</span><span class="p">)</span><span class="o">.</span><span class="n">update</span><span class="p">({</span><span class="s">"x"</span><span class="p">:</span> <span class="mi">5</span><span class="p">})</span>
<span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
<span class="k">except</span><span class="p">:</span>
<span class="n">session</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
<span class="k">raise</span>
<span class="k">class</span> <span class="nc">ThingTwo</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">go</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">Widget</span><span class="p">)</span><span class="o">.</span><span class="n">update</span><span class="p">({</span><span class="s">"q"</span><span class="p">:</span> <span class="mi">18</span><span class="p">})</span>
<span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
<span class="k">except</span><span class="p">:</span>
<span class="n">session</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
<span class="k">raise</span>
<span class="k">def</span> <span class="nf">run_my_program</span><span class="p">():</span>
<span class="n">ThingOne</span><span class="p">()</span><span class="o">.</span><span class="n">go</span><span class="p">()</span>
<span class="n">ThingTwo</span><span class="p">()</span><span class="o">.</span><span class="n">go</span><span class="p">()</span></pre></div>
</div>
<p>Keep the lifecycle of the session (and usually the transaction)
<strong>separate and external</strong>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c">### this is a **better** (but not the only) way to do it ###</span>
<span class="k">class</span> <span class="nc">ThingOne</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">go</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">session</span><span class="p">):</span>
<span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">FooBar</span><span class="p">)</span><span class="o">.</span><span class="n">update</span><span class="p">({</span><span class="s">"x"</span><span class="p">:</span> <span class="mi">5</span><span class="p">})</span>
<span class="k">class</span> <span class="nc">ThingTwo</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">go</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">session</span><span class="p">):</span>
<span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">Widget</span><span class="p">)</span><span class="o">.</span><span class="n">update</span><span class="p">({</span><span class="s">"q"</span><span class="p">:</span> <span class="mi">18</span><span class="p">})</span>
<span class="k">def</span> <span class="nf">run_my_program</span><span class="p">():</span>
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">ThingOne</span><span class="p">()</span><span class="o">.</span><span class="n">go</span><span class="p">(</span><span class="n">session</span><span class="p">)</span>
<span class="n">ThingTwo</span><span class="p">()</span><span class="o">.</span><span class="n">go</span><span class="p">(</span><span class="n">session</span><span class="p">)</span>
<span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
<span class="k">except</span><span class="p">:</span>
<span class="n">session</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
<span class="k">raise</span>
<span class="k">finally</span><span class="p">:</span>
<span class="n">session</span><span class="o">.</span><span class="n">close</span><span class="p">()</span></pre></div>
</div>
<p>The advanced developer will try to keep the details of session, transaction
and exception management as far as possible from the details of the program
doing its work. For example, we can further separate concerns using a <a class="reference external" href="http://docs.python.org/3/library/contextlib.html#contextlib.contextmanager">context manager</a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c">### another way (but again *not the only way*) to do it ###</span>
<span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">contextmanager</span>
<span class="nd">@contextmanager</span>
<span class="k">def</span> <span class="nf">session_scope</span><span class="p">():</span>
<span class="sd">"""Provide a transactional scope around a series of operations."""</span>
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
<span class="k">try</span><span class="p">:</span>
<span class="k">yield</span> <span class="n">session</span>
<span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
<span class="k">except</span><span class="p">:</span>
<span class="n">session</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
<span class="k">raise</span>
<span class="k">finally</span><span class="p">:</span>
<span class="n">session</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="k">def</span> <span class="nf">run_my_program</span><span class="p">():</span>
<span class="k">with</span> <span class="n">session_scope</span><span class="p">()</span> <span class="k">as</span> <span class="n">session</span><span class="p">:</span>
<span class="n">ThingOne</span><span class="p">()</span><span class="o">.</span><span class="n">go</span><span class="p">(</span><span class="n">session</span><span class="p">)</span>
<span class="n">ThingTwo</span><span class="p">()</span><span class="o">.</span><span class="n">go</span><span class="p">(</span><span class="n">session</span><span class="p">)</span></pre></div>
</div>
</div>
<div class="section" id="is-the-session-a-cache">
<h4>Is the Session a cache?<a class="headerlink" href="#is-the-session-a-cache" title="Permalink to this headline">¶</a></h4>
<p>Yeee...no. It’s somewhat used as a cache, in that it implements the
<a class="reference internal" href="../glossary.html#term-identity-map"><em class="xref std std-term">identity map</em></a> pattern, and stores objects keyed to their primary key.
However, it doesn’t do any kind of query caching. This means, if you say
<tt class="docutils literal"><span class="pre">session.query(Foo).filter_by(name='bar')</span></tt>, even if <tt class="docutils literal"><span class="pre">Foo(name='bar')</span></tt>
is right there, in the identity map, the session has no idea about that.
It has to issue SQL to the database, get the rows back, and then when it
sees the primary key in the row, <em>then</em> it can look in the local identity
map and see that the object is already there. It’s only when you say
<tt class="docutils literal"><span class="pre">query.get({some</span> <span class="pre">primary</span> <span class="pre">key})</span></tt> that the
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> doesn’t have to issue a query.</p>
<p>Additionally, the Session stores object instances using a weak reference
by default. This also defeats the purpose of using the Session as a cache.</p>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is not designed to be a
global object from which everyone consults as a “registry” of objects.
That’s more the job of a <strong>second level cache</strong>. SQLAlchemy provides
a pattern for implementing second level caching using <a class="reference external" href="http://dogpilecache.readthedocs.org/">dogpile.cache</a>,
via the <a class="reference internal" href="examples.html#examples-caching"><em>Dogpile Caching</em></a> example.</p>
</div>
<div class="section" id="how-can-i-get-the-session-for-a-certain-object">
<h4>How can I get the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> for a certain object?<a class="headerlink" href="#how-can-i-get-the-session-for-a-certain-object" title="Permalink to this headline">¶</a></h4>
<p>Use the <a class="reference internal" href="#sqlalchemy.orm.session.Session.object_session" title="sqlalchemy.orm.session.Session.object_session"><tt class="xref py py-meth docutils literal"><span class="pre">object_session()</span></tt></a> classmethod
available on <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="o">.</span><span class="n">object_session</span><span class="p">(</span><span class="n">someobject</span><span class="p">)</span></pre></div>
</div>
<p>The newer <a class="reference internal" href="../core/inspection.html"><em>Runtime Inspection API</em></a> system can also be used:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">inspect</span>
<span class="n">session</span> <span class="o">=</span> <span class="n">inspect</span><span class="p">(</span><span class="n">someobject</span><span class="p">)</span><span class="o">.</span><span class="n">session</span></pre></div>
</div>
</div>
<div class="section" id="is-the-session-thread-safe">
<span id="session-faq-threadsafe"></span><h4>Is the session thread-safe?<a class="headerlink" href="#is-the-session-thread-safe" title="Permalink to this headline">¶</a></h4>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is very much intended to be used in a
<strong>non-concurrent</strong> fashion, which usually means in only one thread at a
time.</p>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> should be used in such a way that one
instance exists for a single series of operations within a single
transaction. One expedient way to get this effect is by associating
a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> with the current thread (see <a class="reference internal" href="#unitofwork-contextual"><em>Contextual/Thread-local Sessions</em></a>
for background). Another is to use a pattern
where the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is passed between functions and is otherwise
not shared with other threads.</p>
<p>The bigger point is that you should not <em>want</em> to use the session
with multiple concurrent threads. That would be like having everyone at a
restaurant all eat from the same plate. The session is a local “workspace”
that you use for a specific set of tasks; you don’t want to, or need to,
share that session with other threads who are doing some other task.</p>
<p>Making sure the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is only used in a single concurrent thread at a time
is called a “share nothing” approach to concurrency. But actually, not
sharing the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> implies a more significant pattern; it
means not just the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> object itself, but
also <strong>all objects that are associated with that Session</strong>, must be kept within
the scope of a single concurrent thread. The set of mapped
objects associated with a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> are essentially proxies for data
within database rows accessed over a database connection, and so just like
the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> itself, the whole
set of objects is really just a large-scale proxy for a database connection
(or connections). Ultimately, it’s mostly the DBAPI connection itself that
we’re keeping away from concurrent access; but since the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
and all the objects associated with it are all proxies for that DBAPI connection,
the entire graph is essentially not safe for concurrent access.</p>
<p>If there are in fact multiple threads participating
in the same task, then you may consider sharing the session and its objects between
those threads; however, in this extremely unusual scenario the application would
need to ensure that a proper locking scheme is implemented so that there isn’t
<em>concurrent</em> access to the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> or its state. A more common approach
to this situation is to maintain a single <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> per concurrent thread,
but to instead <em>copy</em> objects from one <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> to another, often
using the <a class="reference internal" href="#sqlalchemy.orm.session.Session.merge" title="sqlalchemy.orm.session.Session.merge"><tt class="xref py py-meth docutils literal"><span class="pre">Session.merge()</span></tt></a> method to copy the state of an object into
a new object local to a different <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>.</p>
</div>
</div>
<div class="section" id="querying">
<h3>Querying<a class="headerlink" href="#querying" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.Session.query" title="sqlalchemy.orm.session.Session.query"><tt class="xref py py-meth docutils literal"><span class="pre">query()</span></tt></a> function takes one or more
<em>entities</em> and returns a new <a class="reference internal" href="query.html#sqlalchemy.orm.query.Query" title="sqlalchemy.orm.query.Query"><tt class="xref py py-class docutils literal"><span class="pre">Query</span></tt></a> object which
will issue mapper queries within the context of this Session. An entity is
defined as a mapped class, a <a class="reference internal" href="mapper_config.html#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> object, an
orm-enabled <em>descriptor</em>, or an <tt class="docutils literal"><span class="pre">AliasedClass</span></tt> object:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># query from a class</span>
<span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">User</span><span class="p">)</span><span class="o">.</span><span class="n">filter_by</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">'ed'</span><span class="p">)</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="c"># query with multiple classes, returns tuples</span>
<span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">User</span><span class="p">,</span> <span class="n">Address</span><span class="p">)</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="s">'addresses'</span><span class="p">)</span><span class="o">.</span><span class="n">filter_by</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">'ed'</span><span class="p">)</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="c"># query using orm-enabled descriptors</span>
<span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">User</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">User</span><span class="o">.</span><span class="n">fullname</span><span class="p">)</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="c"># query from a mapper</span>
<span class="n">user_mapper</span> <span class="o">=</span> <span class="n">class_mapper</span><span class="p">(</span><span class="n">User</span><span class="p">)</span>
<span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">user_mapper</span><span class="p">)</span></pre></div>
</div>
<p>When <a class="reference internal" href="query.html#sqlalchemy.orm.query.Query" title="sqlalchemy.orm.query.Query"><tt class="xref py py-class docutils literal"><span class="pre">Query</span></tt></a> returns results, each object
instantiated is stored within the identity map. When a row matches an object
which is already present, the same object is returned. In the latter case,
whether or not the row is populated onto an existing object depends upon
whether the attributes of the instance have been <em>expired</em> or not. A
default-configured <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> automatically
expires all instances along transaction boundaries, so that with a normally
isolated transaction, there shouldn’t be any issue of instances representing
data which is stale with regards to the current transaction.</p>
<p>The <a class="reference internal" href="query.html#sqlalchemy.orm.query.Query" title="sqlalchemy.orm.query.Query"><tt class="xref py py-class docutils literal"><span class="pre">Query</span></tt></a> object is introduced in great detail in
<a class="reference internal" href="tutorial.html"><em>Object Relational Tutorial</em></a>, and further documented in
<a class="reference internal" href="query.html"><em>Querying</em></a>.</p>
</div>
<div class="section" id="adding-new-or-existing-items">
<h3>Adding New or Existing Items<a class="headerlink" href="#adding-new-or-existing-items" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#sqlalchemy.orm.session.Session.add" title="sqlalchemy.orm.session.Session.add"><tt class="xref py py-meth docutils literal"><span class="pre">add()</span></tt></a> is used to place instances in the
session. For <em>transient</em> (i.e. brand new) instances, this will have the effect
of an INSERT taking place for those instances upon the next flush. For
instances which are <em>persistent</em> (i.e. were loaded by this session), they are
already present and do not need to be added. Instances which are <em>detached</em>
(i.e. have been removed from a session) may be re-associated with a session
using this method:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">user1</span> <span class="o">=</span> <span class="n">User</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">'user1'</span><span class="p">)</span>
<span class="n">user2</span> <span class="o">=</span> <span class="n">User</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">'user2'</span><span class="p">)</span>
<span class="n">session</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">user1</span><span class="p">)</span>
<span class="n">session</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">user2</span><span class="p">)</span>
<span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span> <span class="c"># write changes to the database</span></pre></div>
</div>
<p>To add a list of items to the session at once, use
<a class="reference internal" href="#sqlalchemy.orm.session.Session.add_all" title="sqlalchemy.orm.session.Session.add_all"><tt class="xref py py-meth docutils literal"><span class="pre">add_all()</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">session</span><span class="o">.</span><span class="n">add_all</span><span class="p">([</span><span class="n">item1</span><span class="p">,</span> <span class="n">item2</span><span class="p">,</span> <span class="n">item3</span><span class="p">])</span></pre></div>
</div>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.Session.add" title="sqlalchemy.orm.session.Session.add"><tt class="xref py py-meth docutils literal"><span class="pre">add()</span></tt></a> operation <strong>cascades</strong> along
the <tt class="docutils literal"><span class="pre">save-update</span></tt> cascade. For more details see the section
<a class="reference internal" href="#unitofwork-cascades"><em>Cascades</em></a>.</p>
</div>
<div class="section" id="merging">
<span id="unitofwork-merging"></span><h3>Merging<a class="headerlink" href="#merging" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#sqlalchemy.orm.session.Session.merge" title="sqlalchemy.orm.session.Session.merge"><tt class="xref py py-meth docutils literal"><span class="pre">merge()</span></tt></a> transfers state from an
outside object into a new or already existing instance within a session. It
also reconciles the incoming data against the state of the
database, producing a history stream which will be applied towards the next
flush, or alternatively can be made to produce a simple “transfer” of
state without producing change history or accessing the database. Usage is as follows:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">merged_object</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">merge</span><span class="p">(</span><span class="n">existing_object</span><span class="p">)</span></pre></div>
</div>
<p>When given an instance, it follows these steps:</p>
<ul>
<li><p class="first">It examines the primary key of the instance. If it’s present, it attempts
to locate that instance in the local identity map. If the <tt class="docutils literal"><span class="pre">load=True</span></tt>
flag is left at its default, it also checks the database for this primary
key if not located locally.</p>
</li>
<li><p class="first">If the given instance has no primary key, or if no instance can be found
with the primary key given, a new instance is created.</p>
</li>
<li><p class="first">The state of the given instance is then copied onto the located/newly
created instance. For attributes which are present on the source
instance, the value is transferred to the target instance. For mapped
attributes which aren’t present on the source, the attribute is
expired on the target instance, discarding its existing value.</p>
<p>If the <tt class="docutils literal"><span class="pre">load=True</span></tt> flag is left at its default,
this copy process emits events and will load the target object’s
unloaded collections for each attribute present on the source object,
so that the incoming state can be reconciled against what’s
present in the database. If <tt class="docutils literal"><span class="pre">load</span></tt>
is passed as <tt class="docutils literal"><span class="pre">False</span></tt>, the incoming data is “stamped” directly without
producing any history.</p>
</li>
<li><p class="first">The operation is cascaded to related objects and collections, as
indicated by the <tt class="docutils literal"><span class="pre">merge</span></tt> cascade (see <a class="reference internal" href="#unitofwork-cascades"><em>Cascades</em></a>).</p>
</li>
<li><p class="first">The new instance is returned.</p>
</li>
</ul>
<p>With <a class="reference internal" href="#sqlalchemy.orm.session.Session.merge" title="sqlalchemy.orm.session.Session.merge"><tt class="xref py py-meth docutils literal"><span class="pre">merge()</span></tt></a>, the given “source”
instance is not modified nor is it associated with the target <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>,
and remains available to be merged with any number of other <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
objects. <a class="reference internal" href="#sqlalchemy.orm.session.Session.merge" title="sqlalchemy.orm.session.Session.merge"><tt class="xref py py-meth docutils literal"><span class="pre">merge()</span></tt></a> is useful for
taking the state of any kind of object structure without regard for its
origins or current session associations and copying its state into a
new session. Here’s some examples:</p>
<ul>
<li><p class="first">An application which reads an object structure from a file and wishes to
save it to the database might parse the file, build up the
structure, and then use
<a class="reference internal" href="#sqlalchemy.orm.session.Session.merge" title="sqlalchemy.orm.session.Session.merge"><tt class="xref py py-meth docutils literal"><span class="pre">merge()</span></tt></a> to save it
to the database, ensuring that the data within the file is
used to formulate the primary key of each element of the
structure. Later, when the file has changed, the same
process can be re-run, producing a slightly different
object structure, which can then be <tt class="docutils literal"><span class="pre">merged</span></tt> in again,
and the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> will
automatically update the database to reflect those
changes, loading each object from the database by primary key and
then updating its state with the new state given.</p>
</li>
<li><p class="first">An application is storing objects in an in-memory cache, shared by
many <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> objects simultaneously. <a class="reference internal" href="#sqlalchemy.orm.session.Session.merge" title="sqlalchemy.orm.session.Session.merge"><tt class="xref py py-meth docutils literal"><span class="pre">merge()</span></tt></a>
is used each time an object is retrieved from the cache to create
a local copy of it in each <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> which requests it.
The cached object remains detached; only its state is moved into
copies of itself that are local to individual <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
objects.</p>
<p>In the caching use case, it’s common to use the <tt class="docutils literal"><span class="pre">load=False</span></tt>
flag to remove the overhead of reconciling the object’s state
with the database. There’s also a “bulk” version of
<a class="reference internal" href="#sqlalchemy.orm.session.Session.merge" title="sqlalchemy.orm.session.Session.merge"><tt class="xref py py-meth docutils literal"><span class="pre">merge()</span></tt></a> called <a class="reference internal" href="query.html#sqlalchemy.orm.query.Query.merge_result" title="sqlalchemy.orm.query.Query.merge_result"><tt class="xref py py-meth docutils literal"><span class="pre">merge_result()</span></tt></a>
that was designed to work with cache-extended <a class="reference internal" href="query.html#sqlalchemy.orm.query.Query" title="sqlalchemy.orm.query.Query"><tt class="xref py py-class docutils literal"><span class="pre">Query</span></tt></a>
objects - see the section <a class="reference internal" href="examples.html#examples-caching"><em>Dogpile Caching</em></a>.</p>
</li>
<li><p class="first">An application wants to transfer the state of a series of objects
into a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> maintained by a worker thread or other
concurrent system. <a class="reference internal" href="#sqlalchemy.orm.session.Session.merge" title="sqlalchemy.orm.session.Session.merge"><tt class="xref py py-meth docutils literal"><span class="pre">merge()</span></tt></a> makes a copy of each object
to be placed into this new <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>. At the end of the operation,
the parent thread/process maintains the objects it started with,
and the thread/worker can proceed with local copies of those objects.</p>
<p>In the “transfer between threads/processes” use case, the application
may want to use the <tt class="docutils literal"><span class="pre">load=False</span></tt> flag as well to avoid overhead and
redundant SQL queries as the data is transferred.</p>
</li>
</ul>
<div class="section" id="merge-tips">
<h4>Merge Tips<a class="headerlink" href="#merge-tips" title="Permalink to this headline">¶</a></h4>
<p><a class="reference internal" href="#sqlalchemy.orm.session.Session.merge" title="sqlalchemy.orm.session.Session.merge"><tt class="xref py py-meth docutils literal"><span class="pre">merge()</span></tt></a> is an extremely useful method for many purposes. However,
it deals with the intricate border between objects that are transient/detached and
those that are persistent, as well as the automated transference of state.
The wide variety of scenarios that can present themselves here often require a
more careful approach to the state of objects. Common problems with merge usually involve
some unexpected state regarding the object being passed to <a class="reference internal" href="#sqlalchemy.orm.session.Session.merge" title="sqlalchemy.orm.session.Session.merge"><tt class="xref py py-meth docutils literal"><span class="pre">merge()</span></tt></a>.</p>
<p>Lets use the canonical example of the User and Address objects:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span>
<span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'user'</span>
<span class="nb">id</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="n">Integer</span><span class="p">,</span> <span class="n">primary_key</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="n">name</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="n">String</span><span class="p">(</span><span class="mi">50</span><span class="p">),</span> <span class="n">nullable</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
<span class="n">addresses</span> <span class="o">=</span> <span class="n">relationship</span><span class="p">(</span><span class="s">"Address"</span><span class="p">,</span> <span class="n">backref</span><span class="o">=</span><span class="s">"user"</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">Address</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span>
<span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'address'</span>
<span class="nb">id</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="n">Integer</span><span class="p">,</span> <span class="n">primary_key</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="n">email_address</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="n">String</span><span class="p">(</span><span class="mi">50</span><span class="p">),</span> <span class="n">nullable</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
<span class="n">user_id</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="n">Integer</span><span class="p">,</span> <span class="n">ForeignKey</span><span class="p">(</span><span class="s">'user.id'</span><span class="p">),</span> <span class="n">nullable</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span></pre></div>
</div>
<p>Assume a <tt class="docutils literal"><span class="pre">User</span></tt> object with one <tt class="docutils literal"><span class="pre">Address</span></tt>, already persistent:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">u1</span> <span class="o">=</span> <span class="n">User</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">'ed'</span><span class="p">,</span> <span class="n">addresses</span><span class="o">=</span><span class="p">[</span><span class="n">Address</span><span class="p">(</span><span class="n">email_address</span><span class="o">=</span><span class="s">'ed@ed.com'</span><span class="p">)])</span>
<span class="gp">>>> </span><span class="n">session</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">u1</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span></pre></div>
</div>
<p>We now create <tt class="docutils literal"><span class="pre">a1</span></tt>, an object outside the session, which we’d like
to merge on top of the existing <tt class="docutils literal"><span class="pre">Address</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">existing_a1</span> <span class="o">=</span> <span class="n">u1</span><span class="o">.</span><span class="n">addresses</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="gp">>>> </span><span class="n">a1</span> <span class="o">=</span> <span class="n">Address</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="n">existing_a1</span><span class="o">.</span><span class="n">id</span><span class="p">)</span></pre></div>
</div>
<p>A surprise would occur if we said this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">a1</span><span class="o">.</span><span class="n">user</span> <span class="o">=</span> <span class="n">u1</span>
<span class="gp">>>> </span><span class="n">a1</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">merge</span><span class="p">(</span><span class="n">a1</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
<span class="go">sqlalchemy.orm.exc.FlushError: New instance <Address at 0x1298f50></span>
<span class="go">with identity key (<class '__main__.Address'>, (1,)) conflicts with</span>
<span class="go">persistent instance <Address at 0x12a25d0></span></pre></div>
</div>
<p>Why is that ? We weren’t careful with our cascades. The assignment
of <tt class="docutils literal"><span class="pre">a1.user</span></tt> to a persistent object cascaded to the backref of <tt class="docutils literal"><span class="pre">User.addresses</span></tt>
and made our <tt class="docutils literal"><span class="pre">a1</span></tt> object pending, as though we had added it. Now we have
<em>two</em> <tt class="docutils literal"><span class="pre">Address</span></tt> objects in the session:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">a1</span> <span class="o">=</span> <span class="n">Address</span><span class="p">()</span>
<span class="gp">>>> </span><span class="n">a1</span><span class="o">.</span><span class="n">user</span> <span class="o">=</span> <span class="n">u1</span>
<span class="gp">>>> </span><span class="n">a1</span> <span class="ow">in</span> <span class="n">session</span>
<span class="go">True</span>
<span class="gp">>>> </span><span class="n">existing_a1</span> <span class="ow">in</span> <span class="n">session</span>
<span class="go">True</span>
<span class="gp">>>> </span><span class="n">a1</span> <span class="ow">is</span> <span class="n">existing_a1</span>
<span class="go">False</span></pre></div>
</div>
<p>Above, our <tt class="docutils literal"><span class="pre">a1</span></tt> is already pending in the session. The
subsequent <a class="reference internal" href="#sqlalchemy.orm.session.Session.merge" title="sqlalchemy.orm.session.Session.merge"><tt class="xref py py-meth docutils literal"><span class="pre">merge()</span></tt></a> operation essentially
does nothing. Cascade can be configured via the <a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship.params.cascade" title="sqlalchemy.orm.relationship"><tt class="xref py py-paramref docutils literal"><span class="pre">cascade</span></tt></a>
option on <a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a>, although in this case it
would mean removing the <tt class="docutils literal"><span class="pre">save-update</span></tt> cascade from the
<tt class="docutils literal"><span class="pre">User.addresses</span></tt> relationship - and usually, that behavior
is extremely convenient. The solution here would usually be to not assign
<tt class="docutils literal"><span class="pre">a1.user</span></tt> to an object already persistent in the target
session.</p>
<p>The <tt class="docutils literal"><span class="pre">cascade_backrefs=False</span></tt> option of <a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a>
will also prevent the <tt class="docutils literal"><span class="pre">Address</span></tt> from
being added to the session via the <tt class="docutils literal"><span class="pre">a1.user</span> <span class="pre">=</span> <span class="pre">u1</span></tt> assignment.</p>
<p>Further detail on cascade operation is at <a class="reference internal" href="#unitofwork-cascades"><em>Cascades</em></a>.</p>
<p>Another example of unexpected state:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">a1</span> <span class="o">=</span> <span class="n">Address</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="n">existing_a1</span><span class="o">.</span><span class="n">id</span><span class="p">,</span> <span class="n">user_id</span><span class="o">=</span><span class="n">u1</span><span class="o">.</span><span class="n">id</span><span class="p">)</span>
<span class="gp">>>> </span><span class="k">assert</span> <span class="n">a1</span><span class="o">.</span><span class="n">user</span> <span class="ow">is</span> <span class="bp">None</span>
<span class="gp">>>> </span><span class="bp">True</span>
<span class="gp">>>> </span><span class="n">a1</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">merge</span><span class="p">(</span><span class="n">a1</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
<span class="go">sqlalchemy.exc.IntegrityError: (IntegrityError) address.user_id</span>
<span class="go">may not be NULL</span></pre></div>
</div>
<p>Here, we accessed a1.user, which returned its default value
of <tt class="docutils literal"><span class="pre">None</span></tt>, which as a result of this access, has been placed in the <tt class="docutils literal"><span class="pre">__dict__</span></tt> of
our object <tt class="docutils literal"><span class="pre">a1</span></tt>. Normally, this operation creates no change event,
so the <tt class="docutils literal"><span class="pre">user_id</span></tt> attribute takes precedence during a
flush. But when we merge the <tt class="docutils literal"><span class="pre">Address</span></tt> object into the session, the operation
is equivalent to:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">existing_a1</span><span class="o">.</span><span class="n">id</span> <span class="o">=</span> <span class="n">existing_a1</span><span class="o">.</span><span class="n">id</span>
<span class="gp">>>> </span><span class="n">existing_a1</span><span class="o">.</span><span class="n">user_id</span> <span class="o">=</span> <span class="n">u1</span><span class="o">.</span><span class="n">id</span>
<span class="gp">>>> </span><span class="n">existing_a1</span><span class="o">.</span><span class="n">user</span> <span class="o">=</span> <span class="bp">None</span></pre></div>
</div>
<p>Where above, both <tt class="docutils literal"><span class="pre">user_id</span></tt> and <tt class="docutils literal"><span class="pre">user</span></tt> are assigned to, and change events
are emitted for both. The <tt class="docutils literal"><span class="pre">user</span></tt> association
takes precedence, and None is applied to <tt class="docutils literal"><span class="pre">user_id</span></tt>, causing a failure.</p>
<p>Most <a class="reference internal" href="#sqlalchemy.orm.session.Session.merge" title="sqlalchemy.orm.session.Session.merge"><tt class="xref py py-meth docutils literal"><span class="pre">merge()</span></tt></a> issues can be examined by first checking -
is the object prematurely in the session ?</p>
<div class="highlight-python+sql"><div class="highlight"><pre><span class="o">>>></span> <span class="n">a1</span> <span class="o">=</span> <span class="n">Address</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="n">existing_a1</span><span class="p">,</span> <span class="n">user_id</span><span class="o">=</span><span class="n">user</span><span class="o">.</span><span class="n">id</span><span class="p">)</span>
<span class="o">>>></span> <span class="k">assert</span> <span class="n">a1</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">session</span>
<span class="o">>>></span> <span class="n">a1</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">merge</span><span class="p">(</span><span class="n">a1</span><span class="p">)</span></pre></div>
</div>
<p>Or is there state on the object that we don’t want ? Examining <tt class="docutils literal"><span class="pre">__dict__</span></tt>
is a quick way to check:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">a1</span> <span class="o">=</span> <span class="n">Address</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="n">existing_a1</span><span class="p">,</span> <span class="n">user_id</span><span class="o">=</span><span class="n">user</span><span class="o">.</span><span class="n">id</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">a1</span><span class="o">.</span><span class="n">user</span>
<span class="gp">>>> </span><span class="n">a1</span><span class="o">.</span><span class="n">__dict__</span>
<span class="go">{'_sa_instance_state': <sqlalchemy.orm.state.InstanceState object at 0x1298d10>,</span>
<span class="go"> 'user_id': 1,</span>
<span class="go"> 'id': 1,</span>
<span class="go"> 'user': None}</span>
<span class="gp">>>> </span><span class="c"># we don't want user=None merged, remove it</span>
<span class="gp">>>> </span><span class="k">del</span> <span class="n">a1</span><span class="o">.</span><span class="n">user</span>
<span class="gp">>>> </span><span class="n">a1</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">merge</span><span class="p">(</span><span class="n">a1</span><span class="p">)</span>
<span class="gp">>>> </span><span class="c"># success</span>
<span class="gp">>>> </span><span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span></pre></div>
</div>
</div>
</div>
<div class="section" id="deleting">
<h3>Deleting<a class="headerlink" href="#deleting" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.Session.delete" title="sqlalchemy.orm.session.Session.delete"><tt class="xref py py-meth docutils literal"><span class="pre">delete()</span></tt></a> method places an instance
into the Session’s list of objects to be marked as deleted:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># mark two objects to be deleted</span>
<span class="n">session</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span><span class="n">obj1</span><span class="p">)</span>
<span class="n">session</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span><span class="n">obj2</span><span class="p">)</span>
<span class="c"># commit (or flush)</span>
<span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span></pre></div>
</div>
<div class="section" id="deleting-from-collections">
<span id="session-deleting-from-collections"></span><h4>Deleting from Collections<a class="headerlink" href="#deleting-from-collections" title="Permalink to this headline">¶</a></h4>
<p>A common confusion that arises regarding <a class="reference internal" href="#sqlalchemy.orm.session.Session.delete" title="sqlalchemy.orm.session.Session.delete"><tt class="xref py py-meth docutils literal"><span class="pre">delete()</span></tt></a> is when
objects which are members of a collection are being deleted. While the
collection member is marked for deletion from the database, this does not
impact the collection itself in memory until the collection is expired.
Below, we illustrate that even after an <tt class="docutils literal"><span class="pre">Address</span></tt> object is marked
for deletion, it’s still present in the collection associated with the
parent <tt class="docutils literal"><span class="pre">User</span></tt>, even after a flush:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">address</span> <span class="o">=</span> <span class="n">user</span><span class="o">.</span><span class="n">addresses</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
<span class="gp">>>> </span><span class="n">session</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span><span class="n">address</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">session</span><span class="o">.</span><span class="n">flush</span><span class="p">()</span>
<span class="gp">>>> </span><span class="n">address</span> <span class="ow">in</span> <span class="n">user</span><span class="o">.</span><span class="n">addresses</span>
<span class="go">True</span></pre></div>
</div>
<p>When the above session is committed, all attributes are expired. The next
access of <tt class="docutils literal"><span class="pre">user.addresses</span></tt> will re-load the collection, revealing the
desired state:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
<span class="gp">>>> </span><span class="n">address</span> <span class="ow">in</span> <span class="n">user</span><span class="o">.</span><span class="n">addresses</span>
<span class="go">False</span></pre></div>
</div>
<p>The usual practice of deleting items within collections is to forego the usage
of <a class="reference internal" href="#sqlalchemy.orm.session.Session.delete" title="sqlalchemy.orm.session.Session.delete"><tt class="xref py py-meth docutils literal"><span class="pre">delete()</span></tt></a> directly, and instead use cascade behavior to
automatically invoke the deletion as a result of removing the object from
the parent collection. The <tt class="docutils literal"><span class="pre">delete-orphan</span></tt> cascade accomplishes this,
as illustrated in the example below:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">mapper</span><span class="p">(</span><span class="n">User</span><span class="p">,</span> <span class="n">users_table</span><span class="p">,</span> <span class="n">properties</span><span class="o">=</span><span class="p">{</span>
<span class="s">'addresses'</span><span class="p">:</span><span class="n">relationship</span><span class="p">(</span><span class="n">Address</span><span class="p">,</span> <span class="n">cascade</span><span class="o">=</span><span class="s">"all, delete, delete-orphan"</span><span class="p">)</span>
<span class="p">})</span>
<span class="k">del</span> <span class="n">user</span><span class="o">.</span><span class="n">addresses</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
<span class="n">session</span><span class="o">.</span><span class="n">flush</span><span class="p">()</span></pre></div>
</div>
<p>Where above, upon removing the <tt class="docutils literal"><span class="pre">Address</span></tt> object from the <tt class="docutils literal"><span class="pre">User.addresses</span></tt>
collection, the <tt class="docutils literal"><span class="pre">delete-orphan</span></tt> cascade has the effect of marking the <tt class="docutils literal"><span class="pre">Address</span></tt>
object for deletion in the same way as passing it to <a class="reference internal" href="#sqlalchemy.orm.session.Session.delete" title="sqlalchemy.orm.session.Session.delete"><tt class="xref py py-meth docutils literal"><span class="pre">delete()</span></tt></a>.</p>
<p>See also <a class="reference internal" href="#unitofwork-cascades"><em>Cascades</em></a> for detail on cascades.</p>
</div>
<div class="section" id="deleting-based-on-filter-criterion">
<h4>Deleting based on Filter Criterion<a class="headerlink" href="#deleting-based-on-filter-criterion" title="Permalink to this headline">¶</a></h4>
<p>The caveat with <tt class="docutils literal"><span class="pre">Session.delete()</span></tt> is that you need to have an object handy
already in order to delete. The Query includes a
<a class="reference internal" href="query.html#sqlalchemy.orm.query.Query.delete" title="sqlalchemy.orm.query.Query.delete"><tt class="xref py py-func docutils literal"><span class="pre">delete()</span></tt></a> method which deletes based on
filtering criteria:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">User</span><span class="p">)</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">User</span><span class="o">.</span><span class="n">id</span><span class="o">==</span><span class="mi">7</span><span class="p">)</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span></pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">Query.delete()</span></tt> method includes functionality to “expire” objects
already in the session which match the criteria. However it does have some
caveats, including that “delete” and “delete-orphan” cascades won’t be fully
expressed for collections which are already loaded. See the API docs for
<a class="reference internal" href="query.html#sqlalchemy.orm.query.Query.delete" title="sqlalchemy.orm.query.Query.delete"><tt class="xref py py-meth docutils literal"><span class="pre">delete()</span></tt></a> for more details.</p>
</div>
</div>
<div class="section" id="flushing">
<span id="session-flushing"></span><h3>Flushing<a class="headerlink" href="#flushing" title="Permalink to this headline">¶</a></h3>
<p>When the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is used with its default
configuration, the flush step is nearly always done transparently.
Specifically, the flush occurs before any individual
<a class="reference internal" href="query.html#sqlalchemy.orm.query.Query" title="sqlalchemy.orm.query.Query"><tt class="xref py py-class docutils literal"><span class="pre">Query</span></tt></a> is issued, as well as within the
<a class="reference internal" href="#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-meth docutils literal"><span class="pre">commit()</span></tt></a> call before the transaction is
committed. It also occurs before a SAVEPOINT is issued when
<a class="reference internal" href="#sqlalchemy.orm.session.Session.begin_nested" title="sqlalchemy.orm.session.Session.begin_nested"><tt class="xref py py-meth docutils literal"><span class="pre">begin_nested()</span></tt></a> is used.</p>
<p>Regardless of the autoflush setting, a flush can always be forced by issuing
<a class="reference internal" href="#sqlalchemy.orm.session.Session.flush" title="sqlalchemy.orm.session.Session.flush"><tt class="xref py py-meth docutils literal"><span class="pre">flush()</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">session</span><span class="o">.</span><span class="n">flush</span><span class="p">()</span></pre></div>
</div>
<p>The “flush-on-Query” aspect of the behavior can be disabled by constructing
<a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> with the flag <tt class="docutils literal"><span class="pre">autoflush=False</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Session</span> <span class="o">=</span> <span class="n">sessionmaker</span><span class="p">(</span><span class="n">autoflush</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span></pre></div>
</div>
<p>Additionally, autoflush can be temporarily disabled by setting the
<tt class="docutils literal"><span class="pre">autoflush</span></tt> flag at any time:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">mysession</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
<span class="n">mysession</span><span class="o">.</span><span class="n">autoflush</span> <span class="o">=</span> <span class="bp">False</span></pre></div>
</div>
<p>Some autoflush-disable recipes are available at <a class="reference external" href="http://www.sqlalchemy.org/trac/wiki/UsageRecipes/DisableAutoflush">DisableAutoFlush</a>.</p>
<p>The flush process <em>always</em> occurs within a transaction, even if the
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> has been configured with
<tt class="docutils literal"><span class="pre">autocommit=True</span></tt>, a setting that disables the session’s persistent
transactional state. If no transaction is present,
<a class="reference internal" href="#sqlalchemy.orm.session.Session.flush" title="sqlalchemy.orm.session.Session.flush"><tt class="xref py py-meth docutils literal"><span class="pre">flush()</span></tt></a> creates its own transaction and
commits it. Any failures during flush will always result in a rollback of
whatever transaction is present. If the Session is not in <tt class="docutils literal"><span class="pre">autocommit=True</span></tt>
mode, an explicit call to <a class="reference internal" href="#sqlalchemy.orm.session.Session.rollback" title="sqlalchemy.orm.session.Session.rollback"><tt class="xref py py-meth docutils literal"><span class="pre">rollback()</span></tt></a> is
required after a flush fails, even though the underlying transaction will have
been rolled back already - this is so that the overall nesting pattern of
so-called “subtransactions” is consistently maintained.</p>
</div>
<div class="section" id="committing">
<span id="session-committing"></span><h3>Committing<a class="headerlink" href="#committing" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-meth docutils literal"><span class="pre">commit()</span></tt></a> is used to commit the current
transaction. It always issues <a class="reference internal" href="#sqlalchemy.orm.session.Session.flush" title="sqlalchemy.orm.session.Session.flush"><tt class="xref py py-meth docutils literal"><span class="pre">flush()</span></tt></a>
beforehand to flush any remaining state to the database; this is independent
of the “autoflush” setting. If no transaction is present, it raises an error.
Note that the default behavior of the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
is that a “transaction” is always present; this behavior can be disabled by
setting <tt class="docutils literal"><span class="pre">autocommit=True</span></tt>. In autocommit mode, a transaction can be
initiated by calling the <a class="reference internal" href="#sqlalchemy.orm.session.Session.begin" title="sqlalchemy.orm.session.Session.begin"><tt class="xref py py-meth docutils literal"><span class="pre">begin()</span></tt></a> method.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The term “transaction” here refers to a transactional
construct within the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> itself which may be
maintaining zero or more actual database (DBAPI) transactions. An individual
DBAPI connection begins participation in the “transaction” as it is first
used to execute a SQL statement, then remains present until the session-level
“transaction” is completed. See <a class="reference internal" href="#unitofwork-transaction"><em>Managing Transactions</em></a> for
further detail.</p>
</div>
<p>Another behavior of <a class="reference internal" href="#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-meth docutils literal"><span class="pre">commit()</span></tt></a> is that by
default it expires the state of all instances present after the commit is
complete. This is so that when the instances are next accessed, either through
attribute access or by them being present in a
<a class="reference internal" href="query.html#sqlalchemy.orm.query.Query" title="sqlalchemy.orm.query.Query"><tt class="xref py py-class docutils literal"><span class="pre">Query</span></tt></a> result set, they receive the most recent
state. To disable this behavior, configure
<a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> with <tt class="docutils literal"><span class="pre">expire_on_commit=False</span></tt>.</p>
<p>Normally, instances loaded into the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
are never changed by subsequent queries; the assumption is that the current
transaction is isolated so the state most recently loaded is correct as long
as the transaction continues. Setting <tt class="docutils literal"><span class="pre">autocommit=True</span></tt> works against this
model to some degree since the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
behaves in exactly the same way with regard to attribute state, except no
transaction is present.</p>
</div>
<div class="section" id="rolling-back">
<span id="session-rollback"></span><h3>Rolling Back<a class="headerlink" href="#rolling-back" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#sqlalchemy.orm.session.Session.rollback" title="sqlalchemy.orm.session.Session.rollback"><tt class="xref py py-meth docutils literal"><span class="pre">rollback()</span></tt></a> rolls back the current
transaction. With a default configured session, the post-rollback state of the
session is as follows:</p>
<blockquote>
<div><ul class="simple">
<li>All transactions are rolled back and all connections returned to the
connection pool, unless the Session was bound directly to a Connection, in
which case the connection is still maintained (but still rolled back).</li>
<li>Objects which were initially in the <em>pending</em> state when they were added
to the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> within the lifespan of the
transaction are expunged, corresponding to their INSERT statement being
rolled back. The state of their attributes remains unchanged.</li>
<li>Objects which were marked as <em>deleted</em> within the lifespan of the
transaction are promoted back to the <em>persistent</em> state, corresponding to
their DELETE statement being rolled back. Note that if those objects were
first <em>pending</em> within the transaction, that operation takes precedence
instead.</li>
<li>All objects not expunged are fully expired.</li>
</ul>
</div></blockquote>
<p>With that state understood, the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> may
safely continue usage after a rollback occurs.</p>
<p>When a <a class="reference internal" href="#sqlalchemy.orm.session.Session.flush" title="sqlalchemy.orm.session.Session.flush"><tt class="xref py py-meth docutils literal"><span class="pre">flush()</span></tt></a> fails, typically for
reasons like primary key, foreign key, or “not nullable” constraint
violations, a <a class="reference internal" href="#sqlalchemy.orm.session.Session.rollback" title="sqlalchemy.orm.session.Session.rollback"><tt class="xref py py-meth docutils literal"><span class="pre">rollback()</span></tt></a> is issued
automatically (it’s currently not possible for a flush to continue after a
partial failure). However, the flush process always uses its own transactional
demarcator called a <em>subtransaction</em>, which is described more fully in the
docstrings for <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>. What it means here is
that even though the database transaction has been rolled back, the end user
must still issue <a class="reference internal" href="#sqlalchemy.orm.session.Session.rollback" title="sqlalchemy.orm.session.Session.rollback"><tt class="xref py py-meth docutils literal"><span class="pre">rollback()</span></tt></a> to fully
reset the state of the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>.</p>
</div>
<div class="section" id="expunging">
<h3>Expunging<a class="headerlink" href="#expunging" title="Permalink to this headline">¶</a></h3>
<p>Expunge removes an object from the Session, sending persistent instances to
the detached state, and pending instances to the transient state:</p>
<div class="highlight-python+sql"><div class="highlight"><pre><span class="n">session</span><span class="o">.</span><span class="n">expunge</span><span class="p">(</span><span class="n">obj1</span><span class="p">)</span></pre></div>
</div>
<p>To remove all items, call <a class="reference internal" href="#sqlalchemy.orm.session.Session.expunge_all" title="sqlalchemy.orm.session.Session.expunge_all"><tt class="xref py py-meth docutils literal"><span class="pre">expunge_all()</span></tt></a>
(this method was formerly known as <tt class="docutils literal"><span class="pre">clear()</span></tt>).</p>
</div>
<div class="section" id="closing">
<h3>Closing<a class="headerlink" href="#closing" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.Session.close" title="sqlalchemy.orm.session.Session.close"><tt class="xref py py-meth docutils literal"><span class="pre">close()</span></tt></a> method issues a
<a class="reference internal" href="#sqlalchemy.orm.session.Session.expunge_all" title="sqlalchemy.orm.session.Session.expunge_all"><tt class="xref py py-meth docutils literal"><span class="pre">expunge_all()</span></tt></a>, and <a class="reference internal" href="../glossary.html#term-releases"><em class="xref std std-term">releases</em></a> any
transactional/connection resources. When connections are returned to the
connection pool, transactional state is rolled back as well.</p>
</div>
<div class="section" id="refreshing-expiring">
<span id="session-expire"></span><h3>Refreshing / Expiring<a class="headerlink" href="#refreshing-expiring" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="../glossary.html#term-expiring"><em class="xref std std-term">Expiring</em></a> means that the database-persisted data held inside a series
of object attributes is erased, in such a way that when those attributes
are next accessed, a SQL query is emitted which will refresh that data from
the database.</p>
<p>When we talk about expiration of data we are usually talking about an object
that is in the <a class="reference internal" href="../glossary.html#term-persistent"><em class="xref std std-term">persistent</em></a> state. For example, if we load an object
as follows:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">user</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">User</span><span class="p">)</span><span class="o">.</span><span class="n">filter_by</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">'user1'</span><span class="p">)</span><span class="o">.</span><span class="n">first</span><span class="p">()</span></pre></div>
</div>
<p>The above <tt class="docutils literal"><span class="pre">User</span></tt> object is persistent, and has a series of attributes
present; if we were to look inside its <tt class="docutils literal"><span class="pre">__dict__</span></tt>, we’d see that state
loaded:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">user</span><span class="o">.</span><span class="n">__dict__</span>
<span class="go">{</span>
<span class="go"> 'id': 1, 'name': u'user1',</span>
<span class="go"> '_sa_instance_state': <...>,</span>
<span class="go">}</span></pre></div>
</div>
<p>where <tt class="docutils literal"><span class="pre">id</span></tt> and <tt class="docutils literal"><span class="pre">name</span></tt> refer to those columns in the database.
<tt class="docutils literal"><span class="pre">_sa_instance_state</span></tt> is a non-database-persisted value used by SQLAlchemy
internally (it refers to the <a class="reference internal" href="internals.html#sqlalchemy.orm.state.InstanceState" title="sqlalchemy.orm.state.InstanceState"><tt class="xref py py-class docutils literal"><span class="pre">InstanceState</span></tt></a> for the instance.
While not directly relevant to this section, if we want to get at it,
we should use the <a class="reference internal" href="../core/inspection.html#sqlalchemy.inspection.inspect" title="sqlalchemy.inspection.inspect"><tt class="xref py py-func docutils literal"><span class="pre">inspect()</span></tt></a> function to access it).</p>
<p>At this point, the state in our <tt class="docutils literal"><span class="pre">User</span></tt> object matches that of the loaded
database row. But upon expiring the object using a method such as
<a class="reference internal" href="#sqlalchemy.orm.session.Session.expire" title="sqlalchemy.orm.session.Session.expire"><tt class="xref py py-meth docutils literal"><span class="pre">Session.expire()</span></tt></a>, we see that the state is removed:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">session</span><span class="o">.</span><span class="n">expire</span><span class="p">(</span><span class="n">user</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">user</span><span class="o">.</span><span class="n">__dict__</span>
<span class="go">{'_sa_instance_state': <...>}</span></pre></div>
</div>
<p>We see that while the internal “state” still hangs around, the values which
correspond to the <tt class="docutils literal"><span class="pre">id</span></tt> and <tt class="docutils literal"><span class="pre">name</span></tt> columns are gone. If we were to access
one of these columns and are watching SQL, we’d see this:</p>
<div class="highlight-python+sql"><div class="highlight"><pre><span class="o">>>></span> <span class="k">print</span><span class="p">(</span><span class="n">user</span><span class="o">.</span><span class="n">name</span><span class="p">)</span>
<div class='show_sql'>SELECT user.id AS user_id, user.name AS user_name
FROM user
WHERE user.id = ?
(1,)</div><span class="n">user1</span></pre></div>
</div>
<p>Above, upon accessing the expired attribute <tt class="docutils literal"><span class="pre">user.name</span></tt>, the ORM initiated
a <a class="reference internal" href="../glossary.html#term-lazy-load"><em class="xref std std-term">lazy load</em></a> to retrieve the most recent state from the database,
by emitting a SELECT for the user row to which this user refers. Afterwards,
the <tt class="docutils literal"><span class="pre">__dict__</span></tt> is again populated:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">user</span><span class="o">.</span><span class="n">__dict__</span>
<span class="go">{</span>
<span class="go"> 'id': 1, 'name': u'user1',</span>
<span class="go"> '_sa_instance_state': <...>,</span>
<span class="go">}</span></pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">While we are peeking inside of <tt class="docutils literal"><span class="pre">__dict__</span></tt> in order to see a bit
of what SQLAlchemy does with object attributes, we <strong>should not modify</strong>
the contents of <tt class="docutils literal"><span class="pre">__dict__</span></tt> directly, at least as far as those attributes
which the SQLAlchemy ORM is maintaining (other attributes outside of SQLA’s
realm are fine). This is because SQLAlchemy uses <a class="reference internal" href="../glossary.html#term-descriptors"><em class="xref std std-term">descriptors</em></a> in
order to track the changes we make to an object, and when we modify <tt class="docutils literal"><span class="pre">__dict__</span></tt>
directly, the ORM won’t be able to track that we changed something.</p>
</div>
<p>Another key behavior of both <a class="reference internal" href="#sqlalchemy.orm.session.Session.expire" title="sqlalchemy.orm.session.Session.expire"><tt class="xref py py-meth docutils literal"><span class="pre">expire()</span></tt></a> and <a class="reference internal" href="#sqlalchemy.orm.session.Session.refresh" title="sqlalchemy.orm.session.Session.refresh"><tt class="xref py py-meth docutils literal"><span class="pre">refresh()</span></tt></a>
is that all un-flushed changes on an object are discarded. That is,
if we were to modify an attribute on our <tt class="docutils literal"><span class="pre">User</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">user</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="s">'user2'</span></pre></div>
</div>
<p>but then we call <a class="reference internal" href="#sqlalchemy.orm.session.Session.expire" title="sqlalchemy.orm.session.Session.expire"><tt class="xref py py-meth docutils literal"><span class="pre">expire()</span></tt></a> without first calling <a class="reference internal" href="#sqlalchemy.orm.session.Session.flush" title="sqlalchemy.orm.session.Session.flush"><tt class="xref py py-meth docutils literal"><span class="pre">flush()</span></tt></a>,
our pending value of <tt class="docutils literal"><span class="pre">'user2'</span></tt> is discarded:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">session</span><span class="o">.</span><span class="n">expire</span><span class="p">(</span><span class="n">user</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">user</span><span class="o">.</span><span class="n">name</span>
<span class="go">'user1'</span></pre></div>
</div>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.Session.expire" title="sqlalchemy.orm.session.Session.expire"><tt class="xref py py-meth docutils literal"><span class="pre">expire()</span></tt></a> method can be used to mark as “expired” all ORM-mapped
attributes for an instance:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># expire all ORM-mapped attributes on obj1</span>
<span class="n">session</span><span class="o">.</span><span class="n">expire</span><span class="p">(</span><span class="n">obj1</span><span class="p">)</span></pre></div>
</div>
<p>it can also be passed a list of string attribute names, referring to specific
attributes to be marked as expired:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># expire only attributes obj1.attr1, obj1.attr2</span>
<span class="n">session</span><span class="o">.</span><span class="n">expire</span><span class="p">(</span><span class="n">obj1</span><span class="p">,</span> <span class="p">[</span><span class="s">'attr1'</span><span class="p">,</span> <span class="s">'attr2'</span><span class="p">])</span></pre></div>
</div>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.Session.refresh" title="sqlalchemy.orm.session.Session.refresh"><tt class="xref py py-meth docutils literal"><span class="pre">refresh()</span></tt></a> method has a similar interface, but instead
of expiring, it emits an immediate SELECT for the object’s row immediately:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># reload all attributes on obj1</span>
<span class="n">session</span><span class="o">.</span><span class="n">refresh</span><span class="p">(</span><span class="n">obj1</span><span class="p">)</span></pre></div>
</div>
<p><a class="reference internal" href="#sqlalchemy.orm.session.Session.refresh" title="sqlalchemy.orm.session.Session.refresh"><tt class="xref py py-meth docutils literal"><span class="pre">refresh()</span></tt></a> also accepts a list of string attribute names,
but unlike <a class="reference internal" href="#sqlalchemy.orm.session.Session.expire" title="sqlalchemy.orm.session.Session.expire"><tt class="xref py py-meth docutils literal"><span class="pre">expire()</span></tt></a>, expects at least one name to
be that of a column-mapped attribute:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># reload obj1.attr1, obj1.attr2</span>
<span class="n">session</span><span class="o">.</span><span class="n">refresh</span><span class="p">(</span><span class="n">obj1</span><span class="p">,</span> <span class="p">[</span><span class="s">'attr1'</span><span class="p">,</span> <span class="s">'attr2'</span><span class="p">])</span></pre></div>
</div>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.Session.expire_all" title="sqlalchemy.orm.session.Session.expire_all"><tt class="xref py py-meth docutils literal"><span class="pre">Session.expire_all()</span></tt></a> method allows us to essentially call
<a class="reference internal" href="#sqlalchemy.orm.session.Session.expire" title="sqlalchemy.orm.session.Session.expire"><tt class="xref py py-meth docutils literal"><span class="pre">Session.expire()</span></tt></a> on all objects contained within the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
at once:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">session</span><span class="o">.</span><span class="n">expire_all</span><span class="p">()</span></pre></div>
</div>
<div class="section" id="what-actually-loads">
<h4>What Actually Loads<a class="headerlink" href="#what-actually-loads" title="Permalink to this headline">¶</a></h4>
<p>The SELECT statement that’s emitted when an object marked with <a class="reference internal" href="#sqlalchemy.orm.session.Session.expire" title="sqlalchemy.orm.session.Session.expire"><tt class="xref py py-meth docutils literal"><span class="pre">expire()</span></tt></a>
or loaded with <a class="reference internal" href="#sqlalchemy.orm.session.Session.refresh" title="sqlalchemy.orm.session.Session.refresh"><tt class="xref py py-meth docutils literal"><span class="pre">refresh()</span></tt></a> varies based on several factors, including:</p>
<ul class="simple">
<li>The load of expired attributes is triggered from <strong>column-mapped attributes only</strong>.
While any kind of attribute can be marked as expired, including a
<a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> - mapped attribute, accessing an expired <a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a>
attribute will emit a load only for that attribute, using standard
relationship-oriented lazy loading. Column-oriented attributes, even if
expired, will not load as part of this operation, and instead will load when
any column-oriented attribute is accessed.</li>
<li><a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a>- mapped attributes will not load in response to
expired column-based attributes being accessed.</li>
<li>Regarding relationships, <a class="reference internal" href="#sqlalchemy.orm.session.Session.refresh" title="sqlalchemy.orm.session.Session.refresh"><tt class="xref py py-meth docutils literal"><span class="pre">refresh()</span></tt></a> is more restrictive than
<a class="reference internal" href="#sqlalchemy.orm.session.Session.expire" title="sqlalchemy.orm.session.Session.expire"><tt class="xref py py-meth docutils literal"><span class="pre">expire()</span></tt></a> with regards to attributes that aren’t column-mapped.
Calling <a class="reference internal" href="events.html#sqlalchemy.orm.events.InstanceEvents.refresh" title="sqlalchemy.orm.events.InstanceEvents.refresh"><tt class="xref py py-meth docutils literal"><span class="pre">refresh()</span></tt></a> and passing a list of names that only includes
relationship-mapped attributes will actually raise an error.
In any case, non-eager-loading <a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> attributes will not be
included in any refresh operation.</li>
<li><a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> attributes configured as “eager loading” via the
<a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship.params.lazy" title="sqlalchemy.orm.relationship"><tt class="xref py py-paramref docutils literal"><span class="pre">lazy</span></tt></a> parameter will load in the case of
<a class="reference internal" href="#sqlalchemy.orm.session.Session.refresh" title="sqlalchemy.orm.session.Session.refresh"><tt class="xref py py-meth docutils literal"><span class="pre">refresh()</span></tt></a>, if either no attribute names are specified, or
if their names are inclued in the list of attributes to be
refreshed.</li>
<li>Attributes that are configured as <a class="reference internal" href="mapper_config.html#sqlalchemy.orm.deferred" title="sqlalchemy.orm.deferred"><tt class="xref py py-func docutils literal"><span class="pre">deferred()</span></tt></a> will not normally load,
during either the expired-attribute load or during a refresh.
An unloaded attribute that’s <a class="reference internal" href="mapper_config.html#sqlalchemy.orm.deferred" title="sqlalchemy.orm.deferred"><tt class="xref py py-func docutils literal"><span class="pre">deferred()</span></tt></a> instead loads on its own when directly
accessed, or if part of a “group” of deferred attributes where an unloaded
attribute in that group is accessed.</li>
<li>For expired attributes that are loaded on access, a joined-inheritance table
mapping will emit a SELECT that typically only includes those tables for which
unloaded attributes are present. The action here is sophisticated enough
to load only the parent or child table, for example, if the subset of columns
that were originally expired encompass only one or the other of those tables.</li>
<li>When <a class="reference internal" href="#sqlalchemy.orm.session.Session.refresh" title="sqlalchemy.orm.session.Session.refresh"><tt class="xref py py-meth docutils literal"><span class="pre">refresh()</span></tt></a> is used on a joined-inheritance table mapping,
the SELECT emitted will resemble that of when <a class="reference internal" href="#sqlalchemy.orm.session.Session.query" title="sqlalchemy.orm.session.Session.query"><tt class="xref py py-meth docutils literal"><span class="pre">Session.query()</span></tt></a> is
used on the target object’s class. This is typically all those tables that
are set up as part of the mapping.</li>
</ul>
</div>
<div class="section" id="when-to-expire-or-refresh">
<h4>When to Expire or Refresh<a class="headerlink" href="#when-to-expire-or-refresh" title="Permalink to this headline">¶</a></h4>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> uses the expiration feature automatically whenever
the transaction referred to by the session ends. Meaning, whenever <a class="reference internal" href="#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-meth docutils literal"><span class="pre">Session.commit()</span></tt></a>
or <a class="reference internal" href="#sqlalchemy.orm.session.Session.rollback" title="sqlalchemy.orm.session.Session.rollback"><tt class="xref py py-meth docutils literal"><span class="pre">Session.rollback()</span></tt></a> is called, all objects within the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
are expired, using a feature equivalent to that of the <a class="reference internal" href="#sqlalchemy.orm.session.Session.expire_all" title="sqlalchemy.orm.session.Session.expire_all"><tt class="xref py py-meth docutils literal"><span class="pre">Session.expire_all()</span></tt></a>
method. The rationale is that the end of a transaction is a
demarcating point at which there is no more context available in order to know
what the current state of the database is, as any number of other transactions
may be affecting it. Only when a new transaction starts can we again have access
to the current state of the database, at which point any number of changes
may have occurred.</p>
<div class="sidebar">
<p class="first sidebar-title">Transaction Isolation</p>
<p class="last">Of course, most databases are capable of handling
multiple transactions at once, even involving the same rows of data. When
a relational database handles multiple transactions involving the same
tables or rows, this is when the <a class="reference internal" href="../glossary.html#term-isolation"><em class="xref std std-term">isolation</em></a> aspect of the database comes
into play. The isolation behavior of different databases varies considerably
and even on a single database can be configured to behave in different ways
(via the so-called <em class="xref std std-term">isolation level</em> setting). In that sense, the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
can’t fully predict when the same SELECT statement, emitted a second time,
will definitely return the data we already have, or will return new data.
So as a best guess, it assumes that within the scope of a transaction, unless
it is known that a SQL expression has been emitted to modify a particular row,
there’s no need to refresh a row unless explicitly told to do so.</p>
</div>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.Session.expire" title="sqlalchemy.orm.session.Session.expire"><tt class="xref py py-meth docutils literal"><span class="pre">Session.expire()</span></tt></a> and <a class="reference internal" href="#sqlalchemy.orm.session.Session.refresh" title="sqlalchemy.orm.session.Session.refresh"><tt class="xref py py-meth docutils literal"><span class="pre">Session.refresh()</span></tt></a> methods are used in
those cases when one wants to force an object to re-load its data from the
database, in those cases when it is known that the current state of data
is possibly stale. Reasons for this might include:</p>
<ul class="simple">
<li>some SQL has been emitted within the transaction outside of the
scope of the ORM’s object handling, such as if a <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table.update" title="sqlalchemy.schema.Table.update"><tt class="xref py py-meth docutils literal"><span class="pre">Table.update()</span></tt></a> construct
were emitted using the <a class="reference internal" href="#sqlalchemy.orm.session.Session.execute" title="sqlalchemy.orm.session.Session.execute"><tt class="xref py py-meth docutils literal"><span class="pre">Session.execute()</span></tt></a> method;</li>
<li>if the application
is attempting to acquire data that is known to have been modified in a
concurrent transaction, and it is also known that the isolation rules in effect
allow this data to be visible.</li>
</ul>
<p>The second bullet has the important caveat that “it is also known that the isolation rules in effect
allow this data to be visible.” This means that it cannot be assumed that an
UPDATE that happened on another database connection will yet be visible here
locally; in many cases, it will not. This is why if one wishes to use
<a class="reference internal" href="#sqlalchemy.orm.session.Session.expire" title="sqlalchemy.orm.session.Session.expire"><tt class="xref py py-meth docutils literal"><span class="pre">expire()</span></tt></a> or <a class="reference internal" href="events.html#sqlalchemy.orm.events.InstanceEvents.refresh" title="sqlalchemy.orm.events.InstanceEvents.refresh"><tt class="xref py py-meth docutils literal"><span class="pre">refresh()</span></tt></a> in order to view data between ongoing
transactions, an understanding of the isolation behavior in effect is essential.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p><a class="reference internal" href="#sqlalchemy.orm.session.Session.expire" title="sqlalchemy.orm.session.Session.expire"><tt class="xref py py-meth docutils literal"><span class="pre">Session.expire()</span></tt></a></p>
<p><a class="reference internal" href="#sqlalchemy.orm.session.Session.expire_all" title="sqlalchemy.orm.session.Session.expire_all"><tt class="xref py py-meth docutils literal"><span class="pre">Session.expire_all()</span></tt></a></p>
<p><a class="reference internal" href="#sqlalchemy.orm.session.Session.refresh" title="sqlalchemy.orm.session.Session.refresh"><tt class="xref py py-meth docutils literal"><span class="pre">Session.refresh()</span></tt></a></p>
<p><a class="reference internal" href="../glossary.html#term-isolation"><em class="xref std std-term">isolation</em></a> - glossary explanation of isolation which includes links
to Wikipedia.</p>
<p class="last"><a class="reference external" href="http://techspot.zzzeek.org/2012/11/14/pycon-canada-the-sqlalchemy-session-in-depth/">The SQLAlchemy Session In-Depth</a> - a video + slides with an in-depth discussion of the object
lifecycle including the role of data expiration.</p>
</div>
</div>
</div>
<div class="section" id="session-attributes">
<h3>Session Attributes<a class="headerlink" href="#session-attributes" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> itself acts somewhat like a
set-like collection. All items present may be accessed using the iterator
interface:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">for</span> <span class="n">obj</span> <span class="ow">in</span> <span class="n">session</span><span class="p">:</span>
<span class="k">print</span> <span class="n">obj</span></pre></div>
</div>
<p>And presence may be tested for using regular “contains” semantics:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">if</span> <span class="n">obj</span> <span class="ow">in</span> <span class="n">session</span><span class="p">:</span>
<span class="k">print</span> <span class="s">"Object is present"</span></pre></div>
</div>
<p>The session is also keeping track of all newly created (i.e. pending) objects,
all objects which have had changes since they were last loaded or saved (i.e.
“dirty”), and everything that’s been marked as deleted:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># pending objects recently added to the Session</span>
<span class="n">session</span><span class="o">.</span><span class="n">new</span>
<span class="c"># persistent objects which currently have changes detected</span>
<span class="c"># (this collection is now created on the fly each time the property is called)</span>
<span class="n">session</span><span class="o">.</span><span class="n">dirty</span>
<span class="c"># persistent objects that have been marked as deleted via session.delete(obj)</span>
<span class="n">session</span><span class="o">.</span><span class="n">deleted</span>
<span class="c"># dictionary of all persistent objects, keyed on their</span>
<span class="c"># identity key</span>
<span class="n">session</span><span class="o">.</span><span class="n">identity_map</span></pre></div>
</div>
<p>(Documentation: <a class="reference internal" href="#sqlalchemy.orm.session.Session.new" title="sqlalchemy.orm.session.Session.new"><tt class="xref py py-attr docutils literal"><span class="pre">Session.new</span></tt></a>, <a class="reference internal" href="#sqlalchemy.orm.session.Session.dirty" title="sqlalchemy.orm.session.Session.dirty"><tt class="xref py py-attr docutils literal"><span class="pre">Session.dirty</span></tt></a>,
<a class="reference internal" href="#sqlalchemy.orm.session.Session.deleted" title="sqlalchemy.orm.session.Session.deleted"><tt class="xref py py-attr docutils literal"><span class="pre">Session.deleted</span></tt></a>, <a class="reference internal" href="#sqlalchemy.orm.session.Session.identity_map" title="sqlalchemy.orm.session.Session.identity_map"><tt class="xref py py-attr docutils literal"><span class="pre">Session.identity_map</span></tt></a>).</p>
<p>Note that objects within the session are by default <em>weakly referenced</em>. This
means that when they are dereferenced in the outside application, they fall
out of scope from within the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> as well
and are subject to garbage collection by the Python interpreter. The
exceptions to this include objects which are pending, objects which are marked
as deleted, or persistent objects which have pending changes on them. After a
full flush, these collections are all empty, and all objects are again weakly
referenced. To disable the weak referencing behavior and force all objects
within the session to remain until explicitly expunged, configure
<a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> with the <tt class="docutils literal"><span class="pre">weak_identity_map=False</span></tt>
setting.</p>
</div>
</div>
<div class="section" id="cascades">
<span id="unitofwork-cascades"></span><h2>Cascades<a class="headerlink" href="#cascades" title="Permalink to this headline">¶</a></h2>
<p>Mappers support the concept of configurable <em class="xref std std-term">cascade</em> behavior on
<a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> constructs. This refers
to how operations performed on a “parent” object relative to a
particular <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> should be propagated to items
referred to by that relationship (e.g. “child” objects), and is
affected by the <a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship.params.cascade" title="sqlalchemy.orm.relationship"><tt class="xref py py-paramref docutils literal"><span class="pre">relationship.cascade</span></tt></a> option.</p>
<p>The default behavior of cascade is limited to cascades of the
so-called <a class="reference internal" href="#cascade-save-update"><em>save-update</em></a> and <a class="reference internal" href="#cascade-merge"><em>merge</em></a> settings.
The typical “alternative” setting for cascade is to add
the <a class="reference internal" href="#cascade-delete"><em>delete</em></a> and <a class="reference internal" href="#cascade-delete-orphan"><em>delete-orphan</em></a> options;
these settings are appropriate for related objects which only exist as
long as they are attached to their parent, and are otherwise deleted.</p>
<p>Cascade behavior is configured using the by changing the
<a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship.params.cascade" title="sqlalchemy.orm.relationship"><tt class="xref py py-paramref docutils literal"><span class="pre">cascade</span></tt></a> option on
<a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Order</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span>
<span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'order'</span>
<span class="n">items</span> <span class="o">=</span> <span class="n">relationship</span><span class="p">(</span><span class="s">"Item"</span><span class="p">,</span> <span class="n">cascade</span><span class="o">=</span><span class="s">"all, delete-orphan"</span><span class="p">)</span>
<span class="n">customer</span> <span class="o">=</span> <span class="n">relationship</span><span class="p">(</span><span class="s">"User"</span><span class="p">,</span> <span class="n">cascade</span><span class="o">=</span><span class="s">"save-update"</span><span class="p">)</span></pre></div>
</div>
<p>To set cascades on a backref, the same flag can be used with the
<a class="reference internal" href="relationships.html#sqlalchemy.orm.backref" title="sqlalchemy.orm.backref"><tt class="xref py py-func docutils literal"><span class="pre">backref()</span></tt></a> function, which ultimately feeds
its arguments back into <a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Item</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span>
<span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'item'</span>
<span class="n">order</span> <span class="o">=</span> <span class="n">relationship</span><span class="p">(</span><span class="s">"Order"</span><span class="p">,</span>
<span class="n">backref</span><span class="o">=</span><span class="n">backref</span><span class="p">(</span><span class="s">"items"</span><span class="p">,</span> <span class="n">cascade</span><span class="o">=</span><span class="s">"all, delete-orphan"</span><span class="p">)</span>
<span class="p">)</span></pre></div>
</div>
<div class="sidebar">
<p class="first sidebar-title">The Origins of Cascade</p>
<p class="last">SQLAlchemy’s notion of cascading behavior on relationships,
as well as the options to configure them, are primarily derived
from the similar feature in the Hibernate ORM; Hibernate refers
to “cascade” in a few places such as in
<a class="reference external" href="https://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/example-parentchild.html">Example: Parent/Child</a>.
If cascades are confusing, we’ll refer to their conclusion,
stating “The sections we have just covered can be a bit confusing.
However, in practice, it all works out nicely.”</p>
</div>
<p>The default value of <a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship.params.cascade" title="sqlalchemy.orm.relationship"><tt class="xref py py-paramref docutils literal"><span class="pre">cascade</span></tt></a> is <tt class="docutils literal"><span class="pre">save-update,</span> <span class="pre">merge</span></tt>.
The typical alternative setting for this parameter is either
<tt class="docutils literal"><span class="pre">all</span></tt> or more commonly <tt class="docutils literal"><span class="pre">all,</span> <span class="pre">delete-orphan</span></tt>. The <tt class="docutils literal"><span class="pre">all</span></tt> symbol
is a synonym for <tt class="docutils literal"><span class="pre">save-update,</span> <span class="pre">merge,</span> <span class="pre">refresh-expire,</span> <span class="pre">expunge,</span> <span class="pre">delete</span></tt>,
and using it in conjunction with <tt class="docutils literal"><span class="pre">delete-orphan</span></tt> indicates that the child
object should follow along with its parent in all cases, and be deleted once
it is no longer associated with that parent.</p>
<p>The list of available values which can be specified for
the <a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship.params.cascade" title="sqlalchemy.orm.relationship"><tt class="xref py py-paramref docutils literal"><span class="pre">cascade</span></tt></a> parameter are described in the following subsections.</p>
<div class="section" id="save-update">
<span id="cascade-save-update"></span><h3>save-update<a class="headerlink" href="#save-update" title="Permalink to this headline">¶</a></h3>
<p><tt class="docutils literal"><span class="pre">save-update</span></tt> cascade indicates that when an object is placed into a
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> via <a class="reference internal" href="#sqlalchemy.orm.session.Session.add" title="sqlalchemy.orm.session.Session.add"><tt class="xref py py-meth docutils literal"><span class="pre">Session.add()</span></tt></a>, all the objects associated
with it via this <a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> should also be added to that
same <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>. Suppose we have an object <tt class="docutils literal"><span class="pre">user1</span></tt> with two
related objects <tt class="docutils literal"><span class="pre">address1</span></tt>, <tt class="docutils literal"><span class="pre">address2</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">user1</span> <span class="o">=</span> <span class="n">User</span><span class="p">()</span>
<span class="gp">>>> </span><span class="n">address1</span><span class="p">,</span> <span class="n">address2</span> <span class="o">=</span> <span class="n">Address</span><span class="p">(),</span> <span class="n">Address</span><span class="p">()</span>
<span class="gp">>>> </span><span class="n">user1</span><span class="o">.</span><span class="n">addresses</span> <span class="o">=</span> <span class="p">[</span><span class="n">address1</span><span class="p">,</span> <span class="n">address2</span><span class="p">]</span></pre></div>
</div>
<p>If we add <tt class="docutils literal"><span class="pre">user1</span></tt> to a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>, it will also add
<tt class="docutils literal"><span class="pre">address1</span></tt>, <tt class="docutils literal"><span class="pre">address2</span></tt> implicitly:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">sess</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
<span class="gp">>>> </span><span class="n">sess</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">user1</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">address1</span> <span class="ow">in</span> <span class="n">sess</span>
<span class="go">True</span></pre></div>
</div>
<p><tt class="docutils literal"><span class="pre">save-update</span></tt> cascade also affects attribute operations for objects
that are already present in a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>. If we add a third
object, <tt class="docutils literal"><span class="pre">address3</span></tt> to the <tt class="docutils literal"><span class="pre">user1.addresses</span></tt> collection, it
becomes part of the state of that <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">address3</span> <span class="o">=</span> <span class="n">Address</span><span class="p">()</span>
<span class="gp">>>> </span><span class="n">user1</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">address3</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">address3</span> <span class="ow">in</span> <span class="n">sess</span>
<span class="gp">>>> </span><span class="bp">True</span></pre></div>
</div>
<p><tt class="docutils literal"><span class="pre">save-update</span></tt> has the possibly surprising behavior which is that
persistent objects which were <em>removed</em> from a collection
or in some cases a scalar attribute
may also be pulled into the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> of a parent object; this is
so that the flush process may handle that related object appropriately.
This case can usually only arise if an object is removed from one <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
and added to another:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">user1</span> <span class="o">=</span> <span class="n">sess1</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">User</span><span class="p">)</span><span class="o">.</span><span class="n">filter_by</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="n">first</span><span class="p">()</span>
<span class="gp">>>> </span><span class="n">address1</span> <span class="o">=</span> <span class="n">user1</span><span class="o">.</span><span class="n">addresses</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="gp">>>> </span><span class="n">sess1</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> <span class="c"># user1, address1 no longer associated with sess1</span>
<span class="gp">>>> </span><span class="n">user1</span><span class="o">.</span><span class="n">addresses</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">address1</span><span class="p">)</span> <span class="c"># address1 no longer associated with user1</span>
<span class="gp">>>> </span><span class="n">sess2</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
<span class="gp">>>> </span><span class="n">sess2</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">user1</span><span class="p">)</span> <span class="c"># ... but it still gets added to the new session,</span>
<span class="gp">>>> </span><span class="n">address1</span> <span class="ow">in</span> <span class="n">sess2</span> <span class="c"># because it's still "pending" for flush</span>
<span class="go">True</span></pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">save-update</span></tt> cascade is on by default, and is typically taken
for granted; it simplifies code by allowing a single call to
<a class="reference internal" href="#sqlalchemy.orm.session.Session.add" title="sqlalchemy.orm.session.Session.add"><tt class="xref py py-meth docutils literal"><span class="pre">Session.add()</span></tt></a> to register an entire structure of objects within
that <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> at once. While it can be disabled, there
is usually not a need to do so.</p>
<p>One case where <tt class="docutils literal"><span class="pre">save-update</span></tt> cascade does sometimes get in the way is in that
it takes place in both directions for bi-directional relationships, e.g.
backrefs, meaning that the association of a child object with a particular parent
can have the effect of the parent object being implicitly associated with that
child object’s <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>; this pattern, as well as how to modify its
behavior using the <a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship.params.cascade_backrefs" title="sqlalchemy.orm.relationship"><tt class="xref py py-paramref docutils literal"><span class="pre">cascade_backrefs</span></tt></a> flag,
is discussed in the section <a class="reference internal" href="#backref-cascade"><em>Controlling Cascade on Backrefs</em></a>.</p>
</div>
<div class="section" id="delete">
<span id="cascade-delete"></span><h3>delete<a class="headerlink" href="#delete" title="Permalink to this headline">¶</a></h3>
<p>The <tt class="docutils literal"><span class="pre">delete</span></tt> cascade indicates that when a “parent” object
is marked for deletion, its related “child” objects should also be marked
for deletion. If for example we we have a relationship <tt class="docutils literal"><span class="pre">User.addresses</span></tt>
with <tt class="docutils literal"><span class="pre">delete</span></tt> cascade configured:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span>
<span class="c"># ...</span>
<span class="n">addresses</span> <span class="o">=</span> <span class="n">relationship</span><span class="p">(</span><span class="s">"Address"</span><span class="p">,</span> <span class="n">cascade</span><span class="o">=</span><span class="s">"save-update, merge, delete"</span><span class="p">)</span></pre></div>
</div>
<p>If using the above mapping, we have a <tt class="docutils literal"><span class="pre">User</span></tt> object and two
related <tt class="docutils literal"><span class="pre">Address</span></tt> objects:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">user1</span> <span class="o">=</span> <span class="n">sess</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">User</span><span class="p">)</span><span class="o">.</span><span class="n">filter_by</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="n">first</span><span class="p">()</span>
<span class="gp">>>> </span><span class="n">address1</span><span class="p">,</span> <span class="n">address2</span> <span class="o">=</span> <span class="n">user1</span><span class="o">.</span><span class="n">addresses</span></pre></div>
</div>
<p>If we mark <tt class="docutils literal"><span class="pre">user1</span></tt> for deletion, after the flush operation proceeds,
<tt class="docutils literal"><span class="pre">address1</span></tt> and <tt class="docutils literal"><span class="pre">address2</span></tt> will also be deleted:</p>
<div class="highlight-python+sql"><div class="highlight"><pre><span class="o">>>></span> <span class="n">sess</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span><span class="n">user1</span><span class="p">)</span>
<span class="o">>>></span> <span class="n">sess</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
<div class='show_sql'>DELETE FROM address WHERE address.id = ?
((1,), (2,))
DELETE FROM user WHERE user.id = ?
(1,)
COMMIT</div></pre></div>
</div>
<p>Alternatively, if our <tt class="docutils literal"><span class="pre">User.addresses</span></tt> relationship does <em>not</em> have
<tt class="docutils literal"><span class="pre">delete</span></tt> cascade, SQLAlchemy’s default behavior is to instead de-associate
<tt class="docutils literal"><span class="pre">address1</span></tt> and <tt class="docutils literal"><span class="pre">address2</span></tt> from <tt class="docutils literal"><span class="pre">user1</span></tt> by setting their foreign key
reference to <tt class="docutils literal"><span class="pre">NULL</span></tt>. Using a mapping as follows:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span>
<span class="c"># ...</span>
<span class="n">addresses</span> <span class="o">=</span> <span class="n">relationship</span><span class="p">(</span><span class="s">"Address"</span><span class="p">)</span></pre></div>
</div>
<p>Upon deletion of a parent <tt class="docutils literal"><span class="pre">User</span></tt> object, the rows in <tt class="docutils literal"><span class="pre">address</span></tt> are not
deleted, but are instead de-associated:</p>
<div class="highlight-python+sql"><div class="highlight"><pre><span class="o">>>></span> <span class="n">sess</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span><span class="n">user1</span><span class="p">)</span>
<span class="o">>>></span> <span class="n">sess</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
<div class='show_sql'>UPDATE address SET user_id=? WHERE address.id = ?
(None, 1)
UPDATE address SET user_id=? WHERE address.id = ?
(None, 2)
DELETE FROM user WHERE user.id = ?
(1,)
COMMIT</div></pre></div>
</div>
<p><tt class="docutils literal"><span class="pre">delete</span></tt> cascade is more often than not used in conjunction with
<a class="reference internal" href="#cascade-delete-orphan"><em>delete-orphan</em></a> cascade, which will emit a DELETE for the related
row if the “child” object is deassociated from the parent. The combination
of <tt class="docutils literal"><span class="pre">delete</span></tt> and <tt class="docutils literal"><span class="pre">delete-orphan</span></tt> cascade covers both situations where
SQLAlchemy has to decide between setting a foreign key column to NULL versus
deleting the row entirely.</p>
<div class="topic">
<p class="topic-title first">ORM-level “delete” cascade vs. FOREIGN KEY level “ON DELETE” cascade</p>
<p>The behavior of SQLAlchemy’s “delete” cascade has a lot of overlap with the
<tt class="docutils literal"><span class="pre">ON</span> <span class="pre">DELETE</span> <span class="pre">CASCADE</span></tt> feature of a database foreign key, as well
as with that of the <tt class="docutils literal"><span class="pre">ON</span> <span class="pre">DELETE</span> <span class="pre">SET</span> <span class="pre">NULL</span></tt> foreign key setting when “delete”
cascade is not specified. Database level “ON DELETE” cascades are specific to the
“FOREIGN KEY” construct of the relational database; SQLAlchemy allows
configuration of these schema-level constructs at the <a class="reference internal" href="../glossary.html#term-ddl"><em class="xref std std-term">DDL</em></a> level
using options on <a class="reference internal" href="../core/constraints.html#sqlalchemy.schema.ForeignKeyConstraint" title="sqlalchemy.schema.ForeignKeyConstraint"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKeyConstraint</span></tt></a> which are described
at <a class="reference internal" href="../core/constraints.html#on-update-on-delete"><em>ON UPDATE and ON DELETE</em></a>.</p>
<p>It is important to note the differences between the ORM and the relational
database’s notion of “cascade” as well as how they integrate:</p>
<ul>
<li><p class="first">A database level <tt class="docutils literal"><span class="pre">ON</span> <span class="pre">DELETE</span></tt> cascade is configured effectively
on the <strong>many-to-one</strong> side of the relationship; that is, we configure
it relative to the <tt class="docutils literal"><span class="pre">FOREIGN</span> <span class="pre">KEY</span></tt> constraint that is the “many” side
of a relationship. At the ORM level, <strong>this direction is reversed</strong>.
SQLAlchemy handles the deletion of “child” objects relative to a
“parent” from the “parent” side, which means that <tt class="docutils literal"><span class="pre">delete</span></tt> and
<tt class="docutils literal"><span class="pre">delete-orphan</span></tt> cascade are configured on the <strong>one-to-many</strong>
side.</p>
</li>
<li><p class="first">Database level foreign keys with no <tt class="docutils literal"><span class="pre">ON</span> <span class="pre">DELETE</span></tt> setting
are often used to <strong>prevent</strong> a parent
row from being removed, as it would necessarily leave an unhandled
related row present. If this behavior is desired in a one-to-many
relationship, SQLAlchemy’s default behavior of setting a foreign key
to <tt class="docutils literal"><span class="pre">NULL</span></tt> can be caught in one of two ways:</p>
<blockquote>
<div><ul class="simple">
<li>The easiest and most common is just to set the
foreign-key-holding column to <tt class="docutils literal"><span class="pre">NOT</span> <span class="pre">NULL</span></tt> at the database schema
level. An attempt by SQLAlchemy to set the column to NULL will
fail with a simple NOT NULL constraint exception.</li>
<li>The other, more special case way is to set the <a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship.params.passive_deletes" title="sqlalchemy.orm.relationship"><tt class="xref py py-paramref docutils literal"><span class="pre">passive_deletes</span></tt></a>
flag to the string <tt class="docutils literal"><span class="pre">"all"</span></tt>. This has the effect of entirely
disabling SQLAlchemy’s behavior of setting the foreign key column
to NULL, and a DELETE will be emitted for the parent row without
any affect on the child row, even if the child row is present
in memory. This may be desirable in the case when
database-level foreign key triggers, either special <tt class="docutils literal"><span class="pre">ON</span> <span class="pre">DELETE</span></tt> settings
or otherwise, need to be activated in all cases when a parent row is deleted.</li>
</ul>
</div></blockquote>
</li>
<li><p class="first">Database level <tt class="docutils literal"><span class="pre">ON</span> <span class="pre">DELETE</span></tt> cascade is <strong>vastly more efficient</strong>
than that of SQLAlchemy. The database can chain a series of cascade
operations across many relationships at once; e.g. if row A is deleted,
all the related rows in table B can be deleted, and all the C rows related
to each of those B rows, and on and on, all within the scope of a single
DELETE statement. SQLAlchemy on the other hand, in order to support
the cascading delete operation fully, has to individually load each
related collection in order to target all rows that then may have further
related collections. That is, SQLAlchemy isn’t sophisticated enough
to emit a DELETE for all those related rows at once within this context.</p>
</li>
<li><p class="first">SQLAlchemy doesn’t <strong>need</strong> to be this sophisticated, as we instead provide
smooth integration with the database’s own <tt class="docutils literal"><span class="pre">ON</span> <span class="pre">DELETE</span></tt> functionality,
by using the <a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship.params.passive_deletes" title="sqlalchemy.orm.relationship"><tt class="xref py py-paramref docutils literal"><span class="pre">passive_deletes</span></tt></a> option in conjunction
with properly configured foreign key constraints. Under this behavior,
SQLAlchemy only emits DELETE for those rows that are already locally
present in the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>; for any collections that are unloaded,
it leaves them to the database to handle, rather than emitting a SELECT
for them. The section <a class="reference internal" href="collections.html#passive-deletes"><em>Using Passive Deletes</em></a> provides an example of this use.</p>
</li>
<li><p class="first">While database-level <tt class="docutils literal"><span class="pre">ON</span> <span class="pre">DELETE</span></tt> functionality works only on the “many”
side of a relationship, SQLAlchemy’s “delete” cascade
has <strong>limited</strong> ability to operate in the <em>reverse</em> direction as well,
meaning it can be configured on the “many” side to delete an object
on the “one” side when the reference on the “many” side is deleted. However
this can easily result in constraint violations if there are other objects
referring to this “one” side from the “many”, so it typically is only
useful when a relationship is in fact a “one to one”. The
<a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship.params.single_parent" title="sqlalchemy.orm.relationship"><tt class="xref py py-paramref docutils literal"><span class="pre">single_parent</span></tt></a> flag should be used to establish
an in-Python assertion for this case.</p>
</li>
</ul>
</div>
<p>When using a <a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> that also includes a many-to-many
table using the <a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship.params.secondary" title="sqlalchemy.orm.relationship"><tt class="xref py py-paramref docutils literal"><span class="pre">secondary</span></tt></a> option, SQLAlchemy’s
delete cascade handles the rows in this many-to-many table automatically.
Just like, as described in <a class="reference internal" href="relationships.html#relationships-many-to-many-deletion"><em>Deleting Rows from the Many to Many Table</em></a>,
the addition or removal of an object from a many-to-many collection
results in the INSERT or DELETE of a row in the many-to-many table,
the <tt class="docutils literal"><span class="pre">delete</span></tt> cascade, when activated as the result of a parent object
delete operation, will DELETE not just the row in the “child” table but also
in the many-to-many table.</p>
</div>
<div class="section" id="delete-orphan">
<span id="cascade-delete-orphan"></span><h3>delete-orphan<a class="headerlink" href="#delete-orphan" title="Permalink to this headline">¶</a></h3>
<p><tt class="docutils literal"><span class="pre">delete-orphan</span></tt> cascade adds behavior to the <tt class="docutils literal"><span class="pre">delete</span></tt> cascade,
such that a child object will be marked for deletion when it is
de-associated from the parent, not just when the parent is marked
for deletion. This is a common feature when dealing with a related
object that is “owned” by its parent, with a NOT NULL foreign key,
so that removal of the item from the parent collection results
in its deletion.</p>
<p><tt class="docutils literal"><span class="pre">delete-orphan</span></tt> cascade implies that each child object can only
have one parent at a time, so is configured in the vast majority of cases
on a one-to-many relationship. Setting it on a many-to-one or
many-to-many relationship is more awkward; for this use case,
SQLAlchemy requires that the <a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a>
be configured with the <a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship.params.single_parent" title="sqlalchemy.orm.relationship"><tt class="xref py py-paramref docutils literal"><span class="pre">single_parent</span></tt></a> argument,
establishes Python-side validation that ensures the object
is associated with only one parent at a time.</p>
</div>
<div class="section" id="merge">
<span id="cascade-merge"></span><h3>merge<a class="headerlink" href="#merge" title="Permalink to this headline">¶</a></h3>
<p><tt class="docutils literal"><span class="pre">merge</span></tt> cascade indicates that the <a class="reference internal" href="#sqlalchemy.orm.session.Session.merge" title="sqlalchemy.orm.session.Session.merge"><tt class="xref py py-meth docutils literal"><span class="pre">Session.merge()</span></tt></a>
operation should be propagated from a parent that’s the subject
of the <a class="reference internal" href="#sqlalchemy.orm.session.Session.merge" title="sqlalchemy.orm.session.Session.merge"><tt class="xref py py-meth docutils literal"><span class="pre">Session.merge()</span></tt></a> call down to referred objects.
This cascade is also on by default.</p>
</div>
<div class="section" id="refresh-expire">
<span id="cascade-refresh-expire"></span><h3>refresh-expire<a class="headerlink" href="#refresh-expire" title="Permalink to this headline">¶</a></h3>
<p><tt class="docutils literal"><span class="pre">refresh-expire</span></tt> is an uncommon option, indicating that the
<a class="reference internal" href="#sqlalchemy.orm.session.Session.expire" title="sqlalchemy.orm.session.Session.expire"><tt class="xref py py-meth docutils literal"><span class="pre">Session.expire()</span></tt></a> operation should be propagated from a parent
down to referred objects. When using <a class="reference internal" href="#sqlalchemy.orm.session.Session.refresh" title="sqlalchemy.orm.session.Session.refresh"><tt class="xref py py-meth docutils literal"><span class="pre">Session.refresh()</span></tt></a>,
the referred objects are expired only, but not actually refreshed.</p>
</div>
<div class="section" id="expunge">
<span id="cascade-expunge"></span><h3>expunge<a class="headerlink" href="#expunge" title="Permalink to this headline">¶</a></h3>
<p><tt class="docutils literal"><span class="pre">expunge</span></tt> cascade indicates that when the parent object is removed
from the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> using <a class="reference internal" href="#sqlalchemy.orm.session.Session.expunge" title="sqlalchemy.orm.session.Session.expunge"><tt class="xref py py-meth docutils literal"><span class="pre">Session.expunge()</span></tt></a>, the
operation should be propagated down to referred objects.</p>
</div>
<div class="section" id="controlling-cascade-on-backrefs">
<span id="backref-cascade"></span><h3>Controlling Cascade on Backrefs<a class="headerlink" href="#controlling-cascade-on-backrefs" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="#cascade-save-update"><em>save-update</em></a> cascade by default takes place on attribute change events
emitted from backrefs. This is probably a confusing statement more
easily described through demonstration; it means that, given a mapping such as this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">mapper</span><span class="p">(</span><span class="n">Order</span><span class="p">,</span> <span class="n">order_table</span><span class="p">,</span> <span class="n">properties</span><span class="o">=</span><span class="p">{</span>
<span class="s">'items'</span> <span class="p">:</span> <span class="n">relationship</span><span class="p">(</span><span class="n">Item</span><span class="p">,</span> <span class="n">backref</span><span class="o">=</span><span class="s">'order'</span><span class="p">)</span>
<span class="p">})</span></pre></div>
</div>
<p>If an <tt class="docutils literal"><span class="pre">Order</span></tt> is already in the session, and is assigned to the <tt class="docutils literal"><span class="pre">order</span></tt>
attribute of an <tt class="docutils literal"><span class="pre">Item</span></tt>, the backref appends the <tt class="docutils literal"><span class="pre">Order</span></tt> to the <tt class="docutils literal"><span class="pre">items</span></tt>
collection of that <tt class="docutils literal"><span class="pre">Order</span></tt>, resulting in the <tt class="docutils literal"><span class="pre">save-update</span></tt> cascade taking
place:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">o1</span> <span class="o">=</span> <span class="n">Order</span><span class="p">()</span>
<span class="gp">>>> </span><span class="n">session</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">o1</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">o1</span> <span class="ow">in</span> <span class="n">session</span>
<span class="go">True</span>
<span class="gp">>>> </span><span class="n">i1</span> <span class="o">=</span> <span class="n">Item</span><span class="p">()</span>
<span class="gp">>>> </span><span class="n">i1</span><span class="o">.</span><span class="n">order</span> <span class="o">=</span> <span class="n">o1</span>
<span class="gp">>>> </span><span class="n">i1</span> <span class="ow">in</span> <span class="n">o1</span><span class="o">.</span><span class="n">items</span>
<span class="go">True</span>
<span class="gp">>>> </span><span class="n">i1</span> <span class="ow">in</span> <span class="n">session</span>
<span class="go">True</span></pre></div>
</div>
<p>This behavior can be disabled using the <a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship.params.cascade_backrefs" title="sqlalchemy.orm.relationship"><tt class="xref py py-paramref docutils literal"><span class="pre">cascade_backrefs</span></tt></a> flag:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">mapper</span><span class="p">(</span><span class="n">Order</span><span class="p">,</span> <span class="n">order_table</span><span class="p">,</span> <span class="n">properties</span><span class="o">=</span><span class="p">{</span>
<span class="s">'items'</span> <span class="p">:</span> <span class="n">relationship</span><span class="p">(</span><span class="n">Item</span><span class="p">,</span> <span class="n">backref</span><span class="o">=</span><span class="s">'order'</span><span class="p">,</span>
<span class="n">cascade_backrefs</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
<span class="p">})</span></pre></div>
</div>
<p>So above, the assignment of <tt class="docutils literal"><span class="pre">i1.order</span> <span class="pre">=</span> <span class="pre">o1</span></tt> will append <tt class="docutils literal"><span class="pre">i1</span></tt> to the <tt class="docutils literal"><span class="pre">items</span></tt>
collection of <tt class="docutils literal"><span class="pre">o1</span></tt>, but will not add <tt class="docutils literal"><span class="pre">i1</span></tt> to the session. You can, of
course, <a class="reference internal" href="#sqlalchemy.orm.session.Session.add" title="sqlalchemy.orm.session.Session.add"><tt class="xref py py-meth docutils literal"><span class="pre">add()</span></tt></a> <tt class="docutils literal"><span class="pre">i1</span></tt> to the session at a later point. This
option may be helpful for situations where an object needs to be kept out of a
session until it’s construction is completed, but still needs to be given
associations to objects which are already persistent in the target session.</p>
</div>
</div>
<div class="section" id="managing-transactions">
<span id="unitofwork-transaction"></span><h2>Managing Transactions<a class="headerlink" href="#managing-transactions" title="Permalink to this headline">¶</a></h2>
<p>A newly constructed <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> may be said to be in the “begin” state.
In this state, the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> has not established any connection or
transactional state with any of the <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> objects that may be associated
with it.</p>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> then receives requests to operate upon a database connection.
Typically, this means it is called upon to execute SQL statements using a particular
<a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a>, which may be via <a class="reference internal" href="#sqlalchemy.orm.session.Session.query" title="sqlalchemy.orm.session.Session.query"><tt class="xref py py-meth docutils literal"><span class="pre">Session.query()</span></tt></a>, <a class="reference internal" href="#sqlalchemy.orm.session.Session.execute" title="sqlalchemy.orm.session.Session.execute"><tt class="xref py py-meth docutils literal"><span class="pre">Session.execute()</span></tt></a>,
or within a flush operation of pending data, which occurs when such state exists
and <a class="reference internal" href="#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-meth docutils literal"><span class="pre">Session.commit()</span></tt></a> or <a class="reference internal" href="#sqlalchemy.orm.session.Session.flush" title="sqlalchemy.orm.session.Session.flush"><tt class="xref py py-meth docutils literal"><span class="pre">Session.flush()</span></tt></a> is called.</p>
<p>As these requests are received, each new <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> encountered is associated
with an ongoing transactional state maintained by the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>.
When the first <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> is operated upon, the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> can be said
to have left the “begin” state and entered “transactional” state. For each
<a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> encountered, a <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> is associated with it,
which is acquired via the <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine.contextual_connect" title="sqlalchemy.engine.Engine.contextual_connect"><tt class="xref py py-meth docutils literal"><span class="pre">Engine.contextual_connect()</span></tt></a> method. If a
<a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> was directly associated with the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> (see <a class="reference internal" href="#session-external-transaction"><em>Joining a Session into an External Transaction (such as for test suites)</em></a>
for an example of this), it is
added to the transactional state directly.</p>
<p>For each <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a>, the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> also maintains a <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Transaction" title="sqlalchemy.engine.Transaction"><tt class="xref py py-class docutils literal"><span class="pre">Transaction</span></tt></a> object,
which is acquired by calling <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection.begin" title="sqlalchemy.engine.Connection.begin"><tt class="xref py py-meth docutils literal"><span class="pre">Connection.begin()</span></tt></a> on each <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a>,
or if the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
object has been established using the flag <tt class="docutils literal"><span class="pre">twophase=True</span></tt>, a <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.TwoPhaseTransaction" title="sqlalchemy.engine.TwoPhaseTransaction"><tt class="xref py py-class docutils literal"><span class="pre">TwoPhaseTransaction</span></tt></a>
object acquired via <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection.begin_twophase" title="sqlalchemy.engine.Connection.begin_twophase"><tt class="xref py py-meth docutils literal"><span class="pre">Connection.begin_twophase()</span></tt></a>. These transactions are all committed or
rolled back corresponding to the invocation of the
<a class="reference internal" href="#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-meth docutils literal"><span class="pre">Session.commit()</span></tt></a> and <a class="reference internal" href="#sqlalchemy.orm.session.Session.rollback" title="sqlalchemy.orm.session.Session.rollback"><tt class="xref py py-meth docutils literal"><span class="pre">Session.rollback()</span></tt></a> methods. A commit operation will
also call the <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.TwoPhaseTransaction.prepare" title="sqlalchemy.engine.TwoPhaseTransaction.prepare"><tt class="xref py py-meth docutils literal"><span class="pre">TwoPhaseTransaction.prepare()</span></tt></a> method on all transactions if applicable.</p>
<p>When the transactional state is completed after a rollback or commit, the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
<a class="reference internal" href="../glossary.html#term-releases"><em class="xref std std-term">releases</em></a> all <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Transaction" title="sqlalchemy.engine.Transaction"><tt class="xref py py-class docutils literal"><span class="pre">Transaction</span></tt></a> and <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> resources,
and goes back to the “begin” state, which
will again invoke new <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> and <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Transaction" title="sqlalchemy.engine.Transaction"><tt class="xref py py-class docutils literal"><span class="pre">Transaction</span></tt></a> objects as new
requests to emit SQL statements are received.</p>
<p>The example below illustrates this lifecycle:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">engine</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">"..."</span><span class="p">)</span>
<span class="n">Session</span> <span class="o">=</span> <span class="n">sessionmaker</span><span class="p">(</span><span class="n">bind</span><span class="o">=</span><span class="n">engine</span><span class="p">)</span>
<span class="c"># new session. no connections are in use.</span>
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
<span class="k">try</span><span class="p">:</span>
<span class="c"># first query. a Connection is acquired</span>
<span class="c"># from the Engine, and a Transaction</span>
<span class="c"># started.</span>
<span class="n">item1</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">Item</span><span class="p">)</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="c"># second query. the same Connection/Transaction</span>
<span class="c"># are used.</span>
<span class="n">item2</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">Item</span><span class="p">)</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
<span class="c"># pending changes are created.</span>
<span class="n">item1</span><span class="o">.</span><span class="n">foo</span> <span class="o">=</span> <span class="s">'bar'</span>
<span class="n">item2</span><span class="o">.</span><span class="n">bar</span> <span class="o">=</span> <span class="s">'foo'</span>
<span class="c"># commit. The pending changes above</span>
<span class="c"># are flushed via flush(), the Transaction</span>
<span class="c"># is committed, the Connection object closed</span>
<span class="c"># and discarded, the underlying DBAPI connection</span>
<span class="c"># returned to the connection pool.</span>
<span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
<span class="k">except</span><span class="p">:</span>
<span class="c"># on rollback, the same closure of state</span>
<span class="c"># as that of commit proceeds.</span>
<span class="n">session</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
<span class="k">raise</span></pre></div>
</div>
<div class="section" id="using-savepoint">
<span id="session-begin-nested"></span><h3>Using SAVEPOINT<a class="headerlink" href="#using-savepoint" title="Permalink to this headline">¶</a></h3>
<p>SAVEPOINT transactions, if supported by the underlying engine, may be
delineated using the <a class="reference internal" href="#sqlalchemy.orm.session.Session.begin_nested" title="sqlalchemy.orm.session.Session.begin_nested"><tt class="xref py py-meth docutils literal"><span class="pre">begin_nested()</span></tt></a>
method:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Session</span> <span class="o">=</span> <span class="n">sessionmaker</span><span class="p">()</span>
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
<span class="n">session</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">u1</span><span class="p">)</span>
<span class="n">session</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">u2</span><span class="p">)</span>
<span class="n">session</span><span class="o">.</span><span class="n">begin_nested</span><span class="p">()</span> <span class="c"># establish a savepoint</span>
<span class="n">session</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">u3</span><span class="p">)</span>
<span class="n">session</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span> <span class="c"># rolls back u3, keeps u1 and u2</span>
<span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span> <span class="c"># commits u1 and u2</span></pre></div>
</div>
<p><a class="reference internal" href="#sqlalchemy.orm.session.Session.begin_nested" title="sqlalchemy.orm.session.Session.begin_nested"><tt class="xref py py-meth docutils literal"><span class="pre">begin_nested()</span></tt></a> may be called any number
of times, which will issue a new SAVEPOINT with a unique identifier for each
call. For each <a class="reference internal" href="#sqlalchemy.orm.session.Session.begin_nested" title="sqlalchemy.orm.session.Session.begin_nested"><tt class="xref py py-meth docutils literal"><span class="pre">begin_nested()</span></tt></a> call, a
corresponding <a class="reference internal" href="#sqlalchemy.orm.session.Session.rollback" title="sqlalchemy.orm.session.Session.rollback"><tt class="xref py py-meth docutils literal"><span class="pre">rollback()</span></tt></a> or
<a class="reference internal" href="#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-meth docutils literal"><span class="pre">commit()</span></tt></a> must be issued. (But note that if the return value is
used as a context manager, i.e. in a with-statement, then this rollback/commit
is issued by the context manager upon exiting the context, and so should not be
added explicitly.)</p>
<p>When <a class="reference internal" href="#sqlalchemy.orm.session.Session.begin_nested" title="sqlalchemy.orm.session.Session.begin_nested"><tt class="xref py py-meth docutils literal"><span class="pre">begin_nested()</span></tt></a> is called, a
<a class="reference internal" href="#sqlalchemy.orm.session.Session.flush" title="sqlalchemy.orm.session.Session.flush"><tt class="xref py py-meth docutils literal"><span class="pre">flush()</span></tt></a> is unconditionally issued
(regardless of the <tt class="docutils literal"><span class="pre">autoflush</span></tt> setting). This is so that when a
<a class="reference internal" href="#sqlalchemy.orm.session.Session.rollback" title="sqlalchemy.orm.session.Session.rollback"><tt class="xref py py-meth docutils literal"><span class="pre">rollback()</span></tt></a> occurs, the full state of the
session is expired, thus causing all subsequent attribute/instance access to
reference the full state of the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> right
before <a class="reference internal" href="#sqlalchemy.orm.session.Session.begin_nested" title="sqlalchemy.orm.session.Session.begin_nested"><tt class="xref py py-meth docutils literal"><span class="pre">begin_nested()</span></tt></a> was called.</p>
<p><a class="reference internal" href="#sqlalchemy.orm.session.Session.begin_nested" title="sqlalchemy.orm.session.Session.begin_nested"><tt class="xref py py-meth docutils literal"><span class="pre">begin_nested()</span></tt></a>, in the same manner as the less often
used <a class="reference internal" href="#sqlalchemy.orm.session.Session.begin" title="sqlalchemy.orm.session.Session.begin"><tt class="xref py py-meth docutils literal"><span class="pre">begin()</span></tt></a> method, returns a transactional object
which also works as a context manager.
It can be succinctly used around individual record inserts in order to catch
things like unique constraint exceptions:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">for</span> <span class="n">record</span> <span class="ow">in</span> <span class="n">records</span><span class="p">:</span>
<span class="k">try</span><span class="p">:</span>
<span class="k">with</span> <span class="n">session</span><span class="o">.</span><span class="n">begin_nested</span><span class="p">():</span>
<span class="n">session</span><span class="o">.</span><span class="n">merge</span><span class="p">(</span><span class="n">record</span><span class="p">)</span>
<span class="k">except</span><span class="p">:</span>
<span class="k">print</span> <span class="s">"Skipped record </span><span class="si">%s</span><span class="s">"</span> <span class="o">%</span> <span class="n">record</span>
<span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span></pre></div>
</div>
</div>
<div class="section" id="autocommit-mode">
<span id="session-autocommit"></span><h3>Autocommit Mode<a class="headerlink" href="#autocommit-mode" title="Permalink to this headline">¶</a></h3>
<p>The example of <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> transaction lifecycle illustrated at
the start of <a class="reference internal" href="#unitofwork-transaction"><em>Managing Transactions</em></a> applies to a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> configured in the
default mode of <tt class="docutils literal"><span class="pre">autocommit=False</span></tt>. Constructing a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
with <tt class="docutils literal"><span class="pre">autocommit=True</span></tt> produces a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> placed into “autocommit” mode, where each SQL statement
invoked by a <a class="reference internal" href="#sqlalchemy.orm.session.Session.query" title="sqlalchemy.orm.session.Session.query"><tt class="xref py py-meth docutils literal"><span class="pre">Session.query()</span></tt></a> or <a class="reference internal" href="#sqlalchemy.orm.session.Session.execute" title="sqlalchemy.orm.session.Session.execute"><tt class="xref py py-meth docutils literal"><span class="pre">Session.execute()</span></tt></a> occurs
using a new connection from the connection pool, discarding it after
results have been iterated. The <a class="reference internal" href="#sqlalchemy.orm.session.Session.flush" title="sqlalchemy.orm.session.Session.flush"><tt class="xref py py-meth docutils literal"><span class="pre">Session.flush()</span></tt></a> operation
still occurs within the scope of a single transaction, though this transaction
is closed out after the <a class="reference internal" href="#sqlalchemy.orm.session.Session.flush" title="sqlalchemy.orm.session.Session.flush"><tt class="xref py py-meth docutils literal"><span class="pre">Session.flush()</span></tt></a> operation completes.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p>“autocommit” mode should <strong>not be considered for general use</strong>.
If used, it should always be combined with the usage of
<a class="reference internal" href="#sqlalchemy.orm.session.Session.begin" title="sqlalchemy.orm.session.Session.begin"><tt class="xref py py-meth docutils literal"><span class="pre">Session.begin()</span></tt></a> and <a class="reference internal" href="#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-meth docutils literal"><span class="pre">Session.commit()</span></tt></a>, to ensure
a transaction demarcation.</p>
<p>Executing queries outside of a demarcated transaction is a legacy mode
of usage, and can in some cases lead to concurrent connection
checkouts.</p>
<p class="last">In the absence of a demarcated transaction, the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
cannot make appropriate decisions as to when autoflush should
occur nor when auto-expiration should occur, so these features
should be disabled with <tt class="docutils literal"><span class="pre">autoflush=False,</span> <span class="pre">expire_on_commit=False</span></tt>.</p>
</div>
<p>Modern usage of “autocommit” is for framework integrations that need to control
specifically when the “begin” state occurs. A session which is configured with
<tt class="docutils literal"><span class="pre">autocommit=True</span></tt> may be placed into the “begin” state using the
<a class="reference internal" href="#sqlalchemy.orm.session.Session.begin" title="sqlalchemy.orm.session.Session.begin"><tt class="xref py py-meth docutils literal"><span class="pre">Session.begin()</span></tt></a> method.
After the cycle completes upon <a class="reference internal" href="#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-meth docutils literal"><span class="pre">Session.commit()</span></tt></a> or <a class="reference internal" href="#sqlalchemy.orm.session.Session.rollback" title="sqlalchemy.orm.session.Session.rollback"><tt class="xref py py-meth docutils literal"><span class="pre">Session.rollback()</span></tt></a>,
connection and transaction resources are <a class="reference internal" href="../glossary.html#term-released"><em class="xref std std-term">released</em></a> and the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
goes back into “autocommit” mode, until <a class="reference internal" href="#sqlalchemy.orm.session.Session.begin" title="sqlalchemy.orm.session.Session.begin"><tt class="xref py py-meth docutils literal"><span class="pre">Session.begin()</span></tt></a> is called again:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Session</span> <span class="o">=</span> <span class="n">sessionmaker</span><span class="p">(</span><span class="n">bind</span><span class="o">=</span><span class="n">engine</span><span class="p">,</span> <span class="n">autocommit</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
<span class="n">session</span><span class="o">.</span><span class="n">begin</span><span class="p">()</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">item1</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">Item</span><span class="p">)</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="n">item2</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">Item</span><span class="p">)</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
<span class="n">item1</span><span class="o">.</span><span class="n">foo</span> <span class="o">=</span> <span class="s">'bar'</span>
<span class="n">item2</span><span class="o">.</span><span class="n">bar</span> <span class="o">=</span> <span class="s">'foo'</span>
<span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
<span class="k">except</span><span class="p">:</span>
<span class="n">session</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
<span class="k">raise</span></pre></div>
</div>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.Session.begin" title="sqlalchemy.orm.session.Session.begin"><tt class="xref py py-meth docutils literal"><span class="pre">Session.begin()</span></tt></a> method also returns a transactional token which is
compatible with the Python 2.6 <tt class="docutils literal"><span class="pre">with</span></tt> statement:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Session</span> <span class="o">=</span> <span class="n">sessionmaker</span><span class="p">(</span><span class="n">bind</span><span class="o">=</span><span class="n">engine</span><span class="p">,</span> <span class="n">autocommit</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
<span class="k">with</span> <span class="n">session</span><span class="o">.</span><span class="n">begin</span><span class="p">():</span>
<span class="n">item1</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">Item</span><span class="p">)</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="n">item2</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">Item</span><span class="p">)</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
<span class="n">item1</span><span class="o">.</span><span class="n">foo</span> <span class="o">=</span> <span class="s">'bar'</span>
<span class="n">item2</span><span class="o">.</span><span class="n">bar</span> <span class="o">=</span> <span class="s">'foo'</span></pre></div>
</div>
<div class="section" id="using-subtransactions-with-autocommit">
<span id="session-subtransactions"></span><h4>Using Subtransactions with Autocommit<a class="headerlink" href="#using-subtransactions-with-autocommit" title="Permalink to this headline">¶</a></h4>
<p>A subtransaction indicates usage of the <a class="reference internal" href="#sqlalchemy.orm.session.Session.begin" title="sqlalchemy.orm.session.Session.begin"><tt class="xref py py-meth docutils literal"><span class="pre">Session.begin()</span></tt></a> method in conjunction with
the <tt class="docutils literal"><span class="pre">subtransactions=True</span></tt> flag. This produces a non-transactional, delimiting construct that
allows nesting of calls to <a class="reference internal" href="#sqlalchemy.orm.session.Session.begin" title="sqlalchemy.orm.session.Session.begin"><tt class="xref py py-meth docutils literal"><span class="pre">begin()</span></tt></a> and <a class="reference internal" href="#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-meth docutils literal"><span class="pre">commit()</span></tt></a>.
Its purpose is to allow the construction of code that can function within a transaction
both independently of any external code that starts a transaction,
as well as within a block that has already demarcated a transaction.</p>
<p><tt class="docutils literal"><span class="pre">subtransactions=True</span></tt> is generally only useful in conjunction with
autocommit, and is equivalent to the pattern described at <a class="reference internal" href="../core/connections.html#connections-nested-transactions"><em>Nesting of Transaction Blocks</em></a>,
where any number of functions can call <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection.begin" title="sqlalchemy.engine.Connection.begin"><tt class="xref py py-meth docutils literal"><span class="pre">Connection.begin()</span></tt></a> and <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Transaction.commit" title="sqlalchemy.engine.Transaction.commit"><tt class="xref py py-meth docutils literal"><span class="pre">Transaction.commit()</span></tt></a>
as though they are the initiator of the transaction, but in fact may be participating
in an already ongoing transaction:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># method_a starts a transaction and calls method_b</span>
<span class="k">def</span> <span class="nf">method_a</span><span class="p">(</span><span class="n">session</span><span class="p">):</span>
<span class="n">session</span><span class="o">.</span><span class="n">begin</span><span class="p">(</span><span class="n">subtransactions</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">method_b</span><span class="p">(</span><span class="n">session</span><span class="p">)</span>
<span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span> <span class="c"># transaction is committed here</span>
<span class="k">except</span><span class="p">:</span>
<span class="n">session</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span> <span class="c"># rolls back the transaction</span>
<span class="k">raise</span>
<span class="c"># method_b also starts a transaction, but when</span>
<span class="c"># called from method_a participates in the ongoing</span>
<span class="c"># transaction.</span>
<span class="k">def</span> <span class="nf">method_b</span><span class="p">(</span><span class="n">session</span><span class="p">):</span>
<span class="n">session</span><span class="o">.</span><span class="n">begin</span><span class="p">(</span><span class="n">subtransactions</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">session</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">SomeObject</span><span class="p">(</span><span class="s">'bat'</span><span class="p">,</span> <span class="s">'lala'</span><span class="p">))</span>
<span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span> <span class="c"># transaction is not committed yet</span>
<span class="k">except</span><span class="p">:</span>
<span class="n">session</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span> <span class="c"># rolls back the transaction, in this case</span>
<span class="c"># the one that was initiated in method_a().</span>
<span class="k">raise</span>
<span class="c"># create a Session and call method_a</span>
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">(</span><span class="n">autocommit</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="n">method_a</span><span class="p">(</span><span class="n">session</span><span class="p">)</span>
<span class="n">session</span><span class="o">.</span><span class="n">close</span><span class="p">()</span></pre></div>
</div>
<p>Subtransactions are used by the <a class="reference internal" href="#sqlalchemy.orm.session.Session.flush" title="sqlalchemy.orm.session.Session.flush"><tt class="xref py py-meth docutils literal"><span class="pre">Session.flush()</span></tt></a> process to ensure that the
flush operation takes place within a transaction, regardless of autocommit. When
autocommit is disabled, it is still useful in that it forces the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
into a “pending rollback” state, as a failed flush cannot be resumed in mid-operation,
where the end user still maintains the “scope” of the transaction overall.</p>
</div>
</div>
<div class="section" id="enabling-two-phase-commit">
<span id="session-twophase"></span><h3>Enabling Two-Phase Commit<a class="headerlink" href="#enabling-two-phase-commit" title="Permalink to this headline">¶</a></h3>
<p>For backends which support two-phase operaration (currently MySQL and
PostgreSQL), the session can be instructed to use two-phase commit semantics.
This will coordinate the committing of transactions across databases so that
the transaction is either committed or rolled back in all databases. You can
also <a class="reference internal" href="#sqlalchemy.orm.session.Session.prepare" title="sqlalchemy.orm.session.Session.prepare"><tt class="xref py py-meth docutils literal"><span class="pre">prepare()</span></tt></a> the session for
interacting with transactions not managed by SQLAlchemy. To use two phase
transactions set the flag <tt class="docutils literal"><span class="pre">twophase=True</span></tt> on the session:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">engine1</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">'postgresql://db1'</span><span class="p">)</span>
<span class="n">engine2</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">'postgresql://db2'</span><span class="p">)</span>
<span class="n">Session</span> <span class="o">=</span> <span class="n">sessionmaker</span><span class="p">(</span><span class="n">twophase</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="c"># bind User operations to engine 1, Account operations to engine 2</span>
<span class="n">Session</span><span class="o">.</span><span class="n">configure</span><span class="p">(</span><span class="n">binds</span><span class="o">=</span><span class="p">{</span><span class="n">User</span><span class="p">:</span><span class="n">engine1</span><span class="p">,</span> <span class="n">Account</span><span class="p">:</span><span class="n">engine2</span><span class="p">})</span>
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
<span class="c"># .... work with accounts and users</span>
<span class="c"># commit. session will issue a flush to all DBs, and a prepare step to all DBs,</span>
<span class="c"># before committing both transactions</span>
<span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span></pre></div>
</div>
</div>
</div>
<div class="section" id="embedding-sql-insert-update-expressions-into-a-flush">
<h2>Embedding SQL Insert/Update Expressions into a Flush<a class="headerlink" href="#embedding-sql-insert-update-expressions-into-a-flush" title="Permalink to this headline">¶</a></h2>
<p>This feature allows the value of a database column to be set to a SQL
expression instead of a literal value. It’s especially useful for atomic
updates, calling stored procedures, etc. All you do is assign an expression to
an attribute:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">SomeClass</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="k">pass</span>
<span class="n">mapper</span><span class="p">(</span><span class="n">SomeClass</span><span class="p">,</span> <span class="n">some_table</span><span class="p">)</span>
<span class="n">someobject</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">SomeClass</span><span class="p">)</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="c"># set 'value' attribute to a SQL expression adding one</span>
<span class="n">someobject</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="n">some_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">value</span> <span class="o">+</span> <span class="mi">1</span>
<span class="c"># issues "UPDATE some_table SET value=value+1"</span>
<span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span></pre></div>
</div>
<p>This technique works both for INSERT and UPDATE statements. After the
flush/commit operation, the <tt class="docutils literal"><span class="pre">value</span></tt> attribute on <tt class="docutils literal"><span class="pre">someobject</span></tt> above is
expired, so that when next accessed the newly generated value will be loaded
from the database.</p>
</div>
<div class="section" id="using-sql-expressions-with-sessions">
<span id="session-sql-expressions"></span><h2>Using SQL Expressions with Sessions<a class="headerlink" href="#using-sql-expressions-with-sessions" title="Permalink to this headline">¶</a></h2>
<p>SQL expressions and strings can be executed via the
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> within its transactional context.
This is most easily accomplished using the
<a class="reference internal" href="#sqlalchemy.orm.session.Session.execute" title="sqlalchemy.orm.session.Session.execute"><tt class="xref py py-meth docutils literal"><span class="pre">execute()</span></tt></a> method, which returns a
<a class="reference internal" href="../core/connections.html#sqlalchemy.engine.ResultProxy" title="sqlalchemy.engine.ResultProxy"><tt class="xref py py-class docutils literal"><span class="pre">ResultProxy</span></tt></a> in the same manner as an
<a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> or
<a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Session</span> <span class="o">=</span> <span class="n">sessionmaker</span><span class="p">(</span><span class="n">bind</span><span class="o">=</span><span class="n">engine</span><span class="p">)</span>
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
<span class="c"># execute a string statement</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">"select * from table where id=:id"</span><span class="p">,</span> <span class="p">{</span><span class="s">'id'</span><span class="p">:</span><span class="mi">7</span><span class="p">})</span>
<span class="c"># execute a SQL expression construct</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">select</span><span class="p">([</span><span class="n">mytable</span><span class="p">])</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">mytable</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">id</span><span class="o">==</span><span class="mi">7</span><span class="p">))</span></pre></div>
</div>
<p>The current <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> held by the
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is accessible using the
<a class="reference internal" href="#sqlalchemy.orm.session.Session.connection" title="sqlalchemy.orm.session.Session.connection"><tt class="xref py py-meth docutils literal"><span class="pre">connection()</span></tt></a> method:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">connection</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">connection</span><span class="p">()</span></pre></div>
</div>
<p>The examples above deal with a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> that’s
bound to a single <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> or
<a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a>. To execute statements using a
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> which is bound either to multiple
engines, or none at all (i.e. relies upon bound metadata), both
<a class="reference internal" href="#sqlalchemy.orm.session.Session.execute" title="sqlalchemy.orm.session.Session.execute"><tt class="xref py py-meth docutils literal"><span class="pre">execute()</span></tt></a> and
<a class="reference internal" href="#sqlalchemy.orm.session.Session.connection" title="sqlalchemy.orm.session.Session.connection"><tt class="xref py py-meth docutils literal"><span class="pre">connection()</span></tt></a> accept a <tt class="docutils literal"><span class="pre">mapper</span></tt> keyword
argument, which is passed a mapped class or
<a class="reference internal" href="mapper_config.html#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> instance, which is used to locate the
proper context for the desired engine:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Session</span> <span class="o">=</span> <span class="n">sessionmaker</span><span class="p">()</span>
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
<span class="c"># need to specify mapper or class when executing</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">"select * from table where id=:id"</span><span class="p">,</span> <span class="p">{</span><span class="s">'id'</span><span class="p">:</span><span class="mi">7</span><span class="p">},</span> <span class="n">mapper</span><span class="o">=</span><span class="n">MyMappedClass</span><span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">select</span><span class="p">([</span><span class="n">mytable</span><span class="p">],</span> <span class="n">mytable</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">id</span><span class="o">==</span><span class="mi">7</span><span class="p">),</span> <span class="n">mapper</span><span class="o">=</span><span class="n">MyMappedClass</span><span class="p">)</span>
<span class="n">connection</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">connection</span><span class="p">(</span><span class="n">MyMappedClass</span><span class="p">)</span></pre></div>
</div>
</div>
<div class="section" id="joining-a-session-into-an-external-transaction-such-as-for-test-suites">
<span id="session-external-transaction"></span><h2>Joining a Session into an External Transaction (such as for test suites)<a class="headerlink" href="#joining-a-session-into-an-external-transaction-such-as-for-test-suites" title="Permalink to this headline">¶</a></h2>
<p>If a <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> is being used which is already in a transactional
state (i.e. has a <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Transaction" title="sqlalchemy.engine.Transaction"><tt class="xref py py-class docutils literal"><span class="pre">Transaction</span></tt></a> established), a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> can
be made to participate within that transaction by just binding the
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> to that <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a>. The usual rationale for this
is a test suite that allows ORM code to work freely with a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>,
including the ability to call <a class="reference internal" href="#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-meth docutils literal"><span class="pre">Session.commit()</span></tt></a>, where afterwards the
entire database interaction is rolled back:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy.orm</span> <span class="kn">import</span> <span class="n">sessionmaker</span>
<span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">create_engine</span>
<span class="kn">from</span> <span class="nn">unittest</span> <span class="kn">import</span> <span class="n">TestCase</span>
<span class="c"># global application scope. create Session class, engine</span>
<span class="n">Session</span> <span class="o">=</span> <span class="n">sessionmaker</span><span class="p">()</span>
<span class="n">engine</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">'postgresql://...'</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">SomeTest</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">setUp</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="c"># connect to the database</span>
<span class="bp">self</span><span class="o">.</span><span class="n">connection</span> <span class="o">=</span> <span class="n">engine</span><span class="o">.</span><span class="n">connect</span><span class="p">()</span>
<span class="c"># begin a non-ORM transaction</span>
<span class="bp">self</span><span class="o">.</span><span class="n">trans</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">connection</span><span class="o">.</span><span class="n">begin</span><span class="p">()</span>
<span class="c"># bind an individual Session to the connection</span>
<span class="bp">self</span><span class="o">.</span><span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">(</span><span class="n">bind</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">connection</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">test_something</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="c"># use the session in tests.</span>
<span class="bp">self</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">Foo</span><span class="p">())</span>
<span class="bp">self</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
<span class="k">def</span> <span class="nf">tearDown</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="c"># rollback - everything that happened with the</span>
<span class="c"># Session above (including calls to commit())</span>
<span class="c"># is rolled back.</span>
<span class="bp">self</span><span class="o">.</span><span class="n">trans</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
<span class="c"># return connection to the Engine</span>
<span class="bp">self</span><span class="o">.</span><span class="n">connection</span><span class="o">.</span><span class="n">close</span><span class="p">()</span></pre></div>
</div>
<p>Above, we issue <a class="reference internal" href="#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-meth docutils literal"><span class="pre">Session.commit()</span></tt></a> as well as
<a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Transaction.rollback" title="sqlalchemy.engine.Transaction.rollback"><tt class="xref py py-meth docutils literal"><span class="pre">Transaction.rollback()</span></tt></a>. This is an example of where we take advantage
of the <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> object’s ability to maintain <em>subtransactions</em>, or
nested begin/commit-or-rollback pairs where only the outermost begin/commit
pair actually commits the transaction, or if the outermost block rolls back,
everything is rolled back.</p>
<div class="topic">
<p class="topic-title first">Supporting Tests with Rollbacks</p>
<p>The above recipe works well for any kind of database enabled test, except
for a test that needs to actually invoke <a class="reference internal" href="#sqlalchemy.orm.session.Session.rollback" title="sqlalchemy.orm.session.Session.rollback"><tt class="xref py py-meth docutils literal"><span class="pre">Session.rollback()</span></tt></a> within
the scope of the test itself. The above recipe can be expanded, such
that the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> always runs all operations within the scope
of a SAVEPOINT, which is established at the start of each transaction,
so that tests can also rollback the “transaction” as well while still
remaining in the scope of a larger “transaction” that’s never committed,
using two extra events:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">event</span>
<span class="k">class</span> <span class="nc">SomeTest</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">setUp</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="c"># connect to the database</span>
<span class="bp">self</span><span class="o">.</span><span class="n">connection</span> <span class="o">=</span> <span class="n">engine</span><span class="o">.</span><span class="n">connect</span><span class="p">()</span>
<span class="c"># begin a non-ORM transaction</span>
<span class="bp">self</span><span class="o">.</span><span class="n">trans</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">begin</span><span class="p">()</span>
<span class="c"># bind an individual Session to the connection</span>
<span class="bp">self</span><span class="o">.</span><span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">(</span><span class="n">bind</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">connection</span><span class="p">)</span>
<span class="c"># start the session in a SAVEPOINT...</span>
<span class="bp">self</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">begin_nested</span><span class="p">()</span>
<span class="c"># then each time that SAVEPOINT ends, reopen it</span>
<span class="nd">@event.listens_for</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">session</span><span class="p">,</span> <span class="s">"after_transaction_end"</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">restart_savepoint</span><span class="p">(</span><span class="n">session</span><span class="p">,</span> <span class="n">transaction</span><span class="p">):</span>
<span class="k">if</span> <span class="n">transaction</span><span class="o">.</span><span class="n">nested</span> <span class="ow">and</span> <span class="ow">not</span> <span class="n">transaction</span><span class="o">.</span><span class="n">_parent</span><span class="o">.</span><span class="n">nested</span><span class="p">:</span>
<span class="n">session</span><span class="o">.</span><span class="n">begin_nested</span><span class="p">()</span>
<span class="c"># ... the tearDown() method stays the same</span></pre></div>
</div>
</div>
</div>
<div class="section" id="contextual-thread-local-sessions">
<span id="unitofwork-contextual"></span><h2>Contextual/Thread-local Sessions<a class="headerlink" href="#contextual-thread-local-sessions" title="Permalink to this headline">¶</a></h2>
<p>Recall from the section <a class="reference internal" href="#session-faq-whentocreate"><em>When do I construct a Session, when do I commit it, and when do I close it?</em></a>, the concept of
“session scopes” was introduced, with an emphasis on web applications
and the practice of linking the scope of a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> with that
of a web request. Most modern web frameworks include integration tools
so that the scope of the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> can be managed automatically,
and these tools should be used as they are available.</p>
<p>SQLAlchemy includes its own helper object, which helps with the establishment
of user-defined <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> scopes. It is also used by third-party
integration systems to help construct their integration schemes.</p>
<p>The object is the <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a> object, and it represents a
<strong>registry</strong> of <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> objects. If you’re not familiar with the
registry pattern, a good introduction can be found in <a class="reference external" href="http://martinfowler.com/eaaCatalog/registry.html">Patterns of Enterprise
Architecture</a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a> object is a very popular and useful object
used by many SQLAlchemy applications. However, it is important to note
that it presents <strong>only one approach</strong> to the issue of <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
management. If you’re new to SQLAlchemy, and especially if the
term “thread-local variable” seems strange to you, we recommend that
if possible you familiarize first with an off-the-shelf integration
system such as <a class="reference external" href="http://packages.python.org/Flask-SQLAlchemy/">Flask-SQLAlchemy</a>
or <a class="reference external" href="http://pypi.python.org/pypi/zope.sqlalchemy">zope.sqlalchemy</a>.</p>
</div>
<p>A <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a> is constructed by calling it, passing it a
<strong>factory</strong> which can create new <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> objects. A factory
is just something that produces a new object when called, and in the
case of <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>, the most common factory is the <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a>,
introduced earlier in this section. Below we illustrate this usage:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sqlalchemy.orm</span> <span class="kn">import</span> <span class="n">scoped_session</span>
<span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sqlalchemy.orm</span> <span class="kn">import</span> <span class="n">sessionmaker</span>
<span class="gp">>>> </span><span class="n">session_factory</span> <span class="o">=</span> <span class="n">sessionmaker</span><span class="p">(</span><span class="n">bind</span><span class="o">=</span><span class="n">some_engine</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">Session</span> <span class="o">=</span> <span class="n">scoped_session</span><span class="p">(</span><span class="n">session_factory</span><span class="p">)</span></pre></div>
</div>
<p>The <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a> object we’ve created will now call upon the
<a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> when we “call” the registry:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">some_session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span></pre></div>
</div>
<p>Above, <tt class="docutils literal"><span class="pre">some_session</span></tt> is an instance of <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>, which we
can now use to talk to the database. This same <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is also
present within the <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a> registry we’ve created. If
we call upon the registry a second time, we get back the <strong>same</strong> <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">some_other_session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
<span class="gp">>>> </span><span class="n">some_session</span> <span class="ow">is</span> <span class="n">some_other_session</span>
<span class="go">True</span></pre></div>
</div>
<p>This pattern allows disparate sections of the application to call upon a global
<a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a>, so that all those areas may share the same session
without the need to pass it explicitly. The <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> we’ve established
in our registry will remain, until we explicitly tell our registry to dispose of it,
by calling <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session.remove" title="sqlalchemy.orm.scoping.scoped_session.remove"><tt class="xref py py-meth docutils literal"><span class="pre">scoped_session.remove()</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">Session</span><span class="o">.</span><span class="n">remove</span><span class="p">()</span></pre></div>
</div>
<p>The <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session.remove" title="sqlalchemy.orm.scoping.scoped_session.remove"><tt class="xref py py-meth docutils literal"><span class="pre">scoped_session.remove()</span></tt></a> method first calls <a class="reference internal" href="#sqlalchemy.orm.session.Session.close" title="sqlalchemy.orm.session.Session.close"><tt class="xref py py-meth docutils literal"><span class="pre">Session.close()</span></tt></a> on
the current <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>, which has the effect of releasing any connection/transactional
resources owned by the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> first, then discarding the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
itself. “Releasing” here means that connections are returned to their connection pool and any transactional state is rolled back, ultimately using the <tt class="docutils literal"><span class="pre">rollback()</span></tt> method of the underlying DBAPI connection.</p>
<p>At this point, the <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a> object is “empty”, and will create
a <strong>new</strong> <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> when called again. As illustrated below, this
is not the same <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> we had before:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">new_session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
<span class="gp">>>> </span><span class="n">new_session</span> <span class="ow">is</span> <span class="n">some_session</span>
<span class="go">False</span></pre></div>
</div>
<p>The above series of steps illustrates the idea of the “registry” pattern in a
nutshell. With that basic idea in hand, we can discuss some of the details
of how this pattern proceeds.</p>
<div class="section" id="implicit-method-access">
<h3>Implicit Method Access<a class="headerlink" href="#implicit-method-access" title="Permalink to this headline">¶</a></h3>
<p>The job of the <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a> is simple; hold onto a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
for all who ask for it. As a means of producing more transparent access to this
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>, the <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a> also includes <strong>proxy behavior</strong>,
meaning that the registry itself can be treated just like a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
directly; when methods are called on this object, they are <strong>proxied</strong> to the
underlying <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> being maintained by the registry:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Session</span> <span class="o">=</span> <span class="n">scoped_session</span><span class="p">(</span><span class="n">some_factory</span><span class="p">)</span>
<span class="c"># equivalent to:</span>
<span class="c">#</span>
<span class="c"># session = Session()</span>
<span class="c"># print session.query(MyClass).all()</span>
<span class="c">#</span>
<span class="k">print</span> <span class="n">Session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">MyClass</span><span class="p">)</span><span class="o">.</span><span class="n">all</span><span class="p">()</span></pre></div>
</div>
<p>The above code accomplishes the same task as that of acquiring the current
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> by calling upon the registry, then using that <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>.</p>
</div>
<div class="section" id="thread-local-scope">
<h3>Thread-Local Scope<a class="headerlink" href="#thread-local-scope" title="Permalink to this headline">¶</a></h3>
<p>Users who are familiar with multithreaded programming will note that representing
anything as a global variable is usually a bad idea, as it implies that the
global object will be accessed by many threads concurrently. The <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
object is entirely designed to be used in a <strong>non-concurrent</strong> fashion, which
in terms of multithreading means “only in one thread at a time”. So our
above example of <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a> usage, where the same <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
object is maintained across multiple calls, suggests that some process needs
to be in place such that mutltiple calls across many threads don’t actually get
a handle to the same session. We call this notion <strong>thread local storage</strong>,
which means, a special object is used that will maintain a distinct object
per each application thread. Python provides this via the
<a class="reference external" href="http://docs.python.org/library/threading.html#threading.local">threading.local()</a>
construct. The <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a> object by default uses this object
as storage, so that a single <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is maintained for all who call
upon the <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a> registry, but only within the scope of a single
thread. Callers who call upon the registry in a different thread get a
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> instance that is local to that other thread.</p>
<p>Using this technique, the <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a> provides a quick and relatively
simple (if one is familiar with thread-local storage) way of providing
a single, global object in an application that is safe to be called upon
from multiple threads.</p>
<p>The <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session.remove" title="sqlalchemy.orm.scoping.scoped_session.remove"><tt class="xref py py-meth docutils literal"><span class="pre">scoped_session.remove()</span></tt></a> method, as always, removes the current
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> associated with the thread, if any. However, one advantage of the
<tt class="docutils literal"><span class="pre">threading.local()</span></tt> object is that if the application thread itself ends, the
“storage” for that thread is also garbage collected. So it is in fact “safe” to
use thread local scope with an application that spawns and tears down threads,
without the need to call <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session.remove" title="sqlalchemy.orm.scoping.scoped_session.remove"><tt class="xref py py-meth docutils literal"><span class="pre">scoped_session.remove()</span></tt></a>. However, the scope
of transactions themselves, i.e. ending them via <a class="reference internal" href="#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-meth docutils literal"><span class="pre">Session.commit()</span></tt></a> or
<a class="reference internal" href="#sqlalchemy.orm.session.Session.rollback" title="sqlalchemy.orm.session.Session.rollback"><tt class="xref py py-meth docutils literal"><span class="pre">Session.rollback()</span></tt></a>, will usually still be something that must be explicitly
arranged for at the appropriate time, unless the application actually ties the
lifespan of a thread to the lifespan of a transaction.</p>
</div>
<div class="section" id="using-thread-local-scope-with-web-applications">
<span id="session-lifespan"></span><h3>Using Thread-Local Scope with Web Applications<a class="headerlink" href="#using-thread-local-scope-with-web-applications" title="Permalink to this headline">¶</a></h3>
<p>As discussed in the section <a class="reference internal" href="#session-faq-whentocreate"><em>When do I construct a Session, when do I commit it, and when do I close it?</em></a>, a web application
is architected around the concept of a <strong>web request</strong>, and integrating
such an application with the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> usually implies that the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
will be associated with that request. As it turns out, most Python web frameworks,
with notable exceptions such as the asynchronous frameworks Twisted and
Tornado, use threads in a simple way, such that a particular web request is received,
processed, and completed within the scope of a single <em>worker thread</em>. When
the request ends, the worker thread is released to a pool of workers where it
is available to handle another request.</p>
<p>This simple correspondence of web request and thread means that to associate a
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> with a thread implies it is also associated with the web request
running within that thread, and vice versa, provided that the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is
created only after the web request begins and torn down just before the web request ends.
So it is a common practice to use <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a> as a quick way
to integrate the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> with a web application. The sequence
diagram below illustrates this flow:</p>
<div class="highlight-python"><pre>Web Server Web Framework SQLAlchemy ORM Code
-------------- -------------- ------------------------------
startup -> Web framework # Session registry is established
initializes Session = scoped_session(sessionmaker())
incoming
web request -> web request -> # The registry is *optionally*
starts # called upon explicitly to create
# a Session local to the thread and/or request
Session()
# the Session registry can otherwise
# be used at any time, creating the
# request-local Session() if not present,
# or returning the existing one
Session.query(MyClass) # ...
Session.add(some_object) # ...
# if data was modified, commit the
# transaction
Session.commit()
web request ends -> # the registry is instructed to
# remove the Session
Session.remove()
sends output <-
outgoing web <-
response</pre>
</div>
<p>Using the above flow, the process of integrating the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> with the
web application has exactly two requirements:</p>
<ol class="arabic simple">
<li>Create a single <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a> registry when the web application
first starts, ensuring that this object is accessible by the rest of the
application.</li>
<li>Ensure that <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session.remove" title="sqlalchemy.orm.scoping.scoped_session.remove"><tt class="xref py py-meth docutils literal"><span class="pre">scoped_session.remove()</span></tt></a> is called when the web request ends,
usually by integrating with the web framework’s event system to establish
an “on request end” event.</li>
</ol>
<p>As noted earlier, the above pattern is <strong>just one potential way</strong> to integrate a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
with a web framework, one which in particular makes the significant assumption
that the <strong>web framework associates web requests with application threads</strong>. It is
however <strong>strongly recommended that the integration tools provided with the web framework
itself be used, if available</strong>, instead of <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a>.</p>
<p>In particular, while using a thread local can be convenient, it is preferable that the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> be
associated <strong>directly with the request</strong>, rather than with
the current thread. The next section on custom scopes details a more advanced configuration
which can combine the usage of <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a> with direct request based scope, or
any kind of scope.</p>
</div>
<div class="section" id="using-custom-created-scopes">
<h3>Using Custom Created Scopes<a class="headerlink" href="#using-custom-created-scopes" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a> object’s default behavior of “thread local” scope is only
one of many options on how to “scope” a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>. A custom scope can be defined
based on any existing system of getting at “the current thing we are working with”.</p>
<p>Suppose a web framework defines a library function <tt class="docutils literal"><span class="pre">get_current_request()</span></tt>. An application
built using this framework can call this function at any time, and the result will be
some kind of <tt class="docutils literal"><span class="pre">Request</span></tt> object that represents the current request being processed.
If the <tt class="docutils literal"><span class="pre">Request</span></tt> object is hashable, then this function can be easily integrated with
<a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a> to associate the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> with the request. Below we illustrate
this in conjunction with a hypothetical event marker provided by the web framework
<tt class="docutils literal"><span class="pre">on_request_end</span></tt>, which allows code to be invoked whenever a request ends:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">my_web_framework</span> <span class="kn">import</span> <span class="n">get_current_request</span><span class="p">,</span> <span class="n">on_request_end</span>
<span class="kn">from</span> <span class="nn">sqlalchemy.orm</span> <span class="kn">import</span> <span class="n">scoped_session</span><span class="p">,</span> <span class="n">sessionmaker</span>
<span class="n">Session</span> <span class="o">=</span> <span class="n">scoped_session</span><span class="p">(</span><span class="n">sessionmaker</span><span class="p">(</span><span class="n">bind</span><span class="o">=</span><span class="n">some_engine</span><span class="p">),</span> <span class="n">scopefunc</span><span class="o">=</span><span class="n">get_current_request</span><span class="p">)</span>
<span class="nd">@on_request_end</span>
<span class="k">def</span> <span class="nf">remove_session</span><span class="p">(</span><span class="n">req</span><span class="p">):</span>
<span class="n">Session</span><span class="o">.</span><span class="n">remove</span><span class="p">()</span></pre></div>
</div>
<p>Above, we instantiate <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a> in the usual way, except that we pass
our request-returning function as the “scopefunc”. This instructs <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a>
to use this function to generate a dictionary key whenever the registry is called upon
to return the current <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>. In this case it is particularly important
that we ensure a reliable “remove” system is implemented, as this dictionary is not
otherwise self-managed.</p>
</div>
<div class="section" id="contextual-session-api">
<h3>Contextual Session API<a class="headerlink" href="#contextual-session-api" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="sqlalchemy.orm.scoping.scoped_session">
<em class="property">class </em><tt class="descclassname">sqlalchemy.orm.scoping.</tt><tt class="descname">scoped_session</tt><big>(</big><em>session_factory</em>, <em>scopefunc=None</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.scoping.scoped_session" title="Permalink to this definition">¶</a></dt>
<dd><p>Provides scoped management of <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> objects.</p>
<p>See <a class="reference internal" href="#unitofwork-contextual"><em>Contextual/Thread-local Sessions</em></a> for a tutorial.</p>
<dl class="method">
<dt id="sqlalchemy.orm.scoping.scoped_session.__call__">
<tt class="descname">__call__</tt><big>(</big><em>**kw</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.scoping.scoped_session.__call__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>, creating it
using the session factory if not present.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><span class="target" id="sqlalchemy.orm.scoping.scoped_session.__call__.params.**kw"></span><strong>**kw</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.scoping.scoped_session.__call__.params.**kw">¶</a> – Keyword arguments will be passed to the
session factory callable, if an existing <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
is not present. If the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is present and
keyword arguments have been passed,
<a class="reference internal" href="../core/exceptions.html#sqlalchemy.exc.InvalidRequestError" title="sqlalchemy.exc.InvalidRequestError"><tt class="xref py py-exc docutils literal"><span class="pre">InvalidRequestError</span></tt></a> is raised.</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.scoping.scoped_session.__init__">
<tt class="descname">__init__</tt><big>(</big><em>session_factory</em>, <em>scopefunc=None</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.scoping.scoped_session.__init__" title="Permalink to this definition">¶</a></dt>
<dd><p>Construct a new <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a>.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><span class="target" id="sqlalchemy.orm.scoping.scoped_session.params.session_factory"></span><strong>session_factory</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.scoping.scoped_session.params.session_factory">¶</a> – a factory to create new <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
instances. This is usually, but not necessarily, an instance
of <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a>.</li>
<li><span class="target" id="sqlalchemy.orm.scoping.scoped_session.params.scopefunc"></span><strong>scopefunc</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.scoping.scoped_session.params.scopefunc">¶</a> – optional function which defines
the current scope. If not passed, the <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a>
object assumes “thread-local” scope, and will use
a Python <tt class="docutils literal"><span class="pre">threading.local()</span></tt> in order to maintain the current
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>. If passed, the function should return
a hashable token; this token will be used as the key in a
dictionary in order to store and retrieve the current
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>.</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.scoping.scoped_session.configure">
<tt class="descname">configure</tt><big>(</big><em>**kwargs</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.scoping.scoped_session.configure" title="Permalink to this definition">¶</a></dt>
<dd><p>reconfigure the <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> used by this
<a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a>.</p>
<p>See <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker.configure" title="sqlalchemy.orm.session.sessionmaker.configure"><tt class="xref py py-meth docutils literal"><span class="pre">sessionmaker.configure()</span></tt></a>.</p>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.scoping.scoped_session.query_property">
<tt class="descname">query_property</tt><big>(</big><em>query_cls=None</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.scoping.scoped_session.query_property" title="Permalink to this definition">¶</a></dt>
<dd><p>return a class property which produces a <a class="reference internal" href="query.html#sqlalchemy.orm.query.Query" title="sqlalchemy.orm.query.Query"><tt class="xref py py-class docutils literal"><span class="pre">Query</span></tt></a> object
against the class and the current <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> when called.</p>
<p>e.g.:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Session</span> <span class="o">=</span> <span class="n">scoped_session</span><span class="p">(</span><span class="n">sessionmaker</span><span class="p">())</span>
<span class="k">class</span> <span class="nc">MyClass</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="n">query</span> <span class="o">=</span> <span class="n">Session</span><span class="o">.</span><span class="n">query_property</span><span class="p">()</span>
<span class="c"># after mappers are defined</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">MyClass</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">MyClass</span><span class="o">.</span><span class="n">name</span><span class="o">==</span><span class="s">'foo'</span><span class="p">)</span><span class="o">.</span><span class="n">all</span><span class="p">()</span></pre></div>
</div>
<p>Produces instances of the session’s configured query class by
default. To override and use a custom implementation, provide
a <tt class="docutils literal"><span class="pre">query_cls</span></tt> callable. The callable will be invoked with
the class’s mapper as a positional argument and a session
keyword argument.</p>
<p>There is no limit to the number of query properties placed on
a class.</p>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.scoping.scoped_session.remove">
<tt class="descname">remove</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.orm.scoping.scoped_session.remove" title="Permalink to this definition">¶</a></dt>
<dd><p>Dispose of the current <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>, if present.</p>
<p>This will first call <a class="reference internal" href="#sqlalchemy.orm.session.Session.close" title="sqlalchemy.orm.session.Session.close"><tt class="xref py py-meth docutils literal"><span class="pre">Session.close()</span></tt></a> method
on the current <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>, which releases any existing
transactional/connection resources still being held; transactions
specifically are rolled back. The <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is then
discarded. Upon next usage within the same scope,
the <a class="reference internal" href="#sqlalchemy.orm.scoping.scoped_session" title="sqlalchemy.orm.scoping.scoped_session"><tt class="xref py py-class docutils literal"><span class="pre">scoped_session</span></tt></a> will produce a new
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> object.</p>
</dd></dl>
</dd></dl>
<dl class="class">
<dt id="sqlalchemy.util.ScopedRegistry">
<em class="property">class </em><tt class="descclassname">sqlalchemy.util.</tt><tt class="descname">ScopedRegistry</tt><big>(</big><em>createfunc</em>, <em>scopefunc</em><big>)</big><a class="headerlink" href="#sqlalchemy.util.ScopedRegistry" title="Permalink to this definition">¶</a></dt>
<dd><p>A Registry that can store one or multiple instances of a single
class on the basis of a “scope” function.</p>
<p>The object implements <tt class="docutils literal"><span class="pre">__call__</span></tt> as the “getter”, so by
calling <tt class="docutils literal"><span class="pre">myregistry()</span></tt> the contained object is returned
for the current scope.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><span class="target" id="sqlalchemy.util.ScopedRegistry.params.createfunc"></span><strong>createfunc</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.util.ScopedRegistry.params.createfunc">¶</a> – a callable that returns a new object to be placed in the registry</li>
<li><span class="target" id="sqlalchemy.util.ScopedRegistry.params.scopefunc"></span><strong>scopefunc</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.util.ScopedRegistry.params.scopefunc">¶</a> – a callable that will return a key to store/retrieve an object.</li>
</ul>
</td>
</tr>
</tbody>
</table>
<dl class="method">
<dt id="sqlalchemy.util.ScopedRegistry.__init__">
<tt class="descname">__init__</tt><big>(</big><em>createfunc</em>, <em>scopefunc</em><big>)</big><a class="headerlink" href="#sqlalchemy.util.ScopedRegistry.__init__" title="Permalink to this definition">¶</a></dt>
<dd><p>Construct a new <a class="reference internal" href="#sqlalchemy.util.ScopedRegistry" title="sqlalchemy.util.ScopedRegistry"><tt class="xref py py-class docutils literal"><span class="pre">ScopedRegistry</span></tt></a>.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><span class="target" id="sqlalchemy.util.ScopedRegistry.params.createfunc"></span><strong>createfunc</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.util.ScopedRegistry.params.createfunc">¶</a> – A creation function that will generate
a new value for the current scope, if none is present.</li>
<li><span class="target" id="sqlalchemy.util.ScopedRegistry.params.scopefunc"></span><strong>scopefunc</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.util.ScopedRegistry.params.scopefunc">¶</a> – A function that returns a hashable
token representing the current scope (such as, current
thread identifier).</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.util.ScopedRegistry.clear">
<tt class="descname">clear</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.util.ScopedRegistry.clear" title="Permalink to this definition">¶</a></dt>
<dd><p>Clear the current scope, if any.</p>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.util.ScopedRegistry.has">
<tt class="descname">has</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.util.ScopedRegistry.has" title="Permalink to this definition">¶</a></dt>
<dd><p>Return True if an object is present in the current scope.</p>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.util.ScopedRegistry.set">
<tt class="descname">set</tt><big>(</big><em>obj</em><big>)</big><a class="headerlink" href="#sqlalchemy.util.ScopedRegistry.set" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the value for the current scope.</p>
</dd></dl>
</dd></dl>
<dl class="class">
<dt id="sqlalchemy.util.ThreadLocalRegistry">
<em class="property">class </em><tt class="descclassname">sqlalchemy.util.</tt><tt class="descname">ThreadLocalRegistry</tt><big>(</big><em>createfunc</em><big>)</big><a class="headerlink" href="#sqlalchemy.util.ThreadLocalRegistry" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <tt class="xref py py-class docutils literal"><span class="pre">sqlalchemy.util._collections.ScopedRegistry</span></tt></p>
<p>A <a class="reference internal" href="#sqlalchemy.util.ScopedRegistry" title="sqlalchemy.util.ScopedRegistry"><tt class="xref py py-class docutils literal"><span class="pre">ScopedRegistry</span></tt></a> that uses a <tt class="docutils literal"><span class="pre">threading.local()</span></tt>
variable for storage.</p>
</dd></dl>
</div>
</div>
<div class="section" id="partitioning-strategies">
<span id="session-partitioning"></span><h2>Partitioning Strategies<a class="headerlink" href="#partitioning-strategies" title="Permalink to this headline">¶</a></h2>
<div class="section" id="simple-vertical-partitioning">
<h3>Simple Vertical Partitioning<a class="headerlink" href="#simple-vertical-partitioning" title="Permalink to this headline">¶</a></h3>
<p>Vertical partitioning places different kinds of objects, or different tables,
across multiple databases:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">engine1</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">'postgresql://db1'</span><span class="p">)</span>
<span class="n">engine2</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">'postgresql://db2'</span><span class="p">)</span>
<span class="n">Session</span> <span class="o">=</span> <span class="n">sessionmaker</span><span class="p">(</span><span class="n">twophase</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="c"># bind User operations to engine 1, Account operations to engine 2</span>
<span class="n">Session</span><span class="o">.</span><span class="n">configure</span><span class="p">(</span><span class="n">binds</span><span class="o">=</span><span class="p">{</span><span class="n">User</span><span class="p">:</span><span class="n">engine1</span><span class="p">,</span> <span class="n">Account</span><span class="p">:</span><span class="n">engine2</span><span class="p">})</span>
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span></pre></div>
</div>
<p>Above, operations against either class will make usage of the <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a>
linked to that class. Upon a flush operation, similar rules take place
to ensure each class is written to the right database.</p>
<p>The transactions among the multiple databases can optionally be coordinated
via two phase commit, if the underlying backend supports it. See
<a class="reference internal" href="#session-twophase"><em>Enabling Two-Phase Commit</em></a> for an example.</p>
</div>
<div class="section" id="custom-vertical-partitioning">
<h3>Custom Vertical Partitioning<a class="headerlink" href="#custom-vertical-partitioning" title="Permalink to this headline">¶</a></h3>
<p>More comprehensive rule-based class-level partitioning can be built by
overriding the <a class="reference internal" href="#sqlalchemy.orm.session.Session.get_bind" title="sqlalchemy.orm.session.Session.get_bind"><tt class="xref py py-meth docutils literal"><span class="pre">Session.get_bind()</span></tt></a> method. Below we illustrate
a custom <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> which delivers the following rules:</p>
<ol class="arabic simple">
<li>Flush operations are delivered to the engine named <tt class="docutils literal"><span class="pre">master</span></tt>.</li>
<li>Operations on objects that subclass <tt class="docutils literal"><span class="pre">MyOtherClass</span></tt> all
occur on the <tt class="docutils literal"><span class="pre">other</span></tt> engine.</li>
<li>Read operations for all other classes occur on a random
choice of the <tt class="docutils literal"><span class="pre">slave1</span></tt> or <tt class="docutils literal"><span class="pre">slave2</span></tt> database.</li>
</ol>
<div class="highlight-python"><div class="highlight"><pre><span class="n">engines</span> <span class="o">=</span> <span class="p">{</span>
<span class="s">'master'</span><span class="p">:</span><span class="n">create_engine</span><span class="p">(</span><span class="s">"sqlite:///master.db"</span><span class="p">),</span>
<span class="s">'other'</span><span class="p">:</span><span class="n">create_engine</span><span class="p">(</span><span class="s">"sqlite:///other.db"</span><span class="p">),</span>
<span class="s">'slave1'</span><span class="p">:</span><span class="n">create_engine</span><span class="p">(</span><span class="s">"sqlite:///slave1.db"</span><span class="p">),</span>
<span class="s">'slave2'</span><span class="p">:</span><span class="n">create_engine</span><span class="p">(</span><span class="s">"sqlite:///slave2.db"</span><span class="p">),</span>
<span class="p">}</span>
<span class="kn">from</span> <span class="nn">sqlalchemy.orm</span> <span class="kn">import</span> <span class="n">Session</span><span class="p">,</span> <span class="n">sessionmaker</span>
<span class="kn">import</span> <span class="nn">random</span>
<span class="k">class</span> <span class="nc">RoutingSession</span><span class="p">(</span><span class="n">Session</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">get_bind</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">mapper</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">clause</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
<span class="k">if</span> <span class="n">mapper</span> <span class="ow">and</span> <span class="nb">issubclass</span><span class="p">(</span><span class="n">mapper</span><span class="o">.</span><span class="n">class_</span><span class="p">,</span> <span class="n">MyOtherClass</span><span class="p">):</span>
<span class="k">return</span> <span class="n">engines</span><span class="p">[</span><span class="s">'other'</span><span class="p">]</span>
<span class="k">elif</span> <span class="bp">self</span><span class="o">.</span><span class="n">_flushing</span><span class="p">:</span>
<span class="k">return</span> <span class="n">engines</span><span class="p">[</span><span class="s">'master'</span><span class="p">]</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="n">engines</span><span class="p">[</span>
<span class="n">random</span><span class="o">.</span><span class="n">choice</span><span class="p">([</span><span class="s">'slave1'</span><span class="p">,</span><span class="s">'slave2'</span><span class="p">])</span>
<span class="p">]</span></pre></div>
</div>
<p>The above <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> class is plugged in using the <tt class="docutils literal"><span class="pre">class_</span></tt>
argument to <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Session</span> <span class="o">=</span> <span class="n">sessionmaker</span><span class="p">(</span><span class="n">class_</span><span class="o">=</span><span class="n">RoutingSession</span><span class="p">)</span></pre></div>
</div>
<p>This approach can be combined with multiple <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.MetaData" title="sqlalchemy.schema.MetaData"><tt class="xref py py-class docutils literal"><span class="pre">MetaData</span></tt></a> objects,
using an approach such as that of using the declarative <tt class="docutils literal"><span class="pre">__abstract__</span></tt>
keyword, described at <a class="reference internal" href="extensions/declarative.html#declarative-abstract"><em>__abstract__</em></a>.</p>
</div>
<div class="section" id="horizontal-partitioning">
<h3>Horizontal Partitioning<a class="headerlink" href="#horizontal-partitioning" title="Permalink to this headline">¶</a></h3>
<p>Horizontal partitioning partitions the rows of a single table (or a set of
tables) across multiple databases.</p>
<p>See the “sharding” example: <a class="reference internal" href="examples.html#examples-sharding"><em>Horizontal Sharding</em></a>.</p>
</div>
</div>
<div class="section" id="sessions-api">
<h2>Sessions API<a class="headerlink" href="#sessions-api" title="Permalink to this headline">¶</a></h2>
<div class="section" id="session-and-sessionmaker">
<h3>Session and sessionmaker()<a class="headerlink" href="#session-and-sessionmaker" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="sqlalchemy.orm.session.sessionmaker">
<em class="property">class </em><tt class="descclassname">sqlalchemy.orm.session.</tt><tt class="descname">sessionmaker</tt><big>(</big><em>bind=None</em>, <em>class_=<class 'sqlalchemy.orm.session.Session'></em>, <em>autoflush=True</em>, <em>autocommit=False</em>, <em>expire_on_commit=True</em>, <em>info=None</em>, <em>**kw</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.sessionmaker" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <tt class="xref py py-class docutils literal"><span class="pre">sqlalchemy.orm.session._SessionClassMethods</span></tt></p>
<p>A configurable <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> factory.</p>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> factory generates new
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> objects when called, creating them given
the configurational arguments established here.</p>
<p>e.g.:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># global scope</span>
<span class="n">Session</span> <span class="o">=</span> <span class="n">sessionmaker</span><span class="p">(</span><span class="n">autoflush</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
<span class="c"># later, in a local scope, create and use a session:</span>
<span class="n">sess</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span></pre></div>
</div>
<p>Any keyword arguments sent to the constructor itself will override the
“configured” keywords:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Session</span> <span class="o">=</span> <span class="n">sessionmaker</span><span class="p">()</span>
<span class="c"># bind an individual session to a connection</span>
<span class="n">sess</span> <span class="o">=</span> <span class="n">Session</span><span class="p">(</span><span class="n">bind</span><span class="o">=</span><span class="n">connection</span><span class="p">)</span></pre></div>
</div>
<p>The class also includes a method <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker.configure" title="sqlalchemy.orm.session.sessionmaker.configure"><tt class="xref py py-meth docutils literal"><span class="pre">configure()</span></tt></a>, which can
be used to specify additional keyword arguments to the factory, which
will take effect for subsequent <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> objects generated.
This is usually used to associate one or more <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> objects
with an existing <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> factory before it is first
used:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># application starts</span>
<span class="n">Session</span> <span class="o">=</span> <span class="n">sessionmaker</span><span class="p">()</span>
<span class="c"># ... later</span>
<span class="n">engine</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">'sqlite:///foo.db'</span><span class="p">)</span>
<span class="n">Session</span><span class="o">.</span><span class="n">configure</span><span class="p">(</span><span class="n">bind</span><span class="o">=</span><span class="n">engine</span><span class="p">)</span>
<span class="n">sess</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span></pre></div>
</div>
<dl class="method">
<dt id="sqlalchemy.orm.session.sessionmaker.__call__">
<tt class="descname">__call__</tt><big>(</big><em>**local_kw</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.sessionmaker.__call__" title="Permalink to this definition">¶</a></dt>
<dd><p>Produce a new <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> object using the configuration
established in this <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a>.</p>
<p>In Python, the <tt class="docutils literal"><span class="pre">__call__</span></tt> method is invoked on an object when
it is “called” in the same way as a function:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Session</span> <span class="o">=</span> <span class="n">sessionmaker</span><span class="p">()</span>
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span> <span class="c"># invokes sessionmaker.__call__()</span></pre></div>
</div>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.sessionmaker.__init__">
<tt class="descname">__init__</tt><big>(</big><em>bind=None</em>, <em>class_=<class 'sqlalchemy.orm.session.Session'></em>, <em>autoflush=True</em>, <em>autocommit=False</em>, <em>expire_on_commit=True</em>, <em>info=None</em>, <em>**kw</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.sessionmaker.__init__" title="Permalink to this definition">¶</a></dt>
<dd><p>Construct a new <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a>.</p>
<p>All arguments here except for <tt class="docutils literal"><span class="pre">class_</span></tt> correspond to arguments
accepted by <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> directly. See the
<a class="reference internal" href="#sqlalchemy.orm.session.Session.__init__" title="sqlalchemy.orm.session.Session.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">Session.__init__()</span></tt></a> docstring for more details on parameters.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><span class="target" id="sqlalchemy.orm.session.sessionmaker.params.bind"></span><strong>bind</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.sessionmaker.params.bind">¶</a> – a <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> or other <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connectable" title="sqlalchemy.engine.Connectable"><tt class="xref py py-class docutils literal"><span class="pre">Connectable</span></tt></a> with
which newly created <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> objects will be associated.</li>
<li><span class="target" id="sqlalchemy.orm.session.sessionmaker.params.class_"></span><strong>class_</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.sessionmaker.params.class_">¶</a> – class to use in order to create new <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
objects. Defaults to <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>.</li>
<li><span class="target" id="sqlalchemy.orm.session.sessionmaker.params.autoflush"></span><strong>autoflush</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.sessionmaker.params.autoflush">¶</a> – The autoflush setting to use with newly created
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> objects.</li>
<li><span class="target" id="sqlalchemy.orm.session.sessionmaker.params.autocommit"></span><strong>autocommit</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.sessionmaker.params.autocommit">¶</a> – The autocommit setting to use with newly created
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> objects.</li>
<li><span class="target" id="sqlalchemy.orm.session.sessionmaker.params.expire_on_commit"></span><strong>expire_on_commit=True</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.sessionmaker.params.expire_on_commit">¶</a> – the expire_on_commit setting to use
with newly created <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> objects.</li>
<li><span class="target" id="sqlalchemy.orm.session.sessionmaker.params.info"></span><strong>info</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.sessionmaker.params.info">¶</a> – <p>optional dictionary of information that will be available
via <a class="reference internal" href="#sqlalchemy.orm.session.Session.info" title="sqlalchemy.orm.session.Session.info"><tt class="xref py py-attr docutils literal"><span class="pre">Session.info</span></tt></a>. Note this dictionary is <em>updated</em>, not
replaced, when the <tt class="docutils literal"><span class="pre">info</span></tt> parameter is specified to the specific
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> construction operation.</p>
<div class="versionadded">
<p><span>New in version 0.9.0.</span></p>
</div>
</li>
<li><span class="target" id="sqlalchemy.orm.session.sessionmaker.params.**kw"></span><strong>**kw</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.sessionmaker.params.**kw">¶</a> – all other keyword arguments are passed to the
constructor of newly created <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> objects.</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="classmethod">
<dt id="sqlalchemy.orm.session.sessionmaker.close_all">
<em class="property">classmethod </em><tt class="descname">close_all</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.sessionmaker.close_all" title="Permalink to this definition">¶</a></dt>
<dd><div class="inherited-member container">
<em>inherited from the</em> <tt class="xref py py-meth docutils literal"><span class="pre">close_all()</span></tt> <em>method of</em> <tt class="xref py py-class docutils literal"><span class="pre">_SessionClassMethods</span></tt></div>
<p>Close <em>all</em> sessions in memory.</p>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.sessionmaker.configure">
<tt class="descname">configure</tt><big>(</big><em>**new_kw</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.sessionmaker.configure" title="Permalink to this definition">¶</a></dt>
<dd><p>(Re)configure the arguments for this sessionmaker.</p>
<p>e.g.:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Session</span> <span class="o">=</span> <span class="n">sessionmaker</span><span class="p">()</span>
<span class="n">Session</span><span class="o">.</span><span class="n">configure</span><span class="p">(</span><span class="n">bind</span><span class="o">=</span><span class="n">create_engine</span><span class="p">(</span><span class="s">'sqlite://'</span><span class="p">))</span></pre></div>
</div>
</dd></dl>
<dl class="classmethod">
<dt id="sqlalchemy.orm.session.sessionmaker.identity_key">
<em class="property">classmethod </em><tt class="descname">identity_key</tt><big>(</big><em>*args</em>, <em>**kwargs</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.sessionmaker.identity_key" title="Permalink to this definition">¶</a></dt>
<dd><div class="inherited-member container">
<em>inherited from the</em> <tt class="xref py py-meth docutils literal"><span class="pre">identity_key()</span></tt> <em>method of</em> <tt class="xref py py-class docutils literal"><span class="pre">_SessionClassMethods</span></tt></div>
<p>Return an identity key.</p>
<p>This is an alias of <a class="reference internal" href="mapper_config.html#sqlalchemy.orm.util.identity_key" title="sqlalchemy.orm.util.identity_key"><tt class="xref py py-func docutils literal"><span class="pre">util.identity_key()</span></tt></a>.</p>
</dd></dl>
<dl class="classmethod">
<dt id="sqlalchemy.orm.session.sessionmaker.object_session">
<em class="property">classmethod </em><tt class="descname">object_session</tt><big>(</big><em>instance</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.sessionmaker.object_session" title="Permalink to this definition">¶</a></dt>
<dd><div class="inherited-member container">
<em>inherited from the</em> <tt class="xref py py-meth docutils literal"><span class="pre">object_session()</span></tt> <em>method of</em> <tt class="xref py py-class docutils literal"><span class="pre">_SessionClassMethods</span></tt></div>
<p>Return the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> to which an object belongs.</p>
<p>This is an alias of <a class="reference internal" href="#sqlalchemy.orm.session.object_session" title="sqlalchemy.orm.session.object_session"><tt class="xref py py-func docutils literal"><span class="pre">object_session()</span></tt></a>.</p>
</dd></dl>
</dd></dl>
<dl class="class">
<dt id="sqlalchemy.orm.session.Session">
<em class="property">class </em><tt class="descclassname">sqlalchemy.orm.session.</tt><tt class="descname">Session</tt><big>(</big><em>bind=None</em>, <em>autoflush=True</em>, <em>expire_on_commit=True</em>, <em>_enable_transaction_accounting=True</em>, <em>autocommit=False</em>, <em>twophase=False</em>, <em>weak_identity_map=True</em>, <em>binds=None</em>, <em>extension=None</em>, <em>info=None</em>, <em>query_cls=<class 'sqlalchemy.orm.query.Query'></em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <tt class="xref py py-class docutils literal"><span class="pre">sqlalchemy.orm.session._SessionClassMethods</span></tt></p>
<p>Manages persistence operations for ORM-mapped objects.</p>
<p>The Session’s usage paradigm is described at <a class="reference internal" href=""><em>Using the Session</em></a>.</p>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.__init__">
<tt class="descname">__init__</tt><big>(</big><em>bind=None</em>, <em>autoflush=True</em>, <em>expire_on_commit=True</em>, <em>_enable_transaction_accounting=True</em>, <em>autocommit=False</em>, <em>twophase=False</em>, <em>weak_identity_map=True</em>, <em>binds=None</em>, <em>extension=None</em>, <em>info=None</em>, <em>query_cls=<class 'sqlalchemy.orm.query.Query'></em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.__init__" title="Permalink to this definition">¶</a></dt>
<dd><p>Construct a new Session.</p>
<p>See also the <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> function which is used to
generate a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>-producing callable with a given
set of arguments.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><span class="target" id="sqlalchemy.orm.session.Session.params.autocommit"></span><strong>autocommit</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.params.autocommit">¶</a> – <div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">The autocommit flag is <strong>not for general use</strong>, and if it is
used, queries should only be invoked within the span of a
<a class="reference internal" href="#sqlalchemy.orm.session.Session.begin" title="sqlalchemy.orm.session.Session.begin"><tt class="xref py py-meth docutils literal"><span class="pre">Session.begin()</span></tt></a> / <a class="reference internal" href="#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-meth docutils literal"><span class="pre">Session.commit()</span></tt></a> pair. Executing
queries outside of a demarcated transaction is a legacy mode
of usage, and can in some cases lead to concurrent connection
checkouts.</p>
</div>
<p>Defaults to <tt class="docutils literal"><span class="pre">False</span></tt>. When <tt class="docutils literal"><span class="pre">True</span></tt>, the
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> does not keep a persistent transaction running,
and will acquire connections from the engine on an as-needed basis,
returning them immediately after their use. Flushes will begin and
commit (or possibly rollback) their own transaction if no
transaction is present. When using this mode, the
<a class="reference internal" href="#sqlalchemy.orm.session.Session.begin" title="sqlalchemy.orm.session.Session.begin"><tt class="xref py py-meth docutils literal"><span class="pre">Session.begin()</span></tt></a> method is used to explicitly start
transactions.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="#session-autocommit"><em>Autocommit Mode</em></a></p>
</div>
</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.params.autoflush"></span><strong>autoflush</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.params.autoflush">¶</a> – When <tt class="docutils literal"><span class="pre">True</span></tt>, all query operations will issue a
<a class="reference internal" href="#sqlalchemy.orm.session.Session.flush" title="sqlalchemy.orm.session.Session.flush"><tt class="xref py py-meth docutils literal"><span class="pre">flush()</span></tt></a> call to this <tt class="docutils literal"><span class="pre">Session</span></tt> before proceeding.
This is a convenience feature so that <a class="reference internal" href="#sqlalchemy.orm.session.Session.flush" title="sqlalchemy.orm.session.Session.flush"><tt class="xref py py-meth docutils literal"><span class="pre">flush()</span></tt></a> need
not be called repeatedly in order for database queries to retrieve
results. It’s typical that <tt class="docutils literal"><span class="pre">autoflush</span></tt> is used in conjunction with
<tt class="docutils literal"><span class="pre">autocommit=False</span></tt>. In this scenario, explicit calls to
<a class="reference internal" href="#sqlalchemy.orm.session.Session.flush" title="sqlalchemy.orm.session.Session.flush"><tt class="xref py py-meth docutils literal"><span class="pre">flush()</span></tt></a> are rarely needed; you usually only need to
call <a class="reference internal" href="#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-meth docutils literal"><span class="pre">commit()</span></tt></a> (which flushes) to finalize changes.</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.params.bind"></span><strong>bind</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.params.bind">¶</a> – An optional <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> or <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> to
which this <tt class="docutils literal"><span class="pre">Session</span></tt> should be bound. When specified, all SQL
operations performed by this session will execute via this
connectable.</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.params.binds"></span><strong>binds</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.params.binds">¶</a> – <dl class="docutils">
<dt>An optional dictionary which contains more granular</dt>
<dd>“bind” information than the <tt class="docutils literal"><span class="pre">bind</span></tt> parameter provides. This
dictionary can map individual :class`.Table`
instances as well as <a class="reference internal" href="mapper_config.html#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> instances to individual
<a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> or <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> objects. Operations which
proceed relative to a particular <a class="reference internal" href="mapper_config.html#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> will consult this
dictionary for the direct <a class="reference internal" href="mapper_config.html#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> instance as
well as the mapper’s <tt class="docutils literal"><span class="pre">mapped_table</span></tt> attribute in order to locate a
connectable to use. The full resolution is described in the
<a class="reference internal" href="#sqlalchemy.orm.session.Session.get_bind" title="sqlalchemy.orm.session.Session.get_bind"><tt class="xref py py-meth docutils literal"><span class="pre">Session.get_bind()</span></tt></a>.
Usage looks like:<div class="last highlight-python"><div class="highlight"><pre><span class="n">Session</span> <span class="o">=</span> <span class="n">sessionmaker</span><span class="p">(</span><span class="n">binds</span><span class="o">=</span><span class="p">{</span>
<span class="n">SomeMappedClass</span><span class="p">:</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">'postgresql://engine1'</span><span class="p">),</span>
<span class="n">somemapper</span><span class="p">:</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">'postgresql://engine2'</span><span class="p">),</span>
<span class="n">some_table</span><span class="p">:</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">'postgresql://engine3'</span><span class="p">),</span>
<span class="p">})</span></pre></div>
</div>
</dd>
</dl>
<p>Also see the <a class="reference internal" href="#sqlalchemy.orm.session.Session.bind_mapper" title="sqlalchemy.orm.session.Session.bind_mapper"><tt class="xref py py-meth docutils literal"><span class="pre">Session.bind_mapper()</span></tt></a>
and <a class="reference internal" href="#sqlalchemy.orm.session.Session.bind_table" title="sqlalchemy.orm.session.Session.bind_table"><tt class="xref py py-meth docutils literal"><span class="pre">Session.bind_table()</span></tt></a> methods.</p>
</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.params.class_"></span><strong>class_</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.params.class_">¶</a> – Specify an alternate class other than
<tt class="docutils literal"><span class="pre">sqlalchemy.orm.session.Session</span></tt> which should be used by the
returned class. This is the only argument that is local to the
<a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> function, and is not sent directly to the
constructor for <tt class="docutils literal"><span class="pre">Session</span></tt>.</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.params._enable_transaction_accounting"></span><strong>_enable_transaction_accounting</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.params._enable_transaction_accounting">¶</a> – Defaults to <tt class="docutils literal"><span class="pre">True</span></tt>. A
legacy-only flag which when <tt class="docutils literal"><span class="pre">False</span></tt> disables <em>all</em> 0.5-style
object accounting on transaction boundaries, including auto-expiry
of instances on rollback and commit, maintenance of the “new” and
“deleted” lists upon rollback, and autoflush of pending changes
upon <a class="reference internal" href="#sqlalchemy.orm.session.Session.begin" title="sqlalchemy.orm.session.Session.begin"><tt class="xref py py-meth docutils literal"><span class="pre">begin()</span></tt></a>, all of which are interdependent.</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.params.expire_on_commit"></span><strong>expire_on_commit</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.params.expire_on_commit">¶</a> – Defaults to <tt class="docutils literal"><span class="pre">True</span></tt>. When <tt class="docutils literal"><span class="pre">True</span></tt>, all
instances will be fully expired after each <a class="reference internal" href="#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-meth docutils literal"><span class="pre">commit()</span></tt></a>,
so that all attribute/object access subsequent to a completed
transaction will load from the most recent database state.</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.params.extension"></span><strong>extension</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.params.extension">¶</a> – An optional
<a class="reference internal" href="deprecated.html#sqlalchemy.orm.interfaces.SessionExtension" title="sqlalchemy.orm.interfaces.SessionExtension"><tt class="xref py py-class docutils literal"><span class="pre">SessionExtension</span></tt></a> instance, or a list
of such instances, which will receive pre- and post- commit and
flush events, as well as a post-rollback event. <strong>Deprecated.</strong>
Please see <a class="reference internal" href="events.html#sqlalchemy.orm.events.SessionEvents" title="sqlalchemy.orm.events.SessionEvents"><tt class="xref py py-class docutils literal"><span class="pre">SessionEvents</span></tt></a>.</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.params.info"></span><strong>info</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.params.info">¶</a> – <p>optional dictionary of arbitrary data to be associated
with this <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>. Is available via the
<a class="reference internal" href="#sqlalchemy.orm.session.Session.info" title="sqlalchemy.orm.session.Session.info"><tt class="xref py py-attr docutils literal"><span class="pre">Session.info</span></tt></a> attribute. Note the dictionary is copied at
construction time so that modifications to the per-
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> dictionary will be local to that
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>.</p>
<div class="versionadded">
<p><span>New in version 0.9.0.</span></p>
</div>
</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.params.query_cls"></span><strong>query_cls</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.params.query_cls">¶</a> – Class which should be used to create new Query
objects, as returned by the <a class="reference internal" href="#sqlalchemy.orm.session.Session.query" title="sqlalchemy.orm.session.Session.query"><tt class="xref py py-meth docutils literal"><span class="pre">query()</span></tt></a> method. Defaults
to <a class="reference internal" href="query.html#sqlalchemy.orm.query.Query" title="sqlalchemy.orm.query.Query"><tt class="xref py py-class docutils literal"><span class="pre">Query</span></tt></a>.</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.params.twophase"></span><strong>twophase</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.params.twophase">¶</a> – When <tt class="docutils literal"><span class="pre">True</span></tt>, all transactions will be started as
a “two phase” transaction, i.e. using the “two phase” semantics
of the database in use along with an XID. During a
<a class="reference internal" href="#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-meth docutils literal"><span class="pre">commit()</span></tt></a>, after <a class="reference internal" href="#sqlalchemy.orm.session.Session.flush" title="sqlalchemy.orm.session.Session.flush"><tt class="xref py py-meth docutils literal"><span class="pre">flush()</span></tt></a> has been issued for all
attached databases, the <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.TwoPhaseTransaction.prepare" title="sqlalchemy.engine.TwoPhaseTransaction.prepare"><tt class="xref py py-meth docutils literal"><span class="pre">prepare()</span></tt></a>
method on each database’s <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.TwoPhaseTransaction" title="sqlalchemy.engine.TwoPhaseTransaction"><tt class="xref py py-class docutils literal"><span class="pre">TwoPhaseTransaction</span></tt></a> will be
called. This allows each database to roll back the entire
transaction, before each transaction is committed.</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.params.weak_identity_map"></span><strong>weak_identity_map</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.params.weak_identity_map">¶</a> – Defaults to <tt class="docutils literal"><span class="pre">True</span></tt> - when set to
<tt class="docutils literal"><span class="pre">False</span></tt>, objects placed in the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> will be
strongly referenced until explicitly removed or the
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is closed. <strong>Deprecated</strong> - this option
is obsolete.</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.add">
<tt class="descname">add</tt><big>(</big><em>instance</em>, <em>_warn=True</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.add" title="Permalink to this definition">¶</a></dt>
<dd><p>Place an object in the <tt class="docutils literal"><span class="pre">Session</span></tt>.</p>
<p>Its state will be persisted to the database on the next flush
operation.</p>
<p>Repeated calls to <tt class="docutils literal"><span class="pre">add()</span></tt> will be ignored. The opposite of <tt class="docutils literal"><span class="pre">add()</span></tt>
is <tt class="docutils literal"><span class="pre">expunge()</span></tt>.</p>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.add_all">
<tt class="descname">add_all</tt><big>(</big><em>instances</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.add_all" title="Permalink to this definition">¶</a></dt>
<dd><p>Add the given collection of instances to this <tt class="docutils literal"><span class="pre">Session</span></tt>.</p>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.begin">
<tt class="descname">begin</tt><big>(</big><em>subtransactions=False</em>, <em>nested=False</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.begin" title="Permalink to this definition">¶</a></dt>
<dd><p>Begin a transaction on this <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>.</p>
<p>If this Session is already within a transaction, either a plain
transaction or nested transaction, an error is raised, unless
<tt class="docutils literal"><span class="pre">subtransactions=True</span></tt> or <tt class="docutils literal"><span class="pre">nested=True</span></tt> is specified.</p>
<p>The <tt class="docutils literal"><span class="pre">subtransactions=True</span></tt> flag indicates that this
<a class="reference internal" href="#sqlalchemy.orm.session.Session.begin" title="sqlalchemy.orm.session.Session.begin"><tt class="xref py py-meth docutils literal"><span class="pre">begin()</span></tt></a> can create a subtransaction if a transaction
is already in progress. For documentation on subtransactions, please
see <a class="reference internal" href="#session-subtransactions"><em>Using Subtransactions with Autocommit</em></a>.</p>
<p>The <tt class="docutils literal"><span class="pre">nested</span></tt> flag begins a SAVEPOINT transaction and is equivalent
to calling <a class="reference internal" href="#sqlalchemy.orm.session.Session.begin_nested" title="sqlalchemy.orm.session.Session.begin_nested"><tt class="xref py py-meth docutils literal"><span class="pre">begin_nested()</span></tt></a>. For documentation on
SAVEPOINT transactions, please see <a class="reference internal" href="#session-begin-nested"><em>Using SAVEPOINT</em></a>.</p>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.begin_nested">
<tt class="descname">begin_nested</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.begin_nested" title="Permalink to this definition">¶</a></dt>
<dd><p>Begin a <cite>nested</cite> transaction on this Session.</p>
<p>The target database(s) must support SQL SAVEPOINTs or a
SQLAlchemy-supported vendor implementation of the idea.</p>
<p>For documentation on SAVEPOINT
transactions, please see <a class="reference internal" href="#session-begin-nested"><em>Using SAVEPOINT</em></a>.</p>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.bind_mapper">
<tt class="descname">bind_mapper</tt><big>(</big><em>mapper</em>, <em>bind</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.bind_mapper" title="Permalink to this definition">¶</a></dt>
<dd><p>Bind operations for a mapper to a Connectable.</p>
<dl class="docutils">
<dt>mapper</dt>
<dd>A mapper instance or mapped class</dd>
<dt>bind</dt>
<dd>Any Connectable: a <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> or <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a>.</dd>
</dl>
<p>All subsequent operations involving this mapper will use the given
<cite>bind</cite>.</p>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.bind_table">
<tt class="descname">bind_table</tt><big>(</big><em>table</em>, <em>bind</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.bind_table" title="Permalink to this definition">¶</a></dt>
<dd><p>Bind operations on a Table to a Connectable.</p>
<dl class="docutils">
<dt>table</dt>
<dd>A <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> instance</dd>
<dt>bind</dt>
<dd>Any Connectable: a <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> or <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a>.</dd>
</dl>
<p>All subsequent operations involving this <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> will use the
given <cite>bind</cite>.</p>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.close">
<tt class="descname">close</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close this Session.</p>
<p>This clears all items and ends any transaction in progress.</p>
<p>If this session were created with <tt class="docutils literal"><span class="pre">autocommit=False</span></tt>, a new
transaction is immediately begun. Note that this new transaction does
not use any connection resources until they are first needed.</p>
</dd></dl>
<dl class="classmethod">
<dt id="sqlalchemy.orm.session.Session.close_all">
<em class="property">classmethod </em><tt class="descname">close_all</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.close_all" title="Permalink to this definition">¶</a></dt>
<dd><div class="inherited-member container">
<em>inherited from the</em> <tt class="xref py py-meth docutils literal"><span class="pre">close_all()</span></tt> <em>method of</em> <tt class="xref py py-class docutils literal"><span class="pre">_SessionClassMethods</span></tt></div>
<p>Close <em>all</em> sessions in memory.</p>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.commit">
<tt class="descname">commit</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.commit" title="Permalink to this definition">¶</a></dt>
<dd><p>Flush pending changes and commit the current transaction.</p>
<p>If no transaction is in progress, this method raises an
<a class="reference internal" href="../core/exceptions.html#sqlalchemy.exc.InvalidRequestError" title="sqlalchemy.exc.InvalidRequestError"><tt class="xref py py-exc docutils literal"><span class="pre">InvalidRequestError</span></tt></a>.</p>
<p>By default, the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> also expires all database
loaded state on all ORM-managed attributes after transaction commit.
This so that subsequent operations load the most recent
data from the database. This behavior can be disabled using
the <tt class="docutils literal"><span class="pre">expire_on_commit=False</span></tt> option to <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> or
the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> constructor.</p>
<p>If a subtransaction is in effect (which occurs when begin() is called
multiple times), the subtransaction will be closed, and the next call
to <tt class="docutils literal"><span class="pre">commit()</span></tt> will operate on the enclosing transaction.</p>
<p>When using the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> in its default mode of
<tt class="docutils literal"><span class="pre">autocommit=False</span></tt>, a new transaction will
be begun immediately after the commit, but note that the newly begun
transaction does <em>not</em> use any connection resources until the first
SQL is actually emitted.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="#session-committing"><em>Committing</em></a></p>
</div>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.connection">
<tt class="descname">connection</tt><big>(</big><em>mapper=None</em>, <em>clause=None</em>, <em>bind=None</em>, <em>close_with_result=False</em>, <em>**kw</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.connection" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> object corresponding to this
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> object’s transactional state.</p>
<p>If this <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is configured with <tt class="docutils literal"><span class="pre">autocommit=False</span></tt>,
either the <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> corresponding to the current
transaction is returned, or if no transaction is in progress, a new
one is begun and the <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> returned (note that no
transactional state is established with the DBAPI until the first
SQL statement is emitted).</p>
<p>Alternatively, if this <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is configured with
<tt class="docutils literal"><span class="pre">autocommit=True</span></tt>, an ad-hoc <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> is returned
using <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine.contextual_connect" title="sqlalchemy.engine.Engine.contextual_connect"><tt class="xref py py-meth docutils literal"><span class="pre">Engine.contextual_connect()</span></tt></a> on the underlying
<a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a>.</p>
<p>Ambiguity in multi-bind or unbound <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> objects can be
resolved through any of the optional keyword arguments. This
ultimately makes usage of the <a class="reference internal" href="#sqlalchemy.orm.session.Session.get_bind" title="sqlalchemy.orm.session.Session.get_bind"><tt class="xref py py-meth docutils literal"><span class="pre">get_bind()</span></tt></a> method for resolution.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><span class="target" id="sqlalchemy.orm.session.Session.connection.params.bind"></span><strong>bind</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.connection.params.bind">¶</a> – Optional <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> to be used as the bind. If
this engine is already involved in an ongoing transaction,
that connection will be used. This argument takes precedence
over <tt class="docutils literal"><span class="pre">mapper</span></tt>, <tt class="docutils literal"><span class="pre">clause</span></tt>.</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.connection.params.mapper"></span><strong>mapper</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.connection.params.mapper">¶</a> – Optional <a class="reference internal" href="mapper_config.html#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a> mapped class, used to identify
the appropriate bind. This argument takes precedence over
<tt class="docutils literal"><span class="pre">clause</span></tt>.</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.connection.params.clause"></span><strong>clause</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.connection.params.clause">¶</a> – A <a class="reference internal" href="../core/sqlelement.html#sqlalchemy.sql.expression.ClauseElement" title="sqlalchemy.sql.expression.ClauseElement"><tt class="xref py py-class docutils literal"><span class="pre">ClauseElement</span></tt></a> (i.e. <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.select" title="sqlalchemy.sql.expression.select"><tt class="xref py py-func docutils literal"><span class="pre">select()</span></tt></a>,
<a class="reference internal" href="../core/sqlelement.html#sqlalchemy.sql.expression.text" title="sqlalchemy.sql.expression.text"><tt class="xref py py-func docutils literal"><span class="pre">text()</span></tt></a>,
etc.) which will be used to locate a bind, if a bind
cannot otherwise be identified.</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.connection.params.close_with_result"></span><strong>close_with_result</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.connection.params.close_with_result">¶</a> – Passed to <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine.connect" title="sqlalchemy.engine.Engine.connect"><tt class="xref py py-meth docutils literal"><span class="pre">Engine.connect()</span></tt></a>,
indicating the <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> should be considered
“single use”, automatically closing when the first result set is
closed. This flag only has an effect if this <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is
configured with <tt class="docutils literal"><span class="pre">autocommit=True</span></tt> and does not already have a
transaction in progress.</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.connection.params.**kw"></span><strong>**kw</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.connection.params.**kw">¶</a> – Additional keyword arguments are sent to <a class="reference internal" href="#sqlalchemy.orm.session.Session.get_bind" title="sqlalchemy.orm.session.Session.get_bind"><tt class="xref py py-meth docutils literal"><span class="pre">get_bind()</span></tt></a>,
allowing additional arguments to be passed to custom
implementations of <a class="reference internal" href="#sqlalchemy.orm.session.Session.get_bind" title="sqlalchemy.orm.session.Session.get_bind"><tt class="xref py py-meth docutils literal"><span class="pre">get_bind()</span></tt></a>.</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.delete">
<tt class="descname">delete</tt><big>(</big><em>instance</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.delete" title="Permalink to this definition">¶</a></dt>
<dd><p>Mark an instance as deleted.</p>
<p>The database delete operation occurs upon <tt class="docutils literal"><span class="pre">flush()</span></tt>.</p>
</dd></dl>
<dl class="attribute">
<dt id="sqlalchemy.orm.session.Session.deleted">
<tt class="descname">deleted</tt><a class="headerlink" href="#sqlalchemy.orm.session.Session.deleted" title="Permalink to this definition">¶</a></dt>
<dd><p>The set of all instances marked as ‘deleted’ within this <tt class="docutils literal"><span class="pre">Session</span></tt></p>
</dd></dl>
<dl class="attribute">
<dt id="sqlalchemy.orm.session.Session.dirty">
<tt class="descname">dirty</tt><a class="headerlink" href="#sqlalchemy.orm.session.Session.dirty" title="Permalink to this definition">¶</a></dt>
<dd><p>The set of all persistent instances considered dirty.</p>
<p>E.g.:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">some_mapped_object</span> <span class="ow">in</span> <span class="n">session</span><span class="o">.</span><span class="n">dirty</span></pre></div>
</div>
<p>Instances are considered dirty when they were modified but not
deleted.</p>
<p>Note that this ‘dirty’ calculation is ‘optimistic’; most
attribute-setting or collection modification operations will
mark an instance as ‘dirty’ and place it in this set, even if
there is no net change to the attribute’s value. At flush
time, the value of each attribute is compared to its
previously saved value, and if there’s no net change, no SQL
operation will occur (this is a more expensive operation so
it’s only done at flush time).</p>
<p>To check if an instance has actionable net changes to its
attributes, use the <a class="reference internal" href="#sqlalchemy.orm.session.Session.is_modified" title="sqlalchemy.orm.session.Session.is_modified"><tt class="xref py py-meth docutils literal"><span class="pre">Session.is_modified()</span></tt></a> method.</p>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.enable_relationship_loading">
<tt class="descname">enable_relationship_loading</tt><big>(</big><em>obj</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.enable_relationship_loading" title="Permalink to this definition">¶</a></dt>
<dd><p>Associate an object with this <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> for related
object loading.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last"><a class="reference internal" href="#sqlalchemy.orm.session.Session.enable_relationship_loading" title="sqlalchemy.orm.session.Session.enable_relationship_loading"><tt class="xref py py-meth docutils literal"><span class="pre">enable_relationship_loading()</span></tt></a> exists to serve special
use cases and is not recommended for general use.</p>
</div>
<p>Accesses of attributes mapped with <a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a>
will attempt to load a value from the database using this
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> as the source of connectivity. The values
will be loaded based on foreign key values present on this
object - it follows that this functionality
generally only works for many-to-one-relationships.</p>
<p>The object will be attached to this session, but will
<strong>not</strong> participate in any persistence operations; its state
for almost all purposes will remain either “transient” or
“detached”, except for the case of relationship loading.</p>
<p>Also note that backrefs will often not work as expected.
Altering a relationship-bound attribute on the target object
may not fire off a backref event, if the effective value
is what was already loaded from a foreign-key-holding value.</p>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.Session.enable_relationship_loading" title="sqlalchemy.orm.session.Session.enable_relationship_loading"><tt class="xref py py-meth docutils literal"><span class="pre">Session.enable_relationship_loading()</span></tt></a> method is
similar to the <tt class="docutils literal"><span class="pre">load_on_pending</span></tt> flag on <a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a>.
Unlike that flag, <a class="reference internal" href="#sqlalchemy.orm.session.Session.enable_relationship_loading" title="sqlalchemy.orm.session.Session.enable_relationship_loading"><tt class="xref py py-meth docutils literal"><span class="pre">Session.enable_relationship_loading()</span></tt></a> allows
an object to remain transient while still being able to load
related items.</p>
<p>To make a transient object associated with a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
via <a class="reference internal" href="#sqlalchemy.orm.session.Session.enable_relationship_loading" title="sqlalchemy.orm.session.Session.enable_relationship_loading"><tt class="xref py py-meth docutils literal"><span class="pre">Session.enable_relationship_loading()</span></tt></a> pending, add
it to the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> using <a class="reference internal" href="#sqlalchemy.orm.session.Session.add" title="sqlalchemy.orm.session.Session.add"><tt class="xref py py-meth docutils literal"><span class="pre">Session.add()</span></tt></a> normally.</p>
<p><a class="reference internal" href="#sqlalchemy.orm.session.Session.enable_relationship_loading" title="sqlalchemy.orm.session.Session.enable_relationship_loading"><tt class="xref py py-meth docutils literal"><span class="pre">Session.enable_relationship_loading()</span></tt></a> does not improve
behavior when the ORM is used normally - object references should be
constructed at the object level, not at the foreign key level, so
that they are present in an ordinary way before flush()
proceeds. This method is not intended for general use.</p>
<div class="versionadded">
<p><span>New in version 0.8.</span></p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><tt class="docutils literal"><span class="pre">load_on_pending</span></tt> at <a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> - this flag
allows per-relationship loading of many-to-ones on items that
are pending.</p>
</div>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.execute">
<tt class="descname">execute</tt><big>(</big><em>clause</em>, <em>params=None</em>, <em>mapper=None</em>, <em>bind=None</em>, <em>**kw</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.execute" title="Permalink to this definition">¶</a></dt>
<dd><p>Execute a SQL expression construct or string statement within
the current transaction.</p>
<p>Returns a <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.ResultProxy" title="sqlalchemy.engine.ResultProxy"><tt class="xref py py-class docutils literal"><span class="pre">ResultProxy</span></tt></a> representing
results of the statement execution, in the same manner as that of an
<a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> or
<a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a>.</p>
<p>E.g.:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">result</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span>
<span class="n">user_table</span><span class="o">.</span><span class="n">select</span><span class="p">()</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">user_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">id</span> <span class="o">==</span> <span class="mi">5</span><span class="p">)</span>
<span class="p">)</span></pre></div>
</div>
<p><a class="reference internal" href="#sqlalchemy.orm.session.Session.execute" title="sqlalchemy.orm.session.Session.execute"><tt class="xref py py-meth docutils literal"><span class="pre">execute()</span></tt></a> accepts any executable clause construct,
such as <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.select" title="sqlalchemy.sql.expression.select"><tt class="xref py py-func docutils literal"><span class="pre">select()</span></tt></a>,
<a class="reference internal" href="../core/dml.html#sqlalchemy.sql.expression.insert" title="sqlalchemy.sql.expression.insert"><tt class="xref py py-func docutils literal"><span class="pre">insert()</span></tt></a>,
<a class="reference internal" href="../core/dml.html#sqlalchemy.sql.expression.update" title="sqlalchemy.sql.expression.update"><tt class="xref py py-func docutils literal"><span class="pre">update()</span></tt></a>,
<a class="reference internal" href="../core/dml.html#sqlalchemy.sql.expression.delete" title="sqlalchemy.sql.expression.delete"><tt class="xref py py-func docutils literal"><span class="pre">delete()</span></tt></a>, and
<a class="reference internal" href="../core/sqlelement.html#sqlalchemy.sql.expression.text" title="sqlalchemy.sql.expression.text"><tt class="xref py py-func docutils literal"><span class="pre">text()</span></tt></a>. Plain SQL strings can be passed
as well, which in the case of <a class="reference internal" href="#sqlalchemy.orm.session.Session.execute" title="sqlalchemy.orm.session.Session.execute"><tt class="xref py py-meth docutils literal"><span class="pre">Session.execute()</span></tt></a> only
will be interpreted the same as if it were passed via a
<a class="reference internal" href="../core/sqlelement.html#sqlalchemy.sql.expression.text" title="sqlalchemy.sql.expression.text"><tt class="xref py py-func docutils literal"><span class="pre">text()</span></tt></a> construct. That is, the following usage:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">result</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span>
<span class="s">"SELECT * FROM user WHERE id=:param"</span><span class="p">,</span>
<span class="p">{</span><span class="s">"param"</span><span class="p">:</span><span class="mi">5</span><span class="p">}</span>
<span class="p">)</span></pre></div>
</div>
<p>is equivalent to:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">text</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span>
<span class="n">text</span><span class="p">(</span><span class="s">"SELECT * FROM user WHERE id=:param"</span><span class="p">),</span>
<span class="p">{</span><span class="s">"param"</span><span class="p">:</span><span class="mi">5</span><span class="p">}</span>
<span class="p">)</span></pre></div>
</div>
<p>The second positional argument to <a class="reference internal" href="#sqlalchemy.orm.session.Session.execute" title="sqlalchemy.orm.session.Session.execute"><tt class="xref py py-meth docutils literal"><span class="pre">Session.execute()</span></tt></a> is an
optional parameter set. Similar to that of
<a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection.execute" title="sqlalchemy.engine.Connection.execute"><tt class="xref py py-meth docutils literal"><span class="pre">Connection.execute()</span></tt></a>, whether this is passed as a single
dictionary, or a list of dictionaries, determines whether the DBAPI
cursor’s <tt class="docutils literal"><span class="pre">execute()</span></tt> or <tt class="docutils literal"><span class="pre">executemany()</span></tt> is used to execute the
statement. An INSERT construct may be invoked for a single row:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">result</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span>
<span class="n">users</span><span class="o">.</span><span class="n">insert</span><span class="p">(),</span> <span class="p">{</span><span class="s">"id"</span><span class="p">:</span> <span class="mi">7</span><span class="p">,</span> <span class="s">"name"</span><span class="p">:</span> <span class="s">"somename"</span><span class="p">})</span></pre></div>
</div>
<p>or for multiple rows:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">result</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">users</span><span class="o">.</span><span class="n">insert</span><span class="p">(),</span> <span class="p">[</span>
<span class="p">{</span><span class="s">"id"</span><span class="p">:</span> <span class="mi">7</span><span class="p">,</span> <span class="s">"name"</span><span class="p">:</span> <span class="s">"somename7"</span><span class="p">},</span>
<span class="p">{</span><span class="s">"id"</span><span class="p">:</span> <span class="mi">8</span><span class="p">,</span> <span class="s">"name"</span><span class="p">:</span> <span class="s">"somename8"</span><span class="p">},</span>
<span class="p">{</span><span class="s">"id"</span><span class="p">:</span> <span class="mi">9</span><span class="p">,</span> <span class="s">"name"</span><span class="p">:</span> <span class="s">"somename9"</span><span class="p">}</span>
<span class="p">])</span></pre></div>
</div>
<p>The statement is executed within the current transactional context of
this <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>. The <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> which is used
to execute the statement can also be acquired directly by
calling the <a class="reference internal" href="#sqlalchemy.orm.session.Session.connection" title="sqlalchemy.orm.session.Session.connection"><tt class="xref py py-meth docutils literal"><span class="pre">Session.connection()</span></tt></a> method. Both methods use
a rule-based resolution scheme in order to determine the
<a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a>, which in the average case is derived directly
from the “bind” of the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> itself, and in other cases
can be based on the <a class="reference internal" href="mapper_config.html#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a>
and <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> objects passed to the method; see the
documentation for <a class="reference internal" href="#sqlalchemy.orm.session.Session.get_bind" title="sqlalchemy.orm.session.Session.get_bind"><tt class="xref py py-meth docutils literal"><span class="pre">Session.get_bind()</span></tt></a> for a full description of
this scheme.</p>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.Session.execute" title="sqlalchemy.orm.session.Session.execute"><tt class="xref py py-meth docutils literal"><span class="pre">Session.execute()</span></tt></a> method does <em>not</em> invoke autoflush.</p>
<p>The <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.ResultProxy" title="sqlalchemy.engine.ResultProxy"><tt class="xref py py-class docutils literal"><span class="pre">ResultProxy</span></tt></a> returned by the <a class="reference internal" href="#sqlalchemy.orm.session.Session.execute" title="sqlalchemy.orm.session.Session.execute"><tt class="xref py py-meth docutils literal"><span class="pre">Session.execute()</span></tt></a>
method is returned with the “close_with_result” flag set to true;
the significance of this flag is that if this <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is
autocommitting and does not have a transaction-dedicated
<a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> available, a temporary <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> is
established for the statement execution, which is closed (meaning,
returned to the connection pool) when the <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.ResultProxy" title="sqlalchemy.engine.ResultProxy"><tt class="xref py py-class docutils literal"><span class="pre">ResultProxy</span></tt></a> has
consumed all available data. This applies <em>only</em> when the
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is configured with autocommit=True and no
transaction has been started.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><span class="target" id="sqlalchemy.orm.session.Session.execute.params.clause"></span><strong>clause</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.execute.params.clause">¶</a> – An executable statement (i.e. an <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.Executable" title="sqlalchemy.sql.expression.Executable"><tt class="xref py py-class docutils literal"><span class="pre">Executable</span></tt></a> expression
such as <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.select" title="sqlalchemy.sql.expression.select"><tt class="xref py py-func docutils literal"><span class="pre">expression.select()</span></tt></a>) or string SQL statement
to be executed.</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.execute.params.params"></span><strong>params</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.execute.params.params">¶</a> – Optional dictionary, or list of dictionaries, containing
bound parameter values. If a single dictionary, single-row
execution occurs; if a list of dictionaries, an
“executemany” will be invoked. The keys in each dictionary
must correspond to parameter names present in the statement.</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.execute.params.mapper"></span><strong>mapper</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.execute.params.mapper">¶</a> – Optional <a class="reference internal" href="mapper_config.html#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a> or mapped class, used to identify
the appropriate bind. This argument takes precedence over
<tt class="docutils literal"><span class="pre">clause</span></tt> when locating a bind. See <a class="reference internal" href="#sqlalchemy.orm.session.Session.get_bind" title="sqlalchemy.orm.session.Session.get_bind"><tt class="xref py py-meth docutils literal"><span class="pre">Session.get_bind()</span></tt></a>
for more details.</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.execute.params.bind"></span><strong>bind</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.execute.params.bind">¶</a> – Optional <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> to be used as the bind. If
this engine is already involved in an ongoing transaction,
that connection will be used. This argument takes
precedence over <tt class="docutils literal"><span class="pre">mapper</span></tt> and <tt class="docutils literal"><span class="pre">clause</span></tt> when locating
a bind.</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.execute.params.**kw"></span><strong>**kw</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.execute.params.**kw">¶</a> – Additional keyword arguments are sent to <a class="reference internal" href="#sqlalchemy.orm.session.Session.get_bind" title="sqlalchemy.orm.session.Session.get_bind"><tt class="xref py py-meth docutils literal"><span class="pre">Session.get_bind()</span></tt></a>
to allow extensibility of “bind” schemes.</li>
</ul>
</td>
</tr>
</tbody>
</table>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p><a class="reference internal" href="../core/tutorial.html"><em>SQL Expression Language Tutorial</em></a> - Tutorial on using Core SQL
constructs.</p>
<p><a class="reference internal" href="../core/connections.html"><em>Working with Engines and Connections</em></a> - Further information on direct
statement execution.</p>
<p class="last"><a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection.execute" title="sqlalchemy.engine.Connection.execute"><tt class="xref py py-meth docutils literal"><span class="pre">Connection.execute()</span></tt></a> - core level statement execution
method, which is <a class="reference internal" href="#sqlalchemy.orm.session.Session.execute" title="sqlalchemy.orm.session.Session.execute"><tt class="xref py py-meth docutils literal"><span class="pre">Session.execute()</span></tt></a> ultimately uses
in order to execute the statement.</p>
</div>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.expire">
<tt class="descname">expire</tt><big>(</big><em>instance</em>, <em>attribute_names=None</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.expire" title="Permalink to this definition">¶</a></dt>
<dd><p>Expire the attributes on an instance.</p>
<p>Marks the attributes of an instance as out of date. When an expired
attribute is next accessed, a query will be issued to the
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> object’s current transactional context in order to
load all expired attributes for the given instance. Note that
a highly isolated transaction will return the same values as were
previously read in that same transaction, regardless of changes
in database state outside of that transaction.</p>
<p>To expire all objects in the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> simultaneously,
use <a class="reference internal" href="#sqlalchemy.orm.session.Session.expire_all" title="sqlalchemy.orm.session.Session.expire_all"><tt class="xref py py-meth docutils literal"><span class="pre">Session.expire_all()</span></tt></a>.</p>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> object’s default behavior is to
expire all state whenever the <a class="reference internal" href="#sqlalchemy.orm.session.Session.rollback" title="sqlalchemy.orm.session.Session.rollback"><tt class="xref py py-meth docutils literal"><span class="pre">Session.rollback()</span></tt></a>
or <a class="reference internal" href="#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-meth docutils literal"><span class="pre">Session.commit()</span></tt></a> methods are called, so that new
state can be loaded for the new transaction. For this reason,
calling <a class="reference internal" href="#sqlalchemy.orm.session.Session.expire" title="sqlalchemy.orm.session.Session.expire"><tt class="xref py py-meth docutils literal"><span class="pre">Session.expire()</span></tt></a> only makes sense for the specific
case that a non-ORM SQL statement was emitted in the current
transaction.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><span class="target" id="sqlalchemy.orm.session.Session.expire.params.instance"></span><strong>instance</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.expire.params.instance">¶</a> – The instance to be refreshed.</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.expire.params.attribute_names"></span><strong>attribute_names</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.expire.params.attribute_names">¶</a> – optional list of string attribute names
indicating a subset of attributes to be expired.</li>
</ul>
</td>
</tr>
</tbody>
</table>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p><a class="reference internal" href="#session-expire"><em>Refreshing / Expiring</em></a> - introductory material</p>
<p><a class="reference internal" href="#sqlalchemy.orm.session.Session.expire" title="sqlalchemy.orm.session.Session.expire"><tt class="xref py py-meth docutils literal"><span class="pre">Session.expire()</span></tt></a></p>
<p class="last"><a class="reference internal" href="#sqlalchemy.orm.session.Session.refresh" title="sqlalchemy.orm.session.Session.refresh"><tt class="xref py py-meth docutils literal"><span class="pre">Session.refresh()</span></tt></a></p>
</div>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.expire_all">
<tt class="descname">expire_all</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.expire_all" title="Permalink to this definition">¶</a></dt>
<dd><p>Expires all persistent instances within this Session.</p>
<p>When any attributes on a persistent instance is next accessed,
a query will be issued using the
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> object’s current transactional context in order to
load all expired attributes for the given instance. Note that
a highly isolated transaction will return the same values as were
previously read in that same transaction, regardless of changes
in database state outside of that transaction.</p>
<p>To expire individual objects and individual attributes
on those objects, use <a class="reference internal" href="#sqlalchemy.orm.session.Session.expire" title="sqlalchemy.orm.session.Session.expire"><tt class="xref py py-meth docutils literal"><span class="pre">Session.expire()</span></tt></a>.</p>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> object’s default behavior is to
expire all state whenever the <a class="reference internal" href="#sqlalchemy.orm.session.Session.rollback" title="sqlalchemy.orm.session.Session.rollback"><tt class="xref py py-meth docutils literal"><span class="pre">Session.rollback()</span></tt></a>
or <a class="reference internal" href="#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-meth docutils literal"><span class="pre">Session.commit()</span></tt></a> methods are called, so that new
state can be loaded for the new transaction. For this reason,
calling <a class="reference internal" href="#sqlalchemy.orm.session.Session.expire_all" title="sqlalchemy.orm.session.Session.expire_all"><tt class="xref py py-meth docutils literal"><span class="pre">Session.expire_all()</span></tt></a> should not be needed when
autocommit is <tt class="docutils literal"><span class="pre">False</span></tt>, assuming the transaction is isolated.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p><a class="reference internal" href="#session-expire"><em>Refreshing / Expiring</em></a> - introductory material</p>
<p><a class="reference internal" href="#sqlalchemy.orm.session.Session.expire" title="sqlalchemy.orm.session.Session.expire"><tt class="xref py py-meth docutils literal"><span class="pre">Session.expire()</span></tt></a></p>
<p class="last"><a class="reference internal" href="#sqlalchemy.orm.session.Session.refresh" title="sqlalchemy.orm.session.Session.refresh"><tt class="xref py py-meth docutils literal"><span class="pre">Session.refresh()</span></tt></a></p>
</div>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.expunge">
<tt class="descname">expunge</tt><big>(</big><em>instance</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.expunge" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove the <cite>instance</cite> from this <tt class="docutils literal"><span class="pre">Session</span></tt>.</p>
<p>This will free all internal references to the instance. Cascading
will be applied according to the <em>expunge</em> cascade rule.</p>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.expunge_all">
<tt class="descname">expunge_all</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.expunge_all" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove all object instances from this <tt class="docutils literal"><span class="pre">Session</span></tt>.</p>
<p>This is equivalent to calling <tt class="docutils literal"><span class="pre">expunge(obj)</span></tt> on all objects in this
<tt class="docutils literal"><span class="pre">Session</span></tt>.</p>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.flush">
<tt class="descname">flush</tt><big>(</big><em>objects=None</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.flush" title="Permalink to this definition">¶</a></dt>
<dd><p>Flush all the object changes to the database.</p>
<p>Writes out all pending object creations, deletions and modifications
to the database as INSERTs, DELETEs, UPDATEs, etc. Operations are
automatically ordered by the Session’s unit of work dependency
solver.</p>
<p>Database operations will be issued in the current transactional
context and do not affect the state of the transaction, unless an
error occurs, in which case the entire transaction is rolled back.
You may flush() as often as you like within a transaction to move
changes from Python to the database’s transaction buffer.</p>
<p>For <tt class="docutils literal"><span class="pre">autocommit</span></tt> Sessions with no active manual transaction, flush()
will create a transaction on the fly that surrounds the entire set of
operations int the flush.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><span class="target" id="sqlalchemy.orm.session.Session.flush.params.objects"></span><strong>objects</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.flush.params.objects">¶</a> – <p>Optional; restricts the flush operation to operate
only on elements that are in the given collection.</p>
<p>This feature is for an extremely narrow set of use cases where
particular objects may need to be operated upon before the
full flush() occurs. It is not intended for general use.</p>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.get_bind">
<tt class="descname">get_bind</tt><big>(</big><em>mapper=None</em>, <em>clause=None</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.get_bind" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a “bind” to which this <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is bound.</p>
<p>The “bind” is usually an instance of <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a>,
except in the case where the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> has been
explicitly bound directly to a <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a>.</p>
<p>For a multiply-bound or unbound <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>, the
<tt class="docutils literal"><span class="pre">mapper</span></tt> or <tt class="docutils literal"><span class="pre">clause</span></tt> arguments are used to determine the
appropriate bind to return.</p>
<p>Note that the “mapper” argument is usually present
when <a class="reference internal" href="#sqlalchemy.orm.session.Session.get_bind" title="sqlalchemy.orm.session.Session.get_bind"><tt class="xref py py-meth docutils literal"><span class="pre">Session.get_bind()</span></tt></a> is called via an ORM
operation such as a <a class="reference internal" href="#sqlalchemy.orm.session.Session.query" title="sqlalchemy.orm.session.Session.query"><tt class="xref py py-meth docutils literal"><span class="pre">Session.query()</span></tt></a>, each
individual INSERT/UPDATE/DELETE operation within a
<a class="reference internal" href="#sqlalchemy.orm.session.Session.flush" title="sqlalchemy.orm.session.Session.flush"><tt class="xref py py-meth docutils literal"><span class="pre">Session.flush()</span></tt></a>, call, etc.</p>
<p>The order of resolution is:</p>
<ol class="arabic simple">
<li>if mapper given and session.binds is present,
locate a bind based on mapper.</li>
<li>if clause given and session.binds is present,
locate a bind based on <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> objects
found in the given clause present in session.binds.</li>
<li>if session.bind is present, return that.</li>
<li>if clause given, attempt to return a bind
linked to the <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.MetaData" title="sqlalchemy.schema.MetaData"><tt class="xref py py-class docutils literal"><span class="pre">MetaData</span></tt></a> ultimately
associated with the clause.</li>
<li>if mapper given, attempt to return a bind
linked to the <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.MetaData" title="sqlalchemy.schema.MetaData"><tt class="xref py py-class docutils literal"><span class="pre">MetaData</span></tt></a> ultimately
associated with the <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> or other
selectable to which the mapper is mapped.</li>
<li>No bind can be found, <a class="reference internal" href="../core/exceptions.html#sqlalchemy.exc.UnboundExecutionError" title="sqlalchemy.exc.UnboundExecutionError"><tt class="xref py py-exc docutils literal"><span class="pre">UnboundExecutionError</span></tt></a>
is raised.</li>
</ol>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><span class="target" id="sqlalchemy.orm.session.Session.get_bind.params.mapper"></span><strong>mapper</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.get_bind.params.mapper">¶</a> – Optional <a class="reference internal" href="mapper_config.html#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a> mapped class or instance of
<a class="reference internal" href="mapper_config.html#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a>. The bind can be derived from a <a class="reference internal" href="mapper_config.html#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a>
first by consulting the “binds” map associated with this
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>, and secondly by consulting the <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.MetaData" title="sqlalchemy.schema.MetaData"><tt class="xref py py-class docutils literal"><span class="pre">MetaData</span></tt></a>
associated with the <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> to which the <a class="reference internal" href="mapper_config.html#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a>
is mapped for a bind.</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.get_bind.params.clause"></span><strong>clause</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.get_bind.params.clause">¶</a> – A <a class="reference internal" href="../core/sqlelement.html#sqlalchemy.sql.expression.ClauseElement" title="sqlalchemy.sql.expression.ClauseElement"><tt class="xref py py-class docutils literal"><span class="pre">ClauseElement</span></tt></a> (i.e. <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.select" title="sqlalchemy.sql.expression.select"><tt class="xref py py-func docutils literal"><span class="pre">select()</span></tt></a>,
<a class="reference internal" href="../core/sqlelement.html#sqlalchemy.sql.expression.text" title="sqlalchemy.sql.expression.text"><tt class="xref py py-func docutils literal"><span class="pre">text()</span></tt></a>,
etc.). If the <tt class="docutils literal"><span class="pre">mapper</span></tt> argument is not present or could not
produce a bind, the given expression construct will be searched
for a bound element, typically a <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> associated with
bound <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.MetaData" title="sqlalchemy.schema.MetaData"><tt class="xref py py-class docutils literal"><span class="pre">MetaData</span></tt></a>.</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="classmethod">
<dt id="sqlalchemy.orm.session.Session.identity_key">
<em class="property">classmethod </em><tt class="descname">identity_key</tt><big>(</big><em>*args</em>, <em>**kwargs</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.identity_key" title="Permalink to this definition">¶</a></dt>
<dd><div class="inherited-member container">
<em>inherited from the</em> <tt class="xref py py-meth docutils literal"><span class="pre">identity_key()</span></tt> <em>method of</em> <tt class="xref py py-class docutils literal"><span class="pre">_SessionClassMethods</span></tt></div>
<p>Return an identity key.</p>
<p>This is an alias of <a class="reference internal" href="mapper_config.html#sqlalchemy.orm.util.identity_key" title="sqlalchemy.orm.util.identity_key"><tt class="xref py py-func docutils literal"><span class="pre">util.identity_key()</span></tt></a>.</p>
</dd></dl>
<dl class="attribute">
<dt id="sqlalchemy.orm.session.Session.identity_map">
<tt class="descname">identity_map</tt><em class="property"> = None</em><a class="headerlink" href="#sqlalchemy.orm.session.Session.identity_map" title="Permalink to this definition">¶</a></dt>
<dd><p>A mapping of object identities to objects themselves.</p>
<p>Iterating through <tt class="docutils literal"><span class="pre">Session.identity_map.values()</span></tt> provides
access to the full set of persistent objects (i.e., those
that have row identity) currently in the session.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="mapper_config.html#sqlalchemy.orm.util.identity_key" title="sqlalchemy.orm.util.identity_key"><tt class="xref py py-func docutils literal"><span class="pre">identity_key()</span></tt></a> - helper function to produce the keys used
in this dictionary.</p>
</div>
</dd></dl>
<dl class="attribute">
<dt id="sqlalchemy.orm.session.Session.info">
<tt class="descname">info</tt><a class="headerlink" href="#sqlalchemy.orm.session.Session.info" title="Permalink to this definition">¶</a></dt>
<dd><p>A user-modifiable dictionary.</p>
<p>The initial value of this dictioanry can be populated using the
<tt class="docutils literal"><span class="pre">info</span></tt> argument to the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> constructor or
<a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-class docutils literal"><span class="pre">sessionmaker</span></tt></a> constructor or factory methods. The dictionary
here is always local to this <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> and can be modified
independently of all other <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> objects.</p>
<div class="versionadded">
<p><span>New in version 0.9.0.</span></p>
</div>
</dd></dl>
<dl class="attribute">
<dt id="sqlalchemy.orm.session.Session.is_active">
<tt class="descname">is_active</tt><a class="headerlink" href="#sqlalchemy.orm.session.Session.is_active" title="Permalink to this definition">¶</a></dt>
<dd><p>True if this <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is in “transaction mode” and
is not in “partial rollback” state.</p>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> in its default mode of <tt class="docutils literal"><span class="pre">autocommit=False</span></tt>
is essentially always in “transaction mode”, in that a
<a class="reference internal" href="#sqlalchemy.orm.session.SessionTransaction" title="sqlalchemy.orm.session.SessionTransaction"><tt class="xref py py-class docutils literal"><span class="pre">SessionTransaction</span></tt></a> is associated with it as soon as
it is instantiated. This <a class="reference internal" href="#sqlalchemy.orm.session.SessionTransaction" title="sqlalchemy.orm.session.SessionTransaction"><tt class="xref py py-class docutils literal"><span class="pre">SessionTransaction</span></tt></a> is immediately
replaced with a new one as soon as it is ended, due to a rollback,
commit, or close operation.</p>
<p>“Transaction mode” does <em>not</em> indicate whether
or not actual database connection resources are in use; the
<a class="reference internal" href="#sqlalchemy.orm.session.SessionTransaction" title="sqlalchemy.orm.session.SessionTransaction"><tt class="xref py py-class docutils literal"><span class="pre">SessionTransaction</span></tt></a> object coordinates among zero or more
actual database transactions, and starts out with none, accumulating
individual DBAPI connections as different data sources are used
within its scope. The best way to track when a particular
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> has actually begun to use DBAPI resources is to
implement a listener using the <a class="reference internal" href="events.html#sqlalchemy.orm.events.SessionEvents.after_begin" title="sqlalchemy.orm.events.SessionEvents.after_begin"><tt class="xref py py-meth docutils literal"><span class="pre">SessionEvents.after_begin()</span></tt></a>
method, which will deliver both the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> as well as the
target <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> to a user-defined event listener.</p>
<p>The “partial rollback” state refers to when an “inner” transaction,
typically used during a flush, encounters an error and emits a
rollback of the DBAPI connection. At this point, the
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is in “partial rollback” and awaits for the user to
call <a class="reference internal" href="#sqlalchemy.orm.session.Session.rollback" title="sqlalchemy.orm.session.Session.rollback"><tt class="xref py py-meth docutils literal"><span class="pre">Session.rollback()</span></tt></a>, in order to close out the
transaction stack. It is in this “partial rollback” period that the
<a class="reference internal" href="#sqlalchemy.orm.session.Session.is_active" title="sqlalchemy.orm.session.Session.is_active"><tt class="xref py py-attr docutils literal"><span class="pre">is_active</span></tt></a> flag returns False. After the call to
<a class="reference internal" href="#sqlalchemy.orm.session.Session.rollback" title="sqlalchemy.orm.session.Session.rollback"><tt class="xref py py-meth docutils literal"><span class="pre">Session.rollback()</span></tt></a>, the <a class="reference internal" href="#sqlalchemy.orm.session.SessionTransaction" title="sqlalchemy.orm.session.SessionTransaction"><tt class="xref py py-class docutils literal"><span class="pre">SessionTransaction</span></tt></a> is
replaced with a new one and <a class="reference internal" href="#sqlalchemy.orm.session.Session.is_active" title="sqlalchemy.orm.session.Session.is_active"><tt class="xref py py-attr docutils literal"><span class="pre">is_active</span></tt></a> returns <tt class="docutils literal"><span class="pre">True</span></tt> again.</p>
<p>When a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is used in <tt class="docutils literal"><span class="pre">autocommit=True</span></tt> mode, the
<a class="reference internal" href="#sqlalchemy.orm.session.SessionTransaction" title="sqlalchemy.orm.session.SessionTransaction"><tt class="xref py py-class docutils literal"><span class="pre">SessionTransaction</span></tt></a> is only instantiated within the scope
of a flush call, or when <a class="reference internal" href="#sqlalchemy.orm.session.Session.begin" title="sqlalchemy.orm.session.Session.begin"><tt class="xref py py-meth docutils literal"><span class="pre">Session.begin()</span></tt></a> is called. So
<a class="reference internal" href="#sqlalchemy.orm.session.Session.is_active" title="sqlalchemy.orm.session.Session.is_active"><tt class="xref py py-attr docutils literal"><span class="pre">is_active</span></tt></a> will always be <tt class="docutils literal"><span class="pre">False</span></tt> outside of a flush or
<a class="reference internal" href="#sqlalchemy.orm.session.Session.begin" title="sqlalchemy.orm.session.Session.begin"><tt class="xref py py-meth docutils literal"><span class="pre">Session.begin()</span></tt></a> block in this mode, and will be <tt class="docutils literal"><span class="pre">True</span></tt>
within the <a class="reference internal" href="#sqlalchemy.orm.session.Session.begin" title="sqlalchemy.orm.session.Session.begin"><tt class="xref py py-meth docutils literal"><span class="pre">Session.begin()</span></tt></a> block as long as it doesn’t enter
“partial rollback” state.</p>
<p>From all the above, it follows that the only purpose to this flag is
for application frameworks that wish to detect is a “rollback” is
necessary within a generic error handling routine, for
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> objects that would otherwise be in
“partial rollback” mode. In a typical integration case, this is also
not necessary as it is standard practice to emit
<a class="reference internal" href="#sqlalchemy.orm.session.Session.rollback" title="sqlalchemy.orm.session.Session.rollback"><tt class="xref py py-meth docutils literal"><span class="pre">Session.rollback()</span></tt></a> unconditionally within the outermost
exception catch.</p>
<p>To track the transactional state of a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> fully,
use event listeners, primarily the <a class="reference internal" href="events.html#sqlalchemy.orm.events.SessionEvents.after_begin" title="sqlalchemy.orm.events.SessionEvents.after_begin"><tt class="xref py py-meth docutils literal"><span class="pre">SessionEvents.after_begin()</span></tt></a>,
<a class="reference internal" href="events.html#sqlalchemy.orm.events.SessionEvents.after_commit" title="sqlalchemy.orm.events.SessionEvents.after_commit"><tt class="xref py py-meth docutils literal"><span class="pre">SessionEvents.after_commit()</span></tt></a>,
<a class="reference internal" href="events.html#sqlalchemy.orm.events.SessionEvents.after_rollback" title="sqlalchemy.orm.events.SessionEvents.after_rollback"><tt class="xref py py-meth docutils literal"><span class="pre">SessionEvents.after_rollback()</span></tt></a> and related events.</p>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.is_modified">
<tt class="descname">is_modified</tt><big>(</big><em>instance</em>, <em>include_collections=True</em>, <em>passive=True</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.is_modified" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <tt class="docutils literal"><span class="pre">True</span></tt> if the given instance has locally
modified attributes.</p>
<p>This method retrieves the history for each instrumented
attribute on the instance and performs a comparison of the current
value to its previously committed value, if any.</p>
<p>It is in effect a more expensive and accurate
version of checking for the given instance in the
<a class="reference internal" href="#sqlalchemy.orm.session.Session.dirty" title="sqlalchemy.orm.session.Session.dirty"><tt class="xref py py-attr docutils literal"><span class="pre">Session.dirty</span></tt></a> collection; a full test for
each attribute’s net “dirty” status is performed.</p>
<p>E.g.:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">return</span> <span class="n">session</span><span class="o">.</span><span class="n">is_modified</span><span class="p">(</span><span class="n">someobject</span><span class="p">)</span></pre></div>
</div>
<div class="versionchanged">
<p><span>Changed in version 0.8: </span>When using SQLAlchemy 0.7 and earlier, the <tt class="docutils literal"><span class="pre">passive</span></tt>
flag should <strong>always</strong> be explicitly set to <tt class="docutils literal"><span class="pre">True</span></tt>,
else SQL loads/autoflushes may proceed which can affect
the modified state itself:
<tt class="docutils literal"><span class="pre">session.is_modified(someobject,</span> <span class="pre">passive=True)</span></tt>.
In 0.8 and above, the behavior is corrected and
this flag is ignored.</p>
</div>
<p>A few caveats to this method apply:</p>
<ul>
<li><p class="first">Instances present in the <a class="reference internal" href="#sqlalchemy.orm.session.Session.dirty" title="sqlalchemy.orm.session.Session.dirty"><tt class="xref py py-attr docutils literal"><span class="pre">Session.dirty</span></tt></a> collection may
report <tt class="docutils literal"><span class="pre">False</span></tt> when tested with this method. This is because
the object may have received change events via attribute mutation,
thus placing it in <a class="reference internal" href="#sqlalchemy.orm.session.Session.dirty" title="sqlalchemy.orm.session.Session.dirty"><tt class="xref py py-attr docutils literal"><span class="pre">Session.dirty</span></tt></a>, but ultimately the state
is the same as that loaded from the database, resulting in no net
change here.</p>
</li>
<li><p class="first">Scalar attributes may not have recorded the previously set
value when a new value was applied, if the attribute was not loaded,
or was expired, at the time the new value was received - in these
cases, the attribute is assumed to have a change, even if there is
ultimately no net change against its database value. SQLAlchemy in
most cases does not need the “old” value when a set event occurs, so
it skips the expense of a SQL call if the old value isn’t present,
based on the assumption that an UPDATE of the scalar value is
usually needed, and in those few cases where it isn’t, is less
expensive on average than issuing a defensive SELECT.</p>
<p>The “old” value is fetched unconditionally upon set only if the
attribute container has the <tt class="docutils literal"><span class="pre">active_history</span></tt> flag set to <tt class="docutils literal"><span class="pre">True</span></tt>.
This flag is set typically for primary key attributes and scalar
object references that are not a simple many-to-one. To set this
flag for any arbitrary mapped column, use the <tt class="docutils literal"><span class="pre">active_history</span></tt>
argument with <a class="reference internal" href="mapper_config.html#sqlalchemy.orm.column_property" title="sqlalchemy.orm.column_property"><tt class="xref py py-func docutils literal"><span class="pre">column_property()</span></tt></a>.</p>
</li>
</ul>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><span class="target" id="sqlalchemy.orm.session.Session.is_modified.params.instance"></span><strong>instance</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.is_modified.params.instance">¶</a> – mapped instance to be tested for pending changes.</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.is_modified.params.include_collections"></span><strong>include_collections</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.is_modified.params.include_collections">¶</a> – Indicates if multivalued collections
should be included in the operation. Setting this to <tt class="docutils literal"><span class="pre">False</span></tt> is a
way to detect only local-column based properties (i.e. scalar columns
or many-to-one foreign keys) that would result in an UPDATE for this
instance upon flush.</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.is_modified.params.passive"></span><strong>passive</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.is_modified.params.passive">¶</a> – <div class="versionchanged">
<p><span>Changed in version 0.8: </span>Ignored for backwards compatibility.
When using SQLAlchemy 0.7 and earlier, this flag should always
be set to <tt class="docutils literal"><span class="pre">True</span></tt>.</p>
</div>
</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.merge">
<tt class="descname">merge</tt><big>(</big><em>instance</em>, <em>load=True</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.merge" title="Permalink to this definition">¶</a></dt>
<dd><p>Copy the state of a given instance into a corresponding instance
within this <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>.</p>
<p><a class="reference internal" href="#sqlalchemy.orm.session.Session.merge" title="sqlalchemy.orm.session.Session.merge"><tt class="xref py py-meth docutils literal"><span class="pre">Session.merge()</span></tt></a> examines the primary key attributes of the
source instance, and attempts to reconcile it with an instance of the
same primary key in the session. If not found locally, it attempts
to load the object from the database based on primary key, and if
none can be located, creates a new instance. The state of each
attribute on the source instance is then copied to the target
instance. The resulting target instance is then returned by the
method; the original source instance is left unmodified, and
un-associated with the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> if not already.</p>
<p>This operation cascades to associated instances if the association is
mapped with <tt class="docutils literal"><span class="pre">cascade="merge"</span></tt>.</p>
<p>See <a class="reference internal" href="#unitofwork-merging"><em>Merging</em></a> for a detailed discussion of merging.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><span class="target" id="sqlalchemy.orm.session.Session.merge.params.instance"></span><strong>instance</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.merge.params.instance">¶</a> – Instance to be merged.</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.merge.params.load"></span><strong>load</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.merge.params.load">¶</a> – <p>Boolean, when False, <a class="reference internal" href="#sqlalchemy.orm.session.Session.merge" title="sqlalchemy.orm.session.Session.merge"><tt class="xref py py-meth docutils literal"><span class="pre">merge()</span></tt></a> switches into
a “high performance” mode which causes it to forego emitting history
events as well as all database access. This flag is used for
cases such as transferring graphs of objects into a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
from a second level cache, or to transfer just-loaded objects
into the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> owned by a worker thread or process
without re-querying the database.</p>
<p>The <tt class="docutils literal"><span class="pre">load=False</span></tt> use case adds the caveat that the given
object has to be in a “clean” state, that is, has no pending changes
to be flushed - even if the incoming object is detached from any
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>. This is so that when
the merge operation populates local attributes and
cascades to related objects and
collections, the values can be “stamped” onto the
target object as is, without generating any history or attribute
events, and without the need to reconcile the incoming data with
any existing related objects or collections that might not
be loaded. The resulting objects from <tt class="docutils literal"><span class="pre">load=False</span></tt> are always
produced as “clean”, so it is only appropriate that the given objects
should be “clean” as well, else this suggests a mis-use of the
method.</p>
</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="attribute">
<dt id="sqlalchemy.orm.session.Session.new">
<tt class="descname">new</tt><a class="headerlink" href="#sqlalchemy.orm.session.Session.new" title="Permalink to this definition">¶</a></dt>
<dd><p>The set of all instances marked as ‘new’ within this <tt class="docutils literal"><span class="pre">Session</span></tt>.</p>
</dd></dl>
<dl class="attribute">
<dt id="sqlalchemy.orm.session.Session.no_autoflush">
<tt class="descname">no_autoflush</tt><a class="headerlink" href="#sqlalchemy.orm.session.Session.no_autoflush" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a context manager that disables autoflush.</p>
<p>e.g.:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">with</span> <span class="n">session</span><span class="o">.</span><span class="n">no_autoflush</span><span class="p">:</span>
<span class="n">some_object</span> <span class="o">=</span> <span class="n">SomeClass</span><span class="p">()</span>
<span class="n">session</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">some_object</span><span class="p">)</span>
<span class="c"># won't autoflush</span>
<span class="n">some_object</span><span class="o">.</span><span class="n">related_thing</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">SomeRelated</span><span class="p">)</span><span class="o">.</span><span class="n">first</span><span class="p">()</span></pre></div>
</div>
<p>Operations that proceed within the <tt class="docutils literal"><span class="pre">with:</span></tt> block
will not be subject to flushes occurring upon query
access. This is useful when initializing a series
of objects which involve existing database queries,
where the uncompleted object should not yet be flushed.</p>
<div class="versionadded">
<p><span>New in version 0.7.6.</span></p>
</div>
</dd></dl>
<dl class="classmethod">
<dt id="sqlalchemy.orm.session.Session.object_session">
<em class="property">classmethod </em><tt class="descname">object_session</tt><big>(</big><em>instance</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.object_session" title="Permalink to this definition">¶</a></dt>
<dd><div class="inherited-member container">
<em>inherited from the</em> <tt class="xref py py-meth docutils literal"><span class="pre">object_session()</span></tt> <em>method of</em> <tt class="xref py py-class docutils literal"><span class="pre">_SessionClassMethods</span></tt></div>
<p>Return the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> to which an object belongs.</p>
<p>This is an alias of <a class="reference internal" href="#sqlalchemy.orm.session.object_session" title="sqlalchemy.orm.session.object_session"><tt class="xref py py-func docutils literal"><span class="pre">object_session()</span></tt></a>.</p>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.prepare">
<tt class="descname">prepare</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.prepare" title="Permalink to this definition">¶</a></dt>
<dd><p>Prepare the current transaction in progress for two phase commit.</p>
<p>If no transaction is in progress, this method raises an
<a class="reference internal" href="../core/exceptions.html#sqlalchemy.exc.InvalidRequestError" title="sqlalchemy.exc.InvalidRequestError"><tt class="xref py py-exc docutils literal"><span class="pre">InvalidRequestError</span></tt></a>.</p>
<p>Only root transactions of two phase sessions can be prepared. If the
current transaction is not such, an
<a class="reference internal" href="../core/exceptions.html#sqlalchemy.exc.InvalidRequestError" title="sqlalchemy.exc.InvalidRequestError"><tt class="xref py py-exc docutils literal"><span class="pre">InvalidRequestError</span></tt></a> is raised.</p>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.prune">
<tt class="descname">prune</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.prune" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove unreferenced instances cached in the identity map.</p>
<div class="deprecated">
<p><span>Deprecated since version 0.7: </span>The non-weak-referencing identity map feature is no longer needed.</p>
</div>
<p>Note that this method is only meaningful if “weak_identity_map” is set
to False. The default weak identity map is self-pruning.</p>
<p>Removes any object in this Session’s identity map that is not
referenced in user code, modified, new or scheduled for deletion.
Returns the number of objects pruned.</p>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.query">
<tt class="descname">query</tt><big>(</big><em>*entities</em>, <em>**kwargs</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.query" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new <a class="reference internal" href="query.html#sqlalchemy.orm.query.Query" title="sqlalchemy.orm.query.Query"><tt class="xref py py-class docutils literal"><span class="pre">Query</span></tt></a> object corresponding to this
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>.</p>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.refresh">
<tt class="descname">refresh</tt><big>(</big><em>instance</em>, <em>attribute_names=None</em>, <em>lockmode=None</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.refresh" title="Permalink to this definition">¶</a></dt>
<dd><p>Expire and refresh the attributes on the given instance.</p>
<p>A query will be issued to the database and all attributes will be
refreshed with their current database value.</p>
<p>Lazy-loaded relational attributes will remain lazily loaded, so that
the instance-wide refresh operation will be followed immediately by
the lazy load of that attribute.</p>
<p>Eagerly-loaded relational attributes will eagerly load within the
single refresh operation.</p>
<p>Note that a highly isolated transaction will return the same values as
were previously read in that same transaction, regardless of changes
in database state outside of that transaction - usage of
<a class="reference internal" href="#sqlalchemy.orm.session.Session.refresh" title="sqlalchemy.orm.session.Session.refresh"><tt class="xref py py-meth docutils literal"><span class="pre">refresh()</span></tt></a> usually only makes sense if non-ORM SQL
statement were emitted in the ongoing transaction, or if autocommit
mode is turned on.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><span class="target" id="sqlalchemy.orm.session.Session.refresh.params.attribute_names"></span><strong>attribute_names</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.refresh.params.attribute_names">¶</a> – optional. An iterable collection of
string attribute names indicating a subset of attributes to
be refreshed.</li>
<li><span class="target" id="sqlalchemy.orm.session.Session.refresh.params.lockmode"></span><strong>lockmode</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.session.Session.refresh.params.lockmode">¶</a> – Passed to the <a class="reference internal" href="query.html#sqlalchemy.orm.query.Query" title="sqlalchemy.orm.query.Query"><tt class="xref py py-class docutils literal"><span class="pre">Query</span></tt></a>
as used by <a class="reference internal" href="query.html#sqlalchemy.orm.query.Query.with_lockmode" title="sqlalchemy.orm.query.Query.with_lockmode"><tt class="xref py py-meth docutils literal"><span class="pre">with_lockmode()</span></tt></a>.</li>
</ul>
</td>
</tr>
</tbody>
</table>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p><a class="reference internal" href="#session-expire"><em>Refreshing / Expiring</em></a> - introductory material</p>
<p><a class="reference internal" href="#sqlalchemy.orm.session.Session.expire" title="sqlalchemy.orm.session.Session.expire"><tt class="xref py py-meth docutils literal"><span class="pre">Session.expire()</span></tt></a></p>
<p class="last"><a class="reference internal" href="#sqlalchemy.orm.session.Session.expire_all" title="sqlalchemy.orm.session.Session.expire_all"><tt class="xref py py-meth docutils literal"><span class="pre">Session.expire_all()</span></tt></a></p>
</div>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.rollback">
<tt class="descname">rollback</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.rollback" title="Permalink to this definition">¶</a></dt>
<dd><p>Rollback the current transaction in progress.</p>
<p>If no transaction is in progress, this method is a pass-through.</p>
<p>This method rolls back the current transaction or nested transaction
regardless of subtransactions being in effect. All subtransactions up
to the first real transaction are closed. Subtransactions occur when
<a class="reference internal" href="#sqlalchemy.orm.session.Session.begin" title="sqlalchemy.orm.session.Session.begin"><tt class="xref py py-meth docutils literal"><span class="pre">begin()</span></tt></a> is called multiple times.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="#session-rollback"><em>Rolling Back</em></a></p>
</div>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.session.Session.scalar">
<tt class="descname">scalar</tt><big>(</big><em>clause</em>, <em>params=None</em>, <em>mapper=None</em>, <em>bind=None</em>, <em>**kw</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.scalar" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#sqlalchemy.orm.session.Session.execute" title="sqlalchemy.orm.session.Session.execute"><tt class="xref py py-meth docutils literal"><span class="pre">execute()</span></tt></a> but return a scalar result.</p>
</dd></dl>
<dl class="attribute">
<dt id="sqlalchemy.orm.session.Session.transaction">
<tt class="descname">transaction</tt><em class="property"> = None</em><a class="headerlink" href="#sqlalchemy.orm.session.Session.transaction" title="Permalink to this definition">¶</a></dt>
<dd><p>The current active or inactive <a class="reference internal" href="#sqlalchemy.orm.session.SessionTransaction" title="sqlalchemy.orm.session.SessionTransaction"><tt class="xref py py-class docutils literal"><span class="pre">SessionTransaction</span></tt></a>.</p>
</dd></dl>
</dd></dl>
<dl class="class">
<dt id="sqlalchemy.orm.session.SessionTransaction">
<em class="property">class </em><tt class="descclassname">sqlalchemy.orm.session.</tt><tt class="descname">SessionTransaction</tt><big>(</big><em>session</em>, <em>parent=None</em>, <em>nested=False</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.SessionTransaction" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>-level transaction.</p>
<p><a class="reference internal" href="#sqlalchemy.orm.session.SessionTransaction" title="sqlalchemy.orm.session.SessionTransaction"><tt class="xref py py-class docutils literal"><span class="pre">SessionTransaction</span></tt></a> is a mostly behind-the-scenes object
not normally referenced directly by application code. It coordinates
among multiple <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> objects, maintaining a database
transaction for each one individually, committing or rolling them
back all at once. It also provides optional two-phase commit behavior
which can augment this coordination operation.</p>
<p>The <a class="reference internal" href="#sqlalchemy.orm.session.Session.transaction" title="sqlalchemy.orm.session.Session.transaction"><tt class="xref py py-attr docutils literal"><span class="pre">Session.transaction</span></tt></a> attribute of <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
refers to the current <a class="reference internal" href="#sqlalchemy.orm.session.SessionTransaction" title="sqlalchemy.orm.session.SessionTransaction"><tt class="xref py py-class docutils literal"><span class="pre">SessionTransaction</span></tt></a> object in use, if any.</p>
<p>A <a class="reference internal" href="#sqlalchemy.orm.session.SessionTransaction" title="sqlalchemy.orm.session.SessionTransaction"><tt class="xref py py-class docutils literal"><span class="pre">SessionTransaction</span></tt></a> is associated with a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>
in its default mode of <tt class="docutils literal"><span class="pre">autocommit=False</span></tt> immediately, associated
with no database connections. As the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is called upon
to emit SQL on behalf of various <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> or <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a>
objects, a corresponding <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> and associated
<a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Transaction" title="sqlalchemy.engine.Transaction"><tt class="xref py py-class docutils literal"><span class="pre">Transaction</span></tt></a> is added to a collection within the
<a class="reference internal" href="#sqlalchemy.orm.session.SessionTransaction" title="sqlalchemy.orm.session.SessionTransaction"><tt class="xref py py-class docutils literal"><span class="pre">SessionTransaction</span></tt></a> object, becoming one of the
connection/transaction pairs maintained by the
<a class="reference internal" href="#sqlalchemy.orm.session.SessionTransaction" title="sqlalchemy.orm.session.SessionTransaction"><tt class="xref py py-class docutils literal"><span class="pre">SessionTransaction</span></tt></a>.</p>
<p>The lifespan of the <a class="reference internal" href="#sqlalchemy.orm.session.SessionTransaction" title="sqlalchemy.orm.session.SessionTransaction"><tt class="xref py py-class docutils literal"><span class="pre">SessionTransaction</span></tt></a> ends when the
<a class="reference internal" href="#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-meth docutils literal"><span class="pre">Session.commit()</span></tt></a>, <a class="reference internal" href="#sqlalchemy.orm.session.Session.rollback" title="sqlalchemy.orm.session.Session.rollback"><tt class="xref py py-meth docutils literal"><span class="pre">Session.rollback()</span></tt></a> or
<a class="reference internal" href="#sqlalchemy.orm.session.Session.close" title="sqlalchemy.orm.session.Session.close"><tt class="xref py py-meth docutils literal"><span class="pre">Session.close()</span></tt></a> methods are called. At this point, the
<a class="reference internal" href="#sqlalchemy.orm.session.SessionTransaction" title="sqlalchemy.orm.session.SessionTransaction"><tt class="xref py py-class docutils literal"><span class="pre">SessionTransaction</span></tt></a> removes its association with its parent
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>. A <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> that is in <tt class="docutils literal"><span class="pre">autocommit=False</span></tt>
mode will create a new <a class="reference internal" href="#sqlalchemy.orm.session.SessionTransaction" title="sqlalchemy.orm.session.SessionTransaction"><tt class="xref py py-class docutils literal"><span class="pre">SessionTransaction</span></tt></a> to replace it
immediately, whereas a <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> that’s in <tt class="docutils literal"><span class="pre">autocommit=True</span></tt>
mode will remain without a <a class="reference internal" href="#sqlalchemy.orm.session.SessionTransaction" title="sqlalchemy.orm.session.SessionTransaction"><tt class="xref py py-class docutils literal"><span class="pre">SessionTransaction</span></tt></a> until the
<a class="reference internal" href="#sqlalchemy.orm.session.Session.begin" title="sqlalchemy.orm.session.Session.begin"><tt class="xref py py-meth docutils literal"><span class="pre">Session.begin()</span></tt></a> method is called.</p>
<p>Another detail of <a class="reference internal" href="#sqlalchemy.orm.session.SessionTransaction" title="sqlalchemy.orm.session.SessionTransaction"><tt class="xref py py-class docutils literal"><span class="pre">SessionTransaction</span></tt></a> behavior is that it is
capable of “nesting”. This means that the <a class="reference internal" href="#sqlalchemy.orm.session.Session.begin" title="sqlalchemy.orm.session.Session.begin"><tt class="xref py py-meth docutils literal"><span class="pre">Session.begin()</span></tt></a> method
can be called while an existing <a class="reference internal" href="#sqlalchemy.orm.session.SessionTransaction" title="sqlalchemy.orm.session.SessionTransaction"><tt class="xref py py-class docutils literal"><span class="pre">SessionTransaction</span></tt></a> is already
present, producing a new <a class="reference internal" href="#sqlalchemy.orm.session.SessionTransaction" title="sqlalchemy.orm.session.SessionTransaction"><tt class="xref py py-class docutils literal"><span class="pre">SessionTransaction</span></tt></a> that temporarily
replaces the parent <a class="reference internal" href="#sqlalchemy.orm.session.SessionTransaction" title="sqlalchemy.orm.session.SessionTransaction"><tt class="xref py py-class docutils literal"><span class="pre">SessionTransaction</span></tt></a>. When a
<a class="reference internal" href="#sqlalchemy.orm.session.SessionTransaction" title="sqlalchemy.orm.session.SessionTransaction"><tt class="xref py py-class docutils literal"><span class="pre">SessionTransaction</span></tt></a> is produced as nested, it assigns itself to
the <a class="reference internal" href="#sqlalchemy.orm.session.Session.transaction" title="sqlalchemy.orm.session.Session.transaction"><tt class="xref py py-attr docutils literal"><span class="pre">Session.transaction</span></tt></a> attribute. When it is ended via
<a class="reference internal" href="#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-meth docutils literal"><span class="pre">Session.commit()</span></tt></a> or <a class="reference internal" href="#sqlalchemy.orm.session.Session.rollback" title="sqlalchemy.orm.session.Session.rollback"><tt class="xref py py-meth docutils literal"><span class="pre">Session.rollback()</span></tt></a>, it restores its
parent <a class="reference internal" href="#sqlalchemy.orm.session.SessionTransaction" title="sqlalchemy.orm.session.SessionTransaction"><tt class="xref py py-class docutils literal"><span class="pre">SessionTransaction</span></tt></a> back onto the
<a class="reference internal" href="#sqlalchemy.orm.session.Session.transaction" title="sqlalchemy.orm.session.Session.transaction"><tt class="xref py py-attr docutils literal"><span class="pre">Session.transaction</span></tt></a> attribute. The behavior is effectively a
stack, where <a class="reference internal" href="#sqlalchemy.orm.session.Session.transaction" title="sqlalchemy.orm.session.Session.transaction"><tt class="xref py py-attr docutils literal"><span class="pre">Session.transaction</span></tt></a> refers to the current head of
the stack.</p>
<p>The purpose of this stack is to allow nesting of
<a class="reference internal" href="#sqlalchemy.orm.session.Session.rollback" title="sqlalchemy.orm.session.Session.rollback"><tt class="xref py py-meth docutils literal"><span class="pre">Session.rollback()</span></tt></a> or <a class="reference internal" href="#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-meth docutils literal"><span class="pre">Session.commit()</span></tt></a> calls in context
with various flavors of <a class="reference internal" href="#sqlalchemy.orm.session.Session.begin" title="sqlalchemy.orm.session.Session.begin"><tt class="xref py py-meth docutils literal"><span class="pre">Session.begin()</span></tt></a>. This nesting behavior
applies to when <a class="reference internal" href="#sqlalchemy.orm.session.Session.begin_nested" title="sqlalchemy.orm.session.Session.begin_nested"><tt class="xref py py-meth docutils literal"><span class="pre">Session.begin_nested()</span></tt></a> is used to emit a
SAVEPOINT transaction, and is also used to produce a so-called
“subtransaction” which allows a block of code to use a
begin/rollback/commit sequence regardless of whether or not its enclosing
code block has begun a transaction. The <a class="reference internal" href="#sqlalchemy.orm.session.Session.flush" title="sqlalchemy.orm.session.Session.flush"><tt class="xref py py-meth docutils literal"><span class="pre">flush()</span></tt></a> method, whether
called explicitly or via autoflush, is the primary consumer of the
“subtransaction” feature, in that it wishes to guarantee that it works
within in a transaction block regardless of whether or not the
<a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is in transactional mode when the method is called.</p>
<p>See also:</p>
<p><a class="reference internal" href="#sqlalchemy.orm.session.Session.rollback" title="sqlalchemy.orm.session.Session.rollback"><tt class="xref py py-meth docutils literal"><span class="pre">Session.rollback()</span></tt></a></p>
<p><a class="reference internal" href="#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-meth docutils literal"><span class="pre">Session.commit()</span></tt></a></p>
<p><a class="reference internal" href="#sqlalchemy.orm.session.Session.begin" title="sqlalchemy.orm.session.Session.begin"><tt class="xref py py-meth docutils literal"><span class="pre">Session.begin()</span></tt></a></p>
<p><a class="reference internal" href="#sqlalchemy.orm.session.Session.begin_nested" title="sqlalchemy.orm.session.Session.begin_nested"><tt class="xref py py-meth docutils literal"><span class="pre">Session.begin_nested()</span></tt></a></p>
<p><a class="reference internal" href="#sqlalchemy.orm.session.Session.is_active" title="sqlalchemy.orm.session.Session.is_active"><tt class="xref py py-attr docutils literal"><span class="pre">Session.is_active</span></tt></a></p>
<p><a class="reference internal" href="events.html#sqlalchemy.orm.events.SessionEvents.after_commit" title="sqlalchemy.orm.events.SessionEvents.after_commit"><tt class="xref py py-meth docutils literal"><span class="pre">SessionEvents.after_commit()</span></tt></a></p>
<p><a class="reference internal" href="events.html#sqlalchemy.orm.events.SessionEvents.after_rollback" title="sqlalchemy.orm.events.SessionEvents.after_rollback"><tt class="xref py py-meth docutils literal"><span class="pre">SessionEvents.after_rollback()</span></tt></a></p>
<p><a class="reference internal" href="events.html#sqlalchemy.orm.events.SessionEvents.after_soft_rollback" title="sqlalchemy.orm.events.SessionEvents.after_soft_rollback"><tt class="xref py py-meth docutils literal"><span class="pre">SessionEvents.after_soft_rollback()</span></tt></a></p>
</dd></dl>
</div>
<div class="section" id="session-utilites">
<h3>Session Utilites<a class="headerlink" href="#session-utilites" title="Permalink to this headline">¶</a></h3>
<dl class="function">
<dt id="sqlalchemy.orm.session.make_transient">
<tt class="descclassname">sqlalchemy.orm.session.</tt><tt class="descname">make_transient</tt><big>(</big><em>instance</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.make_transient" title="Permalink to this definition">¶</a></dt>
<dd><p>Make the given instance ‘transient’.</p>
<p>This will remove its association with any
session and additionally will remove its “identity key”,
such that it’s as though the object were newly constructed,
except retaining its values. It also resets the
“deleted” flag on the state if this object
had been explicitly deleted by its session.</p>
<p>Attributes which were “expired” or deferred at the
instance level are reverted to undefined, and
will not trigger any loads.</p>
</dd></dl>
<dl class="function">
<dt id="sqlalchemy.orm.session.make_transient_to_detached">
<tt class="descclassname">sqlalchemy.orm.session.</tt><tt class="descname">make_transient_to_detached</tt><big>(</big><em>instance</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.make_transient_to_detached" title="Permalink to this definition">¶</a></dt>
<dd><p>Make the given transient instance ‘detached’.</p>
<p>All attribute history on the given instance
will be reset as though the instance were freshly loaded
from a query. Missing attributes will be marked as expired.
The primary key attributes of the object, which are required, will be made
into the “key” of the instance.</p>
<p>The object can then be added to a session, or merged
possibly with the load=False flag, at which point it will look
as if it were loaded that way, without emitting SQL.</p>
<p>This is a special use case function that differs from a normal
call to <a class="reference internal" href="#sqlalchemy.orm.session.Session.merge" title="sqlalchemy.orm.session.Session.merge"><tt class="xref py py-meth docutils literal"><span class="pre">Session.merge()</span></tt></a> in that a given persistent state
can be manufactured without any SQL calls.</p>
<div class="versionadded">
<p><span>New in version 0.9.5.</span></p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="#sqlalchemy.orm.session.make_transient" title="sqlalchemy.orm.session.make_transient"><tt class="xref py py-func docutils literal"><span class="pre">make_transient()</span></tt></a></p>
</div>
</dd></dl>
<dl class="function">
<dt id="sqlalchemy.orm.session.object_session">
<tt class="descclassname">sqlalchemy.orm.session.</tt><tt class="descname">object_session</tt><big>(</big><em>instance</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.object_session" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the <tt class="docutils literal"><span class="pre">Session</span></tt> to which instance belongs.</p>
<p>If the instance is not a mapped instance, an error is raised.</p>
</dd></dl>
<dl class="function">
<dt id="sqlalchemy.orm.util.was_deleted">
<tt class="descclassname">sqlalchemy.orm.util.</tt><tt class="descname">was_deleted</tt><big>(</big><em>object</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.util.was_deleted" title="Permalink to this definition">¶</a></dt>
<dd><p>Return True if the given object was deleted
within a session flush.</p>
<div class="versionadded">
<p><span>New in version 0.8.0.</span></p>
</div>
</dd></dl>
</div>
<div class="section" id="attribute-and-state-management-utilities">
<h3>Attribute and State Management Utilities<a class="headerlink" href="#attribute-and-state-management-utilities" title="Permalink to this headline">¶</a></h3>
<p>These functions are provided by the SQLAlchemy attribute
instrumentation API to provide a detailed interface for dealing
with instances, attribute values, and history. Some of them
are useful when constructing event listener functions, such as
those described in <a class="reference internal" href="events.html"><em>ORM Events</em></a>.</p>
<dl class="function">
<dt id="sqlalchemy.orm.util.object_state">
<tt class="descclassname">sqlalchemy.orm.util.</tt><tt class="descname">object_state</tt><big>(</big><em>instance</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.util.object_state" title="Permalink to this definition">¶</a></dt>
<dd><p>Given an object, return the <a class="reference internal" href="internals.html#sqlalchemy.orm.state.InstanceState" title="sqlalchemy.orm.state.InstanceState"><tt class="xref py py-class docutils literal"><span class="pre">InstanceState</span></tt></a>
associated with the object.</p>
<p>Raises <a class="reference internal" href="exceptions.html#sqlalchemy.orm.exc.UnmappedInstanceError" title="sqlalchemy.orm.exc.UnmappedInstanceError"><tt class="xref py py-class docutils literal"><span class="pre">sqlalchemy.orm.exc.UnmappedInstanceError</span></tt></a>
if no mapping is configured.</p>
<p>Equivalent functionality is available via the <a class="reference internal" href="../core/inspection.html#sqlalchemy.inspection.inspect" title="sqlalchemy.inspection.inspect"><tt class="xref py py-func docutils literal"><span class="pre">inspect()</span></tt></a>
function as:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">inspect</span><span class="p">(</span><span class="n">instance</span><span class="p">)</span></pre></div>
</div>
<p>Using the inspection system will raise
<a class="reference internal" href="../core/exceptions.html#sqlalchemy.exc.NoInspectionAvailable" title="sqlalchemy.exc.NoInspectionAvailable"><tt class="xref py py-class docutils literal"><span class="pre">sqlalchemy.exc.NoInspectionAvailable</span></tt></a> if the instance is
not part of a mapping.</p>
</dd></dl>
<dl class="function">
<dt id="sqlalchemy.orm.attributes.del_attribute">
<tt class="descclassname">sqlalchemy.orm.attributes.</tt><tt class="descname">del_attribute</tt><big>(</big><em>instance</em>, <em>key</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.attributes.del_attribute" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete the value of an attribute, firing history events.</p>
<p>This function may be used regardless of instrumentation
applied directly to the class, i.e. no descriptors are required.
Custom attribute management schemes will need to make usage
of this method to establish attribute state as understood
by SQLAlchemy.</p>
</dd></dl>
<dl class="function">
<dt id="sqlalchemy.orm.attributes.get_attribute">
<tt class="descclassname">sqlalchemy.orm.attributes.</tt><tt class="descname">get_attribute</tt><big>(</big><em>instance</em>, <em>key</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.attributes.get_attribute" title="Permalink to this definition">¶</a></dt>
<dd><p>Get the value of an attribute, firing any callables required.</p>
<p>This function may be used regardless of instrumentation
applied directly to the class, i.e. no descriptors are required.
Custom attribute management schemes will need to make usage
of this method to make usage of attribute state as understood
by SQLAlchemy.</p>
</dd></dl>
<dl class="function">
<dt id="sqlalchemy.orm.attributes.get_history">
<tt class="descclassname">sqlalchemy.orm.attributes.</tt><tt class="descname">get_history</tt><big>(</big><em>obj</em>, <em>key</em>, <em>passive=symbol('PASSIVE_OFF')</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.attributes.get_history" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a <a class="reference internal" href="#sqlalchemy.orm.attributes.History" title="sqlalchemy.orm.attributes.History"><tt class="xref py py-class docutils literal"><span class="pre">History</span></tt></a> record for the given object
and attribute key.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><span class="target" id="sqlalchemy.orm.attributes.get_history.params.obj"></span><strong>obj</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.attributes.get_history.params.obj">¶</a> – an object whose class is instrumented by the
attributes package.</li>
<li><span class="target" id="sqlalchemy.orm.attributes.get_history.params.key"></span><strong>key</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.attributes.get_history.params.key">¶</a> – string attribute name.</li>
<li><span class="target" id="sqlalchemy.orm.attributes.get_history.params.passive"></span><strong>passive</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.attributes.get_history.params.passive">¶</a> – indicates loading behavior for the attribute
if the value is not already present. This is a
bitflag attribute, which defaults to the symbol
<tt class="xref py py-attr docutils literal"><span class="pre">PASSIVE_OFF</span></tt> indicating all necessary SQL
should be emitted.</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="function">
<dt id="sqlalchemy.orm.attributes.init_collection">
<tt class="descclassname">sqlalchemy.orm.attributes.</tt><tt class="descname">init_collection</tt><big>(</big><em>obj</em>, <em>key</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.attributes.init_collection" title="Permalink to this definition">¶</a></dt>
<dd><p>Initialize a collection attribute and return the collection adapter.</p>
<p>This function is used to provide direct access to collection internals
for a previously unloaded attribute. e.g.:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">collection_adapter</span> <span class="o">=</span> <span class="n">init_collection</span><span class="p">(</span><span class="n">someobject</span><span class="p">,</span> <span class="s">'elements'</span><span class="p">)</span>
<span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">values</span><span class="p">:</span>
<span class="n">collection_adapter</span><span class="o">.</span><span class="n">append_without_event</span><span class="p">(</span><span class="n">elem</span><span class="p">)</span></pre></div>
</div>
<p>For an easier way to do the above, see
<a class="reference internal" href="#sqlalchemy.orm.attributes.set_committed_value" title="sqlalchemy.orm.attributes.set_committed_value"><tt class="xref py py-func docutils literal"><span class="pre">set_committed_value()</span></tt></a>.</p>
<p>obj is an instrumented object instance. An InstanceState
is accepted directly for backwards compatibility but
this usage is deprecated.</p>
</dd></dl>
<dl class="function">
<dt id="sqlalchemy.orm.attributes.flag_modified">
<tt class="descclassname">sqlalchemy.orm.attributes.</tt><tt class="descname">flag_modified</tt><big>(</big><em>instance</em>, <em>key</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.attributes.flag_modified" title="Permalink to this definition">¶</a></dt>
<dd><p>Mark an attribute on an instance as ‘modified’.</p>
<p>This sets the ‘modified’ flag on the instance and
establishes an unconditional change event for the given attribute.</p>
</dd></dl>
<dl class="function">
<dt id="sqlalchemy.orm.attributes.instance_state">
<tt class="descclassname">sqlalchemy.orm.attributes.</tt><tt class="descname">instance_state</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.orm.attributes.instance_state" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the <a class="reference internal" href="internals.html#sqlalchemy.orm.state.InstanceState" title="sqlalchemy.orm.state.InstanceState"><tt class="xref py py-class docutils literal"><span class="pre">InstanceState</span></tt></a> for a given
mapped object.</p>
<p>This function is the internal version
of <a class="reference internal" href="#sqlalchemy.orm.util.object_state" title="sqlalchemy.orm.util.object_state"><tt class="xref py py-func docutils literal"><span class="pre">object_state()</span></tt></a>. The
<a class="reference internal" href="#sqlalchemy.orm.util.object_state" title="sqlalchemy.orm.util.object_state"><tt class="xref py py-func docutils literal"><span class="pre">object_state()</span></tt></a> and/or the
<a class="reference internal" href="../core/inspection.html#sqlalchemy.inspection.inspect" title="sqlalchemy.inspection.inspect"><tt class="xref py py-func docutils literal"><span class="pre">inspect()</span></tt></a> function is preferred here
as they each emit an informative exception
if the given object is not mapped.</p>
</dd></dl>
<dl class="function">
<dt id="sqlalchemy.orm.instrumentation.is_instrumented">
<tt class="descclassname">sqlalchemy.orm.instrumentation.</tt><tt class="descname">is_instrumented</tt><big>(</big><em>instance</em>, <em>key</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.instrumentation.is_instrumented" title="Permalink to this definition">¶</a></dt>
<dd><p>Return True if the given attribute on the given instance is
instrumented by the attributes package.</p>
<p>This function may be used regardless of instrumentation
applied directly to the class, i.e. no descriptors are required.</p>
</dd></dl>
<dl class="function">
<dt id="sqlalchemy.orm.attributes.set_attribute">
<tt class="descclassname">sqlalchemy.orm.attributes.</tt><tt class="descname">set_attribute</tt><big>(</big><em>instance</em>, <em>key</em>, <em>value</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.attributes.set_attribute" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the value of an attribute, firing history events.</p>
<p>This function may be used regardless of instrumentation
applied directly to the class, i.e. no descriptors are required.
Custom attribute management schemes will need to make usage
of this method to establish attribute state as understood
by SQLAlchemy.</p>
</dd></dl>
<dl class="function">
<dt id="sqlalchemy.orm.attributes.set_committed_value">
<tt class="descclassname">sqlalchemy.orm.attributes.</tt><tt class="descname">set_committed_value</tt><big>(</big><em>instance</em>, <em>key</em>, <em>value</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.attributes.set_committed_value" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the value of an attribute with no history events.</p>
<p>Cancels any previous history present. The value should be
a scalar value for scalar-holding attributes, or
an iterable for any collection-holding attribute.</p>
<p>This is the same underlying method used when a lazy loader
fires off and loads additional data from the database.
In particular, this method can be used by application code
which has loaded additional attributes or collections through
separate queries, which can then be attached to an instance
as though it were part of its original loaded state.</p>
</dd></dl>
<dl class="class">
<dt id="sqlalchemy.orm.attributes.History">
<em class="property">class </em><tt class="descclassname">sqlalchemy.orm.attributes.</tt><tt class="descname">History</tt><a class="headerlink" href="#sqlalchemy.orm.attributes.History" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <a class="reference internal" href="#sqlalchemy.orm.attributes.History" title="sqlalchemy.orm.attributes.History"><tt class="xref py py-class docutils literal"><span class="pre">sqlalchemy.orm.attributes.History</span></tt></a></p>
<p>A 3-tuple of added, unchanged and deleted values,
representing the changes which have occurred on an instrumented
attribute.</p>
<p>The easiest way to get a <a class="reference internal" href="#sqlalchemy.orm.attributes.History" title="sqlalchemy.orm.attributes.History"><tt class="xref py py-class docutils literal"><span class="pre">History</span></tt></a> object for a particular
attribute on an object is to use the <a class="reference internal" href="../core/inspection.html#sqlalchemy.inspection.inspect" title="sqlalchemy.inspection.inspect"><tt class="xref py py-func docutils literal"><span class="pre">inspect()</span></tt></a> function:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">inspect</span>
<span class="n">hist</span> <span class="o">=</span> <span class="n">inspect</span><span class="p">(</span><span class="n">myobject</span><span class="p">)</span><span class="o">.</span><span class="n">attrs</span><span class="o">.</span><span class="n">myattribute</span><span class="o">.</span><span class="n">history</span></pre></div>
</div>
<p>Each tuple member is an iterable sequence:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">added</span></tt> - the collection of items added to the attribute (the first
tuple element).</li>
<li><tt class="docutils literal"><span class="pre">unchanged</span></tt> - the collection of items that have not changed on the
attribute (the second tuple element).</li>
<li><tt class="docutils literal"><span class="pre">deleted</span></tt> - the collection of items that have been removed from the
attribute (the third tuple element).</li>
</ul>
<dl class="method">
<dt id="sqlalchemy.orm.attributes.History.empty">
<tt class="descname">empty</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.orm.attributes.History.empty" title="Permalink to this definition">¶</a></dt>
<dd><p>Return True if this <a class="reference internal" href="#sqlalchemy.orm.attributes.History" title="sqlalchemy.orm.attributes.History"><tt class="xref py py-class docutils literal"><span class="pre">History</span></tt></a> has no changes
and no existing, unchanged state.</p>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.attributes.History.has_changes">
<tt class="descname">has_changes</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.orm.attributes.History.has_changes" title="Permalink to this definition">¶</a></dt>
<dd><p>Return True if this <a class="reference internal" href="#sqlalchemy.orm.attributes.History" title="sqlalchemy.orm.attributes.History"><tt class="xref py py-class docutils literal"><span class="pre">History</span></tt></a> has changes.</p>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.attributes.History.non_added">
<tt class="descname">non_added</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.orm.attributes.History.non_added" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a collection of unchanged + deleted.</p>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.attributes.History.non_deleted">
<tt class="descname">non_deleted</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.orm.attributes.History.non_deleted" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a collection of added + unchanged.</p>
</dd></dl>
<dl class="method">
<dt id="sqlalchemy.orm.attributes.History.sum">
<tt class="descname">sum</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.orm.attributes.History.sum" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a collection of added + unchanged + deleted.</p>
</dd></dl>
</dd></dl>
</div>
</div>
</div>
</div>
</div>
<div id="docs-bottom-navigation" class="docs-navigation-links">
Previous:
<a href="inheritance.html" title="previous chapter">Mapping Class Inheritance Hierarchies</a>
Next:
<a href="query.html" title="next chapter">Querying</a>
<div id="docs-copyright">
© <a href="../copyright.html">Copyright</a> 2007-2014, the SQLAlchemy authors and contributors.
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.2b1.
</div>
</div>
</div>
</body>
</html>
|