forked from mtusi2026/mtusi2026lab2
30 lines
1.3 KiB
Python
30 lines
1.3 KiB
Python
"""Versioned transactional SQL migration runner, safe to rerun."""
|
|
import os
|
|
from pathlib import Path
|
|
import psycopg
|
|
|
|
|
|
def main():
|
|
folder = Path(__file__).resolve().parent.parent / 'db' / 'migrations'
|
|
files = sorted(folder.glob('*.sql'))
|
|
if not files:
|
|
raise RuntimeError('no migrations')
|
|
with psycopg.connect(os.environ['DATABASE_URL'], connect_timeout=5) as conn:
|
|
with conn.transaction():
|
|
# Serialize migration runners and all schema changes in the transaction.
|
|
conn.execute('SELECT pg_advisory_xact_lock(12803802)')
|
|
conn.execute('CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())')
|
|
applied = {r[0] for r in conn.execute('SELECT version FROM schema_migrations')}
|
|
if any(name not in {f.name for f in files} for name in applied):
|
|
raise RuntimeError('database contains unknown migration version')
|
|
for file in files:
|
|
if file.name in applied:
|
|
continue
|
|
conn.execute(file.read_text(encoding='utf-8'))
|
|
conn.execute('INSERT INTO schema_migrations(version) VALUES (%s)', (file.name,))
|
|
print('Applied migration', file.name)
|
|
print('Migrations up to date')
|
|
|
|
if __name__ == '__main__':
|
|
main()
|