如何更新 Python 中的表方案,仅使用 Python(无 CLI)

How to update tables schemes in Python, using only Python (No CLI)

我正在使用 SQL Alchemy,并希望在不使用 CLI 的情况下自动更新表格方案(我的代码结构阻止了它) 我也不需要存储迁移文件。 我一直在寻找 Alembic,它似乎是执行此操作的最佳工具。但是,如果不使用 CLI,我找不到正确的流程或说明如何操作。 我最接近的来自这个: How to run a migration with Python Alembic by code? 但是,即使有解决方案,仍然会出现相同的错误。 我正在考虑使用 autogenerate.produce_migrations(alembic_context, metadata) 来获取操作(效果很好),但是如何执行这些操作呢? 谢谢

终于找到了。下面代码

from alembic import autogenerate, util
from alembic.config import Config

from alembic.runtime.environment import EnvironmentContext
from alembic.script import ScriptDirectory
config = Config()

config.set_main_option("script_location", <script location>)

alembic_script = ScriptDirectory.from_config(config)
environment = EnvironmentContext(config, alembic_script)

with metadata.bind.connect() as connection:
    environment.configure(
        connection=connection,
        target_metadata=metadata,
        fn=fn,
        include_object=include_object
    )

    migrations = autogenerate.produce_migrations(context=environment.get_context(),
                                                 metadata=metadata)
    alembic_script.generate_revision(util.rev_id(), "update table",
                                     upgrades=autogenerate.render_python_code(migrations.upgrade_ops))

    with environment.begin_transaction():
        environment.run_migrations()


def fn(revision, context):
    script = ScriptDirectory.from_config(context.config)
    return script._upgrade_revs(script.get_heads(), revision)


def include_object(object, name, type_, reflected, compare_to):
    if type_ == "table" and reflected and compare_to is None:
        return False
    else:
        return True

备注:

  • include_object 选项确保没有 table 被删除。然后它是可选的

  • 将 <'script location'> 替换为 alembic 的路径。该目录必须包含一个方向“versions”和一个文件script.py.mako。调用一次cli即可自动生成此类数据alembic init <root path of data>

  • 此类代码不处理多个分支和降级:我认为处理这些代码不会那么复杂

  • 所有这些代码都可以在一个函数中调用,具有单个元数据输入(必须绑定到引擎)。