Files
mtusi2026lab2/src/messenger/db.py
T
2026-10-30 12:37:18 +03:00

108 lines
2.9 KiB
Python

"""PostgreSQL connection pool and versioned migrations."""
from __future__ import annotations
import logging
import re
from pathlib import Path
from typing import List, Optional
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
from messenger import config
log = logging.getLogger("messenger.db")
_pool: Optional[ConnectionPool] = None
def get_pool() -> ConnectionPool:
if _pool is None:
raise RuntimeError("Database pool is not initialized")
return _pool
def init_pool() -> ConnectionPool:
global _pool
if _pool is not None:
return _pool
url = config.database_url()
_pool = ConnectionPool(
conninfo=url,
min_size=1,
max_size=10,
kwargs={
"row_factory": dict_row,
"connect_timeout": 5,
"options": "-c statement_timeout=5000",
},
open=True,
timeout=10,
)
return _pool
def close_pool() -> None:
global _pool
if _pool is not None:
_pool.close()
_pool = None
def _split_sql(script: str) -> List[str]:
"""Split SQL file into statements (no procedure bodies in our migrations)."""
# Drop line comments.
cleaned = re.sub(r"--[^\n]*", "", script)
parts = []
for chunk in cleaned.split(";"):
stmt = chunk.strip()
if stmt:
parts.append(stmt)
return parts
def apply_migrations(migrations_path: Optional[Path] = None) -> None:
path = migrations_path or config.migrations_dir()
sql_files = sorted(path.glob("*.sql"))
if not sql_files:
raise RuntimeError(f"No migrations found in {path}")
pool = get_pool()
with pool.connection() as conn:
with conn.transaction():
conn.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT PRIMARY KEY,
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
)
"""
)
for sql_file in sql_files:
version = sql_file.name
row = conn.execute(
"SELECT 1 AS ok FROM schema_migrations WHERE version = %s",
(version,),
).fetchone()
if row:
log.info("migration already applied: %s", version)
continue
script = sql_file.read_text(encoding="utf-8")
for stmt in _split_sql(script):
conn.execute(stmt)
conn.execute(
"INSERT INTO schema_migrations (version) VALUES (%s)",
(version,),
)
log.info("applied migration: %s", version)
def ping() -> bool:
try:
with get_pool().connection() as conn:
conn.execute("SELECT 1")
return True
except Exception as exc:
log.warning("postgres ping failed: %s", type(exc).__name__)
return False