Core Events
class sqlalchemy.event.base.Events
Define event listening functions for a particular target type.
Members
Class signature
class (sqlalchemy.event._HasEventsDispatch
)
attribute dispatch: _Dispatch[_ET] = <sqlalchemy.event.base.EventsDispatch object>
reference back to the _Dispatch class.
Bidirectional against _Dispatch._events
class sqlalchemy.events.PoolEvents
Available events for .
The methods here define the name of an event as well as the names of members that are passed to listener functions.
e.g.:
In addition to accepting the Pool class and instances, PoolEvents also accepts objects and the Engine class as targets, which will be resolved to the .pool
attribute of the given engine or the class:
engine = create_engine("postgresql+psycopg2://scott:tiger@localhost/test")
# will associate with engine.pool
event.listen(engine, 'checkout', my_on_checkout)
Members
checkin(), , close(), , connect(), , dispatch, , invalidate(), , soft_invalidate()
Class signature
class (sqlalchemy.event.Events
)
method sqlalchemy.events.PoolEvents.checkin(dbapi_connection: , connection_record: ConnectionPoolEntry) → None
Called when a connection returns to the pool.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngineOrPool, 'checkin')
def receive_checkin(dbapi_connection, connection_record):
"listen for the 'checkin' event"
# ... (event handling logic) ...
```
Note that the connection may be closed, and may be None if the connection has been invalidated. `checkin` will not be called for detached connections. (They do not return to the pool.)
- Parameters:
- **dbapi\_connection** – a DBAPI connection. The [ConnectionPoolEntry.dbapi\_connection]($ba04c3bd42280074.md#sqlalchemy.pool.ConnectionPoolEntry.dbapi_connection "sqlalchemy.pool.ConnectionPoolEntry.dbapi_connection") attribute.
- **connection\_record** – the [ConnectionPoolEntry]($ba04c3bd42280074.md#sqlalchemy.pool.ConnectionPoolEntry "sqlalchemy.pool.ConnectionPoolEntry") managing the DBAPI connection.
method checkout(dbapi_connection: DBAPIConnection, connection_record: , connection_proxy: PoolProxiedConnection) → None
Called when a connection is retrieved from the Pool.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngineOrPool, 'checkout')
def receive_checkout(dbapi_connection, connection_record, connection_proxy):
"listen for the 'checkout' event"
# ... (event handling logic) ...
```
- Parameters:
- **dbapi\_connection** – a DBAPI connection. The [ConnectionPoolEntry.dbapi\_connection]($ba04c3bd42280074.md#sqlalchemy.pool.ConnectionPoolEntry.dbapi_connection "sqlalchemy.pool.ConnectionPoolEntry.dbapi_connection") attribute.
- **connection\_record** – the [ConnectionPoolEntry]($ba04c3bd42280074.md#sqlalchemy.pool.ConnectionPoolEntry "sqlalchemy.pool.ConnectionPoolEntry") managing the DBAPI connection.
- **connection\_proxy** – the [PoolProxiedConnection]($ba04c3bd42280074.md#sqlalchemy.pool.PoolProxiedConnection "sqlalchemy.pool.PoolProxiedConnection") object which will proxy the public interface of the DBAPI connection for the lifespan of the checkout.
If you raise a [DisconnectionError]($40db62cb9ae746c0.md#sqlalchemy.exc.DisconnectionError "sqlalchemy.exc.DisconnectionError"), the current connection will be disposed and a fresh connection retrieved. Processing of all checkout listeners will abort and restart using the new connection.
See also
[ConnectionEvents.engine\_connect()](#sqlalchemy.events.ConnectionEvents.engine_connect "sqlalchemy.events.ConnectionEvents.engine_connect") - a similar event which occurs upon creation of a new [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection").
method close(dbapi_connection: DBAPIConnection, connection_record: ) → None
Called when a DBAPI connection is closed.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngineOrPool, 'close')
def receive_close(dbapi_connection, connection_record):
"listen for the 'close' event"
# ... (event handling logic) ...
```
The event is emitted before the close occurs.
The close of a connection can fail; typically this is because the connection is already closed. If the close operation fails, the connection is discarded.
The [close()](#sqlalchemy.events.PoolEvents.close "sqlalchemy.events.PoolEvents.close") event corresponds to a connection that’s still associated with the pool. To intercept close events for detached connections use [close\_detached()](#sqlalchemy.events.PoolEvents.close_detached "sqlalchemy.events.PoolEvents.close_detached").
New in version 1.1.
- Parameters:
- **dbapi\_connection** – a DBAPI connection. The [ConnectionPoolEntry.dbapi\_connection]($ba04c3bd42280074.md#sqlalchemy.pool.ConnectionPoolEntry.dbapi_connection "sqlalchemy.pool.ConnectionPoolEntry.dbapi_connection") attribute.
- **connection\_record** – the [ConnectionPoolEntry]($ba04c3bd42280074.md#sqlalchemy.pool.ConnectionPoolEntry "sqlalchemy.pool.ConnectionPoolEntry") managing the DBAPI connection.
method sqlalchemy.events.PoolEvents.close_detached(dbapi_connection: ) → None
Called when a detached DBAPI connection is closed.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngineOrPool, 'close_detached')
def receive_close_detached(dbapi_connection):
"listen for the 'close_detached' event"
# ... (event handling logic) ...
```
The event is emitted before the close occurs.
The close of a connection can fail; typically this is because the connection is already closed. If the close operation fails, the connection is discarded.
New in version 1.1.
- Parameters:
**dbapi\_connection** – a DBAPI connection. The [ConnectionPoolEntry.dbapi\_connection]($ba04c3bd42280074.md#sqlalchemy.pool.ConnectionPoolEntry.dbapi_connection "sqlalchemy.pool.ConnectionPoolEntry.dbapi_connection") attribute.
method sqlalchemy.events.PoolEvents.connect(dbapi_connection: , connection_record: ConnectionPoolEntry) → None
Called at the moment a particular DBAPI connection is first created for a given .
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngineOrPool, 'connect')
def receive_connect(dbapi_connection, connection_record):
"listen for the 'connect' event"
# ... (event handling logic) ...
```
This event allows one to capture the point directly after which the DBAPI module-level `.connect()` method has been used in order to produce a new DBAPI connection.
- Parameters:
- **dbapi\_connection** – a DBAPI connection. The [ConnectionPoolEntry.dbapi\_connection]($ba04c3bd42280074.md#sqlalchemy.pool.ConnectionPoolEntry.dbapi_connection "sqlalchemy.pool.ConnectionPoolEntry.dbapi_connection") attribute.
- **connection\_record** – the [ConnectionPoolEntry]($ba04c3bd42280074.md#sqlalchemy.pool.ConnectionPoolEntry "sqlalchemy.pool.ConnectionPoolEntry") managing the DBAPI connection.
method sqlalchemy.events.PoolEvents.detach(dbapi_connection: , connection_record: ConnectionPoolEntry) → None
Called when a DBAPI connection is “detached” from a pool.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngineOrPool, 'detach')
def receive_detach(dbapi_connection, connection_record):
"listen for the 'detach' event"
# ... (event handling logic) ...
```
This event is emitted after the detach occurs. The connection is no longer associated with the given connection record.
New in version 1.1.
- Parameters:
- **dbapi\_connection** – a DBAPI connection. The [ConnectionPoolEntry.dbapi\_connection]($ba04c3bd42280074.md#sqlalchemy.pool.ConnectionPoolEntry.dbapi_connection "sqlalchemy.pool.ConnectionPoolEntry.dbapi_connection") attribute.
- **connection\_record** – the [ConnectionPoolEntry]($ba04c3bd42280074.md#sqlalchemy.pool.ConnectionPoolEntry "sqlalchemy.pool.ConnectionPoolEntry") managing the DBAPI connection.
attribute dispatch: _Dispatch[_ET] = <sqlalchemy.event.base.PoolEventsDispatch object>
reference back to the _Dispatch class.
Bidirectional against _Dispatch._events
method sqlalchemy.events.PoolEvents.first_connect(dbapi_connection: , connection_record: ConnectionPoolEntry) → None
Called exactly once for the first time a DBAPI connection is checked out from a particular .
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngineOrPool, 'first_connect')
def receive_first_connect(dbapi_connection, connection_record):
"listen for the 'first_connect' event"
# ... (event handling logic) ...
```
The rationale for [PoolEvents.first\_connect()](#sqlalchemy.events.PoolEvents.first_connect "sqlalchemy.events.PoolEvents.first_connect") is to determine information about a particular series of database connections based on the settings used for all connections. Since a particular [Pool]($ba04c3bd42280074.md#sqlalchemy.pool.Pool "sqlalchemy.pool.Pool") refers to a single “creator” function (which in terms of a [Engine]($3743e3464fa80ce7.md#sqlalchemy.engine.Engine "sqlalchemy.engine.Engine") refers to the URL and connection options used), it is typically valid to make observations about a single connection that can be safely assumed to be valid about all subsequent connections, such as the database version, the server and client encoding settings, collation settings, and many others.
- Parameters:
- **dbapi\_connection** – a DBAPI connection. The [ConnectionPoolEntry.dbapi\_connection]($ba04c3bd42280074.md#sqlalchemy.pool.ConnectionPoolEntry.dbapi_connection "sqlalchemy.pool.ConnectionPoolEntry.dbapi_connection") attribute.
- **connection\_record** – the [ConnectionPoolEntry]($ba04c3bd42280074.md#sqlalchemy.pool.ConnectionPoolEntry "sqlalchemy.pool.ConnectionPoolEntry") managing the DBAPI connection.
method sqlalchemy.events.PoolEvents.invalidate(dbapi_connection: , connection_record: ConnectionPoolEntry, exception: Optional[BaseException]) → None
Called when a DBAPI connection is to be “invalidated”.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngineOrPool, 'invalidate')
def receive_invalidate(dbapi_connection, connection_record, exception):
"listen for the 'invalidate' event"
# ... (event handling logic) ...
```
This event is called any time the [ConnectionPoolEntry.invalidate()]($ba04c3bd42280074.md#sqlalchemy.pool.ConnectionPoolEntry.invalidate "sqlalchemy.pool.ConnectionPoolEntry.invalidate") method is invoked, either from API usage or via “auto-invalidation”, without the `soft` flag.
The event occurs before a final attempt to call `.close()` on the connection occurs.
- Parameters:
- **dbapi\_connection** – a DBAPI connection. The [ConnectionPoolEntry.dbapi\_connection]($ba04c3bd42280074.md#sqlalchemy.pool.ConnectionPoolEntry.dbapi_connection "sqlalchemy.pool.ConnectionPoolEntry.dbapi_connection") attribute.
- **connection\_record** – the [ConnectionPoolEntry]($ba04c3bd42280074.md#sqlalchemy.pool.ConnectionPoolEntry "sqlalchemy.pool.ConnectionPoolEntry") managing the DBAPI connection.
- **exception** – the exception object corresponding to the reason for this invalidation, if any. May be `None`.
New in version 0.9.2: Added support for connection invalidation listening.
See also
[More on Invalidation]($ba04c3bd42280074.md#pool-connection-invalidation)
method reset(dbapi_connection: DBAPIConnection, connection_record: , reset_state: PoolResetState) → None
Called before the “reset” action occurs for a pooled connection.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngineOrPool, 'reset')
def receive_reset(dbapi_connection, connection_record, reset_state):
"listen for the 'reset' event"
# ... (event handling logic) ...
# DEPRECATED calling style (pre-2.0, will be removed in a future release)
@event.listens_for(SomeEngineOrPool, 'reset')
def receive_reset(dbapi_connection, connection_record):
"listen for the 'reset' event"
# ... (event handling logic) ...
```
Changed in version 2.0: The [PoolEvents.reset()](#sqlalchemy.events.PoolEvents.reset "sqlalchemy.events.PoolEvents.reset") event now accepts the arguments [PoolEvents.reset.dbapi\_connection](#sqlalchemy.events.PoolEvents.reset.params.dbapi_connection "sqlalchemy.events.PoolEvents.reset"), [PoolEvents.reset.connection\_record](#sqlalchemy.events.PoolEvents.reset.params.connection_record "sqlalchemy.events.PoolEvents.reset"), [PoolEvents.reset.reset\_state](#sqlalchemy.events.PoolEvents.reset.params.reset_state "sqlalchemy.events.PoolEvents.reset"). Support for listener functions which accept the previous argument signature(s) listed above as “deprecated” will be removed in a future release.
This event represents when the `rollback()` method is called on the DBAPI connection before it is returned to the pool or discarded. A custom “reset” strategy may be implemented using this event hook, which may also be combined with disabling the default “reset” behavior using the [Pool.reset\_on\_return]($ba04c3bd42280074.md#sqlalchemy.pool.Pool.params.reset_on_return "sqlalchemy.pool.Pool") parameter.
The primary difference between the [PoolEvents.reset()](#sqlalchemy.events.PoolEvents.reset "sqlalchemy.events.PoolEvents.reset") and [PoolEvents.checkin()](#sqlalchemy.events.PoolEvents.checkin "sqlalchemy.events.PoolEvents.checkin") events are that [PoolEvents.reset()](#sqlalchemy.events.PoolEvents.reset "sqlalchemy.events.PoolEvents.reset") is called not just for pooled connections that are being returned to the pool, but also for connections that were detached using the [Connection.detach()]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection.detach "sqlalchemy.engine.Connection.detach") method as well as asyncio connections that are being discarded due to garbage collection taking place on connections before the connection was checked in.
Note that the event **is not** invoked for connections that were invalidated using [Connection.invalidate()]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection.invalidate "sqlalchemy.engine.Connection.invalidate"). These events may be intercepted using the [PoolEvents.soft\_invalidate()](#sqlalchemy.events.PoolEvents.soft_invalidate "sqlalchemy.events.PoolEvents.soft_invalidate") and [PoolEvents.invalidate()](#sqlalchemy.events.PoolEvents.invalidate "sqlalchemy.events.PoolEvents.invalidate") event hooks, and all “connection close” events may be intercepted using [PoolEvents.close()](#sqlalchemy.events.PoolEvents.close "sqlalchemy.events.PoolEvents.close").
The [PoolEvents.reset()](#sqlalchemy.events.PoolEvents.reset "sqlalchemy.events.PoolEvents.reset") event is usually followed by the [PoolEvents.checkin()](#sqlalchemy.events.PoolEvents.checkin "sqlalchemy.events.PoolEvents.checkin") event, except in those cases where the connection is discarded immediately after reset.
- Parameters:
- **dbapi\_connection** – a DBAPI connection. The [ConnectionPoolEntry.dbapi\_connection]($ba04c3bd42280074.md#sqlalchemy.pool.ConnectionPoolEntry.dbapi_connection "sqlalchemy.pool.ConnectionPoolEntry.dbapi_connection") attribute.
- **connection\_record** – the [ConnectionPoolEntry]($ba04c3bd42280074.md#sqlalchemy.pool.ConnectionPoolEntry "sqlalchemy.pool.ConnectionPoolEntry") managing the DBAPI connection.
- **reset\_state** –
[PoolResetState](#sqlalchemy.events.PoolResetState "sqlalchemy.events.PoolResetState") instance which provides information about the circumstances under which the connection is being reset.
New in version 2.0.
See also
[Reset On Return]($ba04c3bd42280074.md#pool-reset-on-return)
[ConnectionEvents.rollback()](#sqlalchemy.events.ConnectionEvents.rollback "sqlalchemy.events.ConnectionEvents.rollback")
[ConnectionEvents.commit()](#sqlalchemy.events.ConnectionEvents.commit "sqlalchemy.events.ConnectionEvents.commit")
method soft_invalidate(dbapi_connection: DBAPIConnection, connection_record: , exception: Optional[BaseException]) → None
Called when a DBAPI connection is to be “soft invalidated”.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngineOrPool, 'soft_invalidate')
def receive_soft_invalidate(dbapi_connection, connection_record, exception):
"listen for the 'soft_invalidate' event"
# ... (event handling logic) ...
```
This event is called any time the [ConnectionPoolEntry.invalidate()]($ba04c3bd42280074.md#sqlalchemy.pool.ConnectionPoolEntry.invalidate "sqlalchemy.pool.ConnectionPoolEntry.invalidate") method is invoked with the `soft` flag.
Soft invalidation refers to when the connection record that tracks this connection will force a reconnect after the current connection is checked in. It does not actively close the dbapi\_connection at the point at which it is called.
New in version 1.0.3.
- Parameters:
- **dbapi\_connection** – a DBAPI connection. The [ConnectionPoolEntry.dbapi\_connection]($ba04c3bd42280074.md#sqlalchemy.pool.ConnectionPoolEntry.dbapi_connection "sqlalchemy.pool.ConnectionPoolEntry.dbapi_connection") attribute.
- **connection\_record** – the [ConnectionPoolEntry]($ba04c3bd42280074.md#sqlalchemy.pool.ConnectionPoolEntry "sqlalchemy.pool.ConnectionPoolEntry") managing the DBAPI connection.
- **exception** – the exception object corresponding to the reason for this invalidation, if any. May be `None`.
class sqlalchemy.events.PoolResetState
describes the state of a DBAPI connection as it is being passed to the PoolEvents.reset() connection pool event.
Members
New in version 2.0.0b3.
attribute sqlalchemy.events.PoolResetState.asyncio_safe: bool
Indicates if the reset operation is occurring within a scope where an enclosing event loop is expected to be present for asyncio applications.
Will be False in the case that the connection is being garbage collected.
attribute terminate_only: bool
indicates if the connection is to be immediately terminated and not checked in to the pool.
This occurs for connections that were invalidated, as well as asyncio connections that were not cleanly handled by the calling code that are instead being garbage collected. In the latter case, operations can’t be safely run on asyncio connections within garbage collection as there is not necessarily an event loop present.
attribute sqlalchemy.events.PoolResetState.transaction_was_reset: bool
Indicates if the transaction on the DBAPI connection was already essentially “reset” back by the object.
This boolean is True if the Connection had transactional state present upon it, which was then not closed using the or Connection.commit() method; instead, the transaction was closed inline within the method so is guaranteed to remain non-present when this event is reached.
class sqlalchemy.events.ConnectionEvents
Available events for and 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 or Engine class or instance, such as an , 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+psycopg2://scott:tiger@localhost/test')
event.listen(engine, "before_cursor_execute", before_cursor_execute)
or with a specific 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 or before_cursor_execute(), the statement is the exact SQL string that was prepared for transmission to the DBAPI cursor
in the connection’s .
The before_execute() and 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
can be established on any combination of Engine, , as well as instances of each of those classes. Events across all four scopes will fire off for a given instance of Connection. However, for performance reasons, the object determines at instantiation time whether or not its parent Engine has event listeners established. Event listeners added to the class or to an instance of Engine after the instantiation of a dependent instance will usually not be available on that Connection instance. The newly added listeners will instead take effect for instances created subsequent to those event listeners being established on the parent Engine class or instance.
Parameters:
Members
, after_execute(), , before_execute(), , begin_twophase(), , commit_twophase(), , engine_connect(), , prepare_twophase(), , rollback(), , rollback_twophase(), , set_connection_execution_options(),
Class signature
class sqlalchemy.events.ConnectionEvents (sqlalchemy.event.Events
)
method after_cursor_execute(conn: Connection, cursor: , statement: str, parameters: _DBAPIAnyExecuteParams, context: Optional[ExecutionContext], executemany: bool) → None
Intercept low-level cursor execute() events after execution.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngine, 'after_cursor_execute')
def receive_after_cursor_execute(conn, cursor, statement, parameters, context, executemany):
"listen for the 'after_cursor_execute' event"
# ... (event handling logic) ...
```
- Parameters:
- **conn** – [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
- **cursor** – DBAPI 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 [CursorResult]($3743e3464fa80ce7.md#sqlalchemy.engine.CursorResult "sqlalchemy.engine.CursorResult").
- **statement** – string SQL statement, as passed to the DBAPI
- **parameters** – Dictionary, 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]($4877d6ccc0778d3e.md#sqlalchemy.engine.ExecutionContext "sqlalchemy.engine.ExecutionContext") object in use. May be `None`.
- **executemany** – boolean, if `True`, this is an `executemany()` call, if `False`, this is an `execute()` call.
method after_execute(conn: Connection, clauseelement: , multiparams: _CoreMultiExecuteParams, params: _CoreSingleExecuteParams, execution_options: _ExecuteOptions, result: Result[Any]) → None
Intercept high level execute() events after execute.
Example argument forms:
``` from sqlalchemy import event
method before_cursor_execute(conn: Connection, cursor: , statement: str, parameters: _DBAPIAnyExecuteParams, context: Optional[ExecutionContext], executemany: bool) → Optional[[str, _DBAPIAnyExecuteParams]]
Intercept low-level cursor execute() events before execution, receiving the string SQL statement and DBAPI-specific parameter list to be invoked against a cursor.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngine, 'before_cursor_execute')
def receive_before_cursor_execute(conn, cursor, statement, parameters, context, executemany):
"listen for the 'before_cursor_execute' event"
# ... (event handling logic) ...
```
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 [ConnectionEvents](#sqlalchemy.events.ConnectionEvents "sqlalchemy.events.ConnectionEvents").
- Parameters:
- **conn** – [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
- **statement** – string SQL statement, as to be passed to the DBAPI
- **parameters** – Dictionary, 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]($4877d6ccc0778d3e.md#sqlalchemy.engine.ExecutionContext "sqlalchemy.engine.ExecutionContext") object in use. May be `None`.
- **executemany** – boolean, if `True`, this is an `executemany()` call, if `False`, this is an `execute()` call.
See also
[before\_execute()](#sqlalchemy.events.ConnectionEvents.before_execute "sqlalchemy.events.ConnectionEvents.before_execute")
[after\_cursor\_execute()](#sqlalchemy.events.ConnectionEvents.after_cursor_execute "sqlalchemy.events.ConnectionEvents.after_cursor_execute")
method sqlalchemy.events.ConnectionEvents.before_execute(conn: , clauseelement: Executable, multiparams: _CoreMultiExecuteParams, params: _CoreSingleExecuteParams, execution_options: _ExecuteOptions) → Optional[[Executable, _CoreMultiExecuteParams, _CoreSingleExecuteParams]]
Intercept high level execute() events, receiving uncompiled SQL constructs and other objects prior to rendering into SQL.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngine, 'before_execute')
def receive_before_execute(conn, clauseelement, multiparams, params, execution_options):
"listen for the 'before_execute' event"
# ... (event handling logic) ...
# DEPRECATED calling style (pre-1.4, will be removed in a future release)
@event.listens_for(SomeEngine, 'before_execute')
def receive_before_execute(conn, clauseelement, multiparams, params):
"listen for the 'before_execute' event"
# ... (event handling logic) ...
```
Changed in version 1.4: The [ConnectionEvents.before\_execute()](#sqlalchemy.events.ConnectionEvents.before_execute "sqlalchemy.events.ConnectionEvents.before_execute") event now accepts the arguments [ConnectionEvents.before\_execute.conn](#sqlalchemy.events.ConnectionEvents.before_execute.params.conn "sqlalchemy.events.ConnectionEvents.before_execute"), [ConnectionEvents.before\_execute.clauseelement](#sqlalchemy.events.ConnectionEvents.before_execute.params.clauseelement "sqlalchemy.events.ConnectionEvents.before_execute"), [ConnectionEvents.before\_execute.multiparams](#sqlalchemy.events.ConnectionEvents.before_execute.params.multiparams "sqlalchemy.events.ConnectionEvents.before_execute"), [ConnectionEvents.before\_execute.params](#sqlalchemy.events.ConnectionEvents.before_execute.params.params "sqlalchemy.events.ConnectionEvents.before_execute"), [ConnectionEvents.before\_execute.execution\_options](#sqlalchemy.events.ConnectionEvents.before_execute.params.execution_options "sqlalchemy.events.ConnectionEvents.before_execute"). Support for listener functions which accept the previous argument signature(s) listed above as “deprecated” will be removed in a future release.
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
```
- Parameters:
- **conn** – [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
- **clauseelement** – SQL expression construct, [Compiled]($4877d6ccc0778d3e.md#sqlalchemy.engine.Compiled "sqlalchemy.engine.Compiled") instance, or string statement passed to [Connection.execute()]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection.execute "sqlalchemy.engine.Connection.execute").
- **multiparams** – Multiple parameter sets, a list of dictionaries.
- **params** – Single 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.
See also
[before\_cursor\_execute()](#sqlalchemy.events.ConnectionEvents.before_cursor_execute "sqlalchemy.events.ConnectionEvents.before_cursor_execute")
method begin(conn: Connection) → None
Intercept begin() events.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngine, 'begin')
def receive_begin(conn):
"listen for the 'begin' event"
# ... (event handling logic) ...
```
- Parameters:
**conn** – [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
method begin_twophase(conn: Connection, xid: Any) → None
Intercept begin_twophase() events.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngine, 'begin_twophase')
def receive_begin_twophase(conn, xid):
"listen for the 'begin_twophase' event"
# ... (event handling logic) ...
```
- Parameters:
- **conn** – [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
- **xid** – two-phase XID identifier
method commit(conn: Connection) → None
Intercept commit() events, as initiated by a .
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngine, 'commit')
def receive_commit(conn):
"listen for the 'commit' event"
# ... (event handling logic) ...
```
Note that the [Pool]($ba04c3bd42280074.md#sqlalchemy.pool.Pool "sqlalchemy.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 [PoolEvents.reset()](#sqlalchemy.events.PoolEvents.reset "sqlalchemy.events.PoolEvents.reset") hook.
- Parameters:
**conn** – [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
method sqlalchemy.events.ConnectionEvents.commit_twophase(conn: , xid: Any, is_prepared: bool) → None
Intercept commit_twophase() events.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngine, 'commit_twophase')
def receive_commit_twophase(conn, xid, is_prepared):
"listen for the 'commit_twophase' event"
# ... (event handling logic) ...
```
- Parameters:
- **conn** – [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
- **xid** – two-phase XID identifier
- **is\_prepared** – boolean, indicates if [TwoPhaseTransaction.prepare()]($3743e3464fa80ce7.md#sqlalchemy.engine.TwoPhaseTransaction.prepare "sqlalchemy.engine.TwoPhaseTransaction.prepare") was called.
attribute sqlalchemy.events.ConnectionEvents.dispatch: _Dispatch[_ET] = <sqlalchemy.event.base.ConnectionEventsDispatch object>
reference back to the _Dispatch class.
Bidirectional against _Dispatch._events
method engine_connect(conn: Connection) → None
Intercept the creation of a new .
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngine, 'engine_connect')
def receive_engine_connect(conn):
"listen for the 'engine_connect' event"
# ... (event handling logic) ...
# DEPRECATED calling style (pre-2.0, will be removed in a future release)
@event.listens_for(SomeEngine, 'engine_connect')
def receive_engine_connect(conn, branch):
"listen for the 'engine_connect' event"
# ... (event handling logic) ...
```
Changed in version 2.0: The [ConnectionEvents.engine\_connect()](#sqlalchemy.events.ConnectionEvents.engine_connect "sqlalchemy.events.ConnectionEvents.engine_connect") event now accepts the arguments [ConnectionEvents.engine\_connect.conn](#sqlalchemy.events.ConnectionEvents.engine_connect.params.conn "sqlalchemy.events.ConnectionEvents.engine_connect"). Support for listener functions which accept the previous argument signature(s) listed above as “deprecated” will be removed in a future release.
This event is called typically as the direct result of calling the [Engine.connect()]($3743e3464fa80ce7.md#sqlalchemy.engine.Engine.connect "sqlalchemy.engine.Engine.connect") method.
It differs from the [PoolEvents.connect()](#sqlalchemy.events.PoolEvents.connect "sqlalchemy.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 [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") wrapper around such a DBAPI connection.
It also differs from the [PoolEvents.checkout()](#sqlalchemy.events.PoolEvents.checkout "sqlalchemy.events.PoolEvents.checkout") event in that it is specific to the [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object, not the DBAPI connection that [PoolEvents.checkout()](#sqlalchemy.events.PoolEvents.checkout "sqlalchemy.events.PoolEvents.checkout") deals with, although this DBAPI connection is available here via the [Connection.connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection.connection "sqlalchemy.engine.Connection.connection") attribute. But note there can in fact be multiple [PoolEvents.checkout()](#sqlalchemy.events.PoolEvents.checkout "sqlalchemy.events.PoolEvents.checkout") events within the lifespan of a single [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object, if that [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") is invalidated and re-established.
- Parameters:
**conn** – [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object.
See also
[PoolEvents.checkout()](#sqlalchemy.events.PoolEvents.checkout "sqlalchemy.events.PoolEvents.checkout") the lower-level pool checkout event for an individual DBAPI connection
method sqlalchemy.events.ConnectionEvents.engine_disposed(engine: ) → None
Intercept when the Engine.dispose() method is called.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngine, 'engine_disposed')
def receive_engine_disposed(engine):
"listen for the 'engine_disposed' event"
# ... (event handling logic) ...
```
The [Engine.dispose()]($3743e3464fa80ce7.md#sqlalchemy.engine.Engine.dispose "sqlalchemy.engine.Engine.dispose") method instructs the engine to “dispose” of it’s connection pool (e.g. [Pool]($ba04c3bd42280074.md#sqlalchemy.pool.Pool "sqlalchemy.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]($3743e3464fa80ce7.md#sqlalchemy.engine.Engine "sqlalchemy.engine.Engine") should also be cleaned up, keeping in mind that the [Engine]($3743e3464fa80ce7.md#sqlalchemy.engine.Engine "sqlalchemy.engine.Engine") can still be used for new requests in which case it re-acquires connection resources.
New in version 1.0.5.
method prepare_twophase(conn: Connection, xid: Any) → None
Intercept prepare_twophase() events.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngine, 'prepare_twophase')
def receive_prepare_twophase(conn, xid):
"listen for the 'prepare_twophase' event"
# ... (event handling logic) ...
```
- Parameters:
- **conn** – [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
- **xid** – two-phase XID identifier
method release_savepoint(conn: Connection, name: str, context: None) → None
Intercept release_savepoint() events.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngine, 'release_savepoint')
def receive_release_savepoint(conn, name, context):
"listen for the 'release_savepoint' event"
# ... (event handling logic) ...
```
- Parameters:
- **conn** – [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
- **name** – specified name used for the savepoint.
- **context** – not used
method rollback(conn: Connection) → None
Intercept rollback() events, as initiated by a .
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngine, 'rollback')
def receive_rollback(conn):
"listen for the 'rollback' event"
# ... (event handling logic) ...
```
Note that the [Pool]($ba04c3bd42280074.md#sqlalchemy.pool.Pool "sqlalchemy.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 [PoolEvents.reset()](#sqlalchemy.events.PoolEvents.reset "sqlalchemy.events.PoolEvents.reset") hook.
- Parameters:
**conn** – [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
See also
[PoolEvents.reset()](#sqlalchemy.events.PoolEvents.reset "sqlalchemy.events.PoolEvents.reset")
method sqlalchemy.events.ConnectionEvents.rollback_savepoint(conn: , name: str, context: None) → None
Intercept rollback_savepoint() events.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngine, 'rollback_savepoint')
def receive_rollback_savepoint(conn, name, context):
"listen for the 'rollback_savepoint' event"
# ... (event handling logic) ...
```
- Parameters:
- **conn** – [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
- **name** – specified name used for the savepoint.
- **context** – not used
method sqlalchemy.events.ConnectionEvents.rollback_twophase(conn: , xid: Any, is_prepared: bool) → None
Intercept rollback_twophase() events.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngine, 'rollback_twophase')
def receive_rollback_twophase(conn, xid, is_prepared):
"listen for the 'rollback_twophase' event"
# ... (event handling logic) ...
```
- Parameters:
- **conn** – [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
- **xid** – two-phase XID identifier
- **is\_prepared** – boolean, indicates if [TwoPhaseTransaction.prepare()]($3743e3464fa80ce7.md#sqlalchemy.engine.TwoPhaseTransaction.prepare "sqlalchemy.engine.TwoPhaseTransaction.prepare") was called.
method sqlalchemy.events.ConnectionEvents.savepoint(conn: , name: str) → None
Intercept savepoint() events.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngine, 'savepoint')
def receive_savepoint(conn, name):
"listen for the 'savepoint' event"
# ... (event handling logic) ...
```
- Parameters:
- **conn** – [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
- **name** – specified name used for the savepoint.
method sqlalchemy.events.ConnectionEvents.set_connection_execution_options(conn: , opts: Dict[str, Any]) → None
Intercept when the Connection.execution_options() method is called.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngine, 'set_connection_execution_options')
def receive_set_connection_execution_options(conn, opts):
"listen for the 'set_connection_execution_options' event"
# ... (event handling logic) ...
```
This method is called after the new [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") has been produced, with the newly updated execution options collection, but before the [Dialect]($4877d6ccc0778d3e.md#sqlalchemy.engine.Dialect "sqlalchemy.engine.Dialect") has acted upon any of those new options.
Note that this method is not called when a new [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") is produced which is inheriting execution options from its parent [Engine]($3743e3464fa80ce7.md#sqlalchemy.engine.Engine "sqlalchemy.engine.Engine"); to intercept this condition, use the [ConnectionEvents.engine\_connect()](#sqlalchemy.events.ConnectionEvents.engine_connect "sqlalchemy.events.ConnectionEvents.engine_connect") event.
- Parameters:
- **conn** – The newly copied [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
- **opts** –
dictionary of options that were passed to the [Connection.execution\_options()]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection.execution_options "sqlalchemy.engine.Connection.execution_options") method. This dictionary may be modified in place to affect the ultimate options which take effect.
New in version 2.0: the `opts` dictionary may be modified in place.
See also
[ConnectionEvents.set\_engine\_execution\_options()](#sqlalchemy.events.ConnectionEvents.set_engine_execution_options "sqlalchemy.events.ConnectionEvents.set_engine_execution_options") - event which is called when [Engine.execution\_options()]($3743e3464fa80ce7.md#sqlalchemy.engine.Engine.execution_options "sqlalchemy.engine.Engine.execution_options") is called.
method set_engine_execution_options(engine: Engine, opts: Dict[str, Any]) → None
Intercept when the method is called.
Example argument forms:
``` from sqlalchemy import event
class sqlalchemy.events.DialectEvents
event interface for execution-replacement functions.
These events allow direct instrumentation and replacement of key dialect functions which interact with the DBAPI.
Note
DialectEvents hooks should be considered semi-public and experimental. These hooks are not for general use and are only for those situations where intricate re-statement of DBAPI mechanics must be injected onto an existing dialect. For general-use statement-interception events, please use the interface.
See also
ConnectionEvents.before_cursor_execute()
ConnectionEvents.after_cursor_execute()
New in version 0.9.4.
Members
dispatch, , do_execute(), , do_executemany(), , handle_error()
Class signature
class (sqlalchemy.event.Events
)
attribute sqlalchemy.events.DialectEvents.dispatch: _Dispatch[_ET] = <sqlalchemy.event.base.DialectEventsDispatch object>
Bidirectional against _Dispatch._events
method do_connect(dialect: Dialect, conn_rec: , cargs: Tuple[Any, …], cparams: Dict[str, Any]) → Optional[]
Receive connection arguments before a connection is made.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngine, 'do_connect')
def receive_do_connect(dialect, conn_rec, cargs, cparams):
"listen for the 'do_connect' event"
# ... (event handling logic) ...
```
This event is useful in that it allows the handler to manipulate the cargs and/or cparams collections that control how the DBAPI `connect()` function will be called. `cargs` will always be a Python list that can be mutated in-place, and `cparams` a Python dictionary that may also be mutated:
```
e = create_engine("postgresql+psycopg2://user@host/dbname")
@event.listens_for(e, 'do_connect')
def receive_do_connect(dialect, conn_rec, cargs, cparams):
cparams["password"] = "some_password"
```
The event hook may also be used to override the call to `connect()` entirely, by returning a non-`None` DBAPI connection object:
```
e = create_engine("postgresql+psycopg2://user@host/dbname")
def receive_do_connect(dialect, conn_rec, cargs, cparams):
return psycopg2.connect(*cargs, **cparams)
```
New in version 1.0.3.
See also
[Custom DBAPI connect() arguments / on-connect routines]($5bcc461417e5d55c.md#custom-dbapi-args)
method sqlalchemy.events.DialectEvents.do_execute(cursor: , statement: str, parameters: _DBAPISingleExecuteParams, context: ExecutionContext) → Optional[Literal[True]]
Receive a cursor to have execute() called.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngine, 'do_execute')
"listen for the 'do_execute' event"
# ... (event handling logic) ...
```
Return the value True to halt further events from invoking, and to indicate that the cursor execution has already taken place within the event handler.
method do_execute_no_params(cursor: DBAPICursor, statement: str, context: ) → Optional[Literal[True]]
Receive a cursor to have execute() with no parameters called.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngine, 'do_execute_no_params')
def receive_do_execute_no_params(cursor, statement, context):
"listen for the 'do_execute_no_params' event"
# ... (event handling logic) ...
```
Return the value True to halt further events from invoking, and to indicate that the cursor execution has already taken place within the event handler.
method sqlalchemy.events.DialectEvents.do_executemany(cursor: , statement: str, parameters: _DBAPIMultiExecuteParams, context: ExecutionContext) → Optional[Literal[True]]
Receive a cursor to have executemany() called.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngine, 'do_executemany')
def receive_do_executemany(cursor, statement, parameters, context):
"listen for the 'do_executemany' event"
# ... (event handling logic) ...
```
Return the value True to halt further events from invoking, and to indicate that the cursor execution has already taken place within the event handler.
method do_setinputsizes(inputsizes: Dict[BindParameter[Any], Any], cursor: , statement: str, parameters: _DBAPIAnyExecuteParams, context: ExecutionContext) → None
Receive the setinputsizes dictionary for possible modification.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngine, 'do_setinputsizes')
def receive_do_setinputsizes(inputsizes, cursor, statement, parameters, context):
"listen for the 'do_setinputsizes' event"
# ... (event handling logic) ...
```
This event is emitted in the case where the dialect makes use of the DBAPI `cursor.setinputsizes()` method which passes information about parameter binding for a particular statement. The given `inputsizes` dictionary will contain [BindParameter]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.BindParameter "sqlalchemy.sql.expression.BindParameter") objects as keys, linked to DBAPI-specific type objects as values; for parameters that are not bound, they are added to the dictionary with `None` as the value, which means the parameter will not be included in the ultimate setinputsizes call. The event may be used to inspect and/or log the datatypes that are being bound, as well as to modify the dictionary in place. Parameters can be added, modified, or removed from this dictionary. Callers will typically want to inspect the `BindParameter.type` attribute of the given bind objects in order to make decisions about the DBAPI object.
After the event, the `inputsizes` dictionary is converted into an appropriate datastructure to be passed to `cursor.setinputsizes`; either a list for a positional bound parameter execution style, or a dictionary of string parameter keys to DBAPI type objects for a named bound parameter execution style.
The setinputsizes hook overall is only used for dialects which include the flag `use_setinputsizes=True`. Dialects which use this include cx\_Oracle, pg8000, asyncpg, and pyodbc dialects.
Note
For use with pyodbc, the `use_setinputsizes` flag must be passed to the dialect, e.g.:
```
create_engine("mssql+pyodbc://...", use_setinputsizes=True)
```
See also
[Setinputsizes Support]($6934fd6e6a9b44d0.md#mssql-pyodbc-setinputsizes)
New in version 1.2.9.
See also
[Fine grained control over cx\_Oracle data binding performance with setinputsizes]($ad7463812e601793.md#cx-oracle-setinputsizes)
method handle_error(exception_context: ExceptionContext) → Optional[BaseException]
Intercept all exceptions processed by the , typically but not limited to those emitted within the scope of a Connection.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeEngine, 'handle_error')
def receive_handle_error(exception_context):
"listen for the 'handle_error' event"
# ... (event handling logic) ...
```
Changed in version 2.0: the [DialectEvents.handle\_error()](#sqlalchemy.events.DialectEvents.handle_error "sqlalchemy.events.DialectEvents.handle_error") event is moved to the [DialectEvents](#sqlalchemy.events.DialectEvents "sqlalchemy.events.DialectEvents") class, moved from the [ConnectionEvents](#sqlalchemy.events.ConnectionEvents "sqlalchemy.events.ConnectionEvents") class, so that it may also participate in the “pre ping” operation configured with the [create\_engine.pool\_pre\_ping]($5bcc461417e5d55c.md#sqlalchemy.create_engine.params.pool_pre_ping "sqlalchemy.create_engine") parameter. The event remains registered by using the [Engine]($3743e3464fa80ce7.md#sqlalchemy.engine.Engine "sqlalchemy.engine.Engine") as the event target, however note that using the [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") as an event target for [DialectEvents.handle\_error()](#sqlalchemy.events.DialectEvents.handle_error "sqlalchemy.events.DialectEvents.handle_error") is no longer supported.
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()](#sqlalchemy.events.DialectEvents.handle_error "sqlalchemy.events.DialectEvents.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]($3743e3464fa80ce7.md#sqlalchemy.engine.ExceptionContext "sqlalchemy.engine.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
- Establishing whether a DBAPI connection error message indicates that the database connection needs to be reconnected, including for the “pre\_ping” handler used by **some** dialects
- Establishing or disabling whether a connection or the owning connection pool is invalidated or expired in response to a specific exception
- exception re-writing
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.
As of SQLAlchemy 2.0, the “pre\_ping” handler enabled using the [create\_engine.pool\_pre\_ping]($5bcc461417e5d55c.md#sqlalchemy.create_engine.params.pool_pre_ping "sqlalchemy.create_engine") parameter will also participate in the [handle\_error()](#sqlalchemy.events.DialectEvents.handle_error "sqlalchemy.events.DialectEvents.handle_error") process, **for those dialects that rely upon disconnect codes to detect database liveness**. Note that some dialects such as psycopg, psycopg2, and most MySQL dialects make use of a native `ping()` method supplied by the DBAPI which does not make use of disconnect codes.
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 [DialectEvents.handle\_error()](#sqlalchemy.events.DialectEvents.handle_error "sqlalchemy.events.DialectEvents.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]($3743e3464fa80ce7.md#sqlalchemy.engine.ExceptionContext.chained_exception "sqlalchemy.engine.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]($40db62cb9ae746c0.md#sqlalchemy.exc.StatementError "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.
- Parameters:
**context** – an [ExceptionContext]($3743e3464fa80ce7.md#sqlalchemy.engine.ExceptionContext "sqlalchemy.engine.ExceptionContext") object. See this class for details on all available members.
See also
[Supporting new database error codes for disconnect scenarios]($ba04c3bd42280074.md#pool-new-disconnect-codes)
class sqlalchemy.events.DDLEvents
Define event listeners for schema objects, that is, SchemaItem and other subclasses, including MetaData, , Column, etc.
Create / Drop Events
Events emitted when CREATE and DROP commands are emitted to the database. The event hooks in this category include , DDLEvents.after_create(), , and DDLEvents.after_drop().
These events are emitted when using schema-level methods such as and MetaData.drop_all(). Per-object create/drop methods such as , Table.drop(), are also included, as well as dialect-specific methods such as ENUM.create().
New in version 2.0: event hooks now take place for non-table objects including constraints, indexes, and dialect-specific schema types.
Event hooks may be attached directly to a Table object or to a collection, as well as to any SchemaItem class or object that can be individually created and dropped using a distinct SQL command. Such classes include , Sequence, and dialect-specific classes such as .
Example using the DDLEvents.after_create() event, where a custom event hook will emit an ALTER TABLE
command on the current connection, after CREATE TABLE
is emitted:
from sqlalchemy import create_engine
from sqlalchemy import event
from sqlalchemy import Table, Column, Metadata, Integer
m = MetaData()
some_table = Table('some_table', m, Column('data', Integer))
@event.listens_for(some_table, "after_create")
def after_create(target, connection, **kw):
connection.execute(text(
"ALTER TABLE %s SET name=foo_%s" % (target.name, target.name)
))
some_engine = create_engine("postgresql://scott:tiger@host/test")
# will emit "CREATE TABLE some_table" as well as the above
# "ALTER TABLE" statement afterwards
m.create_all(some_engine)
Constraint objects such as , UniqueConstraint, may also be subscribed to these events, however they will not normally produce events as these objects are usually rendered inline within an enclosing CREATE TABLE
statement and implicitly dropped from a DROP TABLE
statement.
For the Index construct, the event hook will be emitted for CREATE INDEX
, however SQLAlchemy does not normally emit DROP INDEX
when dropping tables as this is again implicit within the DROP TABLE
statement.
New in version 2.0: Support for objects for create/drop events was expanded from its previous support for MetaData and to also include Constraint and all subclasses, , Sequence and some type-related constructs such as .
Note
These event hooks are only emitted within the scope of SQLAlchemy’s create/drop methods; they are not necessarily supported by tools such as alembic.
Attachment Events
Attachment events are provided to customize behavior whenever a child schema element is associated with a parent, such as when a is associated with its Table, when a is associated with a Table, etc. These events include and DDLEvents.after_parent_attach().
Reflection Events
The event is used to intercept and modify the in-Python definition of database columns when reflection of database tables proceeds.
Use with Generic DDL
DDL events integrate closely with the class and the ExecutableDDLElement hierarchy of DDL clause constructs, which are themselves appropriate as listener callables:
from sqlalchemy import DDL
event.listen(
some_table,
"after_create",
DDL("ALTER TABLE %(table)s SET name=foo_%(table)s")
)
Event Propagation to MetaData Copies
For all DDLEvent
events, the propagate=True
keyword argument will ensure that a given event handler is propagated to copies of the object, which are made when using the method:
from sqlalchemy import DDL
metadata = MetaData()
some_table = Table("some_table", metadata, Column("data", Integer))
event.listen(
some_table,
"after_create",
DDL("ALTER TABLE %(table)s SET name=foo_%(table)s"),
propagate=True
)
new_metadata = MetaData()
new_table = some_table.to_metadata(new_metadata)
The above DDL object will be associated with the event for both the some_table
and the new_table
Table objects.
See also
Members
, after_drop(), , before_create(), , before_parent_attach(), , dispatch
Class signature
class (sqlalchemy.event.Events
)
method sqlalchemy.events.DDLEvents.after_create(target: , connection: Connection, **kw: Any) → None
Called after CREATE statements are emitted.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSchemaClassOrObject, 'after_create')
def receive_after_create(target, connection, **kw):
"listen for the 'after_create' event"
# ... (event handling logic) ...
```
- Parameters:
- **target** –
the `SchemaObject`, such as a [MetaData]($e81afa1a43dcc92a.md#sqlalchemy.schema.MetaData "sqlalchemy.schema.MetaData") or [Table]($e81afa1a43dcc92a.md#sqlalchemy.schema.Table "sqlalchemy.schema.Table") but also including all create/drop objects such as [Index]($bfd9186e74b37638.md#sqlalchemy.schema.Index "sqlalchemy.schema.Index"), [Sequence]($6bf23ed88b114c55.md#sqlalchemy.schema.Sequence "sqlalchemy.schema.Sequence"), etc., object which is the target of the event.
New in version 2.0: Support for all [SchemaItem]($e81afa1a43dcc92a.md#sqlalchemy.schema.SchemaItem "sqlalchemy.schema.SchemaItem") objects was added.
- **connection** – the [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") where the CREATE statement or statements have been emitted.
- **\*\*kw** – additional keyword arguments relevant to the event. The contents of this dictionary may vary across releases, and include the list of tables being generated for a metadata-level event, the checkfirst flag, and other elements used by internal events.
[listen()]($3f6dba762b02614b.md#sqlalchemy.event.listen "sqlalchemy.event.listen") also accepts the `propagate=True` modifier for this event; when True, the listener function will be established for any copies made of the target object, i.e. those copies that are generated when [Table.to\_metadata()]($e81afa1a43dcc92a.md#sqlalchemy.schema.Table.to_metadata "sqlalchemy.schema.Table.to_metadata") is used.
method after_drop(target: SchemaEventTarget, connection: , **kw: Any) → None
Called after DROP statements are emitted.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSchemaClassOrObject, 'after_drop')
def receive_after_drop(target, connection, **kw):
"listen for the 'after_drop' event"
# ... (event handling logic) ...
```
- Parameters:
- **target** –
the `SchemaObject`, such as a [MetaData]($e81afa1a43dcc92a.md#sqlalchemy.schema.MetaData "sqlalchemy.schema.MetaData") or [Table]($e81afa1a43dcc92a.md#sqlalchemy.schema.Table "sqlalchemy.schema.Table") but also including all create/drop objects such as [Index]($bfd9186e74b37638.md#sqlalchemy.schema.Index "sqlalchemy.schema.Index"), [Sequence]($6bf23ed88b114c55.md#sqlalchemy.schema.Sequence "sqlalchemy.schema.Sequence"), etc., object which is the target of the event.
New in version 2.0: Support for all [SchemaItem]($e81afa1a43dcc92a.md#sqlalchemy.schema.SchemaItem "sqlalchemy.schema.SchemaItem") objects was added.
- **connection** – the [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") where the DROP statement or statements have been emitted.
- **\*\*kw** – additional keyword arguments relevant to the event. The contents of this dictionary may vary across releases, and include the list of tables being generated for a metadata-level event, the checkfirst flag, and other elements used by internal events.
[listen()]($3f6dba762b02614b.md#sqlalchemy.event.listen "sqlalchemy.event.listen") also accepts the `propagate=True` modifier for this event; when True, the listener function will be established for any copies made of the target object, i.e. those copies that are generated when [Table.to\_metadata()]($e81afa1a43dcc92a.md#sqlalchemy.schema.Table.to_metadata "sqlalchemy.schema.Table.to_metadata") is used.
method sqlalchemy.events.DDLEvents.after_parent_attach(target: , parent: SchemaItem) → None
Called after a is associated with a parent SchemaItem.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSchemaClassOrObject, 'after_parent_attach')
def receive_after_parent_attach(target, parent):
"listen for the 'after_parent_attach' event"
# ... (event handling logic) ...
```
- Parameters:
- **target** – the target object
- **parent** – the parent to which the target is being attached.
[listen()]($3f6dba762b02614b.md#sqlalchemy.event.listen "sqlalchemy.event.listen") also accepts the `propagate=True` modifier for this event; when True, the listener function will be established for any copies made of the target object, i.e. those copies that are generated when [Table.to\_metadata()]($e81afa1a43dcc92a.md#sqlalchemy.schema.Table.to_metadata "sqlalchemy.schema.Table.to_metadata") is used.
method before_create(target: SchemaEventTarget, connection: , **kw: Any) → None
Called before CREATE statements are emitted.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSchemaClassOrObject, 'before_create')
def receive_before_create(target, connection, **kw):
"listen for the 'before_create' event"
# ... (event handling logic) ...
```
- Parameters:
- **target** –
the `SchemaObject`, such as a [MetaData]($e81afa1a43dcc92a.md#sqlalchemy.schema.MetaData "sqlalchemy.schema.MetaData") or [Table]($e81afa1a43dcc92a.md#sqlalchemy.schema.Table "sqlalchemy.schema.Table") but also including all create/drop objects such as [Index]($bfd9186e74b37638.md#sqlalchemy.schema.Index "sqlalchemy.schema.Index"), [Sequence]($6bf23ed88b114c55.md#sqlalchemy.schema.Sequence "sqlalchemy.schema.Sequence"), etc., object which is the target of the event.
New in version 2.0: Support for all [SchemaItem]($e81afa1a43dcc92a.md#sqlalchemy.schema.SchemaItem "sqlalchemy.schema.SchemaItem") objects was added.
- **connection** – the [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") where the CREATE statement or statements will be emitted.
- **\*\*kw** – additional keyword arguments relevant to the event. The contents of this dictionary may vary across releases, and include the list of tables being generated for a metadata-level event, the checkfirst flag, and other elements used by internal events.
[listen()]($3f6dba762b02614b.md#sqlalchemy.event.listen "sqlalchemy.event.listen") accepts the `propagate=True` modifier for this event; when True, the listener function will be established for any copies made of the target object, i.e. those copies that are generated when [Table.to\_metadata()]($e81afa1a43dcc92a.md#sqlalchemy.schema.Table.to_metadata "sqlalchemy.schema.Table.to_metadata") is used.
[listen()]($3f6dba762b02614b.md#sqlalchemy.event.listen "sqlalchemy.event.listen") accepts the `insert=True` modifier for this event; when True, the listener function will be prepended to the internal list of events upon discovery, and execute before registered listener functions that do not pass this argument.
method sqlalchemy.events.DDLEvents.before_drop(target: , connection: Connection, **kw: Any) → None
Called before DROP statements are emitted.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSchemaClassOrObject, 'before_drop')
def receive_before_drop(target, connection, **kw):
"listen for the 'before_drop' event"
# ... (event handling logic) ...
```
- Parameters:
- **target** –
the `SchemaObject`, such as a [MetaData]($e81afa1a43dcc92a.md#sqlalchemy.schema.MetaData "sqlalchemy.schema.MetaData") or [Table]($e81afa1a43dcc92a.md#sqlalchemy.schema.Table "sqlalchemy.schema.Table") but also including all create/drop objects such as [Index]($bfd9186e74b37638.md#sqlalchemy.schema.Index "sqlalchemy.schema.Index"), [Sequence]($6bf23ed88b114c55.md#sqlalchemy.schema.Sequence "sqlalchemy.schema.Sequence"), etc., object which is the target of the event.
New in version 2.0: Support for all [SchemaItem]($e81afa1a43dcc92a.md#sqlalchemy.schema.SchemaItem "sqlalchemy.schema.SchemaItem") objects was added.
- **connection** – the [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") where the DROP statement or statements will be emitted.
- **\*\*kw** – additional keyword arguments relevant to the event. The contents of this dictionary may vary across releases, and include the list of tables being generated for a metadata-level event, the checkfirst flag, and other elements used by internal events.
[listen()]($3f6dba762b02614b.md#sqlalchemy.event.listen "sqlalchemy.event.listen") also accepts the `propagate=True` modifier for this event; when True, the listener function will be established for any copies made of the target object, i.e. those copies that are generated when [Table.to\_metadata()]($e81afa1a43dcc92a.md#sqlalchemy.schema.Table.to_metadata "sqlalchemy.schema.Table.to_metadata") is used.
method before_parent_attach(target: SchemaEventTarget, parent: ) → None
Called before a SchemaItem is associated with a parent .
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSchemaClassOrObject, 'before_parent_attach')
def receive_before_parent_attach(target, parent):
"listen for the 'before_parent_attach' event"
# ... (event handling logic) ...
```
- Parameters:
- **target** – the target object
- **parent** – the parent to which the target is being attached.
[listen()]($3f6dba762b02614b.md#sqlalchemy.event.listen "sqlalchemy.event.listen") also accepts the `propagate=True` modifier for this event; when True, the listener function will be established for any copies made of the target object, i.e. those copies that are generated when [Table.to\_metadata()]($e81afa1a43dcc92a.md#sqlalchemy.schema.Table.to_metadata "sqlalchemy.schema.Table.to_metadata") is used.
method sqlalchemy.events.DDLEvents.column_reflect(inspector: , table: Table, column_info: ) → None
Called for each unit of ‘column info’ retrieved when a Table is being reflected.
Example argument forms:
``` from sqlalchemy import event
class sqlalchemy.events.SchemaEventTarget
Base class for elements that are the targets of events.
This includes SchemaItem as well as .
Class signature