env.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import os
  2. from alembic import context
  3. from sqlalchemy import engine_from_config, pool
  4. from embedchain.core.db.models import Base
  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. target_metadata = Base.metadata
  9. # other values from the config, defined by the needs of env.py,
  10. # can be acquired:
  11. # my_important_option = config.get_main_option("my_important_option")
  12. # ... etc.
  13. config.set_main_option("sqlalchemy.url", os.environ.get("EMBEDCHAIN_DB_URI"))
  14. def run_migrations_offline() -> None:
  15. """Run migrations in 'offline' mode.
  16. This configures the context with just a URL
  17. and not an Engine, though an Engine is acceptable
  18. here as well. By skipping the Engine creation
  19. we don't even need a DBAPI to be available.
  20. Calls to context.execute() here emit the given string to the
  21. script output.
  22. """
  23. url = config.get_main_option("sqlalchemy.url")
  24. context.configure(
  25. url=url,
  26. target_metadata=target_metadata,
  27. literal_binds=True,
  28. dialect_opts={"paramstyle": "named"},
  29. )
  30. with context.begin_transaction():
  31. context.run_migrations()
  32. def run_migrations_online() -> None:
  33. """Run migrations in 'online' mode.
  34. In this scenario we need to create an Engine
  35. and associate a connection with the context.
  36. """
  37. connectable = engine_from_config(
  38. config.get_section(config.config_ini_section, {}),
  39. prefix="sqlalchemy.",
  40. poolclass=pool.NullPool,
  41. )
  42. with connectable.connect() as connection:
  43. context.configure(connection=connection, target_metadata=target_metadata)
  44. with context.begin_transaction():
  45. context.run_migrations()
  46. if context.is_offline_mode():
  47. run_migrations_offline()
  48. else:
  49. run_migrations_online()