<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title> Using the Session — SQLAlchemy 0.6.8 Documentation</title> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="../_static/docs.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '0.6.8', COLLAPSE_MODINDEX: false, FILE_SUFFIX: '.html' }; </script> <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> <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.6.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" /> </head> <body> <h1>SQLAlchemy 0.6.8 Documentation</h1> <div id="search"> Search: <form class="search" action="../search.html" method="get"> <input type="text" name="q" size="18" /> <input type="submit" value="Search" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> <div class="versionheader"> Version: <span class="versionnum">0.6.8</span> Last Updated: 06/05/2011 13:10:26 </div> <div class="clearboth"></div> <div id="topnav"> <div id="pagecontrol"> <ul> <li>Prev: <a href="inheritance.html" title="previous chapter">Mapping Class Inheritance Hierarchies</a> </li> <li>Next: <a href="query.html" title="next chapter">Querying</a> </li> <li> <a href="../contents.html">Table of Contents</a> | <a href="../genindex.html">Index</a> | <a href="../_sources/orm/session.txt">view source </li> </ul> </div> <div id="navbanner"> <a class="totoc" href="../index.html">SQLAlchemy 0.6.8 Documentation</a> » <a href="index.html" title="SQLAlchemy ORM">SQLAlchemy ORM</a> » Using the Session <h2> Using the Session </h2> <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></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></li> <li><a class="reference internal" href="#frequently-asked-questions">Frequently Asked Questions</a></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-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></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="#using-subtransactions">Using Subtransactions</a></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="#the-session-object-and-sessionmaker-function">The <tt class="docutils literal"><span class="pre">Session</span></tt> object and <tt class="docutils literal"><span class="pre">sessionmaker()</span></tt> function</a></li> <li><a class="reference internal" href="#contextual-thread-local-sessions">Contextual/Thread-local Sessions</a><ul> <li><a class="reference internal" href="#creating-a-thread-local-context">Creating a Thread-local Context</a></li> <li><a class="reference internal" href="#lifespan-of-a-contextual-session">Lifespan of a Contextual Session</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="#vertical-partitioning">Vertical Partitioning</a></li> <li><a class="reference internal" href="#horizontal-partitioning">Horizontal Partitioning</a></li> </ul> </li> <li><a class="reference internal" href="#session-utilities">Session Utilities</a></li> <li><a class="reference internal" href="#attribute-and-state-management-utilities">Attribute and State Management Utilities</a></li> </ul> </li> </ul> </div> <div class="clearboth"></div> </div> <div class="document"> <div class="body"> <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.base.Engine" title="sqlalchemy.engine.base.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/schema.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 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"> <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-func docutils literal"><span class="pre">sessionmaker()</span></tt></a> function 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-func 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.orm</span> <span class="kn">import</span> <span class="n">sessionmaker</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-func docutils literal"><span class="pre">sessionmaker()</span></tt></a> call creates a class for us, which we assign to the name <tt class="docutils literal"><span class="pre">Session</span></tt>. This class is a subclass of the actual <a class="reference internal" href="#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, which when instantiated, will use the arguments we’ve given the function, in this case to use a particular <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.base.Engine" title="sqlalchemy.engine.base.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> for connection resources.</p> <p>When you write your application, place the call to <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-func docutils literal"><span class="pre">sessionmaker()</span></tt></a> somewhere global, and then make your new <tt class="docutils literal"><span class="pre">Session</span></tt> class available to the rest of your application.</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-func docutils literal"><span class="pre">sessionmaker()</span></tt></a> with an <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.base.Engine" title="sqlalchemy.engine.base.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.base.Engine" title="sqlalchemy.engine.base.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. You can also associate a <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.base.Engine" title="sqlalchemy.engine.base.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> with an existing <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-func docutils literal"><span class="pre">sessionmaker()</span></tt></a> using the <tt class="xref py py-meth docutils literal"><span class="pre">sessionmaker.configure()</span></tt> method:</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> <p>you can also associate 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 with an <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.base.Engine" title="sqlalchemy.engine.base.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> on each invocation:</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="p">(</span><span class="n">bind</span><span class="o">=</span><span class="n">engine</span><span class="p">)</span></pre></div> </div> <p>...or directly with a <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.base.Connection" title="sqlalchemy.engine.base.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">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>While the rationale for the above example may not be apparent, the typical usage is in 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> below for a full example.</p> </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"> <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><em>Transient</em> - 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><em>Pending</em> - when you <a class="reference internal" href="#sqlalchemy.orm.session.Session.add" title="sqlalchemy.orm.session.Session.add"><tt class="xref py py-func 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><em>Persistent</em> - 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><em>Detached</em> - 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> <div class="section" id="frequently-asked-questions"> <h3>Frequently Asked Questions<a class="headerlink" href="#frequently-asked-questions" title="Permalink to this headline">¶</a></h3> <ul> <li><p class="first">When do I make a <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-func docutils literal"><span class="pre">sessionmaker()</span></tt></a> ?</p> <blockquote> <div><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-func 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 <tt class="docutils literal"><span class="pre">configure()</span></tt>.</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-func 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-func docutils literal"><span class="pre">sessionmaker()</span></tt></a> would be somewhere at the module level, and your 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> calls would be sprinkled all throughout your app, such as in a web application within each controller method.</p> </div></blockquote> </li> <li><p class="first">When do I make 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> ?</p> <blockquote> <div><p>You typically 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> when you first need to talk to your database, and want to save some objects or load some existing ones. It then remains in use for the lifespan of a particular database conversation, which includes not just the initial loading of objects but throughout the whole usage of those instances.</p> <p>Objects become detached if their owning session is discarded. They are still functional in the detached state if the user has ensured that their state has not been expired before detachment, but they will not be able to represent the current state of database data. Because of this, it’s best to consider persisted objects as an extension of the state of 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>, and to keep that session around until all referenced objects have been discarded.</p> <p>An exception to this is when objects are placed in caches or otherwise shared among threads or processes, in which case their detached state can be stored, transmitted, or shared. However, the state of detached objects should still be transferred back into 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> 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> or <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> before working with the object (or in the case of merge, its state) again.</p> <p>It is also very common that 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> as well as its associated objects are only referenced by a single thread. Sharing objects between threads is most safely accomplished by sharing their state among multiple instances of those objects, each associated with a distinct <a class="reference internal" href="#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 thread, <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> to transfer state between threads. This pattern is not a strict requirement by any means, but it has the least chance of introducing concurrency issues.</p> <p>To help with the recommended <a class="reference internal" href="#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-thread, <a class="reference internal" href="#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-set-of-objects patterns, the <a class="reference internal" href="#sqlalchemy.orm.scoped_session" title="sqlalchemy.orm.scoped_session"><tt class="xref py py-func docutils literal"><span class="pre">scoped_session()</span></tt></a> function is provided which produces a thread-managed registry 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. It is commonly used in web applications so that a single global variable can be used to safely represent transactional sessions with sets of objects, localized to a single thread. More on this object is in <a class="reference internal" href="#unitofwork-contextual"><em>Contextual/Thread-local Sessions</em></a>.</p> </div></blockquote> </li> <li><p class="first">Is the Session a cache ?</p> <blockquote> <div><p>Yeee...no. It’s somewhat used as a cache, in that it implements the identity map 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://beaker.groovie.org/">Beaker</a>, via the <a class="reference internal" href="examples.html#examples-caching"><em>Beaker Caching</em></a> example.</p> </div></blockquote> </li> <li><p class="first">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 ?</p> <blockquote> <div><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-func 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> </div></blockquote> </li> </ul> <ul id="index-0"> <li><p class="first">Is the session thread-safe?</p> <blockquote> <div><p>Nope. It has no thread synchronization of any kind built in, and particularly when you do a flush operation, it definitely is not open to concurrent threads accessing it, because it holds onto a single database connection at that point. If you use a session which is non-transactional (meaning, <tt class="docutils literal"><span class="pre">autocommit</span></tt> is set to <tt class="xref docutils literal"><span class="pre">True</span></tt>, not the default setting) for read operations only, it’s still not thread-“safe”, but you also wont get any catastrophic failures either, since it checks out and returns connections to the connection pool on an as-needed basis; it’s just that different threads might load the same objects independently of each other, but only one will wind up in the identity map (however, the other one might still live in a collection somewhere).</p> <p>But the bigger point here is, 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. If, on the other hand, there are other threads participating in the same task you are, such as in a desktop graphical application, then you would be sharing the session with those threads, but you also will have implemented a proper locking scheme (or your graphical framework does) so that those threads do not collide.</p> <p>A multithreaded application is usually going to want to make usage of <a class="reference internal" href="#sqlalchemy.orm.scoped_session" title="sqlalchemy.orm.scoped_session"><tt class="xref py py-func docutils literal"><span class="pre">scoped_session()</span></tt></a> to transparently manage sessions per thread. More on this at <a class="reference internal" href="#unitofwork-contextual"><em>Contextual/Thread-local Sessions</em></a>.</p> </div></blockquote> </li> </ul> </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-func 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-func 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-func 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-func 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-func docutils literal"><span class="pre">merge()</span></tt></a> reconciles the current state of an instance and its associated children with existing data in the database, and returns a copy of the instance associated with the session. 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 class="simple"> <li>It examines the primary key of the instance. If it’s present, it attempts to load an instance with that primary key (or pulls from the local identity map).</li> <li>If there’s no primary key on the given instance, or the given primary key does not exist in the database, a new instance is created.</li> <li>The state of the given instance is then copied onto the located/newly created instance.</li> <li>The operation is cascaded to associated child items along the <tt class="docutils literal"><span class="pre">merge</span></tt> cascade. Note that all changes present on the given instance, including changes to collections, are merged.</li> <li>The new instance is returned.</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-func docutils literal"><span class="pre">merge()</span></tt></a>, the given instance is not placed within the session, and can be associated with a different session or detached. <a class="reference internal" href="#sqlalchemy.orm.session.Session.merge" title="sqlalchemy.orm.session.Session.merge"><tt class="xref py py-func docutils literal"><span class="pre">merge()</span></tt></a> is very useful for taking the state of any kind of object structure without regard for its origins or current session associations and placing that state within a session. Here’s two examples:</p> <ul class="simple"> <li>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-func 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.</li> <li>A web application stores mapped entities within an HTTP session object. When each request starts up, the serialized data can be merged into the session, so that the original entity may be safely shared among requests and threads.</li> </ul> <p><a class="reference internal" href="#sqlalchemy.orm.session.Session.merge" title="sqlalchemy.orm.session.Session.merge"><tt class="xref py py-func docutils literal"><span class="pre">merge()</span></tt></a> is frequently used by applications which implement their own second level caches. This refers to an application which uses an in memory dictionary, or an tool like Memcached to store objects over long running spans of time. When such an object needs to exist within 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 class="reference internal" href="#sqlalchemy.orm.session.Session.merge" title="sqlalchemy.orm.session.Session.merge"><tt class="xref py py-func docutils literal"><span class="pre">merge()</span></tt></a> is a good choice since it leaves the original cached object untouched. For this use case, merge provides a keyword option called <tt class="docutils literal"><span class="pre">load=False</span></tt>. When this boolean flag is set to <tt class="xref docutils literal"><span class="pre">False</span></tt>, <a class="reference internal" href="#sqlalchemy.orm.session.Session.merge" title="sqlalchemy.orm.session.Session.merge"><tt class="xref py py-func docutils literal"><span class="pre">merge()</span></tt></a> will not issue any SQL to reconcile the given object against the current state of the database, thereby reducing query overhead. The limitation is that the given object and all of its children may not contain any pending changes, and it’s also of course possible that newer information in the database will not be present on the merged object, since no load is issued.</p> <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 transferrence 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 <tt class="docutils literal"><span class="pre">cascade</span></tt> 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>Note that a new <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> option introduced in 0.6.5, <tt class="docutils literal"><span class="pre">cascade_backrefs=False</span></tt>, 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="xref 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-func 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> <p>The big gotcha with <a class="reference internal" href="#sqlalchemy.orm.session.Session.delete" title="sqlalchemy.orm.session.Session.delete"><tt class="xref py py-func docutils literal"><span class="pre">delete()</span></tt></a> is that <strong>nothing is removed from collections</strong>. Such as, if a <tt class="docutils literal"><span class="pre">User</span></tt> has a collection of three <tt class="docutils literal"><span class="pre">Addresses</span></tt>, deleting an <tt class="docutils literal"><span class="pre">Address</span></tt> will not remove it from <tt class="docutils literal"><span class="pre">user.addresses</span></tt>:</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>The solution is to use proper cascading:</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> <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"> <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-func 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-func 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-func 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-func 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-func 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-func 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"> <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-func 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-func 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-func docutils literal"><span class="pre">begin()</span></tt></a> method.</p> <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-func 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-func 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"> <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-func 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-func 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-func 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-func 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-func 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-func 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-func docutils literal"><span class="pre">expunge_all()</span></tt></a>, and releases 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></pre></div> </div> <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-func 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>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 behavior controls how the Session should treat the instances that have a parent-child relationship with another instance that is operated upon by the Session. Cascade is indicated as a comma-separated list of string keywords, with the possible values <tt class="docutils literal"><span class="pre">all</span></tt>, <tt class="docutils literal"><span class="pre">delete</span></tt>, <tt class="docutils literal"><span class="pre">save-update</span></tt>, <tt class="docutils literal"><span class="pre">refresh-expire</span></tt>, <tt class="docutils literal"><span class="pre">merge</span></tt>, <tt class="docutils literal"><span class="pre">expunge</span></tt>, and <tt class="docutils literal"><span class="pre">delete-orphan</span></tt>.</p> <p>Cascading is configured by setting the <tt class="docutils literal"><span class="pre">cascade</span></tt> keyword argument on 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>:</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">items_table</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="s">'customer'</span> <span class="p">:</span> <span class="n">relationship</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">user_orders_table</span><span class="p">,</span> <span class="n">cascade</span><span class="o">=</span><span class="s">"save-update"</span><span class="p">),</span> <span class="p">})</span></pre></div> </div> <p>The above mapper specifies two relationships, <tt class="docutils literal"><span class="pre">items</span></tt> and <tt class="docutils literal"><span class="pre">customer</span></tt>. The <tt class="docutils literal"><span class="pre">items</span></tt> relationship specifies “all, delete-orphan” as its <tt class="docutils literal"><span class="pre">cascade</span></tt> value, indicating that all <tt class="docutils literal"><span class="pre">add</span></tt>, <tt class="docutils literal"><span class="pre">merge</span></tt>, <tt class="docutils literal"><span class="pre">expunge</span></tt>, <tt class="docutils literal"><span class="pre">refresh</span></tt> <tt class="docutils literal"><span class="pre">delete</span></tt> and <tt class="docutils literal"><span class="pre">expire</span></tt> operations performed on a parent <tt class="docutils literal"><span class="pre">Order</span></tt> instance should also be performed on the child <tt class="docutils literal"><span class="pre">Item</span></tt> instances attached to it. The <tt class="docutils literal"><span class="pre">delete-orphan</span></tt> cascade value additionally indicates that if an <tt class="docutils literal"><span class="pre">Item</span></tt> instance is no longer associated with an <tt class="docutils literal"><span class="pre">Order</span></tt>, it should also be deleted. The “all, delete-orphan” cascade argument allows a so-called <em>lifecycle</em> relationship between an <tt class="docutils literal"><span class="pre">Order</span></tt> and an <tt class="docutils literal"><span class="pre">Item</span></tt> object.</p> <p>The <tt class="docutils literal"><span class="pre">customer</span></tt> relationship specifies only the “save-update” cascade value, indicating most operations will not be cascaded from a parent <tt class="docutils literal"><span class="pre">Order</span></tt> instance to a child <tt class="docutils literal"><span class="pre">User</span></tt> instance except for the <a class="reference internal" href="#sqlalchemy.orm.session.Session.add" title="sqlalchemy.orm.session.Session.add"><tt class="xref py py-func docutils literal"><span class="pre">add()</span></tt></a> operation. <tt class="docutils literal"><span class="pre">save-update</span></tt> cascade indicates that an <a class="reference internal" href="#sqlalchemy.orm.session.Session.add" title="sqlalchemy.orm.session.Session.add"><tt class="xref py py-func docutils literal"><span class="pre">add()</span></tt></a> on the parent will cascade to all child items, and also that items added to a parent which is already present in a session will also be added to that same session. “save-update” cascade also cascades the <em>pending history</em> of a relationship()-based attribute, meaning that objects which were removed from a scalar or collection attribute whose changes have not yet been flushed are also placed into the new session - this so that foreign key clear operations and deletions will take place (new in 0.6).</p> <p>Note that the <tt class="docutils literal"><span class="pre">delete-orphan</span></tt> cascade only functions for relationships where the target object can have a single parent at a time, meaning it is only appropriate for one-to-one or one-to-many relationships. For 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> which establishes one-to-one via a local foreign key, i.e. a many-to-one that stores only a single parent, or one-to-one/one-to-many via a “secondary” (association) table, a warning will be issued if <tt class="docutils literal"><span class="pre">delete-orphan</span></tt> is configured. To disable this warning, also specify the <tt class="docutils literal"><span class="pre">single_parent=True</span></tt> flag on the relationship, which constrains objects to allow attachment to only one parent at a time.</p> <p>The default value for <tt class="docutils literal"><span class="pre">cascade</span></tt> 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> is <tt class="docutils literal"><span class="pre">save-update,</span> <span class="pre">merge</span></tt>.</p> <p><tt class="docutils literal"><span class="pre">save-update</span></tt> cascade also takes place on backrefs by default. This 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">items_table</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">Item</span></tt> to the <tt class="docutils literal"><span class="pre">orders</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">orders</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 as of 0.6.5 using the <tt class="docutils literal"><span class="pre">cascade_backrefs</span></tt> 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">items_table</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">orders</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 <tt class="xref py py-func docutils literal"><span class="pre">add()</span></tt> <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 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>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> manages transactions across all engines associated with it. 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> receives requests to execute SQL statements using a particular <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.base.Engine" title="sqlalchemy.engine.base.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.base.Connection" title="sqlalchemy.engine.base.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a>, it adds each individual <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.base.Engine" title="sqlalchemy.engine.base.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> encountered to its transactional state and maintains an open connection for each one (note that a simple application normally has just one <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.base.Engine" title="sqlalchemy.engine.base.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a>). At commit time, all unflushed data is flushed, and each individual transaction is committed. If the underlying databases support two-phase semantics, this may be used by the Session as well if two-phase transactions are enabled.</p> <p>Normal operation ends the transactional state using the <a class="reference internal" href="#sqlalchemy.orm.session.Session.rollback" title="sqlalchemy.orm.session.Session.rollback"><tt class="xref py py-func 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-func docutils literal"><span class="pre">commit()</span></tt></a> methods. After either is called, 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> starts a new transaction:</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="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="c"># commit- will immediately go into</span> <span class="c"># a new transaction on next use.</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"># rollback - will immediately go into</span> <span class="c"># a new transaction on next use.</span> <span class="n">session</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span></pre></div> </div> <p>A session which is configured with <tt class="docutils literal"><span class="pre">autocommit=True</span></tt> may be placed into a transaction using <a class="reference internal" href="#sqlalchemy.orm.session.Session.begin" title="sqlalchemy.orm.session.Session.begin"><tt class="xref py py-func docutils literal"><span class="pre">begin()</span></tt></a>. With an <tt class="docutils literal"><span class="pre">autocommit=True</span></tt> session that’s been placed into a transaction using <a class="reference internal" href="#sqlalchemy.orm.session.Session.begin" title="sqlalchemy.orm.session.Session.begin"><tt class="xref py py-func docutils literal"><span class="pre">begin()</span></tt></a>, the session releases all connection resources after a <a class="reference internal" href="#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-func 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-func docutils literal"><span class="pre">rollback()</span></tt></a> and remains transaction-less (with the exception of flushes) until the next <a class="reference internal" href="#sqlalchemy.orm.session.Session.begin" title="sqlalchemy.orm.session.Session.begin"><tt class="xref py py-func docutils literal"><span class="pre">begin()</span></tt></a> call:</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">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-func docutils literal"><span class="pre">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">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-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-func 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-func 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-func 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-func 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-func 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-func 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-func 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-func 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-func docutils literal"><span class="pre">begin_nested()</span></tt></a> was called.</p> </div> <div class="section" id="using-subtransactions"> <span id="session-subtransactions"></span><h3>Using Subtransactions<a class="headerlink" href="#using-subtransactions" title="Permalink to this headline">¶</a></h3> <p>A subtransaction, as offered by the <tt class="docutils literal"><span class="pre">subtransactions=True</span></tt> flag 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>, is 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>. It’s 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. By “non-transactional”, we mean that no actual transactional dialogue with the database is generated by this flag beyond that of a single call 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>, regardless of how many times the method is called within a transaction.</p> <p>The subtransaction feature is in fact intrinsic to any call 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>, which uses it internally to ensure that the series of flush steps are enclosed within a transaction, regardless of the setting of <tt class="docutils literal"><span class="pre">autocommit</span></tt> or the presence of an existing transactional context. However, explicit usage of the <tt class="docutils literal"><span class="pre">subtransactions=True</span></tt> flag is generally only useful with an application that uses 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 “autocommit=True” mode, and calls <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> explicitly in order to demarcate transactions. For this reason the subtransaction feature is not commonly used in an explicit way, except for apps that integrate SQLAlchemy-level transaction control with the transaction control of another library or subsystem. For true, general purpose “nested” transactions, where a rollback affects only a portion of the work which has proceeded, savepoints should be used, documented in <a class="reference internal" href="#session-begin-nested"><em>Using SAVEPOINT</em></a>.</p> <p>The feature is the ORM 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.base.Connection.begin" title="sqlalchemy.engine.base.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.base.Transaction.commit" title="sqlalchemy.engine.base.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> <p>As is the case with the non-ORM <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.base.Transaction" title="sqlalchemy.engine.base.Transaction"><tt class="xref py py-class docutils literal"><span class="pre">Transaction</span></tt></a> object, calling <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> rolls back the <strong>entire</strong> transaction, which was initiated by the first call 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">Session.begin()</span></tt></a> (whether this call was explicit by the end user, or implicit in an <tt class="docutils literal"><span class="pre">autocommit=False</span></tt> scenario). However, 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> still considers itself to be in a “partially rolled back” state until <a class="reference internal" href="#sqlalchemy.orm.session.Session.rollback" title="sqlalchemy.orm.session.Session.rollback"><tt class="xref py py-meth docutils literal"><span class="pre">Session.rollback()</span></tt></a> is called explicitly for each call that was made 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">Session.begin()</span></tt></a>, where “partially rolled back” means that no further SQL operations can proceed until each level of the transaction has been acounted for, unless 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 is called which cancels all transactional markers. For a full exposition on the rationale for this, please see “<a class="reference external" href="http://www.sqlalchemy.org/trac/wiki/FAQ#ButwhyisnttheoneautomaticcalltoROLLBACKenoughWhymustIROLLBACKagain">But why isn’t the one automatic call to ROLLBACK enough ? Why must I ROLLBACK again?</a>”. The general theme is that if subtransactions are used as intended, that is, as a means to nest multiple begin/commit pairs, the appropriate rollback calls naturally occur in any case, and allow the session’s nesting of transactional pairs to function in a simple and predictable way without the need to guess as to what level is active.</p> <p>An example of <tt class="docutils literal"><span class="pre">subtransactions=True</span></tt> is nearly identical to that of the non-ORM technique. The nesting of transactions, as well as the natural presence of “rollback” for all transactions should an exception occur, is illustrated:</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="c"># open a transaction. If there was</span> <span class="c"># no previous call to begin(), this will</span> <span class="c"># begin a real transaction (meaning, a</span> <span class="c"># DBAPI connection is procured, which as</span> <span class="c"># per the DBAPI specification is in a transactional</span> <span class="c"># state ready to be committed or rolled back)</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</span> <span class="k">def</span> <span class="nf">method_b</span><span class="p">(</span><span class="n">connection</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="c"># open a transaction - this</span> <span class="c"># runs in the context of method_a()'s</span> <span class="c"># transaction</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>Since 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> method uses a subtransaction, a failed flush will always issue a rollback which then affects the state of the outermost transaction (unless a SAVEPOINT is in use). This forces the need to 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> for the full operation before subsequent SQL operations can proceed.</p> </div> <div class="section" id="enabling-two-phase-commit"> <h3>Enabling Two-Phase Commit<a class="headerlink" href="#enabling-two-phase-commit" title="Permalink to this headline">¶</a></h3> <p>Finally, for MySQL, PostgreSQL, and soon Oracle as well, 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-func 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"> <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-func docutils literal"><span class="pre">execute()</span></tt></a> method, which returns a <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.base.ResultProxy" title="sqlalchemy.engine.base.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.base.Engine" title="sqlalchemy.engine.base.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.base.Connection" title="sqlalchemy.engine.base.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.base.Connection" title="sqlalchemy.engine.base.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-func 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.base.Engine" title="sqlalchemy.engine.base.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.base.Connection" title="sqlalchemy.engine.base.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-func 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-func 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.base.Connection" title="sqlalchemy.engine.base.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.base.Transaction" title="sqlalchemy.engine.base.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.base.Connection" title="sqlalchemy.engine.base.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="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></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.base.Transaction.rollback" title="sqlalchemy.engine.base.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.base.Connection" title="sqlalchemy.engine.base.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="the-session-object-and-sessionmaker-function"> <h2>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 and <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-func docutils literal"><span class="pre">sessionmaker()</span></tt></a> function<a class="headerlink" href="#the-session-object-and-sessionmaker-function" title="Permalink to this headline">¶</a></h2> <dl class="function"> <dt id="sqlalchemy.orm.session.sessionmaker"> <tt class="descclassname">sqlalchemy.orm.session.</tt><tt class="descname">sessionmaker</tt><big>(</big><em>bind=None</em>, <em>class_=None</em>, <em>autoflush=True</em>, <em>autocommit=False</em>, <em>expire_on_commit=True</em>, <em>**kwargs</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.sessionmaker" title="Permalink to this definition">¶</a></dt> <dd><p>Generate a custom-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> class.</p> <p>The returned object is a subclass of <tt class="docutils literal"><span class="pre">Session</span></tt>, which, when instantiated with no arguments, uses the keyword arguments configured here as its constructor arguments.</p> <p>It is intended that the <cite>sessionmaker()</cite> function be called within the global scope of an application, and the returned class be made available to the rest of the application as the single class used to instantiate sessions.</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 special classmethod <tt class="docutils literal"><span class="pre">configure()</span></tt>, which allows additional configurational options to take place after the custom <tt class="docutils literal"><span class="pre">Session</span></tt> class has been generated. This is useful particularly for defining the specific <tt class="docutils literal"><span class="pre">Engine</span></tt> (or engines) to which new instances of <tt class="docutils literal"><span class="pre">Session</span></tt> should be bound:</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:///foo.db'</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> <p>Options:</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><strong>autocommit</strong> – <p>Defaults to <tt class="xref docutils literal"><span class="pre">False</span></tt>. When <tt class="xref docutils literal"><span class="pre">True</span></tt>, the <tt class="docutils literal"><span class="pre">Session</span></tt> 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 <cite>session.begin()</cite> method may be used to begin a transaction explicitly.</p> <p>Leaving it on its default value of <tt class="xref docutils literal"><span class="pre">False</span></tt> means that the <tt class="docutils literal"><span class="pre">Session</span></tt> will acquire a connection and begin a transaction the first time it is used, which it will maintain persistently until <tt class="docutils literal"><span class="pre">rollback()</span></tt>, <tt class="docutils literal"><span class="pre">commit()</span></tt>, or <tt class="docutils literal"><span class="pre">close()</span></tt> is called. When the transaction is released by any of these methods, the <tt class="docutils literal"><span class="pre">Session</span></tt> is ready for the next usage, which will again acquire and maintain a new connection/transaction.</p> </li> <li><strong>autoflush</strong> – When <tt class="xref docutils literal"><span class="pre">True</span></tt>, all query operations will issue a <tt class="docutils literal"><span class="pre">flush()</span></tt> call to this <tt class="docutils literal"><span class="pre">Session</span></tt> before proceeding. This is a convenience feature so that <tt class="docutils literal"><span class="pre">flush()</span></tt> 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 <tt class="docutils literal"><span class="pre">flush()</span></tt> are rarely needed; you usually only need to call <tt class="docutils literal"><span class="pre">commit()</span></tt> (which flushes) to finalize changes.</li> <li><strong>bind</strong> – An optional <tt class="docutils literal"><span class="pre">Engine</span></tt> or <tt class="docutils literal"><span class="pre">Connection</span></tt> 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><strong>binds</strong> – <dl class="docutils"> <dt>An optional dictionary which contains more granular “bind”</dt> <dd>information than the <tt class="docutils literal"><span class="pre">bind</span></tt> parameter provides. This dictionary can map individual <tt class="docutils literal"><span class="pre">Table</span></tt> instances as well as <tt class="docutils literal"><span class="pre">Mapper</span></tt> instances to individual <tt class="docutils literal"><span class="pre">Engine</span></tt> or <tt class="docutils literal"><span class="pre">Connection</span></tt> objects. Operations which proceed relative to a particular <tt class="docutils literal"><span class="pre">Mapper</span></tt> will consult this dictionary for the direct <tt class="docutils literal"><span class="pre">Mapper</span></tt> instance as well as the mapper’s <tt class="docutils literal"><span class="pre">mapped_table</span></tt> attribute in order to locate an connectable to use. The full resolution is described in the <tt class="docutils literal"><span class="pre">get_bind()</span></tt> method of <tt class="docutils literal"><span class="pre">Session</span></tt>. 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><strong>class_</strong> – 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 <tt class="docutils literal"><span class="pre">sessionmaker()</span></tt> function, and is not sent directly to the constructor for <tt class="docutils literal"><span class="pre">Session</span></tt>.</li> <li><strong>_enable_transaction_accounting</strong> – Defaults to <tt class="xref docutils literal"><span class="pre">True</span></tt>. A legacy-only flag which when <tt class="xref 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 begin(), all of which are interdependent.</li> <li><strong>expire_on_commit</strong> – Defaults to <tt class="xref docutils literal"><span class="pre">True</span></tt>. When <tt class="xref docutils literal"><span class="pre">True</span></tt>, all instances will be fully expired after each <tt class="docutils literal"><span class="pre">commit()</span></tt>, so that all attribute/object access subsequent to a completed transaction will load from the most recent database state.</li> <li><strong>extension</strong> – An optional <tt class="xref py py-class docutils literal"><span class="pre">SessionExtension</span></tt> instance, or a list of such instances, which will receive pre- and post- commit and flush events, as well as a post-rollback event. User- defined code may be placed within these hooks using a user-defined subclass of <tt class="docutils literal"><span class="pre">SessionExtension</span></tt>.</li> <li><strong>query_cls</strong> – Class which should be used to create new Query objects, as returned by the <tt class="docutils literal"><span class="pre">query()</span></tt> 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><strong>twophase</strong> – When <tt class="xref 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 <tt class="docutils literal"><span class="pre">commit()</span></tt>, after <tt class="docutils literal"><span class="pre">flush()</span></tt> has been issued for all attached databases, the <tt class="docutils literal"><span class="pre">prepare()</span></tt> method on each database’s <tt class="docutils literal"><span class="pre">TwoPhaseTransaction</span></tt> will be called. This allows each database to roll back the entire transaction, before each transaction is committed.</li> <li><strong>weak_identity_map</strong> – When set to the default value of <tt class="xref docutils literal"><span class="pre">True</span></tt>, a weak-referencing map is used; instances which are not externally referenced will be garbage collected immediately. For dereferenced instances which have pending changes present, the attribute management system will create a temporary strong-reference to the object which lasts until the changes are flushed to the database, at which point it’s again dereferenced. Alternatively, when using the value <tt class="xref docutils literal"><span class="pre">False</span></tt>, the identity map uses a regular Python dictionary to store instances. The session will maintain all instances present until they are removed using expunge(), clear(), or purge().</li> </ul> </td> </tr> </tbody> </table> </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>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>Arguments 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> are described using the <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-func docutils literal"><span class="pre">sessionmaker()</span></tt></a> function, which is the typical point of entry.</p> </dd></dl> <dl class="method"> <dt id="sqlalchemy.orm.session.Session.add"> <tt class="descname">add</tt><big>(</big><em>instance</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 Session.</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</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 <tt class="docutils literal"><span class="pre">Engine</span></tt> or <tt class="docutils literal"><span class="pre">Connection</span></tt>.</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 <tt class="docutils literal"><span class="pre">Table</span></tt> instance</dd> <dt>bind</dt> <dd>Any Connectable: a <tt class="docutils literal"><span class="pre">Engine</span></tt> or <tt class="docutils literal"><span class="pre">Connection</span></tt>.</dd> </dl> <p>All subsequent operations involving this <tt class="docutils literal"><span class="pre">Table</span></tt> 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><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 InvalidRequestError.</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-func 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>For a session configured with autocommit=False, 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> </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><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.base.Connection" title="sqlalchemy.engine.base.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.base.Connection" title="sqlalchemy.engine.base.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.base.Connection" title="sqlalchemy.engine.base.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> returned.</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.base.Connection" title="sqlalchemy.engine.base.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.base.Engine.contextual_connect" title="sqlalchemy.engine.base.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.base.Engine" title="sqlalchemy.engine.base.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"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><strong>mapper</strong> – 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><strong>clause</strong> – A <a class="reference internal" href="../core/expression_api.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/expression_api.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/expression_api.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> </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>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 is_modified() method.</p> </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>**kw</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.execute" title="Permalink to this definition">¶</a></dt> <dd><p>Execute a clause within the current transaction.</p> <p>Returns a <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.base.ResultProxy" title="sqlalchemy.engine.base.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.base.Engine" title="sqlalchemy.engine.base.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.base.Connection" title="sqlalchemy.engine.base.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a>.</p> <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/expression_api.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/expression_api.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/expression_api.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/expression_api.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/expression_api.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>, and additionally accepts plain strings that represent SQL statements. If a plain string is passed, it is first converted to a <a class="reference internal" href="../core/expression_api.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, which here means that bind parameters should be specified using the format <tt class="docutils literal"><span class="pre">:param</span></tt>.</p> <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>, using the same behavior as that of 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 to determine the active <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.base.Connection" title="sqlalchemy.engine.base.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a>. The <tt class="docutils literal"><span class="pre">close_with_result</span></tt> flag is set to <tt class="xref docutils literal"><span class="pre">True</span></tt> so that an <tt class="docutils literal"><span class="pre">autocommit=True</span></tt> <a class="reference internal" href="#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 no active transaction will produce a result that auto-closes the underlying <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.base.Connection" title="sqlalchemy.engine.base.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</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"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><strong>clause</strong> – A <a class="reference internal" href="../core/expression_api.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/expression_api.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/expression_api.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.) or string SQL statement to be executed. The clause will also be used to locate a bind, 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 not bound to a single engine already, and the <tt class="docutils literal"><span class="pre">mapper</span></tt> argument is not passed.</li> <li><strong>params</strong> – Optional dictionary of bind names mapped to values.</li> <li><strong>mapper</strong> – 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.</li> <li><strong>**kw</strong> – 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.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"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><strong>instance</strong> – The instance to be refreshed.</li> <li><strong>attribute_names</strong> – 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="xref 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> <dl class="docutils"> <dt>objects</dt> <dd>Optional; a list or tuple collection. Restricts the flush operation to only these objects, rather than all pending changes. Deprecated - this flag prevents the session from properly maintaining accounting among inter-object relations and can cause invalid results.</dd> </dl> </dd></dl> <dl class="method"> <dt id="sqlalchemy.orm.session.Session.get_bind"> <tt class="descname">get_bind</tt><big>(</big><em>mapper</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 an engine corresponding to the given arguments.</p> <p>All arguments are optional.</p> <dl class="docutils"> <dt>mapper</dt> <dd>Optional, a <tt class="docutils literal"><span class="pre">Mapper</span></tt> or mapped class</dd> <dt>clause</dt> <dd>Optional, A ClauseElement (i.e. select(), text(), etc.)</dd> </dl> </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 Session has an active transaction.</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=False</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="xref docutils literal"><span class="pre">True</span></tt> if instance has modified attributes.</p> <p>This method retrieves a history instance for each instrumented attribute on the instance and performs a comparison of the current value to its previously committed value.</p> <p><tt class="docutils literal"><span class="pre">include_collections</span></tt> indicates if multivalued collections should be included in the operation. Setting this to False 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.</p> <p>The <tt class="docutils literal"><span class="pre">passive</span></tt> flag indicates if unloaded attributes and collections should not be loaded in the course of performing this test.</p> <p>A few caveats to this method apply:</p> <ul> <li><p class="first">Instances present in the ‘dirty’ collection may result in a value of <tt class="xref docutils literal"><span class="pre">False</span></tt> when tested with this method. This because while the object may have received attribute set events, there may be no net changes on its state.</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 only if the attribute container has the “active_history” flag set to <tt class="xref docutils literal"><span class="pre">True</span></tt>. This flag is set typically for primary key attributes and scalar references that are not a simple many-to-one.</p> </li> </ul> </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>, <em>**kw</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.merge" title="Permalink to this definition">¶</a></dt> <dd><p>Copy the state an instance onto the persistent instance with the same identifier.</p> <p>If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent instance. The given instance does not become associated with the session.</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> </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="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><p>Return the <tt class="docutils literal"><span class="pre">Session</span></tt> to which an object belongs.</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 InvalidRequestError.</p> <p>Only root transactions of two phase sessions can be prepared. If the current transaction is not such, an InvalidRequestError 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> <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 <tt class="docutils literal"><span class="pre">Query</span></tt> object corresponding to this <tt class="docutils literal"><span class="pre">Session</span></tt>.</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"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><strong>attribute_names</strong> – optional. An iterable collection of string attribute names indicating a subset of attributes to be refreshed.</li> <li><strong>lockmode</strong> – 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 begin() is called multiple times.</p> </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>**kw</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.scalar" title="Permalink to this definition">¶</a></dt> <dd><p>Like execute() but return a scalar result.</p> </dd></dl> </dd></dl> </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>A common need in applications, particularly those built around web frameworks, is the ability to “share” 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> object among disparate parts of an application, without needing to pass the object explicitly to all method and function calls. What you’re really looking for is some kind of “global” session object, or at least “global” to all the parts of an application which are tasked with servicing the current request. For this pattern, SQLAlchemy provides the ability to enhance 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> class generated by <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-func docutils literal"><span class="pre">sessionmaker()</span></tt></a> to provide auto-contextualizing support. This means that whenever you 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> instance with its constructor, you get an <em>existing</em> <a class="reference internal" href="#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 which is bound to some “context”. By default, this context is the current thread. This feature is what previously was accomplished using the <tt class="docutils literal"><span class="pre">sessioncontext</span></tt> SQLAlchemy extension.</p> <div class="section" id="creating-a-thread-local-context"> <h3>Creating a Thread-local Context<a class="headerlink" href="#creating-a-thread-local-context" title="Permalink to this headline">¶</a></h3> <p>The <a class="reference internal" href="#sqlalchemy.orm.scoped_session" title="sqlalchemy.orm.scoped_session"><tt class="xref py py-func docutils literal"><span class="pre">scoped_session()</span></tt></a> function wraps around the <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-func docutils literal"><span class="pre">sessionmaker()</span></tt></a> function, and produces an object which behaves the same 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> subclass returned by <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-func docutils literal"><span class="pre">sessionmaker()</span></tt></a>:</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">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></pre></div> </div> <p>However, when you instantiate 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> “class”, in reality the object is pulled from a threadlocal variable, or if it doesn’t exist yet, it’s created using the underlying class generated by <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-func docutils literal"><span class="pre">sessionmaker()</span></tt></a>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="c"># call Session() the first time. the new Session instance is created.</span> <span class="gp">>>> </span><span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span> <span class="gp">>>> </span><span class="c"># later, in the same application thread, someone else calls Session()</span> <span class="gp">>>> </span><span class="n">session2</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span> <span class="gp">>>> </span><span class="c"># the two Session objects are *the same* object</span> <span class="gp">>>> </span><span class="n">session</span> <span class="ow">is</span> <span class="n">session2</span> <span class="go">True</span></pre></div> </div> <p>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> constructor now returns 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 every time within the current thread, the object returned by <a class="reference internal" href="#sqlalchemy.orm.scoped_session" title="sqlalchemy.orm.scoped_session"><tt class="xref py py-func docutils literal"><span class="pre">scoped_session()</span></tt></a> also implements most 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> methods and properties at the “class” level, such that you don’t even need 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>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="c"># create some objects</span> <span class="n">u1</span> <span class="o">=</span> <span class="n">User</span><span class="p">()</span> <span class="n">u2</span> <span class="o">=</span> <span class="n">User</span><span class="p">()</span> <span class="c"># save to the contextual session, without instantiating</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="c"># view the "new" attribute</span> <span class="k">assert</span> <span class="n">u1</span> <span class="ow">in</span> <span class="n">Session</span><span class="o">.</span><span class="n">new</span> <span class="c"># commit changes</span> <span class="n">Session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span></pre></div> </div> <p>The contextual session may be disposed of by calling <tt class="docutils literal"><span class="pre">Session.remove()</span></tt>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="c"># remove current contextual session</span> <span class="n">Session</span><span class="o">.</span><span class="n">remove</span><span class="p">()</span></pre></div> </div> <p>After <tt class="docutils literal"><span class="pre">remove()</span></tt> is called, the next operation with the contextual session will start 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> for the current thread.</p> </div> <div class="section" id="lifespan-of-a-contextual-session"> <span id="session-lifespan"></span><h3>Lifespan of a Contextual Session<a class="headerlink" href="#lifespan-of-a-contextual-session" title="Permalink to this headline">¶</a></h3> <p>A (really, really) common question is when does the contextual session get created, when does it get disposed ? We’ll consider a typical lifespan as used in a web application:</p> <div class="highlight-python"><pre>Web Server Web Framework User-defined Controller Call -------------- -------------- ------------------------------ web request -> call controller -> # call Session(). this establishes a new, # contextual Session. session = Session() # load some objects, save some changes objects = session.query(MyClass).all() # some other code calls Session, it's the # same contextual session as "sess" session2 = Session() session2.add(foo) session2.commit() # generate content to be returned return generate_content() Session.remove() <- web response <-</pre> </div> <p>The above example illustrates an explicit call to <a class="reference internal" href="#sqlalchemy.orm.scoping.ScopedSession.remove" title="sqlalchemy.orm.scoping.ScopedSession.remove"><tt class="xref py py-meth docutils literal"><span class="pre">ScopedSession.remove()</span></tt></a>. This has the effect such that each web request starts fresh with a brand new session, and is the most definitive approach to closing out a request.</p> <p>It’s not strictly necessary to remove the session at the end of the request - other options include calling <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>, <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>, <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> at the end so that the existing session returns its connections to the pool and removes any existing transactional context. Doing nothing is an option too, if individual controller methods take responsibility for ensuring that no transactions remain open after a request ends.</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="function"> <dt id="sqlalchemy.orm.scoped_session"> <tt class="descclassname">sqlalchemy.orm.</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.scoped_session" title="Permalink to this definition">¶</a></dt> <dd><p>Provides thread-local or 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>This is a front-end function to <a class="reference internal" href="#sqlalchemy.orm.scoping.ScopedSession" title="sqlalchemy.orm.scoping.ScopedSession"><tt class="xref py py-class docutils literal"><span class="pre">ScopedSession</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"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first simple"> <li><strong>session_factory</strong> – a callable function that produces <a class="reference internal" href="#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, such as <a class="reference internal" href="#sqlalchemy.orm.session.sessionmaker" title="sqlalchemy.orm.session.sessionmaker"><tt class="xref py py-func docutils literal"><span class="pre">sessionmaker()</span></tt></a>.</li> <li><strong>scopefunc</strong> – Optional “scope” function which would be passed to the <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>. If None, the <a class="reference internal" href="#sqlalchemy.util.ThreadLocalRegistry" title="sqlalchemy.util.ThreadLocalRegistry"><tt class="xref py py-class docutils literal"><span class="pre">ThreadLocalRegistry</span></tt></a> is used by default.</li> </ul> </td> </tr> <tr class="field"><th class="field-name">Returns:</th><td class="field-body"><p class="first last">an <a class="reference internal" href="#sqlalchemy.orm.scoping.ScopedSession" title="sqlalchemy.orm.scoping.ScopedSession"><tt class="xref py py-class docutils literal"><span class="pre">ScopedSession</span></tt></a> instance</p> </td> </tr> </tbody> </table> <p>Usage:</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="n">autoflush</span><span class="o">=</span><span class="bp">True</span><span class="p">))</span></pre></div> </div> <p>To instantiate a Session object which is part of the scoped context, instantiate normally:</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="p">()</span></pre></div> </div> <p>Most session methods are available as classmethods from the scoped session:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">Session</span><span class="o">.</span><span class="n">commit</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> </dd></dl> <dl class="class"> <dt id="sqlalchemy.orm.scoping.ScopedSession"> <em class="property">class </em><tt class="descclassname">sqlalchemy.orm.scoping.</tt><tt class="descname">ScopedSession</tt><big>(</big><em>session_factory</em>, <em>scopefunc=None</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.scoping.ScopedSession" title="Permalink to this definition">¶</a></dt> <dd><p>Provides thread-local management of Sessions.</p> <p>Usage:</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></pre></div> </div> <p>... use Session normally.</p> <p>The internal registry is accessible as well, and by default is an instance of <a class="reference internal" href="#sqlalchemy.util.ThreadLocalRegistry" title="sqlalchemy.util.ThreadLocalRegistry"><tt class="xref py py-class docutils literal"><span class="pre">ThreadLocalRegistry</span></tt></a>.</p> <dl class="method"> <dt id="sqlalchemy.orm.scoping.ScopedSession.__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.ScopedSession.__init__" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="method"> <dt id="sqlalchemy.orm.scoping.ScopedSession.configure"> <tt class="descname">configure</tt><big>(</big><em>**kwargs</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.scoping.ScopedSession.configure" title="Permalink to this definition">¶</a></dt> <dd><p>reconfigure the sessionmaker used by this ScopedSession.</p> </dd></dl> <dl class="method"> <dt id="sqlalchemy.orm.scoping.ScopedSession.mapper"> <tt class="descname">mapper</tt><big>(</big><em>*args</em>, <em>**kwargs</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.scoping.ScopedSession.mapper" title="Permalink to this definition">¶</a></dt> <dd><p>return a <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> function which associates this ScopedSession with the Mapper.</p> <p class="deprecated"> <span class="versionmodified">Deprecated since version 0.5: </span><a class="reference internal" href="#sqlalchemy.orm.scoping.ScopedSession.mapper" title="sqlalchemy.orm.scoping.ScopedSession.mapper"><tt class="xref py py-meth docutils literal"><span class="pre">ScopedSession.mapper()</span></tt></a> is deprecated. Please see <a class="reference external" href="http://www.sqlalchemy.org/trac/wiki/UsageRecipes/SessionAwareMapper">http://www.sqlalchemy.org/trac/wiki/UsageRecipes/SessionAwareMapper</a> for information on how to replicate its behavior.</p> </dd></dl> <dl class="method"> <dt id="sqlalchemy.orm.scoping.ScopedSession.query_property"> <tt class="descname">query_property</tt><big>(</big><em>query_cls=None</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.scoping.ScopedSession.query_property" title="Permalink to this definition">¶</a></dt> <dd><p>return a class property which produces a <cite>Query</cite> object against the class 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.ScopedSession.remove"> <tt class="descname">remove</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.orm.scoping.ScopedSession.remove" title="Permalink to this definition">¶</a></dt> <dd><p>Dispose of the current contextual session.</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"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><strong>createfunc</strong> – a callable that returns a new object to be placed in the registry</li> <li><strong>scopefunc</strong> – 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"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><strong>createfunc</strong> – A creation function that will generate a new value for the current scope, if none is present.</li> <li><strong>scopefunc</strong> – 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 forthe 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>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="vertical-partitioning"> <h3>Vertical Partitioning<a class="headerlink" href="#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> </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="session-utilities"> <h2>Session Utilities<a class="headerlink" href="#session-utilities" title="Permalink to this headline">¶</a></h2> <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"> <h2>Attribute and State Management Utilities<a class="headerlink" href="#attribute-and-state-management-utilities" title="Permalink to this headline">¶</a></h2> <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="interfaces.html"><em>ORM Event Interfaces</em></a>.</p> <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>**kwargs</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"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><strong>obj</strong> – an object whose class is instrumented by the attributes package.</li> <li><strong>key</strong> – string attribute name.</li> <li><strong>kwargs</strong> – Optional keyword arguments currently include the <tt class="docutils literal"><span class="pre">passive</span></tt> flag, which indicates if the attribute should be loaded from the database if not already present (<tt class="xref py py-attr docutils literal"><span class="pre">PASSIVE_NO_FETCH</span></tt>), and if the attribute should be not initialized to a blank value otherwise (<tt class="xref py py-attr docutils literal"><span class="pre">PASSIVE_NO_INITIALIZE</span></tt>). Default is <tt class="xref py py-attr docutils literal"><span class="pre">PASSIVE_OFF</span></tt>.</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> <dl class="docutils"> <dt>For an easier way to do the above, see</dt> <dd><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>.</dd> </dl> <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.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 <tt class="xref py py-class docutils literal"><span class="pre">InstanceState</span></tt> for a given object.</p> </dd></dl> <dl class="function"> <dt id="sqlalchemy.orm.attributes.is_instrumented"> <tt class="descclassname">sqlalchemy.orm.attributes.</tt><tt class="descname">is_instrumented</tt><big>(</big><em>instance</em>, <em>key</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.attributes.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.manager_of_class"> <tt class="descclassname">sqlalchemy.orm.attributes.</tt><tt class="descname">manager_of_class</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.orm.attributes.manager_of_class" title="Permalink to this definition">¶</a></dt> <dd><p>Return the <tt class="xref py py-class docutils literal"><span class="pre">ClassManager</span></tt> for a given class.</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>A 3-tuple of added, unchanged and deleted values, representing the changes which have occurred on an instrumented attribute.</p> <p>Each tuple member is an iterable sequence.</p> <dl class="attribute"> <dt id="sqlalchemy.orm.attributes.History.added"> <tt class="descname">added</tt><a class="headerlink" href="#sqlalchemy.orm.attributes.History.added" title="Permalink to this definition">¶</a></dt> <dd><p>Return the collection of items added to the attribute (the first tuple element).</p> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.attributes.History.deleted"> <tt class="descname">deleted</tt><a class="headerlink" href="#sqlalchemy.orm.attributes.History.deleted" title="Permalink to this definition">¶</a></dt> <dd><p>Return the collection of items that have been removed from the attribute (the third tuple element).</p> </dd></dl> <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> <dl class="attribute"> <dt id="sqlalchemy.orm.attributes.History.unchanged"> <tt class="descname">unchanged</tt><a class="headerlink" href="#sqlalchemy.orm.attributes.History.unchanged" title="Permalink to this definition">¶</a></dt> <dd><p>Return the collection of items that have not changed on the attribute (the second tuple element).</p> </dd></dl> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.attributes.sqlalchemy.orm.attributes.PASSIVE_NO_INITIALIZE"> <tt class="descclassname">sqlalchemy.orm.attributes.</tt><tt class="descname">PASSIVE_NO_INITIALIZE</tt><a class="headerlink" href="#sqlalchemy.orm.attributes.sqlalchemy.orm.attributes.PASSIVE_NO_INITIALIZE" title="Permalink to this definition">¶</a></dt> <dd><p>Symbol indicating that loader callables should not be fired off, and a non-initialized attribute should remain that way.</p> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.attributes.sqlalchemy.orm.attributes.PASSIVE_NO_FETCH"> <tt class="descclassname">sqlalchemy.orm.attributes.</tt><tt class="descname">PASSIVE_NO_FETCH</tt><a class="headerlink" href="#sqlalchemy.orm.attributes.sqlalchemy.orm.attributes.PASSIVE_NO_FETCH" title="Permalink to this definition">¶</a></dt> <dd><p>Symbol indicating that loader callables should not boe fired off. Non-initialized attributes should be initialized to an empty value.</p> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.attributes.sqlalchemy.orm.attributes.PASSIVE_OFF"> <tt class="descclassname">sqlalchemy.orm.attributes.</tt><tt class="descname">PASSIVE_OFF</tt><a class="headerlink" href="#sqlalchemy.orm.attributes.sqlalchemy.orm.attributes.PASSIVE_OFF" title="Permalink to this definition">¶</a></dt> <dd><p>Symbol indicating that loader callables should be executed.</p> </dd></dl> </div> </div> </div> </div> <div class="bottomnav"> Previous: <a href="inheritance.html" title="previous chapter">Mapping Class Inheritance Hierarchies</a> Next: <a href="query.html" title="next chapter">Querying</a> <div class="doc_copyright"> © <a href="../copyright.html">Copyright</a> 2007-2011, the SQLAlchemy authors and contributors. Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.0.7. </div> </div> </body> </html>