Spaces:
Runtime error

wavvy / database.py
Charan S
fix: HF Cold Start Backend
57675a4
Raw History Blame Contribute Delete
1.47 kB
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
from sqlalchemy.orm import DeclarativeBase
from config import settings
class Base(DeclarativeBase):
pass
def _normalize_db_url(url: str) -> str:
if url.startswith("postgresql://"):
return url.replace("postgresql://", "postgresql+asyncpg://", 1)
if url.startswith("postgres://"):
return url.replace("postgres://", "postgresql+asyncpg://", 1)
return url
def _make_engine():
return create_async_engine(
_normalize_db_url(settings.database_url),
pool_size=20,
max_overflow=10,
pool_pre_ping=True,
# Required for Supabase/PgBouncer connection pooler compatibility
connect_args={"statement_cache_size": 0},
)
engine = _make_engine()
AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)
def reinit_engine() -> None:
"""Recreate the engine and session factory bound to the current event loop.
Must be called in worker subprocesses (LiveKit agent workers) before any
DB access, because the module-level engine is created in the parent process's
event loop and asyncpg connections are loop-bound.
"""
global engine, AsyncSessionLocal
engine = _make_engine()
AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)
async def get_db() -> AsyncSession:
async with AsyncSessionLocal() as session:
yield session