migrate_process_equipment_id.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #!/usr/bin/env python3
  2. """按 equipment_name 精确匹配回填 equipment_ids。用法: python scripts/migrate_process_equipment_id.py [--dry-run]"""
  3. import argparse
  4. import os
  5. import sys
  6. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  7. from app.core.database import SessionLocal
  8. from app.models.models import BizEquipment, BizProcess, BizProcessRouteStep, BizProductionTaskStep
  9. TABLES = [
  10. ("biz_process", BizProcess),
  11. ("biz_process_route_step", BizProcessRouteStep),
  12. ("biz_production_task_step", BizProductionTaskStep),
  13. ]
  14. def _split_names(name: str) -> list[str]:
  15. text = (name or "").strip()
  16. if not text:
  17. return []
  18. for sep in ("、", ",", ";", ";", "|"):
  19. text = text.replace(sep, ",")
  20. return [x.strip() for x in text.split(",") if x.strip()]
  21. def migrate_table(db, model, dry_run: bool) -> int:
  22. updated = 0
  23. rows = db.query(model).filter(model.del_flag == 0, model.equipment_ids.is_(None)).all()
  24. for row in rows:
  25. names = _split_names(row.equipment_name)
  26. if not names:
  27. continue
  28. matched_ids: list[str] = []
  29. matched_names: list[str] = []
  30. for name in names:
  31. eq = (
  32. db.query(BizEquipment)
  33. .filter(
  34. BizEquipment.tenant_no == row.tenant_no,
  35. BizEquipment.del_flag == 0,
  36. BizEquipment.equipment_name == name,
  37. )
  38. .first()
  39. )
  40. if not eq:
  41. continue
  42. matched_ids.append(eq.id)
  43. matched_names.append(eq.equipment_name or name)
  44. if not matched_ids:
  45. continue
  46. if not dry_run:
  47. row.equipment_ids = ",".join(matched_ids)
  48. row.equipment_name = ",".join(matched_names)
  49. updated += 1
  50. return updated
  51. def main():
  52. parser = argparse.ArgumentParser()
  53. parser.add_argument("--dry-run", action="store_true")
  54. args = parser.parse_args()
  55. db = SessionLocal()
  56. try:
  57. for label, model in TABLES:
  58. n = migrate_table(db, model, args.dry_run)
  59. print(f"{label}: matched {n}")
  60. if not args.dry_run:
  61. db.commit()
  62. print("committed")
  63. else:
  64. print("dry-run, no commit")
  65. finally:
  66. db.close()
  67. if __name__ == "__main__":
  68. main()