class Connection(ConnectionEventsTarget, inspection.Inspectable[
Provides high-level functionality for a wrapped DB-API connection. The :class:`_engine.Connection` object is procured by calling the :meth:`_engine.Engine.connect` method of the :class:`_engine.Engine` object, and provides services for execution of SQL statements as well as transaction control. The Connection object is **not** thread-safe. While a Connection can be shared among threads using properly synchronized access, it is still possible that the underlying DBAPI connection may not support shared access between threads. Check the DBAPI documentation for details. The Connection object represents a single DBAPI connection checked out from the connection pool. In this state, the connection pool has no affect upon the connection, including its expiration or timeout state. For the connection pool to properly manage connections, connections should be returned to the connection pool (i.e. ``connection.close()``) whenever the connection is not in use. .. index:: single: thread safety; Connection
Method | __enter__ |
Undocumented |
Method | __exit__ |
Undocumented |
Method | __init__ |
Construct a new Connection. |
Method | begin |
Begin a transaction prior to autobegin occurring. |
Method | begin |
Begin a nested transaction (i.e. SAVEPOINT) and return a transaction handle that controls the scope of the SAVEPOINT. |
Method | begin |
Begin a two-phase or XA transaction and return a transaction handle. |
Method | close |
Close this :class:`_engine.Connection`. |
Method | commit |
Commit the transaction that is currently in progress. |
Method | commit |
Undocumented |
Method | detach |
Detach the underlying DB-API connection from its connection pool. |
Method | exec |
Executes a SQL statement construct and returns a :class:`_engine.CursorResult`. |
Method | execute |
Executes a SQL statement construct and returns a :class:`_engine.CursorResult`. |
Method | execution |
Set non-SQL options for the connection which take effect during execution. |
Method | get |
Get the non-SQL options which will take effect during execution. |
Method | get |
Return the current isolation level assigned to this :class:`_engine.Connection`. |
Method | get |
Return the current nested transaction in progress, if any. |
Method | get |
Return the current root transaction in progress, if any. |
Method | in |
Return True if a transaction is in progress. |
Method | in |
Return True if a transaction is in progress. |
Method | invalidate |
Invalidate the underlying DBAPI connection associated with this :class:`_engine.Connection`. |
Method | recover |
Undocumented |
Method | rollback |
Roll back the transaction that is currently in progress. |
Method | rollback |
Undocumented |
Method | scalar |
Executes a SQL statement construct and returns a scalar object. |
Method | scalars |
Executes and returns a scalar result set, which yields scalar values from the first column of each row. |
Method | schema |
Return the schema name for the given schema item taking into account current schema translate map. |
Class Variable | should |
Undocumented |
Instance Variable | dialect |
Undocumented |
Instance Variable | dispatch |
Undocumented |
Instance Variable | engine |
Undocumented |
Property | closed |
Return True if this connection is closed. |
Property | connection |
The underlying DB-API connection managed by this Connection. |
Property | default |
The default isolation level assigned to this :class:`_engine.Connection`. |
Property | info |
Info dictionary associated with the underlying DBAPI connection referred to by this :class:`_engine.Connection`, allowing user-defined data to be associated with the connection. |
Property | invalidated |
Return True if this connection was invalidated. |
Class Method | _handle |
Undocumented |
Method | _autobegin |
Undocumented |
Method | _begin |
Undocumented |
Method | _begin |
Undocumented |
Method | _commit |
Undocumented |
Method | _commit |
Undocumented |
Method | _cursor |
Execute a statement + params on the given cursor. |
Method | _exec |
continue the _execute_context() method for an "insertmanyvalues" operation, which will invoke DBAPI cursor.execute() one or more times with individual log and event hook calls. |
Method | _exec |
continue the _execute_context() method for a single DBAPI cursor.execute() or cursor.executemany() call. |
Method | _execute |
Execute a sql.ClauseElement object. |
Method | _execute |
Execute a sql.Compiled object. |
Method | _execute |
Create an :class:`.ExecutionContext` and execute, returning a :class:`_engine.CursorResult`. |
Method | _execute |
Execute a schema.DDL object. |
Method | _execute |
Execute a schema.ColumnDefault object. |
Method | _execute |
Execute a sql.FunctionElement object. |
Method | _get |
Undocumented |
Method | _get |
Undocumented |
Method | _handle |
Undocumented |
Method | _invalid |
Undocumented |
Method | _invoke |
Undocumented |
Method | _is |
Undocumented |
Method | _log |
Undocumented |
Method | _log |
Undocumented |
Method | _prepare |
Undocumented |
Method | _release |
Undocumented |
Method | _revalidate |
Undocumented |
Method | _rollback |
Undocumented |
Method | _rollback |
Undocumented |
Method | _rollback |
Undocumented |
Method | _run |
run a DDL visitor. |
Method | _safe |
Close the given cursor, catching exceptions and turning into log warnings. |
Method | _savepoint |
Undocumented |
Class Variable | _sqla |
Undocumented |
Class Variable | _trans |
Undocumented |
Instance Variable | __can |
Undocumented |
Instance Variable | __in |
Undocumented |
Instance Variable | __savepoint |
Undocumented |
Instance Variable | _allow |
Undocumented |
Instance Variable | _dbapi |
Undocumented |
Instance Variable | _echo |
Undocumented |
Instance Variable | _execution |
Undocumented |
Instance Variable | _has |
Undocumented |
Instance Variable | _is |
Undocumented |
Instance Variable | _nested |
Undocumented |
Instance Variable | _reentrant |
Undocumented |
Instance Variable | _transaction |
Undocumented |
Property | _message |
Undocumented |
Property | _schema |
Undocumented |
Property | _still |
Undocumented |
Inherited from Inspectable
(via ConnectionEventsTarget
):
Class Variable | __slots__ |
Undocumented |
Engine
, connection: Optional[ PoolProxiedConnection]
= None, _has_events: Optional[ bool]
= None, _allow_revalidate: bool
= True, _allow_autobegin: bool
= True):
(source)
¶
Construct a new Connection.
Begin a transaction prior to autobegin occurring. E.g.:: with engine.connect() as conn: with conn.begin() as trans: conn.execute(table.insert(), {"username": "sandy"}) The returned object is an instance of :class:`_engine.RootTransaction`. This object represents the "scope" of the transaction, which completes when either the :meth:`_engine.Transaction.rollback` or :meth:`_engine.Transaction.commit` method is called; the object also works as a context manager as illustrated above. The :meth:`_engine.Connection.begin` method begins a transaction that normally will be begun in any case when the connection is first used to execute a statement. The reason this method might be used would be to invoke the :meth:`_events.ConnectionEvents.begin` event at a specific time, or to organize code within the scope of a connection checkout in terms of context managed blocks, such as:: with engine.connect() as conn: with conn.begin(): conn.execute(...) conn.execute(...) with conn.begin(): conn.execute(...) conn.execute(...) The above code is not fundamentally any different in its behavior than the following code which does not use :meth:`_engine.Connection.begin`; the below style is referred towards as "commit as you go" style:: with engine.connect() as conn: conn.execute(...) conn.execute(...) conn.commit() conn.execute(...) conn.execute(...) conn.commit() From a database point of view, the :meth:`_engine.Connection.begin` method does not emit any SQL or change the state of the underlying DBAPI connection in any way; the Python DBAPI does not have any concept of explicit transaction begin. .. seealso:: :ref:`tutorial_working_with_transactions` - in the :ref:`unified_tutorial` :meth:`_engine.Connection.begin_nested` - use a SAVEPOINT :meth:`_engine.Connection.begin_twophase` - use a two phase /XID transaction :meth:`_engine.Engine.begin` - context manager available from :class:`_engine.Engine`
Begin a nested transaction (i.e. SAVEPOINT) and return a transaction handle that controls the scope of the SAVEPOINT. E.g.:: with engine.begin() as connection: with connection.begin_nested(): connection.execute(table.insert(), {"username": "sandy"}) The returned object is an instance of :class:`_engine.NestedTransaction`, which includes transactional methods :meth:`_engine.NestedTransaction.commit` and :meth:`_engine.NestedTransaction.rollback`; for a nested transaction, these methods correspond to the operations "RELEASE SAVEPOINT <name>" and "ROLLBACK TO SAVEPOINT <name>". The name of the savepoint is local to the :class:`_engine.NestedTransaction` object and is generated automatically. Like any other :class:`_engine.Transaction`, the :class:`_engine.NestedTransaction` may be used as a context manager as illustrated above which will "release" or "rollback" corresponding to if the operation within the block were successful or raised an exception. Nested transactions require SAVEPOINT support in the underlying database, else the behavior is undefined. SAVEPOINT is commonly used to run operations within a transaction that may fail, while continuing the outer transaction. E.g.:: from sqlalchemy import exc with engine.begin() as connection: trans = connection.begin_nested() try: connection.execute(table.insert(), {"username": "sandy"}) trans.commit() except exc.IntegrityError: # catch for duplicate username trans.rollback() # rollback to savepoint # outer transaction continues connection.execute( ... ) If :meth:`_engine.Connection.begin_nested` is called without first calling :meth:`_engine.Connection.begin` or :meth:`_engine.Engine.begin`, the :class:`_engine.Connection` object will "autobegin" the outer transaction first. This outer transaction may be committed using "commit-as-you-go" style, e.g.:: with engine.connect() as connection: # begin() wasn't called with connection.begin_nested(): will auto-"begin()" first connection.execute( ... ) # savepoint is released connection.execute( ... ) # explicitly commit outer transaction connection.commit() # can continue working with connection here .. versionchanged:: 2.0 :meth:`_engine.Connection.begin_nested` will now participate in the connection "autobegin" behavior that is new as of 2.0 / "future" style connections in 1.4. .. seealso:: :meth:`_engine.Connection.begin` :ref:`session_begin_nested` - ORM support for SAVEPOINT
Begin a two-phase or XA transaction and return a transaction handle. The returned object is an instance of :class:`.TwoPhaseTransaction`, which in addition to the methods provided by :class:`.Transaction`, also provides a :meth:`~.TwoPhaseTransaction.prepare` method. :param xid: the two phase transaction id. If not supplied, a random id will be generated. .. seealso:: :meth:`_engine.Connection.begin` :meth:`_engine.Connection.begin_twophase`
Close this :class:`_engine.Connection`. This results in a release of the underlying database resources, that is, the DBAPI connection referenced internally. The DBAPI connection is typically restored back to the connection-holding :class:`_pool.Pool` referenced by the :class:`_engine.Engine` that produced this :class:`_engine.Connection`. Any transactional state present on the DBAPI connection is also unconditionally released via the DBAPI connection's ``rollback()`` method, regardless of any :class:`.Transaction` object that may be outstanding with regards to this :class:`_engine.Connection`. This has the effect of also calling :meth:`_engine.Connection.rollback` if any transaction is in place. After :meth:`_engine.Connection.close` is called, the :class:`_engine.Connection` is permanently in a closed state, and will allow no further operations.
Commit the transaction that is currently in progress. This method commits the current transaction if one has been started. If no transaction was started, the method has no effect, assuming the connection is in a non-invalidated state. A transaction is begun on a :class:`_engine.Connection` automatically whenever a statement is first executed, or when the :meth:`_engine.Connection.begin` method is called. .. note:: The :meth:`_engine.Connection.commit` method only acts upon the primary database transaction that is linked to the :class:`_engine.Connection` object. It does not operate upon a SAVEPOINT that would have been invoked from the :meth:`_engine.Connection.begin_nested` method; for control of a SAVEPOINT, call :meth:`_engine.NestedTransaction.commit` on the :class:`_engine.NestedTransaction` that is returned by the :meth:`_engine.Connection.begin_nested` method itself.
Detach the underlying DB-API connection from its connection pool. E.g.:: with engine.connect() as conn: conn.detach() conn.execute(text("SET search_path TO schema1, schema2")) # work with connection # connection is fully closed (since we used "with:", can # also call .close()) This :class:`_engine.Connection` instance will remain usable. When closed (or exited from a context manager context as above), the DB-API connection will be literally closed and not returned to its originating pool. This method can be used to insulate the rest of an application from a modified state on a connection (such as a transaction isolation level or similar).
str
, parameters: Optional[ _DBAPIAnyExecuteParams]
= None, execution_options: Optional[ CoreExecuteOptionsParameter]
= None) -> CursorResult[ Any]
:
(source)
¶
Executes a SQL statement construct and returns a :class:`_engine.CursorResult`. :param statement: The statement str to be executed. Bound parameters must use the underlying DBAPI's paramstyle, such as "qmark", "pyformat", "format", etc. :param parameters: represent bound parameter values to be used in the execution. The format is one of: a dictionary of named parameters, a tuple of positional parameters, or a list containing either dictionaries or tuples for multiple-execute support. E.g. multiple dictionaries:: conn.exec_driver_sql( "INSERT INTO table (id, value) VALUES (%(id)s, %(value)s)", [{"id":1, "value":"v1"}, {"id":2, "value":"v2"}] ) Single dictionary:: conn.exec_driver_sql( "INSERT INTO table (id, value) VALUES (%(id)s, %(value)s)", dict(id=1, value="v1") ) Single tuple:: conn.exec_driver_sql( "INSERT INTO table (id, value) VALUES (?, ?)", (1, 'v1') ) .. note:: The :meth:`_engine.Connection.exec_driver_sql` method does not participate in the :meth:`_events.ConnectionEvents.before_execute` and :meth:`_events.ConnectionEvents.after_execute` events. To intercept calls to :meth:`_engine.Connection.exec_driver_sql`, use :meth:`_events.ConnectionEvents.before_cursor_execute` and :meth:`_events.ConnectionEvents.after_cursor_execute`. .. seealso:: :pep:`249`
TypedReturnsRows[ _T]
, parameters: Optional[ _CoreAnyExecuteParams]
= None, *, execution_options: Optional[ CoreExecuteOptionsParameter]
= None) -> CursorResult[ _T]
:Executable
, parameters: Optional[ _CoreAnyExecuteParams]
= None, *, execution_options: Optional[ CoreExecuteOptionsParameter]
= None) -> CursorResult[ Any]
:Executes a SQL statement construct and returns a :class:`_engine.CursorResult`. :param statement: The statement to be executed. This is always an object that is in both the :class:`_expression.ClauseElement` and :class:`_expression.Executable` hierarchies, including: * :class:`_expression.Select` * :class:`_expression.Insert`, :class:`_expression.Update`, :class:`_expression.Delete` * :class:`_expression.TextClause` and :class:`_expression.TextualSelect` * :class:`_schema.DDL` and objects which inherit from :class:`_schema.ExecutableDDLElement` :param parameters: parameters which will be bound into the statement. This may be either a dictionary of parameter names to values, or a mutable sequence (e.g. a list) of dictionaries. When a list of dictionaries is passed, the underlying statement execution will make use of the DBAPI ``cursor.executemany()`` method. When a single dictionary is passed, the DBAPI ``cursor.execute()`` method will be used. :param execution_options: optional dictionary of execution options, which will be associated with the statement execution. This dictionary can provide a subset of the options that are accepted by :meth:`_engine.Connection.execution_options`. :return: a :class:`_engine.Result` object.
Optional[ CompiledCacheType]
= ..., logging_token: str
= ..., isolation_level: IsolationLevel
= ..., no_parameters: bool
= False, stream_results: bool
= False, max_row_buffer: int
= ..., yield_per: int
= ..., insertmanyvalues_page_size: int
= ..., schema_translate_map: Optional[ SchemaTranslateMapType]
= ..., **opt: Any
) -> Connection
:(source) ¶
Set non-SQL options for the connection which take effect during execution. This method modifies this :class:`_engine.Connection` **in-place**; the return value is the same :class:`_engine.Connection` object upon which the method is called. Note that this is in contrast to the behavior of the ``execution_options`` methods on other objects such as :meth:`_engine.Engine.execution_options` and :meth:`_sql.Executable.execution_options`. The rationale is that many such execution options necessarily modify the state of the base DBAPI connection in any case so there is no feasible means of keeping the effect of such an option localized to a "sub" connection. .. versionchanged:: 2.0 The :meth:`_engine.Connection.execution_options` method, in contrast to other objects with this method, modifies the connection in-place without creating copy of it. As discussed elsewhere, the :meth:`_engine.Connection.execution_options` method accepts any arbitrary parameters including user defined names. All parameters given are consumable in a number of ways including by using the :meth:`_engine.Connection.get_execution_options` method. See the examples at :meth:`_sql.Executable.execution_options` and :meth:`_engine.Engine.execution_options`. The keywords that are currently recognized by SQLAlchemy itself include all those listed under :meth:`.Executable.execution_options`, as well as others that are specific to :class:`_engine.Connection`. :param compiled_cache: Available on: :class:`_engine.Connection`, :class:`_engine.Engine`. A dictionary where :class:`.Compiled` objects will be cached when the :class:`_engine.Connection` compiles a clause expression into a :class:`.Compiled` object. This dictionary will supersede the statement cache that may be configured on the :class:`_engine.Engine` itself. If set to None, caching is disabled, even if the engine has a configured cache size. Note that the ORM makes use of its own "compiled" caches for some operations, including flush operations. The caching used by the ORM internally supersedes a cache dictionary specified here. :param logging_token: Available on: :class:`_engine.Connection`, :class:`_engine.Engine`, :class:`_sql.Executable`. Adds the specified string token surrounded by brackets in log messages logged by the connection, i.e. the logging that's enabled either via the :paramref:`_sa.create_engine.echo` flag or via the ``logging.getLogger("sqlalchemy.engine")`` logger. This allows a per-connection or per-sub-engine token to be available which is useful for debugging concurrent connection scenarios. .. versionadded:: 1.4.0b2 .. seealso:: :ref:`dbengine_logging_tokens` - usage example :paramref:`_sa.create_engine.logging_name` - adds a name to the name used by the Python logger object itself. :param isolation_level: Available on: :class:`_engine.Connection`, :class:`_engine.Engine`. Set the transaction isolation level for the lifespan of this :class:`_engine.Connection` object. Valid values include those string values accepted by the :paramref:`_sa.create_engine.isolation_level` parameter passed to :func:`_sa.create_engine`. These levels are semi-database specific; see individual dialect documentation for valid levels. The isolation level option applies the isolation level by emitting statements on the DBAPI connection, and **necessarily affects the original Connection object overall**. The isolation level will remain at the given setting until explicitly changed, or when the DBAPI connection itself is :term:`released` to the connection pool, i.e. the :meth:`_engine.Connection.close` method is called, at which time an event handler will emit additional statements on the DBAPI connection in order to revert the isolation level change. .. note:: The ``isolation_level`` execution option may only be established before the :meth:`_engine.Connection.begin` method is called, as well as before any SQL statements are emitted which would otherwise trigger "autobegin", or directly after a call to :meth:`_engine.Connection.commit` or :meth:`_engine.Connection.rollback`. A database cannot change the isolation level on a transaction in progress. .. note:: The ``isolation_level`` execution option is implicitly reset if the :class:`_engine.Connection` is invalidated, e.g. via the :meth:`_engine.Connection.invalidate` method, or if a disconnection error occurs. The new connection produced after the invalidation will **not** have the selected isolation level re-applied to it automatically. .. seealso:: :ref:`dbapi_autocommit` :meth:`_engine.Connection.get_isolation_level` - view current level :param no_parameters: Available on: :class:`_engine.Connection`, :class:`_sql.Executable`. When ``True``, if the final parameter list or dictionary is totally empty, will invoke the statement on the cursor as ``cursor.execute(statement)``, not passing the parameter collection at all. Some DBAPIs such as psycopg2 and mysql-python consider percent signs as significant only when parameters are present; this option allows code to generate SQL containing percent signs (and possibly other characters) that is neutral regarding whether it's executed by the DBAPI or piped into a script that's later invoked by command line tools. :param stream_results: Available on: :class:`_engine.Connection`, :class:`_sql.Executable`. Indicate to the dialect that results should be "streamed" and not pre-buffered, if possible. For backends such as PostgreSQL, MySQL and MariaDB, this indicates the use of a "server side cursor" as opposed to a client side cursor. Other backends such as that of Oracle may already use server side cursors by default. The usage of :paramref:`_engine.Connection.execution_options.stream_results` is usually combined with setting a fixed number of rows to to be fetched in batches, to allow for efficient iteration of database rows while at the same time not loading all result rows into memory at once; this can be configured on a :class:`_engine.Result` object using the :meth:`_engine.Result.yield_per` method, after execution has returned a new :class:`_engine.Result`. If :meth:`_engine.Result.yield_per` is not used, the :paramref:`_engine.Connection.execution_options.stream_results` mode of operation will instead use a dynamically sized buffer which buffers sets of rows at a time, growing on each batch based on a fixed growth size up until a limit which may be configured using the :paramref:`_engine.Connection.execution_options.max_row_buffer` parameter. When using the ORM to fetch ORM mapped objects from a result, :meth:`_engine.Result.yield_per` should always be used with :paramref:`_engine.Connection.execution_options.stream_results`, so that the ORM does not fetch all rows into new ORM objects at once. For typical use, the :paramref:`_engine.Connection.execution_options.yield_per` execution option should be preferred, which sets up both :paramref:`_engine.Connection.execution_options.stream_results` and :meth:`_engine.Result.yield_per` at once. This option is supported both at a core level by :class:`_engine.Connection` as well as by the ORM :class:`_engine.Session`; the latter is described at :ref:`orm_queryguide_yield_per`. .. seealso:: :ref:`engine_stream_results` - background on :paramref:`_engine.Connection.execution_options.stream_results` :paramref:`_engine.Connection.execution_options.max_row_buffer` :paramref:`_engine.Connection.execution_options.yield_per` :ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel` describing the ORM version of ``yield_per`` :param max_row_buffer: Available on: :class:`_engine.Connection`, :class:`_sql.Executable`. Sets a maximum buffer size to use when the :paramref:`_engine.Connection.execution_options.stream_results` execution option is used on a backend that supports server side cursors. The default value if not specified is 1000. .. seealso:: :paramref:`_engine.Connection.execution_options.stream_results` :ref:`engine_stream_results` :param yield_per: Available on: :class:`_engine.Connection`, :class:`_sql.Executable`. Integer value applied which will set the :paramref:`_engine.Connection.execution_options.stream_results` execution option and invoke :meth:`_engine.Result.yield_per` automatically at once. Allows equivalent functionality as is present when using this parameter with the ORM. .. versionadded:: 1.4.40 .. seealso:: :ref:`engine_stream_results` - background and examples on using server side cursors with Core. :ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel` describing the ORM version of ``yield_per`` :param insertmanyvalues_page_size: Available on: :class:`_engine.Connection`, :class:`_engine.Engine`. Number of rows to format into an INSERT statement when the statement uses "insertmanyvalues" mode, which is a paged form of bulk insert that is used for many backends when using :term:`executemany` execution typically in conjunction with RETURNING. Defaults to 1000. May also be modified on a per-engine basis using the :paramref:`_sa.create_engine.insertmanyvalues_page_size` parameter. .. versionadded:: 2.0 .. seealso:: :ref:`engine_insertmanyvalues` :param schema_translate_map: Available on: :class:`_engine.Connection`, :class:`_engine.Engine`, :class:`_sql.Executable`. A dictionary mapping schema names to schema names, that will be applied to the :paramref:`_schema.Table.schema` element of each :class:`_schema.Table` encountered when SQL or DDL expression elements are compiled into strings; the resulting schema name will be converted based on presence in the map of the original name. .. versionadded:: 1.1 .. seealso:: :ref:`schema_translating` .. seealso:: :meth:`_engine.Engine.execution_options` :meth:`.Executable.execution_options` :meth:`_engine.Connection.get_execution_options` :ref:`orm_queryguide_execution_options` - documentation on all ORM-specific execution options
Get the non-SQL options which will take effect during execution. .. versionadded:: 1.3 .. seealso:: :meth:`_engine.Connection.execution_options`
Return the current isolation level assigned to this :class:`_engine.Connection`. This will typically be the default isolation level as determined by the dialect, unless if the :paramref:`.Connection.execution_options.isolation_level` feature has been used to alter the isolation level on a per-:class:`_engine.Connection` basis. This attribute will typically perform a live SQL operation in order to procure the current isolation level, so the value returned is the actual level on the underlying DBAPI connection regardless of how this state was set. Compare to the :attr:`_engine.Connection.default_isolation_level` accessor which returns the dialect-level setting without performing a SQL query. .. versionadded:: 0.9.9 .. seealso:: :attr:`_engine.Connection.default_isolation_level` - view default level :paramref:`_sa.create_engine.isolation_level` - set per :class:`_engine.Engine` isolation level :paramref:`.Connection.execution_options.isolation_level` - set per :class:`_engine.Connection` isolation level
Invalidate the underlying DBAPI connection associated with this :class:`_engine.Connection`. An attempt will be made to close the underlying DBAPI connection immediately; however if this operation fails, the error is logged but not raised. The connection is then discarded whether or not close() succeeded. Upon the next use (where "use" typically means using the :meth:`_engine.Connection.execute` method or similar), this :class:`_engine.Connection` will attempt to procure a new DBAPI connection using the services of the :class:`_pool.Pool` as a source of connectivity (e.g. a "reconnection"). If a transaction was in progress (e.g. the :meth:`_engine.Connection.begin` method has been called) when :meth:`_engine.Connection.invalidate` method is called, at the DBAPI level all state associated with this transaction is lost, as the DBAPI connection is closed. The :class:`_engine.Connection` will not allow a reconnection to proceed until the :class:`.Transaction` object is ended, by calling the :meth:`.Transaction.rollback` method; until that point, any attempt at continuing to use the :class:`_engine.Connection` will raise an :class:`~sqlalchemy.exc.InvalidRequestError`. This is to prevent applications from accidentally continuing an ongoing transactional operations despite the fact that the transaction has been lost due to an invalidation. The :meth:`_engine.Connection.invalidate` method, just like auto-invalidation, will at the connection pool level invoke the :meth:`_events.PoolEvents.invalidate` event. :param exception: an optional ``Exception`` instance that's the reason for the invalidation. is passed along to event handlers and logging functions. .. seealso:: :ref:`pool_connection_invalidation`
Roll back the transaction that is currently in progress. This method rolls back the current transaction if one has been started. If no transaction was started, the method has no effect. If a transaction was started and the connection is in an invalidated state, the transaction is cleared using this method. A transaction is begun on a :class:`_engine.Connection` automatically whenever a statement is first executed, or when the :meth:`_engine.Connection.begin` method is called. .. note:: The :meth:`_engine.Connection.rollback` method only acts upon the primary database transaction that is linked to the :class:`_engine.Connection` object. It does not operate upon a SAVEPOINT that would have been invoked from the :meth:`_engine.Connection.begin_nested` method; for control of a SAVEPOINT, call :meth:`_engine.NestedTransaction.rollback` on the :class:`_engine.NestedTransaction` that is returned by the :meth:`_engine.Connection.begin_nested` method itself.
TypedReturnsRows[ Tuple[ _T]]
, parameters: Optional[ _CoreSingleExecuteParams]
= None, *, execution_options: Optional[ CoreExecuteOptionsParameter]
= None) -> Optional[ _T]
:Executable
, parameters: Optional[ _CoreSingleExecuteParams]
= None, *, execution_options: Optional[ CoreExecuteOptionsParameter]
= None) -> Any
:Executes a SQL statement construct and returns a scalar object. This method is shorthand for invoking the :meth:`_engine.Result.scalar` method after invoking the :meth:`_engine.Connection.execute` method. Parameters are equivalent. :return: a scalar Python value representing the first column of the first row returned.
TypedReturnsRows[ Tuple[ _T]]
, parameters: Optional[ _CoreAnyExecuteParams]
= None, *, execution_options: Optional[ CoreExecuteOptionsParameter]
= None) -> ScalarResult[ _T]
:Executable
, parameters: Optional[ _CoreAnyExecuteParams]
= None, *, execution_options: Optional[ CoreExecuteOptionsParameter]
= None) -> ScalarResult[ Any]
:Executes and returns a scalar result set, which yields scalar values from the first column of each row. This method is equivalent to calling :meth:`_engine.Connection.execute` to receive a :class:`_result.Result` object, then invoking the :meth:`_result.Result.scalars` method to produce a :class:`_result.ScalarResult` instance. :return: a :class:`_result.ScalarResult` .. versionadded:: 1.4.24
The underlying DB-API connection managed by this Connection. This is a SQLAlchemy connection-pool proxied connection which then has the attribute :attr:`_pool._ConnectionFairy.dbapi_connection` that refers to the actual driver connection. .. seealso:: :ref:`dbapi_connections`
The default isolation level assigned to this :class:`_engine.Connection`. This is the isolation level setting that the :class:`_engine.Connection` has when first procured via the :meth:`_engine.Engine.connect` method. This level stays in place until the :paramref:`.Connection.execution_options.isolation_level` is used to change the setting on a per-:class:`_engine.Connection` basis. Unlike :meth:`_engine.Connection.get_isolation_level`, this attribute is set ahead of time from the first connection procured by the dialect, so SQL query is not invoked when this accessor is called. .. versionadded:: 0.9.9 .. seealso:: :meth:`_engine.Connection.get_isolation_level` - view current level :paramref:`_sa.create_engine.isolation_level` - set per :class:`_engine.Engine` isolation level :paramref:`.Connection.execution_options.isolation_level` - set per :class:`_engine.Connection` isolation level
Info dictionary associated with the underlying DBAPI connection referred to by this :class:`_engine.Connection`, allowing user-defined data to be associated with the connection. The data here will follow along with the DBAPI connection including after it is returned to the connection pool and used again in subsequent instances of :class:`_engine.Connection`.
Return True if this connection was invalidated. This does not indicate whether or not the connection was invalidated at the pool level, however
def _handle_dbapi_exception_noconnection(cls, e:
BaseException
, dialect: Dialect
, engine: Optional[ Engine]
= None, is_disconnect: Optional[ bool]
= None, invalidate_pool_on_disconnect: bool
= True, is_pre_ping: bool
= False) -> NoReturn
:
(source)
¶
Undocumented
DBAPICursor
, statement: str
, parameters: _DBAPISingleExecuteParams
, context: Optional[ ExecutionContext]
= None):
(source)
¶
Execute a statement + params on the given cursor. Adds appropriate logging and exception handling. This method is used by DefaultDialect for special-case executions, such as for sequences and column defaults. The path of statement execution in the majority of cases terminates at _execute_context().
Dialect
, context: ExecutionContext
) -> CursorResult[ Any]
:
(source)
¶
continue the _execute_context() method for an "insertmanyvalues" operation, which will invoke DBAPI cursor.execute() one or more times with individual log and event hook calls.
Dialect
, context: ExecutionContext
, statement: Union[ str, Compiled]
, parameters: Optional[ _AnyMultiExecuteParams]
) -> CursorResult[ Any]
:
(source)
¶
continue the _execute_context() method for a single DBAPI cursor.execute() or cursor.executemany() call.
Executable
, distilled_parameters: _CoreMultiExecuteParams
, execution_options: CoreExecuteOptionsParameter
) -> CursorResult[ Any]
:
(source)
¶
Execute a sql.ClauseElement object.
Compiled
, distilled_parameters: _CoreMultiExecuteParams
, execution_options: CoreExecuteOptionsParameter
= _EMPTY_EXECUTION_OPTS) -> CursorResult[ Any]
:
(source)
¶
Execute a sql.Compiled object. TODO: why do we have this? likely deprecate or remove
Dialect
, constructor: Callable[ ..., ExecutionContext]
, statement: Union[ str, Compiled]
, parameters: Optional[ _AnyMultiExecuteParams]
, execution_options: _ExecuteOptions
, *args: Any
, **kw: Any
) -> CursorResult[ Any]
:
(source)
¶
Create an :class:`.ExecutionContext` and execute, returning a :class:`_engine.CursorResult`.
ExecutableDDLElement
, distilled_parameters: _CoreMultiExecuteParams
, execution_options: CoreExecuteOptionsParameter
) -> CursorResult[ Any]
:
(source)
¶
Execute a schema.DDL object.
DefaultGenerator
, distilled_parameters: _CoreMultiExecuteParams
, execution_options: CoreExecuteOptionsParameter
) -> Any
:
(source)
¶
Execute a schema.ColumnDefault object.
FunctionElement[ Any]
, distilled_parameters: _CoreMultiExecuteParams
, execution_options: CoreExecuteOptionsParameter
) -> CursorResult[ Any]
:
(source)
¶
Execute a sql.FunctionElement object.
BaseException
, statement: Optional[ str]
, parameters: Optional[ _AnyExecuteParams]
, cursor: Optional[ DBAPICursor]
, context: Optional[ ExecutionContext]
, is_sub_exec: bool
= False) -> NoReturn
:
(source)
¶
Undocumented
Any
, distilled_params: _CoreMultiExecuteParams
, execution_options: _ExecuteOptions
) -> Tuple[ Any, _CoreMultiExecuteParams, _CoreMultiExecuteParams, _CoreSingleExecuteParams]
:
(source)
¶
Undocumented
Type[ Union[ SchemaGenerator, SchemaDropper]]
, element: SchemaItem
, **kwargs: Any
):
(source)
¶
run a DDL visitor. This method is only here so that the MockConnection can change the options given to the visitor so that "checkfirst" is skipped.