# Database migration scripts import os import sys import logging from flask import Flask from flask_migrate import Migrate, init, migrate, upgrade from database import db, init_db from config import Config logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def create_app(): """Create Flask app for migrations""" app = Flask(__name__) # Load configuration config = Config() app.config.from_object(config) # Initialize database init_db(app) return app def init_migrations(): """Initialize migration repository""" app = create_app() with app.app_context(): # Initialize Flask-Migrate migrate_instance = Migrate(app, db) # Initialize migration repository try: init() logger.info("Migration repository initialized") except Exception as e: logger.error(f"Failed to initialize migrations: {e}") return False return True def create_migration(message="Auto migration"): """Create a new migration""" app = create_app() with app.app_context(): # Initialize Flask-Migrate migrate_instance = Migrate(app, db) try: migrate(message=message) logger.info(f"Migration created: {message}") except Exception as e: logger.error(f"Failed to create migration: {e}") return False return True def run_migrations(): """Run pending migrations""" app = create_app() with app.app_context(): # Initialize Flask-Migrate migrate_instance = Migrate(app, db) try: upgrade() logger.info("Migrations completed successfully") except Exception as e: logger.error(f"Failed to run migrations: {e}") return False return True def create_initial_data(): """Create initial data if needed""" app = create_app() with app.app_context(): try: # Add any initial data here # For example, creating default API keys, admin users, etc. db.session.commit() logger.info("Initial data created") except Exception as e: db.session.rollback() logger.error(f"Failed to create initial data: {e}") return False return True if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: python migrations.py [init|create|run|seed]") sys.exit(1) command = sys.argv[1] if command == "init": if init_migrations(): print("Migration repository initialized successfully") else: print("Failed to initialize migrations") sys.exit(1) elif command == "create": message = sys.argv[2] if len(sys.argv) > 2 else "Auto migration" if create_migration(message): print(f"Migration created: {message}") else: print("Failed to create migration") sys.exit(1) elif command == "run": if run_migrations(): print("Migrations completed successfully") else: print("Failed to run migrations") sys.exit(1) elif command == "seed": if create_initial_data(): print("Initial data created successfully") else: print("Failed to create initial data") sys.exit(1) else: print(f"Unknown command: {command}") print("Available commands: init, create, run, seed") sys.exit(1)