CoolFace
Apppublic

ashnaali22/phase-3-h2

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
async_session.py62 linesDownload Raw Back to database
1"""2Async database session for Phase 3 chat endpoint.3 4This module provides AsyncSession for non-blocking database operations5required by ConversationService and chat endpoint.6 7IMPORTANT: Phase 2 sync sessions remain unchanged - this is ADDITIVE.8"""9 10from typing import AsyncIterator11from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession as AsyncSessionType12from sqlalchemy.orm import sessionmaker13import os14from dotenv import load_dotenv15 16load_dotenv()17DATABASE_URL = os.getenv("DATABASE_URL")18 19# Get database URL from environment20if not DATABASE_URL:21    raise ValueError("DATABASE_URL environment variable is required")22 23# Convert sync URL to async: postgresql:// → postgresql+asyncpg://24# Phase 2 uses: postgresql://user:pass@host/db25# Phase 3 needs: postgresql+asyncpg://user:pass@host/db26async_database_url = DATABASE_URL.replace("postgresql://", "postgresql+asyncpg://")27 28# Create async engine (Neon serverless setup)29async_engine = create_async_engine(30    async_database_url,31    echo=False,32    pool_size=5,33    max_overflow=10,34    pool_pre_ping=True,35    connect_args={"timeout": 30}36)37 38# Create async session factory (exported as async_session_maker for ChatKit compatibility)39async_session_maker = sessionmaker(40    async_engine,41    class_=AsyncSessionType,42    expire_on_commit=False,43)44 45 46async def get_async_session() -> AsyncIterator[AsyncSessionType]:47    """48    FastAPI dependency for async database sessions.49 50    Use this ONLY for Phase 3 chat endpoints.51    Phase 2 REST endpoints continue using get_db().52 53    Example:54        @router.post("/{user_id}/chat")55        async def chat_endpoint(56            session: AsyncSession = Depends(get_async_session)57        ):58            conversation = await get_or_create_conversation(session, ...)59    """60    async with async_session_maker() as session:61        yield session62