SQLAlchemy 1.4 Documentation
SQLAlchemy ORM
- ORM Quick Start
- Object Relational Tutorial (1.x API)
- ORM Mapped Class Configuration
- Relationship Configuration
- Querying Data, Loading Objects
- Using the Session
- Events and Internals
- ORM Extensions
- Asynchronous I/O (asyncio)¶
- Asyncio Platform Installation Notes (Including Apple M1)
- Synopsis - Core
- Synopsis - ORM
- Using events with the asyncio extension
- Using multiple asyncio event loops
- Using asyncio scoped session
- Using the Inspector to inspect schema objects
- Engine API Documentation
create_async_engine()
async_engine_from_config()
AsyncEngine
AsyncConnection
AsyncConnection.begin()
AsyncConnection.begin_nested()
AsyncConnection.close()
AsyncConnection.commit()
AsyncConnection.connection
AsyncConnection.exec_driver_sql()
AsyncConnection.execute()
AsyncConnection.execution_options()
AsyncConnection.get_nested_transaction()
AsyncConnection.get_raw_connection()
AsyncConnection.get_transaction()
AsyncConnection.in_nested_transaction()
AsyncConnection.in_transaction()
AsyncConnection.info
AsyncConnection.invalidate()
AsyncConnection.rollback()
AsyncConnection.run_sync()
AsyncConnection.scalar()
AsyncConnection.scalars()
AsyncConnection.start()
AsyncConnection.stream()
AsyncConnection.stream_scalars()
AsyncConnection.sync_connection
AsyncConnection.sync_engine
AsyncTransaction
- Result Set API Documentation
AsyncResult
AsyncResult.all()
AsyncResult.close()
AsyncResult.closed
AsyncResult.columns()
AsyncResult.fetchmany()
AsyncResult.fetchone()
AsyncResult.first()
AsyncResult.freeze()
AsyncResult.keys()
AsyncResult.mappings()
AsyncResult.memoized_instancemethod()
AsyncResult.one()
AsyncResult.one_or_none()
AsyncResult.partitions()
AsyncResult.scalar()
AsyncResult.scalar_one()
AsyncResult.scalar_one_or_none()
AsyncResult.scalars()
AsyncResult.unique()
AsyncResult.yield_per()
AsyncScalarResult
AsyncScalarResult.all()
AsyncScalarResult.close()
AsyncScalarResult.closed
AsyncScalarResult.fetchall()
AsyncScalarResult.fetchmany()
AsyncScalarResult.first()
AsyncScalarResult.memoized_instancemethod()
AsyncScalarResult.one()
AsyncScalarResult.one_or_none()
AsyncScalarResult.partitions()
AsyncScalarResult.unique()
AsyncScalarResult.yield_per()
AsyncMappingResult
AsyncMappingResult.all()
AsyncMappingResult.close()
AsyncMappingResult.closed
AsyncMappingResult.columns()
AsyncMappingResult.fetchall()
AsyncMappingResult.fetchmany()
AsyncMappingResult.fetchone()
AsyncMappingResult.first()
AsyncMappingResult.keys()
AsyncMappingResult.memoized_instancemethod()
AsyncMappingResult.one()
AsyncMappingResult.one_or_none()
AsyncMappingResult.partitions()
AsyncMappingResult.unique()
AsyncMappingResult.yield_per()
- ORM Session API Documentation
async_object_session()
async_session()
async_scoped_session
async_scoped_session.__call__()
async_scoped_session.__init__()
async_scoped_session.add()
async_scoped_session.add_all()
async_scoped_session.autoflush
async_scoped_session.begin()
async_scoped_session.begin_nested()
async_scoped_session.close()
async_scoped_session.close_all()
async_scoped_session.commit()
async_scoped_session.configure()
async_scoped_session.connection()
async_scoped_session.delete()
async_scoped_session.deleted
async_scoped_session.dirty
async_scoped_session.execute()
async_scoped_session.expire()
async_scoped_session.expire_all()
async_scoped_session.expunge()
async_scoped_session.expunge_all()
async_scoped_session.flush()
async_scoped_session.get()
async_scoped_session.get_bind()
async_scoped_session.identity_key()
async_scoped_session.identity_map
async_scoped_session.info
async_scoped_session.invalidate()
async_scoped_session.is_active
async_scoped_session.is_modified()
async_scoped_session.merge()
async_scoped_session.new
async_scoped_session.no_autoflush
async_scoped_session.object_session()
async_scoped_session.refresh()
async_scoped_session.remove()
async_scoped_session.rollback()
async_scoped_session.scalar()
async_scoped_session.scalars()
async_scoped_session.stream()
async_scoped_session.stream_scalars()
AsyncSession
AsyncSession.sync_session_class
AsyncSession.__init__()
AsyncSession.add()
AsyncSession.add_all()
AsyncSession.begin()
AsyncSession.begin_nested()
AsyncSession.close()
AsyncSession.close_all()
AsyncSession.commit()
AsyncSession.connection()
AsyncSession.delete()
AsyncSession.deleted
AsyncSession.dirty
AsyncSession.execute()
AsyncSession.expire()
AsyncSession.expire_all()
AsyncSession.expunge()
AsyncSession.expunge_all()
AsyncSession.flush()
AsyncSession.get()
AsyncSession.get_bind()
AsyncSession.get_nested_transaction()
AsyncSession.get_transaction()
AsyncSession.identity_key()
AsyncSession.in_nested_transaction()
AsyncSession.in_transaction()
AsyncSession.info
AsyncSession.invalidate()
AsyncSession.is_active
AsyncSession.is_modified()
AsyncSession.merge()
AsyncSession.new
AsyncSession.no_autoflush
AsyncSession.object_session()
AsyncSession.refresh()
AsyncSession.rollback()
AsyncSession.run_sync()
AsyncSession.scalar()
AsyncSession.scalars()
AsyncSession.stream()
AsyncSession.stream_scalars()
AsyncSession.sync_session
AsyncSessionTransaction
- Association Proxy
- Automap
- Baked Queries
- Declarative Extensions
- Mypy / Pep-484 Support for ORM Mappings
- Mutation Tracking
- Ordering List
- Horizontal Sharding
- Hybrid Attributes
- Indexable
- Alternate Class Instrumentation
- Asynchronous I/O (asyncio)¶
- ORM Examples
Project Versions
- Previous: ORM Extensions
- Next: Association Proxy
- Up: Home
- On this page:
- Asynchronous I/O (asyncio)
- Asyncio Platform Installation Notes (Including Apple M1)
- Synopsis - Core
- Synopsis - ORM
- Using events with the asyncio extension
- Using multiple asyncio event loops
- Using asyncio scoped session
- Using the Inspector to inspect schema objects
- Engine API Documentation
create_async_engine()
async_engine_from_config()
AsyncEngine
AsyncConnection
AsyncConnection.begin()
AsyncConnection.begin_nested()
AsyncConnection.close()
AsyncConnection.commit()
AsyncConnection.connection
AsyncConnection.exec_driver_sql()
AsyncConnection.execute()
AsyncConnection.execution_options()
AsyncConnection.get_nested_transaction()
AsyncConnection.get_raw_connection()
AsyncConnection.get_transaction()
AsyncConnection.in_nested_transaction()
AsyncConnection.in_transaction()
AsyncConnection.info
AsyncConnection.invalidate()
AsyncConnection.rollback()
AsyncConnection.run_sync()
AsyncConnection.scalar()
AsyncConnection.scalars()
AsyncConnection.start()
AsyncConnection.stream()
AsyncConnection.stream_scalars()
AsyncConnection.sync_connection
AsyncConnection.sync_engine
AsyncTransaction
- Result Set API Documentation
AsyncResult
AsyncResult.all()
AsyncResult.close()
AsyncResult.closed
AsyncResult.columns()
AsyncResult.fetchmany()
AsyncResult.fetchone()
AsyncResult.first()
AsyncResult.freeze()
AsyncResult.keys()
AsyncResult.mappings()
AsyncResult.memoized_instancemethod()
AsyncResult.one()
AsyncResult.one_or_none()
AsyncResult.partitions()
AsyncResult.scalar()
AsyncResult.scalar_one()
AsyncResult.scalar_one_or_none()
AsyncResult.scalars()
AsyncResult.unique()
AsyncResult.yield_per()
AsyncScalarResult
AsyncScalarResult.all()
AsyncScalarResult.close()
AsyncScalarResult.closed
AsyncScalarResult.fetchall()
AsyncScalarResult.fetchmany()
AsyncScalarResult.first()
AsyncScalarResult.memoized_instancemethod()
AsyncScalarResult.one()
AsyncScalarResult.one_or_none()
AsyncScalarResult.partitions()
AsyncScalarResult.unique()
AsyncScalarResult.yield_per()
AsyncMappingResult
AsyncMappingResult.all()
AsyncMappingResult.close()
AsyncMappingResult.closed
AsyncMappingResult.columns()
AsyncMappingResult.fetchall()
AsyncMappingResult.fetchmany()
AsyncMappingResult.fetchone()
AsyncMappingResult.first()
AsyncMappingResult.keys()
AsyncMappingResult.memoized_instancemethod()
AsyncMappingResult.one()
AsyncMappingResult.one_or_none()
AsyncMappingResult.partitions()
AsyncMappingResult.unique()
AsyncMappingResult.yield_per()
- ORM Session API Documentation
async_object_session()
async_session()
async_scoped_session
async_scoped_session.__call__()
async_scoped_session.__init__()
async_scoped_session.add()
async_scoped_session.add_all()
async_scoped_session.autoflush
async_scoped_session.begin()
async_scoped_session.begin_nested()
async_scoped_session.close()
async_scoped_session.close_all()
async_scoped_session.commit()
async_scoped_session.configure()
async_scoped_session.connection()
async_scoped_session.delete()
async_scoped_session.deleted
async_scoped_session.dirty
async_scoped_session.execute()
async_scoped_session.expire()
async_scoped_session.expire_all()
async_scoped_session.expunge()
async_scoped_session.expunge_all()
async_scoped_session.flush()
async_scoped_session.get()
async_scoped_session.get_bind()
async_scoped_session.identity_key()
async_scoped_session.identity_map
async_scoped_session.info
async_scoped_session.invalidate()
async_scoped_session.is_active
async_scoped_session.is_modified()
async_scoped_session.merge()
async_scoped_session.new
async_scoped_session.no_autoflush
async_scoped_session.object_session()
async_scoped_session.refresh()
async_scoped_session.remove()
async_scoped_session.rollback()
async_scoped_session.scalar()
async_scoped_session.scalars()
async_scoped_session.stream()
async_scoped_session.stream_scalars()
AsyncSession
AsyncSession.sync_session_class
AsyncSession.__init__()
AsyncSession.add()
AsyncSession.add_all()
AsyncSession.begin()
AsyncSession.begin_nested()
AsyncSession.close()
AsyncSession.close_all()
AsyncSession.commit()
AsyncSession.connection()
AsyncSession.delete()
AsyncSession.deleted
AsyncSession.dirty
AsyncSession.execute()
AsyncSession.expire()
AsyncSession.expire_all()
AsyncSession.expunge()
AsyncSession.expunge_all()
AsyncSession.flush()
AsyncSession.get()
AsyncSession.get_bind()
AsyncSession.get_nested_transaction()
AsyncSession.get_transaction()
AsyncSession.identity_key()
AsyncSession.in_nested_transaction()
AsyncSession.in_transaction()
AsyncSession.info
AsyncSession.invalidate()
AsyncSession.is_active
AsyncSession.is_modified()
AsyncSession.merge()
AsyncSession.new
AsyncSession.no_autoflush
AsyncSession.object_session()
AsyncSession.refresh()
AsyncSession.rollback()
AsyncSession.run_sync()
AsyncSession.scalar()
AsyncSession.scalars()
AsyncSession.stream()
AsyncSession.stream_scalars()
AsyncSession.sync_session
AsyncSessionTransaction
Asynchronous I/O (asyncio)¶
Support for Python asyncio. Support for Core and ORM usage is included, using asyncio-compatible dialects.
New in version 1.4.
Warning
Please read Asyncio Platform Installation Notes (Including Apple M1) for important platform installation notes for many platforms, including Apple M1 Architecture.
Tip
The asyncio extension as of SQLAlchemy 1.4.3 can now be considered to be beta level software. API details are subject to change however at this point it is unlikely for there to be significant backwards-incompatible changes.
See also
Asynchronous IO Support for Core and ORM - initial feature announcement
Asyncio Integration - example scripts illustrating working examples of Core and ORM use within the asyncio extension.
Asyncio Platform Installation Notes (Including Apple M1)¶
The asyncio extension requires Python 3 only. It also depends upon the greenlet library. This dependency is installed by default on common machine platforms including:
x86_64 aarch64 ppc64le amd64 win32
For the above platforms, greenlet
is known to supply pre-built wheel files.
For other platforms, greenlet does not install by default;
the current file listing for greenlet can be seen at
Greenlet - Download Files.
Note that there are many architectures omitted, including Apple M1.
To install SQLAlchemy while ensuring the greenlet
dependency is present
regardless of what platform is in use, the
[asyncio]
setuptools extra
may be installed
as follows, which will include also instruct pip
to install greenlet
:
pip install sqlalchemy[asyncio]
Note that installation of greenlet
on platforms that do not have a pre-built
wheel file means that greenlet
will be built from source, which requires
that Python’s development libraries also be present.
Synopsis - Core¶
For Core use, the create_async_engine()
function creates an
instance of AsyncEngine
which then offers an async version of
the traditional Engine
API. The
AsyncEngine
delivers an AsyncConnection
via
its AsyncEngine.connect()
and AsyncEngine.begin()
methods which both deliver asynchronous context managers. The
AsyncConnection
can then invoke statements using either the
AsyncConnection.execute()
method to deliver a buffered
Result
, or the AsyncConnection.stream()
method
to deliver a streaming server-side AsyncResult
:
import asyncio
from sqlalchemy.ext.asyncio import create_async_engine
async def async_main():
engine = create_async_engine(
"postgresql+asyncpg://scott:tiger@localhost/test",
echo=True,
)
async with engine.begin() as conn:
await conn.run_sync(meta.drop_all)
await conn.run_sync(meta.create_all)
await conn.execute(
t1.insert(), [{"name": "some name 1"}, {"name": "some name 2"}]
)
async with engine.connect() as conn:
# select a Result, which will be delivered with buffered
# results
result = await conn.execute(select(t1).where(t1.c.name == "some name 1"))
print(result.fetchall())
# for AsyncEngine created in function scope, close and
# clean-up pooled connections
await engine.dispose()
asyncio.run(async_main())
Above, the AsyncConnection.run_sync()
method may be used to
invoke special DDL functions such as MetaData.create_all()
that
don’t include an awaitable hook.
Tip
It’s advisable to invoke the AsyncEngine.dispose()
method
using await
when using the AsyncEngine
object in a
scope that will go out of context and be garbage collected, as illustrated in the
async_main
function in the above example. This ensures that any
connections held open by the connection pool will be properly disposed
within an awaitable context. Unlike when using blocking IO, SQLAlchemy
cannot properly dispose of these connections within methods like __del__
or weakref finalizers as there is no opportunity to invoke await
.
Failing to explicitly dispose of the engine when it falls out of scope
may result in warnings emitted to standard out resembling the form
RuntimeError: Event loop is closed
within garbage collection.
The AsyncConnection
also features a “streaming” API via
the AsyncConnection.stream()
method that returns an
AsyncResult
object. This result object uses a server-side
cursor and provides an async/await API, such as an async iterator:
async with engine.connect() as conn:
async_result = await conn.stream(select(t1))
async for row in async_result:
print("row: %s" % (row,))
Synopsis - ORM¶
Using 2.0 style querying, the AsyncSession
class
provides full ORM functionality. Within the default mode of use, special care
must be taken to avoid lazy loading or other expired-attribute access
involving ORM relationships and column attributes; the next
section Preventing Implicit IO when Using AsyncSession details this. The example below
illustrates a complete example including mapper and session configuration:
import asyncio
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey
from sqlalchemy import func
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.future import select
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.orm import selectinload
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class A(Base):
__tablename__ = "a"
id = Column(Integer, primary_key=True)
data = Column(String)
create_date = Column(DateTime, server_default=func.now())
bs = relationship("B")
# required in order to access columns with server defaults
# or SQL expression defaults, subsequent to a flush, without
# triggering an expired load
__mapper_args__ = {"eager_defaults": True}
class B(Base):
__tablename__ = "b"
id = Column(Integer, primary_key=True)
a_id = Column(ForeignKey("a.id"))
data = Column(String)
async def async_main():
engine = create_async_engine(
"postgresql+asyncpg://scott:tiger@localhost/test",
echo=True,
)
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
# expire_on_commit=False will prevent attributes from being expired
# after commit.
async_session = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
async with async_session() as session:
async with session.begin():
session.add_all(
[
A(bs=[B(), B()], data="a1"),
A(bs=[B()], data="a2"),
A(bs=[B(), B()], data="a3"),
]
)
stmt = select(A).options(selectinload(A.bs))
result = await session.execute(stmt)
for a1 in result.scalars():
print(a1)
print(f"created at: {a1.create_date}")
for b1 in a1.bs:
print(b1)
result = await session.execute(select(A).order_by(A.id))
a1 = result.scalars().first()
a1.data = "new data"
await session.commit()
# access attribute subsequent to commit; this is what
# expire_on_commit=False allows
print(a1.data)
# for AsyncEngine created in function scope, close and
# clean-up pooled connections
await engine.dispose()
asyncio.run(async_main())
In the example above, the AsyncSession
is instantiated using
the optional sessionmaker
helper, and associated with an
AsyncEngine
against particular database URL. It is
then used in a Python asynchronous context manager (i.e. async with:
statement) so that it is automatically closed at the end of the block; this is
equivalent to calling the AsyncSession.close()
method.
Note
AsyncSession
uses SQLAlchemy’s future mode, which
has several potentially breaking changes. One such change is the new
default behavior of cascade_backrefs
is False
, which may affect
how related objects are saved to the database.
Preventing Implicit IO when Using AsyncSession¶
Using traditional asyncio, the application needs to avoid any points at which IO-on-attribute access may occur. Above, the following measures are taken to prevent this:
The
selectinload()
eager loader is employed in order to eagerly load theA.bs
collection within the scope of theawait session.execute()
call:stmt = select(A).options(selectinload(A.bs))
If the default loader strategy of “lazyload” were left in place, the access of the
A.bs
attribute would raise an asyncio exception. There are a variety of ORM loader options available, which may be configured at the default mapping level or used on a per-query basis, documented at Relationship Loading Techniques.The
AsyncSession
is configured usingSession.expire_on_commit
set to False, so that we may access attributes on an object subsequent to a call toAsyncSession.commit()
, as in the line at the end where we access an attribute:# create AsyncSession with expire_on_commit=False async_session = AsyncSession(engine, expire_on_commit=False) # sessionmaker version async_session = sessionmaker( engine, expire_on_commit=False, class_=AsyncSession ) async with async_session() as session: result = await session.execute(select(A).order_by(A.id)) a1 = result.scalars().first() # commit would normally expire all attributes await session.commit() # access attribute subsequent to commit; this is what # expire_on_commit=False allows print(a1.data)
The
Column.server_default
value on thecreated_at
column will not be refreshed by default after an INSERT; instead, it is normally expired so that it can be loaded when needed. Similar behavior applies to a column where theColumn.default
parameter is assigned to a SQL expression object. To access this value with asyncio, it has to be refreshed within the flush process, which is achieved by setting themapper.eager_defaults
parameter on the mapping:class A(Base): # ... # column with a server_default, or SQL expression default create_date = Column(DateTime, server_default=func.now()) # add this so that it can be accessed __mapper_args__ = {"eager_defaults": True}
Other guidelines include:
Methods like
AsyncSession.expire()
should be avoided in favor ofAsyncSession.refresh()
Avoid using the
all
cascade option documented at Cascades in favor of listing out the desired cascade features explicitly. Theall
cascade option implies among others the refresh-expire setting, which means that theAsyncSession.refresh()
method will expire the attributes on related objects, but not necessarily refresh those related objects assuming eager loading is not configured within therelationship()
, leaving them in an expired state. A future release may introduce the ability to indicate eager loader options when invokingSession.refresh()
and/orAsyncSession.refresh()
.Appropriate loader options should be employed for
deferred()
columns, if used at all, in addition to that ofrelationship()
constructs as noted above. See Deferred Column Loading for background on deferred column loading.
The “dynamic” relationship loader strategy described at Dynamic Relationship Loaders is not compatible by default with the asyncio approach. It can be used directly only if invoked within the
AsyncSession.run_sync()
method described at Running Synchronous Methods and Functions under asyncio, or by using its.statement
attribute to obtain a normal select:user = await session.get(User, 42) addresses = (await session.scalars(user.addresses.statement)).all() stmt = user.addresses.statement.where( Address.email_address.startswith("patrick") ) addresses_filter = (await session.scalars(stmt)).all()
See also
Making use of “dynamic” relationship loads without using Query - notes on migration to 2.0 style
Running Synchronous Methods and Functions under asyncio¶
Deep Alchemy
This approach is essentially exposing publicly the
mechanism by which SQLAlchemy is able to provide the asyncio interface
in the first place. While there is no technical issue with doing so, overall
the approach can probably be considered “controversial” as it works against
some of the central philosophies of the asyncio programming model, which
is essentially that any programming statement that can potentially result
in IO being invoked must have an await
call, lest the program
does not make it explicitly clear every line at which IO may occur.
This approach does not change that general idea, except that it allows
a series of synchronous IO instructions to be exempted from this rule
within the scope of a function call, essentially bundled up into a single
awaitable.
As an alternative means of integrating traditional SQLAlchemy “lazy loading”
within an asyncio event loop, an optional method known as
AsyncSession.run_sync()
is provided which will run any
Python function inside of a greenlet, where traditional synchronous
programming concepts will be translated to use await
when they reach the
database driver. A hypothetical approach here is an asyncio-oriented
application can package up database-related methods into functions that are
invoked using AsyncSession.run_sync()
.
Altering the above example, if we didn’t use selectinload()
for the A.bs
collection, we could accomplish our treatment of these
attribute accesses within a separate function:
import asyncio
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
def fetch_and_update_objects(session):
"""run traditional sync-style ORM code in a function that will be
invoked within an awaitable.
"""
# the session object here is a traditional ORM Session.
# all features are available here including legacy Query use.
stmt = select(A)
result = session.execute(stmt)
for a1 in result.scalars():
print(a1)
# lazy loads
for b1 in a1.bs:
print(b1)
# legacy Query use
a1 = session.query(A).order_by(A.id).first()
a1.data = "new data"
async def async_main():
engine = create_async_engine(
"postgresql+asyncpg://scott:tiger@localhost/test",
echo=True,
)
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
async with AsyncSession(engine) as session:
async with session.begin():
session.add_all(
[
A(bs=[B(), B()], data="a1"),
A(bs=[B()], data="a2"),
A(bs=[B(), B()], data="a3"),
]
)
await session.run_sync(fetch_and_update_objects)
await session.commit()
# for AsyncEngine created in function scope, close and
# clean-up pooled connections
await engine.dispose()
asyncio.run(async_main())
The above approach of running certain functions within a “sync” runner
has some parallels to an application that runs a SQLAlchemy application
on top of an event-based programming library such as gevent
. The
differences are as follows:
unlike when using
gevent
, we can continue to use the standard Python asyncio event loop, or any custom event loop, without the need to integrate into thegevent
event loop.There is no “monkeypatching” whatsoever. The above example makes use of a real asyncio driver and the underlying SQLAlchemy connection pool is also using the Python built-in
asyncio.Queue
for pooling connections.The program can freely switch between async/await code and contained functions that use sync code with virtually no performance penalty. There is no “thread executor” or any additional waiters or synchronization in use.
The underlying network drivers are also using pure Python asyncio concepts, no third party networking libraries as
gevent
andeventlet
provides are in use.
Using events with the asyncio extension¶
The SQLAlchemy event system is not directly exposed by the asyncio extension, meaning there is not yet an “async” version of a SQLAlchemy event handler.
However, as the asyncio extension surrounds the usual synchronous SQLAlchemy API, regular “synchronous” style event handlers are freely available as they would be if asyncio were not used.
As detailed below, there are two current strategies to register events given asyncio-facing APIs:
Events can be registered at the instance level (e.g. a specific
AsyncEngine
instance) by associating the event with thesync
attribute that refers to the proxied object. For example to register thePoolEvents.connect()
event against anAsyncEngine
instance, use itsAsyncEngine.sync_engine
attribute as target. Targets include:To register an event at the class level, targeting all instances of the same type (e.g. all
AsyncSession
instances), use the corresponding sync-style class. For example to register theSessionEvents.before_commit()
event against theAsyncSession
class, use theSession
class as the target.
When working within an event handler that is within an asyncio context, objects
like the Connection
continue to work in their usual
“synchronous” way without requiring await
or async
usage; when messages
are ultimately received by the asyncio database adapter, the calling style is
transparently adapted back into the asyncio calling style. For events that
are passed a DBAPI level connection, such as PoolEvents.connect()
,
the object is a pep-249 compliant “connection” object which will adapt
sync-style calls into the asyncio driver.
Some examples of sync style event handlers associated with async-facing API constructs are illustrated below:
import asyncio
from sqlalchemy import event, text
from sqlalchemy.engine import Engine
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import Session
## Core events ##
engine = create_async_engine("postgresql+asyncpg://scott:tiger@localhost:5432/test")
# connect event on instance of Engine
@event.listens_for(engine.sync_engine, "connect")
def my_on_connect(dbapi_con, connection_record):
print("New DBAPI connection:", dbapi_con)
cursor = dbapi_con.cursor()
# sync style API use for adapted DBAPI connection / cursor
cursor.execute("select 'execute from event'")
print(cursor.fetchone()[0])
# before_execute event on all Engine instances
@event.listens_for(Engine, "before_execute")
def my_before_execute(
conn,
clauseelement,
multiparams,
params,
execution_options,
):
print("before execute!")
## ORM events ##
session = AsyncSession(engine)
# before_commit event on instance of Session
@event.listens_for(session.sync_session, "before_commit")
def my_before_commit(session):
print("before commit!")
# sync style API use on Session
connection = session.connection()
# sync style API use on Connection
result = connection.execute(text("select 'execute from event'"))
print(result.first())
# after_commit event on all Session instances
@event.listens_for(Session, "after_commit")
def my_after_commit(session):
print("after commit!")
async def go():
await session.execute(text("select 1"))
await session.commit()
await session.close()
await engine.dispose()
asyncio.run(go())
The above example prints something along the lines of:
New DBAPI connection: <AdaptedConnection <asyncpg.connection.Connection ...>>
execute from event
before execute!
before commit!
execute from event
after commit!
Using awaitable-only driver methods in connection pool and other events¶
As discussed in the above section, event handlers such as those oriented
around the PoolEvents
event handlers receive a sync-style “DBAPI” connection,
which is a wrapper object supplied by SQLAlchemy asyncio dialects to adapt
the underlying asyncio “driver” connection into one that can be used by
SQLAlchemy’s internals. A special use case arises when the user-defined
implementation for such an event handler needs to make use of the
ultimate “driver” connection directly, using awaitable only methods on that
driver connection. One such example is the .set_type_codec()
method
supplied by the asyncpg driver.
To accommodate this use case, SQLAlchemy’s AdaptedConnection
class provides a method AdaptedConnection.run_async()
that allows
an awaitable function to be invoked within the “synchronous” context of
an event handler or other SQLAlchemy internal. This method is directly
analogous to the AsyncConnection.run_sync()
method that
allows a sync-style method to run under async.
AdaptedConnection.run_async()
should be passed a function that will
accept the innermost “driver” connection as a single argument, and return
an awaitable that will be invoked by the AdaptedConnection.run_async()
method. The given function itself does not need to be declared as async
;
it’s perfectly fine for it to be a Python lambda:
, as the return awaitable
value will be invoked after being returned:
from sqlalchemy import event
from sqlalchemy.ext.asyncio import create_async_engine
engine = create_async_engine(...)
@event.listens_for(engine.sync_engine, "connect")
def register_custom_types(dbapi_connection, ...):
dbapi_connection.run_async(
lambda connection: connection.set_type_codec(
"MyCustomType", encoder, decoder, ...
)
)
Above, the object passed to the register_custom_types
event handler
is an instance of AdaptedConnection
, which provides a DBAPI-like
interface to an underlying async-only driver-level connection object.
The AdaptedConnection.run_async()
method then provides access to an
awaitable environment where the underlying driver level connection may be
acted upon.
New in version 1.4.30.
Using multiple asyncio event loops¶
An application that makes use of multiple event loops, for example in the
uncommon case of combining asyncio with multithreading, should not share the
same AsyncEngine
with different event loops when using the
default pool implementation.
If an AsyncEngine
is be passed from one event loop to another,
the method AsyncEngine.dispose()
should be called before it’s
re-used on a new event loop. Failing to do so may lead to a RuntimeError
along the lines of
Task <Task pending ...> got Future attached to a different loop
If the same engine must be shared between different loop, it should be configured
to disable pooling using NullPool
, preventing the Engine
from using any connection more than once:
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.pool import NullPool
engine = create_async_engine(
"postgresql+asyncpg://user:pass@host/dbname",
poolclass=NullPool,
)
Using asyncio scoped session¶
The “scoped session” pattern used in threaded SQLAlchemy with the
scoped_session
object is also available in asyncio, using
an adapted version called async_scoped_session
.
Tip
SQLAlchemy generally does not recommend the “scoped” pattern
for new development as it relies upon mutable global state that must also be
explicitly torn down when work within the thread or task is complete.
Particularly when using asyncio, it’s likely a better idea to pass the
AsyncSession
directly to the awaitable functions that need
it.
When using async_scoped_session
, as there’s no “thread-local”
concept in the asyncio context, the “scopefunc” parameter must be provided to
the constructor. The example below illustrates using the
asyncio.current_task()
function for this purpose:
from asyncio import current_task
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.asyncio import async_scoped_session
from sqlalchemy.ext.asyncio import AsyncSession
async_session_factory = sessionmaker(some_async_engine, class_=AsyncSession)
AsyncScopedSession = async_scoped_session(async_session_factory, scopefunc=current_task)
some_async_session = AsyncScopedSession()
Warning
The “scopefunc” used by async_scoped_session
is invoked an arbitrary number of times within a task, once for each
time the underlying AsyncSession
is accessed. The function
should therefore be idempotent and lightweight, and should not attempt
to create or mutate any state, such as establishing callbacks, etc.
Warning
Using current_task()
for the “key” in the scope requires that
the async_scoped_session.remove()
method is called from
within the outermost awaitable, to ensure the key is removed from the
registry when the task is complete, otherwise the task handle as well as
the AsyncSession
will remain in memory, essentially
creating a memory leak. See the following example which illustrates
the correct use of async_scoped_session.remove()
.
async_scoped_session
includes proxy
behavior similar to that of scoped_session
, which means it can be
treated as a AsyncSession
directly, keeping in mind that
the usual await
keywords are necessary, including for the
async_scoped_session.remove()
method:
async def some_function(some_async_session, some_object):
# use the AsyncSession directly
some_async_session.add(some_object)
# use the AsyncSession via the context-local proxy
await AsyncScopedSession.commit()
# "remove" the current proxied AsyncSession for the local context
await AsyncScopedSession.remove()
New in version 1.4.19.
Using the Inspector to inspect schema objects¶
SQLAlchemy does not yet offer an asyncio version of the
Inspector
(introduced at Fine Grained Reflection with Inspector),
however the existing interface may be used in an asyncio context by
leveraging the AsyncConnection.run_sync()
method of
AsyncConnection
:
import asyncio
from sqlalchemy import inspect
from sqlalchemy.ext.asyncio import create_async_engine
engine = create_async_engine("postgresql+asyncpg://scott:tiger@localhost/test")
def use_inspector(conn):
inspector = inspect(conn)
# use the inspector
print(inspector.get_view_names())
# return any value to the caller
return inspector.get_table_names()
async def async_main():
async with engine.connect() as conn:
tables = await conn.run_sync(use_inspector)
asyncio.run(async_main())
Engine API Documentation¶
Object Name | Description |
---|---|
async_engine_from_config(configuration[, prefix], **kwargs) |
Create a new AsyncEngine instance using a configuration dictionary. |
An asyncio proxy for a |
|
An asyncio proxy for a |
|
An asyncio proxy for a |
|
create_async_engine(*arg, **kw) |
Create a new async engine instance. |
- function sqlalchemy.ext.asyncio.create_async_engine(*arg, **kw)¶
Create a new async engine instance.
Arguments passed to
create_async_engine()
are mostly identical to those passed to thecreate_engine()
function. The specified dialect must be an asyncio-compatible dialect such as asyncpg.New in version 1.4.
- function sqlalchemy.ext.asyncio.async_engine_from_config(configuration, prefix='sqlalchemy.', **kwargs)¶
Create a new AsyncEngine instance using a configuration dictionary.
This function is analogous to the
engine_from_config()
function in SQLAlchemy Core, except that the requested dialect must be an asyncio-compatible dialect such as asyncpg. The argument signature of the function is identical to that ofengine_from_config()
.New in version 1.4.29.
- class sqlalchemy.ext.asyncio.AsyncEngine(sync_engine)¶
An asyncio proxy for a
Engine
.AsyncEngine
is acquired using thecreate_async_engine()
function:from sqlalchemy.ext.asyncio import create_async_engine engine = create_async_engine("postgresql+asyncpg://user:pass@host/dbname")
New in version 1.4.
Members
begin(), clear_compiled_cache(), connect(), dispose(), execution_options(), get_execution_options(), raw_connection(), sync_engine, update_execution_options()
Class signature
class
sqlalchemy.ext.asyncio.AsyncEngine
(sqlalchemy.ext.asyncio.base.ProxyComparable
,sqlalchemy.ext.asyncio.AsyncConnectable
)-
method
sqlalchemy.ext.asyncio.AsyncEngine.
begin()¶ Return a context manager which when entered will deliver an
AsyncConnection
with anAsyncTransaction
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)"))
-
method
sqlalchemy.ext.asyncio.AsyncEngine.
clear_compiled_cache()¶ Clear the compiled cache associated with the dialect.
Proxied for the
Engine
class on behalf of theAsyncEngine
class.This applies only to the built-in cache that is established via the
create_engine.query_cache_size
parameter. It will not impact any dictionary caches that were passed via theConnection.execution_options.query_cache
parameter.New in version 1.4.
-
method
sqlalchemy.ext.asyncio.AsyncEngine.
connect()¶ Return an
AsyncConnection
object.The
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
AsyncConnection
may also be started outside of a context manager by invoking itsAsyncConnection.start()
method.
-
method
sqlalchemy.ext.asyncio.AsyncEngine.
async dispose()¶ Dispose of the connection pool used by this
AsyncEngine
.This will close all connection pool connections that are currently checked in. See the documentation for the underlying
Engine.dispose()
method for further notes.See also
Engine.dispose()
-
method
sqlalchemy.ext.asyncio.AsyncEngine.
execution_options(**opt)¶ Return a new
AsyncEngine
that will provideAsyncConnection
objects with the given execution options.Proxied from
Engine.execution_options()
. See that method for details.
-
method
sqlalchemy.ext.asyncio.AsyncEngine.
get_execution_options()¶ Get the non-SQL options which will take effect during execution.
Proxied for the
Engine
class on behalf of theAsyncEngine
class.See also
-
method
sqlalchemy.ext.asyncio.AsyncEngine.
async raw_connection()¶ Return a “raw” DBAPI connection from the connection pool.
-
attribute
sqlalchemy.ext.asyncio.AsyncEngine.
sync_engine: Engine¶ Reference to the sync-style
Engine
thisAsyncEngine
proxies requests towards.This instance can be used as an event target.
-
method
sqlalchemy.ext.asyncio.AsyncEngine.
update_execution_options(**opt)¶ Update the default execution_options dictionary of this
Engine
.Proxied for the
Engine
class on behalf of theAsyncEngine
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 tocreate_engine()
.
-
method
- class sqlalchemy.ext.asyncio.AsyncConnection(async_engine, sync_connection=None)¶
An asyncio proxy for a
Connection
.AsyncConnection
is acquired using theAsyncEngine.connect()
method ofAsyncEngine
: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))
New in version 1.4.
Members
begin(), begin_nested(), close(), commit(), connection, exec_driver_sql(), execute(), execution_options(), get_nested_transaction(), get_raw_connection(), get_transaction(), in_nested_transaction(), in_transaction(), info, invalidate(), rollback(), run_sync(), scalar(), scalars(), start(), stream(), stream_scalars(), sync_connection, sync_engine
Class signature
class
sqlalchemy.ext.asyncio.AsyncConnection
(sqlalchemy.ext.asyncio.base.ProxyComparable
,sqlalchemy.ext.asyncio.base.StartableContext
,sqlalchemy.ext.asyncio.AsyncConnectable
)-
method
sqlalchemy.ext.asyncio.AsyncConnection.
begin()¶ Begin a transaction prior to autobegin occurring.
-
method
sqlalchemy.ext.asyncio.AsyncConnection.
begin_nested()¶ Begin a nested transaction and return a transaction handle.
-
method
sqlalchemy.ext.asyncio.AsyncConnection.
async close()¶ Close this
AsyncConnection
.This has the effect of also rolling back the transaction if one is in place.
-
method
sqlalchemy.ext.asyncio.AsyncConnection.
async commit()¶ Commit the transaction that is currently in progress.
This method commits the current transaction if one has been started. If no transaction was started, the method has no effect, assuming the connection is in a non-invalidated state.
A transaction is begun on a
Connection
automatically whenever a statement is first executed, or when theConnection.begin()
method is called.
-
attribute
sqlalchemy.ext.asyncio.AsyncConnection.
connection¶ Not implemented for async; call
AsyncConnection.get_raw_connection()
.
-
method
sqlalchemy.ext.asyncio.AsyncConnection.
async exec_driver_sql(statement, parameters=None, execution_options={})¶ Executes a driver-level SQL string and return buffered
Result
.
-
method
sqlalchemy.ext.asyncio.AsyncConnection.
async execute(statement, parameters=None, execution_options={})¶ Executes a SQL statement construct and return a buffered
Result
.- Parameters:
object¶ –
The statement to be executed. This is always an object that is in both the
ClauseElement
andExecutable
hierarchies, including:DDL
and objects which inherit fromDDLElement
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 DBAPIcursor.execute()
method will be used.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
Connection.execution_options()
.
- Returns:
a
Result
object.
-
method
sqlalchemy.ext.asyncio.AsyncConnection.
async execution_options(**opt)¶ Set non-SQL options for the connection which take effect during execution.
This returns this
AsyncConnection
object with the new options added.See
Connection.execution_options()
for full details on this method.
-
method
sqlalchemy.ext.asyncio.AsyncConnection.
get_nested_transaction()¶ Return an
AsyncTransaction
representing the current nested (savepoint) transaction, if any.This makes use of the underlying synchronous connection’s
Connection.get_nested_transaction()
method to get the currentTransaction
, which is then proxied in a newAsyncTransaction
object.New in version 1.4.0b2.
-
method
sqlalchemy.ext.asyncio.AsyncConnection.
async get_raw_connection()¶ Return the pooled DBAPI-level connection in use by this
AsyncConnection
.This is a SQLAlchemy connection-pool proxied connection which then has the attribute
_ConnectionFairy.driver_connection
that refers to the actual driver connection. Its_ConnectionFairy.dbapi_connection
refers instead to anAdaptedConnection
instance that adapts the driver connection to the DBAPI protocol.
-
method
sqlalchemy.ext.asyncio.AsyncConnection.
get_transaction()¶ Return an
AsyncTransaction
representing the current transaction, if any.This makes use of the underlying synchronous connection’s
Connection.get_transaction()
method to get the currentTransaction
, which is then proxied in a newAsyncTransaction
object.New in version 1.4.0b2.
-
method
sqlalchemy.ext.asyncio.AsyncConnection.
in_nested_transaction()¶ Return True if a transaction is in progress.
New in version 1.4.0b2.
-
method
sqlalchemy.ext.asyncio.AsyncConnection.
in_transaction()¶ Return True if a transaction is in progress.
New in version 1.4.0b2.
-
attribute
sqlalchemy.ext.asyncio.AsyncConnection.
info¶ Return the
Connection.info
dictionary of the underlyingConnection
.This dictionary is freely writable for user-defined state to be associated with the database connection.
This attribute is only available if the
AsyncConnection
is currently connected. If theAsyncConnection.closed
attribute isTrue
, then accessing this attribute will raiseResourceClosedError
.New in version 1.4.0b2.
-
method
sqlalchemy.ext.asyncio.AsyncConnection.
async invalidate(exception=None)¶ Invalidate the underlying DBAPI connection associated with this
Connection
.See the method
Connection.invalidate()
for full detail on this method.
-
method
sqlalchemy.ext.asyncio.AsyncConnection.
async rollback()¶ Roll back the transaction that is currently in progress.
This method rolls back the current transaction if one has been started. If no transaction was started, the method has no effect. If a transaction was started and the connection is in an invalidated state, the transaction is cleared using this method.
A transaction is begun on a
Connection
automatically whenever a statement is first executed, or when theConnection.begin()
method is called.
-
method
sqlalchemy.ext.asyncio.AsyncConnection.
async run_sync(fn, *arg, **kw)¶ 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.
-
method
sqlalchemy.ext.asyncio.AsyncConnection.
async scalar(statement, parameters=None, execution_options={})¶ Executes a SQL statement construct and returns a scalar object.
This method is shorthand for invoking the
Result.scalar()
method after invoking theConnection.execute()
method. Parameters are equivalent.- Returns:
a scalar Python value representing the first column of the first row returned.
-
method
sqlalchemy.ext.asyncio.AsyncConnection.
async scalars(statement, parameters=None, execution_options={})¶ Executes a SQL statement construct and returns a scalar objects.
This method is shorthand for invoking the
Result.scalars()
method after invoking theConnection.execute()
method. Parameters are equivalent.- Returns:
a
ScalarResult
object.
New in version 1.4.24.
-
method
sqlalchemy.ext.asyncio.AsyncConnection.
async start(is_ctxmanager=False)¶ Start this
AsyncConnection
object’s context outside of using a Pythonwith:
block.
-
method
sqlalchemy.ext.asyncio.AsyncConnection.
async stream(statement, parameters=None, execution_options={})¶ Execute a statement and return a streaming
AsyncResult
object.
-
method
sqlalchemy.ext.asyncio.AsyncConnection.
async stream_scalars(statement, parameters=None, execution_options={})¶ Executes a SQL statement and returns a streaming scalar result object.
This method is shorthand for invoking the
AsyncResult.scalars()
method after invoking theConnection.stream()
method. Parameters are equivalent.- Returns:
an
AsyncScalarResult
object.
New in version 1.4.24.
-
attribute
sqlalchemy.ext.asyncio.AsyncConnection.
sync_connection: Connection¶ Reference to the sync-style
Connection
thisAsyncConnection
proxies requests towards.This instance can be used as an event target.
-
attribute
sqlalchemy.ext.asyncio.AsyncConnection.
sync_engine: Engine¶ Reference to the sync-style
Engine
thisAsyncConnection
is associated with via its underlyingConnection
.This instance can be used as an event target.
-
method
- class sqlalchemy.ext.asyncio.AsyncTransaction(connection, nested=False)¶
An asyncio proxy for a
Transaction
.Members
Class signature
class
sqlalchemy.ext.asyncio.AsyncTransaction
(sqlalchemy.ext.asyncio.base.ProxyComparable
,sqlalchemy.ext.asyncio.base.StartableContext
)-
method
sqlalchemy.ext.asyncio.AsyncTransaction.
async close()¶ Close this
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.
-
method
sqlalchemy.ext.asyncio.AsyncTransaction.
async commit()¶ Commit this
Transaction
.
-
method
sqlalchemy.ext.asyncio.AsyncTransaction.
async rollback()¶ Roll back this
Transaction
.
-
method
sqlalchemy.ext.asyncio.AsyncTransaction.
async start(is_ctxmanager=False)¶ Start this
AsyncTransaction
object’s context outside of using a Pythonwith:
block.
-
method
Result Set API Documentation¶
The AsyncResult
object is an async-adapted version of the
Result
object. It is only returned when using the
AsyncConnection.stream()
or AsyncSession.stream()
methods, which return a result object that is on top of an active database
cursor.
Object Name | Description |
---|---|
A wrapper for a |
|
An asyncio wrapper around a |
|
A wrapper for a |
- class sqlalchemy.ext.asyncio.AsyncResult(real_result)¶
An asyncio wrapper around a
Result
object.The
AsyncResult
only applies to statement executions that use a server-side cursor. It is returned only from theAsyncConnection.stream()
andAsyncSession.stream()
methods.Note
As is the case with
Result
, this object is used for ORM results returned byAsyncSession.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 legacyQuery
object. For in-Python de-duplication of instances or rows, use theAsyncResult.unique()
modifier method.New in version 1.4.
Members
all(), close(), closed, columns(), fetchmany(), fetchone(), first(), freeze(), keys(), mappings(), memoized_instancemethod(), one(), one_or_none(), partitions(), scalar(), scalar_one(), scalar_one_or_none(), scalars(), unique(), yield_per()
Class signature
class
sqlalchemy.ext.asyncio.AsyncResult
(sqlalchemy.engine._WithKeys
,sqlalchemy.ext.asyncio.AsyncCommon
)-
method
sqlalchemy.ext.asyncio.AsyncResult.
async all()¶ Return all rows in a list.
Closes the result set after invocation. Subsequent invocations will return an empty list.
- Returns:
a list of
Row
objects.
-
method
sqlalchemy.ext.asyncio.AsyncResult.
async close()¶ inherited from the
AsyncCommon.close()
method ofAsyncCommon
Close this result.
-
attribute
sqlalchemy.ext.asyncio.AsyncResult.
closed¶ inherited from the
FilterResult.closed
attribute ofFilterResult
Return
True
if the underlyingResult
reports closedNew in version 1.4.43.
-
method
sqlalchemy.ext.asyncio.AsyncResult.
columns(*col_expressions)¶ Establish the columns that should be returned in each row.
Refer to
Result.columns()
in the synchronous SQLAlchemy API for a complete behavioral description.
-
method
sqlalchemy.ext.asyncio.AsyncResult.
async fetchmany(size=None)¶ 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
AsyncResult.partitions()
method.- Returns:
a list of
Row
objects.
See also
-
method
sqlalchemy.ext.asyncio.AsyncResult.
async fetchone()¶ Fetch one row.
When all rows are exhausted, returns None.
This method is provided for backwards compatibility with SQLAlchemy 1.x.x.
To fetch the first row of a result only, use the
AsyncResult.first()
method. To iterate through all rows, iterate theAsyncResult
object directly.- Returns:
a
Row
object if no filters are applied, orNone
if no rows remain.
-
method
sqlalchemy.ext.asyncio.AsyncResult.
async first()¶ Fetch the first row or
None
if no row is present.Closes the result set and discards remaining rows.
Note
This method returns one row, e.g. tuple, by default. To return exactly one single scalar value, that is, the first column of the first row, use the
AsyncResult.scalar()
method, or combineAsyncResult.scalars()
andAsyncResult.first()
.Additionally, in contrast to the behavior of the legacy ORM
Query.first()
method, no limit is applied to the SQL query which was invoked to produce thisAsyncResult
; 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.See also
- Returns:
a
Row
object, or None if no rows remain.
-
method
sqlalchemy.ext.asyncio.AsyncResult.
async freeze()¶ Return a callable object that will produce copies of this
AsyncResult
when invoked.The callable object returned is an instance of
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
FrozenResult
is retrieved from a cache, it can be called any number of times where it will produce a newResult
object each time against its stored set of rows.See also
Re-Executing Statements - example usage within the ORM to implement a result-set cache.
-
method
sqlalchemy.ext.asyncio.AsyncResult.
keys()¶ inherited from the
sqlalchemy.engine._WithKeys.keys
method ofsqlalchemy.engine._WithKeys
Return an iterable view which yields the string keys that would be represented by each
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.Changed in version 1.4: a key view object is returned rather than a plain list.
-
method
sqlalchemy.ext.asyncio.AsyncResult.
mappings()¶ Apply a mappings filter to returned rows, returning an instance of
AsyncMappingResult
.When this filter is applied, fetching rows will return
RowMapping
objects instead ofRow
objects.- Returns:
a new
AsyncMappingResult
filtering object referring to the underlyingResult
object.
-
classmethod
sqlalchemy.ext.asyncio.AsyncResult.
memoized_instancemethod(fn)¶ inherited from the
HasMemoized.memoized_instancemethod()
method ofHasMemoized
Decorate a method memoize its return value.
-
method
sqlalchemy.ext.asyncio.AsyncResult.
async one()¶ Return exactly one row or raise an exception.
Raises
NoResultFound
if the result returns no rows, orMultipleResultsFound
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
AsyncResult.scalar_one()
method, or combineAsyncResult.scalars()
andAsyncResult.one()
.New in version 1.4.
- Returns:
The first
Row
.- Raises:
-
method
sqlalchemy.ext.asyncio.AsyncResult.
async one_or_none()¶ Return at most one result or raise an exception.
Returns
None
if the result has no rows. RaisesMultipleResultsFound
if multiple rows are returned.New in version 1.4.
- Returns:
The first
Row
orNone
if no row is available.- Raises:
-
method
sqlalchemy.ext.asyncio.AsyncResult.
async partitions(size=None)¶ 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
Result.partitions()
in the synchronous SQLAlchemy API for a complete behavioral description.
-
method
sqlalchemy.ext.asyncio.AsyncResult.
async scalar()¶ 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
CursorResult.close()
method will have been called.- Returns:
a Python scalar value, or
None
if no rows remain.
-
method
sqlalchemy.ext.asyncio.AsyncResult.
async scalar_one()¶ Return exactly one scalar result or raise an exception.
This is equivalent to calling
AsyncResult.scalars()
and thenAsyncResult.one()
.
-
method
sqlalchemy.ext.asyncio.AsyncResult.
async scalar_one_or_none()¶ Return exactly one scalar result or
None
.This is equivalent to calling
AsyncResult.scalars()
and thenAsyncResult.one_or_none()
.
-
method
sqlalchemy.ext.asyncio.AsyncResult.
scalars(index=0)¶ Return an
AsyncScalarResult
filtering object which will return single elements rather thanRow
objects.Refer to
Result.scalars()
in the synchronous SQLAlchemy API for a complete behavioral description.- Parameters:
index¶ – integer or row key indicating the column to be fetched from each row, defaults to
0
indicating the first column.- Returns:
a new
AsyncScalarResult
filtering object referring to thisAsyncResult
object.
-
method
sqlalchemy.ext.asyncio.AsyncResult.
unique(strategy=None)¶ Apply unique filtering to the objects returned by this
AsyncResult
.Refer to
Result.unique()
in the synchronous SQLAlchemy API for a complete behavioral description.
-
method
sqlalchemy.ext.asyncio.AsyncResult.
yield_per(num)¶ inherited from the
FilterResult.yield_per()
method ofFilterResult
Configure the row-fetching strategy to fetch
num
rows at a time.The
FilterResult.yield_per()
method is a pass through to theResult.yield_per()
method. See that method’s documentation for usage notes.New in version 1.4.40: - added
FilterResult.yield_per()
so that the method is available on all result set implementationsSee also
Using Server Side Cursors (a.k.a. stream results) - describes Core behavior for
Result.yield_per()
Fetching Large Result Sets with Yield Per - in the ORM Querying Guide
-
method
- class sqlalchemy.ext.asyncio.AsyncScalarResult(real_result, index)¶
A wrapper for a
AsyncResult
that returns scalar values rather thanRow
values.The
AsyncScalarResult
object is acquired by calling theAsyncResult.scalars()
method.Refer to the
ScalarResult
object in the synchronous SQLAlchemy API for a complete behavioral description.New in version 1.4.
Members
all(), close(), closed, fetchall(), fetchmany(), first(), memoized_instancemethod(), one(), one_or_none(), partitions(), unique(), yield_per()
Class signature
class
sqlalchemy.ext.asyncio.AsyncScalarResult
(sqlalchemy.ext.asyncio.AsyncCommon
)-
method
sqlalchemy.ext.asyncio.AsyncScalarResult.
async all()¶ Return all scalar values in a list.
Equivalent to
AsyncResult.all()
except that scalar values, rather thanRow
objects, are returned.
-
method
sqlalchemy.ext.asyncio.AsyncScalarResult.
async close()¶ inherited from the
AsyncCommon.close()
method ofAsyncCommon
Close this result.
-
attribute
sqlalchemy.ext.asyncio.AsyncScalarResult.
closed¶ inherited from the
FilterResult.closed
attribute ofFilterResult
Return
True
if the underlyingResult
reports closedNew in version 1.4.43.
-
method
sqlalchemy.ext.asyncio.AsyncScalarResult.
async fetchall()¶ A synonym for the
AsyncScalarResult.all()
method.
-
method
sqlalchemy.ext.asyncio.AsyncScalarResult.
async fetchmany(size=None)¶ Fetch many objects.
Equivalent to
AsyncResult.fetchmany()
except that scalar values, rather thanRow
objects, are returned.
-
method
sqlalchemy.ext.asyncio.AsyncScalarResult.
async first()¶ Fetch the first object or
None
if no object is present.Equivalent to
AsyncResult.first()
except that scalar values, rather thanRow
objects, are returned.
-
classmethod
sqlalchemy.ext.asyncio.AsyncScalarResult.
memoized_instancemethod(fn)¶ inherited from the
HasMemoized.memoized_instancemethod()
method ofHasMemoized
Decorate a method memoize its return value.
-
method
sqlalchemy.ext.asyncio.AsyncScalarResult.
async one()¶ Return exactly one object or raise an exception.
Equivalent to
AsyncResult.one()
except that scalar values, rather thanRow
objects, are returned.
-
method
sqlalchemy.ext.asyncio.AsyncScalarResult.
async one_or_none()¶ Return at most one object or raise an exception.
Equivalent to
AsyncResult.one_or_none()
except that scalar values, rather thanRow
objects, are returned.
-
method
sqlalchemy.ext.asyncio.AsyncScalarResult.
async partitions(size=None)¶ Iterate through sub-lists of elements of the size given.
Equivalent to
AsyncResult.partitions()
except that scalar values, rather thanRow
objects, are returned.
-
method
sqlalchemy.ext.asyncio.AsyncScalarResult.
unique(strategy=None)¶ Apply unique filtering to the objects returned by this
AsyncScalarResult
.See
AsyncResult.unique()
for usage details.
-
method
sqlalchemy.ext.asyncio.AsyncScalarResult.
yield_per(num)¶ inherited from the
FilterResult.yield_per()
method ofFilterResult
Configure the row-fetching strategy to fetch
num
rows at a time.The
FilterResult.yield_per()
method is a pass through to theResult.yield_per()
method. See that method’s documentation for usage notes.New in version 1.4.40: - added
FilterResult.yield_per()
so that the method is available on all result set implementationsSee also
Using Server Side Cursors (a.k.a. stream results) - describes Core behavior for
Result.yield_per()
Fetching Large Result Sets with Yield Per - in the ORM Querying Guide
-
method
- class sqlalchemy.ext.asyncio.AsyncMappingResult(result)¶
A wrapper for a
AsyncResult
that returns dictionary values rather thanRow
values.The
AsyncMappingResult
object is acquired by calling theAsyncResult.mappings()
method.Refer to the
MappingResult
object in the synchronous SQLAlchemy API for a complete behavioral description.New in version 1.4.
Members
all(), close(), closed, columns(), fetchall(), fetchmany(), fetchone(), first(), keys(), memoized_instancemethod(), one(), one_or_none(), partitions(), unique(), yield_per()
Class signature
class
sqlalchemy.ext.asyncio.AsyncMappingResult
(sqlalchemy.engine._WithKeys
,sqlalchemy.ext.asyncio.AsyncCommon
)-
method
sqlalchemy.ext.asyncio.AsyncMappingResult.
async all()¶ Return all scalar values in a list.
Equivalent to
AsyncResult.all()
except thatRowMapping
values, rather thanRow
objects, are returned.
-
method
sqlalchemy.ext.asyncio.AsyncMappingResult.
async close()¶ inherited from the
AsyncCommon.close()
method ofAsyncCommon
Close this result.
-
attribute
sqlalchemy.ext.asyncio.AsyncMappingResult.
closed¶ inherited from the
FilterResult.closed
attribute ofFilterResult
Return
True
if the underlyingResult
reports closedNew in version 1.4.43.
-
method
sqlalchemy.ext.asyncio.AsyncMappingResult.
columns(*col_expressions)¶ Establish the columns that should be returned in each row.
-
method
sqlalchemy.ext.asyncio.AsyncMappingResult.
async fetchall()¶ A synonym for the
AsyncMappingResult.all()
method.
-
method
sqlalchemy.ext.asyncio.AsyncMappingResult.
async fetchmany(size=None)¶ Fetch many objects.
Equivalent to
AsyncResult.fetchmany()
except thatRowMapping
values, rather thanRow
objects, are returned.
-
method
sqlalchemy.ext.asyncio.AsyncMappingResult.
async fetchone()¶ Fetch one object.
Equivalent to
AsyncResult.fetchone()
except thatRowMapping
values, rather thanRow
objects, are returned.
-
method
sqlalchemy.ext.asyncio.AsyncMappingResult.
async first()¶ Fetch the first object or
None
if no object is present.Equivalent to
AsyncResult.first()
except thatRowMapping
values, rather thanRow
objects, are returned.
-
method
sqlalchemy.ext.asyncio.AsyncMappingResult.
keys()¶ inherited from the
sqlalchemy.engine._WithKeys.keys
method ofsqlalchemy.engine._WithKeys
Return an iterable view which yields the string keys that would be represented by each
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.Changed in version 1.4: a key view object is returned rather than a plain list.
-
classmethod
sqlalchemy.ext.asyncio.AsyncMappingResult.
memoized_instancemethod(fn)¶ inherited from the
HasMemoized.memoized_instancemethod()
method ofHasMemoized
Decorate a method memoize its return value.
-
method
sqlalchemy.ext.asyncio.AsyncMappingResult.
async one()¶ Return exactly one object or raise an exception.
Equivalent to
AsyncResult.one()
except thatRowMapping
values, rather thanRow
objects, are returned.
-
method
sqlalchemy.ext.asyncio.AsyncMappingResult.
async one_or_none()¶ Return at most one object or raise an exception.
Equivalent to
AsyncResult.one_or_none()
except thatRowMapping
values, rather thanRow
objects, are returned.
-
method
sqlalchemy.ext.asyncio.AsyncMappingResult.
async partitions(size=None)¶ Iterate through sub-lists of elements of the size given.
Equivalent to
AsyncResult.partitions()
except thatRowMapping
values, rather thanRow
objects, are returned.
-
method
sqlalchemy.ext.asyncio.AsyncMappingResult.
unique(strategy=None)¶ Apply unique filtering to the objects returned by this
AsyncMappingResult
.See
AsyncResult.unique()
for usage details.
-
method
sqlalchemy.ext.asyncio.AsyncMappingResult.
yield_per(num)¶ inherited from the
FilterResult.yield_per()
method ofFilterResult
Configure the row-fetching strategy to fetch
num
rows at a time.The
FilterResult.yield_per()
method is a pass through to theResult.yield_per()
method. See that method’s documentation for usage notes.New in version 1.4.40: - added
FilterResult.yield_per()
so that the method is available on all result set implementationsSee also
Using Server Side Cursors (a.k.a. stream results) - describes Core behavior for
Result.yield_per()
Fetching Large Result Sets with Yield Per - in the ORM Querying Guide
-
method
ORM Session API Documentation¶
Object Name | Description |
---|---|
async_object_session(instance) |
Return the |
Provides scoped management of |
|
async_session(session) |
Return the |
Asyncio version of |
|
A wrapper for the ORM |
- function sqlalchemy.ext.asyncio.async_object_session(instance)¶
Return the
AsyncSession
to which the given instance belongs.This function makes use of the sync-API function
object_session
to retrieve theSession
which refers to the given instance, and from there links it to the originalAsyncSession
.If the
AsyncSession
has been garbage collected, the return value isNone
.This functionality is also available from the
InstanceState.async_session
accessor.- Parameters:
instance¶ – an ORM mapped instance
- Returns:
an
AsyncSession
object, orNone
.
New in version 1.4.18.
- function sqlalchemy.ext.asyncio.async_session(session)¶
Return the
AsyncSession
which is proxying the givenSession
object, if any.- Parameters:
- Returns:
a
AsyncSession
instance, orNone
.
New in version 1.4.18.
- class sqlalchemy.ext.asyncio.async_scoped_session(session_factory, scopefunc)¶
Provides scoped management of
AsyncSession
objects.See the section Using asyncio scoped session for usage details.
New in version 1.4.19.
Members
__call__(), __init__(), add(), add_all(), autoflush, begin(), begin_nested(), close(), close_all(), commit(), configure(), connection(), delete(), deleted, dirty, execute(), expire(), expire_all(), expunge(), expunge_all(), flush(), get(), get_bind(), identity_key(), identity_map, info, invalidate(), is_active, is_modified(), merge(), new, no_autoflush, object_session(), refresh(), remove(), rollback(), scalar(), scalars(), stream(), stream_scalars()
Class signature
class
sqlalchemy.ext.asyncio.async_scoped_session
(sqlalchemy.orm.scoping.ScopedSessionMixin
)-
method
sqlalchemy.ext.asyncio.async_scoped_session.
__call__(**kw)¶ inherited from the
sqlalchemy.orm.scoping.ScopedSessionMixin.__call__
method ofScopedSessionMixin
Return the current
Session
, creating it using thescoped_session.session_factory
if not present.- Parameters:
**kw¶ – Keyword arguments will be passed to the
scoped_session.session_factory
callable, if an existingSession
is not present. If theSession
is present and keyword arguments have been passed,InvalidRequestError
is raised.
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
__init__(session_factory, scopefunc)¶ Construct a new
async_scoped_session
.- Parameters:
session_factory¶ –
a factory to create new
AsyncSession
instances. This is usually, but not necessarily, an instance ofsessionmaker
which itself was passed theAsyncSession
to itssessionmaker.class_
parameter:async_session_factory = sessionmaker(some_async_engine, class_= AsyncSession) AsyncSession = async_scoped_session(async_session_factory, scopefunc=current_task)
scopefunc¶ – function which defines the current scope. A function such as
asyncio.current_task
may be useful here.
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
add(instance, _warn=True)¶ Place an object into this
Session
.Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.Proxied for the
Session
class on behalf of theAsyncSession
class.Objects that are in the transient state when passed to the
Session.add()
method will move to the pending state, until the next flush, at which point they will move to the persistent state.Objects that are in the detached state when passed to the
Session.add()
method will move to the persistent state directly.If the transaction used by the
Session
is rolled back, objects which were transient when they were passed toSession.add()
will be moved back to the transient state, and will no longer be present within thisSession
.
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
add_all(instances)¶ Add the given collection of instances to this
Session
.Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.Proxied for the
Session
class on behalf of theAsyncSession
class.See the documentation for
Session.add()
for a general behavioral description.
-
attribute
sqlalchemy.ext.asyncio.async_scoped_session.
autoflush¶ Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
begin(**kw)¶ Return an
AsyncSessionTransaction
object.Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.The underlying
Session
will perform the “begin” action when theAsyncSessionTransaction
object is entered:async with async_session.begin(): # .. ORM transaction is begun
Note that database IO will not normally occur when the session-level transaction is begun, as database transactions begin on an on-demand basis. However, the begin block is async to accommodate for a
SessionEvents.after_transaction_create()
event hook that may perform IO.For a general description of ORM begin, see
Session.begin()
.
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
begin_nested(**kw)¶ Return an
AsyncSessionTransaction
object which will begin a “nested” transaction, e.g. SAVEPOINT.Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.Behavior is the same as that of
AsyncSession.begin()
.For a general description of ORM begin nested, see
Session.begin_nested()
.
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
close()¶ Close out the transactional resources and ORM objects used by this
AsyncSession
.Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.This expunges all ORM objects associated with this
AsyncSession
, ends any transaction in progress and releases anyAsyncConnection
objects which thisAsyncSession
itself has checked out from associatedAsyncEngine
objects. The operation then leaves theAsyncSession
in a state which it may be used again.Tip
The
AsyncSession.close()
method does not prevent the Session from being used again. TheAsyncSession
itself does not actually have a distinct “closed” state; it merely means theAsyncSession
will release all database connections and ORM objects.See also
Closing - detail on the semantics of
AsyncSession.close()
-
classmethod
sqlalchemy.ext.asyncio.async_scoped_session.
close_all()¶ Close all
AsyncSession
sessions.Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
commit()¶ Commit the current transaction in progress.
Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
configure(**kwargs)¶ inherited from the
ScopedSessionMixin.configure()
method ofScopedSessionMixin
reconfigure the
sessionmaker
used by thisscoped_session
.
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
connection(**kw)¶ Return a
AsyncConnection
object corresponding to thisSession
object’s transactional state.Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.This method may also be used to establish execution options for the database connection used by the current transaction.
New in version 1.4.24: Added **kw arguments which are passed through to the underlying
Session.connection()
method.See also
Session.connection()
- main documentation for “connection”
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
delete(instance)¶ Mark an instance as deleted.
Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.The database delete operation occurs upon
flush()
.As this operation may need to cascade along unloaded relationships, it is awaitable to allow for those queries to take place.
See also
Session.delete()
- main documentation for delete
-
attribute
sqlalchemy.ext.asyncio.async_scoped_session.
deleted¶ The set of all instances marked as ‘deleted’ within this
Session
Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.Proxied for the
Session
class on behalf of theAsyncSession
class.
-
attribute
sqlalchemy.ext.asyncio.async_scoped_session.
dirty¶ The set of all persistent instances considered dirty.
Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.Proxied for the
Session
class on behalf of theAsyncSession
class.E.g.:
some_mapped_object in session.dirty
Instances are considered dirty when they were modified but not deleted.
Note that this ‘dirty’ calculation is ‘optimistic’; most attribute-setting or collection modification operations will mark an instance as ‘dirty’ and place it in this set, even if there is no net change to the attribute’s value. At flush time, the value of each attribute is compared to its previously saved value, and if there’s no net change, no SQL operation will occur (this is a more expensive operation so it’s only done at flush time).
To check if an instance has actionable net changes to its attributes, use the
Session.is_modified()
method.
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
execute(statement, params=None, execution_options={}, bind_arguments=None, **kw)¶ Execute a statement and return a buffered
Result
object.Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.See also
Session.execute()
- main documentation for execute
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
expire(instance, attribute_names=None)¶ Expire the attributes on an instance.
Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.Proxied for the
Session
class on behalf of theAsyncSession
class.Marks the attributes of an instance as out of date. When an expired attribute is next accessed, a query will be issued to the
Session
object’s current transactional context in order to load all expired attributes for the given instance. Note that a highly isolated transaction will return the same values as were previously read in that same transaction, regardless of changes in database state outside of that transaction.To expire all objects in the
Session
simultaneously, useSession.expire_all()
.The
Session
object’s default behavior is to expire all state whenever theSession.rollback()
orSession.commit()
methods are called, so that new state can be loaded for the new transaction. For this reason, callingSession.expire()
only makes sense for the specific case that a non-ORM SQL statement was emitted in the current transaction.- Parameters:
See also
Refreshing / Expiring - introductory material
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
expire_all()¶ Expires all persistent instances within this Session.
Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.Proxied for the
Session
class on behalf of theAsyncSession
class.When any attributes on a persistent instance is next accessed, a query will be issued using the
Session
object’s current transactional context in order to load all expired attributes for the given instance. Note that a highly isolated transaction will return the same values as were previously read in that same transaction, regardless of changes in database state outside of that transaction.To expire individual objects and individual attributes on those objects, use
Session.expire()
.The
Session
object’s default behavior is to expire all state whenever theSession.rollback()
orSession.commit()
methods are called, so that new state can be loaded for the new transaction. For this reason, callingSession.expire_all()
should not be needed when autocommit isFalse
, assuming the transaction is isolated.See also
Refreshing / Expiring - introductory material
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
expunge(instance)¶ Remove the instance from this
Session
.Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.Proxied for the
Session
class on behalf of theAsyncSession
class.This will free all internal references to the instance. Cascading will be applied according to the expunge cascade rule.
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
expunge_all()¶ Remove all object instances from this
Session
.Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.Proxied for the
Session
class on behalf of theAsyncSession
class.This is equivalent to calling
expunge(obj)
on all objects in thisSession
.
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
flush(objects=None)¶ Flush all the object changes to the database.
Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.See also
Session.flush()
- main documentation for flush
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
get(entity, ident, options=None, populate_existing=False, with_for_update=None, identity_token=None)¶ Return an instance based on the given primary key identifier, or
None
if not found.Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.See also
Session.get()
- main documentation for get
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
get_bind(mapper=None, clause=None, bind=None, **kw)¶ Return a “bind” to which the synchronous proxied
Session
is bound.Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.Unlike the
Session.get_bind()
method, this method is currently not used by thisAsyncSession
in any way in order to resolve engines for requests.Note
This method proxies directly to the
Session.get_bind()
method, however is currently not useful as an override target, in contrast to that of theSession.get_bind()
method. The example below illustrates how to implement customSession.get_bind()
schemes that work withAsyncSession
andAsyncEngine
.The pattern introduced at Custom Vertical Partitioning illustrates how to apply a custom bind-lookup scheme to a
Session
given a set ofEngine
objects. To apply a correspondingSession.get_bind()
implementation for use with aAsyncSession
andAsyncEngine
objects, continue to subclassSession
and apply it toAsyncSession
usingAsyncSession.sync_session_class
. The inner method must continue to returnEngine
instances, which can be acquired from aAsyncEngine
using theAsyncEngine.sync_engine
attribute:# using example from "Custom Vertical Partitioning" import random from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import create_async_engine from sqlalchemy.orm import Session, sessionmaker # construct async engines w/ async drivers engines = { 'leader':create_async_engine("sqlite+aiosqlite:///leader.db"), 'other':create_async_engine("sqlite+aiosqlite:///other.db"), 'follower1':create_async_engine("sqlite+aiosqlite:///follower1.db"), 'follower2':create_async_engine("sqlite+aiosqlite:///follower2.db"), } class RoutingSession(Session): def get_bind(self, mapper=None, clause=None, **kw): # within get_bind(), return sync engines if mapper and issubclass(mapper.class_, MyOtherClass): return engines['other'].sync_engine elif self._flushing or isinstance(clause, (Update, Delete)): return engines['leader'].sync_engine else: return engines[ random.choice(['follower1','follower2']) ].sync_engine # apply to AsyncSession using sync_session_class AsyncSessionMaker = sessionmaker( class_=AsyncSession, sync_session_class=RoutingSession )
The
Session.get_bind()
method is called in a non-asyncio, implicitly non-blocking context in the same manner as ORM event hooks and functions that are invoked viaAsyncSession.run_sync()
, so routines that wish to run SQL commands inside ofSession.get_bind()
can continue to do so using blocking-style code, which will be translated to implicitly async calls at the point of invoking IO on the database drivers.
-
classmethod
sqlalchemy.ext.asyncio.async_scoped_session.
identity_key(*args, **kwargs)¶ Return an identity key.
Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.Proxied for the
Session
class on behalf of theAsyncSession
class.This is an alias of
identity_key()
.
-
attribute
sqlalchemy.ext.asyncio.async_scoped_session.
identity_map¶ Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.
-
attribute
sqlalchemy.ext.asyncio.async_scoped_session.
info¶ A user-modifiable dictionary.
Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.Proxied for the
Session
class on behalf of theAsyncSession
class.The initial value of this dictionary can be populated using the
info
argument to theSession
constructor orsessionmaker
constructor or factory methods. The dictionary here is always local to thisSession
and can be modified independently of all otherSession
objects.
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
invalidate()¶ Close this Session, using connection invalidation.
Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.For a complete description, see
Session.invalidate()
.
-
attribute
sqlalchemy.ext.asyncio.async_scoped_session.
is_active¶ True if this
Session
not in “partial rollback” state.Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.Proxied for the
Session
class on behalf of theAsyncSession
class.Changed in version 1.4: The
Session
no longer begins a new transaction immediately, so this attribute will be False when theSession
is first instantiated.“partial rollback” state typically indicates that the flush process of the
Session
has failed, and that theSession.rollback()
method must be emitted in order to fully roll back the transaction.If this
Session
is not in a transaction at all, theSession
will autobegin when it is first used, so in this caseSession.is_active
will return True.Otherwise, if this
Session
is within a transaction, and that transaction has not been rolled back internally, theSession.is_active
will also return True.
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
is_modified(instance, include_collections=True)¶ Return
True
if the given instance has locally modified attributes.Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.Proxied for the
Session
class on behalf of theAsyncSession
class.This method retrieves the history for each instrumented attribute on the instance and performs a comparison of the current value to its previously committed value, if any.
It is in effect a more expensive and accurate version of checking for the given instance in the
Session.dirty
collection; a full test for each attribute’s net “dirty” status is performed.E.g.:
return session.is_modified(someobject)
A few caveats to this method apply:
Instances present in the
Session.dirty
collection may reportFalse
when tested with this method. This is because the object may have received change events via attribute mutation, thus placing it inSession.dirty
, but ultimately the state is the same as that loaded from the database, resulting in no net change here.Scalar attributes may not have recorded the previously set value when a new value was applied, if the attribute was not loaded, or was expired, at the time the new value was received - in these cases, the attribute is assumed to have a change, even if there is ultimately no net change against its database value. SQLAlchemy in most cases does not need the “old” value when a set event occurs, so it skips the expense of a SQL call if the old value isn’t present, based on the assumption that an UPDATE of the scalar value is usually needed, and in those few cases where it isn’t, is less expensive on average than issuing a defensive SELECT.
The “old” value is fetched unconditionally upon set only if the attribute container has the
active_history
flag set toTrue
. This flag is set typically for primary key attributes and scalar object references that are not a simple many-to-one. To set this flag for any arbitrary mapped column, use theactive_history
argument withcolumn_property()
.
- Parameters:
instance¶ – mapped instance to be tested for pending changes.
include_collections¶ – Indicates if multivalued collections should be included in the operation. Setting this to
False
is a way to detect only local-column based properties (i.e. scalar columns or many-to-one foreign keys) that would result in an UPDATE for this instance upon flush.
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
merge(instance, load=True, options=None)¶ Copy the state of a given instance into a corresponding instance within this
AsyncSession
.Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.See also
Session.merge()
- main documentation for merge
-
attribute
sqlalchemy.ext.asyncio.async_scoped_session.
new¶ The set of all instances marked as ‘new’ within this
Session
.Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.Proxied for the
Session
class on behalf of theAsyncSession
class.
-
attribute
sqlalchemy.ext.asyncio.async_scoped_session.
no_autoflush¶ Return a context manager that disables autoflush.
Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.Proxied for the
Session
class on behalf of theAsyncSession
class.e.g.:
with session.no_autoflush: some_object = SomeClass() session.add(some_object) # won't autoflush some_object.related_thing = session.query(SomeRelated).first()
Operations that proceed within the
with:
block will not be subject to flushes occurring upon query access. This is useful when initializing a series of objects which involve existing database queries, where the uncompleted object should not yet be flushed.
-
classmethod
sqlalchemy.ext.asyncio.async_scoped_session.
object_session(instance)¶ Return the
Session
to which an object belongs.Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.Proxied for the
Session
class on behalf of theAsyncSession
class.This is an alias of
object_session()
.
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
refresh(instance, attribute_names=None, with_for_update=None)¶ Expire and refresh the attributes on the given instance.
Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.A query will be issued to the database and all attributes will be refreshed with their current database value.
This is the async version of the
Session.refresh()
method. See that method for a complete description of all options.See also
Session.refresh()
- main documentation for refresh
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
async remove()¶ Dispose of the current
AsyncSession
, if present.Different from scoped_session’s remove method, this method would use await to wait for the close method of AsyncSession.
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
rollback()¶ Rollback the current transaction in progress.
Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
scalar(statement, params=None, execution_options={}, bind_arguments=None, **kw)¶ Execute a statement and return a scalar result.
Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.See also
Session.scalar()
- main documentation for scalar
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
scalars(statement, params=None, execution_options={}, bind_arguments=None, **kw)¶ Execute a statement and return scalar results.
Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.- Returns:
a
ScalarResult
object
New in version 1.4.24: Added
AsyncSession.scalars()
New in version 1.4.26: Added
async_scoped_session.scalars()
See also
Session.scalars()
- main documentation for scalarsAsyncSession.stream_scalars()
- streaming version
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
stream(statement, params=None, execution_options={}, bind_arguments=None, **kw)¶ Execute a statement and return a streaming
AsyncResult
object.Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.
-
method
sqlalchemy.ext.asyncio.async_scoped_session.
stream_scalars(statement, params=None, execution_options={}, bind_arguments=None, **kw)¶ Execute a statement and return a stream of scalar results.
Proxied for the
AsyncSession
class on behalf of theasync_scoped_session
class.- Returns:
an
AsyncScalarResult
object
New in version 1.4.24.
See also
Session.scalars()
- main documentation for scalarsAsyncSession.scalars()
- non streaming version
-
method
- class sqlalchemy.ext.asyncio.AsyncSession(bind=None, binds=None, sync_session_class=None, **kw)¶
Asyncio version of
Session
.The
AsyncSession
is a proxy for a traditionalSession
instance.New in version 1.4.
To use an
AsyncSession
with customSession
implementations, see theAsyncSession.sync_session_class
parameter.Members
sync_session_class, __init__(), add(), add_all(), begin(), begin_nested(), close(), close_all(), commit(), connection(), delete(), deleted, dirty, execute(), expire(), expire_all(), expunge(), expunge_all(), flush(), get(), get_bind(), get_nested_transaction(), get_transaction(), identity_key(), in_nested_transaction(), in_transaction(), info, invalidate(), is_active, is_modified(), merge(), new, no_autoflush, object_session(), refresh(), rollback(), run_sync(), scalar(), scalars(), stream(), stream_scalars(), sync_session
Class signature
class
sqlalchemy.ext.asyncio.AsyncSession
(sqlalchemy.ext.asyncio.base.ReversibleProxy
)-
attribute
sqlalchemy.ext.asyncio.AsyncSession.
sync_session_class = <class 'sqlalchemy.orm.session.Session'>¶ The class or callable that provides the underlying
Session
instance for a particularAsyncSession
.At the class level, this attribute is the default value for the
AsyncSession.sync_session_class
parameter. Custom subclasses ofAsyncSession
can override this.At the instance level, this attribute indicates the current class or callable that was used to provide the
Session
instance for thisAsyncSession
instance.New in version 1.4.24.
-
method
sqlalchemy.ext.asyncio.AsyncSession.
__init__(bind=None, binds=None, sync_session_class=None, **kw)¶ Construct a new
AsyncSession
.All parameters other than
sync_session_class
are passed to thesync_session_class
callable directly to instantiate a newSession
. Refer toSession.__init__()
for parameter documentation.- Parameters:
sync_session_class¶ –
A
Session
subclass or other callable which will be used to construct theSession
which will be proxied. This parameter may be used to provide customSession
subclasses. Defaults to theAsyncSession.sync_session_class
class-level attribute.New in version 1.4.24.
-
method
sqlalchemy.ext.asyncio.AsyncSession.
add(instance, _warn=True)¶ Place an object into this
Session
.Proxied for the
Session
class on behalf of theAsyncSession
class.Objects that are in the transient state when passed to the
Session.add()
method will move to the pending state, until the next flush, at which point they will move to the persistent state.Objects that are in the detached state when passed to the
Session.add()
method will move to the persistent state directly.If the transaction used by the
Session
is rolled back, objects which were transient when they were passed toSession.add()
will be moved back to the transient state, and will no longer be present within thisSession
.
-
method
sqlalchemy.ext.asyncio.AsyncSession.
add_all(instances)¶ Add the given collection of instances to this
Session
.Proxied for the
Session
class on behalf of theAsyncSession
class.See the documentation for
Session.add()
for a general behavioral description.
-
method
sqlalchemy.ext.asyncio.AsyncSession.
begin(**kw)¶ Return an
AsyncSessionTransaction
object.The underlying
Session
will perform the “begin” action when theAsyncSessionTransaction
object is entered:async with async_session.begin(): # .. ORM transaction is begun
Note that database IO will not normally occur when the session-level transaction is begun, as database transactions begin on an on-demand basis. However, the begin block is async to accommodate for a
SessionEvents.after_transaction_create()
event hook that may perform IO.For a general description of ORM begin, see
Session.begin()
.
-
method
sqlalchemy.ext.asyncio.AsyncSession.
begin_nested(**kw)¶ Return an
AsyncSessionTransaction
object which will begin a “nested” transaction, e.g. SAVEPOINT.Behavior is the same as that of
AsyncSession.begin()
.For a general description of ORM begin nested, see
Session.begin_nested()
.
-
method
sqlalchemy.ext.asyncio.AsyncSession.
async close()¶ Close out the transactional resources and ORM objects used by this
AsyncSession
.This expunges all ORM objects associated with this
AsyncSession
, ends any transaction in progress and releases anyAsyncConnection
objects which thisAsyncSession
itself has checked out from associatedAsyncEngine
objects. The operation then leaves theAsyncSession
in a state which it may be used again.Tip
The
AsyncSession.close()
method does not prevent the Session from being used again. TheAsyncSession
itself does not actually have a distinct “closed” state; it merely means theAsyncSession
will release all database connections and ORM objects.See also
Closing - detail on the semantics of
AsyncSession.close()
-
async classmethod
sqlalchemy.ext.asyncio.AsyncSession.
close_all()¶ Close all
AsyncSession
sessions.
-
method
sqlalchemy.ext.asyncio.AsyncSession.
async commit()¶ Commit the current transaction in progress.
-
method
sqlalchemy.ext.asyncio.AsyncSession.
async connection(**kw)¶ Return a
AsyncConnection
object corresponding to thisSession
object’s transactional state.This method may also be used to establish execution options for the database connection used by the current transaction.
New in version 1.4.24: Added **kw arguments which are passed through to the underlying
Session.connection()
method.See also
Session.connection()
- main documentation for “connection”
-
method
sqlalchemy.ext.asyncio.AsyncSession.
async delete(instance)¶ Mark an instance as deleted.
The database delete operation occurs upon
flush()
.As this operation may need to cascade along unloaded relationships, it is awaitable to allow for those queries to take place.
See also
Session.delete()
- main documentation for delete
-
attribute
sqlalchemy.ext.asyncio.AsyncSession.
deleted¶ The set of all instances marked as ‘deleted’ within this
Session
Proxied for the
Session
class on behalf of theAsyncSession
class.
-
attribute
sqlalchemy.ext.asyncio.AsyncSession.
dirty¶ The set of all persistent instances considered dirty.
Proxied for the
Session
class on behalf of theAsyncSession
class.E.g.:
some_mapped_object in session.dirty
Instances are considered dirty when they were modified but not deleted.
Note that this ‘dirty’ calculation is ‘optimistic’; most attribute-setting or collection modification operations will mark an instance as ‘dirty’ and place it in this set, even if there is no net change to the attribute’s value. At flush time, the value of each attribute is compared to its previously saved value, and if there’s no net change, no SQL operation will occur (this is a more expensive operation so it’s only done at flush time).
To check if an instance has actionable net changes to its attributes, use the
Session.is_modified()
method.
-
method
sqlalchemy.ext.asyncio.AsyncSession.
async execute(statement, params=None, execution_options={}, bind_arguments=None, **kw)¶ Execute a statement and return a buffered
Result
object.See also
Session.execute()
- main documentation for execute
-
method
sqlalchemy.ext.asyncio.AsyncSession.
expire(instance, attribute_names=None)¶ Expire the attributes on an instance.
Proxied for the
Session
class on behalf of theAsyncSession
class.Marks the attributes of an instance as out of date. When an expired attribute is next accessed, a query will be issued to the
Session
object’s current transactional context in order to load all expired attributes for the given instance. Note that a highly isolated transaction will return the same values as were previously read in that same transaction, regardless of changes in database state outside of that transaction.To expire all objects in the
Session
simultaneously, useSession.expire_all()
.The
Session
object’s default behavior is to expire all state whenever theSession.rollback()
orSession.commit()
methods are called, so that new state can be loaded for the new transaction. For this reason, callingSession.expire()
only makes sense for the specific case that a non-ORM SQL statement was emitted in the current transaction.- Parameters:
See also
Refreshing / Expiring - introductory material
-
method
sqlalchemy.ext.asyncio.AsyncSession.
expire_all()¶ Expires all persistent instances within this Session.
Proxied for the
Session
class on behalf of theAsyncSession
class.When any attributes on a persistent instance is next accessed, a query will be issued using the
Session
object’s current transactional context in order to load all expired attributes for the given instance. Note that a highly isolated transaction will return the same values as were previously read in that same transaction, regardless of changes in database state outside of that transaction.To expire individual objects and individual attributes on those objects, use
Session.expire()
.The
Session
object’s default behavior is to expire all state whenever theSession.rollback()
orSession.commit()
methods are called, so that new state can be loaded for the new transaction. For this reason, callingSession.expire_all()
should not be needed when autocommit isFalse
, assuming the transaction is isolated.See also
Refreshing / Expiring - introductory material
-
method
sqlalchemy.ext.asyncio.AsyncSession.
expunge(instance)¶ Remove the instance from this
Session
.Proxied for the
Session
class on behalf of theAsyncSession
class.This will free all internal references to the instance. Cascading will be applied according to the expunge cascade rule.
-
method
sqlalchemy.ext.asyncio.AsyncSession.
expunge_all()¶ Remove all object instances from this
Session
.Proxied for the
Session
class on behalf of theAsyncSession
class.This is equivalent to calling
expunge(obj)
on all objects in thisSession
.
-
method
sqlalchemy.ext.asyncio.AsyncSession.
async flush(objects=None)¶ Flush all the object changes to the database.
See also
Session.flush()
- main documentation for flush
-
method
sqlalchemy.ext.asyncio.AsyncSession.
async get(entity, ident, options=None, populate_existing=False, with_for_update=None, identity_token=None)¶ Return an instance based on the given primary key identifier, or
None
if not found.See also
Session.get()
- main documentation for get
-
method
sqlalchemy.ext.asyncio.AsyncSession.
get_bind(mapper=None, clause=None, bind=None, **kw)¶ Return a “bind” to which the synchronous proxied
Session
is bound.Unlike the
Session.get_bind()
method, this method is currently not used by thisAsyncSession
in any way in order to resolve engines for requests.Note
This method proxies directly to the
Session.get_bind()
method, however is currently not useful as an override target, in contrast to that of theSession.get_bind()
method. The example below illustrates how to implement customSession.get_bind()
schemes that work withAsyncSession
andAsyncEngine
.The pattern introduced at Custom Vertical Partitioning illustrates how to apply a custom bind-lookup scheme to a
Session
given a set ofEngine
objects. To apply a correspondingSession.get_bind()
implementation for use with aAsyncSession
andAsyncEngine
objects, continue to subclassSession
and apply it toAsyncSession
usingAsyncSession.sync_session_class
. The inner method must continue to returnEngine
instances, which can be acquired from aAsyncEngine
using theAsyncEngine.sync_engine
attribute:# using example from "Custom Vertical Partitioning" import random from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import create_async_engine from sqlalchemy.orm import Session, sessionmaker # construct async engines w/ async drivers engines = { 'leader':create_async_engine("sqlite+aiosqlite:///leader.db"), 'other':create_async_engine("sqlite+aiosqlite:///other.db"), 'follower1':create_async_engine("sqlite+aiosqlite:///follower1.db"), 'follower2':create_async_engine("sqlite+aiosqlite:///follower2.db"), } class RoutingSession(Session): def get_bind(self, mapper=None, clause=None, **kw): # within get_bind(), return sync engines if mapper and issubclass(mapper.class_, MyOtherClass): return engines['other'].sync_engine elif self._flushing or isinstance(clause, (Update, Delete)): return engines['leader'].sync_engine else: return engines[ random.choice(['follower1','follower2']) ].sync_engine # apply to AsyncSession using sync_session_class AsyncSessionMaker = sessionmaker( class_=AsyncSession, sync_session_class=RoutingSession )
The
Session.get_bind()
method is called in a non-asyncio, implicitly non-blocking context in the same manner as ORM event hooks and functions that are invoked viaAsyncSession.run_sync()
, so routines that wish to run SQL commands inside ofSession.get_bind()
can continue to do so using blocking-style code, which will be translated to implicitly async calls at the point of invoking IO on the database drivers.
-
method
sqlalchemy.ext.asyncio.AsyncSession.
get_nested_transaction()¶ Return the current nested transaction in progress, if any.
- Returns:
an
AsyncSessionTransaction
object, orNone
.
New in version 1.4.18.
-
method
sqlalchemy.ext.asyncio.AsyncSession.
get_transaction()¶ Return the current root transaction in progress, if any.
- Returns:
an
AsyncSessionTransaction
object, orNone
.
New in version 1.4.18.
-
classmethod
sqlalchemy.ext.asyncio.AsyncSession.
identity_key(*args, **kwargs)¶ Return an identity key.
Proxied for the
Session
class on behalf of theAsyncSession
class.This is an alias of
identity_key()
.
-
method
sqlalchemy.ext.asyncio.AsyncSession.
in_nested_transaction()¶ Return True if this
Session
has begun a nested transaction, e.g. SAVEPOINT.Proxied for the
Session
class on behalf of theAsyncSession
class.New in version 1.4.
-
method
sqlalchemy.ext.asyncio.AsyncSession.
in_transaction()¶ Return True if this
Session
has begun a transaction.Proxied for the
Session
class on behalf of theAsyncSession
class.New in version 1.4.
See also
-
attribute
sqlalchemy.ext.asyncio.AsyncSession.
info¶ A user-modifiable dictionary.
Proxied for the
Session
class on behalf of theAsyncSession
class.The initial value of this dictionary can be populated using the
info
argument to theSession
constructor orsessionmaker
constructor or factory methods. The dictionary here is always local to thisSession
and can be modified independently of all otherSession
objects.
-
method
sqlalchemy.ext.asyncio.AsyncSession.
async invalidate()¶ Close this Session, using connection invalidation.
For a complete description, see
Session.invalidate()
.
-
attribute
sqlalchemy.ext.asyncio.AsyncSession.
is_active¶ True if this
Session
not in “partial rollback” state.Proxied for the
Session
class on behalf of theAsyncSession
class.Changed in version 1.4: The
Session
no longer begins a new transaction immediately, so this attribute will be False when theSession
is first instantiated.“partial rollback” state typically indicates that the flush process of the
Session
has failed, and that theSession.rollback()
method must be emitted in order to fully roll back the transaction.If this
Session
is not in a transaction at all, theSession
will autobegin when it is first used, so in this caseSession.is_active
will return True.Otherwise, if this
Session
is within a transaction, and that transaction has not been rolled back internally, theSession.is_active
will also return True.
-
method
sqlalchemy.ext.asyncio.AsyncSession.
is_modified(instance, include_collections=True)¶ Return
True
if the given instance has locally modified attributes.Proxied for the
Session
class on behalf of theAsyncSession
class.This method retrieves the history for each instrumented attribute on the instance and performs a comparison of the current value to its previously committed value, if any.
It is in effect a more expensive and accurate version of checking for the given instance in the
Session.dirty
collection; a full test for each attribute’s net “dirty” status is performed.E.g.:
return session.is_modified(someobject)
A few caveats to this method apply:
Instances present in the
Session.dirty
collection may reportFalse
when tested with this method. This is because the object may have received change events via attribute mutation, thus placing it inSession.dirty
, but ultimately the state is the same as that loaded from the database, resulting in no net change here.Scalar attributes may not have recorded the previously set value when a new value was applied, if the attribute was not loaded, or was expired, at the time the new value was received - in these cases, the attribute is assumed to have a change, even if there is ultimately no net change against its database value. SQLAlchemy in most cases does not need the “old” value when a set event occurs, so it skips the expense of a SQL call if the old value isn’t present, based on the assumption that an UPDATE of the scalar value is usually needed, and in those few cases where it isn’t, is less expensive on average than issuing a defensive SELECT.
The “old” value is fetched unconditionally upon set only if the attribute container has the
active_history
flag set toTrue
. This flag is set typically for primary key attributes and scalar object references that are not a simple many-to-one. To set this flag for any arbitrary mapped column, use theactive_history
argument withcolumn_property()
.
- Parameters:
instance¶ – mapped instance to be tested for pending changes.
include_collections¶ – Indicates if multivalued collections should be included in the operation. Setting this to
False
is a way to detect only local-column based properties (i.e. scalar columns or many-to-one foreign keys) that would result in an UPDATE for this instance upon flush.
-
method
sqlalchemy.ext.asyncio.AsyncSession.
async merge(instance, load=True, options=None)¶ Copy the state of a given instance into a corresponding instance within this
AsyncSession
.See also
Session.merge()
- main documentation for merge
-
attribute
sqlalchemy.ext.asyncio.AsyncSession.
new¶ The set of all instances marked as ‘new’ within this
Session
.Proxied for the
Session
class on behalf of theAsyncSession
class.
-
attribute
sqlalchemy.ext.asyncio.AsyncSession.
no_autoflush¶ Return a context manager that disables autoflush.
Proxied for the
Session
class on behalf of theAsyncSession
class.e.g.:
with session.no_autoflush: some_object = SomeClass() session.add(some_object) # won't autoflush some_object.related_thing = session.query(SomeRelated).first()
Operations that proceed within the
with:
block will not be subject to flushes occurring upon query access. This is useful when initializing a series of objects which involve existing database queries, where the uncompleted object should not yet be flushed.
-
classmethod
sqlalchemy.ext.asyncio.AsyncSession.
object_session(instance)¶ Return the
Session
to which an object belongs.Proxied for the
Session
class on behalf of theAsyncSession
class.This is an alias of
object_session()
.
-
method
sqlalchemy.ext.asyncio.AsyncSession.
async refresh(instance, attribute_names=None, with_for_update=None)¶ Expire and refresh the attributes on the given instance.
A query will be issued to the database and all attributes will be refreshed with their current database value.
This is the async version of the
Session.refresh()
method. See that method for a complete description of all options.See also
Session.refresh()
- main documentation for refresh
-
method
sqlalchemy.ext.asyncio.AsyncSession.
async rollback()¶ Rollback the current transaction in progress.
-
method
sqlalchemy.ext.asyncio.AsyncSession.
async run_sync(fn, *arg, **kw)¶ Invoke the given sync callable passing sync 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 AsyncSession(async_engine) as session: await session.run_sync(some_business_method)
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.
-
method
sqlalchemy.ext.asyncio.AsyncSession.
async scalar(statement, params=None, execution_options={}, bind_arguments=None, **kw)¶ Execute a statement and return a scalar result.
See also
Session.scalar()
- main documentation for scalar
-
method
sqlalchemy.ext.asyncio.AsyncSession.
async scalars(statement, params=None, execution_options={}, bind_arguments=None, **kw)¶ Execute a statement and return scalar results.
- Returns:
a
ScalarResult
object
New in version 1.4.24: Added
AsyncSession.scalars()
New in version 1.4.26: Added
async_scoped_session.scalars()
See also
Session.scalars()
- main documentation for scalarsAsyncSession.stream_scalars()
- streaming version
-
method
sqlalchemy.ext.asyncio.AsyncSession.
async stream(statement, params=None, execution_options={}, bind_arguments=None, **kw)¶ Execute a statement and return a streaming
AsyncResult
object.
-
method
sqlalchemy.ext.asyncio.AsyncSession.
async stream_scalars(statement, params=None, execution_options={}, bind_arguments=None, **kw)¶ Execute a statement and return a stream of scalar results.
- Returns:
an
AsyncScalarResult
object
New in version 1.4.24.
See also
Session.scalars()
- main documentation for scalarsAsyncSession.scalars()
- non streaming version
-
attribute
sqlalchemy.ext.asyncio.AsyncSession.
sync_session: Session¶ Reference to the underlying
Session
thisAsyncSession
proxies requests towards.This instance can be used as an event target.
-
attribute
- class sqlalchemy.ext.asyncio.AsyncSessionTransaction(session, nested=False)¶
A wrapper for the ORM
SessionTransaction
object.This object is provided so that a transaction-holding object for the
AsyncSession.begin()
may be returned.The object supports both explicit calls to
AsyncSessionTransaction.commit()
andAsyncSessionTransaction.rollback()
, as well as use as an async context manager.New in version 1.4.
Members
Class signature
class
sqlalchemy.ext.asyncio.AsyncSessionTransaction
(sqlalchemy.ext.asyncio.base.ReversibleProxy
,sqlalchemy.ext.asyncio.base.StartableContext
)-
method
sqlalchemy.ext.asyncio.AsyncSessionTransaction.
async commit()¶ Commit this
AsyncTransaction
.
-
method
sqlalchemy.ext.asyncio.AsyncSessionTransaction.
async rollback()¶ Roll back this
AsyncTransaction
.
-
method
flambé! the dragon and The Alchemist image designs created and generously donated by Rotem Yaari.
Created using Sphinx 7.2.6. Documentation last generated: Wed 30 Oct 2024 02:18:58 PM EDT