<!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.8 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/changelog.css" type="text/css" /> <link rel="stylesheet" href="../_static/sphinx_paramlinks.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.8.7', 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.8 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.8.7</span> | Release Date: July 22, 2014 </div> <h1>SQLAlchemy 0.8 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.8 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></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">Joining a Session into an External Transaction</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</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"> <h3>Refreshing / Expiring<a class="headerlink" href="#refreshing-expiring" title="Permalink to this headline">¶</a></h3> <p>The Session normally works in the context of an ongoing transaction (with the default setting of autoflush=False). Most databases offer “isolated” transactions - this refers to a series of behaviors that allow the work within a transaction to remain consistent as time passes, regardless of the activities outside of that transaction. A key feature of a high degree of transaction isolation is that emitting the same SELECT statement twice will return the same results as when it was called the first time, even if the data has been modified in another transaction.</p> <p>For this reason, 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> gains very efficient behavior by loading the attributes of each instance only once. Subsequent reads of the same row in the same transaction are assumed to have the same value. The user application also gains directly from this assumption, that the transaction is regarded as a temporary shield against concurrent changes - a good application will ensure that isolation levels are set appropriately such that this assumption can be made, given the kind of data being worked with.</p> <p>To clear out the currently loaded state on an instance, the instance or its individual attributes can be marked as “expired”, which results in a reload to occur upon next access of any of the instance’s attrbutes. The instance can also be immediately reloaded from the database. 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> 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> methods achieve this:</p> <div class="highlight-python"><div class="highlight"><pre><span class="c"># immediately re-load attributes on obj1, obj2</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="n">session</span><span class="o">.</span><span class="n">refresh</span><span class="p">(</span><span class="n">obj2</span><span class="p">)</span> <span class="c"># expire objects obj1, obj2, attributes will be reloaded</span> <span class="c"># on the next access:</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="n">session</span><span class="o">.</span><span class="n">expire</span><span class="p">(</span><span class="n">obj2</span><span class="p">)</span></pre></div> </div> <p>When an expired object reloads, all non-deferred column-based attributes are loaded in one query. Current behavior for expired relationship-based attributes is that they load individually upon access - this behavior may be enhanced in a future release. When a refresh is invoked on an object, the ultimate operation is equivalent to a <a class="reference internal" href="query.html#sqlalchemy.orm.query.Query.get" title="sqlalchemy.orm.query.Query.get"><tt class="xref py py-meth docutils literal"><span class="pre">Query.get()</span></tt></a>, so any relationships configured with eager loading should also load within the scope of the refresh operation.</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">refresh()</span></tt></a> and <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> also support being passed a list of individual attribute names in which to be refreshed. These names can refer to any attribute, column-based or relationship based:</p> <div class="highlight-python"><div class="highlight"><pre><span class="c"># immediately re-load the attributes 'hello', 'world' on obj1, obj2</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">'hello'</span><span class="p">,</span> <span class="s">'world'</span><span class="p">])</span> <span class="n">session</span><span class="o">.</span><span class="n">refresh</span><span class="p">(</span><span class="n">obj2</span><span class="p">,</span> <span class="p">[</span><span class="s">'hello'</span><span class="p">,</span> <span class="s">'world'</span><span class="p">])</span> <span class="c"># expire the attributes 'hello', 'world' objects obj1, obj2, attributes will be reloaded</span> <span class="c"># on the next access:</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">'hello'</span><span class="p">,</span> <span class="s">'world'</span><span class="p">])</span> <span class="n">session</span><span class="o">.</span><span class="n">expire</span><span class="p">(</span><span class="n">obj2</span><span class="p">,</span> <span class="p">[</span><span class="s">'hello'</span><span class="p">,</span> <span class="s">'world'</span><span class="p">])</span></pre></div> </div> <p>The full contents of the session may be expired at once using <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">expire_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">expire_all</span><span class="p">()</span></pre></div> </div> <p>Note that <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">expire_all()</span></tt></a> is called <strong>automatically</strong> 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">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">rollback()</span></tt></a> are called. If using the session in its default mode of autocommit=False and with a well-isolated transactional environment (which is provided by most backends with the notable exception of MySQL MyISAM), there is virtually <em>no reason</em> to ever call <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">expire_all()</span></tt></a> directly - plenty of state will remain on the current transaction until it is rolled back or committed or otherwise removed.</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">refresh()</span></tt></a> and <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> similarly are usually only necessary when an UPDATE or DELETE has been issued manually within the transaction using <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>.</p> </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> cacade 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</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.</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"> <span id="session-external-transaction"></span><h2>Joining a Session into an External Transaction<a class="headerlink" href="#joining-a-session-into-an-external-transaction" 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="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="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"># 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> <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>**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>**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.**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>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>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.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 <tt class="xref py py-meth docutils literal"><span class="pre">Engine.connect()</span></tt>, 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> </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> </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.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> </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.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> </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>