run_local_models_migrations.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. """
  2. 执行本地模型和开放平台相关的数据库迁移脚本
  3. 运行方式:
  4. python scripts/run_local_models_migrations.py
  5. 功能:
  6. - 执行3个数据库迁移文件
  7. - 扩展models表支持本地模型
  8. - 创建platform_api_key表
  9. - 创建api_call_log表
  10. """
  11. import os
  12. import sys
  13. from pathlib import Path
  14. # 添加项目根目录到Python路径
  15. project_root = Path(__file__).parent.parent
  16. sys.path.insert(0, str(project_root))
  17. from app.database import engine
  18. from sqlalchemy import text
  19. def run_migration_file(filepath: str) -> bool:
  20. """执行单个迁移文件"""
  21. try:
  22. with open(filepath, 'r', encoding='utf-8') as f:
  23. sql_content = f.read()
  24. with engine.connect() as conn:
  25. # 执行SQL(可能包含多个语句)
  26. conn.execute(text(sql_content))
  27. conn.commit()
  28. print(f"✅ 成功执行: {os.path.basename(filepath)}")
  29. return True
  30. except Exception as e:
  31. print(f"❌ 执行失败: {os.path.basename(filepath)}")
  32. print(f" 错误信息: {e}")
  33. return False
  34. def main():
  35. """主函数"""
  36. print("=" * 60)
  37. print("开始执行本地模型和开放平台数据库迁移")
  38. print("=" * 60)
  39. # 迁移文件列表(按顺序执行)
  40. migration_files = [
  41. "migrations/044_extend_models_for_local_models.sql",
  42. "migrations/045_create_platform_api_key_table.sql",
  43. "migrations/046_create_api_call_log_table.sql",
  44. ]
  45. success_count = 0
  46. failed_count = 0
  47. for migration_file in migration_files:
  48. filepath = project_root / migration_file
  49. if not filepath.exists():
  50. print(f"⚠️ 文件不存在: {migration_file}")
  51. failed_count += 1
  52. continue
  53. print(f"\n执行迁移: {migration_file}")
  54. if run_migration_file(str(filepath)):
  55. success_count += 1
  56. else:
  57. failed_count += 1
  58. print("\n" + "=" * 60)
  59. print(f"迁移完成: 成功 {success_count} 个, 失败 {failed_count} 个")
  60. print("=" * 60)
  61. if failed_count > 0:
  62. print("\n⚠️ 部分迁移失败,请检查错误信息")
  63. sys.exit(1)
  64. else:
  65. print("\n✅ 所有迁移成功执行!")
  66. print("\n变更内容:")
  67. print(" - models表扩展:is_local, user_id, base_url, local_api_key字段")
  68. print(" - platform_api_key表:平台API Key管理")
  69. print(" - api_call_log表:API调用日志")
  70. print("\n现在可以启动服务并测试本地模型和开放平台API")
  71. if __name__ == "__main__":
  72. main()