|
| 1 | +# Async Support |
| 2 | + |
| 3 | +SQLModel supports asynchronous operations by leveraging SQLAlchemy's `asyncio` extension. |
| 4 | + |
| 5 | +## Setup |
| 6 | + |
| 7 | +To use async features, you need an async database driver. For SQLite, use `aiosqlite`. For PostgreSQL, use `asyncpg`. |
| 8 | + |
| 9 | +```bash |
| 10 | +pip install aiosqlite |
| 11 | +``` |
| 12 | + |
| 13 | +## Async Engine and Session |
| 14 | + |
| 15 | +You can create an async engine using `create_async_engine` and manage sessions with `AsyncSession`. |
| 16 | + |
| 17 | +```python |
| 18 | +from sqlalchemy.ext.asyncio import create_async_engine |
| 19 | +from sqlalchemy.orm import sessionmaker |
| 20 | +from sqlmodel import Field, SQLModel, select |
| 21 | +from sqlmodel.ext.asyncio.session import AsyncSession |
| 22 | + |
| 23 | +class Hero(SQLModel, table=True): |
| 24 | + id: int | None = Field(default=None, primary_key=True) |
| 25 | + name: str |
| 26 | + secret_name: str |
| 27 | + age: int | None = None |
| 28 | + |
| 29 | +DATABASE_URL = "sqlite+aiosqlite:///database.db" |
| 30 | +engine = create_async_engine(DATABASE_URL, echo=True) |
| 31 | + |
| 32 | +async def init_db(): |
| 33 | + async with engine.begin() as conn: |
| 34 | + await conn.run_sync(SQLModel.metadata.create_all) |
| 35 | + |
| 36 | +async def create_hero(): |
| 37 | + async with AsyncSession(engine) as session: |
| 38 | + hero = Hero(name="Deadpond", secret_name="Dive-man") |
| 39 | + session.add(hero) |
| 40 | + await session.commit() |
| 41 | + await session.refresh(hero) |
| 42 | + print(f"Created hero: {hero.name}") |
| 43 | + |
| 44 | +async def select_heroes(): |
| 45 | + async with AsyncSession(engine) as session: |
| 46 | + statement = select(Hero).where(Hero.name == "Deadpond") |
| 47 | + results = await session.exec(statement) |
| 48 | + hero = results.first() |
| 49 | + print(f"Found hero: {hero.name}") |
| 50 | + |
| 51 | +import asyncio |
| 52 | + |
| 53 | +async def main(): |
| 54 | + await init_db() |
| 55 | + await create_hero() |
| 56 | + await select_heroes() |
| 57 | + |
| 58 | +if __name__ == "__main__": |
| 59 | + asyncio.run(main()) |
| 60 | +``` |
| 61 | + |
| 62 | +## Key Differences from Sync |
| 63 | + |
| 64 | +1. **Engine**: Use `create_async_engine` instead of `create_engine`. |
| 65 | +2. **Session**: Use `sqlmodel.ext.asyncio.session.AsyncSession` instead of `sqlmodel.Session`. |
| 66 | +3. **Execution**: Use `await session.exec(statement)` instead of `session.exec(statement)`. |
| 67 | +4. **Commit/Refresh**: Use `await session.commit()` and `await session.refresh(instance)`. |
| 68 | +5. **Table Creation**: Use `conn.run_sync(SQLModel.metadata.create_all)` because `create_all` is a synchronous method. |
0 commit comments