Hasty Briefsbeta

Bilingual

SQLAlchemy 2 In Practice - Chapter 7: Asynchronous SQLAlchemy

a day ago
  • SQLAlchemy 1.4+ supports asynchronous programming via asyncio for both Core and ORM, requiring async-compatible database drivers (e.g., aiosqlite, aiomysql, asyncpg).
  • Asynchronous code must avoid implicit lazy loading; relationships should use eager loaders (like 'joined' or 'selectin') or explicit loaders (like 'write_only') to prevent function coloring issues.
  • Sessions and engines are replaced with asynchronous equivalents (create_async_engine, async_sessionmaker), and 'expire_on_commit' is disabled to avoid implicit database refreshes.
  • Alembic migrations require an async template ('-t async') and configuration of batch mode for compatibility.
  • After a session flush, uninitialized list-style relationships can trigger lazy loading; solutions include initializing relationships explicitly or using the WriteOnlyMapped loader.
  • Query execution methods (session.execute, session.scalar, etc.) must be awaited, and stream()/stream_scalars() are recommended for efficient async iteration over large result sets.