codekingpro/portable-devtools
114k
1import logging2from logging.config import fileConfig3import re4 5from sqlalchemy import engine_from_config6from sqlalchemy import pool7 8from alembic import context9 10USE_TWOPHASE = False11 12# this is the Alembic Config object, which provides13# access to the values within the .ini file in use.14config = context.config15 16# Interpret the config file for Python logging.17# This line sets up loggers basically.18if config.config_file_name is not None:19 fileConfig(config.config_file_name)20logger = logging.getLogger("alembic.env")21 22# gather section names referring to different23# databases. These are named "engine1", "engine2"24# in the sample .ini file.25db_names = config.get_main_option("databases", "")26 27# add your model's MetaData objects here28# for 'autogenerate' support. These must be set29# up to hold just those tables targeting a30# particular database. table.tometadata() may be31# helpful here in case a "copy" of32# a MetaData is needed.33# from myapp import mymodel34# target_metadata = {35# 'engine1':mymodel.metadata1,36# 'engine2':mymodel.metadata237# }38target_metadata = {}39 40# other values from the config, defined by the needs of env.py,41# can be acquired:42# my_important_option = config.get_main_option("my_important_option")43# ... etc.44 45 46def run_migrations_offline() -> None:47 """Run migrations in 'offline' mode.48 49 This configures the context with just a URL50 and not an Engine, though an Engine is acceptable51 here as well. By skipping the Engine creation52 we don't even need a DBAPI to be available.53 54 Calls to context.execute() here emit the given string to the55 script output.56 57 """58 # for the --sql use case, run migrations for each URL into59 # individual files.60 61 engines = {}62 for name in re.split(r",\s*", db_names):63 engines[name] = rec = {}64 rec["url"] = context.config.get_section_option(name, "sqlalchemy.url")65 66 for name, rec in engines.items():67 logger.info("Migrating database %s" % name)68 file_ = "%s.sql" % name69 logger.info("Writing output to %s" % file_)70 with open(file_, "w") as buffer:71 context.configure(72 url=rec["url"],73 output_buffer=buffer,74 target_metadata=target_metadata.get(name),75 literal_binds=True,76 dialect_opts={"paramstyle": "named"},77 )78 with context.begin_transaction():79 context.run_migrations(engine_name=name)80 81 82def run_migrations_online() -> None:83 """Run migrations in 'online' mode.84 85 In this scenario we need to create an Engine86 and associate a connection with the context.87 88 """89 90 # for the direct-to-DB use case, start a transaction on all91 # engines, then run all migrations, then commit all transactions.92 93 engines = {}94 for name in re.split(r",\s*", db_names):95 engines[name] = rec = {}96 rec["engine"] = engine_from_config(97 context.config.get_section(name, {}),98 prefix="sqlalchemy.",99 poolclass=pool.NullPool,100 )101 102 for name, rec in engines.items():103 engine = rec["engine"]104 rec["connection"] = conn = engine.connect()105 106 if USE_TWOPHASE:107 rec["transaction"] = conn.begin_twophase()108 else:109 rec["transaction"] = conn.begin()110 111 try:112 for name, rec in engines.items():113 logger.info("Migrating database %s" % name)114 context.configure(115 connection=rec["connection"],116 upgrade_token="%s_upgrades" % name,117 downgrade_token="%s_downgrades" % name,118 target_metadata=target_metadata.get(name),119 )120 context.run_migrations(engine_name=name)121 122 if USE_TWOPHASE:123 for rec in engines.values():124 rec["transaction"].prepare()125 126 for rec in engines.values():127 rec["transaction"].commit()128 except:129 for rec in engines.values():130 rec["transaction"].rollback()131 raise132 finally:133 for rec in engines.values():134 rec["connection"].close()135 136 137if context.is_offline_mode():138 run_migrations_offline()139else:140 run_migrations_online()141 