6
.. module:: sqlalchemy.pool
8
A connection pool is a standard technique used to maintain
9
long running connections in memory for efficient re-use,
11
management for the total number of connections an application
12
might use simultaneously.
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.
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
24
Connection Pool Configuration
25
-----------------------------
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!
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::
38
engine = create_engine('postgresql://me@localhost/mydb',
39
pool_size=20, max_overflow=0)
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.
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.
59
Switching Pool Implementations
60
------------------------------
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::
68
from sqlalchemy.pool import QueuePool
69
engine = create_engine('sqlite:///file.db', poolclass=QueuePool)
71
Disabling pooling using :class:`.NullPool`::
73
from sqlalchemy.pool import NullPool
74
engine = create_engine(
75
'postgresql+psycopg2://scott:tiger@localhost/test',
78
Using a Custom Connection Function
79
----------------------------------
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
86
import sqlalchemy.pool as pool
90
c = psycopg2.connect(username='ed', host='127.0.0.1', dbname='test')
91
# do things with 'c' to set up
94
engine = create_engine('postgresql+psycopg2://', creator=getconn)
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.
103
------------------------
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::
109
import sqlalchemy.pool as pool
113
c = psycopg2.connect(username='ed', host='127.0.0.1', dbname='test')
116
mypool = pool.QueuePool(getconn, max_overflow=10, pool_size=5)
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::
123
conn = mypool.connect()
126
cursor = conn.cursor()
127
cursor.execute("select foo")
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
133
# "close" the connection. Returns
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).
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`.
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`::
153
e = create_engine('postgresql://', pool=mypool)
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.
162
Dealing with Disconnects
163
------------------------
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.
171
Disconnect Handling - Optimistic
172
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
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.
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::
185
from sqlalchemy import create_engine, exc
186
e = create_engine(...)
190
# suppose the database has been restarted.
191
c.execute("SELECT * FROM table")
193
except exc.DBAPIError, e:
194
# an exception is raised, Connection is invalidated.
195
if e.connection_invalidated:
196
print "Connection was invalidated!"
198
# after the invalidate event, a new connection
199
# starts with a new Pool
201
c.execute("SELECT * FROM table")
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.
211
~~~~~~~~~~~~~~~~~~~~~~~
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
219
from sqlalchemy import create_engine
220
e = create_engine("mysql://scott:tiger@localhost/test", pool_recycle=3600)
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.
227
Disconnect Handling - Pessimistic
228
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
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::
234
from sqlalchemy import exc
235
from sqlalchemy import event
236
from sqlalchemy.pool import Pool
238
@event.listens_for(Pool, "checkout")
239
def ping_connection(dbapi_connection, connection_record, connection_proxy):
240
cursor = dbapi_connection.cursor()
242
cursor.execute("SELECT 1")
244
# optional - dispose the whole pool
245
# instead of invalidating one at a time
246
# connection_proxy._pool.dispose()
248
# raise DisconnectionError - pool will try
249
# connecting again up to three times before raising.
250
raise exc.DisconnectionError()
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
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::
266
from sqlalchemy import create_engine
267
e = create_engine("mysql://scott:tiger@localhost/test", echo_pool=True)
275
# pool size is now three.
277
print "Restart the server"
282
print c.execute("select 1").fetchall()
285
.. _pool_connection_invalidation:
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.
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.
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:
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.
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.
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.
324
All invalidations which occur will invoke the :meth:`.PoolEvents.invalidate`
330
API Documentation - Available Pool Implementations
331
---------------------------------------------------
333
.. autoclass:: sqlalchemy.pool.Pool
335
.. automethod:: __init__
336
.. automethod:: connect
337
.. automethod:: dispose
338
.. automethod:: recreate
339
.. automethod:: unique_connection
341
.. autoclass:: sqlalchemy.pool.QueuePool
343
.. automethod:: __init__
344
.. automethod:: connect
345
.. automethod:: unique_connection
347
.. autoclass:: SingletonThreadPool
349
.. automethod:: __init__
351
.. autoclass:: AssertionPool
354
.. autoclass:: NullPool
357
.. autoclass:: StaticPool
359
.. autoclass:: _ConnectionFairy
362
.. autoattribute:: _connection_record
364
.. autoclass:: _ConnectionRecord
368
Pooling Plain DB-API Connections
369
--------------------------------
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``::
376
import sqlalchemy.pool as pool
377
import psycopg2 as psycopg
379
psycopg = pool.manage(psycopg)
381
# then connect normally
382
connection = psycopg.connect(database='test', username='scott',
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.
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).
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.
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.
412
.. autofunction:: sqlalchemy.pool.manage
414
.. autofunction:: sqlalchemy.pool.clear_managers