env.py 2.1 KB

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