"""One transaction per connection; versioned migrations run as a separate job.""" import os from pathlib import Path import psycopg from psycopg.rows import dict_row def connect(): dsn = Path(os.environ['DATABASE_URL_FILE']).read_text().strip() return psycopg.connect(dsn, connect_timeout=3, row_factory=dict_row, options='-c statement_timeout=5000 -c timezone=UTC') def migrate(): with connect() as db: db.execute('SELECT pg_advisory_xact_lock(2303002)') db.execute('CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY)') for path in sorted((Path(__file__).resolve().parents[1] / 'migrations').glob('*.sql')): if not db.execute('SELECT 1 FROM schema_migrations WHERE version=%s', (path.name,)).fetchone(): db.execute(path.read_text()) db.execute('INSERT INTO schema_migrations VALUES (%s)', (path.name,)) if __name__ == '__main__': migrate() print('Migrations applied')