forked from mtusi2026/mtusi2026lab4
45 lines
1.8 KiB
Python
45 lines
1.8 KiB
Python
"""PostgreSQL configuration and transactional, versioned migrations."""
|
|
import hashlib
|
|
import os
|
|
from pathlib import Path
|
|
import secrets
|
|
|
|
import psycopg
|
|
from psycopg.rows import dict_row
|
|
from psycopg_pool import ConnectionPool
|
|
|
|
|
|
def database_url():
|
|
filename = os.environ.get("DATABASE_URL_FILE")
|
|
return Path(filename).read_text().strip() if filename else os.environ["DATABASE_URL"]
|
|
|
|
|
|
def migrate():
|
|
with psycopg.connect(database_url(), connect_timeout=3) as conn:
|
|
conn.execute("SELECT pg_advisory_xact_lock(2026002)")
|
|
conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations "
|
|
"(version text PRIMARY KEY, checksum text NOT NULL)")
|
|
for path in sorted((Path(__file__).resolve().parents[1] / "migrations").glob("*.sql")):
|
|
sql = path.read_text(encoding="utf-8")
|
|
checksum = hashlib.sha256(sql.encode()).hexdigest()
|
|
old = conn.execute("SELECT checksum FROM schema_migrations WHERE version=%s", (path.name,)).fetchone()
|
|
if old:
|
|
if old[0] != checksum:
|
|
raise RuntimeError("Applied migration checksum changed")
|
|
continue
|
|
conn.execute(sql)
|
|
conn.execute("INSERT INTO schema_migrations VALUES (%s,%s)", (path.name, checksum))
|
|
conn.execute("INSERT INTO settings VALUES ('cursor_key',%s) ON CONFLICT DO NOTHING", (secrets.token_hex(32),))
|
|
|
|
|
|
def pool():
|
|
return ConnectionPool(database_url(), min_size=1, max_size=8, timeout=2,
|
|
max_waiting=32, open=True, check=ConnectionPool.check_connection,
|
|
kwargs={"connect_timeout": 3, "row_factory": dict_row,
|
|
"options": "-c timezone=UTC -c statement_timeout=3000 -c lock_timeout=2000"})
|
|
|
|
|
|
if __name__ == "__main__":
|
|
migrate()
|
|
print("PASS: migrations applied")
|