From 3c41caf109ce84c2d7321ba19945d9210fba427f Mon Sep 17 00:00:00 2001 From: Abhishek Khaparde Date: Tue, 12 May 2026 15:41:08 +0530 Subject: [PATCH] docs: add comprehensive guide for async database sessions --- docs/advanced/async.md | 91 ++++++++++++++++++++++++++++++++++++++++++ mkdocs.yml | 1 + 2 files changed, 92 insertions(+) create mode 100644 docs/advanced/async.md diff --git a/docs/advanced/async.md b/docs/advanced/async.md new file mode 100644 index 0000000000..8bd1379efb --- /dev/null +++ b/docs/advanced/async.md @@ -0,0 +1,91 @@ +# Async Database Sessions + +SQLModel supports asynchronous database sessions using SQLAlchemy's async features. This is particularly useful when building asynchronous applications with frameworks like **FastAPI**. + +## Create the Async Engine + +To use async sessions, you need to use an async database driver (like `aiosqlite` for SQLite or `asyncpg` for PostgreSQL) and create an async engine using `create_async_engine`. + +```python +from sqlalchemy.ext.asyncio import create_async_engine +from sqlmodel import SQLModel + +sqlite_url = "sqlite+aiosqlite:///database.db" + +engine = create_async_engine(sqlite_url, echo=True) + +async def init_db(): + async with engine.begin() as conn: + await conn.run_sync(SQLModel.metadata.create_all) +``` + +## Async Session + +Instead of the standard `Session`, you use `AsyncSession` from `sqlalchemy.ext.asyncio`. + +```python +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.orm import sessionmaker + +async_session_maker = sessionmaker( + engine, class_=AsyncSession, expire_on_commit=False +) + +async def get_async_session() -> AsyncSession: + async with async_session_maker() as session: + yield session +``` + +## Async CRUD Operations + +When using `AsyncSession`, you must `await` operations that communicate with the database. + +### Create + +```python +async def create_hero(session: AsyncSession): + hero = Hero(name="Deadpond", secret_name="Dive Wilson") + session.add(hero) + await session.commit() + await session.refresh(hero) + return hero +``` + +### Read + +For queries, use `session.exec()` (or `session.execute()`) and `await` the result. + +```python +from sqlmodel import select + +async def read_heroes(session: AsyncSession): + statement = select(Hero) + results = await session.exec(statement) + heroes = results.all() + return heroes +``` + +### Update and Delete + +Update and delete operations also require `awaiting` the commit. + +```python +async def update_hero(session: AsyncSession, hero_id: int, new_name: str): + hero = await session.get(Hero, hero_id) + if hero: + hero.name = new_name + session.add(hero) + await session.commit() + await session.refresh(hero) + return hero + +async def delete_hero(session: AsyncSession, hero_id: int): + hero = await session.get(Hero, hero_id) + if hero: + await session.delete(hero) + await session.commit() +``` + +--- + +Payment Address (SOL/RTC): `BVf9eNCQFSamVQ2VwkQZ9UvkUX37j7Syk75DvZtutJef` diff --git a/mkdocs.yml b/mkdocs.yml index b89516e024..4861ef4eb4 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -127,6 +127,7 @@ nav: - tutorial/fastapi/tests.md - Advanced User Guide: - advanced/index.md + - advanced/async.md - advanced/decimal.md - advanced/uuid.md - Resources: