Alembic 无法识别 False 默认值

Alembic doesn't recognize False default value

在维护 SQLAlchemy 数据模型并利用 alembic 进行版本控制时,我所做的以下代码更改导致了一个空修订:

some_column = Column(Boolean, nullable=False, default=False)

之前是:

some_column = Column(Boolean, nullable=False)

因此添加默认值不会在 alembic 中产生任何变化,即生成一个空修订。我尝试了 SQLAlchemy 提供的其他值,例如 false()expression.false() 而不是 False,但结果是相同的(空的 alembic 修订版)。还尝试了 server_default 而不是 default。有问题的数据库是 PostgreSQL。

所谓的空修改,当然是指 alembic 无法识别 SQLAlchemy 中所做的任何更改:

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    pass
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    pass
    # ### end Alembic commands ###

感谢这方面的任何帮助。

要自动执行此操作,您必须启用检测服务器默认更改的设置。

在您的 env.py 中,对于 context.configure 调用(在线和离线迁移,因此在 2 处)添加一个 compare_server_default=True kwarg.

自己输入 alter_column 并且一定要使用 server_default 可能更安全,因为 default 仅用于默认的 python 侧设置(没关系,但听起来不是你想要的)。

引自https://alembic.sqlalchemy.org/en/latest/autogenerate.html#what-does-autogenerate-detect-and-what-does-it-not-detect

Autogenerate can optionally detect:

...

Change of server default. This will occur if you set the EnvironmentContext.configure.compare_server_default parameter to True, or to a custom callable function. This feature works well for simple cases but cannot always produce accurate results.

...