class documentation

class AsyncConnection(ProxyComparable[Connection], StartableContext['AsyncConnection'], AsyncConnectable): (source)

View In Hierarchy

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

Async Method __aexit__ Undocumented
Method __await__ Undocumented
Method __init__ Undocumented
Method begin Begin a transaction prior to autobegin occurring.
Method begin_nested Begin a nested transaction and return a transaction handle.
Async Method close Close this :class:`_asyncio.AsyncConnection`.
Async Method commit Commit the transaction that is currently in progress.
Method dialect.setter Undocumented
Async Method exec_driver_sql Executes a driver-level SQL string and return buffered :class:`_engine.Result`.
Async Method execute Executes a SQL statement construct and return a buffered :class:`_engine.Result`.
Async Method execution_options Set non-SQL options for the connection which take effect during execution.
Async Method get_isolation_level Undocumented
Method get_nested_transaction Return an :class:`.AsyncTransaction` representing the current nested (savepoint) transaction, if any.
Async Method get_raw_connection Return the pooled DBAPI-level connection in use by this :class:`_asyncio.AsyncConnection`.
Method get_transaction Return an :class:`.AsyncTransaction` representing the current transaction, if any.
Method in_nested_transaction Return True if a transaction is in progress.
Method in_transaction Return True if a transaction is in progress.
Async Method invalidate Invalidate the underlying DBAPI connection associated with this :class:`_engine.Connection`.
Async Method rollback Roll back the transaction that is currently in progress.
Async Method run_sync Invoke the given sync callable passing self as the first argument.
Async Method scalar Executes a SQL statement construct and returns a scalar object.
Async Method scalars Executes a SQL statement construct and returns a scalar objects.
Async Method start Start this :class:`_asyncio.AsyncConnection` object's context outside of using a Python ``with:`` block.
Async Method stream Execute a statement and return an awaitable yielding a :class:`_asyncio.AsyncResult` object.
Async Method stream_scalars Execute a statement and return an awaitable yielding a :class:`_asyncio.AsyncScalarResult` object.
Class Variable __slots__ Undocumented
Instance Variable engine Undocumented
Instance Variable sync_connection Reference to the sync-style :class:`_engine.Connection` this :class:`_asyncio.AsyncConnection` proxies requests towards.
Instance Variable sync_engine Reference to the sync-style :class:`_engine.Engine` this :class:`_asyncio.AsyncConnection` is associated with via its underlying :class:`_engine.Connection`.
Property closed Return True if this connection is closed.
Property connection Not implemented for async; call :meth:`_asyncio.AsyncConnection.get_raw_connection`.
Property default_isolation_level The default isolation level assigned to this :class:`_engine.Connection`.
Property dialect Proxy for the :attr:`_engine.Connection.dialect` attribute on behalf of the :class:`_asyncio.AsyncConnection` class.
Property info Return the :attr:`_engine.Connection.info` dictionary of the underlying :class:`_engine.Connection`.
Property invalidated Return True if this connection was invalidated.
Class Method _regenerate_proxy_for_target Undocumented
Property _proxied Undocumented

Inherited from ProxyComparable:

Method __eq__ Undocumented
Method __hash__ Undocumented
Method __ne__ Undocumented

Inherited from ReversibleProxy (via ProxyComparable):

Class Method _retrieve_proxy_for_target Undocumented
Class Method _target_gced Undocumented
Method _assign_proxied Undocumented
Class Variable _proxy_objects Undocumented

Inherited from StartableContext (via ProxyComparable, ReversibleProxy):

Async Method __aenter__ Undocumented
Method _raise_for_not_started Undocumented

Inherited from AsyncConnectable (via ProxyComparable, ReversibleProxy, StartableContext):

Class Method _no_async_engine_events Undocumented
async def __aexit__(self, type_: Any, value: Any, traceback: Any): (source)
def __init__(self, async_engine: AsyncEngine, sync_connection: Optional[Connection] = None): (source)

Undocumented

def begin(self) -> AsyncTransaction: (source)

Begin a transaction prior to autobegin occurring.

def begin_nested(self) -> AsyncTransaction: (source)

Begin a nested transaction and return a transaction handle.

async def close(self): (source)

Close this :class:`_asyncio.AsyncConnection`. This has the effect of also rolling back the transaction if one is in place.

async def commit(self): (source)

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.

@dialect.setter
def dialect(self, attr: Any): (source)

Undocumented

async def exec_driver_sql(self, statement: str, parameters: Optional[_DBAPIAnyExecuteParams] = None, execution_options: Optional[CoreExecuteOptionsParameter] = None) -> CursorResult[Any]: (source)

Executes a driver-level SQL string and return buffered :class:`_engine.Result`.

@overload
async def execute(self, statement: TypedReturnsRows[_T], parameters: Optional[_CoreAnyExecuteParams] = None, *, execution_options: Optional[CoreExecuteOptionsParameter] = None) -> CursorResult[_T]:
@overload
async def execute(self, statement: Executable, parameters: Optional[_CoreAnyExecuteParams] = None, *, execution_options: Optional[CoreExecuteOptionsParameter] = None) -> CursorResult[Any]:
(source)

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.

@overload
async def execution_options(self, *, 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:
@overload
async def execution_options(self, **opt: Any) -> AsyncConnection:
(source)

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.

async def get_isolation_level(self) -> IsolationLevel: (source)

Undocumented

def get_nested_transaction(self) -> Optional[AsyncTransaction]: (source)

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

async def get_raw_connection(self) -> PoolProxiedConnection: (source)

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.

def get_transaction(self) -> Optional[AsyncTransaction]: (source)

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

def in_nested_transaction(self) -> bool: (source)

Return True if a transaction is in progress. .. versionadded:: 1.4.0b2

def in_transaction(self) -> bool: (source)

Return True if a transaction is in progress.

async def invalidate(self, exception: Optional[BaseException] = None): (source)

Invalidate the underlying DBAPI connection associated with this :class:`_engine.Connection`. See the method :meth:`_engine.Connection.invalidate` for full detail on this method.

async def rollback(self): (source)

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.

async def run_sync(self, fn: Callable[..., Any], *arg: Any, **kw: Any) -> Any: (source)

Invoke the given sync callable passing self as the first argument. 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. E.g.:: 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:: :ref:`session_run_sync`

@overload
async def scalar(self, statement: TypedReturnsRows[Tuple[_T]], parameters: Optional[_CoreSingleExecuteParams] = None, *, execution_options: Optional[CoreExecuteOptionsParameter] = None) -> Optional[_T]:
@overload
async def scalar(self, statement: Executable, parameters: Optional[_CoreSingleExecuteParams] = None, *, execution_options: Optional[CoreExecuteOptionsParameter] = None) -> Any:
(source)

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.

@overload
async def scalars(self, statement: TypedReturnsRows[Tuple[_T]], parameters: Optional[_CoreAnyExecuteParams] = None, *, execution_options: Optional[CoreExecuteOptionsParameter] = None) -> ScalarResult[_T]:
@overload
async def scalars(self, statement: Executable, parameters: Optional[_CoreAnyExecuteParams] = None, *, execution_options: Optional[CoreExecuteOptionsParameter] = None) -> ScalarResult[Any]:
(source)

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

async def start(self, is_ctxmanager: bool = False) -> AsyncConnection: (source)

Start this :class:`_asyncio.AsyncConnection` object's context outside of using a Python ``with:`` block.

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`

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`

Undocumented

sync_connection = (source)

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`

sync_engine: Engine = (source)

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`

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.

Not implemented for async; call :meth:`_asyncio.AsyncConnection.get_raw_connection`.

@property
default_isolation_level: Any = (source)

The default isolation level assigned to this :class:`_engine.Connection`. .. container:: class_bases Proxied for the :class:`_engine.Connection` class on behalf of the :class:`_asyncio.AsyncConnection` class. This is the isolation level setting that the :class:`_engine.Connection` has when first procured via the :meth:`_engine.Engine.connect` method. This level stays in place until the :paramref:`.Connection.execution_options.isolation_level` is used to change the setting on a per-:class:`_engine.Connection` basis. Unlike :meth:`_engine.Connection.get_isolation_level`, this attribute is set ahead of time from the first connection procured by the dialect, so SQL query is not invoked when this accessor is called. .. versionadded:: 0.9.9 .. seealso:: :meth:`_engine.Connection.get_isolation_level` - view current level :paramref:`_sa.create_engine.isolation_level` - set per :class:`_engine.Engine` isolation level :paramref:`.Connection.execution_options.isolation_level` - set per :class:`_engine.Connection` isolation level

Proxy for the :attr:`_engine.Connection.dialect` attribute on behalf of the :class:`_asyncio.AsyncConnection` class.

@util.ro_non_memoized_property
info: _InfoType = (source)

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

@property
invalidated: Any = (source)

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

@classmethod
def _regenerate_proxy_for_target(cls, target: Connection) -> AsyncConnection: (source)
@util.ro_non_memoized_property
_proxied: Connection = (source)