Files
mtusi2026lab4/migrate.py
T
2026-11-12 14:37:43 +03:00

15 lines
762 B
Python

import os
from pathlib import Path
import psycopg
url=os.environ['DATABASE_URL']
with psycopg.connect(url) as conn:
with conn.transaction():
conn.execute('CREATE TABLE IF NOT EXISTS schema_migrations(version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())')
conn.execute('SELECT pg_advisory_xact_lock(18202602)')
for path in sorted(Path(__file__).parent.joinpath('migrations').glob('*.sql')):
if not conn.execute('SELECT 1 FROM schema_migrations WHERE version=%s',(path.name,)).fetchone():
conn.execute(path.read_text())
conn.execute('INSERT INTO schema_migrations(version) VALUES (%s)',(path.name,))
print('Applied',path.name)
print('Migrations complete')