from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession from sqlalchemy.orm import DeclarativeBase from sqlalchemy import text from config import settings class Base(DeclarativeBase): pass async_engine = create_async_engine( settings.DATABASE_URL, pool_size=20, max_overflow=40, pool_pre_ping=True, pool_recycle=3600, echo=False, ) AsyncSessionLocal = async_sessionmaker( async_engine, class_=AsyncSession, expire_on_commit=False, ) async def init_db(): async with async_engine.begin() as conn: from models import Base as MBase await conn.run_sync(MBase.metadata.create_all) await _run_migrations() async def _run_migrations(): async with async_engine.begin() as conn: await conn.execute(text( "ALTER TABLE flow_definitions ADD COLUMN IF NOT EXISTS published_version_id UUID REFERENCES flow_versions(id)" )) await conn.execute(text( "ALTER TABLE flow_definitions ADD COLUMN IF NOT EXISTS draft_definition_json JSONB" )) async def get_db(): async with AsyncSessionLocal() as session: try: yield session await session.commit() except Exception: await session.rollback() raise finally: await session.close()