env.py 2.0 KB

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