|
| 1 | +import os |
| 2 | +from logging.config import fileConfig |
| 3 | + |
| 4 | +from alembic import context |
| 5 | +from dotenv import load_dotenv |
| 6 | + |
| 7 | +from birdxplorer_common.settings import GlobalSettings |
| 8 | +from birdxplorer_common.storage import Base, gen_storage |
| 9 | + |
| 10 | +# this is the Alembic Config object, which provides |
| 11 | +# access to the values within the .ini file in use. |
| 12 | +config = context.config |
| 13 | + |
| 14 | +# Interpret the config file for Python logging. |
| 15 | +# This line sets up loggers basically. |
| 16 | +if config.config_file_name is not None: |
| 17 | + fileConfig(config.config_file_name) |
| 18 | + |
| 19 | +work_dir = os.path.dirname(os.path.abspath(__file__)) |
| 20 | +env_file = os.path.join(os.path.dirname(os.path.dirname(work_dir)), ".env") |
| 21 | +load_dotenv(env_file) |
| 22 | +bx_settings = GlobalSettings() |
| 23 | + |
| 24 | +# add your model's MetaData object here |
| 25 | +# for 'autogenerate' support |
| 26 | +# from myapp import mymodel |
| 27 | +# target_metadata = mymodel.Base.metadata |
| 28 | +target_metadata = Base.metadata |
| 29 | + |
| 30 | +# other values from the config, defined by the needs of env.py, |
| 31 | +# can be acquired: |
| 32 | +# my_important_option = config.get_main_option("my_important_option") |
| 33 | +# ... etc. |
| 34 | + |
| 35 | + |
| 36 | +def run_migrations_offline() -> None: |
| 37 | + """Run migrations in 'offline' mode. |
| 38 | +
|
| 39 | + This configures the context with just a URL |
| 40 | + and not an Engine, though an Engine is acceptable |
| 41 | + here as well. By skipping the Engine creation |
| 42 | + we don't even need a DBAPI to be available. |
| 43 | +
|
| 44 | + Calls to context.execute() here emit the given string to the |
| 45 | + script output. |
| 46 | +
|
| 47 | + """ |
| 48 | + url = bx_settings.storage_settings.sqlalchemy_database_url |
| 49 | + context.configure( |
| 50 | + url=url, |
| 51 | + target_metadata=target_metadata, |
| 52 | + literal_binds=True, |
| 53 | + dialect_opts={"paramstyle": "named"}, |
| 54 | + ) |
| 55 | + |
| 56 | + with context.begin_transaction(): |
| 57 | + context.run_migrations() |
| 58 | + |
| 59 | + |
| 60 | +def run_migrations_online() -> None: |
| 61 | + """Run migrations in 'online' mode. |
| 62 | +
|
| 63 | + In this scenario we need to create an Engine |
| 64 | + and associate a connection with the context. |
| 65 | +
|
| 66 | + """ |
| 67 | + storage = gen_storage(settings=bx_settings) |
| 68 | + connectable = storage.engine |
| 69 | + |
| 70 | + with connectable.connect() as connection: |
| 71 | + context.configure(connection=connection, target_metadata=target_metadata) |
| 72 | + |
| 73 | + with context.begin_transaction(): |
| 74 | + context.run_migrations() |
| 75 | + |
| 76 | + |
| 77 | +if context.is_offline_mode(): |
| 78 | + run_migrations_offline() |
| 79 | +else: |
| 80 | + run_migrations_online() |
0 commit comments