Skip to content

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
def __init__(
    self,
    async_engine: AsyncEngine,
    sync_connection: Optional[Connection] = None,
):
    self.engine = async_engine
    self.sync_engine = async_engine.sync_engine
    self.sync_connection = self._assign_proxied(sync_connection)

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
async def start(
    self, is_ctxmanager: bool = False  # noqa: U100
) -> AsyncConnection:
    """Start this :class:`_asyncio.AsyncConnection` object's context
    outside of using a Python ``with:`` block.

    """
    if self.sync_connection:
        raise exc.InvalidRequestError("connection is already started")
    self.sync_connection = self._assign_proxied(
        await greenlet_spawn(self.sync_engine.connect)
    )
    return self

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
async def get_raw_connection(self) -> 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.

    """

    return await greenlet_spawn(getattr, self._proxied, "connection")

info

info() -> _InfoType

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
@util.ro_non_memoized_property
def info(self) -> _InfoType:
    """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

    """
    return self._proxied.info

begin

begin() -> AsyncTransaction

Begin a transaction prior to autobegin occurring.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
def begin(self) -> AsyncTransaction:
    """Begin a transaction prior to autobegin occurring."""
    assert self._proxied
    return AsyncTransaction(self)

begin_nested

begin_nested() -> AsyncTransaction

Begin a nested transaction and return a transaction handle.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
def begin_nested(self) -> AsyncTransaction:
    """Begin a nested transaction and return a transaction handle."""
    assert self._proxied
    return AsyncTransaction(self, nested=True)

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
async def invalidate(
    self, 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.

    """

    return await greenlet_spawn(
        self._proxied.invalidate, exception=exception
    )

in_transaction

in_transaction() -> bool

Return True if a transaction is in progress.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
def in_transaction(self) -> bool:
    """Return True if a transaction is in progress."""

    return self._proxied.in_transaction()

in_nested_transaction

in_nested_transaction() -> bool

Return True if a transaction is in progress.

.. versionadded:: 1.4.0b2

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
def in_nested_transaction(self) -> bool:
    """Return True if a transaction is in progress.

    .. versionadded:: 1.4.0b2

    """
    return self._proxied.in_nested_transaction()

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
def get_transaction(self) -> 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

    """

    trans = self._proxied.get_transaction()
    if trans is not None:
        return AsyncTransaction._retrieve_proxy_for_target(trans)
    else:
        return None

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
def get_nested_transaction(self) -> 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

    """

    trans = self._proxied.get_nested_transaction()
    if trans is not None:
        return AsyncTransaction._retrieve_proxy_for_target(trans)
    else:
        return None

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
async def execution_options(self, **opt: Any) -> AsyncConnection:
    r"""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.

    """

    conn = self._proxied
    c2 = await greenlet_spawn(conn.execution_options, **opt)
    assert c2 is conn
    return self

commit async

commit() -> None

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
async def commit(self) -> None:
    """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.

    """
    await greenlet_spawn(self._proxied.commit)

rollback async

rollback() -> None

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
async def rollback(self) -> None:
    """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.


    """
    await greenlet_spawn(self._proxied.rollback)

close async

close() -> None

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
async def close(self) -> None:
    """Close this :class:`_asyncio.AsyncConnection`.

    This has the effect of also rolling back the transaction if one
    is in place.

    """
    await greenlet_spawn(self._proxied.close)

aclose async

aclose() -> None

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
async def aclose(self) -> None:
    """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

    """
    await self.close()

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
async def exec_driver_sql(
    self,
    statement: str,
    parameters: Optional[_DBAPIAnyExecuteParams] = None,
    execution_options: Optional[CoreExecuteOptionsParameter] = None,
) -> CursorResult[Any]:
    r"""Executes a driver-level SQL string and return buffered
    :class:`_engine.Result`.

    """

    result = await greenlet_spawn(
        self._proxied.exec_driver_sql,
        statement,
        parameters,
        execution_options,
        _require_await=True,
    )

    return await _ensure_sync_result(result, self.exec_driver_sql)

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
@asyncstartablecontext
async def stream(
    self,
    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`

    """
    if not self.dialect.supports_server_side_cursors:
        raise exc.InvalidRequestError(
            "Cant use `stream` or `stream_scalars` with the current "
            "dialect since it does not support server side cursors."
        )

    result = await greenlet_spawn(
        self._proxied.execute,
        statement,
        parameters,
        execution_options=util.EMPTY_DICT.merge_with(
            execution_options, {"stream_results": True}
        ),
        _require_await=True,
    )
    assert result.context._is_server_side
    ar = AsyncResult(result)
    try:
        yield ar
    except GeneratorExit:
        pass
    else:
        task = asyncio.create_task(ar.close())
        await asyncio.shield(task)

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
async def execute(
    self,
    statement: Executable,
    parameters: Optional[_CoreAnyExecuteParams] = None,
    *,
    execution_options: Optional[CoreExecuteOptionsParameter] = None,
) -> CursorResult[Any]:
    r"""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.

    """
    result = await greenlet_spawn(
        self._proxied.execute,
        statement,
        parameters,
        execution_options=execution_options,
        _require_await=True,
    )
    return await _ensure_sync_result(result, self.execute)

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
async def scalar(
    self,
    statement: Executable,
    parameters: Optional[_CoreSingleExecuteParams] = None,
    *,
    execution_options: Optional[CoreExecuteOptionsParameter] = None,
) -> Any:
    r"""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.

    """
    result = await self.execute(
        statement, parameters, execution_options=execution_options
    )
    return result.scalar()

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
async def scalars(
    self,
    statement: Executable,
    parameters: Optional[_CoreAnyExecuteParams] = None,
    *,
    execution_options: Optional[CoreExecuteOptionsParameter] = None,
) -> ScalarResult[Any]:
    r"""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

    """
    result = await self.execute(
        statement, parameters, execution_options=execution_options
    )
    return result.scalars()

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
@asyncstartablecontext
async def stream_scalars(
    self,
    statement: Executable,
    parameters: Optional[_CoreSingleExecuteParams] = None,
    *,
    execution_options: Optional[CoreExecuteOptionsParameter] = None,
) -> AsyncIterator[AsyncScalarResult[Any]]:
    r"""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`

    """

    async with self.stream(
        statement, parameters, execution_options=execution_options
    ) as result:
        yield result.scalars()

run_sync async

run_sync(fn: Callable[..., _T], *arg: Any, **kw: Any) -> _T

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
async def run_sync(
    self, fn: Callable[..., _T], *arg: Any, **kw: Any
) -> _T:
    """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`

    """  # noqa: E501

    return await greenlet_spawn(fn, self._proxied, *arg, **kw)

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
def __init__(self, sync_engine: Engine):
    if not sync_engine.dialect.is_async:
        raise exc.InvalidRequestError(
            "The asyncio extension requires an async driver to be used. "
            f"The loaded {sync_engine.dialect.driver!r} is not async."
        )
    self.sync_engine = self._assign_proxied(sync_engine)

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

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
@contextlib.asynccontextmanager
async def begin(self) -> 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)"))


    """
    conn = self.connect()

    async with conn:
        async with conn.begin():
            yield conn

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
def connect(self) -> 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.

    """

    return self._connection_cls(self)

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
async def raw_connection(self) -> PoolProxiedConnection:
    """Return a "raw" DBAPI connection from the connection pool.

    .. seealso::

        :ref:`dbapi_connections`

    """
    return await greenlet_spawn(self.sync_engine.raw_connection)

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
def execution_options(self, **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.

    """

    return AsyncEngine(self.sync_engine.execution_options(**opt))

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
async def dispose(self, 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`

    """

    await greenlet_spawn(self.sync_engine.dispose, close=close)

clear_compiled_cache

clear_compiled_cache() -> None

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
def clear_compiled_cache(self) -> None:
    r"""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


    """  # noqa: E501

    return self._proxied.clear_compiled_cache()

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
def update_execution_options(self, **opt: Any) -> None:
    r"""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`


    """  # noqa: E501

    return self._proxied.update_execution_options(**opt)

get_execution_options

get_execution_options() -> _ExecuteOptions

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
def get_execution_options(self) -> _ExecuteOptions:
    r"""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`

    """  # noqa: E501

    return self._proxied.get_execution_options()

AsyncMappingResult

AsyncMappingResult(result: Result[Any])

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
def __init__(self, result: Result[Any]):
    self._real_result = result
    self._unique_filter_state = result._unique_filter_state
    self._metadata = result._metadata
    if result._source_supports_scalars:
        self._metadata = self._metadata._reduce([0])

closed property

closed: bool

proxies the .closed attribute of the underlying result object, if any, else raises AttributeError.

.. versionadded:: 2.0.0b3

memoized_attribute

memoized_attribute(
    fget: Callable[..., _T], doc: Optional[str] = None
)

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
def __init__(self, fget: Callable[..., _T], doc: Optional[str] = None):
    self.fget = fget
    self.__doc__ = doc or fget.__doc__
    self.__name__ = fget.__name__

memoized_instancemethod classmethod

memoized_instancemethod(fn: _F) -> _F

Decorate a method memoize its return value.

:meta private:

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
@classmethod
def memoized_instancemethod(cls, fn: _F) -> _F:
    """Decorate a method memoize its return value.

    :meta private:

    """

    def oneshot(self: Any, *args: Any, **kw: Any) -> Any:
        result = fn(self, *args, **kw)

        def memo(*a, **kw):
            return result

        memo.__name__ = fn.__name__
        memo.__doc__ = fn.__doc__
        self.__dict__[fn.__name__] = memo
        self._memoized_keys |= {fn.__name__}
        return result

    return update_wrapper(oneshot, fn)  # type: ignore

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
@_generative
def yield_per(self, 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`

    """
    self._real_result = self._real_result.yield_per(num)
    return self

close async

close() -> None

Close this result.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
async def close(self) -> None:  # type: ignore[override]
    """Close this result."""

    await greenlet_spawn(self._real_result.close)

keys

keys() -> RMKeyView

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
def keys(self) -> RMKeyView:
    """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.


    """
    return self._metadata.keys

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
def unique(
    self,
    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.

    """
    self._unique_filter_state = (set(), strategy)
    return self

columns

columns(*col_expressions: _KeyIndexType) -> Self

Establish the columns that should be returned in each row.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
def columns(self, *col_expressions: _KeyIndexType) -> Self:
    r"""Establish the columns that should be returned in each row."""
    return self._column_slices(col_expressions)

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
async def partitions(
    self, 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.

    """

    getter = self._manyrow_getter

    while True:
        partition = await greenlet_spawn(getter, self, size)
        if partition:
            yield partition
        else:
            break

fetchall async

fetchall() -> Sequence[RowMapping]

A synonym for the :meth:_asyncio.AsyncMappingResult.all method.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
async def fetchall(self) -> Sequence[RowMapping]:
    """A synonym for the :meth:`_asyncio.AsyncMappingResult.all` method."""

    return await greenlet_spawn(self._allrows)

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
async def fetchone(self) -> 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.

    """

    row = await greenlet_spawn(self._onerow_getter, self)
    if row is _NO_ROW:
        return None
    else:
        return row

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
async def fetchmany(
    self, 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.

    """

    return await greenlet_spawn(self._manyrow_getter, self, size)

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
async def all(self) -> 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.

    """

    return await greenlet_spawn(self._allrows)

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
async def first(self) -> 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.

    """
    return await greenlet_spawn(self._only_one_row, False, False, False)

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
async def one_or_none(self) -> 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.

    """
    return await greenlet_spawn(self._only_one_row, True, False, False)

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
async def one(self) -> 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.

    """
    return await greenlet_spawn(self._only_one_row, True, True, False)

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
def __init__(self, real_result: Result[_TP]):
    self._real_result = real_result

    self._metadata = real_result._metadata
    self._unique_filter_state = real_result._unique_filter_state
    self._post_creational_filter = None

    # BaseCursorResult pre-generates the "_row_getter".  Use that
    # if available rather than building a second one
    if "_row_getter" in real_result.__dict__:
        self._set_memoized_attribute(
            "_row_getter", real_result.__dict__["_row_getter"]
        )

closed property

closed: bool

proxies the .closed attribute of the underlying result object, if any, else raises AttributeError.

.. versionadded:: 2.0.0b3

t property

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

memoized_attribute(
    fget: Callable[..., _T], doc: Optional[str] = None
)

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
def __init__(self, fget: Callable[..., _T], doc: Optional[str] = None):
    self.fget = fget
    self.__doc__ = doc or fget.__doc__
    self.__name__ = fget.__name__

memoized_instancemethod classmethod

memoized_instancemethod(fn: _F) -> _F

Decorate a method memoize its return value.

:meta private:

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
@classmethod
def memoized_instancemethod(cls, fn: _F) -> _F:
    """Decorate a method memoize its return value.

    :meta private:

    """

    def oneshot(self: Any, *args: Any, **kw: Any) -> Any:
        result = fn(self, *args, **kw)

        def memo(*a, **kw):
            return result

        memo.__name__ = fn.__name__
        memo.__doc__ = fn.__doc__
        self.__dict__[fn.__name__] = memo
        self._memoized_keys |= {fn.__name__}
        return result

    return update_wrapper(oneshot, fn)  # type: ignore

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
@_generative
def yield_per(self, 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`

    """
    self._real_result = self._real_result.yield_per(num)
    return self

close async

close() -> None

Close this result.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
async def close(self) -> None:  # type: ignore[override]
    """Close this result."""

    await greenlet_spawn(self._real_result.close)

keys

keys() -> RMKeyView

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
def keys(self) -> RMKeyView:
    """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.


    """
    return self._metadata.keys

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
def tuples(self) -> 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

    """

    return self  # type: ignore

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
@_generative
def unique(self, 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.

    """
    self._unique_filter_state = (set(), strategy)
    return self

columns

columns(*col_expressions: _KeyIndexType) -> Self

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
def columns(self, *col_expressions: _KeyIndexType) -> Self:
    r"""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.

    """
    return self._column_slices(col_expressions)

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
async def partitions(
    self, 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.

    """

    getter = self._manyrow_getter

    while True:
        partition = await greenlet_spawn(getter, self, size)
        if partition:
            yield partition
        else:
            break

fetchall async

fetchall() -> Sequence[Row[_TP]]

A synonym for the :meth:_asyncio.AsyncResult.all method.

.. versionadded:: 2.0

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
async def fetchall(self) -> Sequence[Row[_TP]]:
    """A synonym for the :meth:`_asyncio.AsyncResult.all` method.

    .. versionadded:: 2.0

    """

    return await greenlet_spawn(self._allrows)

fetchone async

fetchone() -> Optional[Row[_TP]]

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
async def fetchone(self) -> Optional[Row[_TP]]:
    """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.

    """
    row = await greenlet_spawn(self._onerow_getter, self)
    if row is _NO_ROW:
        return None
    else:
        return row

fetchmany async

fetchmany(size: Optional[int] = None) -> Sequence[Row[_TP]]

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
async def fetchmany(
    self, size: Optional[int] = None
) -> Sequence[Row[_TP]]:
    """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`

    """

    return await greenlet_spawn(self._manyrow_getter, self, size)

all async

all() -> Sequence[Row[_TP]]

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
async def all(self) -> Sequence[Row[_TP]]:
    """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.

    """

    return await greenlet_spawn(self._allrows)

first async

first() -> Optional[Row[_TP]]

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
async def first(self) -> Optional[Row[_TP]]:
    """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`

    """
    return await greenlet_spawn(self._only_one_row, False, False, False)

one_or_none async

one_or_none() -> Optional[Row[_TP]]

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
async def one_or_none(self) -> Optional[Row[_TP]]:
    """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`

    """
    return await greenlet_spawn(self._only_one_row, True, False, False)

scalar_one async

scalar_one() -> _T
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
async def scalar_one(self) -> 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`

    """
    return await greenlet_spawn(self._only_one_row, True, True, True)

scalar_one_or_none async

scalar_one_or_none() -> Optional[_T]
scalar_one_or_none() -> Optional[Any]
scalar_one_or_none() -> Optional[Any]

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
async def scalar_one_or_none(self) -> Optional[Any]:
    """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`

    """
    return await greenlet_spawn(self._only_one_row, True, False, True)

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
async def one(self) -> 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`

    """
    return await greenlet_spawn(self._only_one_row, True, True, False)

scalar async

scalar() -> Optional[_T]
scalar() -> Any
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 def scalar(self) -> 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.

    """
    return await greenlet_spawn(self._only_one_row, False, False, True)

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
async def freeze(self) -> 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.

    """

    return await greenlet_spawn(FrozenResult, self)

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
def scalars(self, 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.

    """
    return AsyncScalarResult(self._real_result, index)

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
def mappings(self) -> 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.

    """

    return AsyncMappingResult(self._real_result)

AsyncScalarResult

AsyncScalarResult(
    real_result: Result[Any], index: _KeyIndexType
)

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
def __init__(self, real_result: Result[Any], index: _KeyIndexType):
    self._real_result = real_result

    if real_result._source_supports_scalars:
        self._metadata = real_result._metadata
        self._post_creational_filter = None
    else:
        self._metadata = real_result._metadata._reduce([index])
        self._post_creational_filter = operator.itemgetter(0)

    self._unique_filter_state = real_result._unique_filter_state

closed property

closed: bool

proxies the .closed attribute of the underlying result object, if any, else raises AttributeError.

.. versionadded:: 2.0.0b3

memoized_attribute

memoized_attribute(
    fget: Callable[..., _T], doc: Optional[str] = None
)

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
def __init__(self, fget: Callable[..., _T], doc: Optional[str] = None):
    self.fget = fget
    self.__doc__ = doc or fget.__doc__
    self.__name__ = fget.__name__

memoized_instancemethod classmethod

memoized_instancemethod(fn: _F) -> _F

Decorate a method memoize its return value.

:meta private:

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
@classmethod
def memoized_instancemethod(cls, fn: _F) -> _F:
    """Decorate a method memoize its return value.

    :meta private:

    """

    def oneshot(self: Any, *args: Any, **kw: Any) -> Any:
        result = fn(self, *args, **kw)

        def memo(*a, **kw):
            return result

        memo.__name__ = fn.__name__
        memo.__doc__ = fn.__doc__
        self.__dict__[fn.__name__] = memo
        self._memoized_keys |= {fn.__name__}
        return result

    return update_wrapper(oneshot, fn)  # type: ignore

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
@_generative
def yield_per(self, 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`

    """
    self._real_result = self._real_result.yield_per(num)
    return self

close async

close() -> None

Close this result.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
async def close(self) -> None:  # type: ignore[override]
    """Close this result."""

    await greenlet_spawn(self._real_result.close)

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
def unique(
    self,
    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.

    """
    self._unique_filter_state = (set(), strategy)
    return self

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
async def partitions(
    self, 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.

    """

    getter = self._manyrow_getter

    while True:
        partition = await greenlet_spawn(getter, self, size)
        if partition:
            yield partition
        else:
            break

fetchall async

fetchall() -> Sequence[_R]

A synonym for the :meth:_asyncio.AsyncScalarResult.all method.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
async def fetchall(self) -> Sequence[_R]:
    """A synonym for the :meth:`_asyncio.AsyncScalarResult.all` method."""

    return await greenlet_spawn(self._allrows)

fetchmany async

fetchmany(size: Optional[int] = None) -> Sequence[_R]

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
async def fetchmany(self, size: Optional[int] = None) -> Sequence[_R]:
    """Fetch many objects.

    Equivalent to :meth:`_asyncio.AsyncResult.fetchmany` except that
    scalar values, rather than :class:`_engine.Row` objects,
    are returned.

    """
    return await greenlet_spawn(self._manyrow_getter, self, size)

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
async def all(self) -> 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.

    """
    return await greenlet_spawn(self._allrows)

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
async def first(self) -> 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.

    """
    return await greenlet_spawn(self._only_one_row, False, False, False)

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
async def one_or_none(self) -> 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.

    """
    return await greenlet_spawn(self._only_one_row, True, False, False)

one async

one() -> _R

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
async def one(self) -> _R:
    """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.

    """
    return await greenlet_spawn(self._only_one_row, True, True, False)

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
def __init__(self, connection: AsyncConnection, nested: bool = False):
    self.connection = connection
    self.sync_transaction = None
    self.nested = nested

close async

close() -> None

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
async def close(self) -> None:
    """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.

    """
    await greenlet_spawn(self._proxied.close)

rollback async

rollback() -> None

Roll back this :class:.AsyncTransaction.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
async def rollback(self) -> None:
    """Roll back this :class:`.AsyncTransaction`."""
    await greenlet_spawn(self._proxied.rollback)

commit async

commit() -> None

Commit this :class:.AsyncTransaction.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
async def commit(self) -> None:
    """Commit this :class:`.AsyncTransaction`."""

    await greenlet_spawn(self._proxied.commit)

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
async def start(self, is_ctxmanager: bool = False) -> AsyncTransaction:
    """Start this :class:`_asyncio.AsyncTransaction` object's context
    outside of using a Python ``with:`` block.

    """

    self.sync_transaction = self._assign_proxied(
        await greenlet_spawn(
            self.connection._proxied.begin_nested
            if self.nested
            else self.connection._proxied.begin
        )
    )
    if is_ctxmanager:
        self.sync_transaction.__enter__()
    return self

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

memoized_attribute(
    fget: Callable[..., _T], doc: Optional[str] = None
)

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
def __init__(self, fget: Callable[..., _T], doc: Optional[str] = None):
    self.fget = fget
    self.__doc__ = doc or fget.__doc__
    self.__name__ = fget.__name__

memoized_instancemethod classmethod

memoized_instancemethod(fn: _F) -> _F

Decorate a method memoize its return value.

:meta private:

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
@classmethod
def memoized_instancemethod(cls, fn: _F) -> _F:
    """Decorate a method memoize its return value.

    :meta private:

    """

    def oneshot(self: Any, *args: Any, **kw: Any) -> Any:
        result = fn(self, *args, **kw)

        def memo(*a, **kw):
            return result

        memo.__name__ = fn.__name__
        memo.__doc__ = fn.__doc__
        self.__dict__[fn.__name__] = memo
        self._memoized_keys |= {fn.__name__}
        return result

    return update_wrapper(oneshot, fn)  # type: ignore

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
@_generative
def yield_per(self, 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`

    """
    self._real_result = self._real_result.yield_per(num)
    return self

close async

close() -> None

Close this result.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
async def close(self) -> None:  # type: ignore[override]
    """Close this result."""

    await greenlet_spawn(self._real_result.close)

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
async def partitions(
    self, 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.

    """
    ...

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
async def fetchone(self) -> Optional[_R]:
    """Fetch one tuple.

    Equivalent to :meth:`_result.Result.fetchone` except that
    tuple values, rather than :class:`_engine.Row`
    objects, are returned.

    """
    ...

fetchall async

fetchall() -> Sequence[_R]

A synonym for the :meth:_engine.ScalarResult.all method.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/result.py
async def fetchall(self) -> Sequence[_R]:
    """A synonym for the :meth:`_engine.ScalarResult.all` method."""
    ...

fetchmany async

fetchmany(size: Optional[int] = None) -> Sequence[_R]

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
async def fetchmany(self, size: Optional[int] = None) -> Sequence[_R]:
    """Fetch many objects.

    Equivalent to :meth:`_result.Result.fetchmany` except that
    tuple values, rather than :class:`_engine.Row` objects,
    are returned.

    """
    ...

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
async def all(self) -> Sequence[_R]:  # noqa: A001
    """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.

    """
    ...

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
async def first(self) -> 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.


    """
    ...

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
async def one_or_none(self) -> 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.

    """
    ...

one async

one() -> _R

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
async def one(self) -> _R:
    """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.

    """
    ...

scalar_one async

scalar_one() -> _T
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
async def scalar_one(self) -> 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`

    """
    ...

scalar_one_or_none async

scalar_one_or_none() -> Optional[_T]
scalar_one_or_none() -> Optional[Any]
scalar_one_or_none() -> Optional[Any]

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
async def scalar_one_or_none(self) -> Optional[Any]:
    """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`

    """
    ...

scalar async

scalar() -> Optional[_T]
scalar() -> Any
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 def scalar(self) -> 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.

    """
    ...

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
def 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

    """
    options = {
        key[len(prefix) :]: value
        for key, value in configuration.items()
        if key.startswith(prefix)
    }
    options["_coerce_config"] = True
    options.update(kwargs)
    url = options.pop("url")
    return create_async_engine(url, **options)

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
def 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

    """

    if kw.get("server_side_cursors", False):
        raise async_exc.AsyncMethodRequired(
            "Can't set server_side_cursors for async engine globally; "
            "use the connection.stream() method for an async "
            "streaming result set"
        )
    kw["_is_async"] = True
    async_creator = kw.pop("async_creator", None)
    if async_creator:
        if kw.get("creator", None):
            raise ArgumentError(
                "Can only specify one of 'async_creator' or 'creator', "
                "not both."
            )

        def creator() -> Any:
            # note that to send adapted arguments like
            # prepared_statement_cache_size, user would use
            # "creator" and emulate this form here
            return sync_engine.dialect.dbapi.connect(  # type: ignore
                async_creator_fn=async_creator
            )

        kw["creator"] = creator
    sync_engine = _create_engine(url, **kw)
    return AsyncEngine(sync_engine)

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
def __init__(
    self,
    engine: Engine,
    connection: Optional[PoolProxiedConnection] = None,
    _has_events: Optional[bool] = None,
    _allow_revalidate: bool = True,
    _allow_autobegin: bool = True,
):
    """Construct a new Connection."""
    self.engine = engine
    self.dialect = dialect = engine.dialect

    if connection is None:
        try:
            self._dbapi_connection = engine.raw_connection()
        except dialect.loaded_dbapi.Error as err:
            Connection._handle_dbapi_exception_noconnection(
                err, dialect, engine
            )
            raise
    else:
        self._dbapi_connection = connection

    self._transaction = self._nested_transaction = None
    self.__savepoint_seq = 0
    self.__in_begin = False

    self.__can_reconnect = _allow_revalidate
    self._allow_autobegin = _allow_autobegin
    self._echo = self.engine._should_log_info()

    if _has_events is None:
        # if _has_events is sent explicitly as False,
        # then don't join the dispatch of the engine; we don't
        # want to handle any of the engine's events in that case.
        self.dispatch = self.dispatch._join(engine.dispatch)
    self._has_events = _has_events or (
        _has_events is None and engine._has_events
    )

    self._execution_options = engine._execution_options

    if self._has_events or self.engine._has_events:
        self.dispatch.engine_connect(self)

closed property

closed: bool

Return True if this connection is closed.

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

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: _InfoType

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

schema_for_object(obj: HasSchemaAttr) -> Optional[str]

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
def schema_for_object(self, obj: HasSchemaAttr) -> Optional[str]:
    """Return the schema name for the given schema item taking into
    account current schema translate map.

    """

    name = obj.schema
    schema_translate_map: Optional[SchemaTranslateMapType] = (
        self._execution_options.get("schema_translate_map", None)
    )

    if (
        schema_translate_map
        and name in schema_translate_map
        and obj._use_schema_map
    ):
        return schema_translate_map[name]
    else:
        return name

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
def execution_options(self, **opt: Any) -> Connection:
    r"""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

    """  # noqa
    if self._has_events or self.engine._has_events:
        self.dispatch.set_connection_execution_options(self, opt)
    self._execution_options = self._execution_options.union(opt)
    self.dialect.set_connection_execution_options(self, opt)
    return self

get_execution_options

get_execution_options() -> _ExecuteOptions

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
def get_execution_options(self) -> _ExecuteOptions:
    """Get the non-SQL options which will take effect during execution.

    .. versionadded:: 1.3

    .. seealso::

        :meth:`_engine.Connection.execution_options`
    """
    return self._execution_options

get_isolation_level

get_isolation_level() -> IsolationLevel

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
def get_isolation_level(self) -> IsolationLevel:
    """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

    """
    dbapi_connection = self.connection.dbapi_connection
    assert dbapi_connection is not None
    try:
        return self.dialect.get_isolation_level(dbapi_connection)
    except BaseException as e:
        self._handle_dbapi_exception(e, None, None, None, None)

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
def invalidate(self, 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`

    """

    if self.invalidated:
        return

    if self.closed:
        raise exc.ResourceClosedError("This Connection is closed")

    if self._still_open_and_dbapi_connection_is_valid:
        pool_proxied_connection = self._dbapi_connection
        assert pool_proxied_connection is not None
        pool_proxied_connection.invalidate(exception)

    self._dbapi_connection = None

detach

detach() -> None

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
def detach(self) -> None:
    """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).

    """

    if self.closed:
        raise exc.ResourceClosedError("This Connection is closed")

    pool_proxied_connection = self._dbapi_connection
    if pool_proxied_connection is None:
        raise exc.InvalidRequestError(
            "Can't detach an invalidated Connection"
        )
    pool_proxied_connection.detach()

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
def begin(self) -> 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`

    """
    if self._transaction is None:
        self._transaction = RootTransaction(self)
        return self._transaction
    else:
        raise exc.InvalidRequestError(
            "This connection has already initialized a SQLAlchemy "
            "Transaction() object via begin() or autobegin; can't "
            "call begin() here unless rollback() or commit() "
            "is called first."
        )

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 " and "ROLLBACK TO SAVEPOINT ". The name of the savepoint is local to the :class:_engine.NestedTransaction object and is generated automatically. Like any other :class:_engine.Transaction, the :class:_engine.NestedTransaction may be used as a context manager as illustrated above which will "release" or "rollback" corresponding to if the operation within the block were successful or raised an exception.

Nested transactions require SAVEPOINT support in the underlying database, else the behavior is undefined. SAVEPOINT is commonly used to run operations within a transaction that may fail, while continuing the outer transaction. E.g.::

from sqlalchemy import exc

with engine.begin() as connection:
    trans = connection.begin_nested()
    try:
        connection.execute(table.insert(), {"username": "sandy"})
        trans.commit()
    except exc.IntegrityError:  # catch for duplicate username
        trans.rollback()  # rollback to savepoint

    # outer transaction continues
    connection.execute( ... )

If :meth:_engine.Connection.begin_nested is called without first calling :meth:_engine.Connection.begin or :meth:_engine.Engine.begin, the :class:_engine.Connection object will "autobegin" the outer transaction first. This outer transaction may be committed using "commit-as-you-go" style, e.g.::

with engine.connect() as connection:  # begin() wasn't called

    with connection.begin_nested(): will auto-"begin()" first
        connection.execute( ... )
    # savepoint is released

    connection.execute( ... )

    # explicitly commit outer transaction
    connection.commit()

    # can continue working with connection here

.. versionchanged:: 2.0

:meth:`_engine.Connection.begin_nested` will now participate
in the connection "autobegin" behavior that is new as of
2.0 / "future" style connections in 1.4.

.. seealso::

:meth:`_engine.Connection.begin`

:ref:`session_begin_nested` - ORM support for SAVEPOINT
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
def begin_nested(self) -> 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 <name>"
    and "ROLLBACK TO SAVEPOINT <name>". The name of the savepoint is local
    to the :class:`_engine.NestedTransaction` object and is generated
    automatically. Like any other :class:`_engine.Transaction`, the
    :class:`_engine.NestedTransaction` may be used as a context manager as
    illustrated above which will "release" or "rollback" corresponding to
    if the operation within the block were successful or raised an
    exception.

    Nested transactions require SAVEPOINT support in the underlying
    database, else the behavior is undefined. SAVEPOINT is commonly used to
    run operations within a transaction that may fail, while continuing the
    outer transaction. E.g.::

        from sqlalchemy import exc

        with engine.begin() as connection:
            trans = connection.begin_nested()
            try:
                connection.execute(table.insert(), {"username": "sandy"})
                trans.commit()
            except exc.IntegrityError:  # catch for duplicate username
                trans.rollback()  # rollback to savepoint

            # outer transaction continues
            connection.execute( ... )

    If :meth:`_engine.Connection.begin_nested` is called without first
    calling :meth:`_engine.Connection.begin` or
    :meth:`_engine.Engine.begin`, the :class:`_engine.Connection` object
    will "autobegin" the outer transaction first. This outer transaction
    may be committed using "commit-as-you-go" style, e.g.::

        with engine.connect() as connection:  # begin() wasn't called

            with connection.begin_nested(): will auto-"begin()" first
                connection.execute( ... )
            # savepoint is released

            connection.execute( ... )

            # explicitly commit outer transaction
            connection.commit()

            # can continue working with connection here

    .. versionchanged:: 2.0

        :meth:`_engine.Connection.begin_nested` will now participate
        in the connection "autobegin" behavior that is new as of
        2.0 / "future" style connections in 1.4.

    .. seealso::

        :meth:`_engine.Connection.begin`

        :ref:`session_begin_nested` - ORM support for SAVEPOINT

    """
    if self._transaction is None:
        self._autobegin()

    return NestedTransaction(self)

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
def begin_twophase(self, 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`

    """

    if self._transaction is not None:
        raise exc.InvalidRequestError(
            "Cannot start a two phase transaction when a transaction "
            "is already in progress."
        )
    if xid is None:
        xid = self.engine.dialect.create_xid()
    return TwoPhaseTransaction(self, xid)

commit

commit() -> None

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
def commit(self) -> None:
    """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.


    """
    if self._transaction:
        self._transaction.commit()

rollback

rollback() -> None

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
def rollback(self) -> None:
    """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.


    """
    if self._transaction:
        self._transaction.rollback()

in_transaction

in_transaction() -> bool

Return True if a transaction is in progress.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
def in_transaction(self) -> bool:
    """Return True if a transaction is in progress."""
    return self._transaction is not None and self._transaction.is_active

in_nested_transaction

in_nested_transaction() -> bool

Return True if a transaction is in progress.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
def in_nested_transaction(self) -> bool:
    """Return True if a transaction is in progress."""
    return (
        self._nested_transaction is not None
        and self._nested_transaction.is_active
    )

get_transaction

get_transaction() -> Optional[RootTransaction]

Return the current root transaction in progress, if any.

.. versionadded:: 1.4

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
def get_transaction(self) -> Optional[RootTransaction]:
    """Return the current root transaction in progress, if any.

    .. versionadded:: 1.4

    """

    return self._transaction

get_nested_transaction

get_nested_transaction() -> Optional[NestedTransaction]

Return the current nested transaction in progress, if any.

.. versionadded:: 1.4

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
def get_nested_transaction(self) -> Optional[NestedTransaction]:
    """Return the current nested transaction in progress, if any.

    .. versionadded:: 1.4

    """
    return self._nested_transaction

close

close() -> None

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
def close(self) -> None:
    """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.

    """

    if self._transaction:
        self._transaction.close()
        skip_reset = True
    else:
        skip_reset = False

    if self._dbapi_connection is not None:
        conn = self._dbapi_connection

        # as we just closed the transaction, close the connection
        # pool connection without doing an additional reset
        if skip_reset:
            cast("_ConnectionFairy", conn)._close_special(
                transaction_reset=True
            )
        else:
            conn.close()

        # There is a slight chance that conn.close() may have
        # triggered an invalidation here in which case
        # _dbapi_connection would already be None, however usually
        # it will be non-None here and in a "closed" state.
        self._dbapi_connection = None
    self.__can_reconnect = False

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
def scalar(
    self,
    statement: Executable,
    parameters: Optional[_CoreSingleExecuteParams] = None,
    *,
    execution_options: Optional[CoreExecuteOptionsParameter] = None,
) -> Any:
    r"""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.

    """
    distilled_parameters = _distill_params_20(parameters)
    try:
        meth = statement._execute_on_scalar
    except AttributeError as err:
        raise exc.ObjectNotExecutableError(statement) from err
    else:
        return meth(
            self,
            distilled_parameters,
            execution_options or NO_OPTIONS,
        )

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
def scalars(
    self,
    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

    """

    return self.execute(
        statement, parameters, execution_options=execution_options
    ).scalars()

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
def execute(
    self,
    statement: Executable,
    parameters: Optional[_CoreAnyExecuteParams] = None,
    *,
    execution_options: Optional[CoreExecuteOptionsParameter] = None,
) -> CursorResult[Any]:
    r"""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.

    """
    distilled_parameters = _distill_params_20(parameters)
    try:
        meth = statement._execute_on_connection
    except AttributeError as err:
        raise exc.ObjectNotExecutableError(statement) from err
    else:
        return meth(
            self,
            distilled_parameters,
            execution_options or NO_OPTIONS,
        )

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
def exec_driver_sql(
    self,
    statement: str,
    parameters: Optional[_DBAPIAnyExecuteParams] = None,
    execution_options: Optional[CoreExecuteOptionsParameter] = None,
) -> CursorResult[Any]:
    r"""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`

    """

    distilled_parameters = _distill_raw_params(parameters)

    execution_options = self._execution_options.merge_with(
        execution_options
    )

    dialect = self.dialect
    ret = self._execute_context(
        dialect,
        dialect.execution_ctx_cls._init_statement,
        statement,
        None,
        execution_options,
        statement,
        distilled_parameters,
    )

    return ret

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')

driver instance-attribute

driver: str

identifying name for the dialect's DBAPI

dbapi instance-attribute

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

type_compiler_instance: TypeCompiler

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

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

server_version_info: Optional[Tuple[Any, ...]]

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

default_schema_name: Optional[str]

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

execute_sequence_format: Union[
    Type[Tuple[Any, ...]], Type[Tuple[List[Any]]]
]

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

insertmanyvalues_implicit_sentinel: (
    InsertmanyvaluesSentinelOpts
)

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

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

reflection_options: Sequence[str] = ()

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

dbapi_exception_translation_map: Mapping[str, str] = (
    EMPTY_DICT
)

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

bind_typing = NONE

define a means of passing typing information to the database and/or driver for bound parameters.

See :class:.BindTyping for values.

.. versionadded:: 2.0

is_async instance-attribute

is_async: bool

Whether or not this dialect is intended for asyncio use.

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

engine_config_types: Mapping[str, Any]

a mapping of string keys that can be in an engine config linked to type conversion functions.

label_length instance-attribute

label_length: Optional[int]

optional user-defined max length for SQL labels

include_set_input_sizes instance-attribute

include_set_input_sizes: Optional[Set[Any]]

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

exclude_set_input_sizes: Optional[Set[Any]]

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 , where refers to a label in the columns clause of the SELECT

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
@util.non_memoized_property
def loaded_dbapi(self) -> ModuleType:
    """same as .dbapi, but is never None; will raise an error if no
    DBAPI was set up.

    .. versionadded:: 2.0

    """
    raise NotImplementedError()

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
def create_connect_args(self, 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`

    """

    raise NotImplementedError()

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
@classmethod
def import_dbapi(cls) -> 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.

    """
    raise NotImplementedError()

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
@classmethod
def type_descriptor(cls, typeobj: TypeEngine[_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.

    """

    raise NotImplementedError()

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
def initialize(self, 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.

    """

    pass

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
def get_columns(
    self,
    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`.

    """

    raise NotImplementedError()

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
def get_multi_columns(
    self,
    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

    """

    raise NotImplementedError()

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
def get_pk_constraint(
    self,
    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`.

    """
    raise NotImplementedError()

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
def get_multi_pk_constraint(
    self,
    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

    """
    raise NotImplementedError()

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
def get_foreign_keys(
    self,
    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`.
    """

    raise NotImplementedError()

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
def get_multi_foreign_keys(
    self,
    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

    """

    raise NotImplementedError()

get_table_names

get_table_names(
    connection: Connection,
    schema: Optional[str] = None,
    **kw: Any,
) -> List[str]

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
def get_table_names(
    self, connection: Connection, schema: Optional[str] = None, **kw: Any
) -> List[str]:
    """Return a list of table names for ``schema``.

    This is an internal dialect method. Applications should use
    :meth:`_engine.Inspector.get_table_names`.

    """

    raise NotImplementedError()

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
def get_temp_table_names(
    self, 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`.

    """

    raise NotImplementedError()

get_view_names

get_view_names(
    connection: Connection,
    schema: Optional[str] = None,
    **kw: Any,
) -> List[str]

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
def get_view_names(
    self, connection: Connection, schema: Optional[str] = None, **kw: Any
) -> List[str]:
    """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.

    """

    raise NotImplementedError()

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
def get_materialized_view_names(
    self, 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

    """

    raise NotImplementedError()

get_sequence_names

get_sequence_names(
    connection: Connection,
    schema: Optional[str] = None,
    **kw: Any,
) -> List[str]

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
def get_sequence_names(
    self, connection: Connection, schema: Optional[str] = None, **kw: Any
) -> List[str]:
    """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
    """

    raise NotImplementedError()

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
def get_temp_view_names(
    self, 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`.

    """

    raise NotImplementedError()

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
def get_schema_names(self, 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`.
    """
    raise NotImplementedError()

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
def get_view_definition(
    self,
    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.
    """

    raise NotImplementedError()

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
def get_indexes(
    self,
    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`.
    """

    raise NotImplementedError()

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
def get_multi_indexes(
    self,
    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

    """

    raise NotImplementedError()

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
def get_unique_constraints(
    self,
    connection: Connection,
    table_name: str,
    schema: Optional[str] = None,
    **kw: Any,
) -> List[ReflectedUniqueConstraint]:
    r"""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`.
    """

    raise NotImplementedError()

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
def get_multi_unique_constraints(
    self,
    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

    """

    raise NotImplementedError()

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
def get_check_constraints(
    self,
    connection: Connection,
    table_name: str,
    schema: Optional[str] = None,
    **kw: Any,
) -> List[ReflectedCheckConstraint]:
    r"""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`.

    """

    raise NotImplementedError()

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
def get_multi_check_constraints(
    self,
    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

    """

    raise NotImplementedError()

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
def get_table_options(
    self,
    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`.
    """
    raise NotImplementedError()

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
def get_multi_table_options(
    self,
    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

    """
    raise NotImplementedError()

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
def get_table_comment(
    self,
    connection: Connection,
    table_name: str,
    schema: Optional[str] = None,
    **kw: Any,
) -> ReflectedTableComment:
    r"""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

    """

    raise NotImplementedError()

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
def get_multi_table_comment(
    self,
    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

    """

    raise NotImplementedError()

normalize_name

normalize_name(name: str) -> str

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
def normalize_name(self, name: str) -> str:
    """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.

    """
    raise NotImplementedError()

denormalize_name

denormalize_name(name: str) -> str

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
def denormalize_name(self, name: str) -> str:
    """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.

    """
    raise NotImplementedError()

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
def has_table(
    self,
    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.

    """

    raise NotImplementedError()

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
def has_index(
    self,
    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

    """

    raise NotImplementedError()

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
def has_sequence(
    self,
    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`.
    """

    raise NotImplementedError()

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
def has_schema(
    self, 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

    """

    raise NotImplementedError()

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
def do_begin(self, 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`.

    """

    raise NotImplementedError()

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
def do_rollback(self, 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`.

    """

    raise NotImplementedError()

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
def do_commit(self, 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`.

    """

    raise NotImplementedError()

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
def do_terminate(self, 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

    """

    raise NotImplementedError()

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
def do_close(self, 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.

    """

    raise NotImplementedError()

do_ping

do_ping(dbapi_connection: DBAPIConnection) -> bool

ping the DBAPI connection and return True if the connection is usable.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
def do_ping(self, dbapi_connection: DBAPIConnection) -> bool:
    """ping the DBAPI connection and return True if the connection is
    usable."""
    raise NotImplementedError()

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
def do_set_input_sizes(
    self,
    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.


    """
    raise NotImplementedError()

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
def create_xid(self) -> 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.
    """

    raise NotImplementedError()

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
def do_savepoint(self, connection: Connection, name: str) -> None:
    """Create a savepoint with the given name.

    :param connection: a :class:`_engine.Connection`.
    :param name: savepoint name.

    """

    raise NotImplementedError()

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
def do_rollback_to_savepoint(
    self, connection: Connection, name: str
) -> None:
    """Rollback a connection to the named savepoint.

    :param connection: a :class:`_engine.Connection`.
    :param name: savepoint name.

    """

    raise NotImplementedError()

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
def do_release_savepoint(self, connection: Connection, name: str) -> None:
    """Release the named savepoint on a connection.

    :param connection: a :class:`_engine.Connection`.
    :param name: savepoint name.
    """

    raise NotImplementedError()

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
def do_begin_twophase(self, connection: Connection, xid: Any) -> None:
    """Begin a two phase transaction on the given connection.

    :param connection: a :class:`_engine.Connection`.
    :param xid: xid

    """

    raise NotImplementedError()

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
def do_prepare_twophase(self, connection: Connection, xid: Any) -> None:
    """Prepare a two phase transaction on the given connection.

    :param connection: a :class:`_engine.Connection`.
    :param xid: xid

    """

    raise NotImplementedError()

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
def do_rollback_twophase(
    self,
    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.

    """

    raise NotImplementedError()

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
def do_commit_twophase(
    self,
    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.

    """

    raise NotImplementedError()

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
def do_recover_twophase(self, connection: Connection) -> List[Any]:
    """Recover list of uncommitted prepared two phase transaction
    identifiers on the given connection.

    :param connection: a :class:`_engine.Connection`.

    """

    raise NotImplementedError()

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
def do_executemany(
    self,
    cursor: DBAPICursor,
    statement: str,
    parameters: _DBAPIMultiExecuteParams,
    context: Optional[ExecutionContext] = None,
) -> None:
    """Provide an implementation of ``cursor.executemany(statement,
    parameters)``."""

    raise NotImplementedError()

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
def do_execute(
    self,
    cursor: DBAPICursor,
    statement: str,
    parameters: Optional[_DBAPISingleExecuteParams],
    context: Optional[ExecutionContext] = None,
) -> None:
    """Provide an implementation of ``cursor.execute(statement,
    parameters)``."""

    raise NotImplementedError()

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
def do_execute_no_params(
    self,
    cursor: DBAPICursor,
    statement: str,
    context: Optional[ExecutionContext] = None,
) -> None:
    """Provide an implementation of ``cursor.execute(statement)``.

    The parameter collection should not be sent.

    """

    raise NotImplementedError()

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
def is_disconnect(
    self,
    e: Exception,
    connection: Optional[Union[PoolProxiedConnection, DBAPIConnection]],
    cursor: Optional[DBAPICursor],
) -> bool:
    """Return True if the given DB-API error indicates an invalid
    connection"""

    raise NotImplementedError()

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
def connect(self, *cargs: Any, **cparams: Any) -> DBAPIConnection:
    r"""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`

    """
    raise NotImplementedError()

on_connect_url

on_connect_url(url: URL) -> Optional[Callable[[Any], Any]]

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
def on_connect_url(self, url: URL) -> Optional[Callable[[Any], Any]]:
    """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`

    """
    return self.on_connect()

on_connect

on_connect() -> Optional[Callable[[Any], Any]]

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
def on_connect(self) -> Optional[Callable[[Any], Any]]:
    """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.

    """
    return None

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
def reset_isolation_level(self, 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

    """

    raise NotImplementedError()

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
def set_isolation_level(
    self, 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

    """

    raise NotImplementedError()

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
def get_isolation_level(
    self, 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


    """

    raise NotImplementedError()

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
def get_default_isolation_level(
    self, 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

    """
    raise NotImplementedError()

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
def get_isolation_level_values(
    self, 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

    """
    raise NotImplementedError()

get_dialect_cls classmethod

get_dialect_cls(url: URL) -> Type[Dialect]

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
@classmethod
def get_dialect_cls(cls, url: URL) -> Type[Dialect]:
    """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.

    """
    return cls

get_async_dialect_cls classmethod

get_async_dialect_cls(url: URL) -> Type[Dialect]

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
@classmethod
def get_async_dialect_cls(cls, url: URL) -> Type[Dialect]:
    """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`

    """
    return cls.get_dialect_cls(url)

load_provisioning classmethod

load_provisioning() -> None

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
@classmethod
def load_provisioning(cls) -> None:
    """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

    """

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
@classmethod
def engine_created(cls, 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.

    """

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
def get_driver_connection(self, 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

    """
    raise NotImplementedError()

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
def set_engine_execution_options(
    self, 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.

    """
    raise NotImplementedError()

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
def set_connection_execution_options(
    self, 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

    """
    raise NotImplementedError()

get_dialect_pool_class

get_dialect_pool_class(url: URL) -> Type[Pool]

return a Pool class to use for a given URL

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/interfaces.py
def get_dialect_pool_class(self, url: URL) -> Type[Pool]:
    """return a Pool class to use for a given URL"""
    raise NotImplementedError()

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
def __init__(
    self,
    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,
):
    self.pool = pool
    self.url = url
    self.dialect = dialect
    if logging_name:
        self.logging_name = logging_name
    self.echo = echo
    self.hide_parameters = hide_parameters
    if query_cache_size != 0:
        self._compiled_cache = util.LRUCache(
            query_cache_size, size_alert=self._lru_size_alert
        )
    else:
        self._compiled_cache = None
    log.instance_logger(self, echoflag=echo)
    if execution_options:
        self.update_execution_options(**execution_options)

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_compiled_cache() -> None

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
def clear_compiled_cache(self) -> None:
    """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

    """
    if self._compiled_cache:
        self._compiled_cache.clear()

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
def update_execution_options(self, **opt: Any) -> None:
    r"""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`

    """
    self.dispatch.set_engine_execution_options(self, opt)
    self._execution_options = self._execution_options.union(opt)
    self.dialect.set_engine_execution_options(self, opt)

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
def execution_options(self, **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`


    """  # noqa: E501
    return self._option_cls(self, opt)

get_execution_options

get_execution_options() -> _ExecuteOptions

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
def get_execution_options(self) -> _ExecuteOptions:
    """Get the non-SQL options which will take effect during execution.

    .. versionadded: 1.3

    .. seealso::

        :meth:`_engine.Engine.execution_options`
    """
    return self._execution_options

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
def dispose(self, 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`

    """
    if close:
        self.pool.dispose()
    self.pool = self.pool.recreate()
    self.dispatch.engine_disposed(self)

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
@contextlib.contextmanager
def begin(self) -> 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`.

    """
    with self.connect() as conn:
        with conn.begin():
            yield conn

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
def connect(self) -> 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`

    """

    return self._connection_cls(self)

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
def raw_connection(self) -> 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`

    """
    return self.pool.connect()

MappingResult

MappingResult(result: Result[Any])

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
def __init__(self, result: Result[Any]):
    self._real_result = result
    self._unique_filter_state = result._unique_filter_state
    self._metadata = result._metadata
    if result._source_supports_scalars:
        self._metadata = self._metadata._reduce([0])

closed property

closed: bool

Return True if the underlying :class:_engine.Result reports closed

.. versionadded:: 1.4.43

memoized_attribute

memoized_attribute(
    fget: Callable[..., _T], doc: Optional[str] = None
)

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
def __init__(self, fget: Callable[..., _T], doc: Optional[str] = None):
    self.fget = fget
    self.__doc__ = doc or fget.__doc__
    self.__name__ = fget.__name__

memoized_instancemethod classmethod

memoized_instancemethod(fn: _F) -> _F

Decorate a method memoize its return value.

:meta private:

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
@classmethod
def memoized_instancemethod(cls, fn: _F) -> _F:
    """Decorate a method memoize its return value.

    :meta private:

    """

    def oneshot(self: Any, *args: Any, **kw: Any) -> Any:
        result = fn(self, *args, **kw)

        def memo(*a, **kw):
            return result

        memo.__name__ = fn.__name__
        memo.__doc__ = fn.__doc__
        self.__dict__[fn.__name__] = memo
        self._memoized_keys |= {fn.__name__}
        return result

    return update_wrapper(oneshot, fn)  # type: ignore

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
@_generative
def yield_per(self, 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`

    """
    self._real_result = self._real_result.yield_per(num)
    return self

close

close() -> None

Close this :class:_engine.FilterResult.

.. versionadded:: 1.4.43

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
def close(self) -> None:
    """Close this :class:`_engine.FilterResult`.

    .. versionadded:: 1.4.43

    """
    self._real_result.close()

keys

keys() -> RMKeyView

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
def keys(self) -> RMKeyView:
    """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.


    """
    return self._metadata.keys

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
def unique(self, 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.

    """
    self._unique_filter_state = (set(), strategy)
    return self

columns

columns(*col_expressions: _KeyIndexType) -> Self

Establish the columns that should be returned in each row.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
def columns(self, *col_expressions: _KeyIndexType) -> Self:
    r"""Establish the columns that should be returned in each row."""
    return self._column_slices(col_expressions)

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
def partitions(
    self, 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.

    """

    getter = self._manyrow_getter

    while True:
        partition = getter(self, size)
        if partition:
            yield partition
        else:
            break

fetchall

fetchall() -> Sequence[RowMapping]

A synonym for the :meth:_engine.MappingResult.all method.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
def fetchall(self) -> Sequence[RowMapping]:
    """A synonym for the :meth:`_engine.MappingResult.all` method."""

    return self._allrows()

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
def fetchone(self) -> 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.

    """

    row = self._onerow_getter(self)
    if row is _NO_ROW:
        return None
    else:
        return row

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
def fetchmany(self, 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.

    """

    return self._manyrow_getter(self, size)

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
def all(self) -> 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.

    """

    return self._allrows()

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
def first(self) -> 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.


    """
    return self._only_one_row(
        raise_for_second_row=False, raise_for_none=False, scalar=False
    )

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
def one_or_none(self) -> 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.

    """
    return self._only_one_row(
        raise_for_second_row=True, raise_for_none=False, scalar=False
    )

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
def one(self) -> 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.

    """
    return self._only_one_row(
        raise_for_second_row=True, raise_for_none=True, scalar=False
    )

Result

Result(cursor_metadata: ResultMetaData)

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
def __init__(self, cursor_metadata: ResultMetaData):
    self._metadata = cursor_metadata

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

memoized_attribute(
    fget: Callable[..., _T], doc: Optional[str] = None
)

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
def __init__(self, fget: Callable[..., _T], doc: Optional[str] = None):
    self.fget = fget
    self.__doc__ = doc or fget.__doc__
    self.__name__ = fget.__name__

memoized_instancemethod classmethod

memoized_instancemethod(fn: _F) -> _F

Decorate a method memoize its return value.

:meta private:

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
@classmethod
def memoized_instancemethod(cls, fn: _F) -> _F:
    """Decorate a method memoize its return value.

    :meta private:

    """

    def oneshot(self: Any, *args: Any, **kw: Any) -> Any:
        result = fn(self, *args, **kw)

        def memo(*a, **kw):
            return result

        memo.__name__ = fn.__name__
        memo.__doc__ = fn.__doc__
        self.__dict__[fn.__name__] = memo
        self._memoized_keys |= {fn.__name__}
        return result

    return update_wrapper(oneshot, fn)  # type: ignore

keys

keys() -> RMKeyView

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
def keys(self) -> RMKeyView:
    """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.


    """
    return self._metadata.keys

close

close() -> None

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
def close(self) -> None:
    """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.

    """
    self._soft_close(hard=True)

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
@_generative
def yield_per(self, 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`

    """
    self._yield_per = num
    return self

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
@_generative
def unique(self, 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.

    """
    self._unique_filter_state = (set(), strategy)
    return self

columns

columns(*col_expressions: _KeyIndexType) -> Self

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
def columns(self, *col_expressions: _KeyIndexType) -> Self:
    r"""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.

    """
    return self._column_slices(col_expressions)

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
def scalars(self, 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.

    """
    return ScalarResult(self, index)

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
def mappings(self) -> 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.

    """

    return MappingResult(self)

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
def tuples(self) -> 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

    """

    return self  # type: ignore

partitions

partitions(
    size: Optional[int] = None,
) -> Iterator[Sequence[Row[_TP]]]

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
def partitions(
    self, size: Optional[int] = None
) -> Iterator[Sequence[Row[_TP]]]:
    """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`

    """

    getter = self._manyrow_getter

    while True:
        partition = getter(self, size)
        if partition:
            yield partition
        else:
            break

fetchall

fetchall() -> Sequence[Row[_TP]]

A synonym for the :meth:_engine.Result.all method.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
def fetchall(self) -> Sequence[Row[_TP]]:
    """A synonym for the :meth:`_engine.Result.all` method."""

    return self._allrows()

fetchone

fetchone() -> Optional[Row[_TP]]

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
def fetchone(self) -> Optional[Row[_TP]]:
    """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.

    """
    row = self._onerow_getter(self)
    if row is _NO_ROW:
        return None
    else:
        return row

fetchmany

fetchmany(size: Optional[int] = None) -> Sequence[Row[_TP]]

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
def fetchmany(self, size: Optional[int] = None) -> Sequence[Row[_TP]]:
    """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`

    """

    return self._manyrow_getter(self, size)

all

all() -> Sequence[Row[_TP]]

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
def all(self) -> Sequence[Row[_TP]]:
    """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.

    """

    return self._allrows()

first

first() -> Optional[Row[_TP]]

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
def first(self) -> Optional[Row[_TP]]:
    """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`

    """

    return self._only_one_row(
        raise_for_second_row=False, raise_for_none=False, scalar=False
    )

one_or_none

one_or_none() -> Optional[Row[_TP]]

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
def one_or_none(self) -> Optional[Row[_TP]]:
    """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`

    """
    return self._only_one_row(
        raise_for_second_row=True, raise_for_none=False, scalar=False
    )

scalar_one

scalar_one() -> _T
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
def scalar_one(self) -> 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`

    """
    return self._only_one_row(
        raise_for_second_row=True, raise_for_none=True, scalar=True
    )

scalar_one_or_none

scalar_one_or_none() -> Optional[_T]
scalar_one_or_none() -> Optional[Any]
scalar_one_or_none() -> Optional[Any]

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
def scalar_one_or_none(self) -> Optional[Any]:
    """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`

    """
    return self._only_one_row(
        raise_for_second_row=True, raise_for_none=False, scalar=True
    )

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
def one(self) -> 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`

    """
    return self._only_one_row(
        raise_for_second_row=True, raise_for_none=True, scalar=False
    )

scalar

scalar() -> Optional[_T]
scalar() -> Any
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
def scalar(self) -> 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.

    """
    return self._only_one_row(
        raise_for_second_row=False, raise_for_none=False, scalar=True
    )

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
def freeze(self) -> 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.

    """

    return FrozenResult(self)

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
def merge(self, *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.

    """
    return MergedResult(self._metadata, (self,) + others)

Row

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.

t property

t: _TP

A synonym for :meth:.Row._tuple.

.. versionadded:: 2.0

tuple

tuple() -> _TP

Return a 'tuple' form of this :class:.Row.

.. versionadded:: 2.0

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/row.py
@deprecated(
    "2.0.19",
    "The :meth:`.Row.tuple` method is deprecated in favor of "
    ":meth:`.Row._tuple`; all :class:`.Row` "
    "methods and library-level attributes are intended to be underscored "
    "to avoid name conflicts.  Please use :meth:`Row._tuple`.",
)
def tuple(self) -> _TP:
    """Return a 'tuple' form of this :class:`.Row`.

    .. versionadded:: 2.0

    """
    return self._tuple()

ScalarResult

ScalarResult(
    real_result: Result[Any], index: _KeyIndexType
)

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
def __init__(self, real_result: Result[Any], index: _KeyIndexType):
    self._real_result = real_result

    if real_result._source_supports_scalars:
        self._metadata = real_result._metadata
        self._post_creational_filter = None
    else:
        self._metadata = real_result._metadata._reduce([index])
        self._post_creational_filter = operator.itemgetter(0)

    self._unique_filter_state = real_result._unique_filter_state

closed property

closed: bool

Return True if the underlying :class:_engine.Result reports closed

.. versionadded:: 1.4.43

memoized_attribute

memoized_attribute(
    fget: Callable[..., _T], doc: Optional[str] = None
)

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
def __init__(self, fget: Callable[..., _T], doc: Optional[str] = None):
    self.fget = fget
    self.__doc__ = doc or fget.__doc__
    self.__name__ = fget.__name__

memoized_instancemethod classmethod

memoized_instancemethod(fn: _F) -> _F

Decorate a method memoize its return value.

:meta private:

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
@classmethod
def memoized_instancemethod(cls, fn: _F) -> _F:
    """Decorate a method memoize its return value.

    :meta private:

    """

    def oneshot(self: Any, *args: Any, **kw: Any) -> Any:
        result = fn(self, *args, **kw)

        def memo(*a, **kw):
            return result

        memo.__name__ = fn.__name__
        memo.__doc__ = fn.__doc__
        self.__dict__[fn.__name__] = memo
        self._memoized_keys |= {fn.__name__}
        return result

    return update_wrapper(oneshot, fn)  # type: ignore

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
@_generative
def yield_per(self, 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`

    """
    self._real_result = self._real_result.yield_per(num)
    return self

close

close() -> None

Close this :class:_engine.FilterResult.

.. versionadded:: 1.4.43

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
def close(self) -> None:
    """Close this :class:`_engine.FilterResult`.

    .. versionadded:: 1.4.43

    """
    self._real_result.close()

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
def unique(self, 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.

    """
    self._unique_filter_state = (set(), strategy)
    return self

partitions

partitions(
    size: Optional[int] = None,
) -> Iterator[Sequence[_R]]

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
def partitions(self, size: Optional[int] = None) -> Iterator[Sequence[_R]]:
    """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.

    """

    getter = self._manyrow_getter

    while True:
        partition = getter(self, size)
        if partition:
            yield partition
        else:
            break

fetchall

fetchall() -> Sequence[_R]

A synonym for the :meth:_engine.ScalarResult.all method.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
def fetchall(self) -> Sequence[_R]:
    """A synonym for the :meth:`_engine.ScalarResult.all` method."""

    return self._allrows()

fetchmany

fetchmany(size: Optional[int] = None) -> Sequence[_R]

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
def fetchmany(self, size: Optional[int] = None) -> Sequence[_R]:
    """Fetch many objects.

    Equivalent to :meth:`_engine.Result.fetchmany` except that
    scalar values, rather than :class:`_engine.Row` objects,
    are returned.

    """
    return self._manyrow_getter(self, size)

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
def all(self) -> 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.

    """
    return self._allrows()

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
def first(self) -> 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.


    """
    return self._only_one_row(
        raise_for_second_row=False, raise_for_none=False, scalar=False
    )

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
def one_or_none(self) -> 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.

    """
    return self._only_one_row(
        raise_for_second_row=True, raise_for_none=False, scalar=False
    )

one

one() -> _R

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
def one(self) -> _R:
    """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.

    """
    return self._only_one_row(
        raise_for_second_row=True, raise_for_none=True, scalar=False
    )

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
def __init__(self, connection: Connection):
    raise NotImplementedError()

close

close() -> None

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
def close(self) -> None:
    """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.

    """
    try:
        self._do_close()
    finally:
        assert not self.is_active

rollback

rollback() -> None

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
def rollback(self) -> None:
    """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.


    """
    try:
        self._do_rollback()
    finally:
        assert not self.is_active

commit

commit() -> None

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
def commit(self) -> None:
    """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.

    """
    try:
        self._do_commit()
    finally:
        assert not self.is_active

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

memoized_attribute(
    fget: Callable[..., _T], doc: Optional[str] = None
)

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
def __init__(self, fget: Callable[..., _T], doc: Optional[str] = None):
    self.fget = fget
    self.__doc__ = doc or fget.__doc__
    self.__name__ = fget.__name__

memoized_instancemethod classmethod

memoized_instancemethod(fn: _F) -> _F

Decorate a method memoize its return value.

:meta private:

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
@classmethod
def memoized_instancemethod(cls, fn: _F) -> _F:
    """Decorate a method memoize its return value.

    :meta private:

    """

    def oneshot(self: Any, *args: Any, **kw: Any) -> Any:
        result = fn(self, *args, **kw)

        def memo(*a, **kw):
            return result

        memo.__name__ = fn.__name__
        memo.__doc__ = fn.__doc__
        self.__dict__[fn.__name__] = memo
        self._memoized_keys |= {fn.__name__}
        return result

    return update_wrapper(oneshot, fn)  # type: ignore

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
@_generative
def yield_per(self, 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`

    """
    self._real_result = self._real_result.yield_per(num)
    return self

close

close() -> None

Close this :class:_engine.FilterResult.

.. versionadded:: 1.4.43

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
def close(self) -> None:
    """Close this :class:`_engine.FilterResult`.

    .. versionadded:: 1.4.43

    """
    self._real_result.close()

partitions

partitions(
    size: Optional[int] = None,
) -> Iterator[Sequence[_R]]

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
def partitions(
    self, size: Optional[int] = None
) -> Iterator[Sequence[_R]]:
    """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.

    """
    ...

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
def fetchone(self) -> Optional[_R]:
    """Fetch one tuple.

    Equivalent to :meth:`_engine.Result.fetchone` except that
    tuple values, rather than :class:`_engine.Row`
    objects, are returned.

    """
    ...

fetchall

fetchall() -> Sequence[_R]

A synonym for the :meth:_engine.ScalarResult.all method.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
def fetchall(self) -> Sequence[_R]:
    """A synonym for the :meth:`_engine.ScalarResult.all` method."""
    ...

fetchmany

fetchmany(size: Optional[int] = None) -> Sequence[_R]

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
def fetchmany(self, size: Optional[int] = None) -> Sequence[_R]:
    """Fetch many objects.

    Equivalent to :meth:`_engine.Result.fetchmany` except that
    tuple values, rather than :class:`_engine.Row` objects,
    are returned.

    """
    ...

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
def all(self) -> Sequence[_R]:  # noqa: A001
    """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.

    """
    ...

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
def first(self) -> 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.


    """
    ...

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
def one_or_none(self) -> 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.

    """
    ...

one

one() -> _R

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
def one(self) -> _R:
    """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.

    """
    ...

scalar_one

scalar_one() -> _T
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
def scalar_one(self) -> 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`

    """
    ...

scalar_one_or_none

scalar_one_or_none() -> Optional[_T]
scalar_one_or_none() -> Optional[Any]
scalar_one_or_none() -> Optional[Any]

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
def scalar_one_or_none(self) -> Optional[Any]:
    """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`

    """
    ...

scalar

scalar() -> Optional[_T]
scalar() -> Any
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
def scalar(self) -> 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.

    """
    ...

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_engine(
    url: Union[str, URL], **kwargs: Any
) -> Engine
create_engine(
    url: Union[str, URL], **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
@util.deprecated_params(
    strategy=(
        "1.4",
        "The :paramref:`_sa.create_engine.strategy` keyword is deprecated, "
        "and the only argument accepted is 'mock'; please use "
        ":func:`.create_mock_engine` going forward.  For general "
        "customization of create_engine which may have been accomplished "
        "using strategies, see :class:`.CreateEnginePlugin`.",
    ),
    empty_in_strategy=(
        "1.4",
        "The :paramref:`_sa.create_engine.empty_in_strategy` keyword is "
        "deprecated, and no longer has any effect.  All IN expressions "
        "are now rendered using "
        'the "expanding parameter" strategy which renders a set of bound'
        'expressions, or an "empty set" SELECT, at statement execution'
        "time.",
    ),
    implicit_returning=(
        "2.0",
        "The :paramref:`_sa.create_engine.implicit_returning` parameter "
        "is deprecated and will be removed in a future release. ",
    ),
)
def create_engine(url: Union[str, _url.URL], **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`

    """  # noqa

    if "strategy" in kwargs:
        strat = kwargs.pop("strategy")
        if strat == "mock":
            # this case is deprecated
            return create_mock_engine(url, **kwargs)  # type: ignore
        else:
            raise exc.ArgumentError("unknown strategy: %r" % strat)

    kwargs.pop("empty_in_strategy", None)

    # create url.URL object
    u = _url.make_url(url)

    u, plugins, kwargs = u._instantiate_plugins(kwargs)

    entrypoint = u._get_entrypoint()
    _is_async = kwargs.pop("_is_async", False)
    if _is_async:
        dialect_cls = entrypoint.get_async_dialect_cls(u)
    else:
        dialect_cls = entrypoint.get_dialect_cls(u)

    if kwargs.pop("_coerce_config", False):

        def pop_kwarg(key: str, default: Optional[Any] = None) -> Any:
            value = kwargs.pop(key, default)
            if key in dialect_cls.engine_config_types:
                value = dialect_cls.engine_config_types[key](value)
            return value

    else:
        pop_kwarg = kwargs.pop  # type: ignore

    dialect_args = {}
    # consume dialect arguments from kwargs
    for k in util.get_cls_kwargs(dialect_cls):
        if k in kwargs:
            dialect_args[k] = pop_kwarg(k)

    dbapi = kwargs.pop("module", None)
    if dbapi is None:
        dbapi_args = {}

        if "import_dbapi" in dialect_cls.__dict__:
            dbapi_meth = dialect_cls.import_dbapi

        elif hasattr(dialect_cls, "dbapi") and inspect.ismethod(
            dialect_cls.dbapi
        ):
            util.warn_deprecated(
                "The dbapi() classmethod on dialect classes has been "
                "renamed to import_dbapi().  Implement an import_dbapi() "
                f"classmethod directly on class {dialect_cls} to remove this "
                "warning; the old .dbapi() classmethod may be maintained for "
                "backwards compatibility.",
                "2.0",
            )
            dbapi_meth = dialect_cls.dbapi
        else:
            dbapi_meth = dialect_cls.import_dbapi

        for k in util.get_func_kwargs(dbapi_meth):
            if k in kwargs:
                dbapi_args[k] = pop_kwarg(k)
        dbapi = dbapi_meth(**dbapi_args)

    dialect_args["dbapi"] = dbapi

    dialect_args.setdefault("compiler_linting", compiler.NO_LINTING)
    enable_from_linting = kwargs.pop("enable_from_linting", True)
    if enable_from_linting:
        dialect_args["compiler_linting"] ^= compiler.COLLECT_CARTESIAN_PRODUCTS

    for plugin in plugins:
        plugin.handle_dialect_kwargs(dialect_cls, dialect_args)

    # create dialect
    dialect = dialect_cls(**dialect_args)

    # assemble connection arguments
    (cargs_tup, cparams) = dialect.create_connect_args(u)
    cparams.update(pop_kwarg("connect_args", {}))

    if "async_fallback" in cparams and util.asbool(cparams["async_fallback"]):
        util.warn_deprecated(
            "The async_fallback dialect argument is deprecated and will be "
            "removed in SQLAlchemy 2.1.",
            "2.0",
        )

    cargs = list(cargs_tup)  # allow mutability

    # look for existing pool or create
    pool = pop_kwarg("pool", None)
    if pool is None:

        def connect(
            connection_record: Optional[ConnectionPoolEntry] = None,
        ) -> DBAPIConnection:
            if dialect._has_events:
                for fn in dialect.dispatch.do_connect:
                    connection = cast(
                        DBAPIConnection,
                        fn(dialect, connection_record, cargs, cparams),
                    )
                    if connection is not None:
                        return connection

            return dialect.connect(*cargs, **cparams)

        creator = pop_kwarg("creator", connect)

        poolclass = pop_kwarg("poolclass", None)
        if poolclass is None:
            poolclass = dialect.get_dialect_pool_class(u)
        pool_args = {"dialect": dialect}

        # consume pool arguments from kwargs, translating a few of
        # the arguments
        for k in util.get_cls_kwargs(poolclass):
            tk = _pool_translate_kwargs.get(k, k)
            if tk in kwargs:
                pool_args[k] = pop_kwarg(tk)

        for plugin in plugins:
            plugin.handle_pool_kwargs(poolclass, pool_args)

        pool = poolclass(creator, **pool_args)
    else:
        pool._dialect = dialect

    # create engine.
    if not pop_kwarg("future", True):
        raise exc.ArgumentError(
            "The 'future' parameter passed to "
            "create_engine() may only be set to True."
        )

    engineclass = base.Engine

    engine_args = {}
    for k in util.get_cls_kwargs(engineclass):
        if k in kwargs:
            engine_args[k] = pop_kwarg(k)

    # internal flags used by the test suite for instrumenting / proxying
    # engines with mocks etc.
    _initialize = kwargs.pop("_initialize", True)

    # all kwargs should be consumed
    if kwargs:
        raise TypeError(
            "Invalid argument(s) %s sent to create_engine(), "
            "using configuration %s/%s/%s.  Please check that the "
            "keyword arguments are appropriate for this combination "
            "of components."
            % (
                ",".join("'%s'" % k for k in kwargs),
                dialect.__class__.__name__,
                pool.__class__.__name__,
                engineclass.__name__,
            )
        )

    engine = engineclass(pool, dialect, u, **engine_args)

    if _initialize:
        do_on_connect = dialect.on_connect_url(u)
        if do_on_connect:

            def on_connect(
                dbapi_connection: DBAPIConnection,
                connection_record: ConnectionPoolEntry,
            ) -> None:
                assert do_on_connect is not None
                do_on_connect(dbapi_connection)

            event.listen(pool, "connect", on_connect)

        builtin_on_connect = dialect._builtin_onconnect()
        if builtin_on_connect:
            event.listen(pool, "connect", builtin_on_connect)

        def first_connect(
            dbapi_connection: DBAPIConnection,
            connection_record: ConnectionPoolEntry,
        ) -> None:
            c = base.Connection(
                engine,
                connection=_AdhocProxiedConnection(
                    dbapi_connection, connection_record
                ),
                _has_events=False,
                # reconnecting will be a reentrant condition, so if the
                # connection goes away, Connection is then closed
                _allow_revalidate=False,
                # dont trigger the autobegin sequence
                # within the up front dialect checks
                _allow_autobegin=False,
            )
            c._execution_options = util.EMPTY_DICT

            try:
                dialect.initialize(c)
            finally:
                # note that "invalidated" and "closed" are mutually
                # exclusive in 1.4 Connection.
                if not c.invalidated and not c.closed:
                    # transaction is rolled back otherwise, tested by
                    # test/dialect/postgresql/test_dialect.py
                    # ::MiscBackendTest::test_initial_transaction_state
                    dialect.do_rollback(c.connection)

        # previously, the "first_connect" event was used here, which was then
        # scaled back if the "on_connect" handler were present.  now,
        # since "on_connect" is virtually always present, just use
        # "connect" event with once_unless_exception in all cases so that
        # the connection event flow is consistent in all cases.
        event.listen(
            pool, "connect", first_connect, _once_unless_exception=True
        )

    dialect_cls.engine_created(engine)
    if entrypoint is not dialect_cls:
        entrypoint.engine_created(engine)

    for plugin in plugins:
        plugin.engine_created(engine)

    return engine

create_mock_engine

create_mock_engine(
    url: Union[str, URL], executor: Any, **kw: Any
) -> MockConnection

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
def create_mock_engine(
    url: Union[str, URL], executor: Any, **kw: Any
) -> MockConnection:
    """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`

    """

    # create url.URL object
    u = _url.make_url(url)

    dialect_cls = u.get_dialect()

    dialect_args = {}
    # consume dialect arguments from kwargs
    for k in util.get_cls_kwargs(dialect_cls):
        if k in kw:
            dialect_args[k] = kw.pop(k)

    # create dialect
    dialect = dialect_cls(**dialect_args)

    return MockConnection(dialect, executor)

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.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/engine/create.py
def 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.

    """

    options = {
        key[len(prefix) :]: configuration[key]
        for key in configuration
        if key.startswith(prefix)
    }
    options["_coerce_config"] = True
    options.update(kwargs)
    url = options.pop("url")
    return create_engine(url, **options)