如果没有检测到任何更改,如何防止 alembic revision --autogenerate 创建修订文件?

mmw*_*way 6 python migration revision alembic

我有一个项目,我正在使用 SQLAlchemy 进行模型,并且我正在尝试集成 Alembic 来进行迁移。当我更改模型时,一切都按预期工作,并且 Alembic 看到模型已更改 -> 它使用命令创建良好的迁移文件: alembic revision --autogenerate -m "model changed"

但是当我没有更改模型中的任何内容并且我使用相同的命令时:

alembic revision --autogenerate -m "should be no migration"

revision 给了我“空”修订文件,如下所示:

"""next

Revision ID: d06d2a8fed5d
Revises: 4461d5328f57
Create Date: 2021-12-02 18:09:42.208607

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = 'd06d2a8fed5d'
down_revision = '4461d5328f57'
branch_labels = None
depends_on = None


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 ###
Run Code Online (Sandbox Code Playgroud)

该文件的目的是什么?当 alembic revision --autogenerate 看不到任何更改时,我可以阻止创建此“空文件”吗?比较我使用 Django 时和输入命令时的内部迁移:

python manage.py makemigrations

我得到类似的输出:

No changes detected

并且没有创建迁移文件。有没有办法对 Alembic 修订版做同样的事情?或者是否有其他命令可以检查模型是否有更改,如果有,那么我可以简单地运行 alembic 修订和升级?

iai*_*air 7

接受的答案没有回答问题。正确的答案是:是的,您可以调用alembic revision --autogenerate并确保仅在发生更改时才会生成修订文件:

根据 Alembic 的文档

在 Flask-Migrate 中实现(正是在这个文件中),它只是对 env.py 进行更改以考虑所需的功能,即如果模型没有更改,则不会自动生成修订版。

您仍然会运行alembic revision --autogenerate -m "should be no migration",但您将对 env.py 进行的更改简而言之:

    def run_migrations_online():
        # almost identical to Flask-Migrate (Thanks miguel!)    
        # this callback is used to prevent an auto-migration from being generated
        # when there are no changes to the schema
    
        def process_revision_directives(context, revision, directives):
            if config.cmd_opts.autogenerate:
                script = directives[0]
                if script.upgrade_ops.is_empty():
                    directives[:] = []
                    print('No changes in schema detected.')
    
        connectable = engine_from_config(
            config.get_section(config.config_ini_section),
            prefix="sqlalchemy.",
            poolclass=pool.NullPool,
        )
    
        with connectable.connect() as connection:
            context.configure(
                connection=connection,
                target_metadata=target_metadata,
                process_revision_directives=process_revision_directives
            )
    
            with context.begin_transaction():
                context.run_migrations() 
Run Code Online (Sandbox Code Playgroud)

现在,您可以轻松调用,alembic revision --autogenerate而无需冒创建新的空修订版的风险。