import logging from pathlib import Path import sys import time import psycopg from config import settings MIGRATIONS = Path(__file__).resolve().parent.parent / 'migrations' LOCK_ID = 20260002 log = logging.getLogger('migrate') def connect(attempts=30): for attempt in range(1, attempts + 1): try: return psycopg.connect(settings.database_url, autocommit=True, connect_timeout=3) except psycopg.OperationalError: if attempt == attempts: raise log.info('database is not ready, retry %d/%d', attempt, attempts) time.sleep(1) def main(): logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(asctime)s %(name)s: %(message)s') with connect() as conn: conn.execute('SELECT pg_advisory_lock(%s)', (LOCK_ID,)) conn.execute('CREATE TABLE IF NOT EXISTS schema_migrations (' 'version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())') applied = {row[0] for row in conn.execute('SELECT version FROM schema_migrations')} for path in sorted(MIGRATIONS.glob('*.sql')): if path.stem in applied: log.info('skip %s: already applied', path.stem) continue with conn.transaction(): conn.execute(path.read_text(encoding='utf-8')) conn.execute('INSERT INTO schema_migrations (version) VALUES (%s)', (path.stem,)) log.info('applied %s', path.stem) conn.execute('SELECT pg_advisory_unlock(%s)', (LOCK_ID,)) log.info('schema is up to date') if __name__ == '__main__': main()