Spaces:
Runtime error

File size: 1,465 Bytes
64fb1e7
 
 
 
 
 
 
 
 
 
57675a4
 
 
 
 
 
 
 
64fb1e7
 
57675a4
64fb1e7
 
 
d453a61
 
64fb1e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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