forked from mtusi2026/mtusi2026lab2
80 lines
2.2 KiB
Python
80 lines
2.2 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
|
|
|
|
|
|
async def apply_migrations() -> None:
|
|
directory = _migrations_dir()
|
|
async with require().acquire() as conn:
|
|
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)
|