class Connection(Connectable):
Provides high-level functionality for a wrapped DB-API connection.
This is the SQLAlchemy 1.x.x version of the _engine.Connection
class. For the :term:`2.0 style` version, which features some API
differences, see _future.Connection
.
The _engine.Connection
object is procured by calling
the _engine.Engine.connect
method of the _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.
Class Method | _handle_dbapi_exception_noconnection |
Undocumented |
Method | __enter__ |
Undocumented |
Method | __exit__ |
Undocumented |
Method | __init__ |
Construct a new Connection. |
Method | _autobegin |
Undocumented |
Method | _autorollback |
Undocumented |
Method | _begin_impl |
Undocumented |
Method | _begin_twophase_impl |
Undocumented |
Method | _branch |
Return a new Connection which references this Connection's engine and connection; but does not have close_with_result enabled, and also whose close() method does nothing. |
Method | _commit_impl |
Undocumented |
Method | _commit_twophase_impl |
Undocumented |
Method | _cursor_execute |
Execute a statement + params on the given cursor. |
Method | _exec_driver_sql |
Undocumented |
Method | _execute_20 |
Undocumented |
Method | _execute_clauseelement |
Execute a sql.ClauseElement object. |
Method | _execute_compiled |
Execute a sql.Compiled object. |
Method | _execute_context |
Create an .ExecutionContext and execute, returning a _engine.CursorResult . |
Method | _execute_ddl |
Execute a schema.DDL object. |
Method | _execute_default |
Execute a schema.ColumnDefault object. |
Method | _execute_function |
Execute a sql.FunctionElement object. |
Method | _generate_for_options |
define connection method chaining behavior for execution_options |
Method | _handle_dbapi_exception |
Undocumented |
Method | _invalid_transaction |
Undocumented |
Method | _invoke_before_exec_event |
Undocumented |
Method | _is_autocommit |
Undocumented |
Method | _log_debug |
Undocumented |
Method | _log_info |
Undocumented |
Method | _prepare_twophase_impl |
Undocumented |
Method | _release_savepoint_impl |
Undocumented |
Method | _revalidate_connection |
Undocumented |
Method | _rollback_impl |
Undocumented |
Method | _rollback_to_savepoint_impl |
Undocumented |
Method | _rollback_twophase_impl |
Undocumented |
Method | _run_ddl_visitor |
run a DDL visitor. |
Method | _safe_close_cursor |
Close the given cursor, catching exceptions and turning into log warnings. |
Method | _savepoint_impl |
Undocumented |
Method | _warn_for_legacy_exec_format |
Undocumented |
Method | begin |
Begin a transaction and return a transaction handle. |
Method | begin_nested |
Begin a nested transaction (i.e. SAVEPOINT) and return a transaction handle, assuming an outer transaction is already established. |
Method | begin_twophase |
Begin a two-phase or XA transaction and return a transaction handle. |
Method | close |
Close this _engine.Connection . |
Method | commit_prepared |
Undocumented |
Method | connect |
Returns a branched version of this _engine.Connection . |
Method | detach |
Detach the underlying DB-API connection from its connection pool. |
Method | exec_driver_sql |
Executes a SQL statement construct and returns a _engine.CursorResult . |
Method | execute |
Executes a SQL statement construct and returns a _engine.CursorResult . |
Method | execution_options |
Set non-SQL options for the connection which take effect during execution. |
Method | get_execution_options |
Get the non-SQL options which will take effect during execution. |
Method | get_isolation_level |
Return the current isolation level assigned to this _engine.Connection . |
Method | get_nested_transaction |
Return the current nested transaction in progress, if any. |
Method | get_transaction |
Return the current root transaction in progress, if any. |
Method | in_nested_transaction |
Return True if a transaction is in progress. |
Method | in_transaction |
Return True if a transaction is in progress. |
Method | invalidate |
Invalidate the underlying DBAPI connection associated with this _engine.Connection . |
Method | recover_twophase |
Undocumented |
Method | rollback_prepared |
Undocumented |
Method | run_callable |
Given a callable object or function, execute it, passing a _engine.Connection as the first argument. |
Method | scalar |
Executes and returns the first column of the first row. |
Method | scalars |
Executes and returns a scalar result set, which yields scalar values from the first column of each row. |
Method | schema_for_object |
Return the schema name for the given schema item taking into account current schema translate map. |
Method | transaction |
Execute the given function within a transaction boundary. |
Class Variable | _is_future |
Undocumented |
Class Variable | _sqla_logger_namespace |
Undocumented |
Class Variable | _trans_context_manager |
Undocumented |
Instance Variable | __branch_from |
Undocumented |
Instance Variable | __can_reconnect |
Undocumented |
Instance Variable | __in_begin |
Undocumented |
Instance Variable | _dbapi_connection |
Undocumented |
Instance Variable | _echo |
Undocumented |
Instance Variable | _execution_options |
Undocumented |
Instance Variable | _has_events |
Undocumented |
Instance Variable | _is_disconnect |
Undocumented |
Instance Variable | _reentrant_error |
Undocumented |
Instance Variable | dialect |
Undocumented |
Instance Variable | dispatch |
Undocumented |
Instance Variable | engine |
The _engine.Engine instance referred to by this .Connectable . |
Instance Variable | should_close_with_result |
Undocumented |
Property | _message_formatter |
Undocumented |
Property | _schema_translate_map |
Undocumented |
Property | _still_open_and_dbapi_connection_is_valid |
Undocumented |
Property | closed |
Return True if this connection is closed. |
Property | connection |
The underlying DB-API connection managed by this Connection. |
Property | default_isolation_level |
The default isolation level assigned to this _engine.Connection . |
Property | info |
Info dictionary associated with the underlying DBAPI connection referred to by this _engine.Connection , allowing user-defined data to be associated with the connection. |
Property | invalidated |
Return True if this connection was invalidated. |
Inherited from Connectable
:
Method | _run_visitor |
Undocumented |
Return a new Connection which references this Connection's engine and connection; but does not have close_with_result enabled, and also whose close() method does nothing.
The Core uses this very sparingly, only in the case of custom SQL default functions that are to be INSERTed as the primary key of a row where we need to get the value back, so we have to invoke it distinctly - this is a very uncommon case.
Userland code accesses _branch() when the connect() method is called. The branched connection acts as much as possible like the parent, except that it stays connected when a close() event occurs.
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().
Execute a sql.Compiled object.
TODO: why do we have this? likely deprecate or remove
.ExecutionContext
and execute, returning
a _engine.CursorResult
.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.
Begin a transaction and return a transaction handle.
The returned object is an instance of .Transaction
.
This object represents the "scope" of the transaction,
which completes when either the .Transaction.rollback
or .Transaction.commit
method is called.
Tip
The _engine.Connection.begin
method is invoked when using
the _engine.Engine.begin
context manager method as well.
All documentation that refers to behaviors specific to the
_engine.Connection.begin
method also apply to use of the
_engine.Engine.begin
method.
Legacy use: nested calls to .begin
on the same
_engine.Connection
will return new .Transaction
objects that represent an emulated transaction within the scope of the
enclosing transaction, that is:
trans = conn.begin() # outermost transaction trans2 = conn.begin() # "nested" trans2.commit() # does nothing trans.commit() # actually commits
Calls to .Transaction.commit
only have an effect
when invoked via the outermost .Transaction
object, though the
.Transaction.rollback
method of any of the
.Transaction
objects will roll back the
transaction.
Tip
The above "nesting" behavior is a legacy behavior specific to
:term:`1.x style` use and will be removed in SQLAlchemy 2.0. For
notes on :term:`2.0 style` use, see
_future.Connection.begin
.
See Also
_engine.Connection.begin_nested
- use a SAVEPOINT
_engine.Connection.begin_twophase
-
use a two phase /XID transaction
_engine.Engine.begin
- context manager available from
_engine.Engine
Begin a nested transaction (i.e. SAVEPOINT) and return a transaction handle, assuming an outer transaction is already established.
Nested transactions require SAVEPOINT support in the underlying database. Any transaction in the hierarchy may commit and rollback, however the outermost transaction still controls the overall commit or rollback of the transaction of a whole.
The legacy form of _engine.Connection.begin_nested
method has
alternate behaviors based on whether or not the
_engine.Connection.begin
method was called previously. If
_engine.Connection.begin
was not called, then this method will
behave the same as the _engine.Connection.begin
method and
return a .RootTransaction
object that begins and commits a
real transaction - no savepoint is invoked. If
_engine.Connection.begin
has been called, and a
.RootTransaction
is already established, then this method
returns an instance of .NestedTransaction
which will invoke
and manage the scope of a SAVEPOINT.
Tip
The above mentioned behavior of
_engine.Connection.begin_nested
is a legacy behavior
specific to :term:`1.x style` use. In :term:`2.0 style` use, the
_future.Connection.begin_nested
method instead autobegins
the outer transaction that can be committed using
"commit-as-you-go" style; see
_future.Connection.begin_nested
for migration details.
_engine.Connection.begin_nested
as returning a .RootTransaction
if
_engine.Connection.begin
were not called has been restored
as was the case in 1.3.x versions; in previous 1.4.x versions, an
outer transaction would be "autobegun" but would not be committed.See Also
_engine.Connection.begin
_engine.Connection.begin_twophase
Begin a two-phase or XA transaction and return a transaction handle.
The returned object is an instance of .TwoPhaseTransaction
,
which in addition to the methods provided by
.Transaction
, also provides a
~.TwoPhaseTransaction.prepare
method.
See Also
_engine.Connection.begin
_engine.Connection.begin_twophase
Parameters | |
xid | the two phase transaction id. If not supplied, a random id will be generated. |
Close this _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 _pool.Pool
referenced
by the _engine.Engine
that produced this
_engine.Connection
. Any transactional state present on
the DBAPI connection is also unconditionally released via
the DBAPI connection's rollback() method, regardless
of any .Transaction
object that may be
outstanding with regards to this _engine.Connection
.
After _engine.Connection.close
is called, the
_engine.Connection
is permanently in a closed state,
and will allow no further operations.
Returns a branched version of this _engine.Connection
.
The _engine.Connection.close
method on the returned
_engine.Connection
can be called and this
_engine.Connection
will remain open.
This method provides usage symmetry with
_engine.Engine.connect
, including for usage
with context managers.
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 _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).
_engine.CursorResult
.Parameters | |
statement | The statement str to be executed. Bound parameters must use the underlying DBAPI's paramstyle, such as "qmark", "pyformat", "format", etc. |
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 See Also |
execution_options | Undocumented |
_engine.CursorResult
.Parameters | |
statement | The statement to be executed. May be one of:
Deprecated since version 2.0: passing a string to
_engine.Connection.execute is
deprecated and will be removed in version 2.0. Use the
_expression.text construct with
_engine.Connection.execute , or the
_engine.Connection.exec_driver_sql
method to invoke a driver-level
SQL string. |
*multiparams | Undocumented |
**params | Undocumented |
multiparams/**params | represent bound parameter values to be used in the execution. Typically, the format is either a collection of one or more dictionaries passed to *multiparams: conn.execute( table.insert(), {"id":1, "value":"v1"}, {"id":2, "value":"v2"} ) ...or individual key/values interpreted by **params: conn.execute( table.insert(), id=1, value="v1" ) In the case that a plain SQL string is passed, and the underlying DBAPI accepts positional bind parameters, a collection of tuples or individual values in *multiparams may be passed: conn.execute( "INSERT INTO table (id, value) VALUES (?, ?)", (1, "v1"), (2, "v2") ) conn.execute( "INSERT INTO table (id, value) VALUES (?, ?)", 1, "v1" ) Note above, the usage of a question mark "?" or other symbol is contingent upon the "paramstyle" accepted by the DBAPI in use, which may be any of "qmark", "named", "pyformat", "format", "numeric". See pep-249 for details on paramstyle. To execute a textual SQL statement which uses bound parameters in a
DBAPI-agnostic way, use the
Deprecated since version 2.0: use of tuple or scalar positional parameters
is deprecated. All params should be dicts or sequences of dicts.
Use
.exec_driver_sql to execute a plain string with
tuple or scalar positional parameters. |
Set non-SQL options for the connection which take effect during execution.
For a "future" style connection, this method returns this same
_future.Connection
object with the new options added.
For a legacy connection, this method returns a copy of this
_engine.Connection
which references the same underlying DBAPI
connection, but also defines the given execution options which will
take effect for a call to
execute
. As the new _engine.Connection
references the
same underlying resource, it's usually a good idea to ensure that
the copies will be discarded immediately, which is implicit if used
as in:
result = connection.execution_options(stream_results=True).\ execute(stmt)
Note that any key/value can be passed to
_engine.Connection.execution_options
,
and it will be stored in the
_execution_options dictionary of the _engine.Connection
.
It
is suitable for usage by end-user schemes to communicate with
event listeners, for example.
The keywords that are currently recognized by SQLAlchemy itself
include all those listed under .Executable.execution_options
,
as well as others that are specific to _engine.Connection
.
See Also
_engine.Engine.execution_options
.Executable.execution_options
_engine.Connection.get_execution_options
Parameters | |
**opt | Undocumented |
autocommit | Available on: Connection, statement. When True, a COMMIT will be invoked after execution when executed in 'autocommit' mode, i.e. when an explicit transaction is not begun on the connection. Note that this is library level, not DBAPI level autocommit. The DBAPI connection will remain in a real transaction unless the "AUTOCOMMIT" isolation level is used.
Deprecated since version 1.4: The "autocommit" execution option is deprecated
and will be removed in SQLAlchemy 2.0. See
:ref:`migration_20_autocommit` for discussion.
|
compiled_cache | Available on: Connection.
A dictionary where 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. |
logging_token | Available on: 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.
New in version 1.4.0b2.
See Also :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. |
isolation_level | Available on: Set the transaction isolation level for the lifespan of this
The isolation level option applies the isolation level by emitting
statements on the DBAPI connection, and necessarily affects the
original Connection object overall, not just the copy that is
returned by the call to Warning The isolation_level execution option should
not be used when a transaction is already established, that
is, the Note The isolation_level execution option is implicitly
reset if the See Also :paramref:`_sa.create_engine.isolation_level`
- set per
:ref:`SQLite Transaction Isolation <sqlite_isolation_level>` :ref:`PostgreSQL Transaction Isolation <postgresql_isolation_level>` :ref:`MySQL Transaction Isolation <mysql_isolation_level>` :ref:`SQL Server Transaction Isolation <mssql_isolation_level>` :ref:`session_transaction_isolation` - for the ORM |
no_parameters | 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. |
stream_results | Available on: Connection, statement. Indicate to the dialect that results should be "streamed" and not pre-buffered, if possible. This is a limitation of many DBAPIs. The flag is currently understood within a subset of dialects within the PostgreSQL and MySQL categories, and may be supported by other third party dialects as well. See Also |
schema_translate_map | Available on: Connection, Engine.
A dictionary mapping schema names to schema names, that will be
applied to the :paramref:`_schema.Table.schema` element of each
New in version 1.1.
See Also |
Get the non-SQL options which will take effect during execution.
See Also
_engine.Connection.execution_options
Return the current isolation level assigned to this
_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-_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
_engine.Connection.default_isolation_level
accessor
which returns the dialect-level setting without performing a SQL
query.
See Also
_engine.Connection.default_isolation_level
- view default level
:paramref:`_sa.create_engine.isolation_level`
- set per _engine.Engine
isolation level
:paramref:`.Connection.execution_options.isolation_level`
- set per _engine.Connection
isolation level
Return the current nested transaction in progress, if any.
Return the current root transaction in progress, if any.
Invalidate the underlying DBAPI connection associated with
this _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
_engine.Connection.execute
method or similar),
this _engine.Connection
will attempt to
procure a new DBAPI connection using the services of the
_pool.Pool
as a source of connectivity (e.g.
a "reconnection").
If a transaction was in progress (e.g. the
_engine.Connection.begin
method has been called) when
_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 _engine.Connection
will not allow a reconnection to proceed until the
.Transaction
object is ended, by calling the
.Transaction.rollback
method; until that point, any attempt at
continuing to use the _engine.Connection
will raise an
~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 _engine.Connection.invalidate
method,
just like auto-invalidation,
will at the connection pool level invoke the
_events.PoolEvents.invalidate
event.
See Also
Parameters | |
exception | an optional Exception instance that's the reason for the invalidation. is passed along to event handlers and logging functions. |
Given a callable object or function, execute it, passing
a _engine.Connection
as the first argument.
The given *args and **kwargs are passed subsequent
to the _engine.Connection
argument.
This function, along with _engine.Engine.run_callable
,
allows a function to be run with a _engine.Connection
or _engine.Engine
object without the need to know
which one is being dealt with.
Executes and returns the first column of the first row.
The underlying result/cursor is closed after execution.
Executes and returns a scalar result set, which yields scalar values from the first column of each row.
This method is equivalent to calling _engine.Connection.execute
to receive a _result.Result
object, then invoking the
_result.Result.scalars
method to produce a
_result.ScalarResult
instance.
Returns | |
a _result.ScalarResult |
Execute the given function within a transaction boundary.
The function is passed this _engine.Connection
as the first argument, followed by the given *args and **kwargs,
e.g.:
def do_something(conn, x, y): conn.execute(text("some statement"), {'x':x, 'y':y}) conn.transaction(do_something, 5, 10)
The operations inside the function are all invoked within the
context of a single .Transaction
.
Upon success, the transaction is committed. If an
exception is raised, the transaction is rolled back
before propagating the exception.
Note
The .transaction
method is superseded by
the usage of the Python with: statement, which can
be used with _engine.Connection.begin
:
with conn.begin(): conn.execute(text("some statement"), {'x':5, 'y':10})
As well as with _engine.Engine.begin
:
with engine.begin() as conn: conn.execute(text("some statement"), {'x':5, 'y':10})
See Also
_engine.Engine.begin
- engine-level transactional
context
_engine.Engine.transaction
- engine-level version of
_engine.Connection.transaction
The _engine.Engine
instance referred to by this
.Connectable
.
May be self if this is already an _engine.Engine
.
The underlying DB-API connection managed by this Connection.
This is a SQLAlchemy connection-pool proxied connection
which then has the attribute
_pool._ConnectionFairy.dbapi_connection
that refers to the
actual driver connection.
See Also
The default isolation level assigned to this
_engine.Connection
.
This is the isolation level setting that the
_engine.Connection
has when first procured via the _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-_engine.Connection
basis.
Unlike _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.
See Also
_engine.Connection.get_isolation_level
- view current level
:paramref:`_sa.create_engine.isolation_level`
- set per _engine.Engine
isolation level
:paramref:`.Connection.execution_options.isolation_level`
- set per _engine.Connection
isolation level
Info dictionary associated with the underlying DBAPI connection
referred to by this _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 _engine.Connection
.