| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- """
- 执行本地模型和开放平台相关的数据库迁移脚本
- 运行方式:
- python scripts/run_local_models_migrations.py
- 功能:
- - 执行3个数据库迁移文件
- - 扩展models表支持本地模型
- - 创建platform_api_key表
- - 创建api_call_log表
- """
- import os
- import sys
- from pathlib import Path
- # 添加项目根目录到Python路径
- project_root = Path(__file__).parent.parent
- sys.path.insert(0, str(project_root))
- from app.database import engine
- from sqlalchemy import text
- def run_migration_file(filepath: str) -> bool:
- """执行单个迁移文件"""
- try:
- with open(filepath, 'r', encoding='utf-8') as f:
- sql_content = f.read()
-
- with engine.connect() as conn:
- # 执行SQL(可能包含多个语句)
- conn.execute(text(sql_content))
- conn.commit()
-
- print(f"✅ 成功执行: {os.path.basename(filepath)}")
- return True
- except Exception as e:
- print(f"❌ 执行失败: {os.path.basename(filepath)}")
- print(f" 错误信息: {e}")
- return False
- def main():
- """主函数"""
- print("=" * 60)
- print("开始执行本地模型和开放平台数据库迁移")
- print("=" * 60)
-
- # 迁移文件列表(按顺序执行)
- migration_files = [
- "migrations/044_extend_models_for_local_models.sql",
- "migrations/045_create_platform_api_key_table.sql",
- "migrations/046_create_api_call_log_table.sql",
- ]
-
- success_count = 0
- failed_count = 0
-
- for migration_file in migration_files:
- filepath = project_root / migration_file
-
- if not filepath.exists():
- print(f"⚠️ 文件不存在: {migration_file}")
- failed_count += 1
- continue
-
- print(f"\n执行迁移: {migration_file}")
- if run_migration_file(str(filepath)):
- success_count += 1
- else:
- failed_count += 1
-
- print("\n" + "=" * 60)
- print(f"迁移完成: 成功 {success_count} 个, 失败 {failed_count} 个")
- print("=" * 60)
-
- if failed_count > 0:
- print("\n⚠️ 部分迁移失败,请检查错误信息")
- sys.exit(1)
- else:
- print("\n✅ 所有迁移成功执行!")
- print("\n变更内容:")
- print(" - models表扩展:is_local, user_id, base_url, local_api_key字段")
- print(" - platform_api_key表:平台API Key管理")
- print(" - api_call_log表:API调用日志")
- print("\n现在可以启动服务并测试本地模型和开放平台API")
- if __name__ == "__main__":
- main()
|