| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165 |
- #!/usr/bin/env python3
- """
- 填充 `purchase_plans.executed_quantity` (当其为 NULL):
- - 默认连接本工程根目录下的 SQLite 数据库 `dibang.db`
- - 从 `weighing_slips` 表按 `purchase_plan_id` 求和 `net_weight`(只统计未作废的 is_voided=0)
- - 将求和结果写回 `purchase_plans.executed_quantity`
- 用法示例:
- python3 scripts/fill_missing_executed_quantity.py --db-type sqlite --db-path ./dibang.db
- python3 scripts/fill_missing_executed_quantity.py --db-type mysql --mysql-host host --mysql-user user --mysql-password pw --mysql-db dbname
- 注意:脚本默认不做单位换算(假定 `weighing_slips.net_weight` 与 `purchase_plans.executed_quantity` 使用相同单位,示例库中为 kg)。
- """
- from __future__ import annotations
- import argparse
- import sys
- from typing import Optional, Tuple
- def parse_args() -> argparse.Namespace:
- parser = argparse.ArgumentParser(
- description="Fill NULL executed_quantity in purchase_plans from weighing_slips.net_weight"
- )
- parser.add_argument("--db-type", choices=("sqlite", "mysql"), default="sqlite",
- help="数据库类型(默认 sqlite)")
- parser.add_argument("--db-path", default="./dibang.db",
- help="SQLite 数据库文件路径(仅 db-type=sqlite 时有效,默认 ./dibang.db)")
- # MySQL 选项
- parser.add_argument("--mysql-host", help="MySQL 主机")
- parser.add_argument("--mysql-port", type=int, default=3306, help="MySQL 端口")
- parser.add_argument("--mysql-user", help="MySQL 用户名")
- parser.add_argument("--mysql-password", help="MySQL 密码")
- parser.add_argument("--mysql-db", help="MySQL 数据库名")
- parser.add_argument("--dry-run", action="store_true", help="仅打印将要执行的更新,不提交")
- parser.add_argument("--verbose", "-v", action="store_true", help="显示详细输出")
- parser.add_argument("--print-sql", action="store_true", help="打印将要执行的 SQL 语句以便核对")
- return parser.parse_args()
- def connect_sqlite(db_path: str):
- import sqlite3
- conn = sqlite3.connect(db_path)
- # 使用 row factory 让查询结果更易读
- conn.row_factory = sqlite3.Row
- return conn
- def connect_mysql(host: str, port: int, user: str, password: str, db: str):
- try:
- import pymysql
- except Exception as exc: # pragma: no cover - runtime dependency may be missing
- raise RuntimeError("要使用 MySQL,请先安装 pymysql:pip install pymysql") from exc
- conn = pymysql.connect(host=host, port=port, user=user, password=password, database=db,
- cursorclass=pymysql.cursors.DictCursor, autocommit=False)
- return conn
- def fetch_plans_with_null_executed_quantity(conn) -> list[Tuple[int, Optional[float]]]:
- """
- 返回 purchase_plans 中 executed_quantity 为 NULL 的计划记录主键列表(id)
- """
- cur = conn.cursor()
- cur.execute("SELECT id, plan_no FROM purchase_plans WHERE executed_quantity IS NULL")
- rows = cur.fetchall()
- # rows may be sqlite3.Row or dict-like
- result = []
- for r in rows:
- plan_id = r["id"] if isinstance(r, dict) or hasattr(r, "__getitem__") else r[0]
- result.append((plan_id, r.get("plan_no") if isinstance(r, dict) or hasattr(r, "get") else None))
- return result
- def sum_net_weight_for_plan(conn, plan_id: int, placeholder: str, print_sql: bool = False) -> Optional[float]:
- cur = conn.cursor()
- # 只统计未作废的地磅单(is_voided = 0)
- 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)"
- if print_sql:
- # 显示替换后的 SQL 便于核对
- try:
- display_sql = sql.replace(placeholder, str(plan_id), 1)
- except Exception:
- display_sql = sql
- print(f"SQL: {display_sql}")
- cur.execute(sql, (plan_id,))
- row = cur.fetchone()
- # fetchone result shape differs: sqlite3 returns tuple, pymysql/dict returns dict
- if row is None:
- return None
- if isinstance(row, dict):
- return row.get("s") or 0.0
- # sqlite3.Row or tuple
- if hasattr(row, "keys") and "s" in row.keys():
- return row["s"] or 0.0
- # tuple-like
- return (row[0] if len(row) > 0 else None) or 0.0
- def update_executed_quantity(conn, plan_id: int, executed_qty: float, dry_run: bool = False):
- cur = conn.cursor()
- # 占位符会在调用处传入(? 或 %s)
- # 这里由调用者传入 placeholder 并决定是否打印 SQL
- raise RuntimeError("update_executed_quantity must be called with placeholder and print_sql flags")
- def main():
- args = parse_args()
- if args.db_type == "sqlite":
- conn = connect_sqlite(args.db_path)
- placeholder = "?"
- else:
- # mysql
- if not (args.mysql_host and args.mysql_user and args.mysql_password and args.mysql_db):
- print("MySQL 模式下必须提供 --mysql-host/--mysql-user/--mysql-password/--mysql-db", file=sys.stderr)
- sys.exit(2)
- conn = connect_mysql(args.mysql_host, args.mysql_port, args.mysql_user, args.mysql_password, args.mysql_db)
- placeholder = "%s"
- try:
- plans = fetch_plans_with_null_executed_quantity(conn)
- if args.verbose:
- print(f"Found {len(plans)} purchase_plans with executed_quantity IS NULL")
- updated = 0
- for plan_id, plan_no in plans:
- sum_net = sum_net_weight_for_plan(conn, plan_id, placeholder, args.print_sql)
- if sum_net is None:
- if args.verbose:
- print(f"plan id={plan_id} plan_no={plan_no}: no weighing_slips found")
- continue
- # sum_net is in same unit as net_weight (assumed kg)
- if args.verbose:
- print(f"plan id={plan_id} plan_no={plan_no}: sum(net_weight)={sum_net}")
- # 准备并打印/执行 UPDATE 语句
- update_sql = f"UPDATE purchase_plans SET executed_quantity = {placeholder} WHERE id = {placeholder}"
- if args.print_sql or args.dry_run:
- # 为便于核对,显示替换后的 SQL(数值已内联)
- try:
- display_update_sql = update_sql.replace(placeholder, str(sum_net), 1).replace(placeholder, str(plan_id), 1)
- except Exception:
- display_update_sql = update_sql
- print(f"SQL: {display_update_sql}")
- if not args.dry_run:
- cur = conn.cursor()
- cur.execute(f"UPDATE purchase_plans SET executed_quantity = {placeholder} WHERE id = {placeholder}", (sum_net, plan_id))
- updated += 1
- if args.dry_run:
- print(f"[DRY RUN] Processed {len(plans)} plans, {updated} would be updated.")
- # do not commit
- else:
- conn.commit()
- print(f"Updated {updated} purchase_plans' executed_quantity.")
- finally:
- conn.close()
- if __name__ == "__main__":
- main()
|