~ubuntu-branches/debian/sid/sqlalchemy/sid

« back to all changes in this revision

Viewing changes to doc/orm/session.html

  • Committer: Bazaar Package Importer
  • Author(s): Piotr Ożarowski
  • Date: 2011-03-27 14:22:50 UTC
  • mfrom: (16.1.9 experimental)
  • Revision ID: james.westby@ubuntu.com-20110327142250-aip46dv6a3r2jwvs
Tags: 0.6.6-2
Upload to unstable

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 
2
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
3
 
 
4
<html>
 
5
    <head>
 
6
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 
7
        
 
8
        <title>
 
9
    Using the Session
 
10
 &mdash; SQLAlchemy 0.6.6 Documentation</title>
 
11
        
 
12
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
 
13
    <link rel="stylesheet" href="../_static/docs.css" type="text/css" />
 
14
 
 
15
    <script type="text/javascript">
 
16
      var DOCUMENTATION_OPTIONS = {
 
17
          URL_ROOT:    '../',
 
18
          VERSION:     '0.6.6',
 
19
          COLLAPSE_MODINDEX: false,
 
20
          FILE_SUFFIX: '.html'
 
21
      };
 
22
    </script>
 
23
        <script type="text/javascript" src="../_static/jquery.js"></script>
 
24
        <script type="text/javascript" src="../_static/underscore.js"></script>
 
25
        <script type="text/javascript" src="../_static/doctools.js"></script>
 
26
    <script type="text/javascript" src="../_static/init.js"></script>
 
27
    <link rel="index" title="Index" href="../genindex.html" />
 
28
    <link rel="search" title="Search" href="../search.html" />
 
29
        <link rel="copyright" title="Copyright" href="../copyright.html" />
 
30
    <link rel="top" title="SQLAlchemy 0.6.6 Documentation" href="../index.html" />
 
31
        <link rel="up" title="SQLAlchemy ORM" href="index.html" />
 
32
        <link rel="next" title="Querying" href="query.html" />
 
33
        <link rel="prev" title="Mapping Class Inheritance Hierarchies" href="inheritance.html" />
 
34
    
 
35
 
 
36
    </head>
 
37
    <body>
 
38
        
 
39
 
 
40
 
 
41
 
 
42
 
 
43
        <h1>SQLAlchemy 0.6.6 Documentation</h1>
 
44
 
 
45
        <div id="search">
 
46
        Search:
 
47
        <form class="search" action="../search.html" method="get">
 
48
          <input type="text" name="q" size="18" /> <input type="submit" value="Search" />
 
49
          <input type="hidden" name="check_keywords" value="yes" />
 
50
          <input type="hidden" name="area" value="default" />
 
51
        </form>
 
52
        </div>
 
53
 
 
54
        <div class="versionheader">
 
55
            Version: <span class="versionnum">0.6.6</span> Last Updated: 01/08/2011 17:20:49
 
56
        </div>
 
57
        <div class="clearboth"></div>
 
58
 
 
59
        <div class="topnav">
 
60
            <div id="pagecontrol">
 
61
                <a href="../genindex.html">Index</a>
 
62
 
 
63
                <div class="sourcelink">(<a href="../_sources/orm/session.txt">view source)</div>
 
64
            </div>
 
65
 
 
66
            <div class="navbanner">
 
67
                <a class="totoc" href="../index.html">Table of Contents</a>
 
68
                        » <a href="index.html" title="SQLAlchemy ORM">SQLAlchemy ORM</a>
 
69
                » 
 
70
    Using the Session
 
71
 
 
72
 
 
73
                
 
74
<div class="prevnext">
 
75
        Previous:
 
76
        <a href="inheritance.html" title="previous chapter">Mapping Class Inheritance Hierarchies</a>
 
77
        Next:
 
78
        <a href="query.html" title="next chapter">Querying</a>
 
79
</div>
 
80
 
 
81
                <h2>
 
82
                    
 
83
    Using the Session
 
84
 
 
85
                </h2>
 
86
            </div>
 
87
                <ul>
 
88
<li><a class="reference internal" href="#">Using the Session</a><ul>
 
89
<li><a class="reference internal" href="#what-does-the-session-do">What does the Session do ?</a></li>
 
90
<li><a class="reference internal" href="#getting-a-session">Getting a Session</a></li>
 
91
<li><a class="reference internal" href="#id1">Using the Session</a><ul>
 
92
<li><a class="reference internal" href="#quickie-intro-to-object-states">Quickie Intro to Object States</a></li>
 
93
<li><a class="reference internal" href="#frequently-asked-questions">Frequently Asked Questions</a></li>
 
94
<li><a class="reference internal" href="#querying">Querying</a></li>
 
95
<li><a class="reference internal" href="#adding-new-or-existing-items">Adding New or Existing Items</a></li>
 
96
<li><a class="reference internal" href="#merging">Merging</a><ul>
 
97
<li><a class="reference internal" href="#merge-tips">Merge Tips</a></li>
 
98
</ul>
 
99
</li>
 
100
<li><a class="reference internal" href="#deleting">Deleting</a><ul>
 
101
<li><a class="reference internal" href="#deleting-based-on-filter-criterion">Deleting based on Filter Criterion</a></li>
 
102
</ul>
 
103
</li>
 
104
<li><a class="reference internal" href="#flushing">Flushing</a></li>
 
105
<li><a class="reference internal" href="#committing">Committing</a></li>
 
106
<li><a class="reference internal" href="#rolling-back">Rolling Back</a></li>
 
107
<li><a class="reference internal" href="#expunging">Expunging</a></li>
 
108
<li><a class="reference internal" href="#closing">Closing</a></li>
 
109
<li><a class="reference internal" href="#refreshing-expiring">Refreshing / Expiring</a></li>
 
110
<li><a class="reference internal" href="#session-attributes">Session Attributes</a></li>
 
111
</ul>
 
112
</li>
 
113
<li><a class="reference internal" href="#cascades">Cascades</a></li>
 
114
<li><a class="reference internal" href="#managing-transactions">Managing Transactions</a><ul>
 
115
<li><a class="reference internal" href="#using-savepoint">Using SAVEPOINT</a></li>
 
116
<li><a class="reference internal" href="#using-subtransactions">Using Subtransactions</a></li>
 
117
<li><a class="reference internal" href="#enabling-two-phase-commit">Enabling Two-Phase Commit</a></li>
 
118
</ul>
 
119
</li>
 
120
<li><a class="reference internal" href="#embedding-sql-insert-update-expressions-into-a-flush">Embedding SQL Insert/Update Expressions into a Flush</a></li>
 
121
<li><a class="reference internal" href="#using-sql-expressions-with-sessions">Using SQL Expressions with Sessions</a></li>
 
122
<li><a class="reference internal" href="#joining-a-session-into-an-external-transaction">Joining a Session into an External Transaction</a></li>
 
123
<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>
 
124
<li><a class="reference internal" href="#contextual-thread-local-sessions">Contextual/Thread-local Sessions</a><ul>
 
125
<li><a class="reference internal" href="#creating-a-thread-local-context">Creating a Thread-local Context</a></li>
 
126
<li><a class="reference internal" href="#lifespan-of-a-contextual-session">Lifespan of a Contextual Session</a></li>
 
127
<li><a class="reference internal" href="#contextual-session-api">Contextual Session API</a></li>
 
128
</ul>
 
129
</li>
 
130
<li><a class="reference internal" href="#partitioning-strategies">Partitioning Strategies</a><ul>
 
131
<li><a class="reference internal" href="#vertical-partitioning">Vertical Partitioning</a></li>
 
132
<li><a class="reference internal" href="#horizontal-partitioning">Horizontal Partitioning</a></li>
 
133
</ul>
 
134
</li>
 
135
<li><a class="reference internal" href="#session-utilities">Session Utilities</a></li>
 
136
<li><a class="reference internal" href="#attribute-and-state-management-utilities">Attribute and State Management Utilities</a></li>
 
137
</ul>
 
138
</li>
 
139
</ul>
 
140
 
 
141
            <div class="clearboth"></div>
 
142
        </div>
 
143
 
 
144
        <div class="document">
 
145
            <div class="body">
 
146
                
 
147
<div class="section" id="module-sqlalchemy.orm.session">
 
148
<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>
 
149
<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"><tt class="xref py py-mod docutils literal"><span class="pre">declarative</span></tt></a> extensions
 
150
are the primary configurational interface for the ORM. Once mappings are
 
151
configured, the primary usage interface for persistence operations is the
 
152
<a class="reference internal" href="#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>
 
153
<div class="section" id="what-does-the-session-do">
 
154
<h2>What does the Session do ?<a class="headerlink" href="#what-does-the-session-do" title="Permalink to this headline">¶</a></h2>
 
155
<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
 
156
conversations with the database and represents a &#8220;holding zone&#8221; for all the
 
157
objects which you&#8217;ve loaded or associated with it during its lifespan. It
 
158
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
 
159
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&#8217;s current database
 
160
connection, populating result rows into objects that are then stored in the
 
161
<a class="reference internal" href="#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
 
162
that maintains unique copies of each object, where &#8220;unique&#8221; means &#8220;only one
 
163
object with a particular primary key&#8221;.</p>
 
164
<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
 
165
are issued or other objects are persisted with it, it requests a connection
 
166
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
 
167
<a class="reference internal" href="#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
 
168
operated upon. This connection represents an ongoing transaction, which
 
169
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
 
170
back its pending state.</p>
 
171
<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
 
172
the database is queried again or before the current transaction is committed,
 
173
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
 
174
of Work</a> pattern.</p>
 
175
<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&#8217;s important to note that the objects
 
176
which are associated with it are <strong>proxy objects</strong> to the transaction being
 
177
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
 
178
objects to re-access the database in order to keep synchronized.   It is
 
179
possible to &#8220;detach&#8221; 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
 
180
them, though this practice has its caveats.  It&#8217;s intended that
 
181
usually, you&#8217;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
 
182
want to work with them again, so that they can resume their normal task of
 
183
representing database state.</p>
 
184
</div>
 
185
<div class="section" id="getting-a-session">
 
186
<h2>Getting a Session<a class="headerlink" href="#getting-a-session" title="Permalink to this headline">¶</a></h2>
 
187
<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
 
188
be directly instantiated. However, to standardize how sessions are configured
 
189
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
 
190
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>
 
191
configuration which can then be used throughout an application without the
 
192
need to repeat the configurational arguments.</p>
 
193
<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>
 
194
<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>
 
195
 
 
196
<span class="c"># create a configured &quot;Session&quot; class</span>
 
197
<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>
 
198
 
 
199
<span class="c"># create a Session</span>
 
200
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
 
201
 
 
202
<span class="c"># work with sess</span>
 
203
<span class="n">myobject</span> <span class="o">=</span> <span class="n">MyObject</span><span class="p">(</span><span class="s">&#39;foo&#39;</span><span class="p">,</span> <span class="s">&#39;bar&#39;</span><span class="p">)</span>
 
204
<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>
 
205
<span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span></pre></div>
 
206
</div>
 
207
<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,
 
208
which we assign to the name <tt class="docutils literal"><span class="pre">Session</span></tt>. This class is a subclass of the
 
209
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
 
210
use the arguments we&#8217;ve given the function, in this case
 
211
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>
 
212
<p>When you write your application, place the call to
 
213
<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
 
214
<tt class="docutils literal"><span class="pre">Session</span></tt> class available to the rest of your application.</p>
 
215
<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>,
 
216
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>
 
217
to acquire connection resources.   This association can
 
218
be set up as in the example above, using the <tt class="docutils literal"><span class="pre">bind</span></tt> argument.   You
 
219
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>
 
220
using the <tt class="xref py py-meth docutils literal"><span class="pre">sessionmaker.configure()</span></tt> method:</p>
 
221
<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>
 
222
<span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">create_engine</span>
 
223
 
 
224
<span class="c"># configure Session class with desired options</span>
 
225
<span class="n">Session</span> <span class="o">=</span> <span class="n">sessionmaker</span><span class="p">()</span>
 
226
 
 
227
<span class="c"># later, we create the engine</span>
 
228
<span class="n">engine</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">&#39;postgresql://...&#39;</span><span class="p">)</span>
 
229
 
 
230
<span class="c"># associate it with our custom Session class</span>
 
231
<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>
 
232
 
 
233
<span class="c"># work with the session</span>
 
234
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span></pre></div>
 
235
</div>
 
236
<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>
 
237
on each invocation:</p>
 
238
<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>
 
239
</div>
 
240
<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>
 
241
<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>
 
242
<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>
 
243
</div>
 
244
<p>While the rationale for the above example may not be apparent, the typical
 
245
usage is in a test fixture that maintains an external transaction - see
 
246
<a class="reference internal" href="#session-external-transaction"><em>Joining a Session into an External Transaction</em></a> below for a full example.</p>
 
247
</div>
 
248
<div class="section" id="id1">
 
249
<h2>Using the Session<a class="headerlink" href="#id1" title="Permalink to this headline">¶</a></h2>
 
250
<div class="section" id="quickie-intro-to-object-states">
 
251
<h3>Quickie Intro to Object States<a class="headerlink" href="#quickie-intro-to-object-states" title="Permalink to this headline">¶</a></h3>
 
252
<p>It&#8217;s helpful to know the states which an instance can have within a session:</p>
 
253
<ul class="simple">
 
254
<li><em>Transient</em> - an instance that&#8217;s not in a session, and is not saved to the
 
255
database; i.e. it has no database identity. The only relationship such an
 
256
object has to the ORM is that its class has a <tt class="docutils literal"><span class="pre">mapper()</span></tt> associated with
 
257
it.</li>
 
258
<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
 
259
instance, it becomes pending. It still wasn&#8217;t actually flushed to the
 
260
database yet, but it will be when the next flush occurs.</li>
 
261
<li><em>Persistent</em> - An instance which is present in the session and has a record
 
262
in the database. You get persistent instances by either flushing so that the
 
263
pending instances become persistent, or by querying the database for
 
264
existing instances (or moving persistent instances from other sessions into
 
265
your local session).</li>
 
266
<li><em>Detached</em> - an instance which has a record in the database, but is not in
 
267
any session. There&#8217;s nothing wrong with this, and you can use objects
 
268
normally when they&#8217;re detached, <strong>except</strong> they will not be able to issue
 
269
any SQL in order to load collections or attributes which are not yet loaded,
 
270
or were marked as &#8220;expired&#8221;.</li>
 
271
</ul>
 
272
<p>Knowing these states is important, since the
 
273
<a class="reference internal" href="#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
 
274
operations (such as trying to save the same object to two different sessions
 
275
at the same time).</p>
 
276
</div>
 
277
<div class="section" id="frequently-asked-questions">
 
278
<h3>Frequently Asked Questions<a class="headerlink" href="#frequently-asked-questions" title="Permalink to this headline">¶</a></h3>
 
279
<ul>
 
280
<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>
 
281
<blockquote>
 
282
<p>Just one time, somewhere in your application&#8217;s global scope. It should be
 
283
looked upon as part of your application&#8217;s configuration. If your
 
284
application has three .py files in a package, you could, for example,
 
285
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
 
286
that point on your other modules say &#8220;from mypackage import Session&#8221;. That
 
287
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>,
 
288
and the configuration of that session is controlled by that central point.</p>
 
289
<p>If your application starts up, does imports, but does not know what
 
290
database it&#8217;s going to be connecting to, you can bind the
 
291
<a class="reference internal" href="#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 &#8220;class&#8221; level to the
 
292
engine later on, using <tt class="docutils literal"><span class="pre">configure()</span></tt>.</p>
 
293
<p>In the examples in this section, we will frequently show the
 
294
<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
 
295
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&#8217;s just for
 
296
example&#8217;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
 
297
at the module level, and your individual
 
298
<a class="reference internal" href="#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
 
299
throughout your app, such as in a web application within each controller
 
300
method.</p>
 
301
</blockquote>
 
302
</li>
 
303
<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>
 
304
<blockquote>
 
305
<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
 
306
database, and want to save some objects or load some existing ones. It
 
307
then remains in use for the lifespan of a particular database
 
308
conversation, which includes not just the initial loading of objects but
 
309
throughout the whole usage of those instances.</p>
 
310
<p>Objects become detached if their owning session is discarded. They are
 
311
still functional in the detached state if the user has ensured that their
 
312
state has not been expired before detachment, but they will not be able to
 
313
represent the current state of database data. Because of this, it&#8217;s best
 
314
to consider persisted objects as an extension of the state of a particular
 
315
<a class="reference internal" href="#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
 
316
objects have been discarded.</p>
 
317
<p>An exception to this is when objects are placed in caches or otherwise
 
318
shared among threads or processes, in which case their detached state can
 
319
be stored, transmitted, or shared. However, the state of detached objects
 
320
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
 
321
<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
 
322
object (or in the case of merge, its state) again.</p>
 
323
<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
 
324
objects are only referenced by a single thread.  Sharing objects between
 
325
threads is most safely accomplished by sharing their state among multiple
 
326
instances of those objects, each associated with a distinct
 
327
<a class="reference internal" href="#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
 
328
between threads.   This pattern is not a strict requirement by any means,
 
329
but it has the least chance of introducing concurrency issues.</p>
 
330
<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,
 
331
<a class="reference internal" href="#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
 
332
<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
 
333
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
 
334
in web applications so that a single global variable can be used to safely
 
335
represent transactional sessions with sets of objects, localized to a
 
336
single thread. More on this object is in <a class="reference internal" href="#unitofwork-contextual"><em>Contextual/Thread-local Sessions</em></a>.</p>
 
337
</blockquote>
 
338
</li>
 
339
<li><p class="first">Is the Session a cache ?</p>
 
340
<blockquote>
 
341
<p>Yeee...no. It&#8217;s somewhat used as a cache, in that it implements the
 
342
identity map pattern, and stores objects keyed to their primary key.
 
343
However, it doesn&#8217;t do any kind of query caching. This means, if you say
 
344
<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>
 
345
is right there, in the identity map, the session has no idea about that.
 
346
It has to issue SQL to the database, get the rows back, and then when it
 
347
sees the primary key in the row, <em>then</em> it can look in the local identity
 
348
map and see that the object is already there. It&#8217;s only when you say
 
349
<tt class="docutils literal"><span class="pre">query.get({some</span> <span class="pre">primary</span> <span class="pre">key})</span></tt> that the
 
350
<a class="reference internal" href="#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&#8217;t have to issue a query.</p>
 
351
<p>Additionally, the Session stores object instances using a weak reference
 
352
by default. This also defeats the purpose of using the Session as a cache.</p>
 
353
<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
 
354
global object from which everyone consults as a &#8220;registry&#8221; of objects.
 
355
That&#8217;s more the job of a <strong>second level cache</strong>.   SQLAlchemy provides
 
356
a pattern for implementing second level caching using <a class="reference external" href="http://beaker.groovie.org/">Beaker</a>,
 
357
via the <a class="reference internal" href="examples.html#examples-caching"><em>Beaker Caching</em></a> example.</p>
 
358
</blockquote>
 
359
</li>
 
360
<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>
 
361
<blockquote>
 
362
<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
 
363
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>
 
364
<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>
 
365
</div>
 
366
</blockquote>
 
367
</li>
 
368
</ul>
 
369
<ul id="index-0">
 
370
<li><p class="first">Is the session thread-safe?</p>
 
371
<blockquote>
 
372
<p>Nope. It has no thread synchronization of any kind built in, and
 
373
particularly when you do a flush operation, it definitely is not open to
 
374
concurrent threads accessing it, because it holds onto a single database
 
375
connection at that point. If you use a session which is non-transactional
 
376
(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)
 
377
for read operations only, it&#8217;s still not thread-&#8220;safe&#8221;, but you also wont
 
378
get any catastrophic failures either, since it checks out and returns
 
379
connections to the connection pool on an as-needed basis; it&#8217;s just that
 
380
different threads might load the same objects independently of each other,
 
381
but only one will wind up in the identity map (however, the other one
 
382
might still live in a collection somewhere).</p>
 
383
<p>But the bigger point here is, you should not <em>want</em> to use the session
 
384
with multiple concurrent threads. That would be like having everyone at a
 
385
restaurant all eat from the same plate. The session is a local &#8220;workspace&#8221;
 
386
that you use for a specific set of tasks; you don&#8217;t want to, or need to,
 
387
share that session with other threads who are doing some other task. If,
 
388
on the other hand, there are other threads participating in the same task
 
389
you are, such as in a desktop graphical application, then you would be
 
390
sharing the session with those threads, but you also will have implemented
 
391
a proper locking scheme (or your graphical framework does) so that those
 
392
threads do not collide.</p>
 
393
<p>A multithreaded application is usually going to want to make usage of
 
394
<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.
 
395
More on this at <a class="reference internal" href="#unitofwork-contextual"><em>Contextual/Thread-local Sessions</em></a>.</p>
 
396
</blockquote>
 
397
</li>
 
398
</ul>
 
399
</div>
 
400
<div class="section" id="querying">
 
401
<h3>Querying<a class="headerlink" href="#querying" title="Permalink to this headline">¶</a></h3>
 
402
<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
 
403
<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
 
404
will issue mapper queries within the context of this Session. An entity is
 
405
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
 
406
orm-enabled <em>descriptor</em>, or an <tt class="docutils literal"><span class="pre">AliasedClass</span></tt> object:</p>
 
407
<div class="highlight-python"><div class="highlight"><pre><span class="c"># query from a class</span>
 
408
<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">&#39;ed&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
 
409
 
 
410
<span class="c"># query with multiple classes, returns tuples</span>
 
411
<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">&#39;addresses&#39;</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">&#39;ed&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
 
412
 
 
413
<span class="c"># query using orm-enabled descriptors</span>
 
414
<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>
 
415
 
 
416
<span class="c"># query from a mapper</span>
 
417
<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>
 
418
<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>
 
419
</div>
 
420
<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
 
421
instantiated is stored within the identity map. When a row matches an object
 
422
which is already present, the same object is returned. In the latter case,
 
423
whether or not the row is populated onto an existing object depends upon
 
424
whether the attributes of the instance have been <em>expired</em> or not. A
 
425
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
 
426
expires all instances along transaction boundaries, so that with a normally
 
427
isolated transaction, there shouldn&#8217;t be any issue of instances representing
 
428
data which is stale with regards to the current transaction.</p>
 
429
<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
 
430
<a class="reference internal" href="tutorial.html"><em>Object Relational Tutorial</em></a>, and further documented in
 
431
<a class="reference internal" href="query.html"><em>Querying</em></a>.</p>
 
432
</div>
 
433
<div class="section" id="adding-new-or-existing-items">
 
434
<h3>Adding New or Existing Items<a class="headerlink" href="#adding-new-or-existing-items" title="Permalink to this headline">¶</a></h3>
 
435
<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
 
436
session. For <em>transient</em> (i.e. brand new) instances, this will have the effect
 
437
of an INSERT taking place for those instances upon the next flush. For
 
438
instances which are <em>persistent</em> (i.e. were loaded by this session), they are
 
439
already present and do not need to be added. Instances which are <em>detached</em>
 
440
(i.e. have been removed from a session) may be re-associated with a session
 
441
using this method:</p>
 
442
<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">&#39;user1&#39;</span><span class="p">)</span>
 
443
<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">&#39;user2&#39;</span><span class="p">)</span>
 
444
<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>
 
445
<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>
 
446
 
 
447
<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>
 
448
</div>
 
449
<p>To add a list of items to the session at once, use
 
450
<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>
 
451
<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>
 
452
</div>
 
453
<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
 
454
the <tt class="docutils literal"><span class="pre">save-update</span></tt> cascade. For more details see the section
 
455
<a class="reference internal" href="#unitofwork-cascades"><em>Cascades</em></a>.</p>
 
456
</div>
 
457
<div class="section" id="merging">
 
458
<span id="unitofwork-merging"></span><h3>Merging<a class="headerlink" href="#merging" title="Permalink to this headline">¶</a></h3>
 
459
<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
 
460
an instance and its associated children with existing data in the database,
 
461
and returns a copy of the instance associated with the session. Usage is as
 
462
follows:</p>
 
463
<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>
 
464
</div>
 
465
<p>When given an instance, it follows these steps:</p>
 
466
<ul class="simple">
 
467
<li>It examines the primary key of the instance. If it&#8217;s present, it attempts
 
468
to load an instance with that primary key (or pulls from the local
 
469
identity map).</li>
 
470
<li>If there&#8217;s no primary key on the given instance, or the given primary key
 
471
does not exist in the database, a new instance is created.</li>
 
472
<li>The state of the given instance is then copied onto the located/newly
 
473
created instance.</li>
 
474
<li>The operation is cascaded to associated child items along the <tt class="docutils literal"><span class="pre">merge</span></tt>
 
475
cascade. Note that all changes present on the given instance, including
 
476
changes to collections, are merged.</li>
 
477
<li>The new instance is returned.</li>
 
478
</ul>
 
479
<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
 
480
placed within the session, and can be associated with a different session or
 
481
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
 
482
taking the state of any kind of object structure without regard for its
 
483
origins or current session associations and placing that state within a
 
484
session. Here&#8217;s two examples:</p>
 
485
<ul class="simple">
 
486
<li>An application which reads an object structure from a file and wishes to
 
487
save it to the database might parse the file, build up the
 
488
structure, and then use
 
489
<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
 
490
to the database, ensuring that the data within the file is
 
491
used to formulate the primary key of each element of the
 
492
structure. Later, when the file has changed, the same
 
493
process can be re-run, producing a slightly different
 
494
object structure, which can then be <tt class="docutils literal"><span class="pre">merged</span></tt> in again,
 
495
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
 
496
automatically update the database to reflect those
 
497
changes.</li>
 
498
<li>A web application stores mapped entities within an HTTP session object.
 
499
When each request starts up, the serialized data can be
 
500
merged into the session, so that the original entity may
 
501
be safely shared among requests and threads.</li>
 
502
</ul>
 
503
<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
 
504
applications which implement their own second level caches. This refers to an
 
505
application which uses an in memory dictionary, or an tool like Memcached to
 
506
store objects over long running spans of time. When such an object needs to
 
507
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>,
 
508
<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
 
509
the original cached object untouched. For this use case, merge provides a
 
510
keyword option called <tt class="docutils literal"><span class="pre">load=False</span></tt>. When this boolean flag is set to
 
511
<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
 
512
SQL to reconcile the given object against the current state of the database,
 
513
thereby reducing query overhead. The limitation is that the given object and
 
514
all of its children may not contain any pending changes, and it&#8217;s also of
 
515
course possible that newer information in the database will not be present on
 
516
the merged object, since no load is issued.</p>
 
517
<div class="section" id="merge-tips">
 
518
<h4>Merge Tips<a class="headerlink" href="#merge-tips" title="Permalink to this headline">¶</a></h4>
 
519
<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,
 
520
it deals with the intricate border between objects that are transient/detached and
 
521
those that are persistent, as well as the automated transferrence of state.
 
522
The wide variety of scenarios that can present themselves here often require a
 
523
more careful approach to the state of objects.   Common problems with merge usually involve
 
524
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>
 
525
<p>Lets use the canonical example of the User and Address objects:</p>
 
526
<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>
 
527
    <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">&#39;user&#39;</span>
 
528
 
 
529
    <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>
 
530
    <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>
 
531
    <span class="n">addresses</span> <span class="o">=</span> <span class="n">relationship</span><span class="p">(</span><span class="s">&quot;Address&quot;</span><span class="p">,</span> <span class="n">backref</span><span class="o">=</span><span class="s">&quot;user&quot;</span><span class="p">)</span>
 
532
 
 
533
<span class="k">class</span> <span class="nc">Address</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span>
 
534
    <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">&#39;address&#39;</span>
 
535
 
 
536
    <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>
 
537
    <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>
 
538
    <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">&#39;user.id&#39;</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>
 
539
</div>
 
540
<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>
 
541
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </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">&#39;ed&#39;</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">&#39;ed@ed.com&#39;</span><span class="p">)])</span>
 
542
<span class="gp">&gt;&gt;&gt; </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>
 
543
<span class="gp">&gt;&gt;&gt; </span><span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span></pre></div>
 
544
</div>
 
545
<p>We now create <tt class="docutils literal"><span class="pre">a1</span></tt>, an object outside the session, which we&#8217;d like
 
546
to merge on top of the existing <tt class="docutils literal"><span class="pre">Address</span></tt>:</p>
 
547
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </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>
 
548
<span class="gp">&gt;&gt;&gt; </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>
 
549
</div>
 
550
<p>A surprise would occur if we said this:</p>
 
551
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">a1</span><span class="o">.</span><span class="n">user</span> <span class="o">=</span> <span class="n">u1</span>
 
552
<span class="gp">&gt;&gt;&gt; </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>
 
553
<span class="gp">&gt;&gt;&gt; </span><span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
 
554
<span class="go">sqlalchemy.orm.exc.FlushError: New instance &lt;Address at 0x1298f50&gt;</span>
 
555
<span class="go">with identity key (&lt;class &#39;__main__.Address&#39;&gt;, (1,)) conflicts with</span>
 
556
<span class="go">persistent instance &lt;Address at 0x12a25d0&gt;</span></pre></div>
 
557
</div>
 
558
<p>Why is that ?   We weren&#8217;t careful with our cascades.   The assignment
 
559
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>
 
560
and made our <tt class="docutils literal"><span class="pre">a1</span></tt> object pending, as though we had added it.   Now we have
 
561
<em>two</em> <tt class="docutils literal"><span class="pre">Address</span></tt> objects in the session:</p>
 
562
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">a1</span> <span class="o">=</span> <span class="n">Address</span><span class="p">()</span>
 
563
<span class="gp">&gt;&gt;&gt; </span><span class="n">a1</span><span class="o">.</span><span class="n">user</span> <span class="o">=</span> <span class="n">u1</span>
 
564
<span class="gp">&gt;&gt;&gt; </span><span class="n">a1</span> <span class="ow">in</span> <span class="n">session</span>
 
565
<span class="go">True</span>
 
566
<span class="gp">&gt;&gt;&gt; </span><span class="n">existing_a1</span> <span class="ow">in</span> <span class="n">session</span>
 
567
<span class="go">True</span>
 
568
<span class="gp">&gt;&gt;&gt; </span><span class="n">a1</span> <span class="ow">is</span> <span class="n">existing_a1</span>
 
569
<span class="go">False</span></pre></div>
 
570
</div>
 
571
<p>Above, our <tt class="docutils literal"><span class="pre">a1</span></tt> is already pending in the session. The
 
572
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
 
573
does nothing. Cascade can be configured via the <tt class="docutils literal"><span class="pre">cascade</span></tt>
 
574
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
 
575
would mean removing the <tt class="docutils literal"><span class="pre">save-update</span></tt> cascade from the
 
576
<tt class="docutils literal"><span class="pre">User.addresses</span></tt> relationship - and usually, that behavior
 
577
is extremely convenient.  The solution here would usually be to not assign
 
578
<tt class="docutils literal"><span class="pre">a1.user</span></tt> to an object already persistent in the target
 
579
session.</p>
 
580
<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,
 
581
<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
 
582
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>
 
583
<p>Further detail on cascade operation is at <a class="reference internal" href="#unitofwork-cascades"><em>Cascades</em></a>.</p>
 
584
<p>Another example of unexpected state:</p>
 
585
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </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>
 
586
<span class="gp">&gt;&gt;&gt; </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>
 
587
<span class="gp">&gt;&gt;&gt; </span><span class="bp">True</span>
 
588
<span class="gp">&gt;&gt;&gt; </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>
 
589
<span class="gp">&gt;&gt;&gt; </span><span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
 
590
<span class="go">sqlalchemy.exc.IntegrityError: (IntegrityError) address.user_id</span>
 
591
<span class="go">may not be NULL</span></pre></div>
 
592
</div>
 
593
<p>Here, we accessed a1.user, which returned its default value
 
594
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
 
595
our object <tt class="docutils literal"><span class="pre">a1</span></tt>.  Normally, this operation creates no change event,
 
596
so the <tt class="docutils literal"><span class="pre">user_id</span></tt> attribute takes precedence during a
 
597
flush.  But when we merge the <tt class="docutils literal"><span class="pre">Address</span></tt> object into the session, the operation
 
598
is equivalent to:</p>
 
599
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </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>
 
600
<span class="gp">&gt;&gt;&gt; </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>
 
601
<span class="gp">&gt;&gt;&gt; </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>
 
602
</div>
 
603
<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
 
604
are emitted for both.  The <tt class="docutils literal"><span class="pre">user</span></tt> association
 
605
takes precedence, and None is applied to <tt class="docutils literal"><span class="pre">user_id</span></tt>, causing a failure.</p>
 
606
<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 -
 
607
is the object prematurely in the session ?</p>
 
608
<div class="highlight-python+sql"><div class="highlight"><pre><span class="o">&gt;&gt;&gt;</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>
 
609
<span class="o">&gt;&gt;&gt;</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>
 
610
<span class="o">&gt;&gt;&gt;</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>
 
611
</div>
 
612
<p>Or is there state on the object that we don&#8217;t want ?   Examining <tt class="docutils literal"><span class="pre">__dict__</span></tt>
 
613
is a quick way to check:</p>
 
614
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </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>
 
615
<span class="gp">&gt;&gt;&gt; </span><span class="n">a1</span><span class="o">.</span><span class="n">user</span>
 
616
<span class="gp">&gt;&gt;&gt; </span><span class="n">a1</span><span class="o">.</span><span class="n">__dict__</span>
 
617
<span class="go">{&#39;_sa_instance_state&#39;: &lt;sqlalchemy.orm.state.InstanceState object at 0x1298d10&gt;,</span>
 
618
<span class="go">    &#39;user_id&#39;: 1,</span>
 
619
<span class="go">    &#39;id&#39;: 1,</span>
 
620
<span class="go">    &#39;user&#39;: None}</span>
 
621
<span class="gp">&gt;&gt;&gt; </span><span class="c"># we don&#39;t want user=None merged, remove it</span>
 
622
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">a1</span><span class="o">.</span><span class="n">user</span>
 
623
<span class="gp">&gt;&gt;&gt; </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>
 
624
<span class="gp">&gt;&gt;&gt; </span><span class="c"># success</span>
 
625
<span class="gp">&gt;&gt;&gt; </span><span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span></pre></div>
 
626
</div>
 
627
</div>
 
628
</div>
 
629
<div class="section" id="deleting">
 
630
<h3>Deleting<a class="headerlink" href="#deleting" title="Permalink to this headline">¶</a></h3>
 
631
<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
 
632
into the Session&#8217;s list of objects to be marked as deleted:</p>
 
633
<div class="highlight-python"><div class="highlight"><pre><span class="c"># mark two objects to be deleted</span>
 
634
<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>
 
635
<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>
 
636
 
 
637
<span class="c"># commit (or flush)</span>
 
638
<span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span></pre></div>
 
639
</div>
 
640
<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
 
641
<strong>nothing is removed from collections</strong>. Such as, if a <tt class="docutils literal"><span class="pre">User</span></tt> has a
 
642
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
 
643
from <tt class="docutils literal"><span class="pre">user.addresses</span></tt>:</p>
 
644
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </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>
 
645
<span class="gp">&gt;&gt;&gt; </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>
 
646
<span class="gp">&gt;&gt;&gt; </span><span class="n">session</span><span class="o">.</span><span class="n">flush</span><span class="p">()</span>
 
647
<span class="gp">&gt;&gt;&gt; </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>
 
648
<span class="go">True</span></pre></div>
 
649
</div>
 
650
<p>The solution is to use proper cascading:</p>
 
651
<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>
 
652
    <span class="s">&#39;addresses&#39;</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">&quot;all, delete, delete-orphan&quot;</span><span class="p">)</span>
 
653
<span class="p">})</span>
 
654
<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>
 
655
<span class="n">session</span><span class="o">.</span><span class="n">flush</span><span class="p">()</span></pre></div>
 
656
</div>
 
657
<div class="section" id="deleting-based-on-filter-criterion">
 
658
<h4>Deleting based on Filter Criterion<a class="headerlink" href="#deleting-based-on-filter-criterion" title="Permalink to this headline">¶</a></h4>
 
659
<p>The caveat with <tt class="docutils literal"><span class="pre">Session.delete()</span></tt> is that you need to have an object handy
 
660
already in order to delete. The Query includes a
 
661
<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
 
662
filtering criteria:</p>
 
663
<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>
 
664
</div>
 
665
<p>The <tt class="docutils literal"><span class="pre">Query.delete()</span></tt> method includes functionality to &#8220;expire&#8221; objects
 
666
already in the session which match the criteria. However it does have some
 
667
caveats, including that &#8220;delete&#8221; and &#8220;delete-orphan&#8221; cascades won&#8217;t be fully
 
668
expressed for collections which are already loaded. See the API docs for
 
669
<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>
 
670
</div>
 
671
</div>
 
672
<div class="section" id="flushing">
 
673
<h3>Flushing<a class="headerlink" href="#flushing" title="Permalink to this headline">¶</a></h3>
 
674
<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
 
675
configuration, the flush step is nearly always done transparently.
 
676
Specifically, the flush occurs before any individual
 
677
<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
 
678
<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
 
679
committed. It also occurs before a SAVEPOINT is issued when
 
680
<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>
 
681
<p>Regardless of the autoflush setting, a flush can always be forced by issuing
 
682
<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>
 
683
<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>
 
684
</div>
 
685
<p>The &#8220;flush-on-Query&#8221; aspect of the behavior can be disabled by constructing
 
686
<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>
 
687
<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>
 
688
</div>
 
689
<p>Additionally, autoflush can be temporarily disabled by setting the
 
690
<tt class="docutils literal"><span class="pre">autoflush</span></tt> flag at any time:</p>
 
691
<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>
 
692
<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>
 
693
</div>
 
694
<p>Some autoflush-disable recipes are available at <a class="reference external" href="http://www.sqlalchemy.org/trac/wiki/UsageRecipes/DisableAutoflush">DisableAutoFlush</a>.</p>
 
695
<p>The flush process <em>always</em> occurs within a transaction, even if the
 
696
<a class="reference internal" href="#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
 
697
<tt class="docutils literal"><span class="pre">autocommit=True</span></tt>, a setting that disables the session&#8217;s persistent
 
698
transactional state. If no transaction is present,
 
699
<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
 
700
commits it. Any failures during flush will always result in a rollback of
 
701
whatever transaction is present. If the Session is not in <tt class="docutils literal"><span class="pre">autocommit=True</span></tt>
 
702
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
 
703
required after a flush fails, even though the underlying transaction will have
 
704
been rolled back already - this is so that the overall nesting pattern of
 
705
so-called &#8220;subtransactions&#8221; is consistently maintained.</p>
 
706
</div>
 
707
<div class="section" id="committing">
 
708
<h3>Committing<a class="headerlink" href="#committing" title="Permalink to this headline">¶</a></h3>
 
709
<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
 
710
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>
 
711
beforehand to flush any remaining state to the database; this is independent
 
712
of the &#8220;autoflush&#8221; setting. If no transaction is present, it raises an error.
 
713
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>
 
714
is that a transaction is always present; this behavior can be disabled by
 
715
setting <tt class="docutils literal"><span class="pre">autocommit=True</span></tt>. In autocommit mode, a transaction can be
 
716
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>
 
717
<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
 
718
default it expires the state of all instances present after the commit is
 
719
complete. This is so that when the instances are next accessed, either through
 
720
attribute access or by them being present in a
 
721
<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
 
722
state. To disable this behavior, configure
 
723
<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>
 
724
<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>
 
725
are never changed by subsequent queries; the assumption is that the current
 
726
transaction is isolated so the state most recently loaded is correct as long
 
727
as the transaction continues. Setting <tt class="docutils literal"><span class="pre">autocommit=True</span></tt> works against this
 
728
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>
 
729
behaves in exactly the same way with regard to attribute state, except no
 
730
transaction is present.</p>
 
731
</div>
 
732
<div class="section" id="rolling-back">
 
733
<h3>Rolling Back<a class="headerlink" href="#rolling-back" title="Permalink to this headline">¶</a></h3>
 
734
<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
 
735
transaction. With a default configured session, the post-rollback state of the
 
736
session is as follows:</p>
 
737
<blockquote>
 
738
<ul class="simple">
 
739
<li>All transactions are rolled back and all connections returned to the
 
740
connection pool, unless the Session was bound directly to a Connection, in
 
741
which case the connection is still maintained (but still rolled back).</li>
 
742
<li>Objects which were initially in the <em>pending</em> state when they were added
 
743
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
 
744
transaction are expunged, corresponding to their INSERT statement being
 
745
rolled back. The state of their attributes remains unchanged.</li>
 
746
<li>Objects which were marked as <em>deleted</em> within the lifespan of the
 
747
transaction are promoted back to the <em>persistent</em> state, corresponding to
 
748
their DELETE statement being rolled back. Note that if those objects were
 
749
first <em>pending</em> within the transaction, that operation takes precedence
 
750
instead.</li>
 
751
<li>All objects not expunged are fully expired.</li>
 
752
</ul>
 
753
</blockquote>
 
754
<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
 
755
safely continue usage after a rollback occurs.</p>
 
756
<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
 
757
reasons like primary key, foreign key, or &#8220;not nullable&#8221; constraint
 
758
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
 
759
automatically (it&#8217;s currently not possible for a flush to continue after a
 
760
partial failure). However, the flush process always uses its own transactional
 
761
demarcator called a <em>subtransaction</em>, which is described more fully in the
 
762
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
 
763
that even though the database transaction has been rolled back, the end user
 
764
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
 
765
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>
 
766
</div>
 
767
<div class="section" id="expunging">
 
768
<h3>Expunging<a class="headerlink" href="#expunging" title="Permalink to this headline">¶</a></h3>
 
769
<p>Expunge removes an object from the Session, sending persistent instances to
 
770
the detached state, and pending instances to the transient state:</p>
 
771
<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>
 
772
</div>
 
773
<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>
 
774
(this method was formerly known as <tt class="docutils literal"><span class="pre">clear()</span></tt>).</p>
 
775
</div>
 
776
<div class="section" id="closing">
 
777
<h3>Closing<a class="headerlink" href="#closing" title="Permalink to this headline">¶</a></h3>
 
778
<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
 
779
<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
 
780
transactional/connection resources. When connections are returned to the
 
781
connection pool, transactional state is rolled back as well.</p>
 
782
</div>
 
783
<div class="section" id="refreshing-expiring">
 
784
<h3>Refreshing / Expiring<a class="headerlink" href="#refreshing-expiring" title="Permalink to this headline">¶</a></h3>
 
785
<p>The Session normally works in the context of an ongoing transaction (with the
 
786
default setting of autoflush=False). Most databases offer &#8220;isolated&#8221;
 
787
transactions - this refers to a series of behaviors that allow the work within
 
788
a transaction to remain consistent as time passes, regardless of the
 
789
activities outside of that transaction. A key feature of a high degree of
 
790
transaction isolation is that emitting the same SELECT statement twice will
 
791
return the same results as when it was called the first time, even if the data
 
792
has been modified in another transaction.</p>
 
793
<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
 
794
loading the attributes of each instance only once.   Subsequent reads of the
 
795
same row in the same transaction are assumed to have the same value.  The
 
796
user application also gains directly from this assumption, that the transaction
 
797
is regarded as a temporary shield against concurrent changes - a good application
 
798
will ensure that isolation levels are set appropriately such that this assumption
 
799
can be made, given the kind of data being worked with.</p>
 
800
<p>To clear out the currently loaded state on an instance, the instance or its individual
 
801
attributes can be marked as &#8220;expired&#8221;, which results in a reload to
 
802
occur upon next access of any of the instance&#8217;s attrbutes.  The instance
 
803
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>
 
804
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>
 
805
<div class="highlight-python"><div class="highlight"><pre><span class="c"># immediately re-load attributes on obj1, obj2</span>
 
806
<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>
 
807
<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>
 
808
 
 
809
<span class="c"># expire objects obj1, obj2, attributes will be reloaded</span>
 
810
<span class="c"># on the next access:</span>
 
811
<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>
 
812
<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>
 
813
</div>
 
814
<p>When an expired object reloads, all non-deferred column-based attributes are
 
815
loaded in one query. Current behavior for expired relationship-based
 
816
attributes is that they load individually upon access - this behavior may be
 
817
enhanced in a future release. When a refresh is invoked on an object, the
 
818
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
 
819
configured with eager loading should also load within the scope of the refresh
 
820
operation.</p>
 
821
<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
 
822
<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
 
823
list of individual attribute names in which to be refreshed. These names can
 
824
refer to any attribute, column-based or relationship based:</p>
 
825
<div class="highlight-python"><div class="highlight"><pre><span class="c"># immediately re-load the attributes &#39;hello&#39;, &#39;world&#39; on obj1, obj2</span>
 
826
<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">&#39;hello&#39;</span><span class="p">,</span> <span class="s">&#39;world&#39;</span><span class="p">])</span>
 
827
<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">&#39;hello&#39;</span><span class="p">,</span> <span class="s">&#39;world&#39;</span><span class="p">])</span>
 
828
 
 
829
<span class="c"># expire the attributes &#39;hello&#39;, &#39;world&#39; objects obj1, obj2, attributes will be reloaded</span>
 
830
<span class="c"># on the next access:</span>
 
831
<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">&#39;hello&#39;</span><span class="p">,</span> <span class="s">&#39;world&#39;</span><span class="p">])</span>
 
832
<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">&#39;hello&#39;</span><span class="p">,</span> <span class="s">&#39;world&#39;</span><span class="p">])</span></pre></div>
 
833
</div>
 
834
<p>The full contents of the session may be expired at once using
 
835
<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>
 
836
<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>
 
837
</div>
 
838
<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
 
839
<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
 
840
session in its default mode of autocommit=False and with a well-isolated
 
841
transactional environment (which is provided by most backends with the notable
 
842
exception of MySQL MyISAM), there is virtually <em>no reason</em> to ever call
 
843
<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
 
844
current transaction until it is rolled back or committed or otherwise removed.</p>
 
845
<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
 
846
only necessary when an UPDATE or DELETE has been issued manually within the
 
847
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>
 
848
</div>
 
849
<div class="section" id="session-attributes">
 
850
<h3>Session Attributes<a class="headerlink" href="#session-attributes" title="Permalink to this headline">¶</a></h3>
 
851
<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
 
852
set-like collection. All items present may be accessed using the iterator
 
853
interface:</p>
 
854
<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>
 
855
    <span class="k">print</span> <span class="n">obj</span></pre></div>
 
856
</div>
 
857
<p>And presence may be tested for using regular &#8220;contains&#8221; semantics:</p>
 
858
<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>
 
859
    <span class="k">print</span> <span class="s">&quot;Object is present&quot;</span></pre></div>
 
860
</div>
 
861
<p>The session is also keeping track of all newly created (i.e. pending) objects,
 
862
all objects which have had changes since they were last loaded or saved (i.e.
 
863
&#8220;dirty&#8221;), and everything that&#8217;s been marked as deleted:</p>
 
864
<div class="highlight-python"><div class="highlight"><pre><span class="c"># pending objects recently added to the Session</span>
 
865
<span class="n">session</span><span class="o">.</span><span class="n">new</span>
 
866
 
 
867
<span class="c"># persistent objects which currently have changes detected</span>
 
868
<span class="c"># (this collection is now created on the fly each time the property is called)</span>
 
869
<span class="n">session</span><span class="o">.</span><span class="n">dirty</span>
 
870
 
 
871
<span class="c"># persistent objects that have been marked as deleted via session.delete(obj)</span>
 
872
<span class="n">session</span><span class="o">.</span><span class="n">deleted</span></pre></div>
 
873
</div>
 
874
<p>Note that objects within the session are by default <em>weakly referenced</em>. This
 
875
means that when they are dereferenced in the outside application, they fall
 
876
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
 
877
and are subject to garbage collection by the Python interpreter. The
 
878
exceptions to this include objects which are pending, objects which are marked
 
879
as deleted, or persistent objects which have pending changes on them. After a
 
880
full flush, these collections are all empty, and all objects are again weakly
 
881
referenced. To disable the weak referencing behavior and force all objects
 
882
within the session to remain until explicitly expunged, configure
 
883
<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>
 
884
setting.</p>
 
885
</div>
 
886
</div>
 
887
<div class="section" id="cascades">
 
888
<span id="unitofwork-cascades"></span><h2>Cascades<a class="headerlink" href="#cascades" title="Permalink to this headline">¶</a></h2>
 
889
<p>Mappers support the concept of configurable <em>cascade</em> behavior on
 
890
<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
 
891
the Session should treat the instances that have a parent-child relationship
 
892
with another instance that is operated upon by the Session. Cascade is
 
893
indicated as a comma-separated list of string keywords, with the possible
 
894
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>,
 
895
<tt class="docutils literal"><span class="pre">expunge</span></tt>, and <tt class="docutils literal"><span class="pre">delete-orphan</span></tt>.</p>
 
896
<p>Cascading is configured by setting the <tt class="docutils literal"><span class="pre">cascade</span></tt> keyword argument on a
 
897
<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>
 
898
<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>
 
899
    <span class="s">&#39;items&#39;</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">&quot;all, delete-orphan&quot;</span><span class="p">),</span>
 
900
    <span class="s">&#39;customer&#39;</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">&quot;save-update&quot;</span><span class="p">),</span>
 
901
<span class="p">})</span></pre></div>
 
902
</div>
 
903
<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
 
904
<tt class="docutils literal"><span class="pre">items</span></tt> relationship specifies &#8220;all, delete-orphan&#8221; as its <tt class="docutils literal"><span class="pre">cascade</span></tt>
 
905
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>
 
906
<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
 
907
should also be performed on the child <tt class="docutils literal"><span class="pre">Item</span></tt> instances attached to it. The
 
908
<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>
 
909
instance is no longer associated with an <tt class="docutils literal"><span class="pre">Order</span></tt>, it should also be deleted.
 
910
The &#8220;all, delete-orphan&#8221; cascade argument allows a so-called <em>lifecycle</em>
 
911
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>
 
912
<p>The <tt class="docutils literal"><span class="pre">customer</span></tt> relationship specifies only the &#8220;save-update&#8221; cascade value,
 
913
indicating most operations will not be cascaded from a parent <tt class="docutils literal"><span class="pre">Order</span></tt>
 
914
instance to a child <tt class="docutils literal"><span class="pre">User</span></tt> instance except for the
 
915
<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
 
916
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
 
917
will cascade to all child items, and also that items added to a parent which
 
918
is already present in a session will also be added to that same session.
 
919
&#8220;save-update&#8221; cascade also cascades the <em>pending history</em> of a
 
920
relationship()-based attribute, meaning that objects which were removed from a
 
921
scalar or collection attribute whose changes have not yet been flushed are
 
922
also placed into the new session - this so that foreign key clear operations
 
923
and deletions will take place (new in 0.6).</p>
 
924
<p>Note that the <tt class="docutils literal"><span class="pre">delete-orphan</span></tt> cascade only functions for relationships where
 
925
the target object can have a single parent at a time, meaning it is only
 
926
appropriate for one-to-one or one-to-many relationships. For a
 
927
<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
 
928
foreign key, i.e. a many-to-one that stores only a single parent, or
 
929
one-to-one/one-to-many via a &#8220;secondary&#8221; (association) table, a warning will
 
930
be issued if <tt class="docutils literal"><span class="pre">delete-orphan</span></tt> is configured. To disable this warning, also
 
931
specify the <tt class="docutils literal"><span class="pre">single_parent=True</span></tt> flag on the relationship, which constrains
 
932
objects to allow attachment to only one parent at a time.</p>
 
933
<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
 
934
<tt class="docutils literal"><span class="pre">save-update,</span> <span class="pre">merge</span></tt>.</p>
 
935
<p><tt class="docutils literal"><span class="pre">save-update</span></tt> cascade also takes place on backrefs by default.   This means
 
936
that, given a mapping such as this:</p>
 
937
<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>
 
938
    <span class="s">&#39;items&#39;</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">&#39;order&#39;</span><span class="p">)</span>
 
939
<span class="p">})</span></pre></div>
 
940
</div>
 
941
<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>
 
942
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>
 
943
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
 
944
place:</p>
 
945
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">o1</span> <span class="o">=</span> <span class="n">Order</span><span class="p">()</span>
 
946
<span class="gp">&gt;&gt;&gt; </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>
 
947
<span class="gp">&gt;&gt;&gt; </span><span class="n">o1</span> <span class="ow">in</span> <span class="n">session</span>
 
948
<span class="go">True</span>
 
949
 
 
950
<span class="gp">&gt;&gt;&gt; </span><span class="n">i1</span> <span class="o">=</span> <span class="n">Item</span><span class="p">()</span>
 
951
<span class="gp">&gt;&gt;&gt; </span><span class="n">i1</span><span class="o">.</span><span class="n">order</span> <span class="o">=</span> <span class="n">o1</span>
 
952
<span class="gp">&gt;&gt;&gt; </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>
 
953
<span class="go">True</span>
 
954
<span class="gp">&gt;&gt;&gt; </span><span class="n">i1</span> <span class="ow">in</span> <span class="n">session</span>
 
955
<span class="go">True</span></pre></div>
 
956
</div>
 
957
<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>
 
958
<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>
 
959
    <span class="s">&#39;items&#39;</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">&#39;order&#39;</span><span class="p">,</span>
 
960
                                <span class="n">cascade_backrefs</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
 
961
<span class="p">})</span></pre></div>
 
962
</div>
 
963
<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>
 
964
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
 
965
course <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> <tt class="docutils literal"><span class="pre">i1</span></tt> to the session at a later point.   This option
 
966
may be helpful for situations where an object needs to be kept out of a
 
967
session until it&#8217;s construction is completed, but still needs to be given
 
968
associations to objects which are already persistent in the target session.</p>
 
969
</div>
 
970
<div class="section" id="managing-transactions">
 
971
<span id="unitofwork-transaction"></span><h2>Managing Transactions<a class="headerlink" href="#managing-transactions" title="Permalink to this headline">¶</a></h2>
 
972
<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
 
973
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>
 
974
receives requests to execute SQL statements using a particular
 
975
<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
 
976
<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
 
977
<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
 
978
and maintains an open connection for each one (note that a simple application
 
979
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
 
980
time, all unflushed data is flushed, and each individual transaction is
 
981
committed. If the underlying databases support two-phase semantics, this may
 
982
be used by the Session as well if two-phase transactions are enabled.</p>
 
983
<p>Normal operation ends the transactional state using the
 
984
<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
 
985
<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
 
986
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
 
987
transaction:</p>
 
988
<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>
 
989
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
 
990
<span class="k">try</span><span class="p">:</span>
 
991
    <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>
 
992
    <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>
 
993
    <span class="n">item1</span><span class="o">.</span><span class="n">foo</span> <span class="o">=</span> <span class="s">&#39;bar&#39;</span>
 
994
    <span class="n">item2</span><span class="o">.</span><span class="n">bar</span> <span class="o">=</span> <span class="s">&#39;foo&#39;</span>
 
995
 
 
996
    <span class="c"># commit- will immediately go into</span>
 
997
    <span class="c"># a new transaction on next use.</span>
 
998
    <span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
 
999
<span class="k">except</span><span class="p">:</span>
 
1000
    <span class="c"># rollback - will immediately go into</span>
 
1001
    <span class="c"># a new transaction on next use.</span>
 
1002
    <span class="n">session</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span></pre></div>
 
1003
</div>
 
1004
<p>A session which is configured with <tt class="docutils literal"><span class="pre">autocommit=True</span></tt> may be placed into a
 
1005
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
 
1006
<tt class="docutils literal"><span class="pre">autocommit=True</span></tt> session that&#8217;s been placed into a transaction using
 
1007
<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
 
1008
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
 
1009
<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
 
1010
(with the exception of flushes) until the next
 
1011
<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>
 
1012
<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>
 
1013
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
 
1014
<span class="n">session</span><span class="o">.</span><span class="n">begin</span><span class="p">()</span>
 
1015
<span class="k">try</span><span class="p">:</span>
 
1016
    <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>
 
1017
    <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>
 
1018
    <span class="n">item1</span><span class="o">.</span><span class="n">foo</span> <span class="o">=</span> <span class="s">&#39;bar&#39;</span>
 
1019
    <span class="n">item2</span><span class="o">.</span><span class="n">bar</span> <span class="o">=</span> <span class="s">&#39;foo&#39;</span>
 
1020
    <span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
 
1021
<span class="k">except</span><span class="p">:</span>
 
1022
    <span class="n">session</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
 
1023
    <span class="k">raise</span></pre></div>
 
1024
</div>
 
1025
<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
 
1026
transactional token which is compatible with the Python 2.6 <tt class="docutils literal"><span class="pre">with</span></tt>
 
1027
statement:</p>
 
1028
<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>
 
1029
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
 
1030
<span class="k">with</span> <span class="n">session</span><span class="o">.</span><span class="n">begin</span><span class="p">():</span>
 
1031
    <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>
 
1032
    <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>
 
1033
    <span class="n">item1</span><span class="o">.</span><span class="n">foo</span> <span class="o">=</span> <span class="s">&#39;bar&#39;</span>
 
1034
    <span class="n">item2</span><span class="o">.</span><span class="n">bar</span> <span class="o">=</span> <span class="s">&#39;foo&#39;</span></pre></div>
 
1035
</div>
 
1036
<div class="section" id="using-savepoint">
 
1037
<span id="session-begin-nested"></span><h3>Using SAVEPOINT<a class="headerlink" href="#using-savepoint" title="Permalink to this headline">¶</a></h3>
 
1038
<p>SAVEPOINT transactions, if supported by the underlying engine, may be
 
1039
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>
 
1040
method:</p>
 
1041
<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>
 
1042
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
 
1043
<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>
 
1044
<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>
 
1045
 
 
1046
<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>
 
1047
<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>
 
1048
<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>
 
1049
 
 
1050
<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>
 
1051
</div>
 
1052
<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
 
1053
of times, which will issue a new SAVEPOINT with a unique identifier for each
 
1054
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
 
1055
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
 
1056
<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>
 
1057
<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
 
1058
<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
 
1059
(regardless of the <tt class="docutils literal"><span class="pre">autoflush</span></tt> setting). This is so that when a
 
1060
<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
 
1061
session is expired, thus causing all subsequent attribute/instance access to
 
1062
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
 
1063
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>
 
1064
</div>
 
1065
<div class="section" id="using-subtransactions">
 
1066
<span id="session-subtransactions"></span><h3>Using Subtransactions<a class="headerlink" href="#using-subtransactions" title="Permalink to this headline">¶</a></h3>
 
1067
<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>,
 
1068
is a non-transactional, delimiting construct that
 
1069
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>.
 
1070
It&#8217;s purpose is to allow the construction of code that can function within a transaction
 
1071
both independently of any external code that starts a transaction,
 
1072
as well as within a block that has already demarcated a transaction.  By &#8220;non-transactional&#8221;, we
 
1073
mean that no actual transactional dialogue with the database is generated by this flag beyond that of
 
1074
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
 
1075
is called within a transaction.</p>
 
1076
<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
 
1077
it internally to ensure that the series of flush steps are enclosed within a transaction,
 
1078
regardless of the setting of <tt class="docutils literal"><span class="pre">autocommit</span></tt> or the presence of an existing transactional context.
 
1079
However, explicit usage of the <tt class="docutils literal"><span class="pre">subtransactions=True</span></tt> flag is generally only useful with an
 
1080
application that uses the
 
1081
<a class="reference internal" href="#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 &#8220;autocommit=True&#8221; 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
 
1082
in order to demarcate transactions.  For this reason the subtransaction feature is not
 
1083
commonly used in an explicit way, except for apps that integrate SQLAlchemy-level transaction control with
 
1084
the transaction control of another library or subsystem.  For true, general purpose &#8220;nested&#8221;
 
1085
transactions, where a rollback affects only a portion of the work which has proceeded,
 
1086
savepoints should be used, documented in <a class="reference internal" href="#session-begin-nested"><em>Using SAVEPOINT</em></a>.</p>
 
1087
<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>,
 
1088
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>
 
1089
as though they are the initiator of the transaction, but in fact may be participating
 
1090
in an already ongoing transaction.</p>
 
1091
<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,
 
1092
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>
 
1093
transaction, which was initiated by the first call to
 
1094
<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
 
1095
end user, or implicit in an <tt class="docutils literal"><span class="pre">autocommit=False</span></tt> scenario).
 
1096
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
 
1097
&#8220;partially rolled back&#8221; 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
 
1098
called explicitly for each call that was made to
 
1099
<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 &#8220;partially rolled back&#8221; means that
 
1100
no further SQL operations can proceed until each level
 
1101
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
 
1102
is called which cancels all transactional markers. For a full exposition on
 
1103
the rationale for this,
 
1104
please see &#8220;<a class="reference external" href="http://www.sqlalchemy.org/trac/wiki/FAQ#ButwhyisnttheoneautomaticcalltoROLLBACKenoughWhymustIROLLBACKagain">But why isn&#8217;t the one automatic call to ROLLBACK
 
1105
enough ? Why must I ROLLBACK again?</a>&#8220;.
 
1106
The general theme is that if subtransactions are used as intended, that is, as a means to nest multiple
 
1107
begin/commit pairs, the appropriate rollback calls naturally occur in any case, and allow the session&#8217;s
 
1108
nesting of transactional pairs to function in a simple and predictable way
 
1109
without the need to guess as to what level is active.</p>
 
1110
<p>An example of <tt class="docutils literal"><span class="pre">subtransactions=True</span></tt> is nearly identical to
 
1111
that of the non-ORM technique. The nesting of transactions, as
 
1112
well as the natural presence of &#8220;rollback&#8221; for all transactions
 
1113
should an exception occur, is illustrated:</p>
 
1114
<div class="highlight-python"><div class="highlight"><pre><span class="c"># method_a starts a transaction and calls method_b</span>
 
1115
<span class="k">def</span> <span class="nf">method_a</span><span class="p">(</span><span class="n">session</span><span class="p">):</span>
 
1116
    <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>
 
1117
                                        <span class="c"># no previous call to begin(), this will</span>
 
1118
                                        <span class="c"># begin a real transaction (meaning, a</span>
 
1119
                                        <span class="c"># DBAPI connection is procured, which as</span>
 
1120
                                        <span class="c"># per the DBAPI specification is in a transactional</span>
 
1121
                                        <span class="c"># state ready to be committed or rolled back)</span>
 
1122
    <span class="k">try</span><span class="p">:</span>
 
1123
        <span class="n">method_b</span><span class="p">(</span><span class="n">session</span><span class="p">)</span>
 
1124
        <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>
 
1125
    <span class="k">except</span><span class="p">:</span>
 
1126
        <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>
 
1127
        <span class="k">raise</span>
 
1128
 
 
1129
<span class="c"># method_b also starts a transaction</span>
 
1130
<span class="k">def</span> <span class="nf">method_b</span><span class="p">(</span><span class="n">connection</span><span class="p">):</span>
 
1131
    <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>
 
1132
                                        <span class="c"># runs in the context of method_a()&#39;s</span>
 
1133
                                        <span class="c"># transaction</span>
 
1134
    <span class="k">try</span><span class="p">:</span>
 
1135
        <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">&#39;bat&#39;</span><span class="p">,</span> <span class="s">&#39;lala&#39;</span><span class="p">))</span>
 
1136
        <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>
 
1137
    <span class="k">except</span><span class="p">:</span>
 
1138
        <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>
 
1139
                           <span class="c"># the one that was initiated in method_a().</span>
 
1140
        <span class="k">raise</span>
 
1141
 
 
1142
<span class="c"># create a Session and call method_a</span>
 
1143
<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>
 
1144
<span class="n">method_a</span><span class="p">(</span><span class="n">session</span><span class="p">)</span>
 
1145
<span class="n">session</span><span class="o">.</span><span class="n">close</span><span class="p">()</span></pre></div>
 
1146
</div>
 
1147
<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
 
1148
will always issue a rollback which then affects the state of the outermost transaction (unless a SAVEPOINT
 
1149
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
 
1150
before subsequent SQL operations can proceed.</p>
 
1151
</div>
 
1152
<div class="section" id="enabling-two-phase-commit">
 
1153
<h3>Enabling Two-Phase Commit<a class="headerlink" href="#enabling-two-phase-commit" title="Permalink to this headline">¶</a></h3>
 
1154
<p>Finally, for MySQL, PostgreSQL, and soon Oracle as well, the session can be
 
1155
instructed to use two-phase commit semantics. This will coordinate the
 
1156
committing of transactions across databases so that the transaction is either
 
1157
committed or rolled back in all databases. You can also
 
1158
<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
 
1159
with transactions not managed by SQLAlchemy. To use two phase transactions set
 
1160
the flag <tt class="docutils literal"><span class="pre">twophase=True</span></tt> on the session:</p>
 
1161
<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">&#39;postgresql://db1&#39;</span><span class="p">)</span>
 
1162
<span class="n">engine2</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">&#39;postgresql://db2&#39;</span><span class="p">)</span>
 
1163
 
 
1164
<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>
 
1165
 
 
1166
<span class="c"># bind User operations to engine 1, Account operations to engine 2</span>
 
1167
<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>
 
1168
 
 
1169
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
 
1170
 
 
1171
<span class="c"># .... work with accounts and users</span>
 
1172
 
 
1173
<span class="c"># commit.  session will issue a flush to all DBs, and a prepare step to all DBs,</span>
 
1174
<span class="c"># before committing both transactions</span>
 
1175
<span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span></pre></div>
 
1176
</div>
 
1177
</div>
 
1178
</div>
 
1179
<div class="section" id="embedding-sql-insert-update-expressions-into-a-flush">
 
1180
<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>
 
1181
<p>This feature allows the value of a database column to be set to a SQL
 
1182
expression instead of a literal value. It&#8217;s especially useful for atomic
 
1183
updates, calling stored procedures, etc. All you do is assign an expression to
 
1184
an attribute:</p>
 
1185
<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>
 
1186
    <span class="k">pass</span>
 
1187
<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>
 
1188
 
 
1189
<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>
 
1190
 
 
1191
<span class="c"># set &#39;value&#39; attribute to a SQL expression adding one</span>
 
1192
<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>
 
1193
 
 
1194
<span class="c"># issues &quot;UPDATE some_table SET value=value+1&quot;</span>
 
1195
<span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span></pre></div>
 
1196
</div>
 
1197
<p>This technique works both for INSERT and UPDATE statements. After the
 
1198
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
 
1199
expired, so that when next accessed the newly generated value will be loaded
 
1200
from the database.</p>
 
1201
</div>
 
1202
<div class="section" id="using-sql-expressions-with-sessions">
 
1203
<h2>Using SQL Expressions with Sessions<a class="headerlink" href="#using-sql-expressions-with-sessions" title="Permalink to this headline">¶</a></h2>
 
1204
<p>SQL expressions and strings can be executed via the
 
1205
<a class="reference internal" href="#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.
 
1206
This is most easily accomplished using the
 
1207
<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
 
1208
<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
 
1209
<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
 
1210
<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>
 
1211
<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>
 
1212
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
 
1213
 
 
1214
<span class="c"># execute a string statement</span>
 
1215
<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">&quot;select * from table where id=:id&quot;</span><span class="p">,</span> <span class="p">{</span><span class="s">&#39;id&#39;</span><span class="p">:</span><span class="mi">7</span><span class="p">})</span>
 
1216
 
 
1217
<span class="c"># execute a SQL expression construct</span>
 
1218
<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>
 
1219
</div>
 
1220
<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
 
1221
<a class="reference internal" href="#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
 
1222
<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>
 
1223
<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>
 
1224
</div>
 
1225
<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&#8217;s
 
1226
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
 
1227
<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
 
1228
<a class="reference internal" href="#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
 
1229
engines, or none at all (i.e. relies upon bound metadata), both
 
1230
<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
 
1231
<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
 
1232
argument, which is passed a mapped class or
 
1233
<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
 
1234
proper context for the desired engine:</p>
 
1235
<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>
 
1236
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
 
1237
 
 
1238
<span class="c"># need to specify mapper or class when executing</span>
 
1239
<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">&quot;select * from table where id=:id&quot;</span><span class="p">,</span> <span class="p">{</span><span class="s">&#39;id&#39;</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>
 
1240
 
 
1241
<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>
 
1242
 
 
1243
<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>
 
1244
</div>
 
1245
</div>
 
1246
<div class="section" id="joining-a-session-into-an-external-transaction">
 
1247
<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>
 
1248
<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
 
1249
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
 
1250
be made to participate within that transaction by just binding the
 
1251
<a class="reference internal" href="#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
 
1252
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>,
 
1253
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
 
1254
entire database interaction is rolled back:</p>
 
1255
<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>
 
1256
<span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">create_engine</span>
 
1257
<span class="kn">from</span> <span class="nn">unittest</span> <span class="kn">import</span> <span class="n">TestCase</span>
 
1258
 
 
1259
<span class="c"># global application scope.  create Session class, engine</span>
 
1260
<span class="n">Session</span> <span class="o">=</span> <span class="n">sessionmaker</span><span class="p">()</span>
 
1261
 
 
1262
<span class="n">engine</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">&#39;postgresql://...&#39;</span><span class="p">)</span>
 
1263
 
 
1264
<span class="k">class</span> <span class="nc">SomeTest</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>
 
1265
    <span class="k">def</span> <span class="nf">setUp</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
 
1266
        <span class="c"># connect to the database</span>
 
1267
        <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>
 
1268
 
 
1269
        <span class="c"># begin a non-ORM transaction</span>
 
1270
        <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>
 
1271
 
 
1272
        <span class="c"># bind an individual Session to the connection</span>
 
1273
        <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>
 
1274
 
 
1275
    <span class="k">def</span> <span class="nf">test_something</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
 
1276
        <span class="c"># use the session in tests.</span>
 
1277
 
 
1278
        <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>
 
1279
        <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>
 
1280
 
 
1281
    <span class="k">def</span> <span class="nf">tearDown</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
 
1282
        <span class="c"># rollback - everything that happened with the</span>
 
1283
        <span class="c"># Session above (including calls to commit())</span>
 
1284
        <span class="c"># is rolled back.</span>
 
1285
        <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>
 
1286
        <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>
 
1287
</div>
 
1288
<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
 
1289
<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
 
1290
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&#8217;s ability to maintain <em>subtransactions</em>, or
 
1291
nested begin/commit-or-rollback pairs where only the outermost begin/commit
 
1292
pair actually commits the transaction, or if the outermost block rolls back,
 
1293
everything is rolled back.</p>
 
1294
</div>
 
1295
<div class="section" id="the-session-object-and-sessionmaker-function">
 
1296
<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>
 
1297
<dl class="function">
 
1298
<dt id="sqlalchemy.orm.session.sessionmaker">
 
1299
<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>
 
1300
<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>
 
1301
<p>The returned object is a subclass of <tt class="docutils literal"><span class="pre">Session</span></tt>, which, when instantiated
 
1302
with no arguments, uses the keyword arguments configured here as its
 
1303
constructor arguments.</p>
 
1304
<p>It is intended that the <cite>sessionmaker()</cite> function be called within the
 
1305
global scope of an application, and the returned class be made available
 
1306
to the rest of the application as the single class used to instantiate
 
1307
sessions.</p>
 
1308
<p>e.g.:</p>
 
1309
<div class="highlight-python"><div class="highlight"><pre><span class="c"># global scope</span>
 
1310
<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>
 
1311
 
 
1312
<span class="c"># later, in a local scope, create and use a session:</span>
 
1313
<span class="n">sess</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span></pre></div>
 
1314
</div>
 
1315
<p>Any keyword arguments sent to the constructor itself will override the
 
1316
&#8220;configured&#8221; keywords:</p>
 
1317
<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>
 
1318
 
 
1319
<span class="c"># bind an individual session to a connection</span>
 
1320
<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>
 
1321
</div>
 
1322
<p>The class also includes a special classmethod <tt class="docutils literal"><span class="pre">configure()</span></tt>, which
 
1323
allows additional configurational options to take place after the custom
 
1324
<tt class="docutils literal"><span class="pre">Session</span></tt> class has been generated.  This is useful particularly for
 
1325
defining the specific <tt class="docutils literal"><span class="pre">Engine</span></tt> (or engines) to which new instances of
 
1326
<tt class="docutils literal"><span class="pre">Session</span></tt> should be bound:</p>
 
1327
<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>
 
1328
<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">&#39;sqlite:///foo.db&#39;</span><span class="p">))</span>
 
1329
 
 
1330
<span class="n">sess</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span></pre></div>
 
1331
</div>
 
1332
<p>Options:</p>
 
1333
<table class="docutils field-list" frame="void" rules="none">
 
1334
<col class="field-name" />
 
1335
<col class="field-body" />
 
1336
<tbody valign="top">
 
1337
<tr class="field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
 
1338
<li><strong>autocommit</strong> &#8211; <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>
 
1339
does not keep a persistent transaction running, and will acquire
 
1340
connections from the engine on an as-needed basis, returning them
 
1341
immediately after their use. Flushes will begin and commit (or possibly
 
1342
rollback) their own transaction if no transaction is present. When using
 
1343
this mode, the <cite>session.begin()</cite> method may be used to begin a
 
1344
transaction explicitly.</p>
 
1345
<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>
 
1346
will acquire a connection and begin a transaction the first time it is
 
1347
used, which it will maintain persistently until <tt class="docutils literal"><span class="pre">rollback()</span></tt>,
 
1348
<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
 
1349
by any of these methods, the <tt class="docutils literal"><span class="pre">Session</span></tt> is ready for the next usage,
 
1350
which will again acquire and maintain a new connection/transaction.</p>
 
1351
</li>
 
1352
<li><strong>autoflush</strong> &#8211; When <tt class="xref docutils literal"><span class="pre">True</span></tt>, all query operations will issue a 
 
1353
<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
 
1354
convenience feature so that <tt class="docutils literal"><span class="pre">flush()</span></tt> need not be called repeatedly
 
1355
in order for database queries to retrieve results. It&#8217;s typical that
 
1356
<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
 
1357
scenario, explicit calls to <tt class="docutils literal"><span class="pre">flush()</span></tt> are rarely needed; you usually
 
1358
only need to call <tt class="docutils literal"><span class="pre">commit()</span></tt> (which flushes) to finalize changes.</li>
 
1359
<li><strong>bind</strong> &#8211; 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
 
1360
<tt class="docutils literal"><span class="pre">Session</span></tt> should be bound. When specified, all SQL operations
 
1361
performed by this session will execute via this connectable.</li>
 
1362
<li><strong>binds</strong> &#8211; <dl class="docutils">
 
1363
<dt>An optional dictionary which contains more granular &#8220;bind&#8221;</dt>
 
1364
<dd>information than the <tt class="docutils literal"><span class="pre">bind</span></tt> parameter provides. This dictionary can
 
1365
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
 
1366
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
 
1367
proceed relative to a particular <tt class="docutils literal"><span class="pre">Mapper</span></tt> will consult this
 
1368
dictionary for the direct <tt class="docutils literal"><span class="pre">Mapper</span></tt> instance as well as the mapper&#8217;s
 
1369
<tt class="docutils literal"><span class="pre">mapped_table</span></tt> attribute in order to locate an connectable to use.
 
1370
The full resolution is described in the <tt class="docutils literal"><span class="pre">get_bind()</span></tt> method of
 
1371
<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>
 
1372
    <span class="n">SomeMappedClass</span><span class="p">:</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">&#39;postgresql://engine1&#39;</span><span class="p">),</span>
 
1373
    <span class="n">somemapper</span><span class="p">:</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">&#39;postgresql://engine2&#39;</span><span class="p">),</span>
 
1374
    <span class="n">some_table</span><span class="p">:</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">&#39;postgresql://engine3&#39;</span><span class="p">),</span>
 
1375
    <span class="p">})</span></pre></div>
 
1376
</div>
 
1377
</dd>
 
1378
</dl>
 
1379
<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>
 
1380
</li>
 
1381
<li><strong>class_</strong> &#8211; Specify an alternate class other than
 
1382
<tt class="docutils literal"><span class="pre">sqlalchemy.orm.session.Session</span></tt> which should be used by the returned
 
1383
class. This is the only argument that is local to the
 
1384
<tt class="docutils literal"><span class="pre">sessionmaker()</span></tt> function, and is not sent directly to the
 
1385
constructor for <tt class="docutils literal"><span class="pre">Session</span></tt>.</li>
 
1386
<li><strong>_enable_transaction_accounting</strong> &#8211; Defaults to <tt class="xref docutils literal"><span class="pre">True</span></tt>.  A
 
1387
legacy-only flag which when <tt class="xref docutils literal"><span class="pre">False</span></tt> disables <em>all</em> 0.5-style object
 
1388
accounting on transaction boundaries, including auto-expiry of
 
1389
instances on rollback and commit, maintenance of the &#8220;new&#8221; and
 
1390
&#8220;deleted&#8221; lists upon rollback, and autoflush of pending changes upon
 
1391
begin(), all of which are interdependent.</li>
 
1392
<li><strong>expire_on_commit</strong> &#8211; 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
 
1393
instances will be fully expired after each <tt class="docutils literal"><span class="pre">commit()</span></tt>, so that all
 
1394
attribute/object access subsequent to a completed transaction will load
 
1395
from the most recent database state.</li>
 
1396
<li><strong>extension</strong> &#8211; An optional 
 
1397
<tt class="xref py py-class docutils literal"><span class="pre">SessionExtension</span></tt> instance, or a list
 
1398
of such instances, which will receive pre- and post- commit and flush
 
1399
events, as well as a post-rollback event. User- defined code may be
 
1400
placed within these hooks using a user-defined subclass of
 
1401
<tt class="docutils literal"><span class="pre">SessionExtension</span></tt>.</li>
 
1402
<li><strong>query_cls</strong> &#8211; Class which should be used to create new Query objects,
 
1403
as returned by the <tt class="docutils literal"><span class="pre">query()</span></tt> method. Defaults to
 
1404
<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>
 
1405
<li><strong>twophase</strong> &#8211; When <tt class="xref docutils literal"><span class="pre">True</span></tt>, all transactions will be started as
 
1406
a &#8220;two phase&#8221; transaction, i.e. using the &#8220;two phase&#8221; semantics
 
1407
of the database in use along with an XID.  During a <tt class="docutils literal"><span class="pre">commit()</span></tt>,
 
1408
after <tt class="docutils literal"><span class="pre">flush()</span></tt> has been issued for all attached databases, the
 
1409
<tt class="docutils literal"><span class="pre">prepare()</span></tt> method on each database&#8217;s <tt class="docutils literal"><span class="pre">TwoPhaseTransaction</span></tt> will
 
1410
be called. This allows each database to roll back the entire
 
1411
transaction, before each transaction is committed.</li>
 
1412
<li><strong>weak_identity_map</strong> &#8211; When set to the default value of <tt class="xref docutils literal"><span class="pre">True</span></tt>, a
 
1413
weak-referencing map is used; instances which are not externally
 
1414
referenced will be garbage collected immediately. For dereferenced
 
1415
instances which have pending changes present, the attribute management
 
1416
system will create a temporary strong-reference to the object which
 
1417
lasts until the changes are flushed to the database, at which point
 
1418
it&#8217;s again dereferenced. Alternatively, when using the value <tt class="xref docutils literal"><span class="pre">False</span></tt>,
 
1419
the identity map uses a regular Python dictionary to store instances.
 
1420
The session will maintain all instances present until they are removed
 
1421
using expunge(), clear(), or purge().</li>
 
1422
</ul>
 
1423
</td>
 
1424
</tr>
 
1425
</tbody>
 
1426
</table>
 
1427
</dd></dl>
 
1428
 
 
1429
<dl class="class">
 
1430
<dt id="sqlalchemy.orm.session.Session">
 
1431
<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=&lt;class 'sqlalchemy.orm.query.Query'&gt;</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session" title="Permalink to this definition">¶</a></dt>
 
1432
<dd><p>Manages persistence operations for ORM-mapped objects.</p>
 
1433
<p>The Session&#8217;s usage paradigm is described at <a class="reference internal" href="#"><em>Using the Session</em></a>.</p>
 
1434
<dl class="method">
 
1435
<dt id="sqlalchemy.orm.session.Session.__init__">
 
1436
<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=&lt;class 'sqlalchemy.orm.query.Query'&gt;</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.session.Session.__init__" title="Permalink to this definition">¶</a></dt>
 
1437
<dd><p>Construct a new Session.</p>
 
1438
<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
 
1439
<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 
 
1440
typical point of entry.</p>
 
1441
</dd></dl>
 
1442
 
 
1443
<dl class="method">
 
1444
<dt id="sqlalchemy.orm.session.Session.add">
 
1445
<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>
 
1446
<dd><p>Place an object in the <tt class="docutils literal"><span class="pre">Session</span></tt>.</p>
 
1447
<p>Its state will be persisted to the database on the next flush
 
1448
operation.</p>
 
1449
<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>
 
1450
is <tt class="docutils literal"><span class="pre">expunge()</span></tt>.</p>
 
1451
</dd></dl>
 
1452
 
 
1453
<dl class="method">
 
1454
<dt id="sqlalchemy.orm.session.Session.add_all">
 
1455
<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>
 
1456
<dd><p>Add the given collection of instances to this <tt class="docutils literal"><span class="pre">Session</span></tt>.</p>
 
1457
</dd></dl>
 
1458
 
 
1459
<dl class="method">
 
1460
<dt id="sqlalchemy.orm.session.Session.begin">
 
1461
<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>
 
1462
<dd><p>Begin a transaction on this Session.</p>
 
1463
<p>If this Session is already within a transaction, either a plain
 
1464
transaction or nested transaction, an error is raised, unless
 
1465
<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>
 
1466
<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> 
 
1467
can create a subtransaction if a transaction is already in progress.
 
1468
For documentation on subtransactions, please see <a class="reference internal" href="#session-subtransactions"><em>Using Subtransactions</em></a>.</p>
 
1469
<p>The <tt class="docutils literal"><span class="pre">nested</span></tt> flag begins a SAVEPOINT transaction and is equivalent
 
1470
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
 
1471
transactions, please see <a class="reference internal" href="#session-begin-nested"><em>Using SAVEPOINT</em></a>.</p>
 
1472
</dd></dl>
 
1473
 
 
1474
<dl class="method">
 
1475
<dt id="sqlalchemy.orm.session.Session.begin_nested">
 
1476
<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>
 
1477
<dd><p>Begin a <cite>nested</cite> transaction on this Session.</p>
 
1478
<p>The target database(s) must support SQL SAVEPOINTs or a
 
1479
SQLAlchemy-supported vendor implementation of the idea.</p>
 
1480
<p>For documentation on SAVEPOINT
 
1481
transactions, please see <a class="reference internal" href="#session-begin-nested"><em>Using SAVEPOINT</em></a>.</p>
 
1482
</dd></dl>
 
1483
 
 
1484
<dl class="method">
 
1485
<dt id="sqlalchemy.orm.session.Session.bind_mapper">
 
1486
<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>
 
1487
<dd><p>Bind operations for a mapper to a Connectable.</p>
 
1488
<dl class="docutils">
 
1489
<dt>mapper</dt>
 
1490
<dd>A mapper instance or mapped class</dd>
 
1491
<dt>bind</dt>
 
1492
<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>
 
1493
</dl>
 
1494
<p>All subsequent operations involving this mapper will use the given
 
1495
<cite>bind</cite>.</p>
 
1496
</dd></dl>
 
1497
 
 
1498
<dl class="method">
 
1499
<dt id="sqlalchemy.orm.session.Session.bind_table">
 
1500
<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>
 
1501
<dd><p>Bind operations on a Table to a Connectable.</p>
 
1502
<dl class="docutils">
 
1503
<dt>table</dt>
 
1504
<dd>A <tt class="docutils literal"><span class="pre">Table</span></tt> instance</dd>
 
1505
<dt>bind</dt>
 
1506
<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>
 
1507
</dl>
 
1508
<p>All subsequent operations involving this <tt class="docutils literal"><span class="pre">Table</span></tt> will use the
 
1509
given <cite>bind</cite>.</p>
 
1510
</dd></dl>
 
1511
 
 
1512
<dl class="method">
 
1513
<dt id="sqlalchemy.orm.session.Session.close">
 
1514
<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>
 
1515
<dd><p>Close this Session.</p>
 
1516
<p>This clears all items and ends any transaction in progress.</p>
 
1517
<p>If this session were created with <tt class="docutils literal"><span class="pre">autocommit=False</span></tt>, a new
 
1518
transaction is immediately begun.  Note that this new transaction does
 
1519
not use any connection resources until they are first needed.</p>
 
1520
</dd></dl>
 
1521
 
 
1522
<dl class="classmethod">
 
1523
<dt id="sqlalchemy.orm.session.Session.close_all">
 
1524
<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>
 
1525
<dd><p>Close <em>all</em> sessions in memory.</p>
 
1526
</dd></dl>
 
1527
 
 
1528
<dl class="method">
 
1529
<dt id="sqlalchemy.orm.session.Session.commit">
 
1530
<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>
 
1531
<dd><p>Flush pending changes and commit the current transaction.</p>
 
1532
<p>If no transaction is in progress, this method raises an
 
1533
InvalidRequestError.</p>
 
1534
<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
 
1535
loaded state on all ORM-managed attributes after transaction commit.
 
1536
This so that subsequent operations load the most recent 
 
1537
data from the database.   This behavior can be disabled using
 
1538
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
 
1539
the <a class="reference internal" href="#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>
 
1540
<p>If a subtransaction is in effect (which occurs when begin() is called
 
1541
multiple times), the subtransaction will be closed, and the next call
 
1542
to <tt class="docutils literal"><span class="pre">commit()</span></tt> will operate on the enclosing transaction.</p>
 
1543
<p>For a session configured with autocommit=False, a new transaction will
 
1544
be begun immediately after the commit, but note that the newly begun
 
1545
transaction does <em>not</em> use any connection resources until the first
 
1546
SQL is actually emitted.</p>
 
1547
</dd></dl>
 
1548
 
 
1549
<dl class="method">
 
1550
<dt id="sqlalchemy.orm.session.Session.connection">
 
1551
<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>
 
1552
<dd><p>Return the active Connection.</p>
 
1553
<p>Retrieves the <tt class="docutils literal"><span class="pre">Connection</span></tt> managing the current transaction.  Any
 
1554
operations executed on the Connection will take place in the same
 
1555
transactional context as <tt class="docutils literal"><span class="pre">Session</span></tt> operations.</p>
 
1556
<p>For <tt class="docutils literal"><span class="pre">autocommit</span></tt> Sessions with no active manual transaction,
 
1557
<tt class="docutils literal"><span class="pre">connection()</span></tt> is a passthrough to <tt class="docutils literal"><span class="pre">contextual_connect()</span></tt> on the
 
1558
underlying engine.</p>
 
1559
<p>Ambiguity in multi-bind or unbound Sessions can be resolved through
 
1560
any of the optional keyword arguments.  See <tt class="docutils literal"><span class="pre">get_bind()</span></tt> for more
 
1561
information.</p>
 
1562
<dl class="docutils">
 
1563
<dt>mapper</dt>
 
1564
<dd>Optional, a <tt class="docutils literal"><span class="pre">mapper</span></tt> or mapped class</dd>
 
1565
<dt>clause</dt>
 
1566
<dd>Optional, any <tt class="docutils literal"><span class="pre">ClauseElement</span></tt></dd>
 
1567
</dl>
 
1568
</dd></dl>
 
1569
 
 
1570
<dl class="method">
 
1571
<dt id="sqlalchemy.orm.session.Session.delete">
 
1572
<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>
 
1573
<dd><p>Mark an instance as deleted.</p>
 
1574
<p>The database delete operation occurs upon <tt class="docutils literal"><span class="pre">flush()</span></tt>.</p>
 
1575
</dd></dl>
 
1576
 
 
1577
<dl class="attribute">
 
1578
<dt id="sqlalchemy.orm.session.Session.deleted">
 
1579
<tt class="descname">deleted</tt><a class="headerlink" href="#sqlalchemy.orm.session.Session.deleted" title="Permalink to this definition">¶</a></dt>
 
1580
<dd><p>The set of all instances marked as &#8216;deleted&#8217; within this <tt class="docutils literal"><span class="pre">Session</span></tt></p>
 
1581
</dd></dl>
 
1582
 
 
1583
<dl class="attribute">
 
1584
<dt id="sqlalchemy.orm.session.Session.dirty">
 
1585
<tt class="descname">dirty</tt><a class="headerlink" href="#sqlalchemy.orm.session.Session.dirty" title="Permalink to this definition">¶</a></dt>
 
1586
<dd><p>The set of all persistent instances considered dirty.</p>
 
1587
<p>Instances are considered dirty when they were modified but not
 
1588
deleted.</p>
 
1589
<p>Note that this &#8216;dirty&#8217; calculation is &#8216;optimistic&#8217;; most
 
1590
attribute-setting or collection modification operations will
 
1591
mark an instance as &#8216;dirty&#8217; and place it in this set, even if
 
1592
there is no net change to the attribute&#8217;s value.  At flush
 
1593
time, the value of each attribute is compared to its
 
1594
previously saved value, and if there&#8217;s no net change, no SQL
 
1595
operation will occur (this is a more expensive operation so
 
1596
it&#8217;s only done at flush time).</p>
 
1597
<p>To check if an instance has actionable net changes to its
 
1598
attributes, use the is_modified() method.</p>
 
1599
</dd></dl>
 
1600
 
 
1601
<dl class="method">
 
1602
<dt id="sqlalchemy.orm.session.Session.execute">
 
1603
<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>
 
1604
<dd><p>Execute a clause within the current transaction.</p>
 
1605
<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
 
1606
results of the statement execution, in the same manner as that of an
 
1607
<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
 
1608
<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>
 
1609
<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">Session.execute()</span></tt></a> accepts any executable clause construct, such
 
1610
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>,
 
1611
<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>,
 
1612
<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>,
 
1613
<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
 
1614
<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
 
1615
plain strings that represent SQL statements. If a plain string is
 
1616
passed, it is first converted to a
 
1617
<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
 
1618
that bind parameters should be specified using the format <tt class="docutils literal"><span class="pre">:param</span></tt>.</p>
 
1619
<p>The statement is executed within the current transactional context of
 
1620
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>. 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 set for
 
1621
&#8220;autocommit&#8221;, and no transaction is in progress, an ad-hoc transaction
 
1622
will be created for the life of the result (i.e., a connection is
 
1623
checked out from the connection pool, which is returned when the
 
1624
result object is closed).</p>
 
1625
<p>If the <a class="reference internal" href="#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> is not bound to an
 
1626
<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
 
1627
<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 given clause will be
 
1628
inspected for binds (i.e., looking for &#8220;bound metadata&#8221;). If the
 
1629
session is bound to multiple connectables, the <tt class="docutils literal"><span class="pre">mapper</span></tt> keyword
 
1630
argument is typically passed in to specify which bind should be used
 
1631
(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> keys multiple bind sources to a series of
 
1632
<tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt> objects). See <a class="reference internal" href="#sqlalchemy.orm.session.Session.get_bind" title="sqlalchemy.orm.session.Session.get_bind"><tt class="xref py py-meth docutils literal"><span class="pre">get_bind()</span></tt></a> for further details on
 
1633
bind resolution.</p>
 
1634
<table class="docutils field-list" frame="void" rules="none">
 
1635
<col class="field-name" />
 
1636
<col class="field-body" />
 
1637
<tbody valign="top">
 
1638
<tr class="field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
 
1639
<li><strong>clause</strong> &#8211; A ClauseElement (i.e. select(), text(), etc.) or
 
1640
string SQL statement to be executed</li>
 
1641
<li><strong>params</strong> &#8211; Optional, a dictionary of bind parameters.</li>
 
1642
<li><strong>mapper</strong> &#8211; Optional, a <tt class="docutils literal"><span class="pre">mapper</span></tt> or mapped class</li>
 
1643
<li><strong>**kw</strong> &#8211; 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>
 
1644
which locates a connectable to use for the execution.</li>
 
1645
</ul>
 
1646
</td>
 
1647
</tr>
 
1648
</tbody>
 
1649
</table>
 
1650
</dd></dl>
 
1651
 
 
1652
<dl class="method">
 
1653
<dt id="sqlalchemy.orm.session.Session.expire">
 
1654
<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>
 
1655
<dd><p>Expire the attributes on an instance.</p>
 
1656
<p>Marks the attributes of an instance as out of date. When an expired
 
1657
attribute is next accessed, a query will be issued to the
 
1658
<a class="reference internal" href="#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&#8217;s current transactional context in order to
 
1659
load all expired attributes for the given instance.   Note that
 
1660
a highly isolated transaction will return the same values as were 
 
1661
previously read in that same transaction, regardless of changes
 
1662
in database state outside of that transaction.</p>
 
1663
<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,
 
1664
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>
 
1665
<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&#8217;s default behavior is to 
 
1666
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>
 
1667
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
 
1668
state can be loaded for the new transaction.   For this reason,
 
1669
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
 
1670
case that a non-ORM SQL statement was emitted in the current
 
1671
transaction.</p>
 
1672
<table class="docutils field-list" frame="void" rules="none">
 
1673
<col class="field-name" />
 
1674
<col class="field-body" />
 
1675
<tbody valign="top">
 
1676
<tr class="field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
 
1677
<li><strong>instance</strong> &#8211; The instance to be refreshed.</li>
 
1678
<li><strong>attribute_names</strong> &#8211; optional list of string attribute names
 
1679
indicating a subset of attributes to be expired.</li>
 
1680
</ul>
 
1681
</td>
 
1682
</tr>
 
1683
</tbody>
 
1684
</table>
 
1685
</dd></dl>
 
1686
 
 
1687
<dl class="method">
 
1688
<dt id="sqlalchemy.orm.session.Session.expire_all">
 
1689
<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>
 
1690
<dd><p>Expires all persistent instances within this Session.</p>
 
1691
<p>When any attributes on a persitent instance is next accessed, 
 
1692
a query will be issued using the
 
1693
<a class="reference internal" href="#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&#8217;s current transactional context in order to
 
1694
load all expired attributes for the given instance.   Note that
 
1695
a highly isolated transaction will return the same values as were 
 
1696
previously read in that same transaction, regardless of changes
 
1697
in database state outside of that transaction.</p>
 
1698
<p>To expire individual objects and individual attributes 
 
1699
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>
 
1700
<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&#8217;s default behavior is to 
 
1701
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>
 
1702
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
 
1703
state can be loaded for the new transaction.   For this reason,
 
1704
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 
 
1705
autocommit is <tt class="xref docutils literal"><span class="pre">False</span></tt>, assuming the transaction is isolated.</p>
 
1706
</dd></dl>
 
1707
 
 
1708
<dl class="method">
 
1709
<dt id="sqlalchemy.orm.session.Session.expunge">
 
1710
<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>
 
1711
<dd><p>Remove the <cite>instance</cite> from this <tt class="docutils literal"><span class="pre">Session</span></tt>.</p>
 
1712
<p>This will free all internal references to the instance.  Cascading
 
1713
will be applied according to the <em>expunge</em> cascade rule.</p>
 
1714
</dd></dl>
 
1715
 
 
1716
<dl class="method">
 
1717
<dt id="sqlalchemy.orm.session.Session.expunge_all">
 
1718
<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>
 
1719
<dd><p>Remove all object instances from this <tt class="docutils literal"><span class="pre">Session</span></tt>.</p>
 
1720
<p>This is equivalent to calling <tt class="docutils literal"><span class="pre">expunge(obj)</span></tt> on all objects in this
 
1721
<tt class="docutils literal"><span class="pre">Session</span></tt>.</p>
 
1722
</dd></dl>
 
1723
 
 
1724
<dl class="method">
 
1725
<dt id="sqlalchemy.orm.session.Session.flush">
 
1726
<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>
 
1727
<dd><p>Flush all the object changes to the database.</p>
 
1728
<p>Writes out all pending object creations, deletions and modifications
 
1729
to the database as INSERTs, DELETEs, UPDATEs, etc.  Operations are
 
1730
automatically ordered by the Session&#8217;s unit of work dependency
 
1731
solver..</p>
 
1732
<p>Database operations will be issued in the current transactional
 
1733
context and do not affect the state of the transaction.  You may
 
1734
flush() as often as you like within a transaction to move changes from
 
1735
Python to the database&#8217;s transaction buffer.</p>
 
1736
<p>For <tt class="docutils literal"><span class="pre">autocommit</span></tt> Sessions with no active manual transaction, flush()
 
1737
will create a transaction on the fly that surrounds the entire set of
 
1738
operations int the flush.</p>
 
1739
<dl class="docutils">
 
1740
<dt>objects</dt>
 
1741
<dd>Optional; a list or tuple collection.  Restricts the flush operation
 
1742
to only these objects, rather than all pending changes.
 
1743
Deprecated - this flag prevents the session from properly maintaining
 
1744
accounting among inter-object relations and can cause invalid results.</dd>
 
1745
</dl>
 
1746
</dd></dl>
 
1747
 
 
1748
<dl class="method">
 
1749
<dt id="sqlalchemy.orm.session.Session.get_bind">
 
1750
<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>
 
1751
<dd><p>Return an engine corresponding to the given arguments.</p>
 
1752
<p>All arguments are optional.</p>
 
1753
<dl class="docutils">
 
1754
<dt>mapper</dt>
 
1755
<dd>Optional, a <tt class="docutils literal"><span class="pre">Mapper</span></tt> or mapped class</dd>
 
1756
<dt>clause</dt>
 
1757
<dd>Optional, A ClauseElement (i.e. select(), text(), etc.)</dd>
 
1758
</dl>
 
1759
</dd></dl>
 
1760
 
 
1761
<dl class="attribute">
 
1762
<dt id="sqlalchemy.orm.session.Session.is_active">
 
1763
<tt class="descname">is_active</tt><a class="headerlink" href="#sqlalchemy.orm.session.Session.is_active" title="Permalink to this definition">¶</a></dt>
 
1764
<dd><p>True if this Session has an active transaction.</p>
 
1765
</dd></dl>
 
1766
 
 
1767
<dl class="method">
 
1768
<dt id="sqlalchemy.orm.session.Session.is_modified">
 
1769
<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>
 
1770
<dd><p>Return <tt class="xref docutils literal"><span class="pre">True</span></tt> if instance has modified attributes.</p>
 
1771
<p>This method retrieves a history instance for each instrumented
 
1772
attribute on the instance and performs a comparison of the current
 
1773
value to its previously committed value.</p>
 
1774
<p><tt class="docutils literal"><span class="pre">include_collections</span></tt> indicates if multivalued collections should be
 
1775
included in the operation.  Setting this to False is a way to detect
 
1776
only local-column based properties (i.e. scalar columns or many-to-one
 
1777
foreign keys) that would result in an UPDATE for this instance upon
 
1778
flush.</p>
 
1779
<p>The <tt class="docutils literal"><span class="pre">passive</span></tt> flag indicates if unloaded attributes and collections
 
1780
should not be loaded in the course of performing this test.</p>
 
1781
<p>A few caveats to this method apply:</p>
 
1782
<ul>
 
1783
<li><p class="first">Instances present in the &#8216;dirty&#8217; collection may result in a value 
 
1784
of <tt class="xref docutils literal"><span class="pre">False</span></tt> when tested with this method.  This because while
 
1785
the object may have received attribute set events, there may be
 
1786
no net changes on its state.</p>
 
1787
</li>
 
1788
<li><p class="first">Scalar attributes may not have recorded the &#8220;previously&#8221; set
 
1789
value when a new value was applied, if the attribute was not loaded,
 
1790
or was expired, at the time the new value was received - in these
 
1791
cases, the attribute is assumed to have a change, even if there is
 
1792
ultimately no net change against its database value. SQLAlchemy in
 
1793
most cases does not need the &#8220;old&#8221; value when a set event occurs, so
 
1794
it skips the expense of a SQL call if the old value isn&#8217;t present,
 
1795
based on the assumption that an UPDATE of the scalar value is
 
1796
usually needed, and in those few cases where it isn&#8217;t, is less
 
1797
expensive on average than issuing a defensive SELECT.</p>
 
1798
<p>The &#8220;old&#8221; value is fetched unconditionally only if the attribute
 
1799
container has the &#8220;active_history&#8221; flag set to <tt class="xref docutils literal"><span class="pre">True</span></tt>. This flag
 
1800
is set typically for primary key attributes and scalar references
 
1801
that are not a simple many-to-one.</p>
 
1802
</li>
 
1803
</ul>
 
1804
</dd></dl>
 
1805
 
 
1806
<dl class="method">
 
1807
<dt id="sqlalchemy.orm.session.Session.merge">
 
1808
<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>
 
1809
<dd><p>Copy the state an instance onto the persistent instance with the same identifier.</p>
 
1810
<p>If there is no persistent instance currently associated with the
 
1811
session, it will be loaded.  Return the persistent instance. If the
 
1812
given instance is unsaved, save a copy of and return it as a newly
 
1813
persistent instance. The given instance does not become associated
 
1814
with the session.</p>
 
1815
<p>This operation cascades to associated instances if the association is
 
1816
mapped with <tt class="docutils literal"><span class="pre">cascade=&quot;merge&quot;</span></tt>.</p>
 
1817
<p>See <a class="reference internal" href="#unitofwork-merging"><em>Merging</em></a> for a detailed discussion of merging.</p>
 
1818
</dd></dl>
 
1819
 
 
1820
<dl class="attribute">
 
1821
<dt id="sqlalchemy.orm.session.Session.new">
 
1822
<tt class="descname">new</tt><a class="headerlink" href="#sqlalchemy.orm.session.Session.new" title="Permalink to this definition">¶</a></dt>
 
1823
<dd><p>The set of all instances marked as &#8216;new&#8217; within this <tt class="docutils literal"><span class="pre">Session</span></tt>.</p>
 
1824
</dd></dl>
 
1825
 
 
1826
<dl class="classmethod">
 
1827
<dt id="sqlalchemy.orm.session.Session.object_session">
 
1828
<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>
 
1829
<dd><p>Return the <tt class="docutils literal"><span class="pre">Session</span></tt> to which an object belongs.</p>
 
1830
</dd></dl>
 
1831
 
 
1832
<dl class="method">
 
1833
<dt id="sqlalchemy.orm.session.Session.prepare">
 
1834
<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>
 
1835
<dd><p>Prepare the current transaction in progress for two phase commit.</p>
 
1836
<p>If no transaction is in progress, this method raises an
 
1837
InvalidRequestError.</p>
 
1838
<p>Only root transactions of two phase sessions can be prepared. If the
 
1839
current transaction is not such, an InvalidRequestError is raised.</p>
 
1840
</dd></dl>
 
1841
 
 
1842
<dl class="method">
 
1843
<dt id="sqlalchemy.orm.session.Session.prune">
 
1844
<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>
 
1845
<dd><p>Remove unreferenced instances cached in the identity map.</p>
 
1846
<p>Note that this method is only meaningful if &#8220;weak_identity_map&#8221; is set
 
1847
to False.  The default weak identity map is self-pruning.</p>
 
1848
<p>Removes any object in this Session&#8217;s identity map that is not
 
1849
referenced in user code, modified, new or scheduled for deletion.
 
1850
Returns the number of objects pruned.</p>
 
1851
</dd></dl>
 
1852
 
 
1853
<dl class="method">
 
1854
<dt id="sqlalchemy.orm.session.Session.query">
 
1855
<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>
 
1856
<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>
 
1857
</dd></dl>
 
1858
 
 
1859
<dl class="method">
 
1860
<dt id="sqlalchemy.orm.session.Session.refresh">
 
1861
<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>
 
1862
<dd><p>Expire and refresh the attributes on the given instance.</p>
 
1863
<p>A query will be issued to the database and all attributes will be
 
1864
refreshed with their current database value.</p>
 
1865
<p>Lazy-loaded relational attributes will remain lazily loaded, so that
 
1866
the instance-wide refresh operation will be followed immediately by
 
1867
the lazy load of that attribute.</p>
 
1868
<p>Eagerly-loaded relational attributes will eagerly load within the
 
1869
single refresh operation.</p>
 
1870
<p>Note that a highly isolated transaction will return the same values as
 
1871
were previously read in that same transaction, regardless of changes
 
1872
in database state outside of that transaction - usage of
 
1873
<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
 
1874
statement were emitted in the ongoing transaction, or if autocommit
 
1875
mode is turned on.</p>
 
1876
<table class="docutils field-list" frame="void" rules="none">
 
1877
<col class="field-name" />
 
1878
<col class="field-body" />
 
1879
<tbody valign="top">
 
1880
<tr class="field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
 
1881
<li><strong>attribute_names</strong> &#8211; optional.  An iterable collection of
 
1882
string attribute names indicating a subset of attributes to 
 
1883
be refreshed.</li>
 
1884
<li><strong>lockmode</strong> &#8211; 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> 
 
1885
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>
 
1886
</ul>
 
1887
</td>
 
1888
</tr>
 
1889
</tbody>
 
1890
</table>
 
1891
</dd></dl>
 
1892
 
 
1893
<dl class="method">
 
1894
<dt id="sqlalchemy.orm.session.Session.rollback">
 
1895
<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>
 
1896
<dd><p>Rollback the current transaction in progress.</p>
 
1897
<p>If no transaction is in progress, this method is a pass-through.</p>
 
1898
<p>This method rolls back the current transaction or nested transaction
 
1899
regardless of subtransactions being in effect.  All subtransactions up
 
1900
to the first real transaction are closed.  Subtransactions occur when
 
1901
begin() is called multiple times.</p>
 
1902
</dd></dl>
 
1903
 
 
1904
<dl class="method">
 
1905
<dt id="sqlalchemy.orm.session.Session.scalar">
 
1906
<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>
 
1907
<dd><p>Like execute() but return a scalar result.</p>
 
1908
</dd></dl>
 
1909
 
 
1910
</dd></dl>
 
1911
 
 
1912
</div>
 
1913
<div class="section" id="contextual-thread-local-sessions">
 
1914
<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>
 
1915
<p>A common need in applications, particularly those built around web frameworks,
 
1916
is the ability to &#8220;share&#8221; 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
 
1917
among disparate parts of an application, without needing to pass the object
 
1918
explicitly to all method and function calls. What you&#8217;re really looking for is
 
1919
some kind of &#8220;global&#8221; session object, or at least &#8220;global&#8221; to all the parts of
 
1920
an application which are tasked with servicing the current request. For this
 
1921
pattern, SQLAlchemy provides the ability to enhance the
 
1922
<a class="reference internal" href="#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
 
1923
<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.
 
1924
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>
 
1925
instance with its constructor, you get an <em>existing</em>
 
1926
<a class="reference internal" href="#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
 
1927
&#8220;context&#8221;. By default, this context is the current thread. This feature is
 
1928
what previously was accomplished using the <tt class="docutils literal"><span class="pre">sessioncontext</span></tt> SQLAlchemy
 
1929
extension.</p>
 
1930
<div class="section" id="creating-a-thread-local-context">
 
1931
<h3>Creating a Thread-local Context<a class="headerlink" href="#creating-a-thread-local-context" title="Permalink to this headline">¶</a></h3>
 
1932
<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
 
1933
<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
 
1934
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
 
1935
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>
 
1936
<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>
 
1937
<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>
 
1938
</div>
 
1939
<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>
 
1940
&#8220;class&#8221;, in reality the object is pulled from a threadlocal variable, or if it
 
1941
doesn&#8217;t exist yet, it&#8217;s created using the underlying class generated by
 
1942
<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>
 
1943
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="c"># call Session() the first time.  the new Session instance is created.</span>
 
1944
<span class="gp">&gt;&gt;&gt; </span><span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
 
1945
 
 
1946
<span class="gp">&gt;&gt;&gt; </span><span class="c"># later, in the same application thread, someone else calls Session()</span>
 
1947
<span class="gp">&gt;&gt;&gt; </span><span class="n">session2</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span>
 
1948
 
 
1949
<span class="gp">&gt;&gt;&gt; </span><span class="c"># the two Session objects are *the same* object</span>
 
1950
<span class="gp">&gt;&gt;&gt; </span><span class="n">session</span> <span class="ow">is</span> <span class="n">session2</span>
 
1951
<span class="go">True</span></pre></div>
 
1952
</div>
 
1953
<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
 
1954
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
 
1955
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>
 
1956
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
 
1957
and properties at the &#8220;class&#8221; level, such that you don&#8217;t even need to
 
1958
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>
 
1959
<div class="highlight-python"><div class="highlight"><pre><span class="c"># create some objects</span>
 
1960
<span class="n">u1</span> <span class="o">=</span> <span class="n">User</span><span class="p">()</span>
 
1961
<span class="n">u2</span> <span class="o">=</span> <span class="n">User</span><span class="p">()</span>
 
1962
 
 
1963
<span class="c"># save to the contextual session, without instantiating</span>
 
1964
<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>
 
1965
<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>
 
1966
 
 
1967
<span class="c"># view the &quot;new&quot; attribute</span>
 
1968
<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>
 
1969
 
 
1970
<span class="c"># commit changes</span>
 
1971
<span class="n">Session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span></pre></div>
 
1972
</div>
 
1973
<p>The contextual session may be disposed of by calling <tt class="docutils literal"><span class="pre">Session.remove()</span></tt>:</p>
 
1974
<div class="highlight-python"><div class="highlight"><pre><span class="c"># remove current contextual session</span>
 
1975
<span class="n">Session</span><span class="o">.</span><span class="n">remove</span><span class="p">()</span></pre></div>
 
1976
</div>
 
1977
<p>After <tt class="docutils literal"><span class="pre">remove()</span></tt> is called, the next operation with the contextual session
 
1978
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
 
1979
thread.</p>
 
1980
</div>
 
1981
<div class="section" id="lifespan-of-a-contextual-session">
 
1982
<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>
 
1983
<p>A (really, really) common question is when does the contextual session get
 
1984
created, when does it get disposed ? We&#8217;ll consider a typical lifespan as used
 
1985
in a web application:</p>
 
1986
<div class="highlight-python"><pre>Web Server          Web Framework        User-defined Controller Call
 
1987
--------------      --------------       ------------------------------
 
1988
web request    -&gt;
 
1989
                    call controller -&gt;   # call Session().  this establishes a new,
 
1990
                                         # contextual Session.
 
1991
                                         session = Session()
 
1992
 
 
1993
                                         # load some objects, save some changes
 
1994
                                         objects = session.query(MyClass).all()
 
1995
 
 
1996
                                         # some other code calls Session, it's the
 
1997
                                         # same contextual session as "sess"
 
1998
                                         session2 = Session()
 
1999
                                         session2.add(foo)
 
2000
                                         session2.commit()
 
2001
 
 
2002
                                         # generate content to be returned
 
2003
                                         return generate_content()
 
2004
                    Session.remove() &lt;-
 
2005
web response   &lt;-</pre>
 
2006
</div>
 
2007
<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
 
2008
has the effect such that each web request starts fresh with a brand new
 
2009
session, and is the most definitive approach to closing out a request.</p>
 
2010
<p>It&#8217;s not strictly necessary to remove the session at the end of the request -
 
2011
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>,
 
2012
<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
 
2013
its connections to the pool and removes any existing transactional context.
 
2014
Doing nothing is an option too, if individual controller methods take responsibility
 
2015
for ensuring that no transactions remain open after a request ends.</p>
 
2016
</div>
 
2017
<div class="section" id="contextual-session-api">
 
2018
<h3>Contextual Session API<a class="headerlink" href="#contextual-session-api" title="Permalink to this headline">¶</a></h3>
 
2019
<dl class="function">
 
2020
<dt id="sqlalchemy.orm.scoped_session">
 
2021
<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>
 
2022
<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>
 
2023
<p>This is a front-end function to
 
2024
<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>
 
2025
<table class="docutils field-list" frame="void" rules="none">
 
2026
<col class="field-name" />
 
2027
<col class="field-body" />
 
2028
<tbody valign="top">
 
2029
<tr class="field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first simple">
 
2030
<li><strong>session_factory</strong> &#8211; a callable function that produces
 
2031
<a class="reference internal" href="#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>
 
2032
<li><strong>scopefunc</strong> &#8211; Optional &#8220;scope&#8221; function which would be
 
2033
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
 
2034
<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>
 
2035
</ul>
 
2036
</td>
 
2037
</tr>
 
2038
<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>
 
2039
</td>
 
2040
</tr>
 
2041
</tbody>
 
2042
</table>
 
2043
<p>Usage:</p>
 
2044
<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>
 
2045
</div>
 
2046
<p>To instantiate a Session object which is part of the scoped context,
 
2047
instantiate normally:</p>
 
2048
<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>
 
2049
</div>
 
2050
<p>Most session methods are available as classmethods from the scoped
 
2051
session:</p>
 
2052
<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>
 
2053
<span class="n">Session</span><span class="o">.</span><span class="n">close</span><span class="p">()</span></pre></div>
 
2054
</div>
 
2055
</dd></dl>
 
2056
 
 
2057
<dl class="class">
 
2058
<dt id="sqlalchemy.orm.scoping.ScopedSession">
 
2059
<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>
 
2060
<dd><p>Provides thread-local management of Sessions.</p>
 
2061
<p>Usage:</p>
 
2062
<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>
 
2063
</div>
 
2064
<p>... use Session normally.</p>
 
2065
<p>The internal registry is accessible as well,
 
2066
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>
 
2067
<dl class="method">
 
2068
<dt id="sqlalchemy.orm.scoping.ScopedSession.__init__">
 
2069
<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>
 
2070
<dd></dd></dl>
 
2071
 
 
2072
<dl class="method">
 
2073
<dt id="sqlalchemy.orm.scoping.ScopedSession.configure">
 
2074
<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>
 
2075
<dd><p>reconfigure the sessionmaker used by this ScopedSession.</p>
 
2076
</dd></dl>
 
2077
 
 
2078
<dl class="method">
 
2079
<dt id="sqlalchemy.orm.scoping.ScopedSession.mapper">
 
2080
<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>
 
2081
<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>
 
2082
<p class="deprecated">
 
2083
<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>
 
2084
</dd></dl>
 
2085
 
 
2086
<dl class="method">
 
2087
<dt id="sqlalchemy.orm.scoping.ScopedSession.query_property">
 
2088
<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>
 
2089
<dd><p>return a class property which produces a <cite>Query</cite> object against the
 
2090
class when called.</p>
 
2091
<p>e.g.:</p>
 
2092
<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>
 
2093
 
 
2094
<span class="k">class</span> <span class="nc">MyClass</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
 
2095
    <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>
 
2096
 
 
2097
<span class="c"># after mappers are defined</span>
 
2098
<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">&#39;foo&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">all</span><span class="p">()</span></pre></div>
 
2099
</div>
 
2100
<p>Produces instances of the session&#8217;s configured query class by
 
2101
default.  To override and use a custom implementation, provide
 
2102
a <tt class="docutils literal"><span class="pre">query_cls</span></tt> callable.  The callable will be invoked with
 
2103
the class&#8217;s mapper as a positional argument and a session
 
2104
keyword argument.</p>
 
2105
<p>There is no limit to the number of query properties placed on
 
2106
a class.</p>
 
2107
</dd></dl>
 
2108
 
 
2109
<dl class="method">
 
2110
<dt id="sqlalchemy.orm.scoping.ScopedSession.remove">
 
2111
<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>
 
2112
<dd><p>Dispose of the current contextual session.</p>
 
2113
</dd></dl>
 
2114
 
 
2115
</dd></dl>
 
2116
 
 
2117
<dl class="class">
 
2118
<dt id="sqlalchemy.util.ScopedRegistry">
 
2119
<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>
 
2120
<dd><p>A Registry that can store one or multiple instances of a single
 
2121
class on the basis of a &#8220;scope&#8221; function.</p>
 
2122
<p>The object implements <tt class="docutils literal"><span class="pre">__call__</span></tt> as the &#8220;getter&#8221;, so by
 
2123
calling <tt class="docutils literal"><span class="pre">myregistry()</span></tt> the contained object is returned
 
2124
for the current scope.</p>
 
2125
<table class="docutils field-list" frame="void" rules="none">
 
2126
<col class="field-name" />
 
2127
<col class="field-body" />
 
2128
<tbody valign="top">
 
2129
<tr class="field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
 
2130
<li><strong>createfunc</strong> &#8211; a callable that returns a new object to be placed in the registry</li>
 
2131
<li><strong>scopefunc</strong> &#8211; a callable that will return a key to store/retrieve an object.</li>
 
2132
</ul>
 
2133
</td>
 
2134
</tr>
 
2135
</tbody>
 
2136
</table>
 
2137
<dl class="method">
 
2138
<dt id="sqlalchemy.util.ScopedRegistry.__init__">
 
2139
<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>
 
2140
<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>
 
2141
<table class="docutils field-list" frame="void" rules="none">
 
2142
<col class="field-name" />
 
2143
<col class="field-body" />
 
2144
<tbody valign="top">
 
2145
<tr class="field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
 
2146
<li><strong>createfunc</strong> &#8211; A creation function that will generate
 
2147
a new value for the current scope, if none is present.</li>
 
2148
<li><strong>scopefunc</strong> &#8211; A function that returns a hashable
 
2149
token representing the current scope (such as, current
 
2150
thread identifier).</li>
 
2151
</ul>
 
2152
</td>
 
2153
</tr>
 
2154
</tbody>
 
2155
</table>
 
2156
</dd></dl>
 
2157
 
 
2158
<dl class="method">
 
2159
<dt id="sqlalchemy.util.ScopedRegistry.clear">
 
2160
<tt class="descname">clear</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.util.ScopedRegistry.clear" title="Permalink to this definition">¶</a></dt>
 
2161
<dd><p>Clear the current scope, if any.</p>
 
2162
</dd></dl>
 
2163
 
 
2164
<dl class="method">
 
2165
<dt id="sqlalchemy.util.ScopedRegistry.has">
 
2166
<tt class="descname">has</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.util.ScopedRegistry.has" title="Permalink to this definition">¶</a></dt>
 
2167
<dd><p>Return True if an object is present in the current scope.</p>
 
2168
</dd></dl>
 
2169
 
 
2170
<dl class="method">
 
2171
<dt id="sqlalchemy.util.ScopedRegistry.set">
 
2172
<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>
 
2173
<dd><p>Set the value forthe current scope.</p>
 
2174
</dd></dl>
 
2175
 
 
2176
</dd></dl>
 
2177
 
 
2178
<dl class="class">
 
2179
<dt id="sqlalchemy.util.ThreadLocalRegistry">
 
2180
<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>
 
2181
<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> 
 
2182
variable for storage.</p>
 
2183
</dd></dl>
 
2184
 
 
2185
</div>
 
2186
</div>
 
2187
<div class="section" id="partitioning-strategies">
 
2188
<span id="session-partitioning"></span><h2>Partitioning Strategies<a class="headerlink" href="#partitioning-strategies" title="Permalink to this headline">¶</a></h2>
 
2189
<div class="section" id="vertical-partitioning">
 
2190
<h3>Vertical Partitioning<a class="headerlink" href="#vertical-partitioning" title="Permalink to this headline">¶</a></h3>
 
2191
<p>Vertical partitioning places different kinds of objects, or different tables,
 
2192
across multiple databases:</p>
 
2193
<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">&#39;postgresql://db1&#39;</span><span class="p">)</span>
 
2194
<span class="n">engine2</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">&#39;postgresql://db2&#39;</span><span class="p">)</span>
 
2195
 
 
2196
<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>
 
2197
 
 
2198
<span class="c"># bind User operations to engine 1, Account operations to engine 2</span>
 
2199
<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>
 
2200
 
 
2201
<span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span></pre></div>
 
2202
</div>
 
2203
</div>
 
2204
<div class="section" id="horizontal-partitioning">
 
2205
<h3>Horizontal Partitioning<a class="headerlink" href="#horizontal-partitioning" title="Permalink to this headline">¶</a></h3>
 
2206
<p>Horizontal partitioning partitions the rows of a single table (or a set of
 
2207
tables) across multiple databases.</p>
 
2208
<p>See the &#8220;sharding&#8221; example: <a class="reference internal" href="examples.html#examples-sharding"><em>Horizontal Sharding</em></a>.</p>
 
2209
</div>
 
2210
</div>
 
2211
<div class="section" id="session-utilities">
 
2212
<h2>Session Utilities<a class="headerlink" href="#session-utilities" title="Permalink to this headline">¶</a></h2>
 
2213
<dl class="function">
 
2214
<dt id="sqlalchemy.orm.session.make_transient">
 
2215
<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>
 
2216
<dd><p>Make the given instance &#8216;transient&#8217;.</p>
 
2217
<p>This will remove its association with any 
 
2218
session and additionally will remove its &#8220;identity key&#8221;,
 
2219
such that it&#8217;s as though the object were newly constructed,
 
2220
except retaining its values.   It also resets the
 
2221
&#8220;deleted&#8221; flag on the state if this object
 
2222
had been explicitly deleted by its session.</p>
 
2223
<p>Attributes which were &#8220;expired&#8221; or deferred at the
 
2224
instance level are reverted to undefined, and 
 
2225
will not trigger any loads.</p>
 
2226
</dd></dl>
 
2227
 
 
2228
<dl class="function">
 
2229
<dt id="sqlalchemy.orm.session.object_session">
 
2230
<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>
 
2231
<dd><p>Return the <tt class="docutils literal"><span class="pre">Session</span></tt> to which instance belongs.</p>
 
2232
<p>If the instance is not a mapped instance, an error is raised.</p>
 
2233
</dd></dl>
 
2234
 
 
2235
</div>
 
2236
<div class="section" id="attribute-and-state-management-utilities">
 
2237
<h2>Attribute and State Management Utilities<a class="headerlink" href="#attribute-and-state-management-utilities" title="Permalink to this headline">¶</a></h2>
 
2238
<p>These functions are provided by the SQLAlchemy attribute
 
2239
instrumentation API to provide a detailed interface for dealing
 
2240
with instances, attribute values, and history.  Some of them
 
2241
are useful when constructing event listener functions, such as
 
2242
those described in <a class="reference internal" href="interfaces.html"><em>ORM Event Interfaces</em></a>.</p>
 
2243
<dl class="function">
 
2244
<dt id="sqlalchemy.orm.attributes.del_attribute">
 
2245
<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>
 
2246
<dd><p>Delete the value of an attribute, firing history events.</p>
 
2247
<p>This function may be used regardless of instrumentation
 
2248
applied directly to the class, i.e. no descriptors are required.
 
2249
Custom attribute management schemes will need to make usage
 
2250
of this method to establish attribute state as understood
 
2251
by SQLAlchemy.</p>
 
2252
</dd></dl>
 
2253
 
 
2254
<dl class="function">
 
2255
<dt id="sqlalchemy.orm.attributes.get_attribute">
 
2256
<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>
 
2257
<dd><p>Get the value of an attribute, firing any callables required.</p>
 
2258
<p>This function may be used regardless of instrumentation
 
2259
applied directly to the class, i.e. no descriptors are required.
 
2260
Custom attribute management schemes will need to make usage
 
2261
of this method to make usage of attribute state as understood
 
2262
by SQLAlchemy.</p>
 
2263
</dd></dl>
 
2264
 
 
2265
<dl class="function">
 
2266
<dt id="sqlalchemy.orm.attributes.get_history">
 
2267
<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>
 
2268
<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 
 
2269
and attribute key.</p>
 
2270
<table class="docutils field-list" frame="void" rules="none">
 
2271
<col class="field-name" />
 
2272
<col class="field-body" />
 
2273
<tbody valign="top">
 
2274
<tr class="field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
 
2275
<li><strong>obj</strong> &#8211; an object whose class is instrumented by the
 
2276
attributes package.</li>
 
2277
<li><strong>key</strong> &#8211; string attribute name.</li>
 
2278
<li><strong>kwargs</strong> &#8211; Optional keyword arguments currently
 
2279
include the <tt class="docutils literal"><span class="pre">passive</span></tt> flag, which indicates if the attribute should be
 
2280
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
 
2281
if the attribute should be not initialized to a blank value otherwise
 
2282
(<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>
 
2283
</ul>
 
2284
</td>
 
2285
</tr>
 
2286
</tbody>
 
2287
</table>
 
2288
</dd></dl>
 
2289
 
 
2290
<dl class="function">
 
2291
<dt id="sqlalchemy.orm.attributes.init_collection">
 
2292
<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>
 
2293
<dd><p>Initialize a collection attribute and return the collection adapter.</p>
 
2294
<p>This function is used to provide direct access to collection internals
 
2295
for a previously unloaded attribute.  e.g.:</p>
 
2296
<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">&#39;elements&#39;</span><span class="p">)</span>
 
2297
<span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">values</span><span class="p">:</span>
 
2298
    <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>
 
2299
</div>
 
2300
<dl class="docutils">
 
2301
<dt>For an easier way to do the above, see</dt>
 
2302
<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>
 
2303
</dl>
 
2304
<p>obj is an instrumented object instance.  An InstanceState
 
2305
is accepted directly for backwards compatibility but 
 
2306
this usage is deprecated.</p>
 
2307
</dd></dl>
 
2308
 
 
2309
<dl class="function">
 
2310
<dt id="sqlalchemy.orm.attributes.instance_state">
 
2311
<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>
 
2312
<dd><p>Return the <tt class="xref py py-class docutils literal"><span class="pre">InstanceState</span></tt> for a given object.</p>
 
2313
</dd></dl>
 
2314
 
 
2315
<dl class="function">
 
2316
<dt id="sqlalchemy.orm.attributes.is_instrumented">
 
2317
<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>
 
2318
<dd><p>Return True if the given attribute on the given instance is
 
2319
instrumented by the attributes package.</p>
 
2320
<p>This function may be used regardless of instrumentation
 
2321
applied directly to the class, i.e. no descriptors are required.</p>
 
2322
</dd></dl>
 
2323
 
 
2324
<dl class="function">
 
2325
<dt id="sqlalchemy.orm.attributes.manager_of_class">
 
2326
<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>
 
2327
<dd><p>Return the <tt class="xref py py-class docutils literal"><span class="pre">ClassManager</span></tt> for a given class.</p>
 
2328
</dd></dl>
 
2329
 
 
2330
<dl class="function">
 
2331
<dt id="sqlalchemy.orm.attributes.set_attribute">
 
2332
<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>
 
2333
<dd><p>Set the value of an attribute, firing history events.</p>
 
2334
<p>This function may be used regardless of instrumentation
 
2335
applied directly to the class, i.e. no descriptors are required.
 
2336
Custom attribute management schemes will need to make usage
 
2337
of this method to establish attribute state as understood
 
2338
by SQLAlchemy.</p>
 
2339
</dd></dl>
 
2340
 
 
2341
<dl class="function">
 
2342
<dt id="sqlalchemy.orm.attributes.set_committed_value">
 
2343
<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>
 
2344
<dd><p>Set the value of an attribute with no history events.</p>
 
2345
<p>Cancels any previous history present.  The value should be 
 
2346
a scalar value for scalar-holding attributes, or
 
2347
an iterable for any collection-holding attribute.</p>
 
2348
<p>This is the same underlying method used when a lazy loader
 
2349
fires off and loads additional data from the database.
 
2350
In particular, this method can be used by application code
 
2351
which has loaded additional attributes or collections through
 
2352
separate queries, which can then be attached to an instance
 
2353
as though it were part of its original loaded state.</p>
 
2354
</dd></dl>
 
2355
 
 
2356
<dl class="class">
 
2357
<dt id="sqlalchemy.orm.attributes.History">
 
2358
<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>
 
2359
<dd><p>A 3-tuple of added, unchanged and deleted values,
 
2360
representing the changes which have occured on an instrumented
 
2361
attribute.</p>
 
2362
<p>Each tuple member is an iterable sequence.</p>
 
2363
<dl class="attribute">
 
2364
<dt id="sqlalchemy.orm.attributes.History.added">
 
2365
<tt class="descname">added</tt><a class="headerlink" href="#sqlalchemy.orm.attributes.History.added" title="Permalink to this definition">¶</a></dt>
 
2366
<dd><p>Return the collection of items added to the attribute (the first tuple
 
2367
element).</p>
 
2368
</dd></dl>
 
2369
 
 
2370
<dl class="attribute">
 
2371
<dt id="sqlalchemy.orm.attributes.History.deleted">
 
2372
<tt class="descname">deleted</tt><a class="headerlink" href="#sqlalchemy.orm.attributes.History.deleted" title="Permalink to this definition">¶</a></dt>
 
2373
<dd><p>Return the collection of items that have been removed from the
 
2374
attribute (the third tuple element).</p>
 
2375
</dd></dl>
 
2376
 
 
2377
<dl class="method">
 
2378
<dt id="sqlalchemy.orm.attributes.History.empty">
 
2379
<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>
 
2380
<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
 
2381
and no existing, unchanged state.</p>
 
2382
</dd></dl>
 
2383
 
 
2384
<dl class="method">
 
2385
<dt id="sqlalchemy.orm.attributes.History.has_changes">
 
2386
<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>
 
2387
<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>
 
2388
</dd></dl>
 
2389
 
 
2390
<dl class="method">
 
2391
<dt id="sqlalchemy.orm.attributes.History.non_added">
 
2392
<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>
 
2393
<dd><p>Return a collection of unchanged + deleted.</p>
 
2394
</dd></dl>
 
2395
 
 
2396
<dl class="method">
 
2397
<dt id="sqlalchemy.orm.attributes.History.non_deleted">
 
2398
<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>
 
2399
<dd><p>Return a collection of added + unchanged.</p>
 
2400
</dd></dl>
 
2401
 
 
2402
<dl class="method">
 
2403
<dt id="sqlalchemy.orm.attributes.History.sum">
 
2404
<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>
 
2405
<dd><p>Return a collection of added + unchanged + deleted.</p>
 
2406
</dd></dl>
 
2407
 
 
2408
<dl class="attribute">
 
2409
<dt id="sqlalchemy.orm.attributes.History.unchanged">
 
2410
<tt class="descname">unchanged</tt><a class="headerlink" href="#sqlalchemy.orm.attributes.History.unchanged" title="Permalink to this definition">¶</a></dt>
 
2411
<dd><p>Return the collection of items that have not changed on the attribute
 
2412
(the second tuple element).</p>
 
2413
</dd></dl>
 
2414
 
 
2415
</dd></dl>
 
2416
 
 
2417
<dl class="attribute">
 
2418
<dt id="sqlalchemy.orm.attributes.sqlalchemy.orm.attributes.PASSIVE_NO_INITIALIZE">
 
2419
<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>
 
2420
<dd><p>Symbol indicating that loader callables should
 
2421
not be fired off, and a non-initialized attribute
 
2422
should remain that way.</p>
 
2423
</dd></dl>
 
2424
 
 
2425
<dl class="attribute">
 
2426
<dt id="sqlalchemy.orm.attributes.sqlalchemy.orm.attributes.PASSIVE_NO_FETCH">
 
2427
<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>
 
2428
<dd><p>Symbol indicating that loader callables should not boe fired off.
 
2429
Non-initialized attributes should be initialized to an empty value.</p>
 
2430
</dd></dl>
 
2431
 
 
2432
<dl class="attribute">
 
2433
<dt id="sqlalchemy.orm.attributes.sqlalchemy.orm.attributes.PASSIVE_OFF">
 
2434
<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>
 
2435
<dd><p>Symbol indicating that loader callables should be executed.</p>
 
2436
</dd></dl>
 
2437
 
 
2438
</div>
 
2439
</div>
 
2440
 
 
2441
            </div>
 
2442
        </div>
 
2443
 
 
2444
        
 
2445
        
 
2446
            <div class="bottomnav">
 
2447
                
 
2448
<div class="prevnext">
 
2449
        Previous:
 
2450
        <a href="inheritance.html" title="previous chapter">Mapping Class Inheritance Hierarchies</a>
 
2451
        Next:
 
2452
        <a href="query.html" title="next chapter">Querying</a>
 
2453
</div>
 
2454
 
 
2455
                <div class="doc_copyright">
 
2456
                    &copy; <a href="../copyright.html">Copyright</a> 2007-2011, the SQLAlchemy authors and contributors.
 
2457
                    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.0.1.
 
2458
                </div>
 
2459
            </div>
 
2460
        
 
2461
 
 
2462
 
 
2463
 
 
2464
 
 
2465
 
 
2466
 
 
2467
    </body>
 
2468
</html>
 
2469
 
 
2470
 
 
2471