Connection Pooling

A connection pool is a standard technique used to maintain long running connections in memory for efficient re-use, as well as to provide management for the total number of connections an application might use simultaneously.

Particularly for server-side web applications, a connection pool is the standard way to maintain a “pool” of active database connections in memory which are reused across requests.

SQLAlchemy includes several connection pool implementations which integrate with the Engine. They can also be used directly for applications that want to add pooling to an otherwise plain DBAPI approach.

Connection Pool Configuration

The Engine returned by the create_engine() function in most cases has a QueuePool integrated, pre-configured with reasonable pooling defaults. If you’re reading this section only to learn how to enable pooling - congratulations! You’re already done.

The most common QueuePool tuning parameters can be passed directly to create_engine() as keyword arguments: pool_size, max_overflow, pool_recycle and pool_timeout. For example:

  1. engine = create_engine('postgresql://me@localhost/mydb',
  2. pool_size=20, max_overflow=0)

In the case of SQLite, the SingletonThreadPool or NullPool are selected by the dialect to provide greater compatibility with SQLite’s threading and locking model, as well as to provide a reasonable default behavior to SQLite “memory” databases, which maintain their entire dataset within the scope of a single connection.

All SQLAlchemy pool implementations have in common that none of them “pre create” connections - all implementations wait until first use before creating a connection. At that point, if no additional concurrent checkout requests for more connections are made, no additional connections are created. This is why it’s perfectly fine for create_engine() to default to using a QueuePool of size five without regard to whether or not the application really needs five connections queued up - the pool would only grow to that size if the application actually used five connections concurrently, in which case the usage of a small pool is an entirely appropriate default behavior.

Switching Pool Implementations

The usual way to use a different kind of pool with create_engine() is to use the poolclass argument. This argument accepts a class imported from the sqlalchemy.pool module, and handles the details of building the pool for you. Common options include specifying QueuePool with SQLite:

  1. from sqlalchemy.pool import QueuePool
  2. engine = create_engine('sqlite:///file.db', poolclass=QueuePool)

Disabling pooling using NullPool:

  1. from sqlalchemy.pool import NullPool
  2. engine = create_engine(
  3. 'postgresql+psycopg2://scott:tiger@localhost/test',
  4. poolclass=NullPool)

Using a Custom Connection Function

See the section Custom DBAPI connect() arguments / on-connect routines for a rundown of the various connection customization routines.

Constructing a Pool

To use a Pool by itself, the creator function is the only argument that’s required and is passed first, followed by any additional options:

  1. import sqlalchemy.pool as pool
  2. import psycopg2
  3. def getconn():
  4. c = psycopg2.connect(user='ed', host='127.0.0.1', dbname='test')
  5. return c
  6. mypool = pool.QueuePool(getconn, max_overflow=10, pool_size=5)

DBAPI connections can then be procured from the pool using the Pool.connect() function. The return value of this method is a DBAPI connection that’s contained within a transparent proxy:

  1. # get a connection
  2. conn = mypool.connect()
  3. # use it
  4. cursor = conn.cursor()
  5. cursor.execute("select foo")

The purpose of the transparent proxy is to intercept the close() call, such that instead of the DBAPI connection being closed, it is returned to the pool:

  1. # "close" the connection. Returns
  2. # it to the pool.
  3. conn.close()

The proxy also returns its contained DBAPI connection to the pool when it is garbage collected, though it’s not deterministic in Python that this occurs immediately (though it is typical with cPython). This usage is not recommended however and in particular is not supported with asyncio DBAPI drivers.

Reset On Return

The pool also includes the a “reset on return” feature which will call the rollback() method of the DBAPI connection when the connection is returned to the pool. This is so that any existing transaction on the connection is removed, not only ensuring that no existing state remains on next usage, but also so that table and row locks are released as well as that any isolated data snapshots are removed. This rollback() occurs in most cases even when using an Engine object, except in the case when the Connection can guarantee that a rollback() has been called immediately before the connection is returned to the pool.

For most DBAPIs, the call to rollback() is very inexpensive and if the DBAPI has already completed a transaction, the method should be a no-op. However, for DBAPIs that incur performance issues with rollback() even if there’s no state on the connection, this behavior can be disabled using the reset_on_return option of Pool. The behavior is safe to disable under the following conditions:

  • If the database does not support transactions at all, such as using MySQL with the MyISAM engine, or the DBAPI is used in autocommit mode only, the behavior can be disabled.

  • If the pool itself doesn’t maintain a connection after it’s checked in, such as when using NullPool, the behavior can be disabled.

  • Otherwise, it must be ensured that: * the application ensures that all Connection

    objects are explicitly closed out using a context manager (i.e. with block) or a try/finally style block

    • connections are never allowed to be garbage collected before being explicitly closed.

    • the DBAPI connection itself, e.g. connection.connection, is not used directly, or the application ensures that .rollback() is called on this connection before releasing it back to the connection pool.

The “reset on return” step may be logged using the logging.DEBUG log level along with the sqlalchemy.pool logger, or by setting echo_pool='debug' with create_engine().

Pool Events

Connection pools support an event interface that allows hooks to execute upon first connect, upon each new connection, and upon checkout and checkin of connections. See PoolEvents for details.

Dealing with Disconnects

The connection pool has the ability to refresh individual connections as well as its entire set of connections, setting the previously pooled connections as “invalid”. A common use case is allow the connection pool to gracefully recover when the database server has been restarted, and all previously established connections are no longer functional. There are two approaches to this.

Disconnect Handling - Pessimistic

The pessimistic approach refers to emitting a test statement on the SQL connection at the start of each connection pool checkout, to test that the database connection is still viable. Typically, this is a simple statement like “SELECT 1”, but may also make use of some DBAPI-specific method to test the connection for liveness.

The approach adds a small bit of overhead to the connection checkout process, however is otherwise the most simple and reliable approach to completely eliminating database errors due to stale pooled connections. The calling application does not need to be concerned about organizing operations to be able to recover from stale connections checked out from the pool.

It is critical to note that the pre-ping approach does not accommodate for connections dropped in the middle of transactions or other SQL operations. If the database becomes unavailable while a transaction is in progress, the transaction will be lost and the database error will be raised. While the Connection object will detect a “disconnect” situation and recycle the connection as well as invalidate the rest of the connection pool when this condition occurs, the individual operation where the exception was raised will be lost, and it’s up to the application to either abandon the operation, or retry the whole transaction again. If the engine is configured using DBAPI-level autocommit connections, as described at Setting Transaction Isolation Levels including DBAPI Autocommit, a connection may be reconnected transparently mid-operation using events. See the section How Do I “Retry” a Statement Execution Automatically? for an example.

Pessimistic testing of connections upon checkout is achievable by using the Pool.pre_ping argument, available from create_engine() via the create_engine.pool_pre_ping argument:

  1. engine = create_engine("mysql+pymysql://user:pw@host/db", pool_pre_ping=True)

The “pre ping” feature will normally emit SQL equivalent to “SELECT 1” each time a connection is checked out from the pool; if an error is raised that is detected as a “disconnect” situation, the connection will be immediately recycled, and all other pooled connections older than the current time are invalidated, so that the next time they are checked out, they will also be recycled before use.

If the database is still not available when “pre ping” runs, then the initial connect will fail and the error for failure to connect will be propagated normally. In the uncommon situation that the database is available for connections, but is not able to respond to a “ping”, the “pre_ping” will try up to three times before giving up, propagating the database error last received.

Note

the “SELECT 1” emitted by “pre-ping” is invoked within the scope of the connection pool / dialect, using a very short codepath for minimal Python latency. As such, this statement is not logged in the SQL echo output, and will not show up in SQLAlchemy’s engine logging.

New in version 1.2: Added “pre-ping” capability to the Pool class.

Custom / Legacy Pessimistic Ping

Before create_engine.pool_pre_ping was added, the “pre-ping” approach historically has been performed manually using the ConnectionEvents.engine_connect() engine event. The most common recipe for this is below, for reference purposes in case an application is already using such a recipe, or special behaviors are needed:

  1. from sqlalchemy import exc
  2. from sqlalchemy import event
  3. from sqlalchemy import select
  4. some_engine = create_engine(...)
  5. @event.listens_for(some_engine, "engine_connect")
  6. def ping_connection(connection, branch):
  7. if branch:
  8. # "branch" refers to a sub-connection of a connection,
  9. # we don't want to bother pinging on these.
  10. return
  11. # turn off "close with result". This flag is only used with
  12. # "connectionless" execution, otherwise will be False in any case
  13. save_should_close_with_result = connection.should_close_with_result
  14. connection.should_close_with_result = False
  15. try:
  16. # run a SELECT 1. use a core select() so that
  17. # the SELECT of a scalar value without a table is
  18. # appropriately formatted for the backend
  19. connection.scalar(select(1))
  20. except exc.DBAPIError as err:
  21. # catch SQLAlchemy's DBAPIError, which is a wrapper
  22. # for the DBAPI's exception. It includes a .connection_invalidated
  23. # attribute which specifies if this connection is a "disconnect"
  24. # condition, which is based on inspection of the original exception
  25. # by the dialect in use.
  26. if err.connection_invalidated:
  27. # run the same SELECT again - the connection will re-validate
  28. # itself and establish a new connection. The disconnect detection
  29. # here also causes the whole connection pool to be invalidated
  30. # so that all stale connections are discarded.
  31. connection.scalar(select(1))
  32. else:
  33. raise
  34. finally:
  35. # restore "close with result"
  36. connection.should_close_with_result = save_should_close_with_result

The above recipe has the advantage that we are making use of SQLAlchemy’s facilities for detecting those DBAPI exceptions that are known to indicate a “disconnect” situation, as well as the Engine object’s ability to correctly invalidate the current connection pool when this condition occurs and allowing the current Connection to re-validate onto a new DBAPI connection.

Disconnect Handling - Optimistic

When pessimistic handling is not employed, as well as when the database is shutdown and/or restarted in the middle of a connection’s period of use within a transaction, the other approach to dealing with stale / closed connections is to let SQLAlchemy handle disconnects as they occur, at which point all connections in the pool are invalidated, meaning they are assumed to be stale and will be refreshed upon next checkout. This behavior assumes the Pool is used in conjunction with a Engine. The Engine has logic which can detect disconnection events and refresh the pool automatically.

When the Connection attempts to use a DBAPI connection, and an exception is raised that corresponds to a “disconnect” event, the connection is invalidated. The Connection then calls the Pool.recreate() method, effectively invalidating all connections not currently checked out so that they are replaced with new ones upon next checkout. This flow is illustrated by the code example below:

  1. from sqlalchemy import create_engine, exc
  2. e = create_engine(...)
  3. c = e.connect()
  4. try:
  5. # suppose the database has been restarted.
  6. c.execute(text("SELECT * FROM table"))
  7. c.close()
  8. except exc.DBAPIError, e:
  9. # an exception is raised, Connection is invalidated.
  10. if e.connection_invalidated:
  11. print("Connection was invalidated!")
  12. # after the invalidate event, a new connection
  13. # starts with a new Pool
  14. c = e.connect()
  15. c.execute(text("SELECT * FROM table"))

The above example illustrates that no special intervention is needed to refresh the pool, which continues normally after a disconnection event is detected. However, one database exception is raised, per each connection that is in use while the database unavailability event occurred. In a typical web application using an ORM Session, the above condition would correspond to a single request failing with a 500 error, then the web application continuing normally beyond that. Hence the approach is “optimistic” in that frequent database restarts are not anticipated.

Setting Pool Recycle

An additional setting that can augment the “optimistic” approach is to set the pool recycle parameter. This parameter prevents the pool from using a particular connection that has passed a certain age, and is appropriate for database backends such as MySQL that automatically close connections that have been stale after a particular period of time:

  1. from sqlalchemy import create_engine
  2. e = create_engine("mysql://scott:tiger@localhost/test", pool_recycle=3600)

Above, any DBAPI connection that has been open for more than one hour will be invalidated and replaced, upon next checkout. Note that the invalidation only occurs during checkout - not on any connections that are held in a checked out state. pool_recycle is a function of the Pool itself, independent of whether or not an Engine is in use.

More on Invalidation

The Pool provides “connection invalidation” services which allow both explicit invalidation of a connection as well as automatic invalidation in response to conditions that are determined to render a connection unusable.

“Invalidation” means that a particular DBAPI connection is removed from the pool and discarded. The .close() method is called on this connection if it is not clear that the connection itself might not be closed, however if this method fails, the exception is logged but the operation still proceeds.

When using a Engine, the Connection.invalidate() method is the usual entrypoint to explicit invalidation. Other conditions by which a DBAPI connection might be invalidated include:

  • a DBAPI exception such as OperationalError, raised when a method like connection.execute() is called, is detected as indicating a so-called “disconnect” condition. As the Python DBAPI provides no standard system for determining the nature of an exception, all SQLAlchemy dialects include a system called is_disconnect() which will examine the contents of an exception object, including the string message and any potential error codes included with it, in order to determine if this exception indicates that the connection is no longer usable. If this is the case, the _ConnectionFairy.invalidate() method is called and the DBAPI connection is then discarded.

  • When the connection is returned to the pool, and calling the connection.rollback() or connection.commit() methods, as dictated by the pool’s “reset on return” behavior, throws an exception. A final attempt at calling .close() on the connection will be made, and it is then discarded.

  • When a listener implementing PoolEvents.checkout() raises the DisconnectionError exception, indicating that the connection won’t be usable and a new connection attempt needs to be made.

All invalidations which occur will invoke the PoolEvents.invalidate() event.

Using FIFO vs. LIFO

The QueuePool class features a flag called QueuePool.use_lifo, which can also be accessed from create_engine() via the flag create_engine.pool_use_lifo. Setting this flag to True causes the pool’s “queue” behavior to instead be that of a “stack”, e.g. the last connection to be returned to the pool is the first one to be used on the next request. In contrast to the pool’s long- standing behavior of first-in-first-out, which produces a round-robin effect of using each connection in the pool in series, lifo mode allows excess connections to remain idle in the pool, allowing server-side timeout schemes to close these connections out. The difference between FIFO and LIFO is basically whether or not its desirable for the pool to keep a full set of connections ready to go even during idle periods:

  1. engine = create_engine(
  2. "postgreql://", pool_use_lifo=True, pool_pre_ping=True)

Above, we also make use of the create_engine.pool_pre_ping flag so that connections which are closed from the server side are gracefully handled by the connection pool and replaced with a new connection.

Note that the flag only applies to QueuePool use.

New in version 1.3.

See also

Dealing with Disconnects

Using Connection Pools with Multiprocessing or os.fork()

It’s critical that when using a connection pool, and by extension when using an Engine created via create_engine(), that the pooled connections are not shared to a forked process. TCP connections are represented as file descriptors, which usually work across process boundaries, meaning this will cause concurrent access to the file descriptor on behalf of two or more entirely independent Python interpreter states.

Depending on specifics of the driver and OS, the issues that arise here range from non-working connections to socket connections that are used by multiple processes concurrently, leading to broken messaging (the latter case is typically the most common).

The SQLAlchemy Engine object refers to a connection pool of existing database connections. So when this object is replicated to a child process, the goal is to ensure that no database connections are carried over. There are three general approaches to this:

  1. Disable pooling using NullPool. This is the most simplistic, one shot system that prevents the Engine from using any connection more than once:

    1. from sqlalchemy.pool import NullPool
    2. engine = create_engine("mysql://user:pass@host/dbname", poolclass=NullPool)
  2. Call Engine.dispose() on any given Engine as soon one is within the new process. In Python multiprocessing, constructs such as multiprocessing.Pool include “initializer” hooks which are a place that this can be performed; otherwise at the top of where os.fork() or where the Process object begins the child fork, a single call to Engine.dispose() will ensure any remaining connections are flushed. This is the recommended approach:

    1. engine = create_engine("mysql://user:pass@host/dbname")
    2. def run_in_process():
    3. # process starts. ensure engine.dispose() is called just once
    4. # at the beginning
    5. engine.dispose()
    6. with engine.connect() as conn:
    7. conn.execute(text("..."))
    8. p = Process(target=run_in_process)
    9. p.start()
  3. An event handler can be applied to the connection pool that tests for connections being shared across process boundaries, and invalidates them. This approach, when combined with an explicit call to dispose() as mentioned above, should cover all cases:

    1. from sqlalchemy import event
    2. from sqlalchemy import exc
    3. import os
    4. engine = create_engine("...")
    5. @event.listens_for(engine, "connect")
    6. def connect(dbapi_connection, connection_record):
    7. connection_record.info['pid'] = os.getpid()
    8. @event.listens_for(engine, "checkout")
    9. def checkout(dbapi_connection, connection_record, connection_proxy):
    10. pid = os.getpid()
    11. if connection_record.info['pid'] != pid:
    12. connection_record.connection = connection_proxy.connection = None
    13. raise exc.DisconnectionError(
    14. "Connection record belongs to pid %s, "
    15. "attempting to check out in pid %s" %
    16. (connection_record.info['pid'], pid)
    17. )

    Above, we use an approach similar to that described in Disconnect Handling - Pessimistic to treat a DBAPI connection that originated in a different parent process as an “invalid” connection, coercing the pool to recycle the connection record to make a new connection.

    When using the above recipe, ensure the dispose approach from #2 is also used, as if the connection pool is exhausted in the parent process when the fork occurs, an empty pool will be copied into the child process which will then hang because it has no connections.

The above strategies will accommodate the case of an Engine being shared among processes. However, for the case of a transaction-active Session or Connection being shared, there’s no automatic fix for this; an application needs to ensure a new child process only initiate new Connection objects and transactions, as well as ORM Session objects. For a Session object, technically this is only needed if the session is currently transaction-bound, however the scope of a single Session is in any case intended to be kept within a single call stack in any case (e.g. not a global object, not shared between processes or threads).

API Documentation - Available Pool Implementations

Object NameDescription

_ConnectionFairy

Proxies a DBAPI connection and provides return-on-dereference support.

_ConnectionRecord

Internal object which maintains an individual DBAPI connection referenced by a Pool.

AssertionPool

A Pool that allows at most one checked out connection at any given time.

NullPool

A Pool which does not pool connections.

Pool

Abstract base class for connection pools.

QueuePool

A Pool that imposes a limit on the number of open connections.

SingletonThreadPool

A Pool that maintains one connection per thread.

StaticPool

A Pool of exactly one connection, used for all requests.

class sqlalchemy.pool.``Pool(creator, recycle=- 1, echo=None, logging_name=None, reset_on_return=True, events=None, dialect=None, pre_ping=False, _dispatch=None)

Abstract base class for connection pools.

Class signature

class sqlalchemy.pool.Pool (sqlalchemy.log.Identified)

  • method sqlalchemy.pool.Pool.__init__(creator, recycle=- 1, echo=None, logging_name=None, reset_on_return=True, events=None, dialect=None, pre_ping=False, _dispatch=None)

    Construct a Pool.

    • Parameters

      • creator – a callable function that returns a DB-API connection object. The function will be called with parameters.

      • recycle – If set to a value other than -1, number of seconds between connection recycling, which means upon checkout, if this timeout is surpassed the connection will be closed and replaced with a newly opened connection. Defaults to -1.

      • logging_name – String identifier which will be used within the “name” field of logging records generated within the “sqlalchemy.pool” logger. Defaults to a hexstring of the object’s id.

      • echo

        if True, the connection pool will log informational output such as when connections are invalidated as well as when connections are recycled to the default log handler, which defaults to sys.stdout for output.. If set to the string "debug", the logging will include pool checkouts and checkins.

        The Pool.echo parameter can also be set from the create_engine() call by using the create_engine.echo_pool parameter.

        See also

        Configuring Logging - further detail on how to configure logging.

      • reset_on_return

        Determine steps to take on

        connections as they are returned to the pool, which were not otherwise handled by a Connection.

        reset_on_return can have any of these values:

        • "rollback" - call rollback() on the connection, to release locks and transaction resources. This is the default value. The vast majority of use cases should leave this value set.

        • True - same as ‘rollback’, this is here for backwards compatibility.

        • "commit" - call commit() on the connection, to release locks and transaction resources. A commit here may be desirable for databases that cache query plans if a commit is emitted, such as Microsoft SQL Server. However, this value is more dangerous than ‘rollback’ because any data changes present on the transaction are committed unconditionally.

        • None - don’t do anything on the connection. This setting is only appropriate if the database / DBAPI works in pure “autocommit” mode at all times, or if the application uses the Engine with consistent connectivity patterns. See the section Reset On Return for more details.

        • False - same as None, this is here for backwards compatibility.

        See also

        Reset On Return

      • events – a list of 2-tuples, each of the form (callable, target) which will be passed to listen() upon construction. Provided here so that event listeners can be assigned via create_engine() before dialect-level listeners are applied.

      • dialect

        a Dialect that will handle the job of calling rollback(), close(), or commit() on DBAPI connections. If omitted, a built-in “stub” dialect is used. Applications that make use of create_engine() should not use this parameter as it is handled by the engine creation strategy.

        New in version 1.1: - dialect is now a public parameter to the Pool.

      • pre_ping

        if True, the pool will emit a “ping” (typically “SELECT 1”, but is dialect-specific) on the connection upon checkout, to test if the connection is alive or not. If not, the connection is transparently re-connected and upon success, all other pooled connections established prior to that timestamp are invalidated. Requires that a dialect is passed as well to interpret the disconnection error.

        New in version 1.2.

  • method sqlalchemy.pool.Pool.connect()

    Return a DBAPI connection from the pool.

    The connection is instrumented such that when its close() method is called, the connection will be returned to the pool.

  • method sqlalchemy.pool.Pool.dispose()

    Dispose of this pool.

    This method leaves the possibility of checked-out connections remaining open, as it only affects connections that are idle in the pool.

    See also

    Pool.recreate()

  • method sqlalchemy.pool.Pool.recreate()

    Return a new Pool, of the same class as this one and configured with identical creation arguments.

    This method is used in conjunction with dispose() to close out an entire Pool and create a new one in its place.

class sqlalchemy.pool.``QueuePool(creator, pool_size=5, max_overflow=10, timeout=30.0, use_lifo=False, \*kw*)

A Pool that imposes a limit on the number of open connections.

QueuePool is the default pooling implementation used for all Engine objects, unless the SQLite dialect is in use.

Class signature

class sqlalchemy.pool.QueuePool (sqlalchemy.pool.base.Pool)

  • method sqlalchemy.pool.QueuePool.__init__(creator, pool_size=5, max_overflow=10, timeout=30.0, use_lifo=False, \*kw*)

    Construct a QueuePool.

    • Parameters

      • creator – a callable function that returns a DB-API connection object, same as that of Pool.creator.

      • pool_size – The size of the pool to be maintained, defaults to 5. This is the largest number of connections that will be kept persistently in the pool. Note that the pool begins with no connections; once this number of connections is requested, that number of connections will remain. pool_size can be set to 0 to indicate no size limit; to disable pooling, use a NullPool instead.

      • max_overflow – The maximum overflow size of the pool. When the number of checked-out connections reaches the size set in pool_size, additional connections will be returned up to this limit. When those additional connections are returned to the pool, they are disconnected and discarded. It follows then that the total number of simultaneous connections the pool will allow is pool_size + max_overflow, and the total number of “sleeping” connections the pool will allow is pool_size. max_overflow can be set to -1 to indicate no overflow limit; no limit will be placed on the total number of concurrent connections. Defaults to 10.

      • timeout – The number of seconds to wait before giving up on returning a connection. Defaults to 30.0. This can be a float but is subject to the limitations of Python time functions which may not be reliable in the tens of milliseconds.

      • use_lifo

        use LIFO (last-in-first-out) when retrieving connections instead of FIFO (first-in-first-out). Using LIFO, a server-side timeout scheme can reduce the number of connections used during non-peak periods of use. When planning for server-side timeouts, ensure that a recycle or pre-ping strategy is in use to gracefully handle stale connections.

        New in version 1.3.

        See also

        Using FIFO vs. LIFO

        Dealing with Disconnects

      • **kw – Other keyword arguments including Pool.recycle, Pool.echo, Pool.reset_on_return and others are passed to the Pool constructor.

  • method sqlalchemy.pool.QueuePool.connect()

    inherited from the Pool.connect() method of Pool

    Return a DBAPI connection from the pool.

    The connection is instrumented such that when its close() method is called, the connection will be returned to the pool.

class sqlalchemy.pool.``SingletonThreadPool(creator, pool_size=5, \*kw*)

A Pool that maintains one connection per thread.

Maintains one connection per each thread, never moving a connection to a thread other than the one which it was created in.

Warning

the SingletonThreadPool will call .close() on arbitrary connections that exist beyond the size setting of pool_size, e.g. if more unique thread identities than what pool_size states are used. This cleanup is non-deterministic and not sensitive to whether or not the connections linked to those thread identities are currently in use.

SingletonThreadPool may be improved in a future release, however in its current status it is generally used only for test scenarios using a SQLite :memory: database and is not recommended for production use.

Options are the same as those of Pool, as well as:

  • Parameters

    pool_size – The number of threads in which to maintain connections at once. Defaults to five.

SingletonThreadPool is used by the SQLite dialect automatically when a memory-based database is used. See SQLite.

Class signature

class sqlalchemy.pool.SingletonThreadPool (sqlalchemy.pool.base.Pool)

  • method sqlalchemy.pool.SingletonThreadPool.__init__(creator, pool_size=5, \*kw*)

    Construct a Pool.

    • Parameters

      • creator – a callable function that returns a DB-API connection object. The function will be called with parameters.

      • recycle – If set to a value other than -1, number of seconds between connection recycling, which means upon checkout, if this timeout is surpassed the connection will be closed and replaced with a newly opened connection. Defaults to -1.

      • logging_name – String identifier which will be used within the “name” field of logging records generated within the “sqlalchemy.pool” logger. Defaults to a hexstring of the object’s id.

      • echo

        if True, the connection pool will log informational output such as when connections are invalidated as well as when connections are recycled to the default log handler, which defaults to sys.stdout for output.. If set to the string "debug", the logging will include pool checkouts and checkins.

        The Pool.echo parameter can also be set from the create_engine() call by using the create_engine.echo_pool parameter.

        See also

        Configuring Logging - further detail on how to configure logging.

      • reset_on_return

        Determine steps to take on

        connections as they are returned to the pool, which were not otherwise handled by a Connection.

        reset_on_return can have any of these values:

        • "rollback" - call rollback() on the connection, to release locks and transaction resources. This is the default value. The vast majority of use cases should leave this value set.

        • True - same as ‘rollback’, this is here for backwards compatibility.

        • "commit" - call commit() on the connection, to release locks and transaction resources. A commit here may be desirable for databases that cache query plans if a commit is emitted, such as Microsoft SQL Server. However, this value is more dangerous than ‘rollback’ because any data changes present on the transaction are committed unconditionally.

        • None - don’t do anything on the connection. This setting is only appropriate if the database / DBAPI works in pure “autocommit” mode at all times, or if the application uses the Engine with consistent connectivity patterns. See the section Reset On Return for more details.

        • False - same as None, this is here for backwards compatibility.

        See also

        Reset On Return

      • events – a list of 2-tuples, each of the form (callable, target) which will be passed to listen() upon construction. Provided here so that event listeners can be assigned via create_engine() before dialect-level listeners are applied.

      • dialect

        a Dialect that will handle the job of calling rollback(), close(), or commit() on DBAPI connections. If omitted, a built-in “stub” dialect is used. Applications that make use of create_engine() should not use this parameter as it is handled by the engine creation strategy.

        New in version 1.1: - dialect is now a public parameter to the Pool.

      • pre_ping

        if True, the pool will emit a “ping” (typically “SELECT 1”, but is dialect-specific) on the connection upon checkout, to test if the connection is alive or not. If not, the connection is transparently re-connected and upon success, all other pooled connections established prior to that timestamp are invalidated. Requires that a dialect is passed as well to interpret the disconnection error.

        New in version 1.2.

class sqlalchemy.pool.``AssertionPool(\args, **kw*)

A Pool that allows at most one checked out connection at any given time.

This will raise an exception if more than one connection is checked out at a time. Useful for debugging code that is using more connections than desired.

Class signature

class sqlalchemy.pool.AssertionPool (sqlalchemy.pool.base.Pool)

class sqlalchemy.pool.``NullPool(creator, recycle=- 1, echo=None, logging_name=None, reset_on_return=True, events=None, dialect=None, pre_ping=False, _dispatch=None)

A Pool which does not pool connections.

Instead it literally opens and closes the underlying DB-API connection per each connection open/close.

Reconnect-related functions such as recycle and connection invalidation are not supported by this Pool implementation, since no connections are held persistently.

Class signature

class sqlalchemy.pool.NullPool (sqlalchemy.pool.base.Pool)

class sqlalchemy.pool.``StaticPool(creator, recycle=- 1, echo=None, logging_name=None, reset_on_return=True, events=None, dialect=None, pre_ping=False, _dispatch=None)

A Pool of exactly one connection, used for all requests.

Reconnect-related functions such as recycle and connection invalidation (which is also used to support auto-reconnect) are not currently supported by this Pool implementation but may be implemented in a future release.

Class signature

class sqlalchemy.pool.StaticPool (sqlalchemy.pool.base.Pool)

class sqlalchemy.pool.``_ConnectionFairy(dbapi_connection, connection_record, echo)

Proxies a DBAPI connection and provides return-on-dereference support.

This is an internal object used by the Pool implementation to provide context management to a DBAPI connection delivered by that Pool.

The name “fairy” is inspired by the fact that the _ConnectionFairy object’s lifespan is transitory, as it lasts only for the length of a specific DBAPI connection being checked out from the pool, and additionally that as a transparent proxy, it is mostly invisible.

See also

_ConnectionRecord

  • attribute sqlalchemy.pool._ConnectionFairy._connection_record = None

    A reference to the _ConnectionRecord object associated with the DBAPI connection.

    This is currently an internal accessor which is subject to change.

  • attribute sqlalchemy.pool._ConnectionFairy.connection = None

    A reference to the actual DBAPI connection being tracked.

  • method sqlalchemy.pool._ConnectionFairy.cursor(\args, **kwargs*)

    Return a new DBAPI cursor for the underlying connection.

    This method is a proxy for the connection.cursor() DBAPI method.

  • method sqlalchemy.pool._ConnectionFairy.detach()

    Separate this connection from its Pool.

    This means that the connection will no longer be returned to the pool when closed, and will instead be literally closed. The containing ConnectionRecord is separated from the DB-API connection, and will create a new connection when next used.

    Note that any overall connection limiting constraints imposed by a Pool implementation may be violated after a detach, as the detached connection is removed from the pool’s knowledge and control.

  • attribute sqlalchemy.pool._ConnectionFairy.info

    Info dictionary associated with the underlying DBAPI connection referred to by this ConnectionFairy, allowing user-defined data to be associated with the connection.

    The data here will follow along with the DBAPI connection including after it is returned to the connection pool and used again in subsequent instances of _ConnectionFairy. It is shared with the _ConnectionRecord.info and Connection.info accessors.

    The dictionary associated with a particular DBAPI connection is discarded when the connection itself is discarded.

  • method sqlalchemy.pool._ConnectionFairy.invalidate(e=None, soft=False)

    Mark this connection as invalidated.

    This method can be called directly, and is also called as a result of the Connection.invalidate() method. When invoked, the DBAPI connection is immediately closed and discarded from further use by the pool. The invalidation mechanism proceeds via the _ConnectionRecord.invalidate() internal method.

    • Parameters

      • e – an exception object indicating a reason for the invalidation.

      • soft

        if True, the connection isn’t closed; instead, this connection will be recycled on next checkout.

        New in version 1.0.3.

  1. See also
  2. [More on Invalidation](#pool-connection-invalidation)

class sqlalchemy.pool.``_ConnectionRecord(pool, connect=True)

Internal object which maintains an individual DBAPI connection referenced by a Pool.

The _ConnectionRecord object always exists for any particular DBAPI connection whether or not that DBAPI connection has been “checked out”. This is in contrast to the _ConnectionFairy which is only a public facade to the DBAPI connection while it is checked out.

A _ConnectionRecord may exist for a span longer than that of a single DBAPI connection. For example, if the _ConnectionRecord.invalidate() method is called, the DBAPI connection associated with this _ConnectionRecord will be discarded, but the _ConnectionRecord may be used again, in which case a new DBAPI connection is produced when the Pool next uses this record.

The _ConnectionRecord is delivered along with connection pool events, including PoolEvents.connect() and PoolEvents.checkout(), however _ConnectionRecord still remains an internal object whose API and internals may change.

See also

_ConnectionFairy

  1. See also
  2. [More on Invalidation](#pool-connection-invalidation)