"""Async SQLModel database configuration for Supabase/PostgreSQL.""" import ssl from typing import AsyncGenerator from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, create_async_engine from sqlalchemy.orm import sessionmaker from sqlmodel import SQLModel from ..core.config.config import settings # Supabase requires SSL but we need to handle certificate verification # For Supabase connection pooler, use a more permissive SSL context ssl_context = ssl.create_default_context() ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE engine: AsyncEngine = create_async_engine( settings.DATABASE_URL, echo=settings.DEBUG, # Disable prepared statement cache for pgbouncer transaction/statement mode connect_args={"ssl": ssl_context, "statement_cache_size": 0}, ) AsyncSessionLocal = sessionmaker( bind=engine, class_=AsyncSession, expire_on_commit=False, ) async def get_session() -> AsyncGenerator[AsyncSession, None]: """FastAPI dependency to provide an async database session.""" async with AsyncSessionLocal() as session: yield session async def init_db() -> None: """Create tables if they do not exist.""" async with engine.begin() as conn: await conn.run_sync(SQLModel.metadata.create_all) async def dispose_engine() -> None: """Dispose the async engine (called on shutdown).""" await engine.dispose()