You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

110 lines
3.2 KiB

  1. import logging
  2. from logging.config import fileConfig
  3. from flask import current_app
  4. from alembic import context
  5. # this is the Alembic Config object, which provides
  6. # access to the values within the .ini file in use.
  7. config = context.config
  8. # Interpret the config file for Python logging.
  9. # This line sets up loggers basically.
  10. fileConfig(config.config_file_name)
  11. logger = logging.getLogger('alembic.env')
  12. def get_engine():
  13. try:
  14. # this works with Flask-SQLAlchemy<3 and Alchemical
  15. return current_app.extensions['migrate'].db.get_engine()
  16. except TypeError:
  17. # this works with Flask-SQLAlchemy>=3
  18. return current_app.extensions['migrate'].db.engine
  19. def get_engine_url():
  20. try:
  21. return get_engine().url.render_as_string(hide_password=False).replace(
  22. '%', '%%')
  23. except AttributeError:
  24. return str(get_engine().url).replace('%', '%%')
  25. # add your model's MetaData object here
  26. # for 'autogenerate' support
  27. # from myapp import mymodel
  28. # target_metadata = mymodel.Base.metadata
  29. config.set_main_option('sqlalchemy.url', get_engine_url())
  30. target_db = current_app.extensions['migrate'].db
  31. # other values from the config, defined by the needs of env.py,
  32. # can be acquired:
  33. # my_important_option = config.get_main_option("my_important_option")
  34. # ... etc.
  35. def get_metadata():
  36. if hasattr(target_db, 'metadatas'):
  37. return target_db.metadatas[None]
  38. return target_db.metadata
  39. def run_migrations_offline():
  40. """Run migrations in 'offline' mode.
  41. This configures the context with just a URL
  42. and not an Engine, though an Engine is acceptable
  43. here as well. By skipping the Engine creation
  44. we don't even need a DBAPI to be available.
  45. Calls to context.execute() here emit the given string to the
  46. script output.
  47. """
  48. url = config.get_main_option("sqlalchemy.url")
  49. context.configure(
  50. url=url, target_metadata=get_metadata(), literal_binds=True
  51. )
  52. with context.begin_transaction():
  53. context.run_migrations()
  54. def run_migrations_online():
  55. """Run migrations in 'online' mode.
  56. In this scenario we need to create an Engine
  57. and associate a connection with the context.
  58. """
  59. # this callback is used to prevent an auto-migration from being generated
  60. # when there are no changes to the schema
  61. # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
  62. def process_revision_directives(context, revision, directives):
  63. if getattr(config.cmd_opts, 'autogenerate', False):
  64. script = directives[0]
  65. if script.upgrade_ops.is_empty():
  66. directives[:] = []
  67. logger.info('No changes in schema detected.')
  68. connectable = get_engine()
  69. with connectable.connect() as connection:
  70. context.configure(
  71. connection=connection,
  72. target_metadata=get_metadata(),
  73. process_revision_directives=process_revision_directives,
  74. **current_app.extensions['migrate'].configure_args
  75. )
  76. with context.begin_transaction():
  77. context.run_migrations()
  78. if context.is_offline_mode():
  79. run_migrations_offline()
  80. else:
  81. run_migrations_online()