migrate_llm_tasks_init.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. """
  2. LLM 任务表:建表 + 种子 Task 01 + lumi_first_line 列迁移
  3. 运行(在 backend 目录): python migrations/migrate_llm_tasks_init.py
  4. """
  5. import asyncio
  6. import sys
  7. from pathlib import Path
  8. from typing import Any
  9. sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
  10. import aiomysql
  11. from config import settings
  12. from data.ab_task_01_prompt import TASK_01_NAME, TASK_01_PROMPT, TASK_01_FIRST_LINE
  13. MIGRATIONS_DIR = Path(__file__).resolve().parent
  14. async def table_exists(cursor: Any) -> bool:
  15. await cursor.execute(
  16. """
  17. SELECT COUNT(*) FROM information_schema.tables
  18. WHERE table_schema = %s AND table_name = 'llm_tasks'
  19. """,
  20. (settings.MYSQL_DATABASE,),
  21. )
  22. row = await cursor.fetchone()
  23. return bool(row and row[0] > 0)
  24. async def column_exists(cursor: Any, column_name: str) -> bool:
  25. await cursor.execute(
  26. """
  27. SELECT COUNT(*) FROM information_schema.columns
  28. WHERE table_schema = %s AND table_name = 'llm_tasks' AND column_name = %s
  29. """,
  30. (settings.MYSQL_DATABASE, column_name),
  31. )
  32. row = await cursor.fetchone()
  33. return bool(row and row[0] > 0)
  34. async def seed_exists(cursor: Any) -> bool:
  35. await cursor.execute("SELECT COUNT(*) FROM llm_tasks WHERE task_name = %s", (TASK_01_NAME,))
  36. row = await cursor.fetchone()
  37. return bool(row and row[0] > 0)
  38. async def migrate() -> bool:
  39. try:
  40. conn: aiomysql.Connection = await aiomysql.connect(
  41. host=settings.MYSQL_HOST,
  42. port=settings.MYSQL_PORT,
  43. user=settings.MYSQL_USER,
  44. password=settings.MYSQL_PASSWORD,
  45. db=settings.MYSQL_DATABASE,
  46. charset="utf8mb4",
  47. )
  48. async with conn.cursor() as cursor:
  49. if not await table_exists(cursor):
  50. print("🔄 创建 llm_tasks 表...")
  51. ddl = (MIGRATIONS_DIR / "add_llm_tasks_table.sql").read_text(encoding="utf-8")
  52. create_part = ddl.split("INSERT INTO", 1)[0]
  53. for stmt in [s.strip() for s in create_part.split(";") if s.strip()]:
  54. if stmt.upper().startswith("SET NAMES"):
  55. continue
  56. await cursor.execute(stmt)
  57. await conn.commit()
  58. print("✅ llm_tasks 表创建完成")
  59. else:
  60. print("✅ llm_tasks 表已存在")
  61. if not await column_exists(cursor, "lumi_first_line"):
  62. print("🔄 添加 lumi_first_line 列...")
  63. alter_sql = (MIGRATIONS_DIR / "add_llm_tasks_lumi_first_line.sql").read_text(encoding="utf-8")
  64. for stmt in [s.strip() for s in alter_sql.split(";") if s.strip()]:
  65. if stmt.upper().startswith("SET NAMES"):
  66. continue
  67. await cursor.execute(stmt)
  68. await conn.commit()
  69. print("✅ lumi_first_line 列已添加")
  70. else:
  71. print("✅ lumi_first_line 列已存在")
  72. if not await seed_exists(cursor):
  73. print("🔄 插入 Task 01 种子数据...")
  74. await cursor.execute(
  75. "INSERT INTO llm_tasks (task_name, task_prompt, lumi_first_line) VALUES (%s, %s, %s)",
  76. (TASK_01_NAME, TASK_01_PROMPT, TASK_01_FIRST_LINE),
  77. )
  78. await conn.commit()
  79. print("✅ Task 01 已写入")
  80. else:
  81. print("✅ Task 01 已存在,跳过插入")
  82. await cursor.execute(
  83. """
  84. UPDATE llm_tasks
  85. SET lumi_first_line = %s
  86. WHERE task_name = %s
  87. AND (lumi_first_line IS NULL OR lumi_first_line = '')
  88. """,
  89. (TASK_01_FIRST_LINE, TASK_01_NAME),
  90. )
  91. await conn.commit()
  92. await cursor.execute(
  93. "SELECT id, task_name, lumi_first_line, created_at FROM llm_tasks ORDER BY created_at DESC LIMIT 1"
  94. )
  95. latest = await cursor.fetchone()
  96. print("📊 当前最新任务:", latest)
  97. conn.close()
  98. return True
  99. except Exception:
  100. import traceback
  101. traceback.print_exc()
  102. return False
  103. if __name__ == "__main__":
  104. ok = asyncio.run(migrate())
  105. sys.exit(0 if ok else 1)