forked from mtusi2026/mtusi2026lab2
30 lines
1002 B
Python
30 lines
1002 B
Python
"""PostgreSQL is the source of truth, including bearer sessions."""
|
|
import os
|
|
from contextlib import contextmanager
|
|
from pathlib import Path
|
|
import psycopg
|
|
from psycopg.rows import dict_row
|
|
|
|
|
|
def database_url():
|
|
secret_file = os.getenv("DATABASE_URL_FILE")
|
|
if secret_file:
|
|
return Path(secret_file).read_text().strip()
|
|
return os.environ["DATABASE_URL"]
|
|
|
|
|
|
@contextmanager
|
|
def db():
|
|
with psycopg.connect(database_url(), row_factory=dict_row, connect_timeout=5) as conn:
|
|
yield conn
|
|
|
|
|
|
def migrate():
|
|
with db() as conn:
|
|
conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations (version TEXT PRIMARY KEY)")
|
|
for file in sorted((Path(__file__).parent.parent / "migrations").glob("*.sql")):
|
|
if conn.execute("SELECT 1 FROM schema_migrations WHERE version=%s", (file.name,)).fetchone():
|
|
continue
|
|
conn.execute(file.read_text())
|
|
conn.execute("INSERT INTO schema_migrations(version) VALUES (%s)", (file.name,))
|