""" Async SQLAlchemy engine and session factory for PostgreSQL. """ from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker from sqlalchemy.orm import DeclarativeBase from core.config import get_settings settings = get_settings() # Definitively fix cloud connectivity by building the URL from validated components from sqlalchemy.engine import URL url = URL.create( drivername="postgresql+asyncpg", username=settings.DB_USER, password=settings.DB_PASS, host=settings.DB_HOST, port=settings.DB_PORT, database=settings.DB_NAME, ) connect_args = { "ssl": "require", "prepared_statement_cache_size": 0 # CRITICAL for Supavisor Transaction mode } from sqlalchemy.pool import NullPool # Unified Cloud Connectivity: Use NullPool for Session-mode compatibility engine = create_async_engine( settings.async_database_url, echo=settings.DEBUG, future=True, poolclass=NullPool, # FORCE immediate release of connections connect_args=connect_args ) async_session_factory = async_sessionmaker( engine, class_=AsyncSession, expire_on_commit=False, ) class Base(DeclarativeBase): """Base class for all SQLAlchemy models.""" pass async def get_db(): """ Standardize database session management. Yields an async session and ensures proper rollback on exceptions. """ async with async_session_factory() as session: try: yield session # We DON'T auto-commit here anymore as it can cause issues # with partial updates in complex routes. Endpoints should call await db.commit(). except Exception: await session.rollback() raise finally: await session.close() import subprocess from core.logging import get_logger logger = get_logger(__name__) async def run_migrations(): """ Run Alembic migrations automatically on startup. This replaces the hacky init_db approach. """ try: logger.info("Running database migrations via Alembic...") # We run this as a subprocess to avoid event loop conflicts # since alembic's env.py often calls asyncio.run() subprocess.run( ["alembic", "upgrade", "head"], check=True ) logger.info("Database migrations completed successfully.") except Exception as e: logger.error(f"Unexpected error during migration: {e}") # In a real app, we might want to exit here to prevent running on old schema # For hackathon, we'll log it and continue. # raise e async def init_db(): """DEPRECATED: Use run_migrations instead for proper versioning.""" async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all)