66 lines
2.6 KiB
Python
66 lines
2.6 KiB
Python
# app/database.py
|
|
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
|
from sqlalchemy.orm import sessionmaker, declarative_base
|
|
from app.config import settings
|
|
import logging
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# Ensure DATABASE_URL is set before proceeding
|
|
if not settings.DATABASE_URL:
|
|
raise ValueError("DATABASE_URL is not configured in settings.")
|
|
|
|
# Create the SQLAlchemy async engine
|
|
# pool_recycle=3600 helps prevent stale connections on some DBs
|
|
engine = create_async_engine(
|
|
settings.DATABASE_URL,
|
|
echo=True, # Log SQL queries (useful for debugging)
|
|
future=True, # Use SQLAlchemy 2.0 style features
|
|
pool_recycle=3600 # Optional: recycle connections after 1 hour
|
|
)
|
|
|
|
# Create a configured "Session" class
|
|
# expire_on_commit=False prevents attributes from expiring after commit
|
|
AsyncSessionLocal = sessionmaker(
|
|
bind=engine,
|
|
class_=AsyncSession,
|
|
expire_on_commit=False,
|
|
autoflush=False,
|
|
autocommit=False,
|
|
)
|
|
|
|
# Base class for our ORM models
|
|
Base = declarative_base()
|
|
|
|
# Dependency to get DB session in path operations
|
|
async def get_async_session() -> AsyncSession: # type: ignore
|
|
"""
|
|
Dependency function that yields an AsyncSession.
|
|
Ensures the session is closed after the request.
|
|
"""
|
|
async with AsyncSessionLocal() as session:
|
|
yield session
|
|
# The 'async with' block handles session.close() automatically.
|
|
# Commit/rollback should be handled by the functions using the session.
|
|
|
|
# Alias for backward compatibility
|
|
get_db = get_async_session
|
|
|
|
async def get_transactional_session() -> AsyncSession: # type: ignore
|
|
"""
|
|
Dependency function that yields an AsyncSession wrapped in a transaction.
|
|
Commits on successful completion of the request handler, rolls back on exceptions.
|
|
"""
|
|
async with AsyncSessionLocal() as session:
|
|
async with session.begin(): # Start a transaction
|
|
try:
|
|
logger.debug(f"Transaction started for session {id(session)}")
|
|
yield session
|
|
# If no exceptions were raised by the endpoint, the 'session.begin()'
|
|
# context manager will automatically commit here.
|
|
logger.debug(f"Transaction committed for session {id(session)}")
|
|
except Exception as e:
|
|
# The 'session.begin()' context manager will automatically
|
|
# rollback on any exception.
|
|
logger.error(f"Transaction rolled back for session {id(session)} due to: {e}", exc_info=True)
|
|
raise # Re-raise the exception to be handled by FastAPI's error handlers |