# -*- coding: utf-8 -*- """ WMS 注释固化进 schema 源码(正确机制): - 列注释:字段已有 .Comment("..."),表级 entsql.WithComments(true) 让 ent 生成 SQL 时 自动把字段注释写成列注释(无需逐字段注入)。 - 表注释:结构体 schema.Comment("...") + WithComments(true)。 - 因此本脚本只改造每个 schema 结构体的 Annotations(),不改动 Fields()。 幂等:已含 WithComments 的结构体跳过重新写入(按表名归一)。 """ import os, re SCHEMA_DIR = os.environ.get("SCHEMA_DIR", r"D:/hardman/bj_power/bj_power_wms/schema") SQL_PATH = r"D:/hardman/bj_power/sql/db_comments_wms.sql" STRUCT_TABLE = { "AgvTask": "agv_tasks", "Attachment": "attachments", "EventLog": "event_log", "InboundDetail": "inbound_details", "InboundOrder": "inbound_orders", "InspectionRecord": "inspection_records", "Inventory": "inventories", "InventoryLock": "inventory_locks", "Material": "materials", "MaterialDemand": "material_demands", "OrderMaterialLedger": "order_material_ledgers", "OutboundDetail": "outbound_details", "OutboundOrder": "outbound_orders", "Permission": "permissions", "ReturnOrder": "return_orders", "Role": "roles", "SemiFinished": "semi_finisheds", "StocktakeItem": "stocktake_items", "StocktakeOrder": "stocktake_orders", "User": "users", "Zone": "zones", } table_comment = {} with open(SQL_PATH, encoding="utf-8") as f: for line in f: m = re.match(r"COMMENT ON TABLE \"(\w+)\" IS '(.*)';", line.strip()) if m: table_comment[m.group(1)] = m.group(2) def sanitize_quotes(s): # 把 ASCII 双引号包裹的文本转成全角引号,避免 ent 生成 schema.go 时破坏 Go 字符串字面量 # (ent 生成器写 Comment: 字段不转义 ASCII 双引号,源里含 " 会直接破坏生成的 Go 代码) s = re.sub(r'"([^"]*)"', '\u201c\\1\u201d', s) return s.replace('"', '\u201c') def gostr(s): s = sanitize_quotes(s) return s.replace('\\', '\\\\').replace('"', '\\"') def ensure_import(src, pkg): if re.search(r'"%s"' % re.escape(pkg), src): return src m = re.search(r'import \(\n((?:.*\n)*?)\)', src) if m: newblock = m.group(0).replace(')', '\t"%s"\n)' % pkg, 1) return src[:m.start()] + newblock + src[m.end():] m2 = re.search(r'import\s+"([^"]+)"', src) if m2: path = m2.group(1) block = 'import (\n\t"%s"\n\t"%s"\n)' % (path, pkg) return src[:m2.start()] + block + src[m2.end():] return src def replace_or_insert_annotations(src, struct, table, tbl_comment): sig = 'func (%s) Annotations() []schema.Annotation {' % struct new_body = ('func (%s) Annotations() []schema.Annotation {\n' '\treturn []schema.Annotation{entsql.Table("%s"), entsql.WithComments(true), schema.Comment("%s")}\n' '}') % (struct, table, gostr(tbl_comment)) if sig in src: i = src.index(sig) depth, j = 0, i while j < len(src): if src[j] == '{': depth += 1 elif src[j] == '}': depth -= 1 if depth == 0: break j += 1 src = src[:i] + new_body + src[j + 1:] else: fs = 'func (%s) Fields() []ent.Field {' % struct src = src.replace('\n' + fs, '\n' + new_body + '\n' + fs, 1) return src for fn in sorted(os.listdir(SCHEMA_DIR)): if not fn.endswith('.go') or fn in ('mixin.go', 'generate.go'): continue path = os.path.join(SCHEMA_DIR, fn) with open(path, encoding='utf-8') as f: src = f.read() structs = re.findall(r'type (\w+) struct \{\s*ent\.Schema\s*\}', src) if not structs: continue changed = False for st in structs: table = STRUCT_TABLE.get(st) if not table: print("!! no table mapping for", st, fn) continue if 'entsql.WithComments(true)' in src and ('func (%s) Annotations()' % st) in src: # already done (idempotent guard) continue new = replace_or_insert_annotations(src, st, table, table_comment.get(table, '')) if new != src: src = new changed = True if changed: src = ensure_import(src, 'entgo.io/ent/dialect/entsql') src = ensure_import(src, 'entgo.io/ent/schema') with open(path, 'w', encoding='utf-8') as f: f.write(src) print("updated:", fn) else: print("no change:", fn) print("DONE")