- Add docker-compose.yml with PostgreSQL 16 container (port 5433) - Create async database session factory with connection pooling - Configure SQLAlchemy 2.0 DeclarativeBase for models - Update .env.example with correct database URL Connection pool settings from research: pool_size=10, max_overflow=20, pool_recycle=1800 (30 min), pool_pre_ping=True for validation.
45 lines
1.2 KiB
Python
45 lines
1.2 KiB
Python
"""Async database session management with connection pooling."""
|
|
|
|
from collections.abc import AsyncGenerator
|
|
|
|
from sqlalchemy.ext.asyncio import (
|
|
AsyncSession,
|
|
async_sessionmaker,
|
|
create_async_engine,
|
|
)
|
|
|
|
from backend.app.core.config import settings
|
|
|
|
# Create async engine with connection pooling settings from research
|
|
# See: 01-RESEARCH.md Pattern 1: Async Database Session Management
|
|
engine = create_async_engine(
|
|
settings.database_url,
|
|
pool_size=10,
|
|
max_overflow=20,
|
|
pool_timeout=30,
|
|
pool_recycle=1800, # 30 minutes - refresh connections
|
|
pool_pre_ping=True, # Validate connections before use
|
|
echo=False, # Set True for SQL logging in development
|
|
)
|
|
|
|
# Session factory for creating async sessions
|
|
async_session_maker = async_sessionmaker(
|
|
engine,
|
|
class_=AsyncSession,
|
|
expire_on_commit=False,
|
|
)
|
|
|
|
|
|
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
|
"""FastAPI dependency for database sessions.
|
|
|
|
Yields an async database session and ensures proper cleanup.
|
|
|
|
Usage:
|
|
@app.get("/items")
|
|
async def get_items(db: AsyncSession = Depends(get_db)):
|
|
# Use db session here
|
|
pass
|
|
"""
|
|
async with async_session_maker() as session:
|
|
yield session
|