env.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. import logging
  2. from logging.config import fileConfig
  3. import re
  4. from sqlalchemy import engine_from_config
  5. from sqlalchemy import pool
  6. from alembic import context
  7. USE_TWOPHASE = False
  8. # this is the Alembic Config object, which provides
  9. # access to the values within the .ini file in use.
  10. config = context.config
  11. # Interpret the config file for Python logging.
  12. # This line sets up loggers basically.
  13. if config.config_file_name is not None:
  14. fileConfig(config.config_file_name)
  15. logger = logging.getLogger("alembic.env")
  16. # gather section names referring to different
  17. # databases. These are named "engine1", "engine2"
  18. # in the sample .ini file.
  19. db_names = config.get_main_option("databases", "")
  20. # add your model's MetaData objects here
  21. # for 'autogenerate' support. These must be set
  22. # up to hold just those tables targeting a
  23. # particular database. table.tometadata() may be
  24. # helpful here in case a "copy" of
  25. # a MetaData is needed.
  26. # from myapp import mymodel
  27. # target_metadata = {
  28. # 'engine1':mymodel.metadata1,
  29. # 'engine2':mymodel.metadata2
  30. # }
  31. target_metadata = {}
  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() -> None:
  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. # for the --sql use case, run migrations for each URL into
  46. # individual files.
  47. engines = {}
  48. for name in re.split(r",\s*", db_names):
  49. engines[name] = rec = {}
  50. rec["url"] = context.config.get_section_option(name, "sqlalchemy.url")
  51. for name, rec in engines.items():
  52. logger.info("Migrating database %s" % name)
  53. file_ = "%s.sql" % name
  54. logger.info("Writing output to %s" % file_)
  55. with open(file_, "w") as buffer:
  56. context.configure(
  57. url=rec["url"],
  58. output_buffer=buffer,
  59. target_metadata=target_metadata.get(name),
  60. literal_binds=True,
  61. dialect_opts={"paramstyle": "named"},
  62. )
  63. with context.begin_transaction():
  64. context.run_migrations(engine_name=name)
  65. def run_migrations_online() -> None:
  66. """Run migrations in 'online' mode.
  67. In this scenario we need to create an Engine
  68. and associate a connection with the context.
  69. """
  70. # for the direct-to-DB use case, start a transaction on all
  71. # engines, then run all migrations, then commit all transactions.
  72. engines = {}
  73. for name in re.split(r",\s*", db_names):
  74. engines[name] = rec = {}
  75. rec["engine"] = engine_from_config(
  76. context.config.get_section(name, {}),
  77. prefix="sqlalchemy.",
  78. poolclass=pool.NullPool,
  79. )
  80. for name, rec in engines.items():
  81. engine = rec["engine"]
  82. rec["connection"] = conn = engine.connect()
  83. if USE_TWOPHASE:
  84. rec["transaction"] = conn.begin_twophase()
  85. else:
  86. rec["transaction"] = conn.begin()
  87. try:
  88. for name, rec in engines.items():
  89. logger.info("Migrating database %s" % name)
  90. context.configure(
  91. connection=rec["connection"],
  92. upgrade_token="%s_upgrades" % name,
  93. downgrade_token="%s_downgrades" % name,
  94. target_metadata=target_metadata.get(name),
  95. )
  96. context.run_migrations(engine_name=name)
  97. if USE_TWOPHASE:
  98. for rec in engines.values():
  99. rec["transaction"].prepare()
  100. for rec in engines.values():
  101. rec["transaction"].commit()
  102. except:
  103. for rec in engines.values():
  104. rec["transaction"].rollback()
  105. raise
  106. finally:
  107. for rec in engines.values():
  108. rec["connection"].close()
  109. if context.is_offline_mode():
  110. run_migrations_offline()
  111. else:
  112. run_migrations_online()