from logging.config import fileConfig from alembic import context from tofu_api.app import create_app from tofu_api.models import BaseModel # This is the Alembic Config object, which provides access to the values within the .ini file in use. alembic_config = context.config # Interpret the config file for Python logging. This line sets up loggers basically. if alembic_config.config_file_name is not None: fileConfig(alembic_config.config_file_name) # Create Flask app, which loads the app config and initializes the database engine. app = create_app() db = app.dependencies.get_sqlalchemy() def process_revision_directives(_context, _revision, directives): """ Callback used to prevent generating empty migrations with autogenerate. Source: https://alembic.sqlalchemy.org/en/latest/cookbook.html#don-t-generate-empty-migrations-with-autogenerate """ if alembic_config.cmd_opts.autogenerate and directives[0].upgrade_ops.is_empty(): directives[:] = [] context_parameters = { 'target_metadata': BaseModel.metadata, 'process_revision_directives': process_revision_directives, 'user_module_prefix': 'tofu_types.', } def run_migrations_offline(): """ Run migrations in 'offline' mode, which does not require an actual database engine and can be used to generate SQL scripts. """ context.configure( url=app.config.sqlalchemy_database_uri, literal_binds=True, dialect_opts={"paramstyle": "named"}, **context_parameters, ) with context.begin_transaction(): context.run_migrations() def run_migrations_online(): """ Run migrations in 'online' mode, which requires a database engine. """ with db.engine.connect() as connection: context.configure( connection=connection, **context_parameters, ) with context.begin_transaction(): context.run_migrations() if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online()