""" 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() import sys import os from sqlalchemy.pool import NullPool # Definitive Process Identification: # We inspect both environment variables and the actual command line arguments # to ensure we never misidentify a Worker as an API (or vice versa). def is_worker_process() -> bool: if os.environ.get("NEXUS_MODE") == "worker": return True # If arq or nexus_worker is in the command line, we are 100% a background worker for arg in sys.argv: if "arq" in arg.lower() or "nexus_worker" in arg.lower(): return True return False # Global state for lazy engine initialization _engine = None _session_factory = None def get_engine(): """Lazily initialize the SQLAlchemy engine with the correct pooling strategy.""" global _engine if _engine is None: is_worker = is_worker_process() # UNIVERSAL FIX: Every process now uses NullPool (Zero-Footprint). # We rely 100% on the server-side PgBouncer for pooling. # This prevents SQLAlchemy from keeping 'warm' local connections that # lead to prepared statement conflicts in transaction-mode proxies. _engine = create_async_engine( settings.async_database_url, echo=settings.DEBUG, future=True, poolclass=NullPool, pool_pre_ping=True, connect_args={ "sslmode": "require", # Psycopg uses sslmode "prepare_threshold": None, # Disable prepared statements for Transaction Mode safety } ) return _engine def get_session_factory(): """Lazily initialize the session maker.""" global _session_factory if _session_factory is None: _session_factory = async_sessionmaker( get_engine(), class_=AsyncSession, expire_on_commit=False, ) return _session_factory # Proxy objects for backward compatibility with existing imports class EngineProxy: def __getattr__(self, name): return getattr(get_engine(), name) def __await__(self): return get_engine().__await__() class SessionFactoryProxy: def __call__(self, **kwargs): return get_session_factory()(**kwargs) def __getattr__(self, name): return getattr(get_session_factory(), name) engine = EngineProxy() async_session_factory = SessionFactoryProxy() 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)