backfill_intimacy_hearts.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. """
  2. 一次性脚本:为历史用户补 3 颗心(在 user_intimacy 中插入 heart_count=3,仅当该用户尚无记录时)。
  3. 运行前请确保已执行 migrate_add_user_intimacy_table.py 创建 user_intimacy 表。
  4. """
  5. import asyncio
  6. import sys
  7. from pathlib import Path
  8. # 将 backend 加入 path,支持从项目根或 backend 目录运行
  9. _backend = Path(__file__).resolve().parent.parent / "backend"
  10. if _backend.exists() and str(_backend) not in sys.path:
  11. sys.path.insert(0, str(_backend))
  12. import aiomysql
  13. from config import settings
  14. async def backfill_intimacy_hearts() -> bool:
  15. """为所有在 users 表中存在且尚未在 user_intimacy 中有记录的用户插入 heart_count=3"""
  16. try:
  17. conn: aiomysql.Connection = await aiomysql.connect(
  18. host=settings.MYSQL_HOST,
  19. port=settings.MYSQL_PORT,
  20. user=settings.MYSQL_USER,
  21. password=settings.MYSQL_PASSWORD,
  22. db=settings.MYSQL_DATABASE,
  23. charset="utf8mb4",
  24. )
  25. async with conn.cursor() as cursor:
  26. # 使用 COLLATE 统一排序规则,避免 users 与 user_intimacy 的 utf8mb4_unicode_ci / utf8mb4_general_ci 混用报错
  27. await cursor.execute(
  28. """
  29. INSERT INTO user_intimacy (user_id, heart_count)
  30. SELECT u.user_id, 3
  31. FROM users u
  32. LEFT JOIN user_intimacy i ON u.user_id = i.user_id COLLATE utf8mb4_unicode_ci
  33. WHERE i.user_id IS NULL
  34. """
  35. )
  36. affected = cursor.rowcount
  37. await conn.commit()
  38. print(f"✅ 已为 {affected} 个历史用户补 3 颗心")
  39. await conn.ensure_closed()
  40. return True
  41. except Exception as exc:
  42. print(f"❌ 脚本执行失败: {exc}")
  43. import traceback
  44. traceback.print_exc()
  45. return False
  46. if __name__ == "__main__":
  47. ok = asyncio.run(backfill_intimacy_hearts())
  48. sys.exit(0 if ok else 1)