You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
146 lines
4.7 KiB
146 lines
4.7 KiB
import os
|
|
from jinja2 import Environment, FileSystemLoader
|
|
from db import get_table, get_columns, get_all_tables
|
|
from utils import *
|
|
import yaml
|
|
|
|
env = Environment(loader=FileSystemLoader("templates/vue"))
|
|
|
|
|
|
def render(template, out, ctx):
|
|
|
|
tpl = env.get_template(template)
|
|
content = tpl.render(**ctx)
|
|
|
|
os.makedirs(os.path.dirname(out), exist_ok=True)
|
|
|
|
with open(out, "w", encoding="utf-8") as f:
|
|
f.write(content)
|
|
|
|
|
|
def build_fields(table):
|
|
|
|
cols = get_columns(table)
|
|
|
|
fields = []
|
|
for c in cols:
|
|
field = {}
|
|
field["name"] = to_camel(c["column_name"])
|
|
field["comment"] = c["column_comment"]
|
|
field["type"] = c["data_type"]
|
|
# ⭐ 在这里调用组件解析
|
|
field["component"] = parse_component(c)
|
|
fields.append(field)
|
|
|
|
return fields
|
|
|
|
|
|
def generate(table):
|
|
|
|
with open("./config.yml", "r", encoding="utf-8") as f:
|
|
cfg = yaml.safe_load(f)
|
|
cfg = resolve_config(cfg)
|
|
|
|
API_DIR = cfg["frontend"]["root"] + "/" + cfg["frontend"]["api"]
|
|
VIEW_DIR = cfg["frontend"]["root"] + "/" + cfg["frontend"]["views"]
|
|
ROUTER_DIR = cfg["frontend"]["root"] + "/" + cfg["frontend"]["router"]
|
|
MOCK_DIR = cfg["frontend"]["root"] + "/" + cfg["frontend"]["mock"]
|
|
EDIT_FIELDS = cfg["frontend"]["editFields"]
|
|
|
|
table_info = get_table(table)
|
|
entity = table.replace("health_", "")
|
|
ctx = {
|
|
"table": table,
|
|
"table_comment": table_info["table_comment"],
|
|
"old_table": to_kebab(table),
|
|
"entity": entity,
|
|
"editFields": to_class_join(EDIT_FIELDS),
|
|
"fields": build_fields(table),
|
|
}
|
|
|
|
render("api.ts.j2", f"{API_DIR}/{entity}.ts", ctx)
|
|
|
|
render("index.vue.j2", f"{VIEW_DIR}/{entity}/index.vue", ctx)
|
|
|
|
render("data.ts.j2", f"{VIEW_DIR}/{entity}/data.ts", ctx)
|
|
|
|
render("form.ts.j2", f"{VIEW_DIR}/{entity}/form.ts", ctx)
|
|
|
|
render("router.ts.j2", f"{ROUTER_DIR}/{entity}.ts", ctx)
|
|
|
|
render("mock.ts.j2", f"{MOCK_DIR}/{entity}.ts", ctx)
|
|
|
|
|
|
# ... existing code ...
|
|
|
|
if __name__ == "__main__":
|
|
import sys
|
|
|
|
def is_database_name(name: str) -> bool:
|
|
"""判断输入是数据库名还是表名:查一下information_schema.tables看是否存在该表"""
|
|
info = get_table(name)
|
|
return info is None
|
|
|
|
def generate_tables(tables: list):
|
|
"""批量生成多个表"""
|
|
if not tables:
|
|
print("❌ 没有可生成的表")
|
|
return
|
|
for t in tables:
|
|
table_name = t if isinstance(t, str) else t["table_name"]
|
|
comment = t.get("table_comment", "") if isinstance(t, dict) else ""
|
|
print(f"=== 生成前端代码:{table_name} ({comment}) ===")
|
|
generate(table_name)
|
|
print(f"\n✅ 共生成 {len(tables)} 张表的前端代码")
|
|
|
|
def generate_by_database(db_name: str):
|
|
"""根据数据库名获取所有表并生成"""
|
|
tables = get_all_tables(db_name)
|
|
if not tables:
|
|
print(f"❌ 数据库 '{db_name}' 中没有找到任何表")
|
|
return
|
|
print(f"📂 数据库 '{db_name}' 共有 {len(tables)} 张表:")
|
|
for t in tables:
|
|
print(f" - {t['table_name']} ({t['table_comment']})")
|
|
print()
|
|
generate_tables(tables)
|
|
|
|
def generate_by_input(input_str: str):
|
|
"""根据输入判断是表名、数据库名,还是逗号分隔的多个表名"""
|
|
input_str = input_str.strip()
|
|
if not input_str:
|
|
print("❌ 未输入内容,退出程序")
|
|
return
|
|
|
|
# 支持逗号分隔的多个表名
|
|
if "," in input_str:
|
|
names = [n.strip() for n in input_str.split(",") if n.strip()]
|
|
generate_tables(names)
|
|
return
|
|
|
|
# 先尝试作为表名查询
|
|
table_info = get_table(input_str)
|
|
if table_info:
|
|
print(
|
|
f"=== 生成前端代码:{input_str} ({table_info.get('table_comment', '')}) ==="
|
|
)
|
|
generate(input_str)
|
|
return
|
|
|
|
# 表名不存在,尝试作为数据库名
|
|
print(f"⚠ '{input_str}' 不是表名,尝试作为数据库名查询...")
|
|
generate_by_database(input_str)
|
|
|
|
# 从命令行参数获取
|
|
if len(sys.argv) > 1:
|
|
arg = sys.argv[1]
|
|
# 支持 --db=xxx 或 --database=xxx 显式指定数据库
|
|
if arg.startswith("--db=") or arg.startswith("--database="):
|
|
db_name = arg.split("=", 1)[1].strip()
|
|
generate_by_database(db_name)
|
|
else:
|
|
generate_by_input(arg)
|
|
else:
|
|
# 如果没有提供参数,提示用户输入
|
|
input_str = input("请输入表名或数据库名 (多个表名用逗号分隔): ").strip()
|
|
generate_by_input(input_str)
|
|
|