From 3bfc73b43ccd1cb7ef068a5438dbcc5749d4c2ff Mon Sep 17 00:00:00 2001 From: admin <2775444633@qq.com> Date: Tue, 24 Nov 2026 17:06:03 +0000 Subject: [PATCH] chore: sync warehouse/etl/extract_mysql_to_s3.py --- warehouse/etl/extract_mysql_to_s3.py | 115 +++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 warehouse/etl/extract_mysql_to_s3.py diff --git a/warehouse/etl/extract_mysql_to_s3.py b/warehouse/etl/extract_mysql_to_s3.py new file mode 100644 index 0000000..9797d12 --- /dev/null +++ b/warehouse/etl/extract_mysql_to_s3.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +"""mini_erp (WSL MySQL) -> MinIO(Parquet) 按天增量抽取。 + +模式: + snapshot 维表/库存余额全量快照 -> ods/mini_erp//dt=/ + incremental 单据/流水按时间窗增量 -> 同上(幂等: 先清分区再写) + +幂等: 同一 bizdate 重跑覆盖同一分区目录, 结果只取决于源库当前状态。 +""" +import argparse, io, json, os, sys +from datetime import date, datetime, timedelta + +import boto3 +import pymysql +import pyarrow as pa +import pyarrow.parquet as pq + +ERP = dict(host=os.getenv("ERP_MYSQL_HOST", "192.168.50.176"), port=int(os.getenv("ERP_MYSQL_PORT", "3308")), + user="erp", password="erp_pass_123", database="mini_erp", charset="utf8mb4") +S3 = dict(endpoint="http://192.168.50.177:9000", key="admin", secret="StrongPassword123!", bucket="warehouse") + +V_STR = pa.string() +V_INT = pa.int64() +V_DBL = pa.float64() +V_DT = pa.timestamp("s") + +TABLES = { + "md_supplier": dict(mode="snapshot", schema=pa.schema([ + ("id", V_INT), ("supplier_code", V_STR), ("supplier_name", V_STR), ("contact_person", V_STR), + ("contact_phone", V_STR), ("address", V_STR), ("status", V_STR), ("remark", V_STR), + ("created_at", V_DT), ("updated_at", V_DT)])), + "md_customer": dict(mode="snapshot", schema=pa.schema([ + ("id", V_INT), ("customer_code", V_STR), ("customer_name", V_STR), ("contact_person", V_STR), + ("contact_phone", V_STR), ("address", V_STR), ("status", V_STR), ("remark", V_STR), + ("created_at", V_DT), ("updated_at", V_DT)])), + "md_sku": dict(mode="snapshot", schema=pa.schema([ + ("id", V_INT), ("sku_code", V_STR), ("sku_name", V_STR), ("category", V_STR), ("spec", V_STR), + ("unit", V_STR), ("purchase_price", V_DBL), ("sale_price", V_DBL), ("safety_stock", V_DBL), + ("status", V_STR), ("remark", V_STR), ("created_at", V_DT), ("updated_at", V_DT)])), + "mdm_alias_mapping": dict(mode="snapshot", schema=pa.schema([ + ("id", V_INT), ("entity_type", V_STR), ("entity_id", V_INT), ("alias", V_STR), + ("source_system", V_STR), ("remark", V_STR), ("created_at", V_DT)])), + "inv_stock": dict(mode="snapshot", schema=pa.schema([ + ("id", V_INT), ("sku_id", V_INT), ("qty_on_hand", V_DBL), ("updated_at", V_DT)])), + "po_order": dict(mode="incremental", ts="updated_at", schema=pa.schema([ + ("id", V_INT), ("order_no", V_STR), ("supplier_id", V_INT), ("order_date", V_STR), + ("status", V_STR), ("total_amount", V_DBL), ("handler", V_STR), ("remark", V_STR), + ("received_at", V_DT), ("created_at", V_DT), ("updated_at", V_DT)])), + "so_order": dict(mode="incremental", ts="updated_at", schema=pa.schema([ + ("id", V_INT), ("order_no", V_STR), ("customer_id", V_INT), ("order_date", V_STR), + ("status", V_STR), ("total_amount", V_DBL), ("handler", V_STR), ("remark", V_STR), + ("shipped_at", V_DT), ("created_at", V_DT), ("updated_at", V_DT)])), + "po_order_item": dict(mode="snapshot", schema=pa.schema([ + ("id", V_INT), ("order_id", V_INT), ("line_no", V_INT), ("sku_id", V_INT), + ("qty", V_DBL), ("price", V_DBL), ("amount", V_DBL)])), + "so_order_item": dict(mode="snapshot", schema=pa.schema([ + ("id", V_INT), ("order_id", V_INT), ("line_no", V_INT), ("sku_id", V_INT), + ("qty", V_DBL), ("price", V_DBL), ("amount", V_DBL)])), + "inv_stock_flow": dict(mode="incremental", ts="created_at", schema=pa.schema([ + ("id", V_INT), ("sku_id", V_INT), ("biz_type", V_STR), ("biz_order_no", V_STR), + ("qty_delta", V_DBL), ("qty_after", V_DBL), ("remark", V_STR), ("created_at", V_DT)])), +} + + +def fetch(conn, table, cfg, dt): + cols = [f.name for f in cfg["schema"]] + cur = conn.cursor() + if cfg["mode"] == "snapshot": + sql = f"SELECT {', '.join(cols)} FROM {table}" + cur.execute(sql) + else: + d0, d1 = dt, dt + timedelta(days=1) + sql = f"SELECT {', '.join(cols)} FROM {table} WHERE {cfg['ts']} >= %s AND {cfg['ts']} < %s" + cur.execute(sql, (d0.strftime("%Y-%m-%d 00:00:00"), d1.strftime("%Y-%m-%d 00:00:00"))) + rows = cur.fetchall() + cur.close() + arrays = [] + for i, f in enumerate(cfg["schema"]): + vals = [r[i] for r in rows] + if f.type == V_DBL: + vals = [float(v) if v is not None else None for v in vals] + elif f.type == V_STR: + vals = [v.isoformat() if isinstance(v, (date, datetime)) else v for v in vals] + arrays.append(pa.array(vals, type=f.type)) + return pa.Table.from_arrays(arrays, schema=cfg["schema"]) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--dt", default=(date.today() - timedelta(days=1)).strftime("%Y-%m-%d")) + args = ap.parse_args() + dt = datetime.strptime(args.dt, "%Y-%m-%d").date() + + s3 = boto3.client("s3", endpoint_url=S3["endpoint"], aws_access_key_id=S3["key"], + aws_secret_access_key=S3["secret"]) + conn = pymysql.connect(**ERP, cursorclass=pymysql.cursors.Cursor) + summary = [] + for table, cfg in TABLES.items(): + tbl = fetch(conn, table, cfg, dt) + prefix = f"ods/mini_erp/{table}/dt={dt.isoformat()}/" + # 幂等: 清空分区目录再写 + keys = [o["Key"] for o in (s3.list_objects_v2(Bucket=S3["bucket"], Prefix=prefix).get("Contents") or [])] + for k in keys: + s3.delete_object(Bucket=S3["bucket"], Key=k) + buf = io.BytesIO() + pq.write_table(tbl, buf) + s3.put_object(Bucket=S3["bucket"], Key=prefix + "part-0.parquet", Body=buf.getvalue()) + summary.append({"table": table, "rows": tbl.num_rows, "mode": cfg["mode"], "path": f"s3a://{S3['bucket']}/{prefix}"}) + conn.close() + print(json.dumps({"dt": dt.isoformat(), "extracted": summary}, ensure_ascii=False)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file