Skip to main content

Modern async SQLAlchemy database context manager for FastAPI, Taskiq, Temporal, and more

Project description

sqladbx 🚀

Modern async SQLAlchemy database context manager for FastAPI, Litestar, Taskiq, Temporal, and more.

PyPI version Python 3.13+ Checked with mypy Ruff pre-commit License: MIT

💡 Inspired by fastapi-async-sqlalchemy - reimagined with modern async patterns, ContextVar-based session management, and extended framework support.

✨ Features

  • 🎯 Simple API - Clean, intuitive interface for database operations
  • Async-first - Built for async/await with SQLAlchemy 2.0+
  • 🔄 Auto Context Management - Automatic session lifecycle with middleware
  • 🌐 Framework Agnostic - Use with web frameworks, CLI scripts, background tasks, or any async Python code
  • 🎭 Multi-Session Support - Handle multiple concurrent sessions when needed
  • 🔒 Type Safe - Full type hints and mypy support
  • 🧪 Well Tested - Comprehensive test coverage

📦 Installation

pip install sqladbx

🚀 Quick Start

FastAPI Example

from fastapi import FastAPI
from sqlmodel import Field, SQLModel
from sqladbx import SQLAlchemyMiddleware, db

# Define your model
class User(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)
    name: str
    email: str

# Create FastAPI app
app = FastAPI()

# Add SQLAlchemy middleware
app.add_middleware(
    SQLAlchemyMiddleware,
    db_url="postgresql+asyncpg://user:password@localhost/dbname"
)

# Use db.session in your endpoints - no context manager needed!
@app.post("/users")
async def create_user(name: str, email: str):
    user = User(name=name, email=email)
    db.session.add(user)
    await db.session.commit()
    await db.session.refresh(user)
    return user

@app.get("/users")
async def list_users():
    result = await db.session.scalars(select(User))
    return result.all()

Without Middleware (Taskiq, Temporal, etc.)

from sqladbx import db

# Initialize once at startup
db.initialize(db_url="postgresql+asyncpg://user:pass@localhost/dbname")

# Use in your code
async def process_data():
    async with db(commit_on_exit=True):
        result = await db.session.scalars(select(User))
        users = result.all()
        # Process users...

# Cleanup on shutdown (optional but recommended)
await db.dispose()

Multi-Session Mode (Concurrent Queries)

import asyncio
from sqladbx import db

async def query1():
    result = await db.session.execute(select(User))
    return result.scalars().all()

async def query2():
    result = await db.session.execute(select(Post))
    return result.scalars().all()

# Run queries concurrently
async with db(multi_sessions=True):
    users, posts = await asyncio.gather(query1(), query2())

Multiple Databases

from sqladbx import create_middleware_and_db

# Create db instances and middlewares
MainMiddleware, main_db = create_middleware_and_db()
ReplicaMiddleware, replica_db = create_middleware_and_db()

# Add to app
app.add_middleware(MainMiddleware, db_url="postgresql://main")
app.add_middleware(ReplicaMiddleware, db_url="postgresql://replica")

@app.get("/users")
async def list_users():
    # Use main_db for writes
    result = await main_db.session.scalars(select(User))
    return result.all()

@app.get("/stats")
async def get_stats():
    # Use replica_db for reads
    result = await replica_db.session.scalars(select(Stats))
    return result.all()

More Examples

See the examples/ directory for complete working examples:

  • examples/fastapi_basic.py
  • examples/fastapi_multi_db.py
  • examples/litestar_basic.py
  • examples/litestar_multi_db.py
  • examples/taskiq_basic.py
  • examples/taskiq_multi_sessions.py

🎓 Best Practices

✅ DO

  • Use middleware for web applications (automatic session management)
  • Use manual context (async with db()) for CLI/background tasks
  • Enable commit_on_exit=True for simple CRUD operations
  • Use separate db proxies for master/replica setups
  • Implement proper error handling with try/except

❌ DON'T

  • Don't mix middleware and manual initialization
  • Don't create sessions manually - use db.session
  • Don't use blocking I/O inside database contexts
  • Don't share sessions between requests

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🔗 Links

💬 Support

If you have any questions or need help, please:

  • Open an issue on GitHub
  • Check existing issues and discussions
  • Read the documentation carefully

Made with ❤️ by Oleksii Svichkar

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sqladbx-0.0.4.tar.gz (9.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sqladbx-0.0.4-py3-none-any.whl (12.3 kB view details)

Uploaded Python 3

File details

Details for the file sqladbx-0.0.4.tar.gz.

File metadata

  • Download URL: sqladbx-0.0.4.tar.gz
  • Upload date:
  • Size: 9.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: Hatch/1.16.2 cpython/3.13.5 HTTPX/0.28.1

File hashes

Hashes for sqladbx-0.0.4.tar.gz
Algorithm Hash digest
SHA256 33c096dc61ccded7e5d5b3fb67ab96dae27636ebc4ea67b2f02b9af286c0db24
MD5 36d7fcba1a6e87580aad443c17d73a83
BLAKE2b-256 466a5a0d8d89341d22d002cccf42d406ea5b5e2a948a3c31e393eaca7d815bd9

See more details on using hashes here.

File details

Details for the file sqladbx-0.0.4-py3-none-any.whl.

File metadata

  • Download URL: sqladbx-0.0.4-py3-none-any.whl
  • Upload date:
  • Size: 12.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: Hatch/1.16.2 cpython/3.13.5 HTTPX/0.28.1

File hashes

Hashes for sqladbx-0.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 90b5892b6867c1e9fb30212424d3272a45aa9fbe9358fe0a424057831c30d64e
MD5 c0408c1914d8c781c0642f19cdcc3a66
BLAKE2b-256 f15fa648d512dc59f9b582703f272dbf6afd0f3379ede5367c4c639fd82c12ec

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page