fastapi: alembic检测不到server_default的修改

一,compare_server_default=True 通常在哪里设置?


通常设置在 [alembic/env.py (line 60)] 的 context.configure(...) 中,
不是在模型或 alembic.ini 里自动生效。

def do_run_migrations(connection: Connection) -> None:
    context.configure(
        connection=connection,
        target_metadata=target_metadata,
        compare_server_default=True,
    )

    with context.begin_transaction():
        context.run_migrations()

离线模式也应同步设置:

context.configure(
    url=url,
    target_metadata=target_metadata,
    literal_binds=True,
    dialect_opts={"paramstyle": "named"},
    compare_server_default=True,
)

 

二,最终效果:

def run_migrations_offline() -> None:
    """Run migrations in 'offline' mode.

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
    we don't even need a DBAPI to be available.

    Calls to context.execute() here emit the given string to the
    script output.

    """
    url = config.get_main_option("sqlalchemy.url")
    context.configure(
        url=url,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
        compare_server_default=True,
    )

    with context.begin_transaction():
        context.run_migrations()


def do_run_migrations(connection: Connection) -> None:
    context.configure(connection=connection, target_metadata=target_metadata, compare_server_default=True)

    with context.begin_transaction():
        context.run_migrations()

 

posted @ 2026-11-21 20:20  刘宏缔的架构森林  阅读(7)  评论(0)    收藏  举报