""" Database migration runner Execute SQL migration files using the Flask app's database connection """ import os import sys # Add parent directory to path to import app sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from extensions import db as database def run_migration(migration_file): """Execute a SQL migration file""" try: # Read migration file migration_path = os.path.join('migrations', migration_file) if not os.path.exists(migration_path): print(f"ERROR: Migration file not found: {migration_path}") sys.exit(1) with open(migration_path, 'r') as f: sql = f.read() # Execute migration using the database connection conn = database.pool.getconn() cursor = conn.cursor() try: cursor.execute(sql) conn.commit() print(f"✓ Successfully executed migration: {migration_file}") except Exception as e: conn.rollback() print(f"ERROR executing migration: {e}") sys.exit(1) finally: cursor.close() database.pool.putconn(conn) except Exception as e: print(f"ERROR: {e}") sys.exit(1) if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: python run_migration.py ") print("Example: python run_migration.py 003_create_login_history.sql") sys.exit(1) # Initialize the app to set up database connection from app import app with app.app_context(): migration_file = sys.argv[1] run_migration(migration_file)