46 lines
1.3 KiB
Python
46 lines
1.3 KiB
Python
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
|
from sqlalchemy.orm import sessionmaker, declarative_base
|
|
from app.config import settings
|
|
|
|
if not settings.DATABASE_URL:
|
|
raise ValueError("DATABASE_URL is not configured in settings.")
|
|
|
|
engine = create_async_engine(
|
|
settings.DATABASE_URL,
|
|
echo=False,
|
|
future=True,
|
|
pool_recycle=3600,
|
|
pool_pre_ping=True
|
|
)
|
|
|
|
AsyncSessionLocal = sessionmaker(
|
|
bind=engine,
|
|
class_=AsyncSession,
|
|
expire_on_commit=False,
|
|
autoflush=False,
|
|
autocommit=False,
|
|
)
|
|
|
|
Base = declarative_base()
|
|
|
|
async def get_session() -> AsyncSession: # type: ignore
|
|
"""
|
|
Dependency function that yields an AsyncSession for read-only operations.
|
|
Ensures the session is closed after the request.
|
|
"""
|
|
async with AsyncSessionLocal() as session:
|
|
yield session
|
|
|
|
async def get_transactional_session() -> AsyncSession: # type: ignore
|
|
"""
|
|
Dependency function that yields an AsyncSession and manages a transaction.
|
|
Commits the transaction if the request handler succeeds, otherwise rollbacks.
|
|
Ensures the session is closed after the request.
|
|
|
|
This follows the FastAPI-DB strategy for endpoint-level transaction management.
|
|
"""
|
|
async with AsyncSessionLocal() as session:
|
|
async with session.begin():
|
|
yield session
|
|
|
|
get_db = get_session |