feat: добавить каркас приложения с PostgreSQL, сессиями и Redis-кэшем
This commit is contained in:
committed by
Evgeny Bushkov (aider)
parent
0ab3a341aa
commit
d8ba046033
@@ -0,0 +1,53 @@
|
||||
"""Пул соединений PostgreSQL и применение миграций."""
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
logger = logging.getLogger("messenger.db")
|
||||
|
||||
MIGRATIONS_DIR = Path(__file__).resolve().parents[1] / "migrations"
|
||||
|
||||
|
||||
def make_pool() -> ConnectionPool:
|
||||
dsn = os.environ.get("DATABASE_URL")
|
||||
if not dsn:
|
||||
raise RuntimeError("DATABASE_URL is not set")
|
||||
pool = ConnectionPool(
|
||||
conninfo=dsn,
|
||||
min_size=int(os.environ.get("DB_POOL_MIN", "1")),
|
||||
max_size=int(os.environ.get("DB_POOL_MAX", "10")),
|
||||
timeout=float(os.environ.get("DB_CONNECT_TIMEOUT", "3")),
|
||||
kwargs={"autocommit": False},
|
||||
open=False,
|
||||
)
|
||||
pool.open(wait=True, timeout=float(os.environ.get("DB_CONNECT_TIMEOUT", "3")))
|
||||
return pool
|
||||
|
||||
|
||||
def apply_migrations(pool: ConnectionPool) -> None:
|
||||
"""Идемпотентно применяет *.sql из migrations/ в лексикографическом порядке."""
|
||||
with pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"CREATE TABLE IF NOT EXISTS schema_migrations ("
|
||||
" version TEXT PRIMARY KEY,"
|
||||
" applied_at TIMESTAMPTZ NOT NULL DEFAULT now())"
|
||||
)
|
||||
conn.commit()
|
||||
cur.execute("SELECT version FROM schema_migrations")
|
||||
applied = {row[0] for row in cur.fetchall()}
|
||||
for path in sorted(MIGRATIONS_DIR.glob("*.sql")):
|
||||
version = path.stem
|
||||
if version in applied:
|
||||
continue
|
||||
logger.info("applying migration %s", version)
|
||||
sql = path.read_text(encoding="utf-8")
|
||||
with conn.transaction():
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(sql)
|
||||
cur.execute(
|
||||
"INSERT INTO schema_migrations(version) VALUES (%s)", (version,)
|
||||
)
|
||||
Reference in New Issue
Block a user