env.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import os
  2. from logging.config import fileConfig
  3. from alembic import context
  4. from sqlalchemy import engine_from_config, pool
  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. # target_metadata = None
  16. from app.models import SQLModel # noqa
  17. target_metadata = SQLModel.metadata
  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 get_url():
  23. user = os.getenv("POSTGRES_USER", "postgres")
  24. password = os.getenv("POSTGRES_PASSWORD", "")
  25. server = os.getenv("POSTGRES_SERVER", "db")
  26. port = os.getenv("POSTGRES_PORT", "5432")
  27. db = os.getenv("POSTGRES_DB", "app")
  28. return f"postgresql+psycopg://{user}:{password}@{server}:{port}/{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,
  53. prefix="sqlalchemy.",
  54. poolclass=pool.NullPool,
  55. )
  56. with connectable.connect() as connection:
  57. context.configure(
  58. connection=connection, target_metadata=target_metadata, compare_type=True
  59. )
  60. with context.begin_transaction():
  61. context.run_migrations()
  62. if context.is_offline_mode():
  63. run_migrations_offline()
  64. else:
  65. run_migrations_online()