Files
mtusi2026lab4/app/db.py
T
dawuduk d208a87ae8 Перенести рабочий стенд lab3 в репозиторий lab4.
API, Postgres, Redis и HAProxy остаются базой для вложений: сессии и история уже общие для нескольких реплик.
2026-11-09 00:04:59 +03:00

88 lines
2.6 KiB
Python

from pathlib import Path
import asyncpg
from app import config
from app.errors import AppError
pool: asyncpg.Pool | None = None
INTEGRITY = (
asyncpg.UniqueViolationError,
asyncpg.ForeignKeyViolationError,
asyncpg.CheckViolationError,
)
def _migrations_dir() -> Path:
here = Path(__file__).resolve().parent
for candidate in (here.parent / "migrations", Path("/app/migrations")):
if candidate.is_dir():
return candidate
raise RuntimeError("migrations directory not found")
async def connect() -> asyncpg.Pool:
global pool
if not config.DATABASE_URL:
raise RuntimeError("DATABASE_URL is not set")
pool = await asyncpg.create_pool(
dsn=config.DATABASE_URL,
min_size=config.DB_POOL_MIN,
max_size=config.DB_POOL_MAX,
command_timeout=config.DB_COMMAND_TIMEOUT,
timeout=config.DB_CONNECT_TIMEOUT,
)
return pool
async def close() -> None:
global pool
if pool is not None:
await pool.close()
pool = None
def require() -> asyncpg.Pool:
if pool is None:
raise AppError(503, "service unavailable")
return pool
async def ping() -> None:
try:
async with require().acquire() as conn:
await conn.execute("SELECT 1")
except AppError:
raise
except Exception:
raise AppError(503, "service unavailable") from None
_MIGRATION_LOCK = 87133103
async def apply_migrations() -> None:
"""Apply pending SQL files once. A session advisory lock stops replica races."""
directory = _migrations_dir()
async with require().acquire() as conn:
await conn.execute("SELECT pg_advisory_lock($1)", _MIGRATION_LOCK)
try:
await conn.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
filename TEXT PRIMARY KEY,
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
)
"""
)
applied = {row["filename"] for row in await conn.fetch("SELECT filename FROM schema_migrations")}
for path in sorted(p for p in directory.glob("*.sql") if p.is_file()):
if path.name in applied:
continue
sql = path.read_text(encoding="utf-8")
async with conn.transaction():
await conn.execute(sql)
await conn.execute("INSERT INTO schema_migrations(filename) VALUES($1)", path.name)
finally:
await conn.execute("SELECT pg_advisory_unlock($1)", _MIGRATION_LOCK)