env.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #ident "@(#)$Format:LocalFoodAI_lanfr144:env.py:%an:%ae:%ad:%cn:%ce:%cd:%H:%D:%N$"
  2. from logging.config import fileConfig
  3. from sqlalchemy import engine_from_config
  4. from sqlalchemy import pool
  5. from alembic import context
  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. import os
  10. db_url = os.environ.get("DATABASE_URL")
  11. if not db_url:
  12. db_host = os.environ.get("DB_HOST")
  13. db_user = os.environ.get("DB_USER") or os.environ.get("DB_OWNER_USER")
  14. db_pass = os.environ.get("DB_PASS") or os.environ.get("DB_OWNER_PASS")
  15. if db_host and db_user and db_pass:
  16. db_url = f"mysql+pymysql://{db_user}:{db_pass}@{db_host}/food_db"
  17. if db_url:
  18. config.set_main_option("sqlalchemy.url", db_url)
  19. # Interpret the config file for Python logging.
  20. # This line sets up loggers basically.
  21. if config.config_file_name is not None:
  22. fileConfig(config.config_file_name)
  23. # add your model's MetaData object here
  24. # for 'autogenerate' support
  25. # from myapp import mymodel
  26. # target_metadata = mymodel.Base.metadata
  27. target_metadata = None
  28. # other values from the config, defined by the needs of env.py,
  29. # can be acquired:
  30. # my_important_option = config.get_main_option("my_important_option")
  31. # ... etc.
  32. def run_migrations_offline() -> None:
  33. """Run migrations in 'offline' mode.
  34. This configures the context with just a URL
  35. and not an Engine, though an Engine is acceptable
  36. here as well. By skipping the Engine creation
  37. we don't even need a DBAPI to be available.
  38. Calls to context.execute() here emit the given string to the
  39. script output.
  40. """
  41. url = config.get_main_option("sqlalchemy.url")
  42. context.configure(
  43. url=url,
  44. target_metadata=target_metadata,
  45. literal_binds=True,
  46. dialect_opts={"paramstyle": "named"},
  47. )
  48. with context.begin_transaction():
  49. context.run_migrations()
  50. def run_migrations_online() -> None:
  51. """Run migrations in 'online' mode.
  52. In this scenario we need to create an Engine
  53. and associate a connection with the context.
  54. """
  55. connectable = engine_from_config(
  56. config.get_section(config.config_ini_section, {}),
  57. prefix="sqlalchemy.",
  58. poolclass=pool.NullPool,
  59. )
  60. with connectable.connect() as connection:
  61. context.configure(
  62. connection=connection, target_metadata=target_metadata
  63. )
  64. with context.begin_transaction():
  65. context.run_migrations()
  66. if context.is_offline_mode():
  67. run_migrations_offline()
  68. else:
  69. run_migrations_online()