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

« back to all changes in this revision

Viewing changes to doc/_sources/core/pooling.txt

  • Committer: Package Import Robot
  • Author(s): Piotr Ożarowski
  • Date: 2014-06-27 20:17:13 UTC
  • mfrom: (1.4.28)
  • Revision ID: package-import@ubuntu.com-20140627201713-g6p1kq8q1qenztrv
Tags: 0.9.6-1
* New upstream release
* Remove Python 3.X build tag files, thanks to Matthias Urlichs for the
  patch (closes: #747852)
* python-fdb isn't in the Debian archive yet so default dialect for firebird://
  URLs is changed to obsolete kinterbasdb, thanks to Russell Stuart for the
  patch (closes: #752145)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
.. _pooling_toplevel:
2
 
 
3
 
Connection Pooling
4
 
==================
5
 
 
6
 
.. module:: sqlalchemy.pool
7
 
 
8
 
A connection pool is a standard technique used to maintain
9
 
long running connections in memory for efficient re-use,
10
 
as well as to provide
11
 
management for the total number of connections an application
12
 
might use simultaneously.
13
 
 
14
 
Particularly for
15
 
server-side web applications, a connection pool is the standard way to
16
 
maintain a "pool" of active database connections in memory which are
17
 
reused across requests.
18
 
 
19
 
SQLAlchemy includes several connection pool implementations
20
 
which integrate with the :class:`.Engine`.  They can also be used
21
 
directly for applications that want to add pooling to an otherwise
22
 
plain DBAPI approach.
23
 
 
24
 
Connection Pool Configuration
25
 
-----------------------------
26
 
 
27
 
The :class:`~.engine.Engine` returned by the
28
 
:func:`~sqlalchemy.create_engine` function in most cases has a :class:`.QueuePool`
29
 
integrated, pre-configured with reasonable pooling defaults.  If
30
 
you're reading this section only to learn how to enable pooling - congratulations!
31
 
You're already done.
32
 
 
33
 
The most common :class:`.QueuePool` tuning parameters can be passed
34
 
directly to :func:`~sqlalchemy.create_engine` as keyword arguments:
35
 
``pool_size``, ``max_overflow``, ``pool_recycle`` and
36
 
``pool_timeout``.  For example::
37
 
 
38
 
  engine = create_engine('postgresql://me@localhost/mydb',
39
 
                         pool_size=20, max_overflow=0)
40
 
 
41
 
In the case of SQLite, the :class:`.SingletonThreadPool` or
42
 
:class:`.NullPool` are selected by the dialect to provide
43
 
greater compatibility with SQLite's threading and locking
44
 
model, as well as to provide a reasonable default behavior
45
 
to SQLite "memory" databases, which maintain their entire
46
 
dataset within the scope of a single connection.
47
 
 
48
 
All SQLAlchemy pool implementations have in common
49
 
that none of them "pre create" connections - all implementations wait
50
 
until first use before creating a connection.   At that point, if
51
 
no additional concurrent checkout requests for more connections
52
 
are made, no additional connections are created.   This is why it's perfectly
53
 
fine for :func:`.create_engine` to default to using a :class:`.QueuePool`
54
 
of size five without regard to whether or not the application really needs five connections
55
 
queued up - the pool would only grow to that size if the application
56
 
actually used five connections concurrently, in which case the usage of a
57
 
small pool is an entirely appropriate default behavior.
58
 
 
59
 
Switching Pool Implementations
60
 
------------------------------
61
 
 
62
 
The usual way to use a different kind of pool with :func:`.create_engine`
63
 
is to use the ``poolclass`` argument.   This argument accepts a class
64
 
imported from the ``sqlalchemy.pool`` module, and handles the details
65
 
of building the pool for you.   Common options include specifying
66
 
:class:`.QueuePool` with SQLite::
67
 
 
68
 
    from sqlalchemy.pool import QueuePool
69
 
    engine = create_engine('sqlite:///file.db', poolclass=QueuePool)
70
 
 
71
 
Disabling pooling using :class:`.NullPool`::
72
 
 
73
 
    from sqlalchemy.pool import NullPool
74
 
    engine = create_engine(
75
 
              'postgresql+psycopg2://scott:tiger@localhost/test',
76
 
              poolclass=NullPool)
77
 
 
78
 
Using a Custom Connection Function
79
 
----------------------------------
80
 
 
81
 
All :class:`.Pool` classes accept an argument ``creator`` which is
82
 
a callable that creates a new connection.  :func:`.create_engine`
83
 
accepts this function to pass onto the pool via an argument of
84
 
the same name::
85
 
 
86
 
    import sqlalchemy.pool as pool
87
 
    import psycopg2
88
 
 
89
 
    def getconn():
90
 
        c = psycopg2.connect(username='ed', host='127.0.0.1', dbname='test')
91
 
        # do things with 'c' to set up
92
 
        return c
93
 
 
94
 
    engine = create_engine('postgresql+psycopg2://', creator=getconn)
95
 
 
96
 
For most "initialize on connection" routines, it's more convenient
97
 
to use the :class:`.PoolEvents` event hooks, so that the usual URL argument to
98
 
:func:`.create_engine` is still usable.  ``creator`` is there as
99
 
a last resort for when a DBAPI has some form of ``connect``
100
 
that is not at all supported by SQLAlchemy.
101
 
 
102
 
Constructing a Pool
103
 
------------------------
104
 
 
105
 
To use a :class:`.Pool` by itself, the ``creator`` function is
106
 
the only argument that's required and is passed first, followed
107
 
by any additional options::
108
 
 
109
 
    import sqlalchemy.pool as pool
110
 
    import psycopg2
111
 
 
112
 
    def getconn():
113
 
        c = psycopg2.connect(username='ed', host='127.0.0.1', dbname='test')
114
 
        return c
115
 
 
116
 
    mypool = pool.QueuePool(getconn, max_overflow=10, pool_size=5)
117
 
 
118
 
DBAPI connections can then be procured from the pool using the :meth:`.Pool.connect`
119
 
function.  The return value of this method is a DBAPI connection that's contained
120
 
within a transparent proxy::
121
 
 
122
 
    # get a connection
123
 
    conn = mypool.connect()
124
 
 
125
 
    # use it
126
 
    cursor = conn.cursor()
127
 
    cursor.execute("select foo")
128
 
 
129
 
The purpose of the transparent proxy is to intercept the ``close()`` call,
130
 
such that instead of the DBAPI connection being closed, it's returned to the
131
 
pool::
132
 
 
133
 
    # "close" the connection.  Returns
134
 
    # it to the pool.
135
 
    conn.close()
136
 
 
137
 
The proxy also returns its contained DBAPI connection to the pool
138
 
when it is garbage collected,
139
 
though it's not deterministic in Python that this occurs immediately (though
140
 
it is typical with cPython).
141
 
 
142
 
The ``close()`` step also performs the important step of calling the
143
 
``rollback()`` method of the DBAPI connection.   This is so that any
144
 
existing transaction on the connection is removed, not only ensuring
145
 
that no existing state remains on next usage, but also so that table
146
 
and row locks are released as well as that any isolated data snapshots
147
 
are removed.   This behavior can be disabled using the ``reset_on_return``
148
 
option of :class:`.Pool`.
149
 
 
150
 
A particular pre-created :class:`.Pool` can be shared with one or more
151
 
engines by passing it to the ``pool`` argument of :func:`.create_engine`::
152
 
 
153
 
    e = create_engine('postgresql://', pool=mypool)
154
 
 
155
 
Pool Events
156
 
-----------
157
 
 
158
 
Connection pools support an event interface that allows hooks to execute
159
 
upon first connect, upon each new connection, and upon checkout and
160
 
checkin of connections.   See :class:`.PoolEvents` for details.
161
 
 
162
 
Dealing with Disconnects
163
 
------------------------
164
 
 
165
 
The connection pool has the ability to refresh individual connections as well as
166
 
its entire set of connections, setting the previously pooled connections as
167
 
"invalid".   A common use case is allow the connection pool to gracefully recover
168
 
when the database server has been restarted, and all previously established connections
169
 
are no longer functional.   There are two approaches to this.
170
 
 
171
 
Disconnect Handling - Optimistic
172
 
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
173
 
 
174
 
The most common approach is to let SQLAlchemy handle disconnects as they
175
 
occur, at which point the pool is refreshed.   This assumes the :class:`.Pool`
176
 
is used in conjunction with a :class:`.Engine`.  The :class:`.Engine` has
177
 
logic which can detect disconnection events and refresh the pool automatically.
178
 
 
179
 
When the :class:`.Connection` attempts to use a DBAPI connection, and an
180
 
exception is raised that corresponds to a "disconnect" event, the connection
181
 
is invalidated. The :class:`.Connection` then calls the :meth:`.Pool.recreate`
182
 
method, effectively invalidating all connections not currently checked out so
183
 
that they are replaced with new ones upon next checkout::
184
 
 
185
 
    from sqlalchemy import create_engine, exc
186
 
    e = create_engine(...)
187
 
    c = e.connect()
188
 
 
189
 
    try:
190
 
        # suppose the database has been restarted.
191
 
        c.execute("SELECT * FROM table")
192
 
        c.close()
193
 
    except exc.DBAPIError, e:
194
 
        # an exception is raised, Connection is invalidated.
195
 
        if e.connection_invalidated:
196
 
            print "Connection was invalidated!"
197
 
 
198
 
    # after the invalidate event, a new connection
199
 
    # starts with a new Pool
200
 
    c = e.connect()
201
 
    c.execute("SELECT * FROM table")
202
 
 
203
 
The above example illustrates that no special intervention is needed, the pool
204
 
continues normally after a disconnection event is detected.   However, an exception is
205
 
raised.   In a typical web application using an ORM Session, the above condition would
206
 
correspond to a single request failing with a 500 error, then the web application
207
 
continuing normally beyond that.   Hence the approach is "optimistic" in that frequent
208
 
database restarts are not anticipated.
209
 
 
210
 
Setting Pool Recycle
211
 
~~~~~~~~~~~~~~~~~~~~~~~
212
 
 
213
 
An additional setting that can augment the "optimistic" approach is to set the
214
 
pool recycle parameter.   This parameter prevents the pool from using a particular
215
 
connection that has passed a certain age, and is appropriate for database backends
216
 
such as MySQL that automatically close connections that have been stale after a particular
217
 
period of time::
218
 
 
219
 
    from sqlalchemy import create_engine
220
 
    e = create_engine("mysql://scott:tiger@localhost/test", pool_recycle=3600)
221
 
 
222
 
Above, any DBAPI connection that has been open for more than one hour will be invalidated and replaced,
223
 
upon next checkout.   Note that the invalidation **only** occurs during checkout - not on
224
 
any connections that are held in a checked out state.     ``pool_recycle`` is a function
225
 
of the :class:`.Pool` itself, independent of whether or not an :class:`.Engine` is in use.
226
 
 
227
 
Disconnect Handling - Pessimistic
228
 
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
229
 
 
230
 
At the expense of some extra SQL emitted for each connection checked out from the pool,
231
 
a "ping" operation established by a checkout event handler
232
 
can detect an invalid connection before it's used::
233
 
 
234
 
    from sqlalchemy import exc
235
 
    from sqlalchemy import event
236
 
    from sqlalchemy.pool import Pool
237
 
 
238
 
    @event.listens_for(Pool, "checkout")
239
 
    def ping_connection(dbapi_connection, connection_record, connection_proxy):
240
 
        cursor = dbapi_connection.cursor()
241
 
        try:
242
 
            cursor.execute("SELECT 1")
243
 
        except:
244
 
            # optional - dispose the whole pool
245
 
            # instead of invalidating one at a time
246
 
            # connection_proxy._pool.dispose()
247
 
 
248
 
            # raise DisconnectionError - pool will try
249
 
            # connecting again up to three times before raising.
250
 
            raise exc.DisconnectionError()
251
 
        cursor.close()
252
 
 
253
 
Above, the :class:`.Pool` object specifically catches :class:`~sqlalchemy.exc.DisconnectionError` and attempts
254
 
to create a new DBAPI connection, up to three times, before giving up and then raising
255
 
:class:`~sqlalchemy.exc.InvalidRequestError`, failing the connection.   This recipe will ensure
256
 
that a new :class:`.Connection` will succeed even if connections
257
 
in the pool have gone stale, provided that the database server is actually running.   The expense
258
 
is that of an additional execution performed per checkout.   When using the ORM :class:`.Session`,
259
 
there is one connection checkout per transaction, so the expense is fairly low.   The ping approach
260
 
above also works with straight connection pool usage, that is, even if no :class:`.Engine` were
261
 
involved.
262
 
 
263
 
The event handler can be tested using a script like the following, restarting the database
264
 
server at the point at which the script pauses for input::
265
 
 
266
 
    from sqlalchemy import create_engine
267
 
    e = create_engine("mysql://scott:tiger@localhost/test", echo_pool=True)
268
 
    c1 = e.connect()
269
 
    c2 = e.connect()
270
 
    c3 = e.connect()
271
 
    c1.close()
272
 
    c2.close()
273
 
    c3.close()
274
 
 
275
 
    # pool size is now three.
276
 
 
277
 
    print "Restart the server"
278
 
    raw_input()
279
 
 
280
 
    for i in xrange(10):
281
 
        c = e.connect()
282
 
        print c.execute("select 1").fetchall()
283
 
        c.close()
284
 
 
285
 
.. _pool_connection_invalidation:
286
 
 
287
 
More on Invalidation
288
 
^^^^^^^^^^^^^^^^^^^^
289
 
 
290
 
The :class:`.Pool` provides "connection invalidation" services which allow
291
 
both explicit invalidation of a connection as well as automatic invalidation
292
 
in response to conditions that are determined to render a connection unusable.
293
 
 
294
 
"Invalidation" means that a particular DBAPI connection is removed from the
295
 
pool and discarded.  The ``.close()`` method is called on this connection
296
 
if it is not clear that the connection itself might not be closed, however
297
 
if this method fails, the exception is logged but the operation still proceeds.
298
 
 
299
 
When using a :class:`.Engine`, the :meth:`.Connection.invalidate` method is
300
 
the usual entrypoint to explicit invalidation.   Other conditions by which
301
 
a DBAPI connection might be invalidated include:
302
 
 
303
 
* a DBAPI exception such as :class:`.OperationalError`, raised when a
304
 
  method like ``connection.execute()`` is called, is detected as indicating
305
 
  a so-called "disconnect" condition.   As the Python DBAPI provides no
306
 
  standard system for determining the nature of an exception, all SQLAlchemy
307
 
  dialects include a system called ``is_disconnect()`` which will examine
308
 
  the contents of an exception object, including the string message and
309
 
  any potential error codes included with it, in order to determine if this
310
 
  exception indicates that the connection is no longer usable.  If this is the
311
 
  case, the :meth:`._ConnectionFairy.invalidate` method is called and the
312
 
  DBAPI connection is then discarded.
313
 
 
314
 
* When the connection is returned to the pool, and
315
 
  calling the ``connection.rollback()`` or ``connection.commit()`` methods,
316
 
  as dictated by the pool's "reset on return" behavior, throws an exception.
317
 
  A final attempt at calling ``.close()`` on the connection will be made,
318
 
  and it is then discarded.
319
 
 
320
 
* When a listener implementing :meth:`.PoolEvents.checkout` raises the
321
 
  :class:`~sqlalchemy.exc.DisconnectionError` exception, indicating that the connection
322
 
  won't be usable and a new connection attempt needs to be made.
323
 
 
324
 
All invalidations which occur will invoke the :meth:`.PoolEvents.invalidate`
325
 
event.
326
 
 
327
 
 
328
 
 
329
 
 
330
 
API Documentation - Available Pool Implementations
331
 
---------------------------------------------------
332
 
 
333
 
.. autoclass:: sqlalchemy.pool.Pool
334
 
 
335
 
   .. automethod:: __init__
336
 
   .. automethod:: connect
337
 
   .. automethod:: dispose
338
 
   .. automethod:: recreate
339
 
   .. automethod:: unique_connection
340
 
 
341
 
.. autoclass:: sqlalchemy.pool.QueuePool
342
 
 
343
 
   .. automethod:: __init__
344
 
   .. automethod:: connect
345
 
   .. automethod:: unique_connection
346
 
 
347
 
.. autoclass:: SingletonThreadPool
348
 
 
349
 
   .. automethod:: __init__
350
 
 
351
 
.. autoclass:: AssertionPool
352
 
 
353
 
 
354
 
.. autoclass:: NullPool
355
 
 
356
 
 
357
 
.. autoclass:: StaticPool
358
 
 
359
 
.. autoclass:: _ConnectionFairy
360
 
    :members:
361
 
 
362
 
    .. autoattribute:: _connection_record
363
 
 
364
 
.. autoclass:: _ConnectionRecord
365
 
    :members:
366
 
 
367
 
 
368
 
Pooling Plain DB-API Connections
369
 
--------------------------------
370
 
 
371
 
Any :pep:`249` DB-API module can be "proxied" through the connection
372
 
pool transparently.  Usage of the DB-API is exactly as before, except
373
 
the ``connect()`` method will consult the pool.  Below we illustrate
374
 
this with ``psycopg2``::
375
 
 
376
 
    import sqlalchemy.pool as pool
377
 
    import psycopg2 as psycopg
378
 
 
379
 
    psycopg = pool.manage(psycopg)
380
 
 
381
 
    # then connect normally
382
 
    connection = psycopg.connect(database='test', username='scott',
383
 
                                 password='tiger')
384
 
 
385
 
This produces a :class:`_DBProxy` object which supports the same
386
 
``connect()`` function as the original DB-API module.  Upon
387
 
connection, a connection proxy object is returned, which delegates its
388
 
calls to a real DB-API connection object.  This connection object is
389
 
stored persistently within a connection pool (an instance of
390
 
:class:`.Pool`) that corresponds to the exact connection arguments sent
391
 
to the ``connect()`` function.
392
 
 
393
 
The connection proxy supports all of the methods on the original
394
 
connection object, most of which are proxied via ``__getattr__()``.
395
 
The ``close()`` method will return the connection to the pool, and the
396
 
``cursor()`` method will return a proxied cursor object.  Both the
397
 
connection proxy and the cursor proxy will also return the underlying
398
 
connection to the pool after they have both been garbage collected,
399
 
which is detected via weakref callbacks  (``__del__`` is not used).
400
 
 
401
 
Additionally, when connections are returned to the pool, a
402
 
``rollback()`` is issued on the connection unconditionally.  This is
403
 
to release any locks still held by the connection that may have
404
 
resulted from normal activity.
405
 
 
406
 
By default, the ``connect()`` method will return the same connection
407
 
that is already checked out in the current thread.  This allows a
408
 
particular connection to be used in a given thread without needing to
409
 
pass it around between functions.  To disable this behavior, specify
410
 
``use_threadlocal=False`` to the ``manage()`` function.
411
 
 
412
 
.. autofunction:: sqlalchemy.pool.manage
413
 
 
414
 
.. autofunction:: sqlalchemy.pool.clear_managers
415