# app/database.py from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession from sqlalchemy.orm import sessionmaker, declarative_base from app.config import settings # 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 pool_pre_ping=True # Add this line to ensure connections are live ) # 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_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. 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. """ async with AsyncSessionLocal() as session: try: await session.begin() yield session await session.commit() except Exception: await session.rollback() raise finally: await session.close() # Alias for backward compatibility get_db = get_session