Fix alembic env crashing on URL-encoded password characters

Passing the DB URL through config.set_main_option() runs it through
ConfigParser, which treats '%' as interpolation syntax — so any password
character that URL-encodes to %xx ('!', '@', '#', ...) crashed migrations
('invalid interpolation syntax'). Build the engine directly from the URL
instead of routing it through the ini config.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
ang3l12
2026-07-13 13:58:06 -06:00
parent 45f1c56a52
commit ba6a61a5bf

View File

@@ -1,7 +1,7 @@
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
from sqlalchemy import create_engine, pool
from app.config import get_settings
from app.models import Base
@@ -10,13 +10,15 @@ config = context.config
if config.config_file_name is not None:
fileConfig(config.config_file_name)
config.set_main_option("sqlalchemy.url", get_settings().sync_database_url)
# The database URL is passed directly to SQLAlchemy rather than through
# config.set_main_option(): ConfigParser treats '%' as interpolation syntax,
# so URL-encoded password characters (e.g. '!' -> '%21') would blow up.
target_metadata = Base.metadata
def run_migrations_offline() -> None:
context.configure(
url=config.get_main_option("sqlalchemy.url"),
url=get_settings().sync_database_url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
@@ -26,15 +28,14 @@ def run_migrations_offline() -> None:
def run_migrations_online() -> None:
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
connectable = create_engine(
get_settings().sync_database_url, poolclass=pool.NullPool
)
with connectable.connect() as connection:
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
connectable.dispose()
if context.is_offline_mode():