env.py 2.5 KB

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