"""Transactional, versioned SQL migrations protected by a database advisory lock.""" import hashlib from pathlib import Path import psycopg from app.config import secret def migrate(): with psycopg.connect(secret('DATABASE_URL'), connect_timeout=3) as conn: conn.execute('SELECT pg_advisory_xact_lock(202602)') conn.execute('''CREATE TABLE IF NOT EXISTS schema_migrations ( version text PRIMARY KEY, checksum text NOT NULL, applied_at timestamptz NOT NULL DEFAULT clock_timestamp())''') for path in sorted((Path(__file__).resolve().parents[1] / 'migrations').glob('*.sql')): sql = path.read_text() checksum = hashlib.sha256(sql.encode()).hexdigest() row = conn.execute('SELECT checksum FROM schema_migrations WHERE version=%s', (path.name,)).fetchone() if row: if row[0] != checksum: raise RuntimeError('Applied migration has changed: ' + path.name) continue conn.execute(sql) conn.execute('INSERT INTO schema_migrations(version, checksum) VALUES (%s,%s)', (path.name, checksum)) print('Applied migration ' + path.name, flush=True) if __name__ == '__main__': migrate()