fix_steam_link.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. """
  2. 修复 buff_selection_request_item 表中 steam_link 为空的数据
  3. 从 buff_goods_info 表获取 steam_url 填充
  4. """
  5. from sqlalchemy import text
  6. from app.database import SessionLocal
  7. def fix_steam_links():
  8. """修复 steam_link 为空的记录"""
  9. db = SessionLocal()
  10. try:
  11. # 1. 查询 steam_link 为空的记录
  12. query = text("""
  13. SELECT DISTINCT sri.id, sri.goods_id, sri.goods_name
  14. FROM buff_selection_request_item sri
  15. LEFT JOIN buff_goods_info bgi ON sri.goods_id = bgi.goods_id
  16. WHERE sri.steam_link = '' OR sri.steam_link IS NULL
  17. HAVING bgi.steam_url IS NOT NULL AND bgi.steam_url != ''
  18. """)
  19. # 分步执行
  20. empty_items = db.execute(text("""
  21. SELECT id, goods_id, goods_name
  22. FROM buff_selection_request_item
  23. WHERE steam_link = '' OR steam_link IS NULL
  24. """)).fetchall()
  25. print(f"找到 {len(empty_items)} 条 steam_link 为空的记录")
  26. fixed_count = 0
  27. for item in empty_items:
  28. item_id, goods_id, goods_name = item
  29. # 从 buff_goods_info 查询 steam_url
  30. result = db.execute(text("""
  31. SELECT steam_url FROM buff_goods_info
  32. WHERE goods_id = :goods_id AND steam_url IS NOT NULL AND steam_url != ''
  33. """), {"goods_id": goods_id}).fetchone()
  34. if result:
  35. steam_url = result[0]
  36. db.execute(text("""
  37. UPDATE buff_selection_request_item
  38. SET steam_link = :steam_url
  39. WHERE id = :item_id
  40. """), {"steam_url": steam_url, "item_id": item_id})
  41. fixed_count += 1
  42. print(f" 修复: id={item_id}, goods_id={goods_id}, steam_url={steam_url[:50]}...")
  43. db.commit()
  44. print(f"\n共修复 {fixed_count} 条记录")
  45. return fixed_count
  46. except Exception as e:
  47. db.rollback()
  48. print(f"修复失败: {e}")
  49. raise
  50. finally:
  51. db.close()
  52. if __name__ == "__main__":
  53. fix_steam_links()