forked from mtusi2026/mtusi2026lab2
54 lines
1.5 KiB
Python
54 lines
1.5 KiB
Python
|
|
import os
|
|
from pathlib import Path
|
|
|
|
import psycopg
|
|
|
|
|
|
DATABASE_URL = os.environ["DATABASE_URL"]
|
|
MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations"
|
|
|
|
|
|
def run_migrations():
|
|
with psycopg.connect(DATABASE_URL) as conn:
|
|
with conn.cursor() as cur:
|
|
# Prevent simultaneous migration runs.
|
|
cur.execute("SELECT pg_advisory_xact_lock(2026002)")
|
|
|
|
cur.execute("""
|
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
version TEXT PRIMARY KEY,
|
|
applied_at TIMESTAMPTZ NOT NULL
|
|
DEFAULT clock_timestamp()
|
|
)
|
|
""")
|
|
|
|
for file in sorted(MIGRATIONS_DIR.glob("*.sql")):
|
|
cur.execute(
|
|
"SELECT 1 FROM schema_migrations WHERE version = %s",
|
|
(file.name,)
|
|
)
|
|
|
|
if cur.fetchone():
|
|
print(f"Already applied: {file.name}")
|
|
continue
|
|
|
|
sql = file.read_text(encoding="utf-8")
|
|
|
|
for statement in sql.split(";"):
|
|
if statement.strip():
|
|
cur.execute(statement)
|
|
|
|
cur.execute(
|
|
"INSERT INTO schema_migrations (version) VALUES (%s)",
|
|
(file.name,)
|
|
)
|
|
|
|
print(f"Applied migration: {file.name}")
|
|
|
|
print("Migrations completed")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
run_migrations()
|