63 lines
2.4 KiB
Python
63 lines
2.4 KiB
Python
# -*- coding: utf-8 -*-
|
||||
|
|
"""
|
|||
|
|
MES 注释固化进 schema 源码(对齐 WMS bake_comments.py 的正确机制):
|
|||
|
|
- MES 32 个 struct 已有 Annotations()(形态统一:[]schema.Annotation{entsql.Annotation{Table: "xxx"}})。
|
|||
|
|
- 在既有返回切片里追加 entsql.WithComments(true) + schema.Comment("表注释"):
|
|||
|
|
WithComments(true) 让字段已有 field.Comment() 自动生成为列注释;
|
|||
|
|
schema.Comment() 为表注释。
|
|||
|
|
- 不动 Fields()、不动既有 entsql.Annotation{Table:...}。
|
|||
|
|
幂等:已含 WithComments(true) 的文件跳过。
|
|||
|
|
"""
|
|||
|
|
import os, re
|
|||
|
|
|
|||
|
|
SCHEMA_DIR = os.environ.get("SCHEMA_DIR", r"D:/hardman/bj_power/bj_power_mes/schema")
|
|||
|
|
SQL_PATH = r"D:/hardman/bj_power/sql/db_comments_mes.sql"
|
|||
|
|
|
|||
|
|
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):
|
|||
|
|
# 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('"', '\\"')
|
|||
|
|
|
|||
|
|
RETURN_RE = re.compile(
|
|||
|
|
r'return \[\]schema\.Annotation\{entsql\.Annotation\{Table: "(\w+)"\}\}')
|
|||
|
|
|
|||
|
|
for fn in sorted(os.listdir(SCHEMA_DIR)):
|
|||
|
|
if not fn.endswith('.go') or fn in ('mixin.go', 'gen.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
|
|||
|
|
m = RETURN_RE.search(src)
|
|||
|
|
if not m:
|
|||
|
|
print("!! no plain-table Annotations return in", fn)
|
|||
|
|
continue
|
|||
|
|
if 'entsql.WithComments(true)' in src:
|
|||
|
|
print("no change (already done):", fn)
|
|||
|
|
continue
|
|||
|
|
table = m.group(1)
|
|||
|
|
if table not in table_comment:
|
|||
|
|
print("!! no table comment found for", table, "in", fn)
|
|||
|
|
continue
|
|||
|
|
old = m.group(0)
|
|||
|
|
new = ('return []schema.Annotation{entsql.Annotation{Table: "%s"}, '
|
|||
|
|
'entsql.WithComments(true), schema.Comment("%s")}' % (table, gostr(table_comment[table])))
|
|||
|
|
src = src.replace(old, new, 1)
|
|||
|
|
with open(path, 'w', encoding='utf-8') as f:
|
|||
|
|
f.write(src)
|
|||
|
|
print("updated:", fn, "->", table)
|
|||
|
|
print("DONE")
|