30 lines
898 B
Python
30 lines
898 B
Python
from collections.abc import AsyncGenerator
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
|
|
|
from app.config import settings
|
|
|
|
engine = create_async_engine(
|
|
settings.DATABASE_URL,
|
|
echo=settings.DEBUG_SQL,
|
|
pool_pre_ping=True,
|
|
)
|
|
|
|
AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)
|
|
|
|
|
|
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
|
"""FastAPI dependency: yields a session, committing on success.
|
|
|
|
Services that need multi-statement atomicity use ``async with db.begin()``
|
|
blocks (those commit/rollback explicitly); a plain commit here persists
|
|
the single-statement writes of the CRUD routers.
|
|
"""
|
|
async with AsyncSessionLocal() as session:
|
|
try:
|
|
yield session
|
|
await session.commit()
|
|
except Exception:
|
|
await session.rollback()
|
|
raise
|