23 lines
802 B
Python
23 lines
802 B
Python
"""Database utilities for async SQLAlchemy engine and sessions."""
|
|
from __future__ import annotations
|
|
|
|
from collections.abc import AsyncGenerator
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
|
|
|
from app.core.config import settings
|
|
|
|
engine = create_async_engine(settings.database_url, echo=settings.sqlalchemy_echo)
|
|
AsyncSessionMaker = async_sessionmaker(bind=engine, expire_on_commit=False)
|
|
|
|
|
|
async def get_session() -> AsyncGenerator[AsyncSession, None]:
|
|
"""Yield an async database session for request scope."""
|
|
async with AsyncSessionMaker() as session:
|
|
try:
|
|
yield session
|
|
await session.commit()
|
|
except Exception: # pragma: no cover - defensive cleanup
|
|
await session.rollback()
|
|
raise
|