Skip to content

Instantly share code, notes, and snippets.

@tooruu
Created February 15, 2026 04:20
Show Gist options
  • Select an option

  • Save tooruu/764155357d7c98137123863a3501b3a3 to your computer and use it in GitHub Desktop.

Select an option

Save tooruu/764155357d7c98137123863a3501b3a3 to your computer and use it in GitHub Desktop.
Async SQLModel SQLite primer
from sqlalchemy import event
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.orm import sessionmaker
from sqlmodel import Field, SQLModel
from sqlmodel.ext.asyncio.session import AsyncSession
class User(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
engine = create_async_engine("sqlite+aiosqlite:///database.sqlite")
SessionLocal = sessionmaker(engine, class_=AsyncSession, autoflush=False, expire_on_commit=False)
@event.listens_for(engine.sync_engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record):
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA journal_mode=WAL")
cursor.execute("PRAGMA synchronous=NORMAL")
cursor.execute("PRAGMA foreign_keys=ON")
cursor.close()
async def main():
async with engine.begin() as conn:
await conn.run_sync(SQLModel.metadata.create_all)
async with SessionLocal.begin() as session:
session.add(User(name="John"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment