Alembic Config does work properly with sqlalchemy.URL #1490
-
Describe the bug
Expected behavior It should work, or a workaround be documented, especially that context.configure has signature To Reproduce Versions.
Additional context
from logging.config import fileConfig
from alembic import context
from app.database import Base
from settings import DB_URL
from sqlalchemy import engine_from_config
from sqlalchemy import pool
config = context.config
if config.config_file_name is not None:
fileConfig(config.config_file_name)
target_metadata = Base.metadata
def run_migrations_offline() -> None:
context.configure(
url=DB_URL,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
configuration = config.get_section(config.config_ini_section, {})
configuration["sqlalchemy.url"] = DB_URL
connectable = engine_from_config(
configuration=configuration,
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online() Have a nice day! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
there is no need to pass the URL to the config. once you're in the env.py, use the programmatically generated URL directly and your code is correct (with the possible exception that you likely should use create_engine directly, rather than engine_from_config which appears unnecessary). This is how alembic's own recipes propose working with various ways of constructing connections. |
Beta Was this translation helpful? Give feedback.
there is no need to pass the URL to the config. once you're in the env.py, use the programmatically generated URL directly and your code is correct (with the possible exception that you likely should use create_engine directly, rather than engine_from_config which appears unnecessary). This is how alembic's own recipes propose working with various ways of constructing connections.