gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 17:00:40 25 4
gpt4 key购买 nike

我正在尝试改善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运行。我的解决方案针对空白数据库。

关于python - 如何检查是否需要生成Alembic迁移?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61374525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com