env.py 3.4 KB

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