forked from mtusi2026/mtusi2026lab5
Принимать файл отдельно от обработки, чтобы задание переживало рестарт и повторную доставку.
This commit is contained in:
@@ -0,0 +1,99 @@
|
||||
"""PostgreSQL pool and migrations. The database is the source of truth."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
log = logging.getLogger("messenger.db")
|
||||
|
||||
_pool: ConnectionPool | None = None
|
||||
_MIGRATION = Path(__file__).resolve().parents[1] / "migrations" / "001_init.sql"
|
||||
_LOCK = 8152026
|
||||
|
||||
|
||||
def init_pool(database_url: str, min_size: int = 1, max_size: int = 8) -> ConnectionPool:
|
||||
global _pool
|
||||
if _pool is not None:
|
||||
return _pool
|
||||
deadline = time.monotonic() + 60
|
||||
last = None
|
||||
while True:
|
||||
try:
|
||||
pool = ConnectionPool(
|
||||
database_url,
|
||||
min_size=min_size,
|
||||
max_size=max_size,
|
||||
kwargs={"row_factory": dict_row, "autocommit": False},
|
||||
open=True,
|
||||
check=ConnectionPool.check_connection,
|
||||
)
|
||||
with pool.connection() as conn:
|
||||
conn.execute("SELECT 1")
|
||||
_pool = pool
|
||||
return pool
|
||||
except Exception as exc: # noqa: BLE001 - startup must wait for Postgres
|
||||
last = exc
|
||||
if time.monotonic() > deadline:
|
||||
raise RuntimeError("database did not become reachable") from last
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def pool() -> ConnectionPool:
|
||||
if _pool is None:
|
||||
raise RuntimeError("database pool is not initialized")
|
||||
return _pool
|
||||
|
||||
|
||||
@contextmanager
|
||||
def connection():
|
||||
with pool().connection() as conn:
|
||||
try:
|
||||
yield conn
|
||||
conn.commit()
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
raise
|
||||
|
||||
|
||||
def _statements(sql: str) -> list[str]:
|
||||
statements = []
|
||||
current: list[str] = []
|
||||
for line in sql.splitlines():
|
||||
stripped = line.strip()
|
||||
if stripped.startswith("--"):
|
||||
continue
|
||||
current.append(line)
|
||||
if stripped.endswith(";"):
|
||||
statement = "\n".join(current).strip()
|
||||
if statement:
|
||||
statements.append(statement)
|
||||
current = []
|
||||
trailing = "\n".join(current).strip()
|
||||
if trailing:
|
||||
statements.append(trailing)
|
||||
return statements
|
||||
|
||||
|
||||
def migrate(database_url: str) -> None:
|
||||
init_pool(database_url)
|
||||
statements = _statements(_MIGRATION.read_text(encoding="utf-8"))
|
||||
with connection() as conn:
|
||||
conn.execute("SELECT pg_advisory_xact_lock(%s)", (_LOCK,))
|
||||
for statement in statements:
|
||||
conn.execute(statement)
|
||||
log.info("schema ready")
|
||||
|
||||
|
||||
def ping() -> bool:
|
||||
try:
|
||||
with connection() as conn:
|
||||
conn.execute("SELECT 1")
|
||||
return True
|
||||
except Exception:
|
||||
log.warning("database ping failed", exc_info=True)
|
||||
return False
|
||||
Reference in New Issue
Block a user