|
| 1 | +from __future__ import with_statement |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import logging |
| 5 | +from logging.config import fileConfig |
| 6 | + |
| 7 | +from sqlalchemy import MetaData |
| 8 | +from flask import current_app |
| 9 | + |
| 10 | +from alembic import context |
| 11 | + |
| 12 | +USE_TWOPHASE = False |
| 13 | + |
| 14 | +# this is the Alembic Config object, which provides |
| 15 | +# access to the values within the .ini file in use. |
| 16 | +config = context.config |
| 17 | + |
| 18 | +# Interpret the config file for Python logging. |
| 19 | +# This line sets up loggers basically. |
| 20 | +fileConfig(config.config_file_name) |
| 21 | +logger = logging.getLogger('alembic.env') |
| 22 | + |
| 23 | +# add your model's MetaData object here |
| 24 | +# for 'autogenerate' support |
| 25 | +# from myapp import mymodel |
| 26 | +# target_metadata = mymodel.Base.metadata |
| 27 | +config.set_main_option( |
| 28 | + 'sqlalchemy.url', |
| 29 | + str(current_app.extensions['migrate'].db.get_engine().url).replace( |
| 30 | + '%', '%%')) |
| 31 | +bind_names = [] |
| 32 | +if current_app.config.get('SQLALCHEMY_BINDS') is not None: |
| 33 | + bind_names = list(current_app.config['SQLALCHEMY_BINDS'].keys()) |
| 34 | +else: |
| 35 | + get_bind_names = getattr(current_app.extensions['migrate'].db, |
| 36 | + 'bind_names', None) |
| 37 | + if get_bind_names: |
| 38 | + bind_names = get_bind_names() |
| 39 | +for bind in bind_names: |
| 40 | + context.config.set_section_option( |
| 41 | + bind, "sqlalchemy.url", |
| 42 | + str(current_app.extensions['migrate'].db.get_engine( |
| 43 | + bind=bind).url).replace('%', '%%')) |
| 44 | +target_metadata = current_app.extensions['migrate'].db.metadata |
| 45 | + |
| 46 | + |
| 47 | +# other values from the config, defined by the needs of env.py, |
| 48 | +# can be acquired: |
| 49 | +# my_important_option = config.get_main_option("my_important_option") |
| 50 | +# ... etc. |
| 51 | + |
| 52 | + |
| 53 | +def get_metadata(bind): |
| 54 | + """Return the metadata for a bind.""" |
| 55 | + if bind == '': |
| 56 | + bind = None |
| 57 | + m = MetaData() |
| 58 | + for t in target_metadata.tables.values(): |
| 59 | + if t.info.get('bind_key') == bind: |
| 60 | + t.tometadata(m) |
| 61 | + return m |
| 62 | + |
| 63 | + |
| 64 | +def run_migrations_offline(): |
| 65 | + """Run migrations in 'offline' mode. |
| 66 | +
|
| 67 | + This configures the context with just a URL |
| 68 | + and not an Engine, though an Engine is acceptable |
| 69 | + here as well. By skipping the Engine creation |
| 70 | + we don't even need a DBAPI to be available. |
| 71 | +
|
| 72 | + Calls to context.execute() here emit the given string to the |
| 73 | + script output. |
| 74 | +
|
| 75 | + """ |
| 76 | + # for the --sql use case, run migrations for each URL into |
| 77 | + # individual files. |
| 78 | + |
| 79 | + engines = { |
| 80 | + '': { |
| 81 | + 'url': context.config.get_main_option('sqlalchemy.url') |
| 82 | + } |
| 83 | + } |
| 84 | + for name in bind_names: |
| 85 | + engines[name] = rec = {} |
| 86 | + rec['url'] = context.config.get_section_option(name, "sqlalchemy.url") |
| 87 | + |
| 88 | + for name, rec in engines.items(): |
| 89 | + logger.info("Migrating database %s" % (name or '<default>')) |
| 90 | + file_ = "%s.sql" % name |
| 91 | + logger.info("Writing output to %s" % file_) |
| 92 | + with open(file_, 'w') as buffer: |
| 93 | + context.configure( |
| 94 | + url=rec['url'], |
| 95 | + output_buffer=buffer, |
| 96 | + target_metadata=get_metadata(name), |
| 97 | + literal_binds=True, |
| 98 | + ) |
| 99 | + with context.begin_transaction(): |
| 100 | + context.run_migrations(engine_name=name) |
| 101 | + |
| 102 | + |
| 103 | +def do_run_migrations(_, engines): |
| 104 | + # this callback is used to prevent an auto-migration from being generated |
| 105 | + # when there are no changes to the schema |
| 106 | + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html |
| 107 | + def process_revision_directives(context, revision, directives): |
| 108 | + if getattr(config.cmd_opts, 'autogenerate', False): |
| 109 | + script = directives[0] |
| 110 | + if len(script.upgrade_ops_list) >= len(bind_names) + 1: |
| 111 | + empty = True |
| 112 | + for upgrade_ops in script.upgrade_ops_list: |
| 113 | + if not upgrade_ops.is_empty(): |
| 114 | + empty = False |
| 115 | + if empty: |
| 116 | + directives[:] = [] |
| 117 | + logger.info('No changes in schema detected.') |
| 118 | + |
| 119 | + for name, rec in engines.items(): |
| 120 | + rec['sync_connection'] = conn = rec['connection']._sync_connection() |
| 121 | + if USE_TWOPHASE: |
| 122 | + rec['transaction'] = conn.begin_twophase() |
| 123 | + else: |
| 124 | + rec['transaction'] = conn.begin() |
| 125 | + |
| 126 | + try: |
| 127 | + for name, rec in engines.items(): |
| 128 | + logger.info("Migrating database %s" % (name or '<default>')) |
| 129 | + context.configure( |
| 130 | + connection=rec['sync_connection'], |
| 131 | + upgrade_token="%s_upgrades" % name, |
| 132 | + downgrade_token="%s_downgrades" % name, |
| 133 | + target_metadata=get_metadata(name), |
| 134 | + process_revision_directives=process_revision_directives, |
| 135 | + **current_app.extensions['migrate'].configure_args |
| 136 | + ) |
| 137 | + context.run_migrations(engine_name=name) |
| 138 | + |
| 139 | + if USE_TWOPHASE: |
| 140 | + for rec in engines.values(): |
| 141 | + rec['transaction'].prepare() |
| 142 | + |
| 143 | + for rec in engines.values(): |
| 144 | + rec['transaction'].commit() |
| 145 | + except: # noqa: E722 |
| 146 | + for rec in engines.values(): |
| 147 | + rec['transaction'].rollback() |
| 148 | + raise |
| 149 | + finally: |
| 150 | + for rec in engines.values(): |
| 151 | + rec['sync_connection'].close() |
| 152 | + |
| 153 | + |
| 154 | +async def run_migrations_online(): |
| 155 | + """Run migrations in 'online' mode. |
| 156 | +
|
| 157 | + In this scenario we need to create an Engine |
| 158 | + and associate a connection with the context. |
| 159 | +
|
| 160 | + """ |
| 161 | + |
| 162 | + # for the direct-to-DB use case, start a transaction on all |
| 163 | + # engines, then run all migrations, then commit all transactions. |
| 164 | + engines = { |
| 165 | + '': {'engine': current_app.extensions['migrate'].db.get_engine()} |
| 166 | + } |
| 167 | + for name in bind_names: |
| 168 | + engines[name] = rec = {} |
| 169 | + rec['engine'] = current_app.extensions['migrate'].db.get_engine( |
| 170 | + bind=name) |
| 171 | + |
| 172 | + for name, rec in engines.items(): |
| 173 | + engine = rec['engine'] |
| 174 | + rec['connection'] = await engine.connect().start() |
| 175 | + |
| 176 | + await engines['']['connection'].run_sync(do_run_migrations, engines) |
| 177 | + |
| 178 | + for rec in engines.values(): |
| 179 | + await rec['connection'].close() |
| 180 | + |
| 181 | + |
| 182 | +if context.is_offline_mode(): |
| 183 | + run_migrations_offline() |
| 184 | +else: |
| 185 | + asyncio.run(run_migrations_online()) |
0 commit comments