env.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. # Licensed to the Apache Software Foundation (ASF) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The ASF licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. import logging
  18. from logging.config import fileConfig
  19. from alembic import context
  20. from flask import current_app
  21. from flask_appbuilder import Base
  22. from sqlalchemy import engine_from_config, pool
  23. # this is the Alembic Config object, which provides
  24. # access to the values within the .ini file in use.
  25. config = context.config
  26. # Interpret the config file for Python logging.
  27. # This line sets up loggers basically.
  28. fileConfig(config.config_file_name)
  29. logger = logging.getLogger("alembic.env")
  30. config.set_main_option("sqlalchemy.url", current_app.config["SQLALCHEMY_DATABASE_URI"])
  31. target_metadata = Base.metadata # pylint: disable=no-member
  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 run_migrations_offline():
  37. """Run migrations in 'offline' mode.
  38. This configures the context with just a URL
  39. and not an Engine, though an Engine is acceptable
  40. here as well. By skipping the Engine creation
  41. we don't even need a DBAPI to be available.
  42. Calls to context.execute() here emit the given string to the
  43. script output.
  44. """
  45. url = config.get_main_option("sqlalchemy.url")
  46. context.configure(url=url)
  47. with context.begin_transaction():
  48. context.run_migrations()
  49. def run_migrations_online():
  50. """Run migrations in 'online' mode.
  51. In this scenario we need to create an Engine
  52. and associate a connection with the context.
  53. """
  54. # this callback is used to prevent an auto-migration from being generated
  55. # when there are no changes to the schema
  56. # reference: https://alembic.sqlalchemy.org/en/latest/cookbook.html
  57. def process_revision_directives(
  58. context, revision, directives
  59. ): # pylint: disable=redefined-outer-name, unused-argument
  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. engine = engine_from_config(
  66. config.get_section(config.config_ini_section),
  67. prefix="sqlalchemy.",
  68. poolclass=pool.NullPool,
  69. )
  70. connection = engine.connect()
  71. kwargs = {}
  72. if engine.name in ("sqlite", "mysql"):
  73. kwargs = {"transaction_per_migration": True, "transactional_ddl": True}
  74. configure_args = current_app.extensions["migrate"].configure_args
  75. if configure_args:
  76. kwargs.update(configure_args)
  77. context.configure(
  78. connection=connection,
  79. target_metadata=target_metadata,
  80. # compare_type=True,
  81. process_revision_directives=process_revision_directives,
  82. **kwargs
  83. )
  84. try:
  85. with context.begin_transaction():
  86. context.run_migrations()
  87. finally:
  88. connection.close()
  89. if context.is_offline_mode():
  90. run_migrations_offline()
  91. else:
  92. run_migrations_online()