Files
mtusi2026lab2/app/db.py
T
Artu-RitoandClaude Sonnet 5 d12159a8cc Лаба 2: PostgreSQL-хранилище и Redis-сессии (оценка 4)
FastAPI + asyncpg + Redis/argon2id. Пользователи/чаты/участники/сообщения
в Postgres с версионируемой миграцией и keyset-пагинацией. Basic-вход,
Bearer-сессии в Redis с TTL и AOF-персистентностью. make check/test/
test-persistence/validate зелёные; evidence по EXPLAIN ANALYZE, короткому
TTL и падению Redis приложены в REPORT.md.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-30 00:23:26 +03:00

70 lines
1.9 KiB
Python

"""PostgreSQL connection pool and versioned migration runner."""
import logging
from pathlib import Path
import asyncpg
logger = logging.getLogger("app.db")
MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations"
_pool: asyncpg.Pool | None = None
async def init_pool(dsn: str) -> asyncpg.Pool:
global _pool
_pool = await asyncpg.create_pool(
dsn,
min_size=2,
max_size=10,
command_timeout=5,
timeout=5,
)
await _run_migrations(_pool)
return _pool
async def close_pool() -> 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 initialized")
return _pool
async def _run_migrations(p: asyncpg.Pool) -> None:
async with p.acquire() as conn:
await conn.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT PRIMARY KEY,
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
)
"""
)
applied = {r["version"] for r in await conn.fetch("SELECT version FROM schema_migrations")}
for path in sorted(MIGRATIONS_DIR.glob("*.sql")):
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 (version) VALUES ($1)", path.name
)
logger.info("applied migration %s", path.name)
async def ping() -> bool:
try:
async with pool().acquire() as conn:
await conn.fetchval("SELECT 1")
return True
except Exception: # noqa: BLE001 - readiness probe, any failure means not ready
return False