""" Database connection and session management using SQLAlchemy with async support. """ from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker from sqlalchemy.orm import declarative_base from app.config import settings # Create async engine engine = create_async_engine( settings.DATABASE_URL, echo=settings.DEBUG, pool_pre_ping=True, pool_size=10, max_overflow=20, ) # Create async session factory AsyncSessionLocal = async_sessionmaker( engine, class_=AsyncSession, expire_on_commit=False, autocommit=False, autoflush=False, ) # Base class for declarative models Base = declarative_base() async def get_db() -> AsyncSession: """ Dependency for FastAPI endpoints to get database session. Usage: @app.get("/users") async def get_users(db: AsyncSession = Depends(get_db)): ... """ async with AsyncSessionLocal() as session: try: yield session await session.commit() except Exception: await session.rollback() raise finally: await session.close() async def init_db(): """ Initialize database - create all tables. Should be called on application startup. """ async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) async def close_db(): """ Close database connections. Should be called on application shutdown. """ await engine.dispose()