35 lines
947 B
Python
35 lines
947 B
Python
"""Engine, session factory and the `get_db` request dependency.
|
|
|
|
One transaction per request: the dependency opens a session, the service layer
|
|
commits on success, and any escaping exception rolls the whole request back — so a
|
|
state change and its audit row can never be persisted separately.
|
|
"""
|
|
|
|
from collections.abc import AsyncGenerator
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
|
|
|
from app.config.settings import settings
|
|
|
|
engine = create_async_engine(
|
|
settings.DATABASE_URL,
|
|
echo=settings.DB_ECHO,
|
|
pool_pre_ping=True,
|
|
)
|
|
|
|
AsyncSessionLocal = async_sessionmaker(
|
|
bind=engine,
|
|
class_=AsyncSession,
|
|
expire_on_commit=False,
|
|
autoflush=False,
|
|
)
|
|
|
|
|
|
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
|
async with AsyncSessionLocal() as session:
|
|
try:
|
|
yield session
|
|
except Exception:
|
|
await session.rollback()
|
|
raise
|