如何检查是否需要生成 Alembic 迁移?

How do I check if Alembic migrations need to be generated?

我正在尝试改进 CI 管道,以防止添加或更改 SQLAlchemy 模型但提交作者编写或生成的 Alembic 迁移不会到达生产分支的情况。

alembic --help 似乎没有为这种情况提供任何有用的命令,但它已经具有所需的所有元数据(target_metadata 变量)和 env.py 中的数据库凭据让这一切成为现实。

在 CI 中实施此检查的最佳做法是什么?

这是我使用的解决方案。这是我作为测试实施的检查。

from alembic.autogenerate import compare_metadata
from alembic.command import upgrade
from alembic.runtime.migration import MigrationContext
from alembic.config import Config

from models.base import Base


def test_migrations_sane():
    """
    This test ensures that models defined by SQLAlchemy match what alembic migrations think
    the database should look like. If these are different, then once we have constructed
    the database via Alembic (via running all migrations) alembic will generate a set of changes to
    modify the database to match the schema defined by SQLAlchemy models. If these are the same,
    the set of changes is going to be empty. Which is exactly what we want to check.
    """
    engine = "SQLAlchemy DB Engine instance"
    try:
        with engine.connect() as connection:
            alembic_conf_file = "location of alembic.ini"
            alembic_config = Config(alembic_conf_file)
            upgrade(alembic_config, "head")
            mc = MigrationContext.configure(connection)
            diff = compare_metadata(mc, Base.metadata)

            assert diff == []
    finally:
        with engine.connect() as connection:
            # Resetting the DB
            connection.execute(
                """
                DROP SCHEMA public CASCADE;
                CREATE SCHEMA public;
                GRANT ALL ON SCHEMA public TO postgres;
                GRANT ALL ON SCHEMA public TO public;
                """
            )

编辑:我注意到您链接了一个应该做同样事情的图书馆。我试了一下,但它似乎假设它 运行 正在检查的数据库必须有 alembic 运行 反对它。我的解决方案适用于空白数据库。

alembic-autogen-check工具可用:https://pypi.org/project/alembic-autogen-check/虽然它需要创建一个数据库来检查。