env.py 6.0 KB

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