from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from sqlalchemy.orm import declarative_base, sessionmaker from backend.config import settings # Convert postgres:// to postgresql:// for SQLAlchemy DATABASE_URL = settings.DATABASE_URL.replace("postgresql://", "postgresql+asyncpg://") # Create async engine with statement_cache_size=0 for Supabase pgbouncer compatibility engine = create_async_engine( DATABASE_URL, echo=True, future=True, connect_args={ "statement_cache_size": 0, "prepared_statement_cache_size": 0, "server_settings": {"jit": "off"}, }, pool_pre_ping=True, pool_recycle=300, ) # Create async session factory async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) Base = declarative_base() async def get_db(): """Dependency for FastAPI routes to get database session""" async with async_session() as session: try: yield session await session.commit() except Exception: await session.rollback() raise finally: await session.close() async def init_db(): """Initialize database tables""" async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all)