env.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. from logging.config import fileConfig
  2. from sqlalchemy import engine_from_config
  3. from sqlalchemy import pool
  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. if config.config_file_name is not None:
  11. fileConfig(config.config_file_name)
  12. # add your model's MetaData object here
  13. # for 'autogenerate' support
  14. # from myapp import mymodel
  15. # target_metadata = mymodel.Base.metadata
  16. target_metadata = None
  17. # other values from the config, defined by the needs of env.py,
  18. # can be acquired:
  19. # my_important_option = config.get_main_option("my_important_option")
  20. # ... etc.
  21. def run_migrations_offline() -> None:
  22. """Run migrations in 'offline' mode.
  23. This configures the context with just a URL
  24. and not an Engine, though an Engine is acceptable
  25. here as well. By skipping the Engine creation
  26. we don't even need a DBAPI to be available.
  27. Calls to context.execute() here emit the given string to the
  28. script output.
  29. """
  30. url = config.get_main_option("sqlalchemy.url")
  31. context.configure(
  32. url=url,
  33. target_metadata=target_metadata,
  34. literal_binds=True,
  35. dialect_opts={"paramstyle": "named"},
  36. )
  37. with context.begin_transaction():
  38. context.run_migrations()
  39. def run_migrations_online() -> None:
  40. """Run migrations in 'online' mode.
  41. In this scenario we need to create an Engine
  42. and associate a connection with the context.
  43. """
  44. connectable = engine_from_config(
  45. config.get_section(config.config_ini_section, {}),
  46. prefix="sqlalchemy.",
  47. poolclass=pool.NullPool,
  48. )
  49. with connectable.connect() as connection:
  50. context.configure(
  51. connection=connection, target_metadata=target_metadata
  52. )
  53. with context.begin_transaction():
  54. context.run_migrations()
  55. if context.is_offline_mode():
  56. run_migrations_offline()
  57. else:
  58. run_migrations_online()