Files
mtusi2026lab4/src/messenger/db.py
T

98 lines
3.6 KiB
Python

"""PostgreSQL connection pool and schema migrations."""
from __future__ import annotations
import os
from contextlib import contextmanager
from pathlib import Path
from psycopg2 import pool, OperationalError, InterfaceError
from psycopg2.extras import RealDictCursor
from .config import Config
from .errors import Unavailable
_ROOT = Path(__file__).resolve().parents[2]
_MIGRATIONS_DIR = _ROOT / 'migrations'
class Database:
"""Thread-safe connection pool with prepared statement timeouts.
All queries are parameterised (%s). Connections are returned to the pool
after every operation; the pool itself is closed on shutdown.
"""
def __init__(self, config: Config):
self._config = config
self._pool = None
def open(self):
if self._pool is not None:
return
try:
self._pool = pool.ThreadedConnectionPool(
minconn=self._config.pool_min,
maxconn=self._config.pool_max,
dsn=self._config.database_url,
connect_timeout=self._config.connect_timeout,
cursor_factory=RealDictCursor,
)
except Exception as exc: # psycopg2.Error or configuration error
raise Unavailable('Не удалось подключиться к PostgreSQL: %s' % exc) from None
def close(self):
if self._pool is not None:
self._pool.closeall()
self._pool = None
@contextmanager
def connection(self):
"""Yield a connection; rollback on exception, return to pool on exit."""
if self._pool is None:
raise Unavailable('База данных не инициализирована')
try:
conn = self._pool.getconn()
except (pool.PoolError, OperationalError, InterfaceError):
raise Unavailable('Пул соединений PostgreSQL недоступен') from None
try:
with conn.cursor() as cur:
cur.execute('SET statement_timeout = %s',
(self._config.statement_timeout * 1000,))
yield conn
except Exception as exc:
try:
conn.rollback()
except Exception:
pass
if isinstance(exc, (OperationalError, InterfaceError)):
raise Unavailable('PostgreSQL недоступен') from None
raise
finally:
self._pool.putconn(conn, close=bool(conn.closed))
@contextmanager
def cursor(self):
"""Yield a cursor inside a connection; commit on success, rollback on failure."""
with self.connection() as conn:
with conn.cursor() as cur:
yield cur
conn.commit()
def ping(self):
with self.cursor() as cur:
cur.execute('SELECT 1')
cur.fetchone()
def run_migrations(self):
"""Apply versioned migrations once, under a transaction advisory lock."""
with self.cursor() as cur:
cur.execute('SELECT pg_advisory_xact_lock(3072026)')
cur.execute('CREATE TABLE IF NOT EXISTS schema_migrations '
'(name text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())')
for path in sorted(_MIGRATIONS_DIR.glob('*.sql')):
cur.execute('SELECT 1 FROM schema_migrations WHERE name = %s', (path.name,))
if cur.fetchone() is not None:
continue
cur.execute(path.read_text(encoding='utf-8'))
cur.execute('INSERT INTO schema_migrations(name) VALUES (%s)', (path.name,))