Download database.py from brocode12/wavvy: direct link, hf CLI and curl.
- Browser
- Download file 1.47 kB
-
https://huggingface.co/spaces/brocode12/wavvy/resolve/main/database.py
- Command line
-
hf download hf://spaces/brocode12/wavvy/database.py
-
curl -L -o database.py https://huggingface.co/spaces/brocode12/wavvy/resolve/main/database.py
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 | |