package util import ( "bufio" "fmt" "os" "strings" ) // const base_url = "E:\\project\\kkc\\kkc-go\\" const base_url = "D:\\project\\study\\kkc\\kkc-go\\" // 修改mysql数据库对应的go类型 func FormatSqlType(str string) string { str = strings.ToLower(str) switch str { case "varchar": return "string" case "char": return "string" case "int": return "int64" case "decimal": return "float64" case "datetime": return "time.Time" case "longblob": return "string" default: panic("未定义的类型:" + str) } } //---------------------------------------------------------- // MysqlToStruct 根据mysql 生成对应的struct及String函数 func MysqlToStruct() { var structString = "package domain\n\nimport (\n \"fmt\"\n \"time\"\n)\n\n" for _, mtable := range MTables { structString += fmt.Sprint("//", mtable.GreatHump, " ", mtable.Comment, "\n", "type ", mtable.GreatHump, " struct {\n") cols := mtable.MColumns var toString = "" for i := range cols { if cols[i].LittleHump == "id" && cols[i].IsKey { structString += fmt.Sprint(" ", cols[i].GreatHump, " int64 `json:\"", cols[i].LittleHump, "\"`", "// ", cols[i].Length, " ", cols[i].Length2, " 注释:", cols[i].Comment, "\n") toString += fmt.Sprint(cols[i].GreatHump, ":\", receiver.", cols[i].GreatHump, ", \",") } else { structString += fmt.Sprint(" ", cols[i].GreatHump, " ", cols[i].TypeName, " `xorm:\"", cols[i].Name, "\" json:\"", cols[i].LittleHump, "\"`", "// ", cols[i].Length, " ", cols[i].Length2, " 注释:", cols[i].Comment, "\n") toString += fmt.Sprint(cols[i].GreatHump, ":\", receiver.", cols[i].GreatHump, ", \",") } } structString += "}\n\n" structString += fmt.Sprint("func (receiver ", mtable.GreatHump, ") String() string {\n") structString += fmt.Sprint(" return fmt.Sprint(\"", mtable.GreatHump, "{", toString[0:len(toString)-1], "}\")\n}\n\n") fmt.Println(structString) } fileUrl := base_url + "\\data\\domain\\DoMain.go" //清空文件 os.Truncate(fileUrl, 0) file, _ := os.OpenFile(fileUrl, os.O_CREATE|os.O_RDWR, 0666) defer file.Close() writer := bufio.NewWriter(file) //writer.WriteString("package domain\n\nimport (\n \"fmt\"\n \"time\"\n)\n\n") writer.WriteString(structString) writer.Flush() //file.Write([]byte("package domain\n\nimport \"time\"\n")) //file.Write([]byte(structString)) } // MysqlToDao 生成简单的CRUD dao层 func MysqlToDao() { var baseUrl = base_url + "data\\dao\\manage\\" tables := MTables for _, table := range tables { var dao = "" fileName := table.GreatHump + "Dao.go" dao += "package manage\n\nimport (\n\t\"demo/configs\"\n\t\"demo/data/domain\"\n\t\"demo/data/domain/vo\"\n)\n" //get if table.Name == "role_authority" { fmt.Println(table.ExistId, "====================>") } var idColumn MColumn for _, column := range table.MColumns { if column.IsKey { idColumn = column break } } //没有id的不适用 if table.ExistId { dao += "func Get" + table.GreatHump + "ById(id int64) (domain." + table.GreatHump + ", error) {" + "\n\tvar " + table.LittleHump + " domain." + table.GreatHump + "" + "\n\t_, err := configs.Engine.Where(\"id = ?\", id).Get(&" + table.LittleHump + ")" + "\n\tif err != nil {" + "\n\t\treturn " + table.LittleHump + ", err" + "\n\t}" + "\n\treturn " + table.LittleHump + ", nil" + "\n}\n\n" } dao += "func Get" + table.GreatHump + "ListInId(ids []int64) ([]domain." + table.GreatHump + ", error) {" + "\n\trows, err := configs.Engine.In(\"id\", ids).Rows(&domain." + table.GreatHump + "{})" + "\n\tif err != nil {" + "\n\t\treturn make([]domain." + table.GreatHump + ", 0), err" + "\n\t}" + "\n\tdefer rows.Close()" + "\n\tvar list []domain." + table.GreatHump + "" + "\n\tfor rows.Next() {" + "\n\t\tvar u domain." + table.GreatHump + "" + "\n\t\tlist = append(list, u)" + "\n\t}" + "\n\treturn list, nil" + "\n}\n\n" //list dao += "func Get" + table.GreatHump + "List(" + table.LittleHump + " domain." + table.GreatHump + ", pageNum, pageSize int) (vo.BaseListVo, error) {" + "\n\tvar arr []domain." + table.GreatHump + "\n\tCount, err := configs.Engine.Limit(pageSize, (pageNum-1)*pageSize).Desc(\"id\").FindAndCount(&arr, &" + table.LittleHump + ")" + "\n\tvar vo vo.BaseListVo" + "\n\tif err != nil {" + "\n\t\treturn vo, err" + "\n\t}" + "\n\tif err != nil {" + "\n\t\treturn vo, err" + "\n\t}" + "\n\tvo.PageNum = pageNum" + "\n\tvo.PageSize = pageSize" + "\n\tvo.List = make([]any, len(arr))" + "\n\tfor i, v := range arr {" + "\n\t\tvo.List[i] = v" + "\n\t}" + "\n\tvo.Total = int(Count)" + "\n\treturn vo, nil" + "\n}\n\n" dao += "func Save" + table.GreatHump + "(" + table.LittleHump + " *domain." + table.GreatHump + ") (domain." + table.GreatHump + ", error) {" + "\n\t_, err := configs.Engine.Insert(&" + table.LittleHump + ")" + "\n\tif err != nil {" + "\n\t\treturn *" + table.LittleHump + ", err" + "\n\t}" + "\n\treturn *" + table.LittleHump + ", nil" + "\n}\n\n" dao += "func Set" + table.GreatHump + "(" + table.LittleHump + "Map map[string]interface{}, id int64) (domain." + table.GreatHump + ", bool, error) {" + "\n\tvar " + table.LittleHump + " domain." + table.GreatHump + "" + "\n\t_, err := configs.Engine.Table(\"" + table.Name + "\").Where(\"" + idColumn.Name + " = ?\", id).Update(" + table.LittleHump + "Map)" + "\n\tif err != nil {" + "\n\t\treturn " + table.LittleHump + ", false, err" + "\n\t}" + "\n\treturn " + table.LittleHump + ", true, nil" + "\n}\n\n" if table.ExistId { dao += "func Delete" + table.GreatHump + "(id int64) bool {" + "\n\tvar " + table.LittleHump + " domain." + table.GreatHump + "\n\ti, err := configs.Engine.Where(\"id = ?\", id).Delete(&" + table.LittleHump + ")" + "\n\tif err != nil {" + "\n\t\treturn false" + "\n\t}" + "\n\treturn i > 0" + "\n}" } //创建文件 url := baseUrl + fileName WriteFile(url, dao) } } func MysqlToBaseCRUDRouter() { tables := MTables var template = "package router" + "\n" + "\nimport (" + "\n\t\"demo/data/dao/manage\"" + "\n\t\"demo/data/domain\"" + "\n\t\"demo/share\"" + "\n\t\"encoding/json\"" + "\n\t\"github.com/gin-gonic/gin\"" + "\n\t\"github.com/spf13/cast\"" + "\n)" + "\n" var routerHeader = "" var routerBody = "" var getRouterFunc = "" for i := range tables { table := tables[i] getRouterFunc += "//Base" + table.GreatHump + "Router(group)\n" routerHeader += "\nfunc Base" + table.GreatHump + "Router(group *gin.RouterGroup) {" + "\n\tBase" + table.GreatHump + "Group := group.Group(\"/back/base\")" + "\n\tPushRouter(Base" + table.GreatHump + "Group, \"GET\", \"/" + table.LittleHump + "\", GetBase" + table.GreatHump + "ById)" + "\n\tPushRouter(Base" + table.GreatHump + "Group, \"POST\", \"/" + table.LittleHump + "/list\", GetBase" + table.GreatHump + "List)" + "\n\tPushRouter(Base" + table.GreatHump + "Group, \"POST\", \"/" + table.LittleHump + "/in\", GetBase" + table.GreatHump + "ListInId)" + "\n\tPushRouter(Base" + table.GreatHump + "Group, \"POST\", \"/" + table.LittleHump + "\", SaveBase" + table.GreatHump + ")" + "\n\tPushRouter(Base" + table.GreatHump + "Group, \"PUT\", \"/" + table.LittleHump + "\", UpdateBase" + table.GreatHump + ")" + "\n\tPushRouter(Base" + table.GreatHump + "Group, \"DELETE\", \"/" + table.LittleHump + "\", DeleteBase" + table.GreatHump + ")" + "\n}\n" routerBody += "\nfunc GetBase" + table.GreatHump + "ById(c *gin.Context) {" + "\n\tid := c.Param(\"id\")" + "\n\t" + table.LittleHump + ", err := manage.Get" + table.GreatHump + "ById(cast.ToInt64(id))" + "\n\tif err != nil {" + "\n\t\tc.JSON(200, CreateResultError(500, \"用户查询不存在\"))" + "\n\t}" + "\n\tc.JSON(200, CreateResultData(" + table.LittleHump + "))" + "\n}" + "\n" + "\nfunc GetBase" + table.GreatHump + "List(c *gin.Context) {" + "\n\tdata := share.GetJsonAnyParam(c)" + "\n\tparam, _ := data(\"param\")" + "\n\tpageNum, _ := data(\"pageNum\")" + "\n\tpageSize, _ := data(\"pageSize\")" + "\n\t" + table.LittleHump + " := domain." + table.GreatHump + "{}" + //"\n\terr := json.Unmarshal([]byte(cast.ToString(param)), &" + table.LittleHump + ")" + "\n\terr := mapstructure.Decode(param, &" + table.LittleHump + ")\n\tif err != nil {\n\t\tc.JSON(200, CreateResultError(500, \"json转换错误\"))\n\t}" + "\n\tlist, err := manage.Get" + table.GreatHump + "List(" + table.LittleHump + ", cast.ToInt(pageNum), cast.ToInt(pageSize))" + "\n\tif err != nil {" + "\n\t\tc.JSON(200, CreateResultError(500, \"查询错误\"))" + "\n\t}" + "\n\tc.JSON(200, CreateResultData(list))" + "\n}" + "\n" + "\nfunc GetBase" + table.GreatHump + "ListInId(c *gin.Context) {" + "\n\tdata := share.GetJsonAnyParam(c)" + "\n\tidsString, _ := data(\"ids\")" + "\n\tvar ids []int64" + "\n\terr := json.Unmarshal([]byte(cast.ToString(idsString)), &ids)" + "\n\tlist, err := manage.Get" + table.GreatHump + "ListInId(ids)" + "\n\tif err != nil {" + "\n\t\tc.JSON(200, CreateResultError(500, \"查询错误\"))" + "\n\t}" + "\n\tc.JSON(200, CreateResultData(list))" + "\n}" + "\n" + "\nfunc SaveBase" + table.GreatHump + "(c *gin.Context) {" + "\n\tdata := share.GetJsonAnyParam(c)" + "\n\t" + table.LittleHump + "Param, _ := data(\"" + table.LittleHump + "\")" + "\n\t" + table.LittleHump + " := domain." + table.GreatHump + "{}" + "\n\terr := json.Unmarshal([]byte(cast.ToString(" + table.LittleHump + "Param)), &" + table.LittleHump + ")" + "\n\tsave" + table.GreatHump + ", err := manage.Save" + table.GreatHump + "(&" + table.LittleHump + ")" + "\n\tif err != nil {" + "\n\t\tc.JSON(200, CreateResultError(500, \"保存错误\"))" + "\n\t}" + "\n\tc.JSON(200, CreateResultData(save" + table.GreatHump + "))" + "\n}" + "\n" + "\nfunc UpdateBase" + table.GreatHump + "(c *gin.Context) {" + "\n\tdata := share.GetJsonAnyParam(c)" + "\n\t" + table.LittleHump + ", _ := data(\"" + table.LittleHump + "\")" + "\n\tid, _ := data(\"id\")" + "\n" + "\n\tset" + table.GreatHump + ", b, err := manage.Set" + table.GreatHump + "(cast.ToStringMap(" + table.LittleHump + "), cast.ToInt64(id))" + "\n\tif err != nil || !b {" + "\n\t\tc.JSON(200, CreateResultError(500, \"修改错误\"))" + "\n\t}" + "\n\tc.JSON(200, CreateResultData(set" + table.GreatHump + "))" + "\n}" + "\n" + "\nfunc DeleteBase" + table.GreatHump + "(c *gin.Context) {" + "\n\tid := c.Param(\"id\")" + "\n\tres := manage.Delete" + table.GreatHump + "(cast.ToInt64(id))" + "\n\tif !res {" + "\n\t\tc.JSON(200, CreateResultError(500, \"删除错误\"))" + "\n\t}" + "\n\tc.JSON(200, CreateResult())" + "\n}" + "\n" } //url := "D:\\project\\study\\kkc\\go-xorm-create\\go-xorm-create\\text\\TextFile" url := "D:\\project\\study\\kkc\\kkc-go\\router\\BasaeBackRouter.go" WriteFile(url, template+getRouterFunc+routerHeader+routerBody) }