env.py 2.1 KB

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