def migrate_via_alembic():
    """ 自动迁移，通过 alembic 实现 """
    def process_revision_directives(context, revision, directives):
        """ 如果无改变，不生成迁移脚本 """
        script = directives[0]
        if script.upgrade_ops.is_empty():
            directives[:] = []
    alembic_cfg = config.Config()
    # 获取脚本路径
    script_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "migration")
    versions_scripts_path = os.path.join(script_path, 'versions')
    if not os.path.exists(versions_scripts_path):
        os.makedirs(versions_scripts_path, 0o700)
    alembic_cfg.set_main_option('script_location', script_path)
    command.stamp(alembic_cfg, 'head', purge=True)  # 将当前标记为最新版
    scripts = command.revision(  # 自动生成迁移脚本
        alembic_cfg,
        autogenerate=True,
        process_revision_directives=process_revision_directives
    )
    if not scripts:
        print("数据库已是最新版本")
        return
    command.upgrade(alembic_cfg, 'head')
    print("检测到旧版数据库，已完成自动迁移")
自动迁移，通过 alembic 实现
biliup/database/db.py