|
| 1 | +import logging |
| 2 | +import os |
| 3 | +from asyncio import get_event_loop |
| 4 | + |
| 5 | +from alembic import context |
| 6 | +from sqlalchemy import Column, Integer, String |
| 7 | +from sqlalchemy.ext.asyncio import AsyncEngine |
| 8 | + |
| 9 | +from sqlalchemy_bind_manager import SQLAlchemyAsyncConfig, SQLAlchemyBindManager |
| 10 | + |
| 11 | +################################################################ |
| 12 | +## Note: The bind_config, sa_manager and models are normally ## |
| 13 | +## implemented in an application. This is only an example! ## |
| 14 | +################################################################ |
| 15 | +bind_config = { |
| 16 | + "default": SQLAlchemyAsyncConfig( |
| 17 | + engine_url=f"sqlite+aiosqlite:///{os.path.dirname(os.path.abspath(__file__))}/sqlite.db", |
| 18 | + engine_options=dict( |
| 19 | + connect_args={ |
| 20 | + "check_same_thread": False, |
| 21 | + }, |
| 22 | + echo=False, |
| 23 | + future=True, |
| 24 | + ), |
| 25 | + ), |
| 26 | +} |
| 27 | + |
| 28 | +sa_manager = SQLAlchemyBindManager(config=bind_config) |
| 29 | + |
| 30 | +class BookModel(sa_manager.get_bind().model_declarative_base): |
| 31 | + id = Column(Integer) |
| 32 | + title = Column(String) |
| 33 | +################################################################ |
| 34 | +## Note: The bind_config, sa_manager and models are normally ## |
| 35 | +## implemented in an application. This is only an example! ## |
| 36 | +################################################################ |
| 37 | + |
| 38 | + |
| 39 | +USE_TWOPHASE = False |
| 40 | + |
| 41 | +# this is the Alembic Config object, which provides |
| 42 | +# access to the values within the .ini file in use. |
| 43 | +config = context.config |
| 44 | + |
| 45 | +logger = logging.getLogger("alembic.env") |
| 46 | +target_metadata = sa_manager.get_bind_mappers_metadata() |
| 47 | +db_names = target_metadata.keys() |
| 48 | +config.set_main_option("databases", ",".join(db_names)) |
| 49 | + |
| 50 | + |
| 51 | +def run_migrations_offline() -> None: |
| 52 | + """Run migrations in 'offline' mode. |
| 53 | +
|
| 54 | + This configures the context with just a URL |
| 55 | + and not an Engine, though an Engine is acceptable |
| 56 | + here as well. By skipping the Engine creation |
| 57 | + we don't even need a DBAPI to be available. |
| 58 | +
|
| 59 | + Calls to context.execute() here emit the given string to the |
| 60 | + script output. |
| 61 | +
|
| 62 | + """ |
| 63 | + # for the --sql use case, run migrations for each URL into |
| 64 | + # individual files. |
| 65 | + |
| 66 | + engines = {} |
| 67 | + for name in db_names: |
| 68 | + engines[name] = {} |
| 69 | + engines[name]["url"] = sa_manager.get_bind(name).engine.url |
| 70 | + |
| 71 | + for name, rec in engines.items(): |
| 72 | + logger.info(f"Migrating database {name}") |
| 73 | + file_ = f"{name}.sql" |
| 74 | + logger.info(f"Writing output to {file_}") |
| 75 | + with open(file_, "w") as buffer: |
| 76 | + context.configure( |
| 77 | + url=rec["url"], |
| 78 | + output_buffer=buffer, |
| 79 | + target_metadata=target_metadata.get(name), |
| 80 | + literal_binds=True, |
| 81 | + dialect_opts={"paramstyle": "named"}, |
| 82 | + ) |
| 83 | + with context.begin_transaction(): |
| 84 | + context.run_migrations(engine_name=name) |
| 85 | + |
| 86 | + |
| 87 | +def do_run_migration(conn, name): |
| 88 | + context.configure( |
| 89 | + connection=conn, |
| 90 | + upgrade_token=f"{name}_upgrades", |
| 91 | + downgrade_token=f"{name}_downgrades", |
| 92 | + target_metadata=target_metadata.get(name), |
| 93 | + ) |
| 94 | + context.run_migrations(engine_name=name) |
| 95 | + |
| 96 | + |
| 97 | +async def run_migrations_online() -> None: |
| 98 | + """Run migrations in 'online' mode. |
| 99 | +
|
| 100 | + In this scenario we need to create an Engine |
| 101 | + and associate a connection with the context. |
| 102 | + """ |
| 103 | + |
| 104 | + # for the direct-to-DB use case, start a transaction on all |
| 105 | + # engines, then run all migrations, then commit all transactions. |
| 106 | + |
| 107 | + engines = {} |
| 108 | + for name in db_names: |
| 109 | + engines[name] = {} |
| 110 | + engines[name]["engine"] = sa_manager.get_bind(name).engine |
| 111 | + |
| 112 | + for name, rec in engines.items(): |
| 113 | + engine = rec["engine"] |
| 114 | + if isinstance(engine, AsyncEngine): |
| 115 | + rec["connection"] = conn = await engine.connect() |
| 116 | + |
| 117 | + if USE_TWOPHASE: |
| 118 | + rec["transaction"] = await conn.begin_twophase() |
| 119 | + else: |
| 120 | + rec["transaction"] = await conn.begin() |
| 121 | + else: |
| 122 | + rec["connection"] = conn = engine.connect() |
| 123 | + |
| 124 | + if USE_TWOPHASE: |
| 125 | + rec["transaction"] = conn.begin_twophase() |
| 126 | + else: |
| 127 | + rec["transaction"] = conn.begin() |
| 128 | + |
| 129 | + try: |
| 130 | + for name, rec in engines.items(): |
| 131 | + logger.info(f"Migrating database {name}") |
| 132 | + if isinstance(rec["engine"], AsyncEngine): |
| 133 | + |
| 134 | + def migration_callable(*args, **kwargs): |
| 135 | + return do_run_migration(*args, name=name, **kwargs) |
| 136 | + |
| 137 | + await rec["connection"].run_sync(migration_callable) |
| 138 | + else: |
| 139 | + do_run_migration(name, rec) |
| 140 | + |
| 141 | + if USE_TWOPHASE: |
| 142 | + for rec in engines.values(): |
| 143 | + if isinstance(rec["engine"], AsyncEngine): |
| 144 | + await rec["transaction"].prepare() |
| 145 | + else: |
| 146 | + rec["transaction"].prepare() |
| 147 | + |
| 148 | + for rec in engines.values(): |
| 149 | + if isinstance(rec["engine"], AsyncEngine): |
| 150 | + await rec["transaction"].commit() |
| 151 | + else: |
| 152 | + rec["transaction"].commit() |
| 153 | + except: |
| 154 | + for rec in engines.values(): |
| 155 | + if isinstance(rec["engine"], AsyncEngine): |
| 156 | + await rec["transaction"].rollback() |
| 157 | + else: |
| 158 | + rec["transaction"].rollback() |
| 159 | + raise |
| 160 | + finally: |
| 161 | + for rec in engines.values(): |
| 162 | + if isinstance(rec["engine"], AsyncEngine): |
| 163 | + await rec["connection"].close() |
| 164 | + else: |
| 165 | + rec["connection"].close() |
| 166 | + |
| 167 | + |
| 168 | +if context.is_offline_mode(): |
| 169 | + run_migrations_offline() |
| 170 | +else: |
| 171 | + loop = get_event_loop() |
| 172 | + if loop.is_running(): |
| 173 | + loop.create_task(run_migrations_online()) |
| 174 | + else: |
| 175 | + loop.run_until_complete(run_migrations_online()) |
0 commit comments