"""Версионируемые миграции: одна транзакция, блокировка от параллельного запуска.""" from pathlib import Path import psycopg from src.config import setting def main(): with psycopg.connect(setting('DATABASE_URL'), connect_timeout=5) as conn: conn.execute('SELECT pg_advisory_xact_lock(2301002)') conn.execute('CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY)') for path in sorted(Path('/app/migrations' if Path('/app/migrations').exists() else 'migrations').glob('*.sql')): if not conn.execute('SELECT 1 FROM schema_migrations WHERE version=%s', (path.name,)).fetchone(): conn.execute(path.read_text(encoding='utf-8')) conn.execute('INSERT INTO schema_migrations VALUES (%s)', (path.name,)) print('Применена миграция:', path.name) if __name__ == '__main__': main()