class documentation

class ConnectionEvents(event.Events):

Known subclasses: sqlalchemy.ext.asyncio.events.AsyncConnectionEvents

View In Hierarchy

Available events for .Connectable, which includes _engine.Connection and _engine.Engine.

The methods here define the name of an event as well as the names of members that are passed to listener functions.

An event listener can be associated with any .Connectable class or instance, such as an _engine.Engine, e.g.:

from sqlalchemy import event, create_engine

def before_cursor_execute(conn, cursor, statement, parameters, context,
                                                executemany):
    log.info("Received statement: %s", statement)

engine = create_engine('postgresql://scott:tiger@localhost/test')
event.listen(engine, "before_cursor_execute", before_cursor_execute)

or with a specific _engine.Connection:

with engine.begin() as conn:
    @event.listens_for(conn, 'before_cursor_execute')
    def before_cursor_execute(conn, cursor, statement, parameters,
                                    context, executemany):
        log.info("Received statement: %s", statement)

When the methods are called with a statement parameter, such as in .after_cursor_execute or .before_cursor_execute, the statement is the exact SQL string that was prepared for transmission to the DBAPI cursor in the connection's .Dialect.

The .before_execute and .before_cursor_execute events can also be established with the retval=True flag, which allows modification of the statement and parameters to be sent to the database. The .before_cursor_execute event is particularly useful here to add ad-hoc string transformations, such as comments, to all executions:

from sqlalchemy.engine import Engine
from sqlalchemy import event

@event.listens_for(Engine, "before_cursor_execute", retval=True)
def comment_sql_calls(conn, cursor, statement, parameters,
                                    context, executemany):
    statement = statement + " -- some comment"
    return statement, parameters

Note

_events.ConnectionEvents can be established on any combination of _engine.Engine, _engine.Connection, as well as instances of each of those classes. Events across all four scopes will fire off for a given instance of _engine.Connection. However, for performance reasons, the _engine.Connection object determines at instantiation time whether or not its parent _engine.Engine has event listeners established. Event listeners added to the _engine.Engine class or to an instance of _engine.Engine after the instantiation of a dependent _engine.Connection instance will usually not be available on that _engine.Connection instance. The newly added listeners will instead take effect for _engine.Connection instances created subsequent to those event listeners being established on the parent _engine.Engine class or instance.

Parameters
retval=​FalseApplies to the .before_execute and .before_cursor_execute events only. When True, the user-defined event function must have a return value, which is a tuple of parameters that replace the given statement and parameters. See those methods for a description of specific return arguments.
Class Method ​_listen Undocumented
Method after​_cursor​_execute Intercept low-level cursor execute() events after execution.
Method after​_execute Intercept high level execute() events after execute.
Method before​_cursor​_execute Intercept low-level cursor execute() events before execution, receiving the string SQL statement and DBAPI-specific parameter list to be invoked against a cursor.
Method before​_execute Intercept high level execute() events, receiving uncompiled SQL constructs and other objects prior to rendering into SQL.
Method begin Intercept begin() events.
Method begin​_twophase Intercept begin_twophase() events.
Method commit Intercept commit() events, as initiated by a .Transaction.
Method commit​_twophase Intercept commit_twophase() events.
Method engine​_connect Intercept the creation of a new _engine.Connection.
Method engine​_disposed Intercept when the _engine.Engine.dispose method is called.
Method handle​_error Intercept all exceptions processed by the _engine.Connection.
Method prepare​_twophase Intercept prepare_twophase() events.
Method release​_savepoint Intercept release_savepoint() events.
Method rollback Intercept rollback() events, as initiated by a .Transaction.
Method rollback​_savepoint Intercept rollback_savepoint() events.
Method rollback​_twophase Intercept rollback_twophase() events.
Method savepoint Intercept savepoint() events.
Method set​_connection​_execution​_options Intercept when the _engine.Connection.execution_options method is called.
Method set​_engine​_execution​_options Intercept when the _engine.Engine.execution_options method is called.
Class Variable ​_target​_class​_doc Undocumented

Inherited from Events:

Class Method ​_accept​_with Undocumented
Class Method ​_clear Undocumented
Class Method ​_remove Undocumented
Static Method ​_set​_dispatch Undocumented
@classmethod
def _listen(cls, event_key, retval=False):
def after_cursor_execute(self, conn, cursor, statement, parameters, context, executemany):
Intercept low-level cursor execute() events after execution.
Parameters
conn_engine.Connection object
cursorDBAPI cursor object. Will have results pending if the statement was a SELECT, but these should not be consumed as they will be needed by the _engine.CursorResult.
statementstring SQL statement, as passed to the DBAPI
parametersDictionary, tuple, or list of parameters being passed to the execute() or executemany() method of the DBAPI cursor. In some cases may be None.
context.ExecutionContext object in use. May be None.
executemanyboolean, if True, this is an executemany() call, if False, this is an execute() call.
@event._legacy_signature('1.4', ['conn', 'clauseelement', 'multiparams', 'params', 'result'], (lambda conn, clauseelement, multiparams, params, execution_options, resu...
def after_execute(self, conn, clauseelement, multiparams, params, execution_options, result):
Intercept high level execute() events after execute.
Parameters
conn_engine.Connection object
clauseelementSQL expression construct, .Compiled instance, or string statement passed to _engine.Connection.execute.
multiparamsMultiple parameter sets, a list of dictionaries.
paramsSingle parameter set, a single dictionary.
execution​_options

dictionary of execution options passed along with the statement, if any. This is a merge of all options that will be used, including those of the statement, the connection, and those passed in to the method itself for the 2.0 style of execution.

result_engine.CursorResult generated by the execution.
def before_cursor_execute(self, conn, cursor, statement, parameters, context, executemany):

Intercept low-level cursor execute() events before execution, receiving the string SQL statement and DBAPI-specific parameter list to be invoked against a cursor.

This event is a good choice for logging as well as late modifications to the SQL string. It's less ideal for parameter modifications except for those which are specific to a target backend.

This event can be optionally established with the retval=True flag. The statement and parameters arguments should be returned as a two-tuple in this case:

@event.listens_for(Engine, "before_cursor_execute", retval=True)
def before_cursor_execute(conn, cursor, statement,
                parameters, context, executemany):
    # do something with statement, parameters
    return statement, parameters

See the example at _events.ConnectionEvents.

See Also

.before_execute

.after_cursor_execute

Parameters
conn_engine.Connection object
cursorDBAPI cursor object
statementstring SQL statement, as to be passed to the DBAPI
parametersDictionary, tuple, or list of parameters being passed to the execute() or executemany() method of the DBAPI cursor. In some cases may be None.
context.ExecutionContext object in use. May be None.
executemanyboolean, if True, this is an executemany() call, if False, this is an execute() call.
@event._legacy_signature('1.4', ['conn', 'clauseelement', 'multiparams', 'params'], (lambda conn, clauseelement, multiparams, params, execution_options: (co...
def before_execute(self, conn, clauseelement, multiparams, params, execution_options):

Intercept high level execute() events, receiving uncompiled SQL constructs and other objects prior to rendering into SQL.

This event is good for debugging SQL compilation issues as well as early manipulation of the parameters being sent to the database, as the parameter lists will be in a consistent format here.

This event can be optionally established with the retval=True flag. The clauseelement, multiparams, and params arguments should be returned as a three-tuple in this case:

@event.listens_for(Engine, "before_execute", retval=True)
def before_execute(conn, clauseelement, multiparams, params):
    # do something with clauseelement, multiparams, params
    return clauseelement, multiparams, params

See Also

.before_cursor_execute

Parameters
conn_engine.Connection object
clauseelementSQL expression construct, .Compiled instance, or string statement passed to _engine.Connection.execute.
multiparamsMultiple parameter sets, a list of dictionaries.
paramsSingle parameter set, a single dictionary.
execution​_options

dictionary of execution options passed along with the statement, if any. This is a merge of all options that will be used, including those of the statement, the connection, and those passed in to the method itself for the 2.0 style of execution.

def begin(self, conn):
Intercept begin() events.
Parameters
conn_engine.Connection object
def begin_twophase(self, conn, xid):
Intercept begin_twophase() events.
Parameters
conn_engine.Connection object
xidtwo-phase XID identifier
def commit(self, conn):

Intercept commit() events, as initiated by a .Transaction.

Note that the _pool.Pool may also "auto-commit" a DBAPI connection upon checkin, if the reset_on_return flag is set to the value 'commit'. To intercept this commit, use the _events.PoolEvents.reset hook.

Parameters
conn_engine.Connection object
def commit_twophase(self, conn, xid, is_prepared):
Intercept commit_twophase() events.
Parameters
conn_engine.Connection object
xidtwo-phase XID identifier
is​_preparedboolean, indicates if .TwoPhaseTransaction.prepare was called.
def engine_connect(self, conn, branch):

Intercept the creation of a new _engine.Connection.

This event is called typically as the direct result of calling the _engine.Engine.connect method.

It differs from the _events.PoolEvents.connect method, which refers to the actual connection to a database at the DBAPI level; a DBAPI connection may be pooled and reused for many operations. In contrast, this event refers only to the production of a higher level _engine.Connection wrapper around such a DBAPI connection.

It also differs from the _events.PoolEvents.checkout event in that it is specific to the _engine.Connection object, not the DBAPI connection that _events.PoolEvents.checkout deals with, although this DBAPI connection is available here via the _engine.Connection.connection attribute. But note there can in fact be multiple _events.PoolEvents.checkout events within the lifespan of a single _engine.Connection object, if that _engine.Connection is invalidated and re-established. There can also be multiple _engine.Connection objects generated for the same already-checked-out DBAPI connection, in the case that a "branch" of a _engine.Connection is produced.

See Also

_events.PoolEvents.checkout the lower-level pool checkout event for an individual DBAPI connection

Parameters
conn_engine.Connection object.
branchif True, this is a "branch" of an existing _engine.Connection. A branch is generated within the course of a statement execution to invoke supplemental statements, most typically to pre-execute a SELECT of a default value for the purposes of an INSERT statement.
def engine_disposed(self, engine):

Intercept when the _engine.Engine.dispose method is called.

The _engine.Engine.dispose method instructs the engine to "dispose" of it's connection pool (e.g. _pool.Pool), and replaces it with a new one. Disposing of the old pool has the effect that existing checked-in connections are closed. The new pool does not establish any new connections until it is first used.

This event can be used to indicate that resources related to the _engine.Engine should also be cleaned up, keeping in mind that the _engine.Engine can still be used for new requests in which case it re-acquires connection resources.

New in version 1.0.5.
def handle_error(self, exception_context):

Intercept all exceptions processed by the _engine.Connection.

This includes all exceptions emitted by the DBAPI as well as within SQLAlchemy's statement invocation process, including encoding errors and other statement validation errors. Other areas in which the event is invoked include transaction begin and end, result row fetching, cursor creation.

Note that .handle_error may support new kinds of exceptions and new calling scenarios at any time. Code which uses this event must expect new calling patterns to be present in minor releases.

To support the wide variety of members that correspond to an exception, as well as to allow extensibility of the event without backwards incompatibility, the sole argument received is an instance of .ExceptionContext. This object contains data members representing detail about the exception.

Use cases supported by this hook include:

  • read-only, low-level exception handling for logging and debugging purposes
  • exception re-writing
  • Establishing or disabling whether a connection or the owning connection pool is invalidated or expired in response to a specific exception [1].

The hook is called while the cursor from the failed operation (if any) is still open and accessible. Special cleanup operations can be called on this cursor; SQLAlchemy will attempt to close this cursor subsequent to this hook being invoked. If the connection is in "autocommit" mode, the transaction also remains open within the scope of this hook; the rollback of the per-statement transaction also occurs after the hook is called.

Note

[1]The pool "pre_ping" handler enabled using the :paramref:`_sa.create_engine.pool_pre_ping` parameter does not consult this event before deciding if the "ping" returned false, as opposed to receiving an unhandled error. For this use case, the :ref:`legacy recipe based on engine_connect() may be used <pool_disconnects_pessimistic_custom>`. A future API allow more comprehensive customization of the "disconnect" detection mechanism across all functions.

A handler function has two options for replacing the SQLAlchemy-constructed exception into one that is user defined. It can either raise this new exception directly, in which case all further event listeners are bypassed and the exception will be raised, after appropriate cleanup as taken place:

@event.listens_for(Engine, "handle_error")
def handle_exception(context):
    if isinstance(context.original_exception,
        psycopg2.OperationalError) and \
        "failed" in str(context.original_exception):
        raise MySpecialException("failed operation")

Warning

Because the _events.ConnectionEvents.handle_error event specifically provides for exceptions to be re-thrown as the ultimate exception raised by the failed statement, stack traces will be misleading if the user-defined event handler itself fails and throws an unexpected exception; the stack trace may not illustrate the actual code line that failed! It is advised to code carefully here and use logging and/or inline debugging if unexpected exceptions are occurring.

Alternatively, a "chained" style of event handling can be used, by configuring the handler with the retval=True modifier and returning the new exception instance from the function. In this case, event handling will continue onto the next handler. The "chained" exception is available using .ExceptionContext.chained_exception:

@event.listens_for(Engine, "handle_error", retval=True)
def handle_exception(context):
    if context.chained_exception is not None and \
        "special" in context.chained_exception.message:
        return MySpecialException("failed",
            cause=context.chained_exception)

Handlers that return None may be used within the chain; when a handler returns None, the previous exception instance, if any, is maintained as the current exception that is passed onto the next handler.

When a custom exception is raised or returned, SQLAlchemy raises this new exception as-is, it is not wrapped by any SQLAlchemy object. If the exception is not a subclass of sqlalchemy.exc.StatementError, certain features may not be available; currently this includes the ORM's feature of adding a detail hint about "autoflush" to exceptions raised within the autoflush process.

New in version 0.9.7: Added the _events.ConnectionEvents.handle_error hook.
Changed in version 1.1: The .handle_error event will now receive all exceptions that inherit from BaseException, including SystemExit and KeyboardInterrupt. The setting for .ExceptionContext.is_disconnect is True in this case and the default for .ExceptionContext.invalidate_pool_on_disconnect is False.
Changed in version 1.0.0: The .handle_error event is now invoked when an _engine.Engine fails during the initial call to _engine.Engine.connect, as well as when a _engine.Connection object encounters an error during a reconnect operation.
Changed in version 1.0.0: The .handle_error event is not fired off when a dialect makes use of the skip_user_error_events execution option. This is used by dialects which intend to catch SQLAlchemy-specific exceptions within specific operations, such as when the MySQL dialect detects a table not present within the has_table() dialect method. Prior to 1.0.0, code which implements .handle_error needs to ensure that exceptions thrown in these scenarios are re-raised without modification.
Parameters
exception​_contextUndocumented
contextan .ExceptionContext object. See this class for details on all available members.
def prepare_twophase(self, conn, xid):
Intercept prepare_twophase() events.
Parameters
conn_engine.Connection object
xidtwo-phase XID identifier
def release_savepoint(self, conn, name, context):
Intercept release_savepoint() events.
Parameters
conn_engine.Connection object
namespecified name used for the savepoint.
contextnot used
def rollback(self, conn):

Intercept rollback() events, as initiated by a .Transaction.

Note that the _pool.Pool also "auto-rolls back" a DBAPI connection upon checkin, if the reset_on_return flag is set to its default value of 'rollback'. To intercept this rollback, use the _events.PoolEvents.reset hook.

See Also

_events.PoolEvents.reset

Parameters
conn_engine.Connection object
def rollback_savepoint(self, conn, name, context):
Intercept rollback_savepoint() events.
Parameters
conn_engine.Connection object
namespecified name used for the savepoint.
contextnot used
def rollback_twophase(self, conn, xid, is_prepared):
Intercept rollback_twophase() events.
Parameters
conn_engine.Connection object
xidtwo-phase XID identifier
is​_preparedboolean, indicates if .TwoPhaseTransaction.prepare was called.
def savepoint(self, conn, name):
Intercept savepoint() events.
Parameters
conn_engine.Connection object
namespecified name used for the savepoint.
def set_connection_execution_options(self, conn, opts):

Intercept when the _engine.Connection.execution_options method is called.

This method is called after the new _engine.Connection has been produced, with the newly updated execution options collection, but before the .Dialect has acted upon any of those new options.

Note that this method is not called when a new _engine.Connection is produced which is inheriting execution options from its parent _engine.Engine; to intercept this condition, use the _events.ConnectionEvents.engine_connect event.

New in version 0.9.0.

See Also

_events.ConnectionEvents.set_engine_execution_options - event which is called when _engine.Engine.execution_options is called.

Parameters
connThe newly copied _engine.Connection object
optsdictionary of options that were passed to the _engine.Connection.execution_options method.
def set_engine_execution_options(self, engine, opts):

Intercept when the _engine.Engine.execution_options method is called.

The _engine.Engine.execution_options method produces a shallow copy of the _engine.Engine which stores the new options. That new _engine.Engine is passed here. A particular application of this method is to add a _events.ConnectionEvents.engine_connect event handler to the given _engine.Engine which will perform some per- _engine.Connection task specific to these execution options.

New in version 0.9.0.

See Also

_events.ConnectionEvents.set_connection_execution_options - event which is called when _engine.Connection.execution_options is called.

Parameters
engineUndocumented
optsdictionary of options that were passed to the _engine.Connection.execution_options method.
connThe newly copied _engine.Engine object
_target_class_doc: str =