Files
mtusi2026lab4/src/migrate.py
T

29 lines
1.4 KiB
Python

"""Versioned, transactional migrations, serialized across deployers."""
import hashlib
import os
from pathlib import Path
import psycopg
def main():
with psycopg.connect(os.environ['DATABASE_URL'],autocommit=True,connect_timeout=5) as conn:
conn.execute('SELECT pg_advisory_lock(23012026)')
try:
conn.execute('CREATE TABLE IF NOT EXISTS schema_migrations (name text PRIMARY KEY, sha256 text NOT NULL, applied_at timestamptz NOT NULL DEFAULT clock_timestamp())')
for file in sorted((Path(__file__).resolve().parents[1]/'migrations').glob('*.sql')):
data=file.read_bytes(); digest=hashlib.sha256(data).hexdigest()
row=conn.execute('SELECT sha256 FROM schema_migrations WHERE name=%s',(file.name,)).fetchone()
if row:
if row[0]!=digest: raise RuntimeError('An applied migration was modified: '+file.name)
print('Already applied:',file.name,flush=True)
continue
with conn.transaction():
conn.execute(data.decode('utf-8'))
conn.execute('INSERT INTO schema_migrations(name,sha256) VALUES (%s,%s)',(file.name,digest))
print('Applied:',file.name,flush=True)
finally:
conn.execute('SELECT pg_advisory_unlock(23012026)')
if __name__=='__main__': main()