Files
皓月归尘 1c316594f5 feat(generate): 优化代码生成逻辑
- 新增公共字段配置,统一处理常见字段的生成规则
- 修复模板中的一些错误,如变量名、函数名等
- 优化代码结构,提高可读性和可维护性
2025-07-01 23:40:43 +08:00

113 lines
4.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# _*_ coding : UTF-8 _*_
# @Time : 2025/03/03 00:03
# @UpdateTime : 2025/03/03 00:03
# @Author : sonder
# @File : generate.py
# @Software : PyCharm
# @Comment : 本程序
from datetime import datetime
from config.constant import MYSQL_TO_TORTOISE_TYPE
class Generate:
"""
代码生成成工具
"""
@classmethod
def convert_mysql_type(cls, mysql_type: str):
"""
将 MySQL 字段类型转换为 Tortoise-ORM 的字段类型。
:param mysql_type: MySQL 的字段类型,如 "varchar(255)""int(11)"
:return: Tortoise-ORM 对应的字段类型,如 "CharField""IntField"
"""
# 提取字段的基本类型(去掉括号及长度信息)
base_type = mysql_type.split("(")[0].lower()
# 处理特殊情况tinyint(1) -> BooleanField
if base_type == "tinyint":
if "(1)" in mysql_type: # tinyint(1) 视为 Boolean
return "BooleanField", None
return "IntField", None # 其他 tinyint 作为 IntField 处理
max_length = None
if "(" in mysql_type and base_type in {"char", "varchar"}:
max_length = int(mysql_type.split("(")[1].split(")")[0]) # 提取最大长度
field_type = MYSQL_TO_TORTOISE_TYPE.get(base_type, "TextField")
return field_type, max_length
@classmethod
def prepare_template_data(cls, table_info, columns):
TYPE_DEFINE = {
"int": 0,
"str": "",
"bool": False,
"float": 0.0,
"datetime": "",
"list": [],
"dict": {},
"set": set(),
"tuple": (),
"bytes": b"",
"None": 'null',
}
PYTHON_TO_TS = {
"int": "number",
"float": "number",
"str": "string",
"bool": "boolean",
"datetime": "string",
"Optional[int]": "number | null",
"Optional[str]": "string | null",
"Optional[bool]": "boolean | null",
"Optional[float]": "number | null",
"Optional[datetime]": "string | null",
"List[int]": "number[]",
"List[str]": "string[]",
"List[bool]": "boolean[]",
"List[datetime]": "string[]",
"Dict[str, Any]": "Record<string, any>",
"Any": "any",
}
common_column = ["id", "del_flag", "create_by", "update_by", "create_time", "update_time"]
"""组织数据,供 Jinja2 渲染"""
return {
"author": table_info.get('author', ""),
"prefix": table_info["prefix"],
"table_name": table_info["table_name"],
"class_name": table_info["class_name"],
"table_comment": table_info.get("table_comment", ""),
"description": table_info.get("description", ""),
"name": table_info.get('class_name', "").lower(),
"permission_id": table_info.get('permission_id', ""),
"columns": [
{
"python_name": col["python_name"],
"field_type": cls.convert_mysql_type(col["column_type"])[0],
"max_length": cls.convert_mysql_type(col["column_type"])[1],
"is_common": col["python_name"] in common_column,
"is_nullable": not col["is_required"],
"is_unique": col.get("is_unique", False),
"default": col.get("default", None),
"column_comment": col.get("column_comment", ""),
"column_name": col["column_name"],
"is_required": col.get("is_required", False),
"is_edit": col.get("is_edit", False),
"is_list": col.get("is_list", False),
"is_query": col.get("is_query", False),
"is_insert": col.get("is_insert", False),
"is_hide": col.get("is_hide", False),
"query_way": col.get("query_way", "="),
"show_type": col.get("show_type", "input"),
"python_type": col.get("python_type", "str"),
"define": TYPE_DEFINE.get(col.get("python_type", "str"), None),
"typescript_type": PYTHON_TO_TS.get(col.get("python_type", "str"), "any"),
}
for col in columns
if col["python_name"] and col["column_type"]
],
"current_time": datetime.now().strftime("%Y/%m/%d %H:%M:%S")
}