Skip to content

Commit 3c41caf

Browse files
committed
docs: add comprehensive guide for async database sessions
1 parent 816f290 commit 3c41caf

2 files changed

Lines changed: 92 additions & 0 deletions

File tree

docs/advanced/async.md

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
# Async Database Sessions
2+
3+
SQLModel supports asynchronous database sessions using SQLAlchemy's async features. This is particularly useful when building asynchronous applications with frameworks like **FastAPI**.
4+
5+
## Create the Async Engine
6+
7+
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`.
8+
9+
```python
10+
from sqlalchemy.ext.asyncio import create_async_engine
11+
from sqlmodel import SQLModel
12+
13+
sqlite_url = "sqlite+aiosqlite:///database.db"
14+
15+
engine = create_async_engine(sqlite_url, echo=True)
16+
17+
async def init_db():
18+
async with engine.begin() as conn:
19+
await conn.run_sync(SQLModel.metadata.create_all)
20+
```
21+
22+
## Async Session
23+
24+
Instead of the standard `Session`, you use `AsyncSession` from `sqlalchemy.ext.asyncio`.
25+
26+
```python
27+
from sqlalchemy.ext.asyncio import AsyncSession
28+
from sqlalchemy.orm import sessionmaker
29+
30+
async_session_maker = sessionmaker(
31+
engine, class_=AsyncSession, expire_on_commit=False
32+
)
33+
34+
async def get_async_session() -> AsyncSession:
35+
async with async_session_maker() as session:
36+
yield session
37+
```
38+
39+
## Async CRUD Operations
40+
41+
When using `AsyncSession`, you must `await` operations that communicate with the database.
42+
43+
### Create
44+
45+
```python
46+
async def create_hero(session: AsyncSession):
47+
hero = Hero(name="Deadpond", secret_name="Dive Wilson")
48+
session.add(hero)
49+
await session.commit()
50+
await session.refresh(hero)
51+
return hero
52+
```
53+
54+
### Read
55+
56+
For queries, use `session.exec()` (or `session.execute()`) and `await` the result.
57+
58+
```python
59+
from sqlmodel import select
60+
61+
async def read_heroes(session: AsyncSession):
62+
statement = select(Hero)
63+
results = await session.exec(statement)
64+
heroes = results.all()
65+
return heroes
66+
```
67+
68+
### Update and Delete
69+
70+
Update and delete operations also require `awaiting` the commit.
71+
72+
```python
73+
async def update_hero(session: AsyncSession, hero_id: int, new_name: str):
74+
hero = await session.get(Hero, hero_id)
75+
if hero:
76+
hero.name = new_name
77+
session.add(hero)
78+
await session.commit()
79+
await session.refresh(hero)
80+
return hero
81+
82+
async def delete_hero(session: AsyncSession, hero_id: int):
83+
hero = await session.get(Hero, hero_id)
84+
if hero:
85+
await session.delete(hero)
86+
await session.commit()
87+
```
88+
89+
---
90+
91+
Payment Address (SOL/RTC): `BVf9eNCQFSamVQ2VwkQZ9UvkUX37j7Syk75DvZtutJef`

mkdocs.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,7 @@ nav:
127127
- tutorial/fastapi/tests.md
128128
- Advanced User Guide:
129129
- advanced/index.md
130+
- advanced/async.md
130131
- advanced/decimal.md
131132
- advanced/uuid.md
132133
- Resources:

0 commit comments

Comments
 (0)