env.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. from __future__ import with_statement
  2. import os
  3. from alembic import context
  4. from sqlalchemy import engine_from_config, pool
  5. from logging.config import fileConfig
  6. # this is the Alembic Config object, which provides
  7. # access to the values within the .ini file in use.
  8. config = context.config
  9. # Interpret the config file for Python logging.
  10. # This line sets up loggers basically.
  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. from app.db.base import Base # noqa
  18. target_metadata = Base.metadata
  19. # other values from the config, defined by the needs of env.py,
  20. # can be acquired:
  21. # my_important_option = config.get_main_option("my_important_option")
  22. # ... etc.
  23. def get_url():
  24. user = os.getenv("POSTGRES_USER", "postgres")
  25. password = os.getenv("POSTGRES_PASSWORD", "")
  26. server = os.getenv("POSTGRES_SERVER", "db")
  27. db = os.getenv("POSTGRES_DB", "app")
  28. return f"postgresql://{user}:{password}@{server}/{db}"
  29. def run_migrations_offline():
  30. """Run migrations in 'offline' mode.
  31. This configures the context with just a URL
  32. and not an Engine, though an Engine is acceptable
  33. here as well. By skipping the Engine creation
  34. we don't even need a DBAPI to be available.
  35. Calls to context.execute() here emit the given string to the
  36. script output.
  37. """
  38. url = get_url()
  39. context.configure(
  40. url=url, target_metadata=target_metadata, literal_binds=True, compare_type=True
  41. )
  42. with context.begin_transaction():
  43. context.run_migrations()
  44. def run_migrations_online():
  45. """Run migrations in 'online' mode.
  46. In this scenario we need to create an Engine
  47. and associate a connection with the context.
  48. """
  49. configuration = config.get_section(config.config_ini_section)
  50. configuration["sqlalchemy.url"] = get_url()
  51. connectable = engine_from_config(
  52. configuration, prefix="sqlalchemy.", poolclass=pool.NullPool,
  53. )
  54. with connectable.connect() as connection:
  55. context.configure(
  56. connection=connection, target_metadata=target_metadata, compare_type=True
  57. )
  58. with context.begin_transaction():
  59. context.run_migrations()
  60. if context.is_offline_mode():
  61. run_migrations_offline()
  62. else:
  63. run_migrations_online()