在批处理模式下使用 Alembic 更改 sa.Column 可空 属性

Change sa.Column nullable property with Alembic in Batch mode

我有一个数据库升级迁移我想应用到数据库列:

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('details') as batch_op:
        batch_op.alter_column('details', 'non_essential_cookies',
                              existing_type=sa.BOOLEAN(),
                              nullable=False)
    # ### end Alembic commands ###

我正在实施批处理模式,因为 ALTER 不受支持,之前我收到此错误:sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) near "ALTER":。但是,我希望批处理模式可以工作,但现在我收到了新错误:

TypeError: <flask_script.commands.Command object at 0x1149bb278>: alter_column() got multiple values for argument 'nullable'.

我在table中只有一个元组,相关属性不为NULL,所以数据库迁移是有效的。就是不明白为什么会有多个值

来自 docs:

The method is used as a context manager, which returns an instance of BatchOperations; this object is the same as Operations except that table names and schema names are omitted.

这里的关键点是在 BatchOperations 实例上调用操作时不必提供 table 名称。

alter_column 的签名是:

alter_column(table_name, column_name, nullable=None, server_default=False, new_column_name=None, type_=None, existing_type=None, existing_server_default=False, existing_nullable=None, schema=None, **kw)

所以从你的代码来看:

with op.batch_alter_table('details') as batch_op:
        batch_op.alter_column('details', 'non_essential_cookies',
                              existing_type=sa.BOOLEAN(),
                              nullable=False)

'details' 被传递给 column_name'non_essential_cookies' 作为位置参数被传递给 nullable。稍后当您使用关键字 arg,nullable=False.

再次指定 nullable 的值时会导致此问题