fill_missing_executed_quantity.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. #!/usr/bin/env python3
  2. """
  3. 填充 `purchase_plans.executed_quantity` (当其为 NULL):
  4. - 默认连接本工程根目录下的 SQLite 数据库 `dibang.db`
  5. - 从 `weighing_slips` 表按 `purchase_plan_id` 求和 `net_weight`(只统计未作废的 is_voided=0)
  6. - 将求和结果写回 `purchase_plans.executed_quantity`
  7. 用法示例:
  8. python3 scripts/fill_missing_executed_quantity.py --db-type sqlite --db-path ./dibang.db
  9. python3 scripts/fill_missing_executed_quantity.py --db-type mysql --mysql-host host --mysql-user user --mysql-password pw --mysql-db dbname
  10. 注意:脚本默认不做单位换算(假定 `weighing_slips.net_weight` 与 `purchase_plans.executed_quantity` 使用相同单位,示例库中为 kg)。
  11. """
  12. from __future__ import annotations
  13. import argparse
  14. import sys
  15. from typing import Optional, Tuple
  16. def parse_args() -> argparse.Namespace:
  17. parser = argparse.ArgumentParser(
  18. description="Fill NULL executed_quantity in purchase_plans from weighing_slips.net_weight"
  19. )
  20. parser.add_argument("--db-type", choices=("sqlite", "mysql"), default="sqlite",
  21. help="数据库类型(默认 sqlite)")
  22. parser.add_argument("--db-path", default="./dibang.db",
  23. help="SQLite 数据库文件路径(仅 db-type=sqlite 时有效,默认 ./dibang.db)")
  24. # MySQL 选项
  25. parser.add_argument("--mysql-host", help="MySQL 主机")
  26. parser.add_argument("--mysql-port", type=int, default=3306, help="MySQL 端口")
  27. parser.add_argument("--mysql-user", help="MySQL 用户名")
  28. parser.add_argument("--mysql-password", help="MySQL 密码")
  29. parser.add_argument("--mysql-db", help="MySQL 数据库名")
  30. parser.add_argument("--dry-run", action="store_true", help="仅打印将要执行的更新,不提交")
  31. parser.add_argument("--verbose", "-v", action="store_true", help="显示详细输出")
  32. parser.add_argument("--print-sql", action="store_true", help="打印将要执行的 SQL 语句以便核对")
  33. return parser.parse_args()
  34. def connect_sqlite(db_path: str):
  35. import sqlite3
  36. conn = sqlite3.connect(db_path)
  37. # 使用 row factory 让查询结果更易读
  38. conn.row_factory = sqlite3.Row
  39. return conn
  40. def connect_mysql(host: str, port: int, user: str, password: str, db: str):
  41. try:
  42. import pymysql
  43. except Exception as exc: # pragma: no cover - runtime dependency may be missing
  44. raise RuntimeError("要使用 MySQL,请先安装 pymysql:pip install pymysql") from exc
  45. conn = pymysql.connect(host=host, port=port, user=user, password=password, database=db,
  46. cursorclass=pymysql.cursors.DictCursor, autocommit=False)
  47. return conn
  48. def fetch_plans_with_null_executed_quantity(conn) -> list[Tuple[int, Optional[float]]]:
  49. """
  50. 返回 purchase_plans 中 executed_quantity 为 NULL 的计划记录主键列表(id)
  51. """
  52. cur = conn.cursor()
  53. cur.execute("SELECT id, plan_no FROM purchase_plans WHERE executed_quantity IS NULL")
  54. rows = cur.fetchall()
  55. # rows may be sqlite3.Row or dict-like
  56. result = []
  57. for r in rows:
  58. plan_id = r["id"] if isinstance(r, dict) or hasattr(r, "__getitem__") else r[0]
  59. result.append((plan_id, r.get("plan_no") if isinstance(r, dict) or hasattr(r, "get") else None))
  60. return result
  61. def sum_net_weight_for_plan(conn, plan_id: int, placeholder: str, print_sql: bool = False) -> Optional[float]:
  62. cur = conn.cursor()
  63. # 只统计未作废的地磅单(is_voided = 0)
  64. sql = f"SELECT SUM(net_weight) as s FROM weighing_slips WHERE purchase_plan_id = {placeholder} AND (is_voided IS NULL OR is_voided = 0)"
  65. if print_sql:
  66. # 显示替换后的 SQL 便于核对
  67. try:
  68. display_sql = sql.replace(placeholder, str(plan_id), 1)
  69. except Exception:
  70. display_sql = sql
  71. print(f"SQL: {display_sql}")
  72. cur.execute(sql, (plan_id,))
  73. row = cur.fetchone()
  74. # fetchone result shape differs: sqlite3 returns tuple, pymysql/dict returns dict
  75. if row is None:
  76. return None
  77. if isinstance(row, dict):
  78. return row.get("s") or 0.0
  79. # sqlite3.Row or tuple
  80. if hasattr(row, "keys") and "s" in row.keys():
  81. return row["s"] or 0.0
  82. # tuple-like
  83. return (row[0] if len(row) > 0 else None) or 0.0
  84. def update_executed_quantity(conn, plan_id: int, executed_qty: float, dry_run: bool = False):
  85. cur = conn.cursor()
  86. # 占位符会在调用处传入(? 或 %s)
  87. # 这里由调用者传入 placeholder 并决定是否打印 SQL
  88. raise RuntimeError("update_executed_quantity must be called with placeholder and print_sql flags")
  89. def main():
  90. args = parse_args()
  91. if args.db_type == "sqlite":
  92. conn = connect_sqlite(args.db_path)
  93. placeholder = "?"
  94. else:
  95. # mysql
  96. if not (args.mysql_host and args.mysql_user and args.mysql_password and args.mysql_db):
  97. print("MySQL 模式下必须提供 --mysql-host/--mysql-user/--mysql-password/--mysql-db", file=sys.stderr)
  98. sys.exit(2)
  99. conn = connect_mysql(args.mysql_host, args.mysql_port, args.mysql_user, args.mysql_password, args.mysql_db)
  100. placeholder = "%s"
  101. try:
  102. plans = fetch_plans_with_null_executed_quantity(conn)
  103. if args.verbose:
  104. print(f"Found {len(plans)} purchase_plans with executed_quantity IS NULL")
  105. updated = 0
  106. for plan_id, plan_no in plans:
  107. sum_net = sum_net_weight_for_plan(conn, plan_id, placeholder, args.print_sql)
  108. if sum_net is None:
  109. if args.verbose:
  110. print(f"plan id={plan_id} plan_no={plan_no}: no weighing_slips found")
  111. continue
  112. # sum_net is in same unit as net_weight (assumed kg)
  113. if args.verbose:
  114. print(f"plan id={plan_id} plan_no={plan_no}: sum(net_weight)={sum_net}")
  115. # 准备并打印/执行 UPDATE 语句
  116. update_sql = f"UPDATE purchase_plans SET executed_quantity = {placeholder} WHERE id = {placeholder}"
  117. if args.print_sql or args.dry_run:
  118. # 为便于核对,显示替换后的 SQL(数值已内联)
  119. try:
  120. display_update_sql = update_sql.replace(placeholder, str(sum_net), 1).replace(placeholder, str(plan_id), 1)
  121. except Exception:
  122. display_update_sql = update_sql
  123. print(f"SQL: {display_update_sql}")
  124. if not args.dry_run:
  125. cur = conn.cursor()
  126. cur.execute(f"UPDATE purchase_plans SET executed_quantity = {placeholder} WHERE id = {placeholder}", (sum_net, plan_id))
  127. updated += 1
  128. if args.dry_run:
  129. print(f"[DRY RUN] Processed {len(plans)} plans, {updated} would be updated.")
  130. # do not commit
  131. else:
  132. conn.commit()
  133. print(f"Updated {updated} purchase_plans' executed_quantity.")
  134. finally:
  135. conn.close()
  136. if __name__ == "__main__":
  137. main()