Flask数据迁移保留现有的表


在使用flask-migrate 进行数据迁移的过程中,会删除掉数据库中所有的表。因为在alembic的设定中:如果目标数据库存在不属于元数据的表,自动生成过程通常会假定这些表是数据库中的无用,并对每个表执行 Operations.drop _ table ()操作。

为了防止这种情况的出现,使用 EnvironmentContext.configure.include _ name 钩子进行过滤:

(The EnvironmentContext.configure.include_name hook is also most appropriate to limit the names of tables in the target database to be considered. If a target database has many tables that are not part of the MetaData, the autogenerate process will normally assume these are extraneous tables in the database to be dropped, and it will generate a Operations.drop_table() operation for each. To prevent this, the EnvironmentContext.configure.include_name hook may be used to search for each name within the tables collection of the MetaData object and ensure names which aren’t present are not included:)

from flask import current_app
'''
target_metadata 获取当前项目中所有的表数据
在 MetaData 对象的表集合中搜索每个名称,并确保不包含不存在的名称
'''
target_metadata = current_app.extensions['migrate'].db.metadata

def include_name(name, type_, parent_names):
    if type_ == "table":
        return name in target_metadata.tables
    else:
        return True

#默认会执行 run_migrations_online()函数,在context.configure配置以下几项
context.configure(
    # ...
    target_metadata = target_metadata,
    include_name = include_name,
    include_schemas = False
)

相关