Nik*_*yev 6 python continuous-integration sqlalchemy alembic
我正在尝试改进 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;
"""
)
Run Code Online (Sandbox Code Playgroud)
编辑:我注意到你链接了一个应该做同样事情的库。我尝试了一下,但似乎它假设运行检查的数据库必须已经对其运行了 alembic。我的解决方案适用于空白数据库。
编辑编辑:自从离开这个答案后,我发现了pytest-alembic提供此功能及更多功能的包。我个人没有用过,但看起来很甜。
有alembic-autogen-check可用的工具: https: //pypi.org/project/alembic-autogen-check/虽然它需要创建一个数据库来检查。
编辑(2023-06-01):alembic现在有check命令。
| 归档时间: |
|
| 查看次数: |
658 次 |
| 最近记录: |