使用 alembic 自动生成时忽略模型

2024-04-18

我正在尝试使用自动生成数据库的修订版本alembic。这样做时,我想忽略一些模型(它们具有当前版本的 MySQL 不支持的数据类型)。这是我尝试过的方法,似乎工作正常,但我不确定这是最惯用的方法

inside alembic/env.py

def include_object(object, type_, name, reflected, compare_to):
    if type_ == 'table' and name == 'model_to_be_ignored':
        return False
    return True

然后里面run_migrations_online and run_migrations_offline I gave include_object=include_object这似乎工作正常。

理想情况下我想使用skip_autogenerate=True,但不确定我可以定义它,以便稍后我可以简单地删除该行models.py并在升级到较新版本的数据库时获得我想要的行为。

我有什么遗漏的吗?


据我所知,skip_autogenerateAlembic 和 SQLAlchemy 都不会自动处理。但你可以将其添加到Table.info像这样:

  1. 定义一个 mixin 添加skip_autogenerate to Table.info。这是基于 Flask-SQLAlchemy 的绑定元混合 https://github.com/minisotm/flask-sqlalchemy/blob/master/flask_sqlalchemy/model.py#L114
class ModelInfoMetaMixin(object):
    def __init__(cls, name, bases, d):
        skip_autogenerate = d.pop("__skip_autogenerate__", None)

        super(ModelInfoMetaMixin, cls).__init__(name, bases, d)

        if skip_autogenerate is not None and getattr(cls, "__table__", None) is not None:
            cls.__table__.info["skip_autogenerate"] = skip_autogenerate
  1. 使用这个 mixin 定义一个元类并将其传递给declarative_base()
from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base

class DefaultMeta(ModelInfoMetaMixin, DeclarativeMeta):
    pass

Model = declarative_base(cls=BaseModel, metaclass=DefaultMeta)
  1. 然后您可以使用此标记定义您的模型:
class OneModel(Model):
    __skip_autogenerate__ = True
    uuid = Column(UUID(as_uuid=True), primary_key=True)
  1. 最后,skip_autogenerate将在 Alembic 中提供include_object:
def include_object(object, name, type_, reflected, compare_to):
    # skip objects marked with "skip_autogenerate"
    if object.info.get("skip_autogenerate", False):
        return False

    return True
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 alembic 自动生成时忽略模型 的相关文章

随机推荐