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.

The asyncio extension requires at least Python version 3.6.

Note

The asyncio should be regarded as alpha level for the 1.4 release of SQLAlchemy. API details are subject to change at any time.

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.

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:

  1. import asyncio
  2. from sqlalchemy.ext.asyncio import create_async_engine
  3. async def async_main():
  4. engine = create_async_engine(
  5. "postgresql+asyncpg://scott:tiger@localhost/test", echo=True,
  6. )
  7. async with engine.begin() as conn:
  8. await conn.run_sync(meta.drop_all)
  9. await conn.run_sync(meta.create_all)
  10. await conn.execute(
  11. t1.insert(), [{"name": "some name 1"}, {"name": "some name 2"}]
  12. )
  13. async with engine.connect() as conn:
  14. # select a Result, which will be delivered with buffered
  15. # results
  16. result = await conn.execute(select(t1).where(t1.c.name == "some name 1"))
  17. print(result.fetchall())
  18. 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.

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:

  1. async with engine.connect() as conn:
  2. async_result = await conn.stream(select(t1))
  3. async for row in async_result:
  4. 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:

  1. import asyncio
  2. from sqlalchemy import Column
  3. from sqlalchemy import DateTime
  4. from sqlalchemy import ForeignKey
  5. from sqlalchemy import func
  6. from sqlalchemy import Integer
  7. from sqlalchemy import String
  8. from sqlalchemy.ext.asyncio import AsyncSession
  9. from sqlalchemy.ext.asyncio import create_async_engine
  10. from sqlalchemy.ext.declarative import declarative_base
  11. from sqlalchemy.future import select
  12. from sqlalchemy.orm import relationship
  13. from sqlalchemy.orm import selectinload
  14. from sqlalchemy.orm import sessionmaker
  15. Base = declarative_base()
  16. class A(Base):
  17. __tablename__ = "a"
  18. id = Column(Integer, primary_key=True)
  19. data = Column(String)
  20. create_date = Column(DateTime, server_default=func.now())
  21. bs = relationship("B")
  22. # required in order to access columns with server defaults
  23. # or SQL expression defaults, subsequent to a flush, without
  24. # triggering an expired load
  25. __mapper_args__ = {"eager_defaults": True}
  26. class B(Base):
  27. __tablename__ = "b"
  28. id = Column(Integer, primary_key=True)
  29. a_id = Column(ForeignKey("a.id"))
  30. data = Column(String)
  31. async def async_main():
  32. engine = create_async_engine(
  33. "postgresql+asyncpg://scott:tiger@localhost/test",
  34. echo=True,
  35. )
  36. async with engine.begin() as conn:
  37. await conn.run_sync(Base.metadata.drop_all)
  38. await conn.run_sync(Base.metadata.create_all)
  39. # expire_on_commit=False will prevent attributes from being expired
  40. # after commit.
  41. async_session = sessionmaker(
  42. engine, expire_on_commit=False, class_=AsyncSession
  43. )
  44. async with async_session() as session:
  45. async with session.begin():
  46. session.add_all(
  47. [
  48. A(bs=[B(), B()], data="a1"),
  49. A(bs=[B()], data="a2"),
  50. A(bs=[B(), B()], data="a3"),
  51. ]
  52. )
  53. stmt = select(A).options(selectinload(A.bs))
  54. result = await session.execute(stmt)
  55. for a1 in result.scalars():
  56. print(a1)
  57. print(f"created at: {a1.create_date}")
  58. for b1 in a1.bs:
  59. print(b1)
  60. result = await session.execute(select(A).order_by(A.id))
  61. a1 = result.scalars().first()
  62. a1.data = "new data"
  63. await session.commit()
  64. # access attribute subsequent to commit; this is what
  65. # expire_on_commit=False allows
  66. print(a1.data)
  67. 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.

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 the A.bs collection within the scope of the await session.execute() call:

    1. 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 using Session.expire_on_commit set to False, so that we may access attributes on an object subsequent to a call to AsyncSession.commit(), as in the line at the end where we access an attribute:

    1. # create AsyncSession with expire_on_commit=False
    2. async_session = AsyncSession(engine, expire_on_commit=False)
    3. # sessionmaker version
    4. async_session = sessionmaker(
    5. engine, expire_on_commit=False, class_=AsyncSession
    6. )
    7. async with async_session() as session:
    8. result = await session.execute(select(A).order_by(A.id))
    9. a1 = result.scalars().first()
    10. # commit would normally expire all attributes
    11. await session.commit()
    12. # access attribute subsequent to commit; this is what
    13. # expire_on_commit=False allows
    14. print(a1.data)
  • The Column.server_default value on the created_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 the Column.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 the mapper.eager_defaults parameter on the mapping:

    1. class A(Base):
    2. # ...
    3. # column with a server_default, or SQL expression default
    4. create_date = Column(DateTime, server_default=func.now())
    5. # add this so that it can be accessed
    6. __mapper_args__ = {"eager_defaults": True}

Other guidelines include:

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:

  1. import asyncio
  2. from sqlalchemy.ext.asyncio import create_async_engine
  3. from sqlalchemy.ext.asyncio import AsyncSession
  4. def fetch_and_update_objects(session):
  5. """run traditional sync-style ORM code in a function that will be
  6. invoked within an awaitable.
  7. """
  8. # the session object here is a traditional ORM Session.
  9. # all features are available here including legacy Query use.
  10. stmt = select(A)
  11. result = session.execute(stmt)
  12. for a1 in result.scalars():
  13. print(a1)
  14. # lazy loads
  15. for b1 in a1.bs:
  16. print(b1)
  17. # legacy Query use
  18. a1 = session.query(A).order_by(A.id).first()
  19. a1.data = "new data"
  20. async def async_main():
  21. engine = create_async_engine(
  22. "postgresql+asyncpg://scott:tiger@localhost/test", echo=True,
  23. )
  24. async with engine.begin() as conn:
  25. await conn.run_sync(Base.metadata.drop_all)
  26. await conn.run_sync(Base.metadata.create_all)
  27. async with AsyncSession(engine) as session:
  28. async with session.begin():
  29. session.add_all(
  30. [
  31. A(bs=[B(), B()], data="a1"),
  32. A(bs=[B()], data="a2"),
  33. A(bs=[B(), B()], data="a3"),
  34. ]
  35. )
  36. await session.run_sync(fetch_and_update_objects)
  37. await session.commit()
  38. 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:

  1. 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 the gevent event loop.

  2. 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.

  3. 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.

  4. The underlying network drivers are also using pure Python asyncio concepts, no third party networking libraries as gevent and eventlet provides are in use.

Using multiple asyncio event loops

An application that makes use of multiple event loops, for example by 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:

  1. from sqlalchemy.pool import NullPool
  2. engine = create_async_engine(
  3. "postgresql+asyncpg://user:pass@host/dbname", poolclass=NullPool
  4. )

Engine API Documentation

Object NameDescription

AsyncConnection

An asyncio proxy for a Connection.

AsyncEngine

An asyncio proxy for a Engine.

AsyncTransaction

An asyncio proxy for a Transaction.

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 the create_engine() function. The specified dialect must be an asyncio-compatible dialect such as asyncpg.

New in version 1.4.

class sqlalchemy.ext.asyncio.``AsyncEngine(sync_engine: sqlalchemy.future.engine.Engine)

An asyncio proxy for a Engine.

AsyncEngine is acquired using the create_async_engine() function:

  1. from sqlalchemy.ext.asyncio import create_async_engine
  2. engine = create_async_engine("postgresql+asyncpg://user:pass@host/dbname")

New in version 1.4.

Class signature

class sqlalchemy.ext.asyncio.AsyncEngine (sqlalchemy.ext.asyncio.base.ProxyComparable, sqlalchemy.ext.asyncio.AsyncConnectable)

class sqlalchemy.ext.asyncio.``AsyncConnection(async_engine: sqlalchemy.ext.asyncio.engine.AsyncEngine, sync_connection: Optional[sqlalchemy.future.engine.Connection] = None)

An asyncio proxy for a Connection.

AsyncConnection is acquired using the AsyncEngine.connect() method of AsyncEngine:

  1. from sqlalchemy.ext.asyncio import create_async_engine
  2. engine = create_async_engine("postgresql+asyncpg://user:pass@host/dbname")
  3. async with engine.connect() as conn:
  4. result = await conn.execute(select(table))

New in version 1.4.

Class signature

class sqlalchemy.ext.asyncio.AsyncConnection (sqlalchemy.ext.asyncio.base.ProxyComparable, sqlalchemy.ext.asyncio.base.StartableContext, sqlalchemy.ext.asyncio.AsyncConnectable)

class sqlalchemy.ext.asyncio.``AsyncTransaction(connection: sqlalchemy.ext.asyncio.engine.AsyncConnection, nested: bool = False)

An asyncio proxy for a Transaction.

Class signature

class sqlalchemy.ext.asyncio.AsyncTransaction (sqlalchemy.ext.asyncio.base.ProxyComparable, sqlalchemy.ext.asyncio.base.StartableContext)

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 NameDescription

AsyncMappingResult

A wrapper for a AsyncResult that returns dictionary values rather than Row values.

AsyncResult

An asyncio wrapper around a Result object.

AsyncScalarResult

A wrapper for a AsyncResult that returns scalar values rather than Row values.

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 the AsyncConnection.stream() and AsyncSession.stream() methods.

New in version 1.4.

Class signature

class sqlalchemy.ext.asyncio.AsyncResult (sqlalchemy.ext.asyncio.AsyncCommon)

class sqlalchemy.ext.asyncio.``AsyncScalarResult(real_result, index)

A wrapper for a AsyncResult that returns scalar values rather than Row values.

The AsyncScalarResult object is acquired by calling the AsyncResult.scalars() method.

Refer to the ScalarResult object in the synchronous SQLAlchemy API for a complete behavioral description.

New in version 1.4.

Class signature

class sqlalchemy.ext.asyncio.AsyncScalarResult (sqlalchemy.ext.asyncio.AsyncCommon)

class sqlalchemy.ext.asyncio.``AsyncMappingResult(result)

A wrapper for a AsyncResult that returns dictionary values rather than Row values.

The AsyncMappingResult object is acquired by calling the AsyncResult.mappings() method.

Refer to the MappingResult object in the synchronous SQLAlchemy API for a complete behavioral description.

New in version 1.4.

Class signature

class sqlalchemy.ext.asyncio.AsyncMappingResult (sqlalchemy.ext.asyncio.AsyncCommon)

ORM Session API Documentation

Object NameDescription

AsyncSession

Asyncio version of Session.

AsyncSessionTransaction

A wrapper for the ORM SessionTransaction object.

class sqlalchemy.ext.asyncio.``AsyncSession(bind: Optional[sqlalchemy.ext.asyncio.engine.AsyncEngine] = None, binds: Optional[Mapping[object, sqlalchemy.ext.asyncio.engine.AsyncEngine]] = None, \*kw*)

Asyncio version of Session.

New in version 1.4.

  • method sqlalchemy.ext.asyncio.AsyncSession.add(instance, _warn=True)

    Place an object in the Session.

    Proxied for the Session class on behalf of the AsyncSession class.

    Its state will be persisted to the database on the next flush operation.

    Repeated calls to add() will be ignored. The opposite of add() is expunge().

  • 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 the AsyncSession class.

  • method sqlalchemy.ext.asyncio.AsyncSession.begin(\*kw*)

    Return an AsyncSessionTransaction object.

    The underlying Session will perform the “begin” action when the AsyncSessionTransaction object is entered:

    1. async with async_session.begin():
    2. # .. 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().

  • async method sqlalchemy.ext.asyncio.AsyncSession.close()

    Close this AsyncSession.

  • method sqlalchemy.ext.asyncio.AsyncSession.async classmethod close_all()

    Close all AsyncSession sessions.

  • async method sqlalchemy.ext.asyncio.AsyncSession.commit()

    Commit the current transaction in progress.

  • async method sqlalchemy.ext.asyncio.AsyncSession.connection()

    Return a AsyncConnection object corresponding to this Session object’s transactional state.

  • async method sqlalchemy.ext.asyncio.AsyncSession.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.

  • 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 the AsyncSession class.

  • attribute sqlalchemy.ext.asyncio.AsyncSession.dirty

    The set of all persistent instances considered dirty.

    Proxied for the Session class on behalf of the AsyncSession class.

    E.g.:

    1. 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.

  • async method sqlalchemy.ext.asyncio.AsyncSession.execute(statement: sqlalchemy.sql.base.Executable, params: Optional[Mapping] = None, execution_options: Mapping = {}, bind_arguments: Optional[Mapping] = None, \*kw*) → sqlalchemy.engine.Result

    Execute a statement and return a buffered Result object.

  • method sqlalchemy.ext.asyncio.AsyncSession.expire(instance, attribute_names=None)

    Expire the attributes on an instance.

    Proxied for the Session class on behalf of the AsyncSession 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, use Session.expire_all().

    The Session object’s default behavior is to expire all state whenever the Session.rollback() or Session.commit() methods are called, so that new state can be loaded for the new transaction. For this reason, calling Session.expire() only makes sense for the specific case that a non-ORM SQL statement was emitted in the current transaction.

    • Parameters

      • instance – The instance to be refreshed.

      • attribute_names – optional list of string attribute names indicating a subset of attributes to be expired.

  1. See also
  2. [Refreshing / Expiring]($ab781dd78600e308.md#session-expire) - introductory material
  3. [`Session.expire()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.expire "sqlalchemy.orm.Session.expire")
  4. [`Session.refresh()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.refresh "sqlalchemy.orm.Session.refresh")
  5. [`Query.populate_existing()`]($3cf240505c8b4e45.md#sqlalchemy.orm.Query.populate_existing "sqlalchemy.orm.Query.populate_existing")
  • method sqlalchemy.ext.asyncio.AsyncSession.expire_all()

    Expires all persistent instances within this Session.

    Proxied for the Session class on behalf of the AsyncSession 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 the Session.rollback() or Session.commit() methods are called, so that new state can be loaded for the new transaction. For this reason, calling Session.expire_all() should not be needed when autocommit is False, assuming the transaction is isolated.

    See also

    Refreshing / Expiring - introductory material

    Session.expire()

    Session.refresh()

    Query.populate_existing()

  • method sqlalchemy.ext.asyncio.AsyncSession.expunge(instance)

    Remove the instance from this Session.

    Proxied for the Session class on behalf of the AsyncSession 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 the AsyncSession class.

    This is equivalent to calling expunge(obj) on all objects in this Session.

  • async method sqlalchemy.ext.asyncio.AsyncSession.flush(objects=None)

    Flush all the object changes to the database.

    See also

    Session.flush()

  • async method sqlalchemy.ext.asyncio.AsyncSession.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.

  • method sqlalchemy.ext.asyncio.AsyncSession.get_bind(mapper=None, clause=None, bind=None, _sa_skip_events=None, _sa_skip_for_implicit_returning=False)

    Return a “bind” to which this Session is bound.

    Proxied for the Session class on behalf of the AsyncSession class.

    The “bind” is usually an instance of Engine, except in the case where the Session has been explicitly bound directly to a Connection.

    For a multiply-bound or unbound Session, the mapper or clause arguments are used to determine the appropriate bind to return.

    Note that the “mapper” argument is usually present when Session.get_bind() is called via an ORM operation such as a Session.query(), each individual INSERT/UPDATE/DELETE operation within a Session.flush(), call, etc.

    The order of resolution is:

    1. if mapper given and Session.binds is present, locate a bind based first on the mapper in use, then on the mapped class in use, then on any base classes that are present in the __mro__ of the mapped class, from more specific superclasses to more general.

    2. if clause given and Session.binds is present, locate a bind based on Table objects found in the given clause present in Session.binds.

    3. if Session.binds is present, return that.

    4. if clause given, attempt to return a bind linked to the MetaData ultimately associated with the clause.

    5. if mapper given, attempt to return a bind linked to the MetaData ultimately associated with the Table or other selectable to which the mapper is mapped.

    6. No bind can be found, UnboundExecutionError is raised.

    Note that the Session.get_bind() method can be overridden on a user-defined subclass of Session to provide any kind of bind resolution scheme. See the example at Custom Vertical Partitioning.

    • Parameters

      • mapper – Optional mapper() mapped class or instance of Mapper. The bind can be derived from a Mapper first by consulting the “binds” map associated with this Session, and secondly by consulting the MetaData associated with the Table to which the Mapper is mapped for a bind.

      • clause – A ClauseElement (i.e. select(), text(), etc.). If the mapper argument is not present or could not produce a bind, the given expression construct will be searched for a bound element, typically a Table associated with bound MetaData.

  1. See also
  2. [Partitioning Strategies (e.g. multiple database backends per Session)]($40343ee29299c061.md#session-partitioning)
  3. [`Session.binds`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.params.binds "sqlalchemy.orm.Session")
  4. [`Session.bind_mapper()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.bind_mapper "sqlalchemy.orm.Session.bind_mapper")
  5. [`Session.bind_table()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.bind_table "sqlalchemy.orm.Session.bind_table")
  • method sqlalchemy.ext.asyncio.AsyncSession.classmethod identity_key(\args, **kwargs*)

    Return an identity key.

    Proxied for the Session class on behalf of the AsyncSession class.

    This is an alias of identity_key().

  • method sqlalchemy.ext.asyncio.AsyncSession.in_transaction()

    Return True if this Session has begun a transaction.

    Proxied for the Session class on behalf of the AsyncSession class.

    New in version 1.4.

    See also

    Session.is_active

  • attribute sqlalchemy.ext.asyncio.AsyncSession.info

    A user-modifiable dictionary.

    Proxied for the Session class on behalf of the AsyncSession class.

    The initial value of this dictionary can be populated using the info argument to the Session constructor or sessionmaker constructor or factory methods. The dictionary here is always local to this Session and can be modified independently of all other Session objects.

  • attribute sqlalchemy.ext.asyncio.AsyncSession.is_active

    True if this Session not in “partial rollback” state.

    Proxied for the Session class on behalf of the AsyncSession class.

    Changed in version 1.4: The Session no longer begins a new transaction immediately, so this attribute will be False when the Session is first instantiated.

    “partial rollback” state typically indicates that the flush process of the Session has failed, and that the Session.rollback() method must be emitted in order to fully roll back the transaction.

    If this Session is not in a transaction at all, the Session will autobegin when it is first used, so in this case Session.is_active will return True.

    Otherwise, if this Session is within a transaction, and that transaction has not been rolled back internally, the Session.is_active will also return True.

    See also

    “This Session’s transaction has been rolled back due to a previous exception during flush.” (or similar)

    Session.in_transaction()

  • 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 the AsyncSession 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.:

    1. return session.is_modified(someobject)

    A few caveats to this method apply:

    • Instances present in the Session.dirty collection may report False when tested with this method. This is because the object may have received change events via attribute mutation, thus placing it in Session.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 to True. 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 the active_history argument with column_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.

  • async method sqlalchemy.ext.asyncio.AsyncSession.merge(instance, load=True)

    Copy the state of a given instance into a corresponding instance within this AsyncSession.

  • 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 the AsyncSession class.

  • attribute sqlalchemy.ext.asyncio.AsyncSession.no_autoflush

    Return a context manager that disables autoflush.

    Proxied for the Session class on behalf of the AsyncSession class.

    e.g.:

    1. with session.no_autoflush:
    2. some_object = SomeClass()
    3. session.add(some_object)
    4. # won't autoflush
    5. 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.

  • method sqlalchemy.ext.asyncio.AsyncSession.classmethod object_session(instance)

    Return the Session to which an object belongs.

    Proxied for the Session class on behalf of the AsyncSession class.

    This is an alias of object_session().

  • async method sqlalchemy.ext.asyncio.AsyncSession.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.

  • async method sqlalchemy.ext.asyncio.AsyncSession.rollback()

    Rollback the current transaction in progress.

  • async method sqlalchemy.ext.asyncio.AsyncSession.run_sync(fn: Callable[[…], T], \arg, **kw*) → T

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

    1. with AsyncSession(async_engine) as session:
    2. 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.

    See also

    Running Synchronous Methods and Functions under asyncio

  • async method sqlalchemy.ext.asyncio.AsyncSession.scalar(statement: sqlalchemy.sql.base.Executable, params: Optional[Mapping] = None, execution_options: Mapping = {}, bind_arguments: Optional[Mapping] = None, \*kw*) → Any

    Execute a statement and return a scalar result.

  • async method sqlalchemy.ext.asyncio.AsyncSession.stream(statement, params=None, execution_options={}, bind_arguments=None, \*kw*)

    Execute a statement and return a streaming AsyncResult object.

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() and AsyncSessionTransaction.rollback(), as well as use as an async context manager.

New in version 1.4.

Class signature

class sqlalchemy.ext.asyncio.AsyncSessionTransaction (sqlalchemy.ext.asyncio.base.StartableContext)