Engines
plateforme.core.database.engines
This module provides utilities for managing database engines within the Plateforme framework using SQLAlchemy features.
Async
This module provides utilities for managing database engines within the Plateforme framework using SQLAlchemy features.
AsyncConnection
AsyncConnection(
async_engine: AsyncEngine,
sync_connection: Optional[Connection] = None,
)
Bases: ProxyComparable[Connection]
, StartableContext['AsyncConnection']
, AsyncConnectable
An asyncio proxy for a :class:_engine.Connection
.
:class:_asyncio.AsyncConnection
is acquired using the
:meth:_asyncio.AsyncEngine.connect
method of :class:_asyncio.AsyncEngine
::
from sqlalchemy.ext.asyncio import create_async_engine
engine = create_async_engine("postgresql+asyncpg://user:pass@host/dbname")
async with engine.connect() as conn:
result = await conn.execute(select(table))
.. versionadded:: 1.4
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
sync_engine
instance-attribute
sync_engine: Engine
Reference to the sync-style :class:_engine.Engine
this
:class:_asyncio.AsyncConnection
is associated with via its underlying
:class:_engine.Connection
.
This instance can be used as an event target.
.. seealso::
:ref:`asyncio_events`
sync_connection
instance-attribute
sync_connection: Optional[Connection]
Reference to the sync-style :class:_engine.Connection
this
:class:_asyncio.AsyncConnection
proxies requests towards.
This instance can be used as an event target.
.. seealso::
:ref:`asyncio_events`
connection
property
connection: NoReturn
Not implemented for async; call
:meth:_asyncio.AsyncConnection.get_raw_connection
.
closed
property
closed: Any
Return True if this connection is closed.
.. container:: class_bases
Proxied for the :class:`_engine.Connection` class
on behalf of the :class:`_asyncio.AsyncConnection` class.
invalidated
property
invalidated: Any
Return True if this connection was invalidated.
.. container:: class_bases
Proxied for the :class:`_engine.Connection` class
on behalf of the :class:`_asyncio.AsyncConnection` class.
This does not indicate whether or not the connection was invalidated at the pool level, however
dialect
property
writable
dialect: Any
Proxy for the :attr:_engine.Connection.dialect
attribute
on behalf of the :class:_asyncio.AsyncConnection
class.
default_isolation_level
property
default_isolation_level: Any
The initial-connection time isolation level associated with the
:class:_engine.Dialect
in use.
.. container:: class_bases
Proxied for the :class:`_engine.Connection` class
on behalf of the :class:`_asyncio.AsyncConnection` class.
This value is independent of the
:paramref:.Connection.execution_options.isolation_level
and
:paramref:.Engine.execution_options.isolation_level
execution
options, and is determined by the :class:_engine.Dialect
when the
first connection is created, by performing a SQL query against the
database for the current isolation level before any additional commands
have been emitted.
Calling this accessor does not invoke any new SQL queries.
.. seealso::
:meth:`_engine.Connection.get_isolation_level`
- view current actual isolation 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
start
async
start(is_ctxmanager: bool = False) -> AsyncConnection
Start this :class:_asyncio.AsyncConnection
object's context
outside of using a Python with:
block.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
get_raw_connection
async
get_raw_connection() -> PoolProxiedConnection
Return the pooled DBAPI-level connection in use by this
:class:_asyncio.AsyncConnection
.
This is a SQLAlchemy connection-pool proxied connection
which then has the attribute
:attr:_pool._ConnectionFairy.driver_connection
that refers to the
actual driver connection. Its
:attr:_pool._ConnectionFairy.dbapi_connection
refers instead
to an :class:_engine.AdaptedConnection
instance that
adapts the driver connection to the DBAPI protocol.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
info
Return the :attr:_engine.Connection.info
dictionary of the
underlying :class:_engine.Connection
.
This dictionary is freely writable for user-defined state to be associated with the database connection.
This attribute is only available if the :class:.AsyncConnection
is
currently connected. If the :attr:.AsyncConnection.closed
attribute
is True
, then accessing this attribute will raise
:class:.ResourceClosedError
.
.. versionadded:: 1.4.0b2
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
begin
begin() -> AsyncTransaction
begin_nested
begin_nested() -> AsyncTransaction
Begin a nested transaction and return a transaction handle.
invalidate
async
invalidate(
exception: Optional[BaseException] = None,
) -> None
Invalidate the underlying DBAPI connection associated with
this :class:_engine.Connection
.
See the method :meth:_engine.Connection.invalidate
for full
detail on this method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
in_transaction
in_transaction() -> bool
in_nested_transaction
in_nested_transaction() -> bool
Return True if a transaction is in progress.
.. versionadded:: 1.4.0b2
get_transaction
get_transaction() -> Optional[AsyncTransaction]
Return an :class:.AsyncTransaction
representing the current
transaction, if any.
This makes use of the underlying synchronous connection's
:meth:_engine.Connection.get_transaction
method to get the current
:class:_engine.Transaction
, which is then proxied in a new
:class:.AsyncTransaction
object.
.. versionadded:: 1.4.0b2
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
get_nested_transaction
get_nested_transaction() -> Optional[AsyncTransaction]
Return an :class:.AsyncTransaction
representing the current
nested (savepoint) transaction, if any.
This makes use of the underlying synchronous connection's
:meth:_engine.Connection.get_nested_transaction
method to get the
current :class:_engine.Transaction
, which is then proxied in a new
:class:.AsyncTransaction
object.
.. versionadded:: 1.4.0b2
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
execution_options
async
execution_options(
*,
compiled_cache: 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,
) -> AsyncConnection
execution_options(**opt: Any) -> AsyncConnection
execution_options(**opt: Any) -> AsyncConnection
Set non-SQL options for the connection which take effect during execution.
This returns this :class:_asyncio.AsyncConnection
object with
the new options added.
See :meth:_engine.Connection.execution_options
for full details
on this method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
commit
async
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.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
rollback
async
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.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
close
async
Close this :class:_asyncio.AsyncConnection
.
This has the effect of also rolling back the transaction if one is in place.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
aclose
async
A synonym for :meth:_asyncio.AsyncConnection.close
.
The :meth:_asyncio.AsyncConnection.aclose
name is specifically
to support the Python standard library @contextlib.aclosing
context manager function.
.. versionadded:: 2.0.20
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
exec_driver_sql
async
exec_driver_sql(
statement: str,
parameters: Optional[_DBAPIAnyExecuteParams] = None,
execution_options: Optional[
CoreExecuteOptionsParameter
] = None,
) -> CursorResult[Any]
Executes a driver-level SQL string and return buffered
:class:_engine.Result
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
stream
async
stream(
statement: TypedReturnsRows[_T],
parameters: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: Optional[
CoreExecuteOptionsParameter
] = None,
) -> GeneratorStartableContext[AsyncResult[_T]]
stream(
statement: Executable,
parameters: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: Optional[
CoreExecuteOptionsParameter
] = None,
) -> GeneratorStartableContext[AsyncResult[Any]]
stream(
statement: Executable,
parameters: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: Optional[
CoreExecuteOptionsParameter
] = None,
) -> AsyncIterator[AsyncResult[Any]]
Execute a statement and return an awaitable yielding a
:class:_asyncio.AsyncResult
object.
E.g.::
result = await conn.stream(stmt):
async for row in result:
print(f"{row}")
The :meth:.AsyncConnection.stream
method supports optional context manager use against the
:class:.AsyncResult
object, as in::
async with conn.stream(stmt) as result:
async for row in result:
print(f"{row}")
In the above pattern, the :meth:.AsyncResult.close
method is
invoked unconditionally, even if the iterator is interrupted by an
exception throw. Context manager use remains optional, however,
and the function may be called in either an async with fn():
or
await fn()
style.
.. versionadded:: 2.0.0b3 added context manager support
:return: an awaitable object that will yield an
:class:_asyncio.AsyncResult
object.
.. seealso::
:meth:`.AsyncConnection.stream_scalars`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
execute
async
execute(
statement: TypedReturnsRows[_T],
parameters: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: Optional[
CoreExecuteOptionsParameter
] = None,
) -> CursorResult[_T]
execute(
statement: Executable,
parameters: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: Optional[
CoreExecuteOptionsParameter
] = None,
) -> CursorResult[Any]
execute(
statement: Executable,
parameters: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: Optional[
CoreExecuteOptionsParameter
] = None,
) -> CursorResult[Any]
Executes a SQL statement construct and return a buffered
:class:_engine.Result
.
:param object: 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.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
scalar
async
scalar(
statement: TypedReturnsRows[Tuple[_T]],
parameters: Optional[_CoreSingleExecuteParams] = None,
*,
execution_options: Optional[
CoreExecuteOptionsParameter
] = None,
) -> Optional[_T]
scalar(
statement: Executable,
parameters: Optional[_CoreSingleExecuteParams] = None,
*,
execution_options: Optional[
CoreExecuteOptionsParameter
] = None,
) -> Any
scalar(
statement: 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.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
scalars
async
scalars(
statement: TypedReturnsRows[Tuple[_T]],
parameters: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: Optional[
CoreExecuteOptionsParameter
] = None,
) -> ScalarResult[_T]
scalars(
statement: Executable,
parameters: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: Optional[
CoreExecuteOptionsParameter
] = None,
) -> ScalarResult[Any]
scalars(
statement: Executable,
parameters: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: Optional[
CoreExecuteOptionsParameter
] = None,
) -> ScalarResult[Any]
Executes a SQL statement construct and returns a scalar objects.
This method is shorthand for invoking the
:meth:_engine.Result.scalars
method after invoking the
:meth:_engine.Connection.execute
method. Parameters are equivalent.
:return: a :class:_engine.ScalarResult
object.
.. versionadded:: 1.4.24
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
stream_scalars
async
stream_scalars(
statement: TypedReturnsRows[Tuple[_T]],
parameters: Optional[_CoreSingleExecuteParams] = None,
*,
execution_options: Optional[
CoreExecuteOptionsParameter
] = None,
) -> GeneratorStartableContext[AsyncScalarResult[_T]]
stream_scalars(
statement: Executable,
parameters: Optional[_CoreSingleExecuteParams] = None,
*,
execution_options: Optional[
CoreExecuteOptionsParameter
] = None,
) -> GeneratorStartableContext[AsyncScalarResult[Any]]
stream_scalars(
statement: Executable,
parameters: Optional[_CoreSingleExecuteParams] = None,
*,
execution_options: Optional[
CoreExecuteOptionsParameter
] = None,
) -> AsyncIterator[AsyncScalarResult[Any]]
Execute a statement and return an awaitable yielding a
:class:_asyncio.AsyncScalarResult
object.
E.g.::
result = await conn.stream_scalars(stmt)
async for scalar in result:
print(f"{scalar}")
This method is shorthand for invoking the
:meth:_engine.AsyncResult.scalars
method after invoking the
:meth:_engine.Connection.stream
method. Parameters are equivalent.
The :meth:.AsyncConnection.stream_scalars
method supports optional context manager use against the
:class:.AsyncScalarResult
object, as in::
async with conn.stream_scalars(stmt) as result:
async for scalar in result:
print(f"{scalar}")
In the above pattern, the :meth:.AsyncScalarResult.close
method is
invoked unconditionally, even if the iterator is interrupted by an
exception throw. Context manager use remains optional, however,
and the function may be called in either an async with fn():
or
await fn()
style.
.. versionadded:: 2.0.0b3 added context manager support
:return: an awaitable object that will yield an
:class:_asyncio.AsyncScalarResult
object.
.. versionadded:: 1.4.24
.. seealso::
:meth:`.AsyncConnection.stream`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
run_sync
async
Invoke the given synchronous (i.e. not async) callable,
passing a synchronous-style :class:_engine.Connection
as the first
argument.
This method allows traditional synchronous SQLAlchemy functions to run within the context of an asyncio application.
E.g.::
def do_something_with_core(conn: Connection, arg1: int, arg2: str) -> str:
'''A synchronous function that does not require awaiting
:param conn: a Core SQLAlchemy Connection, used synchronously
:return: an optional return value is supported
'''
conn.execute(
some_table.insert().values(int_col=arg1, str_col=arg2)
)
return "success"
async def do_something_async(async_engine: AsyncEngine) -> None:
'''an async function that uses awaiting'''
async with async_engine.begin() as async_conn:
# run do_something_with_core() with a sync-style
# Connection, proxied into an awaitable
return_code = await async_conn.run_sync(do_something_with_core, 5, "strval")
print(return_code)
This method maintains the asyncio event loop all the way through to the database connection by running the given callable in a specially instrumented greenlet.
The most rudimentary use of :meth:.AsyncConnection.run_sync
is to
invoke methods such as :meth:_schema.MetaData.create_all
, given
an :class:.AsyncConnection
that needs to be provided to
:meth:_schema.MetaData.create_all
as a :class:_engine.Connection
object::
# run metadata.create_all(conn) with a sync-style Connection,
# proxied into an awaitable
with async_engine.begin() as conn:
await conn.run_sync(metadata.create_all)
.. note::
The provided callable is invoked inline within the asyncio event
loop, and will block on traditional IO calls. IO within this
callable should only call into SQLAlchemy's asyncio database
APIs which will be properly adapted to the greenlet context.
.. seealso::
:meth:`.AsyncSession.run_sync`
:ref:`session_run_sync`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
AsyncEngine
AsyncEngine(sync_engine: Engine)
Bases: ProxyComparable[Engine]
, AsyncConnectable
An asyncio proxy for a :class:_engine.Engine
.
:class:_asyncio.AsyncEngine
is acquired using the
:func:_asyncio.create_async_engine
function::
from sqlalchemy.ext.asyncio import create_async_engine
engine = create_async_engine("postgresql+asyncpg://user:pass@host/dbname")
.. versionadded:: 1.4
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
sync_engine
instance-attribute
sync_engine: Engine = _assign_proxied(sync_engine)
Reference to the sync-style :class:_engine.Engine
this
:class:_asyncio.AsyncEngine
proxies requests towards.
This instance can be used as an event target.
.. seealso::
:ref:`asyncio_events`
url
property
writable
url: URL
Proxy for the :attr:_engine.Engine.url
attribute
on behalf of the :class:_asyncio.AsyncEngine
class.
pool
property
writable
pool: Pool
Proxy for the :attr:_engine.Engine.pool
attribute
on behalf of the :class:_asyncio.AsyncEngine
class.
dialect
property
writable
dialect: Dialect
Proxy for the :attr:_engine.Engine.dialect
attribute
on behalf of the :class:_asyncio.AsyncEngine
class.
engine
property
engine: Any
Returns this :class:.Engine
.
.. container:: class_bases
Proxied for the :class:`_engine.Engine` class
on behalf of the :class:`_asyncio.AsyncEngine` class.
Used for legacy schemes that accept :class:.Connection
/
:class:.Engine
objects within the same variable.
name
property
name: Any
String name of the :class:~sqlalchemy.engine.interfaces.Dialect
in use by this :class:Engine
.
.. container:: class_bases
Proxied for the :class:`_engine.Engine` class
on behalf of the :class:`_asyncio.AsyncEngine` class.
driver
property
driver: Any
Driver name of the :class:~sqlalchemy.engine.interfaces.Dialect
in use by this :class:Engine
.
.. container:: class_bases
Proxied for the :class:`_engine.Engine` class
on behalf of the :class:`_asyncio.AsyncEngine` class.
echo
property
writable
echo: Any
When True
, enable log output for this element.
.. container:: class_bases
Proxied for the :class:`_engine.Engine` class
on behalf of the :class:`_asyncio.AsyncEngine` class.
This has the effect of setting the Python logging level for the namespace
of this element's class and object reference. A value of boolean True
indicates that the loglevel logging.INFO
will be set for the logger,
whereas the string value debug
will set the loglevel to
logging.DEBUG
.
begin
async
begin() -> AsyncIterator[AsyncConnection]
Return a context manager which when entered will deliver an
:class:_asyncio.AsyncConnection
with an
:class:_asyncio.AsyncTransaction
established.
E.g.::
async with async_engine.begin() as conn:
await conn.execute(
text("insert into table (x, y, z) values (1, 2, 3)")
)
await conn.execute(text("my_special_procedure(5)"))
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
connect
connect() -> AsyncConnection
Return an :class:_asyncio.AsyncConnection
object.
The :class:_asyncio.AsyncConnection
will procure a database
connection from the underlying connection pool when it is entered
as an async context manager::
async with async_engine.connect() as conn:
result = await conn.execute(select(user_table))
The :class:_asyncio.AsyncConnection
may also be started outside of a
context manager by invoking its :meth:_asyncio.AsyncConnection.start
method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
raw_connection
async
raw_connection() -> PoolProxiedConnection
Return a "raw" DBAPI connection from the connection pool.
.. seealso::
:ref:`dbapi_connections`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
execution_options
execution_options(
*,
compiled_cache: Optional[CompiledCacheType] = ...,
logging_token: str = ...,
isolation_level: IsolationLevel = ...,
insertmanyvalues_page_size: int = ...,
schema_translate_map: Optional[
SchemaTranslateMapType
] = ...,
**opt: Any,
) -> AsyncEngine
execution_options(**opt: Any) -> AsyncEngine
execution_options(**opt: Any) -> AsyncEngine
Return a new :class:_asyncio.AsyncEngine
that will provide
:class:_asyncio.AsyncConnection
objects with the given execution
options.
Proxied from :meth:_engine.Engine.execution_options
. See that
method for details.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
dispose
async
dispose(close: bool = True) -> None
Dispose of the connection pool used by this
:class:_asyncio.AsyncEngine
.
:param close: if left at its default of True
, has the
effect of fully closing all currently checked in
database connections. Connections that are still checked out
will not be closed, however they will no longer be associated
with this :class:_engine.Engine
,
so when they are closed individually, eventually the
:class:_pool.Pool
which they are associated with will
be garbage collected and they will be closed out fully, if
not already closed on checkin.
If set to False
, the previous connection pool is de-referenced,
and otherwise not touched in any way.
.. seealso::
:meth:`_engine.Engine.dispose`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
clear_compiled_cache
Clear the compiled cache associated with the dialect.
.. container:: class_bases
Proxied for the :class:`_engine.Engine` class on
behalf of the :class:`_asyncio.AsyncEngine` class.
This applies only to the built-in cache that is established
via the :paramref:_engine.create_engine.query_cache_size
parameter.
It will not impact any dictionary caches that were passed via the
:paramref:.Connection.execution_options.compiled_cache
parameter.
.. versionadded:: 1.4
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
update_execution_options
update_execution_options(**opt: Any) -> None
Update the default execution_options dictionary
of this :class:_engine.Engine
.
.. container:: class_bases
Proxied for the :class:`_engine.Engine` class on
behalf of the :class:`_asyncio.AsyncEngine` class.
The given keys/values in **opt are added to the
default execution options that will be used for
all connections. The initial contents of this dictionary
can be sent via the execution_options
parameter
to :func:_sa.create_engine
.
.. seealso::
:meth:`_engine.Connection.execution_options`
:meth:`_engine.Engine.execution_options`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
get_execution_options
Get the non-SQL options which will take effect during execution.
.. container:: class_bases
Proxied for the :class:`_engine.Engine` class on
behalf of the :class:`_asyncio.AsyncEngine` class.
.. versionadded: 1.3
.. seealso::
:meth:`_engine.Engine.execution_options`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
AsyncMappingResult
Bases: _WithKeys
, AsyncCommon[RowMapping]
A wrapper for a :class:_asyncio.AsyncResult
that returns dictionary
values rather than :class:_engine.Row
values.
The :class:_asyncio.AsyncMappingResult
object is acquired by calling the
:meth:_asyncio.AsyncResult.mappings
method.
Refer to the :class:_result.MappingResult
object in the synchronous
SQLAlchemy API for a complete behavioral description.
.. versionadded:: 1.4
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
closed
property
closed: bool
proxies the .closed attribute of the underlying result object,
if any, else raises AttributeError
.
.. versionadded:: 2.0.0b3
memoized_attribute
Bases: memoized_property[_T]
A read-only @property that is only evaluated once.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
memoized_instancemethod
classmethod
Decorate a method memoize its return value.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
yield_per
yield_per(num: int) -> Self
Configure the row-fetching strategy to fetch num
rows at a time.
The :meth:_engine.FilterResult.yield_per
method is a pass through
to the :meth:_engine.Result.yield_per
method. See that method's
documentation for usage notes.
.. versionadded:: 1.4.40 - added :meth:_engine.FilterResult.yield_per
so that the method is available on all result set implementations
.. seealso::
:ref:`engine_stream_results` - describes Core behavior for
:meth:`_engine.Result.yield_per`
:ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
close
async
keys
Return an iterable view which yields the string keys that would
be represented by each :class:_engine.Row
.
The keys can represent the labels of the columns returned by a core statement or the names of the orm classes returned by an orm execution.
The view also can be tested for key containment using the Python
in
operator, which will test both for the string keys represented
in the view, as well as for alternate keys such as column objects.
.. versionchanged:: 1.4 a key view object is returned rather than a plain list.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
unique
unique(
strategy: Optional[_UniqueFilterType] = None,
) -> Self
Apply unique filtering to the objects returned by this
:class:_asyncio.AsyncMappingResult
.
See :meth:_asyncio.AsyncResult.unique
for usage details.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
columns
Establish the columns that should be returned in each row.
partitions
async
partitions(
size: Optional[int] = None,
) -> AsyncIterator[Sequence[RowMapping]]
Iterate through sub-lists of elements of the size given.
Equivalent to :meth:_asyncio.AsyncResult.partitions
except that
:class:_engine.RowMapping
values, rather than :class:_engine.Row
objects, are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
fetchall
async
fetchall() -> Sequence[RowMapping]
A synonym for the :meth:_asyncio.AsyncMappingResult.all
method.
fetchone
async
fetchone() -> Optional[RowMapping]
Fetch one object.
Equivalent to :meth:_asyncio.AsyncResult.fetchone
except that
:class:_engine.RowMapping
values, rather than :class:_engine.Row
objects, are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
fetchmany
async
fetchmany(
size: Optional[int] = None,
) -> Sequence[RowMapping]
Fetch many rows.
Equivalent to :meth:_asyncio.AsyncResult.fetchmany
except that
:class:_engine.RowMapping
values, rather than :class:_engine.Row
objects, are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
all
async
all() -> Sequence[RowMapping]
Return all rows in a list.
Equivalent to :meth:_asyncio.AsyncResult.all
except that
:class:_engine.RowMapping
values, rather than :class:_engine.Row
objects, are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
first
async
first() -> Optional[RowMapping]
Fetch the first object or None
if no object is present.
Equivalent to :meth:_asyncio.AsyncResult.first
except that
:class:_engine.RowMapping
values, rather than :class:_engine.Row
objects, are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
one_or_none
async
one_or_none() -> Optional[RowMapping]
Return at most one object or raise an exception.
Equivalent to :meth:_asyncio.AsyncResult.one_or_none
except that
:class:_engine.RowMapping
values, rather than :class:_engine.Row
objects, are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
one
async
one() -> RowMapping
Return exactly one object or raise an exception.
Equivalent to :meth:_asyncio.AsyncResult.one
except that
:class:_engine.RowMapping
values, rather than :class:_engine.Row
objects, are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
AsyncResult
AsyncResult(real_result: Result[_TP])
Bases: _WithKeys
, AsyncCommon[Row[_TP]]
An asyncio wrapper around a :class:_result.Result
object.
The :class:_asyncio.AsyncResult
only applies to statement executions that
use a server-side cursor. It is returned only from the
:meth:_asyncio.AsyncConnection.stream
and
:meth:_asyncio.AsyncSession.stream
methods.
.. note:: As is the case with :class:_engine.Result
, this object is
used for ORM results returned by :meth:_asyncio.AsyncSession.execute
,
which can yield instances of ORM mapped objects either individually or
within tuple-like rows. Note that these result objects do not
deduplicate instances or rows automatically as is the case with the
legacy :class:_orm.Query
object. For in-Python de-duplication of
instances or rows, use the :meth:_asyncio.AsyncResult.unique
modifier
method.
.. versionadded:: 1.4
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
closed
property
closed: bool
proxies the .closed attribute of the underlying result object,
if any, else raises AttributeError
.
.. versionadded:: 2.0.0b3
t
property
t: AsyncTupleResult[_TP]
Apply a "typed tuple" typing filter to returned rows.
The :attr:_asyncio.AsyncResult.t
attribute is a synonym for
calling the :meth:_asyncio.AsyncResult.tuples
method.
.. versionadded:: 2.0
memoized_attribute
Bases: memoized_property[_T]
A read-only @property that is only evaluated once.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
memoized_instancemethod
classmethod
Decorate a method memoize its return value.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
yield_per
yield_per(num: int) -> Self
Configure the row-fetching strategy to fetch num
rows at a time.
The :meth:_engine.FilterResult.yield_per
method is a pass through
to the :meth:_engine.Result.yield_per
method. See that method's
documentation for usage notes.
.. versionadded:: 1.4.40 - added :meth:_engine.FilterResult.yield_per
so that the method is available on all result set implementations
.. seealso::
:ref:`engine_stream_results` - describes Core behavior for
:meth:`_engine.Result.yield_per`
:ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
close
async
keys
Return an iterable view which yields the string keys that would
be represented by each :class:_engine.Row
.
The keys can represent the labels of the columns returned by a core statement or the names of the orm classes returned by an orm execution.
The view also can be tested for key containment using the Python
in
operator, which will test both for the string keys represented
in the view, as well as for alternate keys such as column objects.
.. versionchanged:: 1.4 a key view object is returned rather than a plain list.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
tuples
tuples() -> AsyncTupleResult[_TP]
Apply a "typed tuple" typing filter to returned rows.
This method returns the same :class:_asyncio.AsyncResult
object
at runtime,
however annotates as returning a :class:_asyncio.AsyncTupleResult
object that will indicate to :pep:484
typing tools that plain typed
Tuple
instances are returned rather than rows. This allows
tuple unpacking and __getitem__
access of :class:_engine.Row
objects to by typed, for those cases where the statement invoked
itself included typing information.
.. versionadded:: 2.0
:return: the :class:_result.AsyncTupleResult
type at typing time.
.. seealso::
:attr:`_asyncio.AsyncResult.t` - shorter synonym
:attr:`_engine.Row.t` - :class:`_engine.Row` version
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
unique
unique(
strategy: Optional[_UniqueFilterType] = None,
) -> Self
Apply unique filtering to the objects returned by this
:class:_asyncio.AsyncResult
.
Refer to :meth:_engine.Result.unique
in the synchronous
SQLAlchemy API for a complete behavioral description.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
columns
Establish the columns that should be returned in each row.
Refer to :meth:_engine.Result.columns
in the synchronous
SQLAlchemy API for a complete behavioral description.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
partitions
async
partitions(
size: Optional[int] = None,
) -> AsyncIterator[Sequence[Row[_TP]]]
Iterate through sub-lists of rows of the size given.
An async iterator is returned::
async def scroll_results(connection):
result = await connection.stream(select(users_table))
async for partition in result.partitions(100):
print("list of rows: %s" % partition)
Refer to :meth:_engine.Result.partitions
in the synchronous
SQLAlchemy API for a complete behavioral description.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
fetchall
async
A synonym for the :meth:_asyncio.AsyncResult.all
method.
.. versionadded:: 2.0
fetchone
async
Fetch one row.
When all rows are exhausted, returns None.
This method is provided for backwards compatibility with SQLAlchemy 1.x.x.
To fetch the first row of a result only, use the
:meth:_asyncio.AsyncResult.first
method. To iterate through all
rows, iterate the :class:_asyncio.AsyncResult
object directly.
:return: a :class:_engine.Row
object if no filters are applied,
or None
if no rows remain.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
fetchmany
async
Fetch many rows.
When all rows are exhausted, returns an empty list.
This method is provided for backwards compatibility with SQLAlchemy 1.x.x.
To fetch rows in groups, use the
:meth:._asyncio.AsyncResult.partitions
method.
:return: a list of :class:_engine.Row
objects.
.. seealso::
:meth:`_asyncio.AsyncResult.partitions`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
all
async
Return all rows in a list.
Closes the result set after invocation. Subsequent invocations will return an empty list.
:return: a list of :class:_engine.Row
objects.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
first
async
Fetch the first row or None
if no row is present.
Closes the result set and discards remaining rows.
.. note:: This method returns one row, e.g. tuple, by default.
To return exactly one single scalar value, that is, the first
column of the first row, use the
:meth:_asyncio.AsyncResult.scalar
method,
or combine :meth:_asyncio.AsyncResult.scalars
and
:meth:_asyncio.AsyncResult.first
.
Additionally, in contrast to the behavior of the legacy ORM
:meth:_orm.Query.first
method, no limit is applied to the
SQL query which was invoked to produce this
:class:_asyncio.AsyncResult
;
for a DBAPI driver that buffers results in memory before yielding
rows, all rows will be sent to the Python process and all but
the first row will be discarded.
.. seealso::
:ref:`migration_20_unify_select`
:return: a :class:_engine.Row
object, or None
if no rows remain.
.. seealso::
:meth:`_asyncio.AsyncResult.scalar`
:meth:`_asyncio.AsyncResult.one`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
one_or_none
async
Return at most one result or raise an exception.
Returns None
if the result has no rows.
Raises :class:.MultipleResultsFound
if multiple rows are returned.
.. versionadded:: 1.4
:return: The first :class:_engine.Row
or None
if no row
is available.
:raises: :class:.MultipleResultsFound
.. seealso::
:meth:`_asyncio.AsyncResult.first`
:meth:`_asyncio.AsyncResult.one`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
scalar_one
async
scalar_one() -> Any
scalar_one() -> Any
Return exactly one scalar result or raise an exception.
This is equivalent to calling :meth:_asyncio.AsyncResult.scalars
and
then :meth:_asyncio.AsyncResult.one
.
.. seealso::
:meth:`_asyncio.AsyncResult.one`
:meth:`_asyncio.AsyncResult.scalars`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
scalar_one_or_none
async
Return exactly one scalar result or None
.
This is equivalent to calling :meth:_asyncio.AsyncResult.scalars
and
then :meth:_asyncio.AsyncResult.one_or_none
.
.. seealso::
:meth:`_asyncio.AsyncResult.one_or_none`
:meth:`_asyncio.AsyncResult.scalars`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
one
async
one() -> Row[_TP]
Return exactly one row or raise an exception.
Raises :class:.NoResultFound
if the result returns no
rows, or :class:.MultipleResultsFound
if multiple rows
would be returned.
.. note:: This method returns one row, e.g. tuple, by default.
To return exactly one single scalar value, that is, the first
column of the first row, use the
:meth:_asyncio.AsyncResult.scalar_one
method, or combine
:meth:_asyncio.AsyncResult.scalars
and
:meth:_asyncio.AsyncResult.one
.
.. versionadded:: 1.4
:return: The first :class:_engine.Row
.
:raises: :class:.MultipleResultsFound
, :class:.NoResultFound
.. seealso::
:meth:`_asyncio.AsyncResult.first`
:meth:`_asyncio.AsyncResult.one_or_none`
:meth:`_asyncio.AsyncResult.scalar_one`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
scalar
async
scalar() -> Any
Fetch the first column of the first row, and close the result set.
Returns None
if there are no rows to fetch.
No validation is performed to test if additional rows remain.
After calling this method, the object is fully closed,
e.g. the :meth:_engine.CursorResult.close
method will have been called.
:return: a Python scalar value, or None
if no rows remain.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
freeze
async
freeze() -> FrozenResult[_TP]
Return a callable object that will produce copies of this
:class:_asyncio.AsyncResult
when invoked.
The callable object returned is an instance of
:class:_engine.FrozenResult
.
This is used for result set caching. The method must be called
on the result when it has been unconsumed, and calling the method
will consume the result fully. When the :class:_engine.FrozenResult
is retrieved from a cache, it can be called any number of times where
it will produce a new :class:_engine.Result
object each time
against its stored set of rows.
.. seealso::
:ref:`do_orm_execute_re_executing` - example usage within the
ORM to implement a result-set cache.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
scalars
scalars(index: Literal[0]) -> AsyncScalarResult[_T]
scalars() -> AsyncScalarResult[_T]
scalars(index: _KeyIndexType = 0) -> AsyncScalarResult[Any]
scalars(index: _KeyIndexType = 0) -> AsyncScalarResult[Any]
Return an :class:_asyncio.AsyncScalarResult
filtering object which
will return single elements rather than :class:_row.Row
objects.
Refer to :meth:_result.Result.scalars
in the synchronous
SQLAlchemy API for a complete behavioral description.
:param index: integer or row key indicating the column to be fetched
from each row, defaults to 0
indicating the first column.
:return: a new :class:_asyncio.AsyncScalarResult
filtering object
referring to this :class:_asyncio.AsyncResult
object.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
mappings
mappings() -> AsyncMappingResult
Apply a mappings filter to returned rows, returning an instance of
:class:_asyncio.AsyncMappingResult
.
When this filter is applied, fetching rows will return
:class:_engine.RowMapping
objects instead of :class:_engine.Row
objects.
:return: a new :class:_asyncio.AsyncMappingResult
filtering object
referring to the underlying :class:_result.Result
object.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
AsyncScalarResult
Bases: AsyncCommon[_R]
A wrapper for a :class:_asyncio.AsyncResult
that returns scalar values
rather than :class:_row.Row
values.
The :class:_asyncio.AsyncScalarResult
object is acquired by calling the
:meth:_asyncio.AsyncResult.scalars
method.
Refer to the :class:_result.ScalarResult
object in the synchronous
SQLAlchemy API for a complete behavioral description.
.. versionadded:: 1.4
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
closed
property
closed: bool
proxies the .closed attribute of the underlying result object,
if any, else raises AttributeError
.
.. versionadded:: 2.0.0b3
memoized_attribute
Bases: memoized_property[_T]
A read-only @property that is only evaluated once.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
memoized_instancemethod
classmethod
Decorate a method memoize its return value.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
yield_per
yield_per(num: int) -> Self
Configure the row-fetching strategy to fetch num
rows at a time.
The :meth:_engine.FilterResult.yield_per
method is a pass through
to the :meth:_engine.Result.yield_per
method. See that method's
documentation for usage notes.
.. versionadded:: 1.4.40 - added :meth:_engine.FilterResult.yield_per
so that the method is available on all result set implementations
.. seealso::
:ref:`engine_stream_results` - describes Core behavior for
:meth:`_engine.Result.yield_per`
:ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
close
async
unique
unique(
strategy: Optional[_UniqueFilterType] = None,
) -> Self
Apply unique filtering to the objects returned by this
:class:_asyncio.AsyncScalarResult
.
See :meth:_asyncio.AsyncResult.unique
for usage details.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
partitions
async
partitions(
size: Optional[int] = None,
) -> AsyncIterator[Sequence[_R]]
Iterate through sub-lists of elements of the size given.
Equivalent to :meth:_asyncio.AsyncResult.partitions
except that
scalar values, rather than :class:_engine.Row
objects,
are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
fetchall
async
fetchall() -> Sequence[_R]
A synonym for the :meth:_asyncio.AsyncScalarResult.all
method.
fetchmany
async
Fetch many objects.
Equivalent to :meth:_asyncio.AsyncResult.fetchmany
except that
scalar values, rather than :class:_engine.Row
objects,
are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
all
async
all() -> Sequence[_R]
Return all scalar values in a list.
Equivalent to :meth:_asyncio.AsyncResult.all
except that
scalar values, rather than :class:_engine.Row
objects,
are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
first
async
first() -> Optional[_R]
Fetch the first object or None
if no object is present.
Equivalent to :meth:_asyncio.AsyncResult.first
except that
scalar values, rather than :class:_engine.Row
objects,
are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
one_or_none
async
one_or_none() -> Optional[_R]
Return at most one object or raise an exception.
Equivalent to :meth:_asyncio.AsyncResult.one_or_none
except that
scalar values, rather than :class:_engine.Row
objects,
are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
one
async
Return exactly one object or raise an exception.
Equivalent to :meth:_asyncio.AsyncResult.one
except that
scalar values, rather than :class:_engine.Row
objects,
are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
AsyncTransaction
AsyncTransaction(
connection: AsyncConnection, nested: bool = False
)
Bases: ProxyComparable[Transaction]
, StartableContext['AsyncTransaction']
An asyncio proxy for a :class:_engine.Transaction
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
close
async
Close this :class:.AsyncTransaction
.
If this transaction is the base transaction in a begin/commit nesting, the transaction will rollback(). Otherwise, the method returns.
This is used to cancel a Transaction without affecting the scope of an enclosing transaction.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
rollback
async
commit
async
start
async
start(is_ctxmanager: bool = False) -> AsyncTransaction
Start this :class:_asyncio.AsyncTransaction
object's context
outside of using a Python with:
block.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
AsyncTupleResult
Bases: AsyncCommon[_R]
, TypingOnly
A :class:_asyncio.AsyncResult
that's typed as returning plain
Python tuples instead of rows.
Since :class:_engine.Row
acts like a tuple in every way already,
this class is a typing only class, regular :class:_asyncio.AsyncResult
is
still used at runtime.
closed
property
closed: bool
proxies the .closed attribute of the underlying result object,
if any, else raises AttributeError
.
.. versionadded:: 2.0.0b3
memoized_attribute
Bases: memoized_property[_T]
A read-only @property that is only evaluated once.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
memoized_instancemethod
classmethod
Decorate a method memoize its return value.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
yield_per
yield_per(num: int) -> Self
Configure the row-fetching strategy to fetch num
rows at a time.
The :meth:_engine.FilterResult.yield_per
method is a pass through
to the :meth:_engine.Result.yield_per
method. See that method's
documentation for usage notes.
.. versionadded:: 1.4.40 - added :meth:_engine.FilterResult.yield_per
so that the method is available on all result set implementations
.. seealso::
:ref:`engine_stream_results` - describes Core behavior for
:meth:`_engine.Result.yield_per`
:ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
close
async
partitions
async
partitions(
size: Optional[int] = None,
) -> AsyncIterator[Sequence[_R]]
Iterate through sub-lists of elements of the size given.
Equivalent to :meth:_result.Result.partitions
except that
tuple values, rather than :class:_engine.Row
objects,
are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
fetchone
async
fetchone() -> Optional[_R]
Fetch one tuple.
Equivalent to :meth:_result.Result.fetchone
except that
tuple values, rather than :class:_engine.Row
objects, are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
fetchall
async
fetchall() -> Sequence[_R]
fetchmany
async
Fetch many objects.
Equivalent to :meth:_result.Result.fetchmany
except that
tuple values, rather than :class:_engine.Row
objects,
are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
all
async
all() -> Sequence[_R]
Return all scalar values in a list.
Equivalent to :meth:_result.Result.all
except that
tuple values, rather than :class:_engine.Row
objects,
are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
first
async
first() -> Optional[_R]
Fetch the first object or None
if no object is present.
Equivalent to :meth:_result.Result.first
except that
tuple values, rather than :class:_engine.Row
objects,
are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
one_or_none
async
one_or_none() -> Optional[_R]
Return at most one object or raise an exception.
Equivalent to :meth:_result.Result.one_or_none
except that
tuple values, rather than :class:_engine.Row
objects,
are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
one
async
Return exactly one object or raise an exception.
Equivalent to :meth:_result.Result.one
except that
tuple values, rather than :class:_engine.Row
objects,
are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
scalar_one
async
scalar_one() -> Any
scalar_one() -> Any
Return exactly one scalar result or raise an exception.
This is equivalent to calling :meth:_engine.Result.scalars
and then :meth:_engine.Result.one
.
.. seealso::
:meth:`_engine.Result.one`
:meth:`_engine.Result.scalars`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
scalar_one_or_none
async
Return exactly one or no scalar result.
This is equivalent to calling :meth:_engine.Result.scalars
and then :meth:_engine.Result.one_or_none
.
.. seealso::
:meth:`_engine.Result.one_or_none`
:meth:`_engine.Result.scalars`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
scalar
async
scalar() -> Any
Fetch the first column of the first row, and close the result set.
Returns None
if there are no rows to fetch.
No validation is performed to test if additional rows remain.
After calling this method, the object is fully closed,
e.g. the :meth:_engine.CursorResult.close
method will have been called.
:return: a Python scalar value , or None
if no rows remain.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
async_engine_from_config
async_engine_from_config(
configuration: Dict[str, Any],
prefix: str = "sqlalchemy.",
**kwargs: Any,
) -> AsyncEngine
Create a new AsyncEngine instance using a configuration dictionary.
This function is analogous to the :func:_sa.engine_from_config
function
in SQLAlchemy Core, except that the requested dialect must be an
asyncio-compatible dialect such as :ref:dialect-postgresql-asyncpg
.
The argument signature of the function is identical to that
of :func:_sa.engine_from_config
.
.. versionadded:: 1.4.29
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
create_async_engine
create_async_engine(
url: Union[str, URL], **kw: Any
) -> AsyncEngine
Create a new async engine instance.
Arguments passed to :func:_asyncio.create_async_engine
are mostly
identical to those passed to the :func:_sa.create_engine
function.
The specified dialect must be an asyncio-compatible dialect
such as :ref:dialect-postgresql-asyncpg
.
.. versionadded:: 1.4
:param async_creator: an async callable which returns a driver-level
asyncio connection. If given, the function should take no arguments,
and return a new asyncio connection from the underlying asyncio
database driver; the connection will be wrapped in the appropriate
structures to be used with the :class:.AsyncEngine
. Note that the
parameters specified in the URL are not applied here, and the creator
function should use its own connection parameters.
This parameter is the asyncio equivalent of the
:paramref:`_sa.create_engine.creator` parameter of the
:func:`_sa.create_engine` function.
.. versionadded:: 2.0.16
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
Sync
This module provides utilities for managing database engines within the Plateforme framework using SQLAlchemy features.
Connection
Connection(
engine: Engine,
connection: Optional[PoolProxiedConnection] = None,
_has_events: Optional[bool] = None,
_allow_revalidate: bool = True,
_allow_autobegin: bool = True,
)
Bases: ConnectionEventsTarget
, Inspectable['Inspector']
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
Construct a new Connection.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
invalidated
property
invalidated: bool
Return True if this connection was invalidated.
This does not indicate whether or not the connection was invalidated at the pool level, however
connection
property
connection: PoolProxiedConnection
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`
default_isolation_level
property
default_isolation_level: Optional[IsolationLevel]
The initial-connection time isolation level associated with the
:class:_engine.Dialect
in use.
This value is independent of the
:paramref:.Connection.execution_options.isolation_level
and
:paramref:.Engine.execution_options.isolation_level
execution
options, and is determined by the :class:_engine.Dialect
when the
first connection is created, by performing a SQL query against the
database for the current isolation level before any additional commands
have been emitted.
Calling this accessor does not invoke any new SQL queries.
.. seealso::
:meth:`_engine.Connection.get_isolation_level`
- view current actual isolation 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
property
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
.
schema_for_object
Return the schema name for the given schema item taking into account current schema translate map.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
execution_options
execution_options(
*,
compiled_cache: 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
execution_options(**opt: Any) -> Connection
execution_options(**opt: Any) -> Connection
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 actual 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.
.. 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
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 |
|
get_execution_options
Get the non-SQL options which will take effect during execution.
.. versionadded:: 1.3
.. seealso::
:meth:`_engine.Connection.execution_options`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
get_isolation_level
Return the current actual isolation level that's present on the database within the scope of this connection.
This attribute will perform a live SQL operation against the database
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. This will be one of the four actual isolation
modes READ UNCOMMITTED
, READ COMMITTED
, REPEATABLE READ
,
SERIALIZABLE
. It will not include the AUTOCOMMIT
isolation
level setting. Third party dialects may also feature additional
isolation level settings.
.. note:: This method will not report on the AUTOCOMMIT
isolation level, which is a separate :term:dbapi
setting that's
independent of actual isolation level. When AUTOCOMMIT
is
in use, the database connection still has a "traditional" isolation
mode in effect, that is typically one of the four values
READ UNCOMMITTED
, READ COMMITTED
, REPEATABLE READ
,
SERIALIZABLE
.
Compare to the :attr:_engine.Connection.default_isolation_level
accessor which returns the isolation level that is present on the
database at initial connection time.
.. 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
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
invalidate
invalidate(
exception: Optional[BaseException] = None,
) -> None
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`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
detach
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).
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
begin
begin() -> RootTransaction
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 known
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`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
begin_nested
begin_nested() -> NestedTransaction
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 _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
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 |
|
begin_twophase
begin_twophase(
xid: Optional[Any] = None,
) -> TwoPhaseTransaction
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`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
commit
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.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
rollback
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.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
in_transaction
in_transaction() -> bool
get_transaction
get_transaction() -> Optional[RootTransaction]
Return the current root transaction in progress, if any.
.. versionadded:: 1.4
get_nested_transaction
get_nested_transaction() -> Optional[NestedTransaction]
Return the current nested transaction in progress, if any.
.. versionadded:: 1.4
close
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.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
scalar
scalar(
statement: TypedReturnsRows[Tuple[_T]],
parameters: Optional[_CoreSingleExecuteParams] = None,
*,
execution_options: Optional[
CoreExecuteOptionsParameter
] = None,
) -> Optional[_T]
scalar(
statement: Executable,
parameters: Optional[_CoreSingleExecuteParams] = None,
*,
execution_options: Optional[
CoreExecuteOptionsParameter
] = None,
) -> Any
scalar(
statement: 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.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
scalars
scalars(
statement: TypedReturnsRows[Tuple[_T]],
parameters: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: Optional[
CoreExecuteOptionsParameter
] = None,
) -> ScalarResult[_T]
scalars(
statement: Executable,
parameters: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: Optional[
CoreExecuteOptionsParameter
] = None,
) -> ScalarResult[Any]
scalars(
statement: 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
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
execute
execute(
statement: TypedReturnsRows[_T],
parameters: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: Optional[
CoreExecuteOptionsParameter
] = None,
) -> CursorResult[_T]
execute(
statement: Executable,
parameters: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: Optional[
CoreExecuteOptionsParameter
] = None,
) -> CursorResult[Any]
execute(
statement: 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.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
exec_driver_sql
exec_driver_sql(
statement: str,
parameters: Optional[_DBAPIAnyExecuteParams] = None,
execution_options: Optional[
CoreExecuteOptionsParameter
] = None,
) -> CursorResult[Any]
Executes a string SQL statement on the DBAPI cursor directly, without any SQL compilation steps.
This can be used to pass any string directly to the
cursor.execute()
method of the DBAPI in use.
: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.
:return: a :class:_engine.CursorResult
.
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`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 |
|
Dialect
Bases: EventTarget
Define the behavior of a specific database and DB-API combination.
Any aspect of metadata definition, SQL query generation, execution, result-set handling, or anything else which varies between databases is defined under the general category of the Dialect. The Dialect acts as a factory for other database-specific object implementations including ExecutionContext, Compiled, DefaultGenerator, and TypeEngine.
.. note:: Third party dialects should not subclass :class:.Dialect
directly. Instead, subclass :class:.default.DefaultDialect
or
descendant class.
name
instance-attribute
name: str
identifying name for the dialect from a DBAPI-neutral point of view (i.e. 'sqlite')
dbapi
instance-attribute
dbapi: Optional[ModuleType]
A reference to the DBAPI module object itself.
SQLAlchemy dialects import DBAPI modules using the classmethod
:meth:.Dialect.import_dbapi
. The rationale is so that any dialect
module can be imported and used to generate SQL statements without the
need for the actual DBAPI driver to be installed. Only when an
:class:.Engine
is constructed using :func:.create_engine
does the
DBAPI get imported; at that point, the creation process will assign
the DBAPI module to this attribute.
Dialects should therefore implement :meth:.Dialect.import_dbapi
which will import the necessary module and return it, and then refer
to self.dbapi
in dialect code in order to refer to the DBAPI module
contents.
.. versionchanged:: The :attr:.Dialect.dbapi
attribute is exclusively
used as the per-:class:.Dialect
-instance reference to the DBAPI
module. The previous not-fully-documented .Dialect.dbapi()
classmethod is deprecated and replaced by :meth:.Dialect.import_dbapi
.
positional
instance-attribute
positional: bool
True if the paramstyle for this Dialect is positional.
paramstyle
instance-attribute
paramstyle: str
the paramstyle to be used (some DB-APIs support multiple paramstyles).
statement_compiler
instance-attribute
statement_compiler: Type[SQLCompiler]
a :class:.Compiled
class used to compile SQL statements
ddl_compiler
instance-attribute
ddl_compiler: Type[DDLCompiler]
a :class:.Compiled
class used to compile DDL statements
type_compiler_cls
class-attribute
type_compiler_cls: Type[TypeCompiler]
a :class:.Compiled
class used to compile SQL type objects
.. versionadded:: 2.0
type_compiler_instance
instance-attribute
instance of a :class:.Compiled
class used to compile SQL type
objects
.. versionadded:: 2.0
type_compiler
instance-attribute
type_compiler: Any
legacy; this is a TypeCompiler class at the class level, a TypeCompiler instance at the instance level.
Refer to type_compiler_instance instead.
preparer
instance-attribute
preparer: Type[IdentifierPreparer]
a :class:.IdentifierPreparer
class used to
quote identifiers.
identifier_preparer
instance-attribute
identifier_preparer: IdentifierPreparer
This element will refer to an instance of :class:.IdentifierPreparer
once a :class:.DefaultDialect
has been constructed.
server_version_info
instance-attribute
a tuple containing a version number for the DB backend in use.
This value is only available for supporting dialects, and is typically populated during the initial connection to the database.
default_schema_name
instance-attribute
the name of the default schema. This value is only available for supporting dialects, and is typically populated during the initial connection to the database.
default_isolation_level
instance-attribute
default_isolation_level: Optional[IsolationLevel]
the isolation that is implicitly present on new connections
execution_ctx_cls
instance-attribute
execution_ctx_cls: Type[ExecutionContext]
a :class:.ExecutionContext
class used to handle statement execution
execute_sequence_format
instance-attribute
either the 'tuple' or 'list' type, depending on what cursor.execute() accepts for the second argument (they vary).
supports_alter
instance-attribute
supports_alter: bool
True
if the database supports ALTER TABLE
- used only for
generating foreign key constraints in certain circumstances
max_identifier_length
instance-attribute
max_identifier_length: int
The maximum length of identifier names.
supports_server_side_cursors
instance-attribute
supports_server_side_cursors: bool
indicates if the dialect supports server side cursors
server_side_cursors
instance-attribute
server_side_cursors: bool
deprecated; indicates if the dialect should attempt to use server side cursors by default
supports_sane_rowcount
instance-attribute
supports_sane_rowcount: bool
Indicate whether the dialect properly implements rowcount for
UPDATE
and DELETE
statements.
supports_sane_multi_rowcount
instance-attribute
supports_sane_multi_rowcount: bool
Indicate whether the dialect properly implements rowcount for
UPDATE
and DELETE
statements when executed via
executemany.
supports_empty_insert
instance-attribute
supports_empty_insert: bool
dialect supports INSERT () VALUES (), i.e. a plain INSERT with no columns in it.
This is not usually supported; an "empty" insert is typically suited using either "INSERT..DEFAULT VALUES" or "INSERT ... (col) VALUES (DEFAULT)".
supports_default_values
instance-attribute
supports_default_values: bool
dialect supports INSERT... DEFAULT VALUES syntax
supports_default_metavalue
instance-attribute
supports_default_metavalue: bool
dialect supports INSERT...(col) VALUES (DEFAULT) syntax.
Most databases support this in some way, e.g. SQLite supports it using
VALUES (NULL)
. MS SQL Server supports the syntax also however
is the only included dialect where we have this disabled, as
MSSQL does not support the field for the IDENTITY column, which is
usually where we like to make use of the feature.
default_metavalue_token
class-attribute
instance-attribute
default_metavalue_token: str = 'DEFAULT'
for INSERT... VALUES (DEFAULT) syntax, the token to put in the parenthesis.
E.g. for SQLite this is the keyword "NULL".
supports_multivalues_insert
instance-attribute
supports_multivalues_insert: bool
Target database supports INSERT...VALUES with multiple value sets, i.e. INSERT INTO table (cols) VALUES (...), (...), (...), ...
insert_executemany_returning
instance-attribute
insert_executemany_returning: bool
dialect / driver / database supports some means of providing INSERT...RETURNING support when dialect.do_executemany() is used.
insert_executemany_returning_sort_by_parameter_order
instance-attribute
insert_executemany_returning_sort_by_parameter_order: bool
dialect / driver / database supports some means of providing
INSERT...RETURNING support when dialect.do_executemany() is used
along with the :paramref:_dml.Insert.returning.sort_by_parameter_order
parameter being set.
update_executemany_returning
instance-attribute
update_executemany_returning: bool
dialect supports UPDATE..RETURNING with executemany.
delete_executemany_returning
instance-attribute
delete_executemany_returning: bool
dialect supports DELETE..RETURNING with executemany.
use_insertmanyvalues
instance-attribute
use_insertmanyvalues: bool
if True, indicates "insertmanyvalues" functionality should be used
to allow for insert_executemany_returning
behavior, if possible.
In practice, setting this to True means:
if supports_multivalues_insert
, insert_returning
and
use_insertmanyvalues
are all True, the SQL compiler will produce
an INSERT that will be interpreted by the :class:.DefaultDialect
as an :attr:.ExecuteStyle.INSERTMANYVALUES
execution that allows
for INSERT of many rows with RETURNING by rewriting a single-row
INSERT statement to have multiple VALUES clauses, also executing
the statement multiple times for a series of batches when large numbers
of rows are given.
The parameter is False for the default dialect, and is set to
True for SQLAlchemy internal dialects SQLite, MySQL/MariaDB, PostgreSQL,
SQL Server. It remains at False for Oracle, which provides native
"executemany with RETURNING" support and also does not support
supports_multivalues_insert
. For MySQL/MariaDB, those MySQL
dialects that don't support RETURNING will not report
insert_executemany_returning
as True.
.. versionadded:: 2.0
.. seealso::
:ref:`engine_insertmanyvalues`
use_insertmanyvalues_wo_returning
instance-attribute
use_insertmanyvalues_wo_returning: bool
if True, and use_insertmanyvalues is also True, INSERT statements that don't include RETURNING will also use "insertmanyvalues".
.. versionadded:: 2.0
.. seealso::
:ref:`engine_insertmanyvalues`
insertmanyvalues_implicit_sentinel
instance-attribute
Options indicating the database supports a form of bulk INSERT where the autoincrement integer primary key can be reliably used as an ordering for INSERTed rows.
.. versionadded:: 2.0.10
.. seealso::
:ref:`engine_insertmanyvalues_returning_order`
insertmanyvalues_page_size
instance-attribute
insertmanyvalues_page_size: int
Number of rows to render into an individual INSERT..VALUES() statement
for :attr:.ExecuteStyle.INSERTMANYVALUES
executions.
The default dialect defaults this to 1000.
.. versionadded:: 2.0
.. seealso::
:paramref:`_engine.Connection.execution_options.insertmanyvalues_page_size` -
execution option available on :class:`_engine.Connection`, statements
insertmanyvalues_max_parameters
instance-attribute
insertmanyvalues_max_parameters: int
Alternate to insertmanyvalues_page_size, will additionally limit page size based on number of parameters total in the statement.
preexecute_autoincrement_sequences
instance-attribute
preexecute_autoincrement_sequences: bool
True if 'implicit' primary key functions must be executed separately in order to get their value, if RETURNING is not used.
This is currently oriented towards PostgreSQL when the
implicit_returning=False
parameter is used on a :class:.Table
object.
insert_returning
instance-attribute
insert_returning: bool
if the dialect supports RETURNING with INSERT
.. versionadded:: 2.0
update_returning
instance-attribute
update_returning: bool
if the dialect supports RETURNING with UPDATE
.. versionadded:: 2.0
update_returning_multifrom
instance-attribute
update_returning_multifrom: bool
if the dialect supports RETURNING with UPDATE..FROM
.. versionadded:: 2.0
delete_returning
instance-attribute
delete_returning: bool
if the dialect supports RETURNING with DELETE
.. versionadded:: 2.0
delete_returning_multifrom
instance-attribute
delete_returning_multifrom: bool
if the dialect supports RETURNING with DELETE..FROM
.. versionadded:: 2.0
favor_returning_over_lastrowid
instance-attribute
favor_returning_over_lastrowid: bool
for backends that support both a lastrowid and a RETURNING insert strategy, favor RETURNING for simple single-int pk inserts.
cursor.lastrowid tends to be more performant on most backends.
supports_identity_columns
instance-attribute
supports_identity_columns: bool
target database supports IDENTITY
cte_follows_insert
instance-attribute
cte_follows_insert: bool
target database, when given a CTE with an INSERT statement, needs the CTE to be below the INSERT
colspecs
instance-attribute
colspecs: MutableMapping[
Type[TypeEngine[Any]], Type[TypeEngine[Any]]
]
A dictionary of TypeEngine classes from sqlalchemy.types mapped to subclasses that are specific to the dialect class. This dictionary is class-level only and is not accessed from the dialect instance itself.
supports_sequences
instance-attribute
supports_sequences: bool
Indicates if the dialect supports CREATE SEQUENCE or similar.
sequences_optional
instance-attribute
sequences_optional: bool
If True, indicates if the :paramref:_schema.Sequence.optional
parameter on the :class:_schema.Sequence
construct
should signal to not generate a CREATE SEQUENCE. Applies only to
dialects that support sequences. Currently used only to allow PostgreSQL
SERIAL to be used on a column that specifies Sequence() for usage on
other backends.
default_sequence_base
instance-attribute
default_sequence_base: int
the default value that will be rendered as the "START WITH" portion of a CREATE SEQUENCE DDL statement.
supports_native_enum
instance-attribute
supports_native_enum: bool
Indicates if the dialect supports a native ENUM construct.
This will prevent :class:_types.Enum
from generating a CHECK
constraint when that type is used in "native" mode.
supports_native_boolean
instance-attribute
supports_native_boolean: bool
Indicates if the dialect supports a native boolean construct.
This will prevent :class:_types.Boolean
from generating a CHECK
constraint when that type is used.
supports_native_decimal
instance-attribute
supports_native_decimal: bool
indicates if Decimal objects are handled and returned for precision numeric types, or if floats are returned
supports_native_uuid
instance-attribute
supports_native_uuid: bool
indicates if Python UUID() objects are handled natively by the driver for SQL UUID datatypes.
.. versionadded:: 2.0
returns_native_bytes
instance-attribute
returns_native_bytes: bool
indicates if Python bytes() objects are returned natively by the driver for SQL "binary" datatypes.
.. versionadded:: 2.0.11
construct_arguments
class-attribute
instance-attribute
construct_arguments: Optional[
List[
Tuple[
Type[Union[SchemaItem, ClauseElement]],
Mapping[str, Any],
]
]
] = None
Optional set of argument specifiers for various SQLAlchemy constructs, typically schema items.
To implement, establish as a series of tuples, as in::
construct_arguments = [
(schema.Index, {
"using": False,
"where": None,
"ops": None
})
]
If the above construct is established on the PostgreSQL dialect,
the :class:.Index
construct will now accept the keyword arguments
postgresql_using
, postgresql_where
, nad postgresql_ops
.
Any other argument specified to the constructor of :class:.Index
which is prefixed with postgresql_
will raise :class:.ArgumentError
.
A dialect which does not include a construct_arguments
member will
not participate in the argument validation system. For such a dialect,
any argument name is accepted by all participating constructs, within
the namespace of arguments prefixed with that dialect name. The rationale
here is so that third-party dialects that haven't yet implemented this
feature continue to function in the old way.
.. seealso::
:class:`.DialectKWArgs` - implementing base class which consumes
:attr:`.DefaultDialect.construct_arguments`
reflection_options
class-attribute
instance-attribute
Sequence of string names indicating keyword arguments that can be
established on a :class:.Table
object which will be passed as
"reflection options" when using :paramref:.Table.autoload_with
.
Current example is "oracle_resolve_synonyms" in the Oracle dialect.
dbapi_exception_translation_map
class-attribute
instance-attribute
A dictionary of names that will contain as values the names of pep-249 exceptions ("IntegrityError", "OperationalError", etc) keyed to alternate class names, to support the case where a DBAPI has exception classes that aren't named as they are referred to (e.g. IntegrityError = MyException). In the vast majority of cases this dictionary is empty.
supports_comments
instance-attribute
supports_comments: bool
Indicates the dialect supports comment DDL on tables and columns.
inline_comments
instance-attribute
inline_comments: bool
Indicates the dialect supports comment DDL that's inline with the definition of a Table or Column. If False, this implies that ALTER must be used to set table and column comments.
supports_constraint_comments
instance-attribute
supports_constraint_comments: bool
Indicates if the dialect supports comment DDL on constraints.
.. versionadded: 2.0
supports_statement_cache
class-attribute
instance-attribute
supports_statement_cache: bool = True
indicates if this dialect supports caching.
All dialects that are compatible with statement caching should set this flag to True directly on each dialect class and subclass that supports it. SQLAlchemy tests that this flag is locally present on each dialect subclass before it will use statement caching. This is to provide safety for legacy or new dialects that are not yet fully tested to be compliant with SQL statement caching.
.. versionadded:: 1.4.5
.. seealso::
:ref:`engine_thirdparty_caching`
bind_typing
class-attribute
instance-attribute
define a means of passing typing information to the database and/or driver for bound parameters.
See :class:.BindTyping
for values.
.. versionadded:: 2.0
has_terminate
instance-attribute
has_terminate: bool
Whether or not this dialect has a separate "terminate" implementation that does not block or require awaiting.
engine_config_types
instance-attribute
a mapping of string keys that can be in an engine config linked to type conversion functions.
label_length
instance-attribute
optional user-defined max length for SQL labels
include_set_input_sizes
instance-attribute
set of DBAPI type objects that should be included in automatic cursor.setinputsizes() calls.
This is only used if bind_typing is BindTyping.SET_INPUT_SIZES
exclude_set_input_sizes
instance-attribute
set of DBAPI type objects that should be excluded in automatic cursor.setinputsizes() calls.
This is only used if bind_typing is BindTyping.SET_INPUT_SIZES
supports_simple_order_by_label
instance-attribute
supports_simple_order_by_label: bool
target database supports ORDER BY
div_is_floordiv
instance-attribute
div_is_floordiv: bool
target database treats the / division operator as "floor division"
tuple_in_values
instance-attribute
tuple_in_values: bool
target database supports tuple IN, i.e. (x, y) IN ((q, p), (r, z))
loaded_dbapi
loaded_dbapi() -> ModuleType
same as .dbapi, but is never None; will raise an error if no DBAPI was set up.
.. versionadded:: 2.0
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
create_connect_args
create_connect_args(url: URL) -> ConnectArgsType
Build DB-API compatible connection arguments.
Given a :class:.URL
object, returns a tuple
consisting of a (*args, **kwargs)
suitable to send directly
to the dbapi's connect function. The arguments are sent to the
:meth:.Dialect.connect
method which then runs the DBAPI-level
connect()
function.
The method typically makes use of the
:meth:.URL.translate_connect_args
method in order to generate a dictionary of options.
The default implementation is::
def create_connect_args(self, url):
opts = url.translate_connect_args()
opts.update(url.query)
return ([], opts)
:param url: a :class:.URL
object
:return: a tuple of (*args, **kwargs)
which will be passed to the
:meth:.Dialect.connect
method.
.. seealso::
:meth:`.URL.translate_connect_args`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
import_dbapi
classmethod
import_dbapi() -> ModuleType
Import the DBAPI module that is used by this dialect.
The Python module object returned here will be assigned as an
instance variable to a constructed dialect under the name
.dbapi
.
.. versionchanged:: 2.0 The :meth:.Dialect.import_dbapi
class
method is renamed from the previous method .Dialect.dbapi()
,
which would be replaced at dialect instantiation time by the
DBAPI module itself, thus using the same name in two different ways.
If a .Dialect.dbapi()
classmethod is present on a third-party
dialect, it will be used and a deprecation warning will be emitted.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
type_descriptor
classmethod
type_descriptor(typeobj: TypeEngine[_T" optional hover>_T]) -> TypeEngine[_T]
Transform a generic type to a dialect-specific type.
Dialect classes will usually use the
:func:_types.adapt_type
function in the types module to
accomplish this.
The returned result is cached per dialect class so can contain no dialect-instance state.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
initialize
initialize(connection: Connection) -> None
Called during strategized creation of the dialect with a connection.
Allows dialects to configure options based on server version info or other properties.
The connection passed here is a SQLAlchemy Connection object, with full capabilities.
The initialize() method of the base dialect should be called via super().
.. note:: as of SQLAlchemy 1.4, this method is called before
any :meth:_engine.Dialect.on_connect
hooks are called.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_columns
get_columns(
connection: Connection,
table_name: str,
schema: Optional[str] = None,
**kw: Any,
) -> List[ReflectedColumn]
Return information about columns in table_name
.
Given a :class:_engine.Connection
, a string
table_name
, and an optional string schema
, return column
information as a list of dictionaries
corresponding to the :class:.ReflectedColumn
dictionary.
This is an internal dialect method. Applications should use
:meth:.Inspector.get_columns
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_multi_columns
get_multi_columns(
connection: Connection,
schema: Optional[str] = None,
filter_names: Optional[Collection[str]] = None,
**kw: Any,
) -> Iterable[Tuple[TableKey, List[ReflectedColumn]]]
Return information about columns in all tables in the
given schema
.
This is an internal dialect method. Applications should use
:meth:.Inspector.get_multi_columns
.
.. note:: The :class:_engine.DefaultDialect
provides a default
implementation that will call the single table method for
each object returned by :meth:Dialect.get_table_names
,
:meth:Dialect.get_view_names
or
:meth:Dialect.get_materialized_view_names
depending on the
provided kind
. Dialects that want to support a faster
implementation should implement this method.
.. versionadded:: 2.0
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_pk_constraint
get_pk_constraint(
connection: Connection,
table_name: str,
schema: Optional[str] = None,
**kw: Any,
) -> ReflectedPrimaryKeyConstraint
Return information about the primary key constraint on table_name`.
Given a :class:_engine.Connection
, a string
table_name
, and an optional string schema
, return primary
key information as a dictionary corresponding to the
:class:.ReflectedPrimaryKeyConstraint
dictionary.
This is an internal dialect method. Applications should use
:meth:.Inspector.get_pk_constraint
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_multi_pk_constraint
get_multi_pk_constraint(
connection: Connection,
schema: Optional[str] = None,
filter_names: Optional[Collection[str]] = None,
**kw: Any,
) -> Iterable[
Tuple[TableKey, ReflectedPrimaryKeyConstraint]
]
Return information about primary key constraints in
all tables in the given schema
.
This is an internal dialect method. Applications should use
:meth:.Inspector.get_multi_pk_constraint
.
.. note:: The :class:_engine.DefaultDialect
provides a default
implementation that will call the single table method for
each object returned by :meth:Dialect.get_table_names
,
:meth:Dialect.get_view_names
or
:meth:Dialect.get_materialized_view_names
depending on the
provided kind
. Dialects that want to support a faster
implementation should implement this method.
.. versionadded:: 2.0
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_foreign_keys
get_foreign_keys(
connection: Connection,
table_name: str,
schema: Optional[str] = None,
**kw: Any,
) -> List[ReflectedForeignKeyConstraint]
Return information about foreign_keys in table_name
.
Given a :class:_engine.Connection
, a string
table_name
, and an optional string schema
, return foreign
key information as a list of dicts corresponding to the
:class:.ReflectedForeignKeyConstraint
dictionary.
This is an internal dialect method. Applications should use
:meth:_engine.Inspector.get_foreign_keys
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_multi_foreign_keys
get_multi_foreign_keys(
connection: Connection,
schema: Optional[str] = None,
filter_names: Optional[Collection[str]] = None,
**kw: Any,
) -> Iterable[
Tuple[TableKey, List[ReflectedForeignKeyConstraint]]
]
Return information about foreign_keys in all tables
in the given schema
.
This is an internal dialect method. Applications should use
:meth:_engine.Inspector.get_multi_foreign_keys
.
.. note:: The :class:_engine.DefaultDialect
provides a default
implementation that will call the single table method for
each object returned by :meth:Dialect.get_table_names
,
:meth:Dialect.get_view_names
or
:meth:Dialect.get_materialized_view_names
depending on the
provided kind
. Dialects that want to support a faster
implementation should implement this method.
.. versionadded:: 2.0
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_table_names
Return a list of table names for schema
.
This is an internal dialect method. Applications should use
:meth:_engine.Inspector.get_table_names
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_temp_table_names
get_temp_table_names(
connection: Connection,
schema: Optional[str] = None,
**kw: Any,
) -> List[str]
Return a list of temporary table names on the given connection, if supported by the underlying backend.
This is an internal dialect method. Applications should use
:meth:_engine.Inspector.get_temp_table_names
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_view_names
Return a list of all non-materialized view names available in the database.
This is an internal dialect method. Applications should use
:meth:_engine.Inspector.get_view_names
.
:param schema: schema name to query, if not the default schema.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_materialized_view_names
get_materialized_view_names(
connection: Connection,
schema: Optional[str] = None,
**kw: Any,
) -> List[str]
Return a list of all materialized view names available in the database.
This is an internal dialect method. Applications should use
:meth:_engine.Inspector.get_materialized_view_names
.
:param schema: schema name to query, if not the default schema.
.. versionadded:: 2.0
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_sequence_names
Return a list of all sequence names available in the database.
This is an internal dialect method. Applications should use
:meth:_engine.Inspector.get_sequence_names
.
:param schema: schema name to query, if not the default schema.
.. versionadded:: 1.4
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_temp_view_names
get_temp_view_names(
connection: Connection,
schema: Optional[str] = None,
**kw: Any,
) -> List[str]
Return a list of temporary view names on the given connection, if supported by the underlying backend.
This is an internal dialect method. Applications should use
:meth:_engine.Inspector.get_temp_view_names
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_schema_names
get_schema_names(
connection: Connection, **kw: Any
) -> List[str]
Return a list of all schema names available in the database.
This is an internal dialect method. Applications should use
:meth:_engine.Inspector.get_schema_names
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_view_definition
get_view_definition(
connection: Connection,
view_name: str,
schema: Optional[str] = None,
**kw: Any,
) -> str
Return plain or materialized view definition.
This is an internal dialect method. Applications should use
:meth:_engine.Inspector.get_view_definition
.
Given a :class:_engine.Connection
, a string
view_name
, and an optional string schema
, return the view
definition.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_indexes
get_indexes(
connection: Connection,
table_name: str,
schema: Optional[str] = None,
**kw: Any,
) -> List[ReflectedIndex]
Return information about indexes in table_name
.
Given a :class:_engine.Connection
, a string
table_name
and an optional string schema
, return index
information as a list of dictionaries corresponding to the
:class:.ReflectedIndex
dictionary.
This is an internal dialect method. Applications should use
:meth:.Inspector.get_indexes
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_multi_indexes
get_multi_indexes(
connection: Connection,
schema: Optional[str] = None,
filter_names: Optional[Collection[str]] = None,
**kw: Any,
) -> Iterable[Tuple[TableKey, List[ReflectedIndex]]]
Return information about indexes in in all tables
in the given schema
.
This is an internal dialect method. Applications should use
:meth:.Inspector.get_multi_indexes
.
.. note:: The :class:_engine.DefaultDialect
provides a default
implementation that will call the single table method for
each object returned by :meth:Dialect.get_table_names
,
:meth:Dialect.get_view_names
or
:meth:Dialect.get_materialized_view_names
depending on the
provided kind
. Dialects that want to support a faster
implementation should implement this method.
.. versionadded:: 2.0
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_unique_constraints
get_unique_constraints(
connection: Connection,
table_name: str,
schema: Optional[str] = None,
**kw: Any,
) -> List[ReflectedUniqueConstraint]
Return information about unique constraints in table_name
.
Given a string table_name
and an optional string schema
, return
unique constraint information as a list of dicts corresponding
to the :class:.ReflectedUniqueConstraint
dictionary.
This is an internal dialect method. Applications should use
:meth:.Inspector.get_unique_constraints
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_multi_unique_constraints
get_multi_unique_constraints(
connection: Connection,
schema: Optional[str] = None,
filter_names: Optional[Collection[str]] = None,
**kw: Any,
) -> Iterable[
Tuple[TableKey, List[ReflectedUniqueConstraint]]
]
Return information about unique constraints in all tables
in the given schema
.
This is an internal dialect method. Applications should use
:meth:.Inspector.get_multi_unique_constraints
.
.. note:: The :class:_engine.DefaultDialect
provides a default
implementation that will call the single table method for
each object returned by :meth:Dialect.get_table_names
,
:meth:Dialect.get_view_names
or
:meth:Dialect.get_materialized_view_names
depending on the
provided kind
. Dialects that want to support a faster
implementation should implement this method.
.. versionadded:: 2.0
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_check_constraints
get_check_constraints(
connection: Connection,
table_name: str,
schema: Optional[str] = None,
**kw: Any,
) -> List[ReflectedCheckConstraint]
Return information about check constraints in table_name
.
Given a string table_name
and an optional string schema
, return
check constraint information as a list of dicts corresponding
to the :class:.ReflectedCheckConstraint
dictionary.
This is an internal dialect method. Applications should use
:meth:.Inspector.get_check_constraints
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_multi_check_constraints
get_multi_check_constraints(
connection: Connection,
schema: Optional[str] = None,
filter_names: Optional[Collection[str]] = None,
**kw: Any,
) -> Iterable[
Tuple[TableKey, List[ReflectedCheckConstraint]]
]
Return information about check constraints in all tables
in the given schema
.
This is an internal dialect method. Applications should use
:meth:.Inspector.get_multi_check_constraints
.
.. note:: The :class:_engine.DefaultDialect
provides a default
implementation that will call the single table method for
each object returned by :meth:Dialect.get_table_names
,
:meth:Dialect.get_view_names
or
:meth:Dialect.get_materialized_view_names
depending on the
provided kind
. Dialects that want to support a faster
implementation should implement this method.
.. versionadded:: 2.0
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_table_options
get_table_options(
connection: Connection,
table_name: str,
schema: Optional[str] = None,
**kw: Any,
) -> Dict[str, Any]
Return a dictionary of options specified when table_name
was created.
This is an internal dialect method. Applications should use
:meth:_engine.Inspector.get_table_options
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_multi_table_options
get_multi_table_options(
connection: Connection,
schema: Optional[str] = None,
filter_names: Optional[Collection[str]] = None,
**kw: Any,
) -> Iterable[Tuple[TableKey, Dict[str, Any]]]
Return a dictionary of options specified when the tables in the given schema were created.
This is an internal dialect method. Applications should use
:meth:_engine.Inspector.get_multi_table_options
.
.. note:: The :class:_engine.DefaultDialect
provides a default
implementation that will call the single table method for
each object returned by :meth:Dialect.get_table_names
,
:meth:Dialect.get_view_names
or
:meth:Dialect.get_materialized_view_names
depending on the
provided kind
. Dialects that want to support a faster
implementation should implement this method.
.. versionadded:: 2.0
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_table_comment
get_table_comment(
connection: Connection,
table_name: str,
schema: Optional[str] = None,
**kw: Any,
) -> ReflectedTableComment
Return the "comment" for the table identified by table_name
.
Given a string table_name
and an optional string schema
, return
table comment information as a dictionary corresponding to the
:class:.ReflectedTableComment
dictionary.
This is an internal dialect method. Applications should use
:meth:.Inspector.get_table_comment
.
:raise: NotImplementedError
for dialects that don't support
comments.
.. versionadded:: 1.2
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_multi_table_comment
get_multi_table_comment(
connection: Connection,
schema: Optional[str] = None,
filter_names: Optional[Collection[str]] = None,
**kw: Any,
) -> Iterable[Tuple[TableKey, ReflectedTableComment]]
Return information about the table comment in all tables
in the given schema
.
This is an internal dialect method. Applications should use
:meth:_engine.Inspector.get_multi_table_comment
.
.. note:: The :class:_engine.DefaultDialect
provides a default
implementation that will call the single table method for
each object returned by :meth:Dialect.get_table_names
,
:meth:Dialect.get_view_names
or
:meth:Dialect.get_materialized_view_names
depending on the
provided kind
. Dialects that want to support a faster
implementation should implement this method.
.. versionadded:: 2.0
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
normalize_name
convert the given name to lowercase if it is detected as case insensitive.
This method is only used if the dialect defines requires_name_normalize=True.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
denormalize_name
convert the given name to a case insensitive identifier for the backend if it is an all-lowercase name.
This method is only used if the dialect defines requires_name_normalize=True.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
has_table
has_table(
connection: Connection,
table_name: str,
schema: Optional[str] = None,
**kw: Any,
) -> bool
For internal dialect use, check the existence of a particular table or view in the database.
Given a :class:_engine.Connection
object, a string table_name and
optional schema name, return True if the given table exists in the
database, False otherwise.
This method serves as the underlying implementation of the
public facing :meth:.Inspector.has_table
method, and is also used
internally to implement the "checkfirst" behavior for methods like
:meth:_schema.Table.create
and :meth:_schema.MetaData.create_all
.
.. note:: This method is used internally by SQLAlchemy, and is
published so that third-party dialects may provide an
implementation. It is not the public API for checking for table
presence. Please use the :meth:.Inspector.has_table
method.
.. versionchanged:: 2.0:: :meth:_engine.Dialect.has_table
now
formally supports checking for additional table-like objects:
- any type of views (plain or materialized)
- temporary tables of any kind
Previously, these two checks were not formally specified and different dialects would vary in their behavior. The dialect testing suite now includes tests for all of these object types, and dialects to the degree that the backing database supports views or temporary tables should seek to support locating these objects for full compliance.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
has_index
has_index(
connection: Connection,
table_name: str,
index_name: str,
schema: Optional[str] = None,
**kw: Any,
) -> bool
Check the existence of a particular index name in the database.
Given a :class:_engine.Connection
object, a string
table_name
and string index name, return True
if an index of
the given name on the given table exists, False
otherwise.
The :class:.DefaultDialect
implements this in terms of the
:meth:.Dialect.has_table
and :meth:.Dialect.get_indexes
methods,
however dialects can implement a more performant version.
This is an internal dialect method. Applications should use
:meth:_engine.Inspector.has_index
.
.. versionadded:: 1.4
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
has_sequence
has_sequence(
connection: Connection,
sequence_name: str,
schema: Optional[str] = None,
**kw: Any,
) -> bool
Check the existence of a particular sequence in the database.
Given a :class:_engine.Connection
object and a string
sequence_name
, return True
if the given sequence exists in
the database, False
otherwise.
This is an internal dialect method. Applications should use
:meth:_engine.Inspector.has_sequence
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
has_schema
has_schema(
connection: Connection, schema_name: str, **kw: Any
) -> bool
Check the existence of a particular schema name in the database.
Given a :class:_engine.Connection
object, a string
schema_name
, return True
if a schema of the
given exists, False
otherwise.
The :class:.DefaultDialect
implements this by checking
the presence of schema_name
among the schemas returned by
:meth:.Dialect.get_schema_names
,
however dialects can implement a more performant version.
This is an internal dialect method. Applications should use
:meth:_engine.Inspector.has_schema
.
.. versionadded:: 2.0
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
do_begin
do_begin(dbapi_connection: PoolProxiedConnection) -> None
Provide an implementation of connection.begin()
, given a
DB-API connection.
The DBAPI has no dedicated "begin" method and it is expected that transactions are implicit. This hook is provided for those DBAPIs that might need additional help in this area.
:param dbapi_connection: a DBAPI connection, typically
proxied within a :class:.ConnectionFairy
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
do_rollback
do_rollback(
dbapi_connection: PoolProxiedConnection,
) -> None
Provide an implementation of connection.rollback()
, given
a DB-API connection.
:param dbapi_connection: a DBAPI connection, typically
proxied within a :class:.ConnectionFairy
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
do_commit
do_commit(dbapi_connection: PoolProxiedConnection) -> None
Provide an implementation of connection.commit()
, given a
DB-API connection.
:param dbapi_connection: a DBAPI connection, typically
proxied within a :class:.ConnectionFairy
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
do_terminate
do_terminate(dbapi_connection: DBAPIConnection) -> None
Provide an implementation of connection.close()
that tries as
much as possible to not block, given a DBAPI
connection.
In the vast majority of cases this just calls .close(), however for some asyncio dialects may call upon different API features.
This hook is called by the :class:_pool.Pool
when a connection is being recycled or has been invalidated.
.. versionadded:: 1.4.41
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
do_close
do_close(dbapi_connection: DBAPIConnection) -> None
Provide an implementation of connection.close()
, given a DBAPI
connection.
This hook is called by the :class:_pool.Pool
when a connection has been
detached from the pool, or is being returned beyond the normal
capacity of the pool.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
do_ping
do_ping(dbapi_connection: DBAPIConnection) -> bool
ping the DBAPI connection and return True if the connection is usable.
do_set_input_sizes
do_set_input_sizes(
cursor: DBAPICursor,
list_of_tuples: _GenericSetInputSizesType,
context: ExecutionContext,
) -> Any
invoke the cursor.setinputsizes() method with appropriate arguments
This hook is called if the :attr:.Dialect.bind_typing
attribute is
set to the
:attr:.BindTyping.SETINPUTSIZES
value.
Parameter data is passed in a list of tuples (paramname, dbtype,
sqltype), where paramname
is the key of the parameter in the
statement, dbtype
is the DBAPI datatype and sqltype
is the
SQLAlchemy type. The order of tuples is in the correct parameter order.
.. versionadded:: 1.4
.. versionchanged:: 2.0 - setinputsizes mode is now enabled by
setting :attr:.Dialect.bind_typing
to
:attr:.BindTyping.SETINPUTSIZES
. Dialects which accept
a use_setinputsizes
parameter should set this value
appropriately.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
create_xid
create_xid() -> Any
Create a two-phase transaction ID.
This id will be passed to do_begin_twophase(), do_rollback_twophase(), do_commit_twophase(). Its format is unspecified.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
do_savepoint
do_savepoint(connection: Connection, name: str) -> None
Create a savepoint with the given name.
:param connection: a :class:_engine.Connection
.
:param name: savepoint name.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
do_rollback_to_savepoint
do_rollback_to_savepoint(
connection: Connection, name: str
) -> None
Rollback a connection to the named savepoint.
:param connection: a :class:_engine.Connection
.
:param name: savepoint name.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
do_release_savepoint
do_release_savepoint(
connection: Connection, name: str
) -> None
Release the named savepoint on a connection.
:param connection: a :class:_engine.Connection
.
:param name: savepoint name.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
do_begin_twophase
do_begin_twophase(connection: Connection, xid: Any) -> None
Begin a two phase transaction on the given connection.
:param connection: a :class:_engine.Connection
.
:param xid: xid
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
do_prepare_twophase
do_prepare_twophase(
connection: Connection, xid: Any
) -> None
Prepare a two phase transaction on the given connection.
:param connection: a :class:_engine.Connection
.
:param xid: xid
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
do_rollback_twophase
do_rollback_twophase(
connection: Connection,
xid: Any,
is_prepared: bool = True,
recover: bool = False,
) -> None
Rollback a two phase transaction on the given connection.
:param connection: a :class:_engine.Connection
.
:param xid: xid
:param is_prepared: whether or not
:meth:.TwoPhaseTransaction.prepare
was called.
:param recover: if the recover flag was passed.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
do_commit_twophase
do_commit_twophase(
connection: Connection,
xid: Any,
is_prepared: bool = True,
recover: bool = False,
) -> None
Commit a two phase transaction on the given connection.
:param connection: a :class:_engine.Connection
.
:param xid: xid
:param is_prepared: whether or not
:meth:.TwoPhaseTransaction.prepare
was called.
:param recover: if the recover flag was passed.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
do_recover_twophase
do_recover_twophase(connection: Connection) -> List[Any]
Recover list of uncommitted prepared two phase transaction identifiers on the given connection.
:param connection: a :class:_engine.Connection
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
do_executemany
do_executemany(
cursor: DBAPICursor,
statement: str,
parameters: _DBAPIMultiExecuteParams,
context: Optional[ExecutionContext] = None,
) -> None
Provide an implementation of cursor.executemany(statement,
parameters)
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
do_execute
do_execute(
cursor: DBAPICursor,
statement: str,
parameters: Optional[_DBAPISingleExecuteParams],
context: Optional[ExecutionContext] = None,
) -> None
Provide an implementation of cursor.execute(statement,
parameters)
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
do_execute_no_params
do_execute_no_params(
cursor: DBAPICursor,
statement: str,
context: Optional[ExecutionContext] = None,
) -> None
Provide an implementation of cursor.execute(statement)
.
The parameter collection should not be sent.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
is_disconnect
is_disconnect(
e: Exception,
connection: Optional[
Union[PoolProxiedConnection, DBAPIConnection]
],
cursor: Optional[DBAPICursor],
) -> bool
Return True if the given DB-API error indicates an invalid connection
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
connect
connect(*cargs: Any, **cparams: Any) -> DBAPIConnection
Establish a connection using this dialect's DBAPI.
The default implementation of this method is::
def connect(self, *cargs, **cparams):
return self.dbapi.connect(*cargs, **cparams)
The *cargs, **cparams
parameters are generated directly
from this dialect's :meth:.Dialect.create_connect_args
method.
This method may be used for dialects that need to perform programmatic per-connection steps when a new connection is procured from the DBAPI.
:param *cargs: positional parameters returned from the
:meth:.Dialect.create_connect_args
method
:param **cparams: keyword parameters returned from the
:meth:.Dialect.create_connect_args
method.
:return: a DBAPI connection, typically from the :pep:249
module
level .connect()
function.
.. seealso::
:meth:`.Dialect.create_connect_args`
:meth:`.Dialect.on_connect`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
on_connect_url
return a callable which sets up a newly created DBAPI connection.
This method is a new hook that supersedes the
:meth:_engine.Dialect.on_connect
method when implemented by a
dialect. When not implemented by a dialect, it invokes the
:meth:_engine.Dialect.on_connect
method directly to maintain
compatibility with existing dialects. There is no deprecation
for :meth:_engine.Dialect.on_connect
expected.
The callable should accept a single argument "conn" which is the DBAPI connection itself. The inner callable has no return value.
E.g.::
class MyDialect(default.DefaultDialect):
# ...
def on_connect_url(self, url):
def do_on_connect(connection):
connection.execute("SET SPECIAL FLAGS etc")
return do_on_connect
This is used to set dialect-wide per-connection options such as isolation modes, Unicode modes, etc.
This method differs from :meth:_engine.Dialect.on_connect
in that
it is passed the :class:_engine.URL
object that's relevant to the
connect args. Normally the only way to get this is from the
:meth:_engine.Dialect.on_connect
hook is to look on the
:class:_engine.Engine
itself, however this URL object may have been
replaced by plugins.
.. note::
The default implementation of
:meth:`_engine.Dialect.on_connect_url` is to invoke the
:meth:`_engine.Dialect.on_connect` method. Therefore if a dialect
implements this method, the :meth:`_engine.Dialect.on_connect`
method **will not be called** unless the overriding dialect calls
it directly from here.
.. versionadded:: 1.4.3 added :meth:_engine.Dialect.on_connect_url
which normally calls into :meth:_engine.Dialect.on_connect
.
:param url: a :class:_engine.URL
object representing the
:class:_engine.URL
that was passed to the
:meth:_engine.Dialect.create_connect_args
method.
:return: a callable that accepts a single DBAPI connection as an argument, or None.
.. seealso::
:meth:`_engine.Dialect.on_connect`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
on_connect
return a callable which sets up a newly created DBAPI connection.
The callable should accept a single argument "conn" which is the DBAPI connection itself. The inner callable has no return value.
E.g.::
class MyDialect(default.DefaultDialect):
# ...
def on_connect(self):
def do_on_connect(connection):
connection.execute("SET SPECIAL FLAGS etc")
return do_on_connect
This is used to set dialect-wide per-connection options such as isolation modes, Unicode modes, etc.
The "do_on_connect" callable is invoked by using the
:meth:_events.PoolEvents.connect
event
hook, then unwrapping the DBAPI connection and passing it into the
callable.
.. versionchanged:: 1.4 the on_connect hook is no longer called twice
for the first connection of a dialect. The on_connect hook is still
called before the :meth:_engine.Dialect.initialize
method however.
.. versionchanged:: 1.4.3 the on_connect hook is invoked from a new method on_connect_url that passes the URL that was used to create the connect args. Dialects can implement on_connect_url instead of on_connect if they need the URL object that was used for the connection in order to get additional context.
If None is returned, no event listener is generated.
:return: a callable that accepts a single DBAPI connection as an argument, or None.
.. seealso::
:meth:`.Dialect.connect` - allows the DBAPI ``connect()`` sequence
itself to be controlled.
:meth:`.Dialect.on_connect_url` - supersedes
:meth:`.Dialect.on_connect` to also receive the
:class:`_engine.URL` object in context.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
reset_isolation_level
reset_isolation_level(
dbapi_connection: DBAPIConnection,
) -> None
Given a DBAPI connection, revert its isolation to the default.
Note that this is a dialect-level method which is used as part
of the implementation of the :class:_engine.Connection
and
:class:_engine.Engine
isolation level facilities; these APIs should be preferred for
most typical use cases.
.. seealso::
:meth:`_engine.Connection.get_isolation_level`
- view current level
:attr:`_engine.Connection.default_isolation_level`
- view default level
:paramref:`.Connection.execution_options.isolation_level` -
set per :class:`_engine.Connection` isolation level
:paramref:`_sa.create_engine.isolation_level` -
set per :class:`_engine.Engine` isolation level
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
set_isolation_level
set_isolation_level(
dbapi_connection: DBAPIConnection, level: IsolationLevel
) -> None
Given a DBAPI connection, set its isolation level.
Note that this is a dialect-level method which is used as part
of the implementation of the :class:_engine.Connection
and
:class:_engine.Engine
isolation level facilities; these APIs should be preferred for
most typical use cases.
If the dialect also implements the
:meth:.Dialect.get_isolation_level_values
method, then the given
level is guaranteed to be one of the string names within that sequence,
and the method will not need to anticipate a lookup failure.
.. seealso::
:meth:`_engine.Connection.get_isolation_level`
- view current level
:attr:`_engine.Connection.default_isolation_level`
- view default level
:paramref:`.Connection.execution_options.isolation_level` -
set per :class:`_engine.Connection` isolation level
:paramref:`_sa.create_engine.isolation_level` -
set per :class:`_engine.Engine` isolation level
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_isolation_level
get_isolation_level(
dbapi_connection: DBAPIConnection,
) -> IsolationLevel
Given a DBAPI connection, return its isolation level.
When working with a :class:_engine.Connection
object,
the corresponding
DBAPI connection may be procured using the
:attr:_engine.Connection.connection
accessor.
Note that this is a dialect-level method which is used as part
of the implementation of the :class:_engine.Connection
and
:class:_engine.Engine
isolation level facilities;
these APIs should be preferred for most typical use cases.
.. seealso::
:meth:`_engine.Connection.get_isolation_level`
- view current level
:attr:`_engine.Connection.default_isolation_level`
- view default level
:paramref:`.Connection.execution_options.isolation_level` -
set per :class:`_engine.Connection` isolation level
:paramref:`_sa.create_engine.isolation_level` -
set per :class:`_engine.Engine` isolation level
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_default_isolation_level
get_default_isolation_level(
dbapi_conn: DBAPIConnection,
) -> IsolationLevel
Given a DBAPI connection, return its isolation level, or a default isolation level if one cannot be retrieved.
This method may only raise NotImplementedError and must not raise any other exception, as it is used implicitly upon first connect.
The method must return a value for a dialect that supports isolation level settings, as this level is what will be reverted towards when a per-connection isolation level change is made.
The method defaults to using the :meth:.Dialect.get_isolation_level
method unless overridden by a dialect.
.. versionadded:: 1.3.22
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_isolation_level_values
get_isolation_level_values(
dbapi_conn: DBAPIConnection,
) -> List[IsolationLevel]
return a sequence of string isolation level names that are accepted by this dialect.
The available names should use the following conventions:
- use UPPERCASE names. isolation level methods will accept lowercase names but these are normalized into UPPERCASE before being passed along to the dialect.
- separate words should be separated by spaces, not underscores, e.g.
REPEATABLE READ
. isolation level names will have underscores converted to spaces before being passed along to the dialect. - The names for the four standard isolation names to the extent that
they are supported by the backend should be
READ UNCOMMITTED
READ COMMITTED
,REPEATABLE READ
,SERIALIZABLE
- if the dialect supports an autocommit option it should be provided
using the isolation level name
AUTOCOMMIT
. - Other isolation modes may also be present, provided that they are named in UPPERCASE and use spaces not underscores.
This function is used so that the default dialect can check that
a given isolation level parameter is valid, else raises an
:class:_exc.ArgumentError
.
A DBAPI connection is passed to the method, in the unlikely event that the dialect needs to interrogate the connection itself to determine this list, however it is expected that most backends will return a hardcoded list of values. If the dialect supports "AUTOCOMMIT", that value should also be present in the sequence returned.
The method raises NotImplementedError
by default. If a dialect
does not implement this method, then the default dialect will not
perform any checking on a given isolation level value before passing
it onto the :meth:.Dialect.set_isolation_level
method. This is
to allow backwards-compatibility with third party dialects that may
not yet be implementing this method.
.. versionadded:: 2.0
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_dialect_cls
classmethod
Given a URL, return the :class:.Dialect
that will be used.
This is a hook that allows an external plugin to provide functionality around an existing dialect, by allowing the plugin to be loaded from the url based on an entrypoint, and then the plugin returns the actual dialect to be used.
By default this just returns the cls.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_async_dialect_cls
classmethod
Given a URL, return the :class:.Dialect
that will be used by
an async engine.
By default this is an alias of :meth:.Dialect.get_dialect_cls
and
just returns the cls. It may be used if a dialect provides
both a sync and async version under the same name, like the
psycopg
driver.
.. versionadded:: 2
.. seealso::
:meth:`.Dialect.get_dialect_cls`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
load_provisioning
classmethod
set up the provision.py module for this dialect.
For dialects that include a provision.py module that sets up provisioning followers, this method should initiate that process.
A typical implementation would be::
@classmethod
def load_provisioning(cls):
__import__("mydialect.provision")
The default method assumes a module named provision.py
inside
the owning package of the current dialect, based on the __module__
attribute::
@classmethod
def load_provisioning(cls):
package = ".".join(cls.__module__.split(".")[0:-1])
try:
__import__(package + ".provision")
except ImportError:
pass
.. versionadded:: 1.3.14
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
engine_created
classmethod
engine_created(engine: Engine) -> None
A convenience hook called before returning the final
:class:_engine.Engine
.
If the dialect returned a different class from the
:meth:.get_dialect_cls
method, then the hook is called on both classes, first on
the dialect class returned by the :meth:.get_dialect_cls
method and
then on the class on which the method was called.
The hook should be used by dialects and/or wrappers to apply special events to the engine or its components. In particular, it allows a dialect-wrapping class to apply dialect-level events.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_driver_connection
get_driver_connection(connection: DBAPIConnection) -> Any
Returns the connection object as returned by the external driver package.
For normal dialects that use a DBAPI compliant driver this call
will just return the connection
passed as argument.
For dialects that instead adapt a non DBAPI compliant driver, like
when adapting an asyncio driver, this call will return the
connection-like object as returned by the driver.
.. versionadded:: 1.4.24
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
set_engine_execution_options
set_engine_execution_options(
engine: Engine, opts: CoreExecuteOptionsParameter
) -> None
Establish execution options for a given engine.
This is implemented by :class:.DefaultDialect
to establish
event hooks for new :class:.Connection
instances created
by the given :class:.Engine
which will then invoke the
:meth:.Dialect.set_connection_execution_options
method for that
connection.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
set_connection_execution_options
set_connection_execution_options(
connection: Connection,
opts: CoreExecuteOptionsParameter,
) -> None
Establish execution options for a given connection.
This is implemented by :class:.DefaultDialect
in order to implement
the :paramref:_engine.Connection.execution_options.isolation_level
execution option. Dialects can intercept various execution options
which may need to modify state on a particular DBAPI connection.
.. versionadded:: 1.4
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
get_dialect_pool_class
Engine
Engine(
pool: Pool,
dialect: Dialect,
url: URL,
logging_name: Optional[str] = None,
echo: Optional[_EchoFlagType] = None,
query_cache_size: int = 500,
execution_options: Optional[Mapping[str, Any]] = None,
hide_parameters: bool = False,
)
Bases: ConnectionEventsTarget
, Identified
, Inspectable['Inspector']
Connects a :class:~sqlalchemy.pool.Pool
and
:class:~sqlalchemy.engine.interfaces.Dialect
together to provide a
source of database connectivity and behavior.
An :class:_engine.Engine
object is instantiated publicly using the
:func:~sqlalchemy.create_engine
function.
.. seealso::
:doc:`/core/engines`
:ref:`connections_toplevel`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
engine
property
engine: Engine
Returns this :class:.Engine
.
Used for legacy schemes that accept :class:.Connection
/
:class:.Engine
objects within the same variable.
name
property
name: str
String name of the :class:~sqlalchemy.engine.interfaces.Dialect
in use by this :class:Engine
.
driver
property
driver: str
Driver name of the :class:~sqlalchemy.engine.interfaces.Dialect
in use by this :class:Engine
.
clear_compiled_cache
Clear the compiled cache associated with the dialect.
This applies only to the built-in cache that is established
via the :paramref:_engine.create_engine.query_cache_size
parameter.
It will not impact any dictionary caches that were passed via the
:paramref:.Connection.execution_options.compiled_cache
parameter.
.. versionadded:: 1.4
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
update_execution_options
update_execution_options(**opt: Any) -> None
Update the default execution_options dictionary
of this :class:_engine.Engine
.
The given keys/values in **opt are added to the
default execution options that will be used for
all connections. The initial contents of this dictionary
can be sent via the execution_options
parameter
to :func:_sa.create_engine
.
.. seealso::
:meth:`_engine.Connection.execution_options`
:meth:`_engine.Engine.execution_options`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
execution_options
execution_options(
*,
compiled_cache: Optional[CompiledCacheType] = ...,
logging_token: str = ...,
isolation_level: IsolationLevel = ...,
insertmanyvalues_page_size: int = ...,
schema_translate_map: Optional[
SchemaTranslateMapType
] = ...,
**opt: Any,
) -> OptionEngine
execution_options(**opt: Any) -> OptionEngine
execution_options(**opt: Any) -> OptionEngine
Return a new :class:_engine.Engine
that will provide
:class:_engine.Connection
objects with the given execution options.
The returned :class:_engine.Engine
remains related to the original
:class:_engine.Engine
in that it shares the same connection pool and
other state:
- The :class:
_pool.Pool
used by the new :class:_engine.Engine
is the same instance. The :meth:_engine.Engine.dispose
method will replace the connection pool instance for the parent engine as well as this one. - Event listeners are "cascaded" - meaning, the new
:class:
_engine.Engine
inherits the events of the parent, and new events can be associated with the new :class:_engine.Engine
individually. - The logging configuration and logging_name is copied from the parent
:class:
_engine.Engine
.
The intent of the :meth:_engine.Engine.execution_options
method is
to implement schemes where multiple :class:_engine.Engine
objects refer to the same connection pool, but are differentiated
by options that affect some execution-level behavior for each
engine. One such example is breaking into separate "reader" and
"writer" :class:_engine.Engine
instances, where one
:class:_engine.Engine
has a lower :term:isolation level
setting configured or is even
transaction-disabled using "autocommit". An example of this
configuration is at :ref:dbapi_autocommit_multiple
.
Another example is one that
uses a custom option shard_id
which is consumed by an event
to change the current schema on a database connection::
from sqlalchemy import event
from sqlalchemy.engine import Engine
primary_engine = create_engine("mysql+mysqldb://")
shard1 = primary_engine.execution_options(shard_id="shard1")
shard2 = primary_engine.execution_options(shard_id="shard2")
shards = {"default": "base", "shard_1": "db1", "shard_2": "db2"}
@event.listens_for(Engine, "before_cursor_execute")
def _switch_shard(conn, cursor, stmt,
params, context, executemany):
shard_id = conn.get_execution_options().get('shard_id', "default")
current_shard = conn.info.get("current_shard", None)
if current_shard != shard_id:
cursor.execute("use %s" % shards[shard_id])
conn.info["current_shard"] = shard_id
The above recipe illustrates two :class:_engine.Engine
objects that
will each serve as factories for :class:_engine.Connection
objects
that have pre-established "shard_id" execution options present. A
:meth:_events.ConnectionEvents.before_cursor_execute
event handler
then interprets this execution option to emit a MySQL use
statement
to switch databases before a statement execution, while at the same
time keeping track of which database we've established using the
:attr:_engine.Connection.info
dictionary.
.. seealso::
:meth:`_engine.Connection.execution_options`
- update execution options
on a :class:`_engine.Connection` object.
:meth:`_engine.Engine.update_execution_options`
- update the execution
options for a given :class:`_engine.Engine` in place.
:meth:`_engine.Engine.get_execution_options`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 |
|
get_execution_options
Get the non-SQL options which will take effect during execution.
.. versionadded: 1.3
.. seealso::
:meth:`_engine.Engine.execution_options`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
dispose
dispose(close: bool = True) -> None
Dispose of the connection pool used by this
:class:_engine.Engine
.
A new connection pool is created immediately after the old one has been disposed. The previous connection pool is disposed either actively, by closing out all currently checked-in connections in that pool, or passively, by losing references to it but otherwise not closing any connections. The latter strategy is more appropriate for an initializer in a forked Python process.
:param close: if left at its default of True
, has the
effect of fully closing all currently checked in
database connections. Connections that are still checked out
will not be closed, however they will no longer be associated
with this :class:_engine.Engine
,
so when they are closed individually, eventually the
:class:_pool.Pool
which they are associated with will
be garbage collected and they will be closed out fully, if
not already closed on checkin.
If set to False
, the previous connection pool is de-referenced,
and otherwise not touched in any way.
.. versionadded:: 1.4.33 Added the :paramref:.Engine.dispose.close
parameter to allow the replacement of a connection pool in a child
process without interfering with the connections used by the parent
process.
.. seealso::
:ref:`engine_disposal`
:ref:`pooling_multiprocessing`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
begin
begin() -> Iterator[Connection]
Return a context manager delivering a :class:_engine.Connection
with a :class:.Transaction
established.
E.g.::
with engine.begin() as conn:
conn.execute(
text("insert into table (x, y, z) values (1, 2, 3)")
)
conn.execute(text("my_special_procedure(5)"))
Upon successful operation, the :class:.Transaction
is committed. If an error is raised, the :class:.Transaction
is rolled back.
.. seealso::
:meth:`_engine.Engine.connect` - procure a
:class:`_engine.Connection` from
an :class:`_engine.Engine`.
:meth:`_engine.Connection.begin` - start a :class:`.Transaction`
for a particular :class:`_engine.Connection`.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
connect
connect() -> Connection
Return a new :class:_engine.Connection
object.
The :class:_engine.Connection
acts as a Python context manager, so
the typical use of this method looks like::
with engine.connect() as connection:
connection.execute(text("insert into table values ('foo')"))
connection.commit()
Where above, after the block is completed, the connection is "closed"
and its underlying DBAPI resources are returned to the connection pool.
This also has the effect of rolling back any transaction that
was explicitly begun or was begun via autobegin, and will
emit the :meth:_events.ConnectionEvents.rollback
event if one was
started and is still in progress.
.. seealso::
:meth:`_engine.Engine.begin`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
raw_connection
raw_connection() -> PoolProxiedConnection
Return a "raw" DBAPI connection from the connection pool.
The returned object is a proxied version of the DBAPI
connection object used by the underlying driver in use.
The object will have all the same behavior as the real DBAPI
connection, except that its close()
method will result in the
connection being returned to the pool, rather than being closed
for real.
This method provides direct DBAPI connection access for
special situations when the API provided by
:class:_engine.Connection
is not needed. When a :class:_engine.Connection
object is already
present, the DBAPI connection is available using
the :attr:_engine.Connection.connection
accessor.
.. seealso::
:ref:`dbapi_connections`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
MappingResult
Bases: _WithKeys
, FilterResult[RowMapping]
A wrapper for a :class:_engine.Result
that returns dictionary values
rather than :class:_engine.Row
values.
The :class:_engine.MappingResult
object is acquired by calling the
:meth:_engine.Result.mappings
method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
closed
property
closed: bool
Return True
if the underlying :class:_engine.Result
reports
closed
.. versionadded:: 1.4.43
memoized_attribute
Bases: memoized_property[_T]
A read-only @property that is only evaluated once.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
memoized_instancemethod
classmethod
Decorate a method memoize its return value.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
yield_per
yield_per(num: int) -> Self
Configure the row-fetching strategy to fetch num
rows at a time.
The :meth:_engine.FilterResult.yield_per
method is a pass through
to the :meth:_engine.Result.yield_per
method. See that method's
documentation for usage notes.
.. versionadded:: 1.4.40 - added :meth:_engine.FilterResult.yield_per
so that the method is available on all result set implementations
.. seealso::
:ref:`engine_stream_results` - describes Core behavior for
:meth:`_engine.Result.yield_per`
:ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
close
Close this :class:_engine.FilterResult
.
.. versionadded:: 1.4.43
keys
Return an iterable view which yields the string keys that would
be represented by each :class:_engine.Row
.
The keys can represent the labels of the columns returned by a core statement or the names of the orm classes returned by an orm execution.
The view also can be tested for key containment using the Python
in
operator, which will test both for the string keys represented
in the view, as well as for alternate keys such as column objects.
.. versionchanged:: 1.4 a key view object is returned rather than a plain list.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
unique
unique(
strategy: Optional[_UniqueFilterType] = None,
) -> Self
Apply unique filtering to the objects returned by this
:class:_engine.MappingResult
.
See :meth:_engine.Result.unique
for usage details.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
columns
Establish the columns that should be returned in each row.
partitions
partitions(
size: Optional[int] = None,
) -> Iterator[Sequence[RowMapping]]
Iterate through sub-lists of elements of the size given.
Equivalent to :meth:_engine.Result.partitions
except that
:class:_engine.RowMapping
values, rather than :class:_engine.Row
objects, are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
fetchall
fetchall() -> Sequence[RowMapping]
fetchone
fetchone() -> Optional[RowMapping]
Fetch one object.
Equivalent to :meth:_engine.Result.fetchone
except that
:class:_engine.RowMapping
values, rather than :class:_engine.Row
objects, are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
fetchmany
fetchmany(
size: Optional[int] = None,
) -> Sequence[RowMapping]
Fetch many objects.
Equivalent to :meth:_engine.Result.fetchmany
except that
:class:_engine.RowMapping
values, rather than :class:_engine.Row
objects, are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
all
all() -> Sequence[RowMapping]
Return all scalar values in a sequence.
Equivalent to :meth:_engine.Result.all
except that
:class:_engine.RowMapping
values, rather than :class:_engine.Row
objects, are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
first
first() -> Optional[RowMapping]
Fetch the first object or None
if no object is present.
Equivalent to :meth:_engine.Result.first
except that
:class:_engine.RowMapping
values, rather than :class:_engine.Row
objects, are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
one_or_none
one_or_none() -> Optional[RowMapping]
Return at most one object or raise an exception.
Equivalent to :meth:_engine.Result.one_or_none
except that
:class:_engine.RowMapping
values, rather than :class:_engine.Row
objects, are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
one
one() -> RowMapping
Return exactly one object or raise an exception.
Equivalent to :meth:_engine.Result.one
except that
:class:_engine.RowMapping
values, rather than :class:_engine.Row
objects, are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
Result
Bases: _WithKeys
, ResultInternal[Row[_TP]]
Represent a set of database results.
.. versionadded:: 1.4 The :class:_engine.Result
object provides a
completely updated usage model and calling facade for SQLAlchemy
Core and SQLAlchemy ORM. In Core, it forms the basis of the
:class:_engine.CursorResult
object which replaces the previous
:class:_engine.ResultProxy
interface. When using the ORM, a
higher level object called :class:_engine.ChunkedIteratorResult
is normally used.
.. note:: In SQLAlchemy 1.4 and above, this object is
used for ORM results returned by :meth:_orm.Session.execute
, which can
yield instances of ORM mapped objects either individually or within
tuple-like rows. Note that the :class:_engine.Result
object does not
deduplicate instances or rows automatically as is the case with the
legacy :class:_orm.Query
object. For in-Python de-duplication of
instances or rows, use the :meth:_engine.Result.unique
modifier
method.
.. seealso::
:ref:`tutorial_fetching_rows` - in the :doc:`/tutorial/index`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
closed
property
closed: bool
return True
if this :class:_engine.Result
reports .closed
.. versionadded:: 1.4.43
t
property
t: TupleResult[_TP]
Apply a "typed tuple" typing filter to returned rows.
The :attr:_engine.Result.t
attribute is a synonym for
calling the :meth:_engine.Result.tuples
method.
.. versionadded:: 2.0
memoized_attribute
Bases: memoized_property[_T]
A read-only @property that is only evaluated once.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
memoized_instancemethod
classmethod
Decorate a method memoize its return value.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
keys
Return an iterable view which yields the string keys that would
be represented by each :class:_engine.Row
.
The keys can represent the labels of the columns returned by a core statement or the names of the orm classes returned by an orm execution.
The view also can be tested for key containment using the Python
in
operator, which will test both for the string keys represented
in the view, as well as for alternate keys such as column objects.
.. versionchanged:: 1.4 a key view object is returned rather than a plain list.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
close
close this :class:_engine.Result
.
The behavior of this method is implementation specific, and is
not implemented by default. The method should generally end
the resources in use by the result object and also cause any
subsequent iteration or row fetching to raise
:class:.ResourceClosedError
.
.. versionadded:: 1.4.27 - .close()
was previously not generally
available for all :class:_engine.Result
classes, instead only
being available on the :class:_engine.CursorResult
returned for
Core statement executions. As most other result objects, namely the
ones used by the ORM, are proxying a :class:_engine.CursorResult
in any case, this allows the underlying cursor result to be closed
from the outside facade for the case when the ORM query is using
the yield_per
execution option where it does not immediately
exhaust and autoclose the database cursor.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
yield_per
yield_per(num: int) -> Self
Configure the row-fetching strategy to fetch num
rows at a time.
This impacts the underlying behavior of the result when iterating over
the result object, or otherwise making use of methods such as
:meth:_engine.Result.fetchone
that return one row at a time. Data
from the underlying cursor or other data source will be buffered up to
this many rows in memory, and the buffered collection will then be
yielded out one row at a time or as many rows are requested. Each time
the buffer clears, it will be refreshed to this many rows or as many
rows remain if fewer remain.
The :meth:_engine.Result.yield_per
method is generally used in
conjunction with the
:paramref:_engine.Connection.execution_options.stream_results
execution option, which will allow the database dialect in use to make
use of a server side cursor, if the DBAPI supports a specific "server
side cursor" mode separate from its default mode of operation.
.. tip::
Consider using the
:paramref:`_engine.Connection.execution_options.yield_per`
execution option, which will simultaneously set
:paramref:`_engine.Connection.execution_options.stream_results`
to ensure the use of server side cursors, as well as automatically
invoke the :meth:`_engine.Result.yield_per` method to establish
a fixed row buffer size at once.
The :paramref:`_engine.Connection.execution_options.yield_per`
execution option is available for ORM operations, with
:class:`_orm.Session`-oriented use described at
:ref:`orm_queryguide_yield_per`. The Core-only version which works
with :class:`_engine.Connection` is new as of SQLAlchemy 1.4.40.
.. versionadded:: 1.4
:param num: number of rows to fetch each time the buffer is refilled. If set to a value below 1, fetches all rows for the next buffer.
.. seealso::
:ref:`engine_stream_results` - describes Core behavior for
:meth:`_engine.Result.yield_per`
:ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
unique
unique(
strategy: Optional[_UniqueFilterType] = None,
) -> Self
Apply unique filtering to the objects returned by this
:class:_engine.Result
.
When this filter is applied with no arguments, the rows or objects returned will filtered such that each row is returned uniquely. The algorithm used to determine this uniqueness is by default the Python hashing identity of the whole tuple. In some cases a specialized per-entity hashing scheme may be used, such as when using the ORM, a scheme is applied which works against the primary key identity of returned objects.
The unique filter is applied after all other filters, which means
if the columns returned have been refined using a method such as the
:meth:_engine.Result.columns
or :meth:_engine.Result.scalars
method, the uniquing is applied to only the column or columns
returned. This occurs regardless of the order in which these
methods have been called upon the :class:_engine.Result
object.
The unique filter also changes the calculus used for methods like
:meth:_engine.Result.fetchmany
and :meth:_engine.Result.partitions
.
When using :meth:_engine.Result.unique
, these methods will continue
to yield the number of rows or objects requested, after uniquing
has been applied. However, this necessarily impacts the buffering
behavior of the underlying cursor or datasource, such that multiple
underlying calls to cursor.fetchmany()
may be necessary in order
to accumulate enough objects in order to provide a unique collection
of the requested size.
:param strategy: a callable that will be applied to rows or objects
being iterated, which should return an object that represents the
unique value of the row. A Python set()
is used to store
these identities. If not passed, a default uniqueness strategy
is used which may have been assembled by the source of this
:class:_engine.Result
object.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
columns
Establish the columns that should be returned in each row.
This method may be used to limit the columns returned as well
as to reorder them. The given list of expressions are normally
a series of integers or string key names. They may also be
appropriate :class:.ColumnElement
objects which correspond to
a given statement construct.
.. versionchanged:: 2.0 Due to a bug in 1.4, the
:meth:_engine.Result.columns
method had an incorrect behavior
where calling upon the method with just one index would cause the
:class:_engine.Result
object to yield scalar values rather than
:class:_engine.Row
objects. In version 2.0, this behavior
has been corrected such that calling upon
:meth:_engine.Result.columns
with a single index will
produce a :class:_engine.Result
object that continues
to yield :class:_engine.Row
objects, which include
only a single column.
E.g.::
statement = select(table.c.x, table.c.y, table.c.z)
result = connection.execute(statement)
for z, y in result.columns('z', 'y'):
# ...
Example of using the column objects from the statement itself::
for z, y in result.columns(
statement.selected_columns.c.z,
statement.selected_columns.c.y
):
# ...
.. versionadded:: 1.4
:param *col_expressions: indicates columns to be returned. Elements
may be integer row indexes, string column names, or appropriate
:class:.ColumnElement
objects corresponding to a select construct.
:return: this :class:_engine.Result
object with the modifications
given.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
scalars
scalars() -> ScalarResult[_T]
scalars(index: Literal[0]) -> ScalarResult[_T]
scalars(index: _KeyIndexType = 0) -> ScalarResult[Any]
scalars(index: _KeyIndexType = 0) -> ScalarResult[Any]
Return a :class:_engine.ScalarResult
filtering object which
will return single elements rather than :class:_row.Row
objects.
E.g.::
>>> result = conn.execute(text("select int_id from table"))
>>> result.scalars().all()
[1, 2, 3]
When results are fetched from the :class:_engine.ScalarResult
filtering object, the single column-row that would be returned by the
:class:_engine.Result
is instead returned as the column's value.
.. versionadded:: 1.4
:param index: integer or row key indicating the column to be fetched
from each row, defaults to 0
indicating the first column.
:return: a new :class:_engine.ScalarResult
filtering object referring
to this :class:_engine.Result
object.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
mappings
mappings() -> MappingResult
Apply a mappings filter to returned rows, returning an instance of
:class:_engine.MappingResult
.
When this filter is applied, fetching rows will return
:class:_engine.RowMapping
objects instead of :class:_engine.Row
objects.
.. versionadded:: 1.4
:return: a new :class:_engine.MappingResult
filtering object
referring to this :class:_engine.Result
object.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
tuples
tuples() -> TupleResult[_TP]
Apply a "typed tuple" typing filter to returned rows.
This method returns the same :class:_engine.Result
object
at runtime,
however annotates as returning a :class:_engine.TupleResult
object
that will indicate to :pep:484
typing tools that plain typed
Tuple
instances are returned rather than rows. This allows
tuple unpacking and __getitem__
access of :class:_engine.Row
objects to by typed, for those cases where the statement invoked
itself included typing information.
.. versionadded:: 2.0
:return: the :class:_engine.TupleResult
type at typing time.
.. seealso::
:attr:`_engine.Result.t` - shorter synonym
:attr:`_engine.Row._t` - :class:`_engine.Row` version
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
partitions
Iterate through sub-lists of rows of the size given.
Each list will be of the size given, excluding the last list to be yielded, which may have a small number of rows. No empty lists will be yielded.
The result object is automatically closed when the iterator is fully consumed.
Note that the backend driver will usually buffer the entire result
ahead of time unless the
:paramref:.Connection.execution_options.stream_results
execution
option is used indicating that the driver should not pre-buffer
results, if possible. Not all drivers support this option and
the option is silently ignored for those who do not.
When using the ORM, the :meth:_engine.Result.partitions
method
is typically more effective from a memory perspective when it is
combined with use of the
:ref:yield_per execution option <orm_queryguide_yield_per>
,
which instructs both the DBAPI driver to use server side cursors,
if available, as well as instructs the ORM loading internals to only
build a certain amount of ORM objects from a result at a time before
yielding them out.
.. versionadded:: 1.4
:param size: indicate the maximum number of rows to be present
in each list yielded. If None, makes use of the value set by
the :meth:_engine.Result.yield_per
, method, if it were called,
or the :paramref:_engine.Connection.execution_options.yield_per
execution option, which is equivalent in this regard. If
yield_per weren't set, it makes use of the
:meth:_engine.Result.fetchmany
default, which may be backend
specific and not well defined.
:return: iterator of lists
.. seealso::
:ref:`engine_stream_results`
:ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
fetchall
fetchone
Fetch one row.
When all rows are exhausted, returns None.
This method is provided for backwards compatibility with SQLAlchemy 1.x.x.
To fetch the first row of a result only, use the
:meth:_engine.Result.first
method. To iterate through all
rows, iterate the :class:_engine.Result
object directly.
:return: a :class:_engine.Row
object if no filters are applied,
or None
if no rows remain.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
fetchmany
Fetch many rows.
When all rows are exhausted, returns an empty sequence.
This method is provided for backwards compatibility with SQLAlchemy 1.x.x.
To fetch rows in groups, use the :meth:_engine.Result.partitions
method.
:return: a sequence of :class:_engine.Row
objects.
.. seealso::
:meth:`_engine.Result.partitions`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
all
Return all rows in a sequence.
Closes the result set after invocation. Subsequent invocations will return an empty sequence.
.. versionadded:: 1.4
:return: a sequence of :class:_engine.Row
objects.
.. seealso::
:ref:`engine_stream_results` - How to stream a large result set
without loading it completely in python.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
first
Fetch the first row or None
if no row is present.
Closes the result set and discards remaining rows.
.. note:: This method returns one row, e.g. tuple, by default.
To return exactly one single scalar value, that is, the first
column of the first row, use the
:meth:_engine.Result.scalar
method,
or combine :meth:_engine.Result.scalars
and
:meth:_engine.Result.first
.
Additionally, in contrast to the behavior of the legacy ORM
:meth:_orm.Query.first
method, no limit is applied to the
SQL query which was invoked to produce this
:class:_engine.Result
;
for a DBAPI driver that buffers results in memory before yielding
rows, all rows will be sent to the Python process and all but
the first row will be discarded.
.. seealso::
:ref:`migration_20_unify_select`
:return: a :class:_engine.Row
object, or None
if no rows remain.
.. seealso::
:meth:`_engine.Result.scalar`
:meth:`_engine.Result.one`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
one_or_none
Return at most one result or raise an exception.
Returns None
if the result has no rows.
Raises :class:.MultipleResultsFound
if multiple rows are returned.
.. versionadded:: 1.4
:return: The first :class:_engine.Row
or None
if no row
is available.
:raises: :class:.MultipleResultsFound
.. seealso::
:meth:`_engine.Result.first`
:meth:`_engine.Result.one`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
scalar_one
scalar_one() -> Any
scalar_one() -> Any
Return exactly one scalar result or raise an exception.
This is equivalent to calling :meth:_engine.Result.scalars
and
then :meth:_engine.Result.one
.
.. seealso::
:meth:`_engine.Result.one`
:meth:`_engine.Result.scalars`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
scalar_one_or_none
Return exactly one scalar result or None
.
This is equivalent to calling :meth:_engine.Result.scalars
and
then :meth:_engine.Result.one_or_none
.
.. seealso::
:meth:`_engine.Result.one_or_none`
:meth:`_engine.Result.scalars`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
one
one() -> Row[_TP]
Return exactly one row or raise an exception.
Raises :class:.NoResultFound
if the result returns no
rows, or :class:.MultipleResultsFound
if multiple rows
would be returned.
.. note:: This method returns one row, e.g. tuple, by default.
To return exactly one single scalar value, that is, the first
column of the first row, use the
:meth:_engine.Result.scalar_one
method, or combine
:meth:_engine.Result.scalars
and
:meth:_engine.Result.one
.
.. versionadded:: 1.4
:return: The first :class:_engine.Row
.
:raises: :class:.MultipleResultsFound
, :class:.NoResultFound
.. seealso::
:meth:`_engine.Result.first`
:meth:`_engine.Result.one_or_none`
:meth:`_engine.Result.scalar_one`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
scalar
scalar() -> Any
Fetch the first column of the first row, and close the result set.
Returns None
if there are no rows to fetch.
No validation is performed to test if additional rows remain.
After calling this method, the object is fully closed,
e.g. the :meth:_engine.CursorResult.close
method will have been called.
:return: a Python scalar value, or None
if no rows remain.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
freeze
freeze() -> FrozenResult[_TP]
Return a callable object that will produce copies of this
:class:_engine.Result
when invoked.
The callable object returned is an instance of
:class:_engine.FrozenResult
.
This is used for result set caching. The method must be called
on the result when it has been unconsumed, and calling the method
will consume the result fully. When the :class:_engine.FrozenResult
is retrieved from a cache, it can be called any number of times where
it will produce a new :class:_engine.Result
object each time
against its stored set of rows.
.. seealso::
:ref:`do_orm_execute_re_executing` - example usage within the
ORM to implement a result-set cache.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
merge
merge(*others: Result[Any]) -> MergedResult[_TP]
Merge this :class:_engine.Result
with other compatible result
objects.
The object returned is an instance of :class:_engine.MergedResult
,
which will be composed of iterators from the given result
objects.
The new result will use the metadata from this result object. The subsequent result objects must be against an identical set of result / cursor metadata, otherwise the behavior is undefined.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
Row
Bases: BaseRow
, Sequence[Any]
, Generic[_TP]
Represent a single result row.
The :class:.Row
object represents a row of a database result. It is
typically associated in the 1.x series of SQLAlchemy with the
:class:_engine.CursorResult
object, however is also used by the ORM for
tuple-like results as of SQLAlchemy 1.4.
The :class:.Row
object seeks to act as much like a Python named
tuple as possible. For mapping (i.e. dictionary) behavior on a row,
such as testing for containment of keys, refer to the :attr:.Row._mapping
attribute.
.. seealso::
:ref:`tutorial_selecting_data` - includes examples of selecting
rows from SELECT statements.
.. versionchanged:: 1.4
Renamed ``RowProxy`` to :class:`.Row`. :class:`.Row` is no longer a
"proxy" object in that it contains the final form of data within it,
and now acts mostly like a named tuple. Mapping-like functionality is
moved to the :attr:`.Row._mapping` attribute. See
:ref:`change_4710_core` for background on this change.
Row objects are constructed by CursorResult objects.
tuple
Return a 'tuple' form of this :class:.Row
.
.. versionadded:: 2.0
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/row.py
ScalarResult
Bases: FilterResult[_R]
A wrapper for a :class:_engine.Result
that returns scalar values
rather than :class:_row.Row
values.
The :class:_engine.ScalarResult
object is acquired by calling the
:meth:_engine.Result.scalars
method.
A special limitation of :class:_engine.ScalarResult
is that it has
no fetchone()
method; since the semantics of fetchone()
are that
the None
value indicates no more results, this is not compatible
with :class:_engine.ScalarResult
since there is no way to distinguish
between None
as a row value versus None
as an indicator. Use
next(result)
to receive values individually.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
closed
property
closed: bool
Return True
if the underlying :class:_engine.Result
reports
closed
.. versionadded:: 1.4.43
memoized_attribute
Bases: memoized_property[_T]
A read-only @property that is only evaluated once.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
memoized_instancemethod
classmethod
Decorate a method memoize its return value.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
yield_per
yield_per(num: int) -> Self
Configure the row-fetching strategy to fetch num
rows at a time.
The :meth:_engine.FilterResult.yield_per
method is a pass through
to the :meth:_engine.Result.yield_per
method. See that method's
documentation for usage notes.
.. versionadded:: 1.4.40 - added :meth:_engine.FilterResult.yield_per
so that the method is available on all result set implementations
.. seealso::
:ref:`engine_stream_results` - describes Core behavior for
:meth:`_engine.Result.yield_per`
:ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
close
Close this :class:_engine.FilterResult
.
.. versionadded:: 1.4.43
unique
unique(
strategy: Optional[_UniqueFilterType] = None,
) -> Self
Apply unique filtering to the objects returned by this
:class:_engine.ScalarResult
.
See :meth:_engine.Result.unique
for usage details.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
partitions
Iterate through sub-lists of elements of the size given.
Equivalent to :meth:_engine.Result.partitions
except that
scalar values, rather than :class:_engine.Row
objects,
are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
fetchall
fetchall() -> Sequence[_R]
fetchmany
Fetch many objects.
Equivalent to :meth:_engine.Result.fetchmany
except that
scalar values, rather than :class:_engine.Row
objects,
are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
all
all() -> Sequence[_R]
Return all scalar values in a sequence.
Equivalent to :meth:_engine.Result.all
except that
scalar values, rather than :class:_engine.Row
objects,
are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
first
first() -> Optional[_R]
Fetch the first object or None
if no object is present.
Equivalent to :meth:_engine.Result.first
except that
scalar values, rather than :class:_engine.Row
objects,
are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
one_or_none
one_or_none() -> Optional[_R]
Return at most one object or raise an exception.
Equivalent to :meth:_engine.Result.one_or_none
except that
scalar values, rather than :class:_engine.Row
objects,
are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
one
Return exactly one object or raise an exception.
Equivalent to :meth:_engine.Result.one
except that
scalar values, rather than :class:_engine.Row
objects,
are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
Transaction
Transaction(connection: Connection)
Bases: TransactionalContext
Represent a database transaction in progress.
The :class:.Transaction
object is procured by
calling the :meth:_engine.Connection.begin
method of
:class:_engine.Connection
::
from sqlalchemy import create_engine
engine = create_engine("postgresql+psycopg2://scott:tiger@localhost/test")
connection = engine.connect()
trans = connection.begin()
connection.execute(text("insert into x (a, b) values (1, 2)"))
trans.commit()
The object provides :meth:.rollback
and :meth:.commit
methods in order to control transaction boundaries. It
also implements a context manager interface so that
the Python with
statement can be used with the
:meth:_engine.Connection.begin
method::
with connection.begin():
connection.execute(text("insert into x (a, b) values (1, 2)"))
The Transaction object is not threadsafe.
.. seealso::
:meth:`_engine.Connection.begin`
:meth:`_engine.Connection.begin_twophase`
:meth:`_engine.Connection.begin_nested`
.. index:: single: thread safety; Transaction
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
close
Close this :class:.Transaction
.
If this transaction is the base transaction in a begin/commit nesting, the transaction will rollback(). Otherwise, the method returns.
This is used to cancel a Transaction without affecting the scope of an enclosing transaction.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
rollback
Roll back this :class:.Transaction
.
The implementation of this may vary based on the type of transaction in use:
-
For a simple database transaction (e.g. :class:
.RootTransaction
), it corresponds to a ROLLBACK. -
For a :class:
.NestedTransaction
, it corresponds to a "ROLLBACK TO SAVEPOINT" operation. -
For a :class:
.TwoPhaseTransaction
, DBAPI-specific methods for two phase transactions may be used.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
commit
Commit this :class:.Transaction
.
The implementation of this may vary based on the type of transaction in use:
-
For a simple database transaction (e.g. :class:
.RootTransaction
), it corresponds to a COMMIT. -
For a :class:
.NestedTransaction
, it corresponds to a "RELEASE SAVEPOINT" operation. -
For a :class:
.TwoPhaseTransaction
, DBAPI-specific methods for two phase transactions may be used.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
TupleResult
Bases: FilterResult[_R]
, TypingOnly
A :class:_engine.Result
that's typed as returning plain
Python tuples instead of rows.
Since :class:_engine.Row
acts like a tuple in every way already,
this class is a typing only class, regular :class:_engine.Result
is
still used at runtime.
closed
property
closed: bool
Return True
if the underlying :class:_engine.Result
reports
closed
.. versionadded:: 1.4.43
memoized_attribute
Bases: memoized_property[_T]
A read-only @property that is only evaluated once.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
memoized_instancemethod
classmethod
Decorate a method memoize its return value.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
yield_per
yield_per(num: int) -> Self
Configure the row-fetching strategy to fetch num
rows at a time.
The :meth:_engine.FilterResult.yield_per
method is a pass through
to the :meth:_engine.Result.yield_per
method. See that method's
documentation for usage notes.
.. versionadded:: 1.4.40 - added :meth:_engine.FilterResult.yield_per
so that the method is available on all result set implementations
.. seealso::
:ref:`engine_stream_results` - describes Core behavior for
:meth:`_engine.Result.yield_per`
:ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
close
Close this :class:_engine.FilterResult
.
.. versionadded:: 1.4.43
partitions
Iterate through sub-lists of elements of the size given.
Equivalent to :meth:_engine.Result.partitions
except that
tuple values, rather than :class:_engine.Row
objects,
are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
fetchone
fetchone() -> Optional[_R]
Fetch one tuple.
Equivalent to :meth:_engine.Result.fetchone
except that
tuple values, rather than :class:_engine.Row
objects, are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
fetchall
fetchall() -> Sequence[_R]
fetchmany
Fetch many objects.
Equivalent to :meth:_engine.Result.fetchmany
except that
tuple values, rather than :class:_engine.Row
objects,
are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
all
all() -> Sequence[_R]
Return all scalar values in a sequence.
Equivalent to :meth:_engine.Result.all
except that
tuple values, rather than :class:_engine.Row
objects,
are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
first
first() -> Optional[_R]
Fetch the first object or None
if no object is present.
Equivalent to :meth:_engine.Result.first
except that
tuple values, rather than :class:_engine.Row
objects,
are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
one_or_none
one_or_none() -> Optional[_R]
Return at most one object or raise an exception.
Equivalent to :meth:_engine.Result.one_or_none
except that
tuple values, rather than :class:_engine.Row
objects,
are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
one
Return exactly one object or raise an exception.
Equivalent to :meth:_engine.Result.one
except that
tuple values, rather than :class:_engine.Row
objects,
are returned.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
scalar_one
scalar_one() -> Any
scalar_one() -> Any
Return exactly one scalar result or raise an exception.
This is equivalent to calling :meth:_engine.Result.scalars
and then :meth:_engine.Result.one
.
.. seealso::
:meth:`_engine.Result.one`
:meth:`_engine.Result.scalars`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
scalar_one_or_none
Return exactly one or no scalar result.
This is equivalent to calling :meth:_engine.Result.scalars
and then :meth:_engine.Result.one_or_none
.
.. seealso::
:meth:`_engine.Result.one_or_none`
:meth:`_engine.Result.scalars`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
scalar
scalar() -> Any
Fetch the first column of the first row, and close the result set.
Returns None
if there are no rows to fetch.
No validation is performed to test if additional rows remain.
After calling this method, the object is fully closed,
e.g. the :meth:_engine.CursorResult.close
method will have been called.
:return: a Python scalar value , or None
if no rows remain.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
create_engine
create_engine(
url: Union[str, URL],
*,
connect_args: Dict[Any, Any] = ...,
convert_unicode: bool = ...,
creator: Union[
_CreatorFnType, _CreatorWRecFnType
] = ...,
echo: _EchoFlagType = ...,
echo_pool: _EchoFlagType = ...,
enable_from_linting: bool = ...,
execution_options: _ExecuteOptions = ...,
future: Literal[True],
hide_parameters: bool = ...,
implicit_returning: Literal[True] = ...,
insertmanyvalues_page_size: int = ...,
isolation_level: IsolationLevel = ...,
json_deserializer: Callable[..., Any] = ...,
json_serializer: Callable[..., Any] = ...,
label_length: Optional[int] = ...,
logging_name: str = ...,
max_identifier_length: Optional[int] = ...,
max_overflow: int = ...,
module: Optional[Any] = ...,
paramstyle: Optional[_ParamStyle] = ...,
pool: Optional[Pool] = ...,
poolclass: Optional[Type[Pool]] = ...,
pool_logging_name: str = ...,
pool_pre_ping: bool = ...,
pool_size: int = ...,
pool_recycle: int = ...,
pool_reset_on_return: Optional[
_ResetStyleArgType
] = ...,
pool_timeout: float = ...,
pool_use_lifo: bool = ...,
plugins: List[str] = ...,
query_cache_size: int = ...,
use_insertmanyvalues: bool = ...,
**kwargs: Any,
) -> Engine
Create a new :class:_engine.Engine
instance.
The standard calling form is to send the :ref:URL <database_urls>
as the
first positional argument, usually a string
that indicates database dialect and connection arguments::
engine = create_engine("postgresql+psycopg2://scott:tiger@localhost/test")
.. note::
Please review :ref:`database_urls` for general guidelines in composing
URL strings. In particular, special characters, such as those often
part of passwords, must be URL encoded to be properly parsed.
Additional keyword arguments may then follow it which
establish various options on the resulting :class:_engine.Engine
and its underlying :class:.Dialect
and :class:_pool.Pool
constructs::
engine = create_engine("mysql+mysqldb://scott:tiger@hostname/dbname",
pool_recycle=3600, echo=True)
The string form of the URL is
dialect[+driver]://user:password@host/dbname[?key=value..]
, where
dialect
is a database name such as mysql
, oracle
,
postgresql
, etc., and driver
the name of a DBAPI, such as
psycopg2
, pyodbc
, cx_oracle
, etc. Alternatively,
the URL can be an instance of :class:~sqlalchemy.engine.url.URL
.
**kwargs
takes a wide variety of options which are routed
towards their appropriate components. Arguments may be specific to
the :class:_engine.Engine
, the underlying :class:.Dialect
,
as well as the
:class:_pool.Pool
. Specific dialects also accept keyword arguments that
are unique to that dialect. Here, we describe the parameters
that are common to most :func:_sa.create_engine()
usage.
Once established, the newly resulting :class:_engine.Engine
will
request a connection from the underlying :class:_pool.Pool
once
:meth:_engine.Engine.connect
is called, or a method which depends on it
such as :meth:_engine.Engine.execute
is invoked. The
:class:_pool.Pool
in turn
will establish the first actual DBAPI connection when this request
is received. The :func:_sa.create_engine
call itself does not
establish any actual DBAPI connections directly.
.. seealso::
:doc:`/core/engines`
:doc:`/dialects/index`
:ref:`connections_toplevel`
:param connect_args: a dictionary of options which will be
passed directly to the DBAPI's connect()
method as
additional keyword arguments. See the example
at :ref:custom_dbapi_args
.
:param creator: a callable which returns a DBAPI connection. This creation function will be passed to the underlying connection pool and will be used to create all new database connections. Usage of this function causes connection parameters specified in the URL argument to be bypassed.
This hook is not as flexible as the newer
:meth:`_events.DialectEvents.do_connect` hook which allows complete
control over how a connection is made to the database, given the full
set of URL arguments and state beforehand.
.. seealso::
:meth:`_events.DialectEvents.do_connect` - event hook that allows
full control over DBAPI connection mechanics.
:ref:`custom_dbapi_args`
:param echo=False: if True, the Engine will log all statements
as well as a repr()
of their parameter lists to the default log
handler, which defaults to sys.stdout
for output. If set to the
string "debug"
, result rows will be printed to the standard output
as well. The echo
attribute of Engine
can be modified at any
time to turn logging on and off; direct control of logging is also
available using the standard Python logging
module.
.. seealso::
:ref:`dbengine_logging` - further detail on how to configure
logging.
:param echo_pool=False: if True, the connection pool will log
informational output such as when connections are invalidated
as well as when connections are recycled to the default log handler,
which defaults to sys.stdout
for output. If set to the string
"debug"
, the logging will include pool checkouts and checkins.
Direct control of logging is also available using the standard Python
logging
module.
.. seealso::
:ref:`dbengine_logging` - further detail on how to configure
logging.
:param empty_in_strategy: No longer used; SQLAlchemy now uses "empty set" behavior for IN in all cases.
:param enable_from_linting: defaults to True. Will emit a warning if a given SELECT statement is found to have un-linked FROM elements which would cause a cartesian product.
.. versionadded:: 1.4
.. seealso::
:ref:`change_4737`
:param execution_options: Dictionary execution options which will
be applied to all connections. See
:meth:~sqlalchemy.engine.Connection.execution_options
:param future: Use the 2.0 style :class:_engine.Engine
and
:class:_engine.Connection
API.
As of SQLAlchemy 2.0, this parameter is present for backwards
compatibility only and must remain at its default value of ``True``.
The :paramref:`_sa.create_engine.future` parameter will be
deprecated in a subsequent 2.x release and eventually removed.
.. versionadded:: 1.4
.. versionchanged:: 2.0 All :class:`_engine.Engine` objects are
"future" style engines and there is no longer a ``future=False``
mode of operation.
.. seealso::
:ref:`migration_20_toplevel`
:param hide_parameters: Boolean, when set to True, SQL statement parameters
will not be displayed in INFO logging nor will they be formatted into
the string representation of :class:.StatementError
objects.
.. versionadded:: 1.3.8
.. seealso::
:ref:`dbengine_logging` - further detail on how to configure
logging.
:param implicit_returning=True: Legacy parameter that may only be set
to True. In SQLAlchemy 2.0, this parameter does nothing. In order to
disable "implicit returning" for statements invoked by the ORM,
configure this on a per-table basis using the
:paramref:.Table.implicit_returning
parameter.
:param insertmanyvalues_page_size: 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, but may also be subject to dialect-specific limiting
factors which may override this value on a per-statement basis.
.. versionadded:: 2.0
.. seealso::
:ref:`engine_insertmanyvalues`
:ref:`engine_insertmanyvalues_page_size`
:paramref:`_engine.Connection.execution_options.insertmanyvalues_page_size`
:param isolation_level: optional string name of an isolation level
which will be set on all new connections unconditionally.
Isolation levels are typically some subset of the string names
"SERIALIZABLE"
, "REPEATABLE READ"
,
"READ COMMITTED"
, "READ UNCOMMITTED"
and "AUTOCOMMIT"
based on backend.
The :paramref:`_sa.create_engine.isolation_level` parameter is
in contrast to the
:paramref:`.Connection.execution_options.isolation_level`
execution option, which may be set on an individual
:class:`.Connection`, as well as the same parameter passed to
:meth:`.Engine.execution_options`, where it may be used to create
multiple engines with different isolation levels that share a common
connection pool and dialect.
.. versionchanged:: 2.0 The
:paramref:`_sa.create_engine.isolation_level`
parameter has been generalized to work on all dialects which support
the concept of isolation level, and is provided as a more succinct,
up front configuration switch in contrast to the execution option
which is more of an ad-hoc programmatic option.
.. seealso::
:ref:`dbapi_autocommit`
:param json_deserializer: for dialects that support the
:class:_types.JSON
datatype, this is a Python callable that will convert a JSON string
to a Python object. By default, the Python json.loads
function is
used.
.. versionchanged:: 1.3.7 The SQLite dialect renamed this from
``_json_deserializer``.
:param json_serializer: for dialects that support the :class:_types.JSON
datatype, this is a Python callable that will render a given object
as JSON. By default, the Python json.dumps
function is used.
.. versionchanged:: 1.3.7 The SQLite dialect renamed this from
``_json_serializer``.
:param label_length=None: optional integer value which limits
the size of dynamically generated column labels to that many
characters. If less than 6, labels are generated as
"_(counter)". If None
, the value of
dialect.max_identifier_length
, which may be affected via the
:paramref:_sa.create_engine.max_identifier_length
parameter,
is used instead. The value of
:paramref:_sa.create_engine.label_length
may not be larger than that of
:paramref:_sa.create_engine.max_identfier_length
.
.. seealso::
:paramref:`_sa.create_engine.max_identifier_length`
:param logging_name: String identifier which will be used within the "name" field of logging records generated within the "sqlalchemy.engine" logger. Defaults to a hexstring of the object's id.
.. seealso::
:ref:`dbengine_logging` - further detail on how to configure
logging.
:paramref:`_engine.Connection.execution_options.logging_token`
:param max_identifier_length: integer; override the max_identifier_length
determined by the dialect. if None
or zero, has no effect. This
is the database's configured maximum number of characters that may be
used in a SQL identifier such as a table name, column name, or label
name. All dialects determine this value automatically, however in the
case of a new database version for which this value has changed but
SQLAlchemy's dialect has not been adjusted, the value may be passed
here.
.. versionadded:: 1.3.9
.. seealso::
:paramref:`_sa.create_engine.label_length`
:param max_overflow=10: the number of connections to allow in
connection pool "overflow", that is connections that can be
opened above and beyond the pool_size setting, which defaults
to five. this is only used with :class:~sqlalchemy.pool.QueuePool
.
:param module=None: reference to a Python module object (the module
itself, not its string name). Specifies an alternate DBAPI module to
be used by the engine's dialect. Each sub-dialect references a
specific DBAPI which will be imported before first connect. This
parameter causes the import to be bypassed, and the given module to
be used instead. Can be used for testing of DBAPIs as well as to
inject "mock" DBAPI implementations into the :class:_engine.Engine
.
:param paramstyle=None: The paramstyle <https://legacy.python.org/dev/peps/pep-0249/#paramstyle>
_
to use when rendering bound parameters. This style defaults to the
one recommended by the DBAPI itself, which is retrieved from the
.paramstyle
attribute of the DBAPI. However, most DBAPIs accept
more than one paramstyle, and in particular it may be desirable
to change a "named" paramstyle into a "positional" one, or vice versa.
When this attribute is passed, it should be one of the values
"qmark"
, "numeric"
, "named"
, "format"
or
"pyformat"
, and should correspond to a parameter style known
to be supported by the DBAPI in use.
:param pool=None: an already-constructed instance of
:class:~sqlalchemy.pool.Pool
, such as a
:class:~sqlalchemy.pool.QueuePool
instance. If non-None, this
pool will be used directly as the underlying connection pool
for the engine, bypassing whatever connection parameters are
present in the URL argument. For information on constructing
connection pools manually, see :ref:pooling_toplevel
.
:param poolclass=None: a :class:~sqlalchemy.pool.Pool
subclass, which will be used to create a connection pool
instance using the connection parameters given in the URL. Note
this differs from pool
in that you don't actually
instantiate the pool in this case, you just indicate what type
of pool to be used.
:param pool_logging_name: String identifier which will be used within the "name" field of logging records generated within the "sqlalchemy.pool" logger. Defaults to a hexstring of the object's id.
.. seealso::
:ref:`dbengine_logging` - further detail on how to configure
logging.
:param pool_pre_ping: boolean, if True will enable the connection pool "pre-ping" feature that tests connections for liveness upon each checkout.
.. versionadded:: 1.2
.. seealso::
:ref:`pool_disconnects_pessimistic`
:param pool_size=5: the number of connections to keep open
inside the connection pool. This used with
:class:~sqlalchemy.pool.QueuePool
as
well as :class:~sqlalchemy.pool.SingletonThreadPool
. With
:class:~sqlalchemy.pool.QueuePool
, a pool_size
setting
of 0 indicates no limit; to disable pooling, set poolclass
to
:class:~sqlalchemy.pool.NullPool
instead.
:param pool_recycle=-1: this setting causes the pool to recycle connections after the given number of seconds has passed. It defaults to -1, or no timeout. For example, setting to 3600 means connections will be recycled after one hour. Note that MySQL in particular will disconnect automatically if no activity is detected on a connection for eight hours (although this is configurable with the MySQLDB connection itself and the server configuration as well).
.. seealso::
:ref:`pool_setting_recycle`
:param pool_reset_on_return='rollback': set the
:paramref:_pool.Pool.reset_on_return
parameter of the underlying
:class:_pool.Pool
object, which can be set to the values
"rollback"
, "commit"
, or None
.
.. seealso::
:ref:`pool_reset_on_return`
:param pool_timeout=30: number of seconds to wait before giving
up on getting a connection from the pool. This is only used
with :class:~sqlalchemy.pool.QueuePool
. This can be a float but is
subject to the limitations of Python time functions which may not be
reliable in the tens of milliseconds.
.. note: don't use 30.0 above, it seems to break with the :param tag
:param pool_use_lifo=False: use LIFO (last-in-first-out) when retrieving
connections from :class:.QueuePool
instead of FIFO
(first-in-first-out). Using LIFO, a server-side timeout scheme can
reduce the number of connections used during non- peak periods of
use. When planning for server-side timeouts, ensure that a recycle or
pre-ping strategy is in use to gracefully handle stale connections.
.. versionadded:: 1.3
.. seealso::
:ref:`pool_use_lifo`
:ref:`pool_disconnects`
:param plugins: string list of plugin names to load. See
:class:.CreateEnginePlugin
for background.
.. versionadded:: 1.2.3
:param query_cache_size: size of the cache used to cache the SQL string form of queries. Set to zero to disable caching.
The cache is pruned of its least recently used items when its size reaches N * 1.5. Defaults to 500, meaning the cache will always store at least 500 SQL statements when filled, and will grow up to 750 items at which point it is pruned back down to 500 by removing the 250 least recently used items.
Caching is accomplished on a per-statement basis by generating a cache key that represents the statement's structure, then generating string SQL for the current dialect only if that key is not present in the cache. All statements support caching, however some features such as an INSERT with a large set of parameters will intentionally bypass the cache. SQL logging will indicate statistics for each statement whether or not it were pull from the cache.
.. note:: some ORM functions related to unit-of-work persistence as well as some attribute loading strategies will make use of individual per-mapper caches outside of the main cache.
.. seealso::
:ref:`sql_caching`
.. versionadded:: 1.4
:param use_insertmanyvalues: True by default, use the "insertmanyvalues" execution style for INSERT..RETURNING statements by default.
.. versionadded:: 2.0
.. seealso::
:ref:`engine_insertmanyvalues`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/create.py
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 |
|
create_mock_engine
Create a "mock" engine used for echoing DDL.
This is a utility function used for debugging or storing the output of DDL
sequences as generated by :meth:_schema.MetaData.create_all
and related methods.
The function accepts a URL which is used only to determine the kind of dialect to be used, as well as an "executor" callable function which will receive a SQL expression object and parameters, which can then be echoed or otherwise printed. The executor's return value is not handled, nor does the engine allow regular string statements to be invoked, and is therefore only useful for DDL that is sent to the database without receiving any results.
E.g.::
from sqlalchemy import create_mock_engine
def dump(sql, *multiparams, **params):
print(sql.compile(dialect=engine.dialect))
engine = create_mock_engine('postgresql+psycopg2://', dump)
metadata.create_all(engine, checkfirst=False)
:param url: A string URL which typically needs to contain only the database backend name.
:param executor: a callable which receives the arguments sql
,
*multiparams
and **params
. The sql
parameter is typically
an instance of :class:.ExecutableDDLElement
, which can then be compiled
into a string using :meth:.ExecutableDDLElement.compile
.
.. versionadded:: 1.4 - the :func:.create_mock_engine
function replaces
the previous "mock" engine strategy used with
:func:_sa.create_engine
.
.. seealso::
:ref:`faq_ddl_as_string`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/mock.py
engine_from_config
engine_from_config(
configuration: Dict[str, Any],
prefix: str = "sqlalchemy.",
**kwargs: Any,
) -> Engine
Create a new Engine instance using a configuration dictionary.
The dictionary is typically produced from a config file.
The keys of interest to engine_from_config()
should be prefixed, e.g.
sqlalchemy.url
, sqlalchemy.echo
, etc. The 'prefix' argument
indicates the prefix to be searched for. Each matching key (after the
prefix is stripped) is treated as though it were the corresponding keyword
argument to a :func:_sa.create_engine
call.
The only required key is (assuming the default prefix) sqlalchemy.url
,
which provides the :ref:database URL <database_urls>
.
A select set of keyword arguments will be "coerced" to their
expected type based on string values. The set of arguments
is extensible per-dialect using the engine_config_types
accessor.
:param configuration: A dictionary (typically produced from a config file,
but this is not a requirement). Items whose keys start with the value
of 'prefix' will have that prefix stripped, and will then be passed to
:func:_sa.create_engine
.
:param prefix: Prefix to match and then strip from keys in 'configuration'.
:param kwargs: Each keyword argument to engine_from_config()
itself
overrides the corresponding item taken from the 'configuration'
dictionary. Keyword arguments should not be prefixed.