34 lines
988 B
Python
34 lines
988 B
Python
"""Database session management."""
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
|
|
from sqlalchemy.orm import sessionmaker
|
|
|
|
from app.core.config import settings
|
|
|
|
# Convert sync DATABASE_URL to async (replace postgresql:// with postgresql+asyncpg://)
|
|
async_database_url = str(settings.DATABASE_URL).replace("postgresql://", "postgresql+asyncpg://")
|
|
|
|
# Create async SQLAlchemy engine
|
|
engine = create_async_engine(
|
|
async_database_url,
|
|
pool_size=settings.DATABASE_POOL_SIZE,
|
|
max_overflow=settings.DATABASE_MAX_OVERFLOW,
|
|
pool_pre_ping=True, # Verify connections before using
|
|
echo=settings.DEBUG, # Log SQL queries in debug mode
|
|
)
|
|
|
|
# Create async session factory
|
|
SessionLocal = sessionmaker(
|
|
bind=engine,
|
|
class_=AsyncSession,
|
|
autocommit=False,
|
|
autoflush=False,
|
|
expire_on_commit=False,
|
|
)
|
|
|
|
|
|
async def get_db():
|
|
"""Dependency for getting async database session."""
|
|
async with SessionLocal() as session:
|
|
yield session
|