forked from mtusi2026/mtusi2026lab4
62 lines
1.6 KiB
Python
62 lines
1.6 KiB
Python
"""PostgreSQL pool, JSON codec, and idempotent schema migration."""
|
|
|
|
import json
|
|
from pathlib import Path
|
|
|
|
import asyncpg
|
|
|
|
from app.config import Settings
|
|
|
|
_pool: asyncpg.Pool | None = None
|
|
_MIGRATION = Path(__file__).resolve().parents[1] / "infra" / "migrate.sql"
|
|
|
|
|
|
async def _init_connection(conn: asyncpg.Connection) -> None:
|
|
await conn.execute("SET TIME ZONE 'UTC'")
|
|
await conn.execute("SET statement_timeout = '30s'")
|
|
await conn.set_type_codec(
|
|
"jsonb",
|
|
encoder=json.dumps,
|
|
decoder=json.loads,
|
|
schema="pg_catalog",
|
|
format="text",
|
|
)
|
|
|
|
|
|
async def connect(settings: Settings) -> asyncpg.Pool:
|
|
global _pool
|
|
if _pool is None:
|
|
_pool = await asyncpg.create_pool(
|
|
settings.database_url,
|
|
min_size=1,
|
|
max_size=12,
|
|
timeout=10,
|
|
command_timeout=30,
|
|
init=_init_connection,
|
|
)
|
|
return _pool
|
|
|
|
|
|
async def migrate(settings: Settings) -> None:
|
|
pool = await connect(settings)
|
|
sql = _MIGRATION.read_text(encoding="utf-8")
|
|
statements = [part.strip() for part in sql.split(";") if part.strip()]
|
|
async with pool.acquire() as conn:
|
|
async with conn.transaction():
|
|
await conn.execute("SELECT pg_advisory_xact_lock(874521)")
|
|
for statement in statements:
|
|
await conn.execute(statement)
|
|
|
|
|
|
async def close() -> None:
|
|
global _pool
|
|
if _pool is not None:
|
|
await _pool.close()
|
|
_pool = None
|
|
|
|
|
|
def pool() -> asyncpg.Pool:
|
|
if _pool is None:
|
|
raise RuntimeError("database pool is not connected")
|
|
return _pool
|