Core Events

This section describes the event interfaces provided in SQLAlchemy Core. For an introduction to the event listening API, see Events. ORM events are described in ORM Events.

Object NameDescription

Events

Define event listening functions for a particular target type.

class sqlalchemy.event.base.``Events

Define event listening functions for a particular target type.

Connection Pool Events

Object NameDescription

PoolEvents

Available events for Pool.

class sqlalchemy.events.``PoolEvents

Available events for Pool.

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

e.g.:

  1. from sqlalchemy import event
  2. def my_on_checkout(dbapi_conn, connection_rec, connection_proxy):
  3. "handle an on checkout event"
  4. event.listen(Pool, 'checkout', my_on_checkout)

In addition to accepting the Pool class and Pool instances, PoolEvents also accepts Engine objects and the Engine class as targets, which will be resolved to the .pool attribute of the given engine or the Pool class:

  1. engine = create_engine("postgresql://scott:tiger@localhost/test")
  2. # will associate with engine.pool
  3. event.listen(engine, 'checkout', my_on_checkout)

Class signature

class sqlalchemy.events.PoolEvents (sqlalchemy.event.Events)

  • method sqlalchemy.events.PoolEvents.checkin(dbapi_connection, connection_record)

    Called when a connection returns to the pool.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeEngineOrPool, 'checkin')
  2. def receive_checkin(dbapi_connection, connection_record):
  3. "listen for the 'checkin' event"
  4. # ... (event handling logic) ...
  5. ```
  6. 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.)
  7. - Parameters
  8. - **dbapi\_connection** – a DBAPI connection.
  9. - **connection\_record** – the [`_ConnectionRecord`]($dd0c1db3426fd2af.md#sqlalchemy.pool._ConnectionRecord "sqlalchemy.pool._ConnectionRecord") managing the DBAPI connection.
  • method sqlalchemy.events.PoolEvents.checkout(dbapi_connection, connection_record, connection_proxy)

    Called when a connection is retrieved from the Pool.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeEngineOrPool, 'checkout')
  2. def receive_checkout(dbapi_connection, connection_record, connection_proxy):
  3. "listen for the 'checkout' event"
  4. # ... (event handling logic) ...
  5. ```
  6. - Parameters
  7. - **dbapi\_connection** – a DBAPI connection.
  8. - **connection\_record** – the [`_ConnectionRecord`]($dd0c1db3426fd2af.md#sqlalchemy.pool._ConnectionRecord "sqlalchemy.pool._ConnectionRecord") managing the DBAPI connection.
  9. - **connection\_proxy** – the [`_ConnectionFairy`]($dd0c1db3426fd2af.md#sqlalchemy.pool._ConnectionFairy "sqlalchemy.pool._ConnectionFairy") object which will proxy the public interface of the DBAPI connection for the lifespan of the checkout.
  10. If you raise a [`DisconnectionError`]($93db9a8cbc566d23.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.
  11. See also
  12. [`ConnectionEvents.engine_connect()`](#sqlalchemy.events.ConnectionEvents.engine_connect "sqlalchemy.events.ConnectionEvents.engine_connect") - a similar event which occurs upon creation of a new [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection").
  • method sqlalchemy.events.PoolEvents.close(dbapi_connection, connection_record)

    Called when a DBAPI connection is closed.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeEngineOrPool, 'close')
  2. def receive_close(dbapi_connection, connection_record):
  3. "listen for the 'close' event"
  4. # ... (event handling logic) ...
  5. ```
  6. The event is emitted before the close occurs.
  7. 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.
  8. 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").
  9. New in version 1.1.
  • method sqlalchemy.events.PoolEvents.close_detached(dbapi_connection)

    Called when a detached DBAPI connection is closed.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeEngineOrPool, 'close_detached')
  2. def receive_close_detached(dbapi_connection):
  3. "listen for the 'close_detached' event"
  4. # ... (event handling logic) ...
  5. ```
  6. The event is emitted before the close occurs.
  7. 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.
  8. New in version 1.1.
  • method sqlalchemy.events.PoolEvents.connect(dbapi_connection, connection_record)

    Called at the moment a particular DBAPI connection is first created for a given Pool.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeEngineOrPool, 'connect')
  2. def receive_connect(dbapi_connection, connection_record):
  3. "listen for the 'connect' event"
  4. # ... (event handling logic) ...
  5. ```
  6. 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.
  7. - Parameters
  8. - **dbapi\_connection** – a DBAPI connection.
  9. - **connection\_record** – the [`_ConnectionRecord`]($dd0c1db3426fd2af.md#sqlalchemy.pool._ConnectionRecord "sqlalchemy.pool._ConnectionRecord") managing the DBAPI connection.
  • method sqlalchemy.events.PoolEvents.detach(dbapi_connection, connection_record)

    Called when a DBAPI connection is “detached” from a pool.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeEngineOrPool, 'detach')
  2. def receive_detach(dbapi_connection, connection_record):
  3. "listen for the 'detach' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is emitted after the detach occurs. The connection is no longer associated with the given connection record.
  7. New in version 1.1.
  • method sqlalchemy.events.PoolEvents.first_connect(dbapi_connection, connection_record)

    Called exactly once for the first time a DBAPI connection is checked out from a particular Pool.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeEngineOrPool, 'first_connect')
  2. def receive_first_connect(dbapi_connection, connection_record):
  3. "listen for the 'first_connect' event"
  4. # ... (event handling logic) ...
  5. ```
  6. 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`]($dd0c1db3426fd2af.md#sqlalchemy.pool.Pool "sqlalchemy.pool.Pool") refers to a single “creator” function (which in terms of a [`Engine`]($cd778e34cf5e4642.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.
  7. - Parameters
  8. - **dbapi\_connection** – a DBAPI connection.
  9. - **connection\_record** – the [`_ConnectionRecord`]($dd0c1db3426fd2af.md#sqlalchemy.pool._ConnectionRecord "sqlalchemy.pool._ConnectionRecord") managing the DBAPI connection.
  • method sqlalchemy.events.PoolEvents.invalidate(dbapi_connection, connection_record, exception)

    Called when a DBAPI connection is to be “invalidated”.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeEngineOrPool, 'invalidate')
  2. def receive_invalidate(dbapi_connection, connection_record, exception):
  3. "listen for the 'invalidate' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is called any time the [`_ConnectionRecord.invalidate()`]($dd0c1db3426fd2af.md#sqlalchemy.pool._ConnectionRecord.invalidate "sqlalchemy.pool._ConnectionRecord.invalidate") method is invoked, either from API usage or via “auto-invalidation”, without the `soft` flag.
  7. The event occurs before a final attempt to call `.close()` on the connection occurs.
  8. - Parameters
  9. - **dbapi\_connection** – a DBAPI connection.
  10. - **connection\_record** – the [`_ConnectionRecord`]($dd0c1db3426fd2af.md#sqlalchemy.pool._ConnectionRecord "sqlalchemy.pool._ConnectionRecord") managing the DBAPI connection.
  11. - **exception** – the exception object corresponding to the reason for this invalidation, if any. May be `None`.
  12. New in version 0.9.2: Added support for connection invalidation listening.
  13. See also
  14. [More on Invalidation]($dd0c1db3426fd2af.md#pool-connection-invalidation)
  • method sqlalchemy.events.PoolEvents.reset(dbapi_connection, connection_record)

    Called before the “reset” action occurs for a pooled connection.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeEngineOrPool, 'reset')
  2. def receive_reset(dbapi_connection, connection_record):
  3. "listen for the 'reset' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event represents when the `rollback()` method is called on the DBAPI connection before it is returned to the pool. The behavior of “reset” can be controlled, including disabled, using the `reset_on_return` pool argument.
  7. 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 is called, except in those cases where the connection is discarded immediately after reset.
  8. - Parameters
  9. - **dbapi\_connection** – a DBAPI connection.
  10. - **connection\_record** – the [`_ConnectionRecord`]($dd0c1db3426fd2af.md#sqlalchemy.pool._ConnectionRecord "sqlalchemy.pool._ConnectionRecord") managing the DBAPI connection.
  11. See also
  12. [`ConnectionEvents.rollback()`](#sqlalchemy.events.ConnectionEvents.rollback "sqlalchemy.events.ConnectionEvents.rollback")
  13. [`ConnectionEvents.commit()`](#sqlalchemy.events.ConnectionEvents.commit "sqlalchemy.events.ConnectionEvents.commit")
  • method sqlalchemy.events.PoolEvents.soft_invalidate(dbapi_connection, connection_record, exception)

    Called when a DBAPI connection is to be “soft invalidated”.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeEngineOrPool, 'soft_invalidate')
  2. def receive_soft_invalidate(dbapi_connection, connection_record, exception):
  3. "listen for the 'soft_invalidate' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is called any time the [`_ConnectionRecord.invalidate()`]($dd0c1db3426fd2af.md#sqlalchemy.pool._ConnectionRecord.invalidate "sqlalchemy.pool._ConnectionRecord.invalidate") method is invoked with the `soft` flag.
  7. 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.
  8. New in version 1.0.3.

SQL Execution and Connection Events

Object NameDescription

ConnectionEvents

Available events for Connectable, which includes Connection and Engine.

DialectEvents

event interface for execution-replacement functions.

class sqlalchemy.events.``ConnectionEvents

Available events for Connectable, which includes Connection 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 Connectable class or instance, such as an Engine, e.g.:

  1. from sqlalchemy import event, create_engine
  2. def before_cursor_execute(conn, cursor, statement, parameters, context,
  3. executemany):
  4. log.info("Received statement: %s", statement)
  5. engine = create_engine('postgresql://scott:tiger@localhost/test')
  6. event.listen(engine, "before_cursor_execute", before_cursor_execute)

or with a specific Connection:

  1. with engine.begin() as conn:
  2. @event.listens_for(conn, 'before_cursor_execute')
  3. def before_cursor_execute(conn, cursor, statement, parameters,
  4. context, executemany):
  5. 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:

  1. from sqlalchemy.engine import Engine
  2. from sqlalchemy import event
  3. @event.listens_for(Engine, "before_cursor_execute", retval=True)
  4. def comment_sql_calls(conn, cursor, statement, parameters,
  5. context, executemany):
  6. statement = statement + " -- some comment"
  7. return statement, parameters

Note

ConnectionEvents can be established on any combination of Engine, Connection, 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 Connection object determines at instantiation time whether or not its parent Engine has event listeners established. Event listeners added to the Engine class or to an instance of Engine after the instantiation of a dependent Connection instance will usually not be available on that Connection instance. The newly added listeners will instead take effect for Connection instances created subsequent to those event listeners being established on the parent Engine class or instance.

  • Parameters

    retval=False – Applies 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 signature

class sqlalchemy.events.ConnectionEvents (sqlalchemy.event.Events)

  • method sqlalchemy.events.ConnectionEvents.after_cursor_execute(conn, cursor, statement, parameters, context, executemany)

    Intercept low-level cursor execute() events after execution.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeEngine, 'after_cursor_execute')
  2. def receive_after_cursor_execute(conn, cursor, statement, parameters, context, executemany):
  3. "listen for the 'after_cursor_execute' event"
  4. # ... (event handling logic) ...
  5. ```
  6. - Parameters
  7. - **conn** – [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
  8. - **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`]($cd778e34cf5e4642.md#sqlalchemy.engine.CursorResult "sqlalchemy.engine.CursorResult").
  9. - **statement** – string SQL statement, as passed to the DBAPI
  10. - **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`.
  11. - **context** – [`ExecutionContext`]($52b7b42f4bea86d9.md#sqlalchemy.engine.ExecutionContext "sqlalchemy.engine.ExecutionContext") object in use. May be `None`.
  12. - **executemany** – boolean, if `True`, this is an `executemany()` call, if `False`, this is an `execute()` call.
  • method sqlalchemy.events.ConnectionEvents.after_execute(conn, clauseelement, multiparams, params, execution_options, result)

    Intercept high level execute() events after execute.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeEngine, 'after_execute')
  2. def receive_after_execute(conn, clauseelement, multiparams, params, execution_options, result):
  3. "listen for the 'after_execute' event"
  4. # ... (event handling logic) ...
  5. # DEPRECATED calling style (pre-1.4, will be removed in a future release)
  6. @event.listens_for(SomeEngine, 'after_execute')
  7. def receive_after_execute(conn, clauseelement, multiparams, params, result):
  8. "listen for the 'after_execute' event"
  9. # ... (event handling logic) ...
  10. ```
  11. Deprecated since version 1.4: The `after_execute` event now accepts the arguments `conn, clauseelement, multiparams, params, execution_options, result`. Support for listener functions which accept the previous argument signature(s) listed above as “deprecated” will be removed in a future release.
  12. - Parameters
  13. - **conn** – [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
  14. - **clauseelement** – SQL expression construct, [`Compiled`]($52b7b42f4bea86d9.md#sqlalchemy.engine.Compiled "sqlalchemy.engine.Compiled") instance, or string statement passed to [`Connection.execute()`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection.execute "sqlalchemy.engine.Connection.execute").
  15. - **multiparams** – Multiple parameter sets, a list of dictionaries.
  16. - **params** – Single parameter set, a single dictionary.
  17. - **execution\_options** –
  18. 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.
  19. - **result** – [`CursorResult`]($cd778e34cf5e4642.md#sqlalchemy.engine.CursorResult "sqlalchemy.engine.CursorResult") generated by the execution.
  • method sqlalchemy.events.ConnectionEvents.before_cursor_execute(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.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeEngine, 'before_cursor_execute')
  2. def receive_before_cursor_execute(conn, cursor, statement, parameters, context, executemany):
  3. "listen for the 'before_cursor_execute' event"
  4. # ... (event handling logic) ...
  5. ```
  6. 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.
  7. 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:
  8. ```
  9. @event.listens_for(Engine, "before_cursor_execute", retval=True)
  10. def before_cursor_execute(conn, cursor, statement,
  11. parameters, context, executemany):
  12. # do something with statement, parameters
  13. return statement, parameters
  14. ```
  15. See the example at [`ConnectionEvents`](#sqlalchemy.events.ConnectionEvents "sqlalchemy.events.ConnectionEvents").
  16. - Parameters
  17. - **conn** – [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
  18. - **cursor** – DBAPI cursor object
  19. - **statement** – string SQL statement, as to be passed to the DBAPI
  20. - **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`.
  21. - **context** – [`ExecutionContext`]($52b7b42f4bea86d9.md#sqlalchemy.engine.ExecutionContext "sqlalchemy.engine.ExecutionContext") object in use. May be `None`.
  22. - **executemany** – boolean, if `True`, this is an `executemany()` call, if `False`, this is an `execute()` call.
  23. See also
  24. [`before_execute()`](#sqlalchemy.events.ConnectionEvents.before_execute "sqlalchemy.events.ConnectionEvents.before_execute")
  25. [`after_cursor_execute()`](#sqlalchemy.events.ConnectionEvents.after_cursor_execute "sqlalchemy.events.ConnectionEvents.after_cursor_execute")
  • method sqlalchemy.events.ConnectionEvents.before_execute(conn, clauseelement, multiparams, params, execution_options)

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

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeEngine, 'before_execute')
  2. def receive_before_execute(conn, clauseelement, multiparams, params, execution_options):
  3. "listen for the 'before_execute' event"
  4. # ... (event handling logic) ...
  5. # DEPRECATED calling style (pre-1.4, will be removed in a future release)
  6. @event.listens_for(SomeEngine, 'before_execute')
  7. def receive_before_execute(conn, clauseelement, multiparams, params):
  8. "listen for the 'before_execute' event"
  9. # ... (event handling logic) ...
  10. ```
  11. Deprecated since version 1.4: The `before_execute` event now accepts the arguments `conn, clauseelement, multiparams, params, execution_options`. Support for listener functions which accept the previous argument signature(s) listed above as “deprecated” will be removed in a future release.
  12. 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.
  13. 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:
  14. ```
  15. @event.listens_for(Engine, "before_execute", retval=True)
  16. def before_execute(conn, clauseelement, multiparams, params):
  17. # do something with clauseelement, multiparams, params
  18. return clauseelement, multiparams, params
  19. ```
  20. - Parameters
  21. - **conn** – [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
  22. - **clauseelement** – SQL expression construct, [`Compiled`]($52b7b42f4bea86d9.md#sqlalchemy.engine.Compiled "sqlalchemy.engine.Compiled") instance, or string statement passed to [`Connection.execute()`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection.execute "sqlalchemy.engine.Connection.execute").
  23. - **multiparams** – Multiple parameter sets, a list of dictionaries.
  24. - **params** – Single parameter set, a single dictionary.
  25. - **execution\_options** –
  26. 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.
  27. See also
  28. [`before_cursor_execute()`](#sqlalchemy.events.ConnectionEvents.before_cursor_execute "sqlalchemy.events.ConnectionEvents.before_cursor_execute")
  1. @event.listens_for(SomeEngine, 'begin')
  2. def receive_begin(conn):
  3. "listen for the 'begin' event"
  4. # ... (event handling logic) ...
  5. ```
  6. - Parameters
  7. **conn** – [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
  1. @event.listens_for(SomeEngine, 'begin_twophase')
  2. def receive_begin_twophase(conn, xid):
  3. "listen for the 'begin_twophase' event"
  4. # ... (event handling logic) ...
  5. ```
  6. - Parameters
  7. - **conn** – [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
  8. - **xid** – two-phase XID identifier
  1. @event.listens_for(SomeEngine, 'commit')
  2. def receive_commit(conn):
  3. "listen for the 'commit' event"
  4. # ... (event handling logic) ...
  5. ```
  6. Note that the [`Pool`]($dd0c1db3426fd2af.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.
  7. - Parameters
  8. **conn** – [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
  • method sqlalchemy.events.ConnectionEvents.commit_twophase(conn, xid, is_prepared)

    Intercept commit_twophase() events.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeEngine, 'commit_twophase')
  2. def receive_commit_twophase(conn, xid, is_prepared):
  3. "listen for the 'commit_twophase' event"
  4. # ... (event handling logic) ...
  5. ```
  6. - Parameters
  7. - **conn** – [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
  8. - **xid** – two-phase XID identifier
  9. - **is\_prepared** – boolean, indicates if [`TwoPhaseTransaction.prepare()`]($cd778e34cf5e4642.md#sqlalchemy.engine.TwoPhaseTransaction.prepare "sqlalchemy.engine.TwoPhaseTransaction.prepare") was called.
  1. @event.listens_for(SomeEngine, 'engine_connect')
  2. def receive_engine_connect(conn, branch):
  3. "listen for the 'engine_connect' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is called typically as the direct result of calling the [`Engine.connect()`]($cd778e34cf5e4642.md#sqlalchemy.engine.Engine.connect "sqlalchemy.engine.Engine.connect") method.
  7. 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`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") wrapper around such a DBAPI connection.
  8. It also differs from the [`PoolEvents.checkout()`](#sqlalchemy.events.PoolEvents.checkout "sqlalchemy.events.PoolEvents.checkout") event in that it is specific to the [`Connection`]($cd778e34cf5e4642.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`]($cd778e34cf5e4642.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`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object, if that [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") is invalidated and re-established. There can also be multiple [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") objects generated for the same already-checked-out DBAPI connection, in the case that a “branch” of a [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") is produced.
  9. - Parameters
  10. - **conn** – [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object.
  11. - **branch** – if True, this is a “branch” of an existing [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.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.
  12. See also
  13. [`PoolEvents.checkout()`](#sqlalchemy.events.PoolEvents.checkout "sqlalchemy.events.PoolEvents.checkout") the lower-level pool checkout event for an individual DBAPI connection
  1. @event.listens_for(SomeEngine, 'engine_disposed')
  2. def receive_engine_disposed(engine):
  3. "listen for the 'engine_disposed' event"
  4. # ... (event handling logic) ...
  5. ```
  6. The [`Engine.dispose()`]($cd778e34cf5e4642.md#sqlalchemy.engine.Engine.dispose "sqlalchemy.engine.Engine.dispose") method instructs the engine to “dispose” of it’s connection pool (e.g. [`Pool`]($dd0c1db3426fd2af.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.
  7. This event can be used to indicate that resources related to the [`Engine`]($cd778e34cf5e4642.md#sqlalchemy.engine.Engine "sqlalchemy.engine.Engine") should also be cleaned up, keeping in mind that the [`Engine`]($cd778e34cf5e4642.md#sqlalchemy.engine.Engine "sqlalchemy.engine.Engine") can still be used for new requests in which case it re-acquires connection resources.
  8. New in version 1.0.5.
  1. @event.listens_for(SomeEngine, 'handle_error')
  2. def receive_handle_error(exception_context):
  3. "listen for the 'handle_error' event"
  4. # ... (event handling logic) ...
  5. ```
  6. 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.
  7. Note that [`handle_error()`](#sqlalchemy.events.ConnectionEvents.handle_error "sqlalchemy.events.ConnectionEvents.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.
  8. 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`]($cd778e34cf5e4642.md#sqlalchemy.engine.ExceptionContext "sqlalchemy.engine.ExceptionContext"). This object contains data members representing detail about the exception.
  9. Use cases supported by this hook include:
  10. - read-only, low-level exception handling for logging and debugging purposes
  11. - exception re-writing
  12. - Establishing or disabling whether a connection or the owning connection pool is invalidated or expired in response to a specific exception [1](#id2).
  13. 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.
  14. Note
  15. - [1](#id1)
  16. The pool “pre\_ping” handler enabled using the [`create_engine.pool_pre_ping`]($1741d37c5d31b92e.md#sqlalchemy.create_engine.params.pool_pre_ping "sqlalchemy.create_engine") 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 [legacy recipe based on engine\_connect() may be used]($dd0c1db3426fd2af.md#pool-disconnects-pessimistic-custom). A future API allow more comprehensive customization of the “disconnect” detection mechanism across all functions.
  17. 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:
  18. ```
  19. @event.listens_for(Engine, "handle_error")
  20. def handle_exception(context):
  21. if isinstance(context.original_exception,
  22. psycopg2.OperationalError) and \
  23. "failed" in str(context.original_exception):
  24. raise MySpecialException("failed operation")
  25. ```
  26. Warning
  27. Because the [`ConnectionEvents.handle_error()`](#sqlalchemy.events.ConnectionEvents.handle_error "sqlalchemy.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.
  28. 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`]($cd778e34cf5e4642.md#sqlalchemy.engine.ExceptionContext.chained_exception "sqlalchemy.engine.ExceptionContext.chained_exception"):
  29. ```
  30. @event.listens_for(Engine, "handle_error", retval=True)
  31. def handle_exception(context):
  32. if context.chained_exception is not None and \
  33. "special" in context.chained_exception.message:
  34. return MySpecialException("failed",
  35. cause=context.chained_exception)
  36. ```
  37. 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.
  38. 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`]($93db9a8cbc566d23.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.
  39. - Parameters
  40. **context** – an [`ExceptionContext`]($cd778e34cf5e4642.md#sqlalchemy.engine.ExceptionContext "sqlalchemy.engine.ExceptionContext") object. See this class for details on all available members.
  41. New in version 0.9.7: Added the [`ConnectionEvents.handle_error()`](#sqlalchemy.events.ConnectionEvents.handle_error "sqlalchemy.events.ConnectionEvents.handle_error") hook.
  42. Changed in version 1.1: The [`handle_error()`](#sqlalchemy.events.ConnectionEvents.handle_error "sqlalchemy.events.ConnectionEvents.handle_error") event will now receive all exceptions that inherit from `BaseException`, including `SystemExit` and `KeyboardInterrupt`. The setting for [`ExceptionContext.is_disconnect`]($cd778e34cf5e4642.md#sqlalchemy.engine.ExceptionContext.is_disconnect "sqlalchemy.engine.ExceptionContext.is_disconnect") is `True` in this case and the default for [`ExceptionContext.invalidate_pool_on_disconnect`]($cd778e34cf5e4642.md#sqlalchemy.engine.ExceptionContext.invalidate_pool_on_disconnect "sqlalchemy.engine.ExceptionContext.invalidate_pool_on_disconnect") is `False`.
  43. Changed in version 1.0.0: The [`handle_error()`](#sqlalchemy.events.ConnectionEvents.handle_error "sqlalchemy.events.ConnectionEvents.handle_error") event is now invoked when an [`Engine`]($cd778e34cf5e4642.md#sqlalchemy.engine.Engine "sqlalchemy.engine.Engine") fails during the initial call to [`Engine.connect()`]($cd778e34cf5e4642.md#sqlalchemy.engine.Engine.connect "sqlalchemy.engine.Engine.connect"), as well as when a [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object encounters an error during a reconnect operation.
  44. Changed in version 1.0.0: The [`handle_error()`](#sqlalchemy.events.ConnectionEvents.handle_error "sqlalchemy.events.ConnectionEvents.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()`](#sqlalchemy.events.ConnectionEvents.handle_error "sqlalchemy.events.ConnectionEvents.handle_error") needs to ensure that exceptions thrown in these scenarios are re-raised without modification.
  1. @event.listens_for(SomeEngine, 'prepare_twophase')
  2. def receive_prepare_twophase(conn, xid):
  3. "listen for the 'prepare_twophase' event"
  4. # ... (event handling logic) ...
  5. ```
  6. - Parameters
  7. - **conn** – [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
  8. - **xid** – two-phase XID identifier
  • method sqlalchemy.events.ConnectionEvents.release_savepoint(conn, name, context)

    Intercept release_savepoint() events.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeEngine, 'release_savepoint')
  2. def receive_release_savepoint(conn, name, context):
  3. "listen for the 'release_savepoint' event"
  4. # ... (event handling logic) ...
  5. ```
  6. - Parameters
  7. - **conn** – [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
  8. - **name** – specified name used for the savepoint.
  9. - **context** – not used
  1. @event.listens_for(SomeEngine, 'rollback')
  2. def receive_rollback(conn):
  3. "listen for the 'rollback' event"
  4. # ... (event handling logic) ...
  5. ```
  6. Note that the [`Pool`]($dd0c1db3426fd2af.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.
  7. - Parameters
  8. **conn** – [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
  9. See also
  10. [`PoolEvents.reset()`](#sqlalchemy.events.PoolEvents.reset "sqlalchemy.events.PoolEvents.reset")
  • method sqlalchemy.events.ConnectionEvents.rollback_savepoint(conn, name, context)

    Intercept rollback_savepoint() events.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeEngine, 'rollback_savepoint')
  2. def receive_rollback_savepoint(conn, name, context):
  3. "listen for the 'rollback_savepoint' event"
  4. # ... (event handling logic) ...
  5. ```
  6. - Parameters
  7. - **conn** – [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
  8. - **name** – specified name used for the savepoint.
  9. - **context** – not used
  • method sqlalchemy.events.ConnectionEvents.rollback_twophase(conn, xid, is_prepared)

    Intercept rollback_twophase() events.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeEngine, 'rollback_twophase')
  2. def receive_rollback_twophase(conn, xid, is_prepared):
  3. "listen for the 'rollback_twophase' event"
  4. # ... (event handling logic) ...
  5. ```
  6. - Parameters
  7. - **conn** – [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
  8. - **xid** – two-phase XID identifier
  9. - **is\_prepared** – boolean, indicates if [`TwoPhaseTransaction.prepare()`]($cd778e34cf5e4642.md#sqlalchemy.engine.TwoPhaseTransaction.prepare "sqlalchemy.engine.TwoPhaseTransaction.prepare") was called.
  1. @event.listens_for(SomeEngine, 'savepoint')
  2. def receive_savepoint(conn, name):
  3. "listen for the 'savepoint' event"
  4. # ... (event handling logic) ...
  5. ```
  6. - Parameters
  7. - **conn** – [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
  8. - **name** – specified name used for the savepoint.
  1. @event.listens_for(SomeEngine, 'set_connection_execution_options')
  2. def receive_set_connection_execution_options(conn, opts):
  3. "listen for the 'set_connection_execution_options' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This method is called after the new [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") has been produced, with the newly updated execution options collection, but before the [`Dialect`]($52b7b42f4bea86d9.md#sqlalchemy.engine.Dialect "sqlalchemy.engine.Dialect") has acted upon any of those new options.
  7. Note that this method is not called when a new [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") is produced which is inheriting execution options from its parent [`Engine`]($cd778e34cf5e4642.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.
  8. - Parameters
  9. - **conn** – The newly copied [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object
  10. - **opts** – dictionary of options that were passed to the [`Connection.execution_options()`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection.execution_options "sqlalchemy.engine.Connection.execution_options") method.
  11. New in version 0.9.0.
  12. See also
  13. [`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()`]($cd778e34cf5e4642.md#sqlalchemy.engine.Engine.execution_options "sqlalchemy.engine.Engine.execution_options") is called.
  1. @event.listens_for(SomeEngine, 'set_engine_execution_options')
  2. def receive_set_engine_execution_options(engine, opts):
  3. "listen for the 'set_engine_execution_options' event"
  4. # ... (event handling logic) ...
  5. ```
  6. The [`Engine.execution_options()`]($cd778e34cf5e4642.md#sqlalchemy.engine.Engine.execution_options "sqlalchemy.engine.Engine.execution_options") method produces a shallow copy of the [`Engine`]($cd778e34cf5e4642.md#sqlalchemy.engine.Engine "sqlalchemy.engine.Engine") which stores the new options. That new [`Engine`]($cd778e34cf5e4642.md#sqlalchemy.engine.Engine "sqlalchemy.engine.Engine") is passed here. A particular application of this method is to add a [`ConnectionEvents.engine_connect()`](#sqlalchemy.events.ConnectionEvents.engine_connect "sqlalchemy.events.ConnectionEvents.engine_connect") event handler to the given [`Engine`]($cd778e34cf5e4642.md#sqlalchemy.engine.Engine "sqlalchemy.engine.Engine") which will perform some per- [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") task specific to these execution options.
  7. - Parameters
  8. - **conn** – The newly copied [`Engine`]($cd778e34cf5e4642.md#sqlalchemy.engine.Engine "sqlalchemy.engine.Engine") object
  9. - **opts** – dictionary of options that were passed to the [`Connection.execution_options()`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection.execution_options "sqlalchemy.engine.Connection.execution_options") method.
  10. New in version 0.9.0.
  11. See also
  12. [`ConnectionEvents.set_connection_execution_options()`](#sqlalchemy.events.ConnectionEvents.set_connection_execution_options "sqlalchemy.events.ConnectionEvents.set_connection_execution_options") - event which is called when [`Connection.execution_options()`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection.execution_options "sqlalchemy.engine.Connection.execution_options") is called.

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 ConnectionEvents interface.

See also

ConnectionEvents.before_cursor_execute()

ConnectionEvents.before_execute()

ConnectionEvents.after_cursor_execute()

ConnectionEvents.after_execute()

New in version 0.9.4.

Class signature

class sqlalchemy.events.DialectEvents (sqlalchemy.event.Events)

  • method sqlalchemy.events.DialectEvents.do_connect(dialect, conn_rec, cargs, cparams)

    Receive connection arguments before a connection is made.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeEngine, 'do_connect')
  2. def receive_do_connect(dialect, conn_rec, cargs, cparams):
  3. "listen for the 'do_connect' event"
  4. # ... (event handling logic) ...
  5. ```
  6. Return a DBAPI connection to halt further events from invoking; the returned connection will be used.
  7. Alternatively, the event can manipulate the cargs and/or cparams collections; cargs will always be a Python list that can be mutated in-place and cparams a Python dictionary. Return None to allow control to pass to the next event handler and ultimately to allow the dialect to connect normally, given the updated arguments.
  8. New in version 1.0.3.
  9. See also
  10. [Custom DBAPI connect() arguments / on-connect routines]($1741d37c5d31b92e.md#custom-dbapi-args)
  • method sqlalchemy.events.DialectEvents.do_execute(cursor, statement, parameters, context)

    Receive a cursor to have execute() called.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeEngine, 'do_execute')
  2. def receive_do_execute(cursor, statement, parameters, context):
  3. "listen for the 'do_execute' event"
  4. # ... (event handling logic) ...
  5. ```
  6. 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_execute_no_params(cursor, statement, context)

    Receive a cursor to have execute() with no parameters called.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeEngine, 'do_execute_no_params')
  2. def receive_do_execute_no_params(cursor, statement, context):
  3. "listen for the 'do_execute_no_params' event"
  4. # ... (event handling logic) ...
  5. ```
  6. 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, parameters, context)

    Receive a cursor to have executemany() called.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeEngine, 'do_executemany')
  2. def receive_do_executemany(cursor, statement, parameters, context):
  3. "listen for the 'do_executemany' event"
  4. # ... (event handling logic) ...
  5. ```
  6. 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_setinputsizes(inputsizes, cursor, statement, parameters, context)

    Receive the setinputsizes dictionary for possible modification.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeEngine, 'do_setinputsizes')
  2. def receive_do_setinputsizes(inputsizes, cursor, statement, parameters, context):
  3. "listen for the 'do_setinputsizes' event"
  4. # ... (event handling logic) ...
  5. ```
  6. 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`]($f62ce11674ae62ed.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.
  7. 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.
  8. 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.
  9. Note
  10. For use with pyodbc, the `use_setinputsizes` flag must be passed to the dialect, e.g.:
  11. ```
  12. create_engine("mssql+pyodbc://...", use_setinputsizes=True)
  13. ```
  14. See also
  15. [Setinputsizes Support]($ed2b8a36ca490cdf.md#mssql-pyodbc-setinputsizes)
  16. New in version 1.2.9.
  17. See also
  18. [Fine grained control over cx\_Oracle data binding performance with setinputsizes]($79f150df0b55c5a0.md#cx-oracle-setinputsizes)

Schema Events

Object NameDescription

DDLEvents

Define event listeners for schema objects, that is, SchemaItem and other SchemaEventTarget subclasses, including MetaData, Table, Column.

SchemaEventTarget

Base class for elements that are the targets of DDLEvents events.

class sqlalchemy.events.``DDLEvents

Define event listeners for schema objects, that is, SchemaItem and other SchemaEventTarget subclasses, including MetaData, Table, Column.

MetaData and Table support events specifically regarding when CREATE and DROP DDL is emitted to the database.

Attachment events are also provided to customize behavior whenever a child schema element is associated with a parent, such as, when a Column is associated with its Table, when a ForeignKeyConstraint is associated with a Table, etc.

Example using the after_create event:

  1. from sqlalchemy import event
  2. from sqlalchemy import Table, Column, Metadata, Integer
  3. m = MetaData()
  4. some_table = Table('some_table', m, Column('data', Integer))
  5. def after_create(target, connection, **kw):
  6. connection.execute(text(
  7. "ALTER TABLE %s SET name=foo_%s" % (target.name, target.name)
  8. ))
  9. event.listen(some_table, "after_create", after_create)

DDL events integrate closely with the DDL class and the DDLElement hierarchy of DDL clause constructs, which are themselves appropriate as listener callables:

  1. from sqlalchemy import DDL
  2. event.listen(
  3. some_table,
  4. "after_create",
  5. DDL("ALTER TABLE %(table)s SET name=foo_%(table)s")
  6. )

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

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 Table.to_metadata() method:

  1. from sqlalchemy import DDL
  2. event.listen(
  3. some_table,
  4. "after_create",
  5. DDL("ALTER TABLE %(table)s SET name=foo_%(table)s"),
  6. propagate=True
  7. )
  8. new_table = some_table.to_metadata(new_metadata)

The above DDL object will also be associated with the Table object represented by new_table.

See also

Events

DDLElement

DDL

Controlling DDL Sequences

Class signature

class sqlalchemy.events.DDLEvents (sqlalchemy.event.Events)

  • method sqlalchemy.events.DDLEvents.after_create(target, connection, \*kw*)

    Called after CREATE statements are emitted.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSchemaClassOrObject, 'after_create')
  2. def receive_after_create(target, connection, **kw):
  3. "listen for the 'after_create' event"
  4. # ... (event handling logic) ...
  5. ```
  6. - Parameters
  7. - **target** – the [`MetaData`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.MetaData "sqlalchemy.schema.MetaData") or [`Table`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Table "sqlalchemy.schema.Table") object which is the target of the event.
  8. - **connection** – the [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") where the CREATE statement or statements have been emitted.
  9. - **\*\*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.
  10. [`listen()`]($c14d75f7aa5f8339.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()`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Table.to_metadata "sqlalchemy.schema.Table.to_metadata") is used.
  • method sqlalchemy.events.DDLEvents.after_drop(target, connection, \*kw*)

    Called after DROP statements are emitted.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSchemaClassOrObject, 'after_drop')
  2. def receive_after_drop(target, connection, **kw):
  3. "listen for the 'after_drop' event"
  4. # ... (event handling logic) ...
  5. ```
  6. - Parameters
  7. - **target** – the [`MetaData`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.MetaData "sqlalchemy.schema.MetaData") or [`Table`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Table "sqlalchemy.schema.Table") object which is the target of the event.
  8. - **connection** – the [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") where the DROP statement or statements have been emitted.
  9. - **\*\*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.
  10. [`listen()`]($c14d75f7aa5f8339.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()`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Table.to_metadata "sqlalchemy.schema.Table.to_metadata") is used.
  1. @event.listens_for(SomeSchemaClassOrObject, 'after_parent_attach')
  2. def receive_after_parent_attach(target, parent):
  3. "listen for the 'after_parent_attach' event"
  4. # ... (event handling logic) ...
  5. ```
  6. - Parameters
  7. - **target** – the target object
  8. - **parent** – the parent to which the target is being attached.
  9. [`listen()`]($c14d75f7aa5f8339.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()`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Table.to_metadata "sqlalchemy.schema.Table.to_metadata") is used.
  • method sqlalchemy.events.DDLEvents.before_create(target, connection, \*kw*)

    Called before CREATE statements are emitted.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSchemaClassOrObject, 'before_create')
  2. def receive_before_create(target, connection, **kw):
  3. "listen for the 'before_create' event"
  4. # ... (event handling logic) ...
  5. ```
  6. - Parameters
  7. - **target** – the [`MetaData`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.MetaData "sqlalchemy.schema.MetaData") or [`Table`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Table "sqlalchemy.schema.Table") object which is the target of the event.
  8. - **connection** – the [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") where the CREATE statement or statements will be emitted.
  9. - **\*\*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.
  10. [`listen()`]($c14d75f7aa5f8339.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()`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Table.to_metadata "sqlalchemy.schema.Table.to_metadata") is used.
  • method sqlalchemy.events.DDLEvents.before_drop(target, connection, \*kw*)

    Called before DROP statements are emitted.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSchemaClassOrObject, 'before_drop')
  2. def receive_before_drop(target, connection, **kw):
  3. "listen for the 'before_drop' event"
  4. # ... (event handling logic) ...
  5. ```
  6. - Parameters
  7. - **target** – the [`MetaData`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.MetaData "sqlalchemy.schema.MetaData") or [`Table`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Table "sqlalchemy.schema.Table") object which is the target of the event.
  8. - **connection** – the [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") where the DROP statement or statements will be emitted.
  9. - **\*\*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.
  10. [`listen()`]($c14d75f7aa5f8339.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()`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Table.to_metadata "sqlalchemy.schema.Table.to_metadata") is used.
  1. @event.listens_for(SomeSchemaClassOrObject, 'before_parent_attach')
  2. def receive_before_parent_attach(target, parent):
  3. "listen for the 'before_parent_attach' event"
  4. # ... (event handling logic) ...
  5. ```
  6. - Parameters
  7. - **target** – the target object
  8. - **parent** – the parent to which the target is being attached.
  9. [`listen()`]($c14d75f7aa5f8339.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()`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Table.to_metadata "sqlalchemy.schema.Table.to_metadata") is used.
  • method sqlalchemy.events.DDLEvents.column_reflect(inspector, table, column_info)

    Called for each unit of ‘column info’ retrieved when a Table is being reflected.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSchemaClassOrObject, 'column_reflect')
  2. def receive_column_reflect(inspector, table, column_info):
  3. "listen for the 'column_reflect' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is most easily used by applying it to a specific [`MetaData`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.MetaData "sqlalchemy.schema.MetaData") instance, where it will take effect for all [`Table`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Table "sqlalchemy.schema.Table") objects within that [`MetaData`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.MetaData "sqlalchemy.schema.MetaData") that undergo reflection:
  7. ```
  8. metadata = MetaData()
  9. @event.listens_for(metadata, 'column_reflect')
  10. def receive_column_reflect(inspector, table, column_info):
  11. # receives for all Table objects that are reflected
  12. # under this MetaData
  13. # will use the above event hook
  14. my_table = Table("my_table", metadata, autoload_with=some_engine)
  15. ```
  16. New in version 1.4.0b2: The [`DDLEvents.column_reflect()`](#sqlalchemy.events.DDLEvents.column_reflect "sqlalchemy.events.DDLEvents.column_reflect") hook may now be applied to a [`MetaData`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.MetaData "sqlalchemy.schema.MetaData") object as well as the [`MetaData`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.MetaData "sqlalchemy.schema.MetaData") class itself where it will take place for all [`Table`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Table "sqlalchemy.schema.Table") objects associated with the targeted [`MetaData`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.MetaData "sqlalchemy.schema.MetaData").
  17. It may also be applied to the [`Table`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Table "sqlalchemy.schema.Table") class across the board:
  18. ```
  19. from sqlalchemy import Table
  20. @event.listens_for(Table, 'column_reflect')
  21. def receive_column_reflect(inspector, table, column_info):
  22. # receives for all Table objects that are reflected
  23. ```
  24. It can also be applied to a specific [`Table`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Table "sqlalchemy.schema.Table") at the point that one is being reflected using the [`Table.listeners`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Table.params.listeners "sqlalchemy.schema.Table") parameter:
  25. ```
  26. t1 = Table(
  27. "my_table",
  28. autoload_with=some_engine,
  29. listeners=[
  30. ('column_reflect', receive_column_reflect)
  31. ]
  32. )
  33. ```
  34. A future release will allow it to be associated with a specific [`MetaData`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.MetaData "sqlalchemy.schema.MetaData") object as well.
  35. The dictionary of column information as returned by the dialect is passed, and can be modified. The dictionary is that returned in each element of the list returned by [`Inspector.get_columns()`]($cd9b74024ff70de7.md#sqlalchemy.engine.reflection.Inspector.get_columns "sqlalchemy.engine.reflection.Inspector.get_columns"):
  36. > - `name` - the column’s name, is applied to the [`Column.name`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Column.params.name "sqlalchemy.schema.Column") parameter
  37. >
  38. > - `type` - the type of this column, which should be an instance of [`TypeEngine`]($0625e71dff02631f.md#sqlalchemy.types.TypeEngine "sqlalchemy.types.TypeEngine"), is applied to the [`Column.type`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Column.params.type "sqlalchemy.schema.Column") parameter
  39. >
  40. > - `nullable` - boolean flag if the column is NULL or NOT NULL, is applied to the [`Column.nullable`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Column.params.nullable "sqlalchemy.schema.Column") parameter
  41. >
  42. > - `default` - the column’s server default value. This is normally specified as a plain string SQL expression, however the event can pass a [`FetchedValue`]($42c00eeb4c391fb1.md#sqlalchemy.schema.FetchedValue "sqlalchemy.schema.FetchedValue"), [`DefaultClause`]($42c00eeb4c391fb1.md#sqlalchemy.schema.DefaultClause "sqlalchemy.schema.DefaultClause"), or [`text()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.text "sqlalchemy.sql.expression.text") object as well. Is applied to the [`Column.server_default`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Column.params.server_default "sqlalchemy.schema.Column") parameter
  43. >
  44. The event is called before any action is taken against this dictionary, and the contents can be modified; the following additional keys may be added to the dictionary to further modify how the [`Column`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Column "sqlalchemy.schema.Column") is constructed:
  45. > - `key` - the string key that will be used to access this [`Column`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Column "sqlalchemy.schema.Column") in the `.c` collection; will be applied to the [`Column.key`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Column.params.key "sqlalchemy.schema.Column") parameter. Is also used for ORM mapping. See the section [Automating Column Naming Schemes from Reflected Tables]($89e57867d3c33213.md#mapper-automated-reflection-schemes) for an example.
  46. >
  47. > - `quote` - force or un-force quoting on the column name; is applied to the [`Column.quote`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Column.params.quote "sqlalchemy.schema.Column") parameter.
  48. >
  49. > - `info` - a dictionary of arbitrary data to follow along with the [`Column`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Column "sqlalchemy.schema.Column"), is applied to the [`Column.info`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Column.params.info "sqlalchemy.schema.Column") parameter.
  50. >
  51. [`listen()`]($c14d75f7aa5f8339.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()`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Table.to_metadata "sqlalchemy.schema.Table.to_metadata") is used.
  52. See also
  53. [Automating Column Naming Schemes from Reflected Tables]($89e57867d3c33213.md#mapper-automated-reflection-schemes) - in the ORM mapping documentation
  54. [Intercepting Column Definitions]($83685e84de2bcd75.md#automap-intercepting-columns) - in the [Automap]($83685e84de2bcd75.md) documentation
  55. [Reflecting with Database-Agnostic Types]($cd9b74024ff70de7.md#metadata-reflection-dbagnostic-types) - in the [Reflecting Database Objects]($cd9b74024ff70de7.md) documentation

class sqlalchemy.events.``SchemaEventTarget

Base class for elements that are the targets of DDLEvents events.

This includes SchemaItem as well as SchemaType.