36 lines
939 B
Python
36 lines
939 B
Python
from typing import cast
|
|
|
|
from psycopg_pool import AsyncConnectionPool
|
|
|
|
from app.config import get_settings
|
|
|
|
_pool: AsyncConnectionPool | None = None
|
|
|
|
|
|
async def get_pool() -> AsyncConnectionPool:
|
|
global _pool # noqa: PLW0603 — lazy singleton, by design
|
|
if _pool is None:
|
|
settings = get_settings()
|
|
_pool = AsyncConnectionPool(
|
|
conninfo=settings.database_url,
|
|
min_size=1,
|
|
max_size=10,
|
|
open=False,
|
|
)
|
|
await _pool.open()
|
|
return _pool
|
|
|
|
|
|
async def close_pool() -> None:
|
|
global _pool # noqa: PLW0603 — lazy singleton, by design
|
|
if _pool is not None:
|
|
await _pool.close()
|
|
_pool = None
|
|
|
|
|
|
async def check_db() -> bool:
|
|
pool = await get_pool()
|
|
async with pool.connection() as conn, conn.cursor() as cur:
|
|
await cur.execute("SELECT 1")
|
|
row = await cur.fetchone()
|
|
return cast(tuple[int], row)[0] == 1
|