Can I use asyncpg + sqlmodel in Python? If so, show me examples. Is that faster than…
- User
Can I use asyncpg + sqlmodel in Python? If so, show me examples. Is that faster than psycopg3?
Assistant
Can I use asyncpg + sqlmodel in Python? If so, show me examples. Is that faster than psycopg3?
Yes, you can use asyncpg with SQLModel in Python, but it requires some extra setup since SQLModel is primarily designed to work with SQLAlchemy's async support (which typically uses asyncpg under the hood via sqlalchemy.ext.asyncio). However, you can use asyncpg directly for raw SQL queries while still leveraging SQLModel for ORM operations.
SQLModel works with SQLAlchemy's async engine, which can use asyncpg as the underlying driver.
from sqlmodel import SQLModel, Field, create_engine
from sqlmodel.ext.asyncio.session import AsyncSession
from sqlalchemy.ext.asyncio import create_async_engine
import asyncio
class Hero(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
secret_name: str
age: int | None = None
async def main():
# Use asyncpg via SQLAlchemy's async engine
DATABASE_URL = "postgresql+asyncpg://user:password@localhost/dbname"
engine = create_async_engine(DATABASE_URL, echo=True)
async with engine.begin() as conn:
await conn.run_sync(SQLModel.metadata.create_all)
# Insert and query data
async with AsyncSession(engine) as session:
hero = Hero(name="Deadpond", secret_name="Dive Wilson")
session.add(hero)
await session.commit()
result = await session.execute(select(Hero))
heroes = result.scalars().all()
print(heroes)
asyncio.run(main())
If you need raw speed, you can use asyncpg directly for queries while still using SQLModel for schema definitions.
import asyncpg
import asyncio
from sqlmodel import SQLModel, Field
class Hero(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
secret_name: str
age: int | None = None
async def main():
conn = await asyncpg.connect("postgresql://user:password@localhost/dbname")
# Create table (using raw SQL)
await conn.execute("""
CREATE TABLE IF NOT EXISTS hero (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
secret_name TEXT NOT NULL,
age INTEGER
)
""")
# Insert data
await conn.execute(
"INSERT INTO hero (name, secret_name, age) VALUES ($1, $2, $3)",
"Deadpond", "Dive Wilson", 30
)
# Query data
rows = await conn.fetch("SELECT * FROM hero")
for row in rows:
print(row)
await conn.close()
asyncio.run(main())
asyncpg is faster than psycopg3 for asynchronous workloads because:
psycopg3 is more versatile (sync + async) and better integrated with SQLAlchemy/SQLModel out of the box.| Operation | asyncpg | psycopg3 (async) |
|---|---|---|
| Simple query | ~10k QPS | ~7k QPS |
| Bulk insert | ~20k rows/sec | ~15k rows/sec |
asyncpg directly if you need raw speed and are comfortable with SQL.Would you like a more detailed benchmark or a hybrid approach (mixing ORM + raw asyncpg)?