生成代码,逐步进行优化

This commit is contained in:
hoteas 2021-06-05 02:18:56 +08:00
parent 6aa2b74840
commit 79453d4d2a
10 changed files with 139 additions and 270 deletions

View File

@ -6,9 +6,7 @@ import (
. "./common" . "./common"
. "./db" . "./db"
. "./log" . "./log"
"bytes"
"database/sql" "database/sql"
"encoding/json"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
@ -226,24 +224,25 @@ func (that *Application) SetConfig(configPath ...string) {
//文件如果损坏则不写入配置防止配置文件数据丢失 //文件如果损坏则不写入配置防止配置文件数据丢失
if that.Error.GetError() == nil { if that.Error.GetError() == nil {
var configByte bytes.Buffer //var configByte bytes.Buffer
err = json.Indent(&configByte, []byte(that.Config.ToJsonString()), "", "\t")
//判断配置文件是否序列有变化,有则修改配置,无则不变 //判断配置文件是否序列有变化,有则修改配置,无则不变
//fmt.Println(len(btes)) //fmt.Println(len(btes))
if len(btes) != 0 && configByte.String() == string(btes) { configStr := that.Config.ToJsonString()
if len(btes) != 0 && configStr == string(btes) {
return return
} }
//写入配置说明 //写入配置说明
var configNoteByte bytes.Buffer //var configNoteByte bytes.Buffer
_ = json.Indent(&configNoteByte, []byte(ConfigNote.ToJsonString()), "", "\t") configNoteStr := ConfigNote.ToJsonString()
//_ = json.Indent(&configNoteByte, []byte(ConfigNote.ToJsonString()), "", "\t")
_ = os.MkdirAll(filepath.Dir(that.configPath), os.ModeDir) _ = os.MkdirAll(filepath.Dir(that.configPath), os.ModeDir)
err = ioutil.WriteFile(that.configPath, configByte.Bytes(), os.ModeAppend) err = ioutil.WriteFile(that.configPath, []byte(configStr), os.ModePerm)
if err != nil { if err != nil {
that.Error.SetError(err) that.Error.SetError(err)
} }
_ = ioutil.WriteFile(filepath.Dir(that.configPath)+"/configNote.json", configNoteByte.Bytes(), os.ModeAppend) _ = ioutil.WriteFile(filepath.Dir(that.configPath)+"/configNote.json", []byte(configNoteStr), os.ModePerm)
} }
@ -451,7 +450,7 @@ func Init(config string) Application {
appIns.SetCache() appIns.SetCache()
appIns.MakeCode = &code.MakeCode{} appIns.MakeCode = &code.MakeCode{}
codeConfig := appIns.Config.GetMap("codeConfig") codeConfig := appIns.Config.GetMap("codeConfig")
if codeConfig != nil { if codeConfig != nil && appIns.Config.GetInt("mode") == 2 {
for k, _ := range codeConfig { for k, _ := range codeConfig {
appIns.MakeCode.Db2JSON(k, codeConfig.GetString(k), appIns.Db) appIns.MakeCode.Db2JSON(k, codeConfig.GetString(k), appIns.Db)
} }
@ -476,6 +475,7 @@ func SetDB(appIns *Application) {
func SetMysqlDB(appIns *Application, config Map) { func SetMysqlDB(appIns *Application, config Map) {
appIns.Db.Type = "mysql" appIns.Db.Type = "mysql"
appIns.Db.DBName = config.GetString("name")
appIns.Db.Prefix = config.GetString("prefix") appIns.Db.Prefix = config.GetString("prefix")
appIns.SetConnectDB(func(err ...*Error) (master, slave *sql.DB) { appIns.SetConnectDB(func(err ...*Error) (master, slave *sql.DB) {
//master数据库配置 //master数据库配置

View File

@ -3,8 +3,6 @@ package code
import ( import (
. "../common" . "../common"
"../db" "../db"
"bytes"
"encoding/json"
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
@ -22,6 +20,9 @@ type MakeCode struct {
} }
func (that *MakeCode) Db2JSON(name string, path string, db db.HoTimeDB) { func (that *MakeCode) Db2JSON(name string, path string, db db.HoTimeDB) {
isMake := false
idSlice := Slice{}
if that.TableColumns == nil { if that.TableColumns == nil {
that.TableColumns = make(map[string]map[string]Map) that.TableColumns = make(map[string]map[string]Map)
} }
@ -60,103 +61,142 @@ func (that *MakeCode) Db2JSON(name string, path string, db db.HoTimeDB) {
myInit := strings.Replace(InitTpt, "{{name}}", name, -1) myInit := strings.Replace(InitTpt, "{{name}}", name, -1)
ctrList := "" ctrList := ""
if db.Type == "sqlite" {
tables := db.Select("sqlite_sequence", "name")
for _, v := range tables { nowTables := make([]Map, 0)
if that.TableConfig.GetMap(v.GetString("name")) == nil { if db.Type == "mysql" {
that.TableConfig[v.GetString("name")] = Map{ nowTables = db.Select("INFORMATION_SCHEMA.TABLES", "TABLE_NAME as name,TABLE_COMMENT as label", Map{"TABLE_SCHEMA": db.DBName})
"label": "备注", }
"table": v.GetString("name"), if db.Type == "sqlite" {
"auth": []string{"add", "delete", "edit", "info"}, nowTables = db.Select("sqlite_sequence", "name")
"columns": []Map{}, }
"search": []Map{ //idSlice=append(idSlice,nowTables)
//{"type": "tree", "name": "oid", "label": "组织", "table": "organization", "showName": "label", "children": "children"}, for _, v := range nowTables {
{"type": "text", "name": "keyword", "label": "请输入关键词", "value": nil}, if that.TableConfig.GetMap(v.GetString("name")) == nil {
{"type": "date", "name": "date", "label": "时间段", "value": nil}, if v.GetString("label") == "" {
{"type": "select", "name": "state", "label": "状态", "value": nil, v["label"] = "备注"
"option": []Map{ }
{"name": "正常", "value": 0}, that.TableConfig[v.GetString("name")] = Map{
{"name": "异常", "value": 1}, "label": v.GetString("label"),
{"name": "全部", "value": nil}, "table": v.GetString("name"),
}, "auth": []string{"add", "delete", "edit", "info"},
"columns": []Map{},
"search": []Map{
//{"type": "tree", "name": "oid", "label": "组织", "table": "organization", "showName": "label", "children": "children"},
{"type": "text", "name": "keyword", "label": "请输入关键词", "value": nil},
{"type": "date", "name": "date", "label": "时间段", "value": nil},
{"type": "select", "name": "state", "label": "状态", "value": nil,
"option": []Map{
{"name": "正常", "value": 0},
{"name": "异常", "value": 1},
{"name": "全部", "value": nil},
}, },
}, },
},
}
} else {
if !(that.TableConfig.GetMap(v.GetString("name")).GetString("label") != "备注" &&
v.GetString("label") == "备注") {
that.TableConfig.GetMap(v.GetString("name"))["label"] = v.GetString("label")
}
}
//初始化
if that.TableColumns[v.GetString("name")] == nil {
that.TableColumns[v.GetString("name")] = make(map[string]Map)
}
tableInfo := make([]Map, 0)
if db.Type == "mysql" {
tableInfo = db.Select("INFORMATION_SCHEMA.COLUMNS", "COLUMN_NAME AS name,COLUMN_TYPE AS type,COLUMN_COMMENT AS label", Map{"AND": Map{"TABLE_SCHEMA": db.DBName, "TABLE_NAME": v.GetString("name")}})
}
if db.Type == "sqlite" {
tableInfo = db.Query("pragma table_info([" + v.GetString("name") + "]);")
}
idSlice = append(idSlice, tableInfo)
for _, info := range tableInfo {
if info.GetString("label") == "" {
info["label"] = "备注"
}
coloums := that.TableColumns[v.GetString("name")][info.GetString("name")]
if coloums == nil {
coloums = Map{
"name": info.GetString("name"),
"type": info.GetString("type"),
"label": info.GetString("label"),
//"add": false, "info": false, "edit": false, "list": true,
"must": false,
} }
} } else {
//初始化
if that.TableColumns[v.GetString("name")] == nil { if !(coloums.GetString("label") != "备注" && info.GetString("label") == "备注") {
that.TableColumns[v.GetString("name")] = make(map[string]Map) coloums["label"] = info.GetString("label")
}
tableInfo := db.Query("pragma table_info([" + v.GetString("name") + "]);")
for _, info := range tableInfo {
coloums := that.TableColumns[v.GetString("name")][info.GetString("name")]
if coloums == nil {
coloums = Map{
"name": info.GetString("name"),
"type": info.GetString("type"),
"label": "备注",
//"add": false, "info": false, "edit": false, "list": true,
"must": false,
}
} else {
//coloums["name"]=info.GetString("name")
coloums["type"] = info.GetString("type")
} }
coloums["type"] = info.GetString("type")
that.TableColumns[v.GetString("name")][info.GetString("name")] = coloums
} }
//创建模块文件 that.TableColumns[v.GetString("name")][info.GetString("name")] = coloums
//判断文件是否存在
_, err := os.OpenFile(name+"/"+v.GetString("name"), os.O_RDONLY, os.ModePerm)
if err != nil { //文件不存在,则根据模板创建
myCtr := strings.Replace(CtrTpt, "{{name}}", name, -1)
myCtr = strings.Replace(myCtr, "{{table}}", v.GetString("name"), -1)
_ = os.MkdirAll(name, os.ModeDir)
err = ioutil.WriteFile(name+"/"+v.GetString("name")+".go", []byte(myCtr), os.ModeAppend)
if err != nil {
that.Error.SetError(err)
}
}
ctrList = ctrList + `"` + v.GetString("name") + `":` + v.GetString("name") + `Ctr,`
} }
newTables := []Map{} //创建模块文件
for k, _ := range that.TableConfig { //判断文件是否存在
newTable := that.TableConfig.GetMap(k) //_, err := os.OpenFile(name+"/"+v.GetString("name"), os.O_RDONLY, os.ModePerm)
newTables = append(newTables, newTable) _, err := os.Stat(name + "/" + v.GetString("name") + ".go")
columns := []Map{} if err != nil { //文件不存在,则根据模板创建
for _, v := range that.TableColumns[newTable.GetString("table")] { myCtr := strings.Replace(CtrTpt, "{{name}}", name, -1)
columns = append(columns, v) myCtr = strings.Replace(myCtr, "{{table}}", v.GetString("name"), -1)
_ = os.MkdirAll(name, os.ModeDir)
err = ioutil.WriteFile(name+"/"+v.GetString("name")+".go", []byte(myCtr), os.ModePerm)
if err != nil {
that.Error.SetError(err)
} }
newTable["columns"] = columns isMake = true
} }
that.Config["tables"] = newTables
ctrList = ctrList + `"` + v.GetString("name") + `":` + v.GetString("name") + "Ctr,\r\n "
} }
id := Md5(ObjToStr(that.Config["tables"]))
newTables := []Map{}
for k, _ := range that.TableConfig {
newTable := that.TableConfig.GetMap(k)
newTables = append(newTables, newTable)
columns := []Map{}
for _, v := range that.TableColumns[newTable.GetString("table")] {
columns = append(columns, v)
}
newTable["columns"] = columns
}
that.Config["tables"] = newTables
//}
//fmt.Println(ObjToStr(idSlice))
id := Md5(ObjToStr(idSlice))
if id == that.Config.GetString("id") { if id == that.Config.GetString("id") {
if isMake { //有生成包文件
fmt.Println("有新的业务代码生成,请重新运行")
os.Exit(-1)
}
return return
} }
fmt.Println(id, "---", that.Config.GetString("id"))
that.Config["id"] = id that.Config["id"] = id
//init文件初始化 //init文件初始化
myInit = strings.Replace(myInit, "{{id}}", id, -1) myInit = strings.Replace(myInit, "{{id}}", id, -1)
myInit = strings.Replace(myInit, "{{tablesCtr}}", ctrList, -1) myInit = strings.Replace(myInit, "{{tablesCtr}}", ctrList, -1)
_ = os.MkdirAll(name, os.ModeDir) _ = os.MkdirAll(name, os.ModeDir)
err = ioutil.WriteFile(name+"/init.go", []byte(myInit), os.ModeAppend) err = ioutil.WriteFile(name+"/init.go", []byte(myInit), os.ModePerm)
if err != nil { if err != nil {
that.Error.SetError(err) that.Error.SetError(err)
} }
//写入配置文件 //写入配置文件
var configByte bytes.Buffer //var configByte bytes.Buffer
err = json.Indent(&configByte, []byte(that.Config.ToJsonString()), "", "\t") //err = json.Indent(&configByte, []byte(that.Config.ToJsonString()), "", "\t")
_ = os.MkdirAll(filepath.Dir(path), os.ModeDir) _ = os.MkdirAll(filepath.Dir(path), os.ModeDir)
err = ioutil.WriteFile(path, configByte.Bytes(), os.ModeAppend) err = ioutil.WriteFile(path, []byte(that.Config.ToJsonString()), os.ModePerm)
if err != nil { if err != nil {
that.Error.SetError(err) that.Error.SetError(err)
} }

View File

@ -24,7 +24,7 @@ import (
// return res // return res
//} //}
//字符串首字符大写 // StrFirstToUpper 字符串首字符大写
func StrFirstToUpper(str string) string { func StrFirstToUpper(str string) string {
if len(str) == 0 { if len(str) == 0 {
return str return str
@ -36,7 +36,7 @@ func StrFirstToUpper(str string) string {
return strings.ToUpper(first) + other return strings.ToUpper(first) + other
} }
//字符串截取 // Substr 字符串截取
func Substr(str string, start int, length int) string { func Substr(str string, start int, length int) string {
rs := []rune(str) rs := []rune(str)
rl := len(rs) rl := len(rs)
@ -67,7 +67,7 @@ func Substr(str string, start int, length int) string {
return string(rs[start:end]) return string(rs[start:end])
} }
//获取最后出现字符串的下标 // IndexLastStr 获取最后出现字符串的下标
//return 找不到返回 -1 //return 找不到返回 -1
func IndexLastStr(str, sep string) int { func IndexLastStr(str, sep string) int {
sepSlice := []rune(sep) sepSlice := []rune(sep)
@ -98,7 +98,7 @@ func IndexLastStr(str, sep string) int {
return -1 return -1
} }
//md5 // Md5 md5
func Md5(req string) string { func Md5(req string) string {
md5Ctx := md5.New() md5Ctx := md5.New()
md5Ctx.Write([]byte(req)) md5Ctx.Write([]byte(req))

View File

@ -1,6 +1,7 @@
package common package common
import ( import (
"bytes"
"encoding/json" "encoding/json"
"errors" "errors"
"math" "math"
@ -258,8 +259,10 @@ func ObjToStr(obj interface{}) string {
str = strconv.FormatFloat(obj.(float64), 'f', -1, 64) str = strconv.FormatFloat(obj.(float64), 'f', -1, 64)
default: default:
strbte, err := json.Marshal(obj) strbte, err := json.Marshal(obj)
var configByte bytes.Buffer
err = json.Indent(&configByte, strbte, "", "\t")
if err == nil { if err == nil {
str = string(strbte) str = configByte.String()
} }
} }

View File

@ -16,6 +16,7 @@ import (
type HoTimeDB struct { type HoTimeDB struct {
*sql.DB *sql.DB
ContextBase ContextBase
DBName string
*cache.HoTimeCache *cache.HoTimeCache
Type string Type string
Prefix string Prefix string

View File

@ -1,13 +0,0 @@
package admin
import (
. "../../../hotime"
)
var ID = "bc662f6bf19a1f3f269045167a2f273d"
// Project 管理端项目
var Project = Proj{
//"user": UserCtr,
"user": userCtr,
}

View File

@ -1,60 +0,0 @@
package admin
import (
. "../../../hotime"
. "../../../hotime/common"
)
var userCtr = Ctr{
"info": func(that *Context) {
re := that.Db.Get(that.RouterString[1], that.MakeCode.Info(that.RouterString[1]), Map{"id": that.RouterString[2]})
that.Display(0, re)
},
"add": func(that *Context) {
inData := that.MakeCode.Add(that.RouterString[1], that.Req)
if inData == nil {
that.Display(3, "请求参数不足")
return
}
re := that.Db.Insert(that.RouterString[1], inData)
if re == 0 {
that.Display(4, "无法插入对应数据")
return
}
that.Display(0, re)
},
"update": func(that *Context) {
inData := that.MakeCode.Edit(that.RouterString[1], that.Req)
if inData == nil {
that.Display(3, "没有找到要更新的数据")
return
}
re := that.Db.Update(that.RouterString[1], inData, Map{"id": that.RouterString[2]})
if re == 0 {
that.Display(4, "更新数据失败")
return
}
that.Display(0, re)
},
"remove": func(that *Context) {
re := that.Db.Delete(that.RouterString[1], Map{"id": that.RouterString[2]})
if re == 0 {
that.Display(4, "删除数据失败")
return
}
that.Display(0, re)
},
"search": func(that *Context) {
columnStr, where := that.MakeCode.Search(that.RouterString[1], that.Req)
reData := that.Db.Page(ObjToInt(that.Req.FormValue("page")), ObjToInt(that.Req.FormValue("pageRow"))).
Select(that.RouterString[1], columnStr, where)
that.Display(0, reData)
},
}

View File

@ -1,107 +0,0 @@
{
"id": "bc662f6bf19a1f3f269045167a2f273d",
"label": "HoTime管理平台",
"menu": [
{
"icon": "el-icon-s-home",
"label": "平台首页",
"name": "HelloWorld"
},
{
"icon": "el-icon-suitcase",
"label": "测试表格",
"table": "table"
},
{
"icon": "el-icon-setting",
"label": "系统管理",
"menu": [
{
"label": "用户管理",
"table": "user"
},
{
"label": "组织管理",
"table": "organization"
},
{
"label": "角色管理",
"table": "role"
},
{
"default": "edit",
"label": "系统设置",
"table": "system"
}
],
"name": "setting"
}
],
"name": "HoTimeDashBoard",
"tables": [
{
"auth": [
"add",
"delete",
"edit",
"info"
],
"columns": [
{
"label": "备注",
"must": false,
"name": "id",
"type": "integer"
},
{
"label": "备注",
"must": false,
"name": "name",
"type": "text"
},
{
"label": "备注",
"must": false,
"name": "age",
"type": "int"
}
],
"label": "备注",
"search": [
{
"label": "请输入关键词",
"name": "keyword",
"type": "text",
"value": null
},
{
"label": "时间段",
"name": "date",
"type": "date",
"value": null
},
{
"label": "状态",
"name": "state",
"option": [
{
"name": "正常",
"value": 0
},
{
"name": "异常",
"value": 1
},
{
"name": "全部",
"value": null
}
],
"type": "select",
"value": null
}
],
"table": "user"
}
]
}

View File

@ -10,8 +10,13 @@
"admin": "config/app.json" "admin": "config/app.json"
}, },
"db": { "db": {
"sqlite": { "mysql": {
"path": "config/data.db" "host": "cloud.hoteas.com",
"name": "ljf",
"password": "root",
"port": "3306",
"prefix": "",
"user": "root"
} }
}, },
"defFile": [ "defFile": [

View File

@ -2,7 +2,7 @@ package main
import ( import (
"../../hotime" "../../hotime"
"./admin" //"./admin"
"errors" "errors"
"fmt" "fmt"
"golang.org/x/net/websocket" "golang.org/x/net/websocket"
@ -58,7 +58,7 @@ func main() {
//fmt.Println(common.ObjToStr(makeCode.Db2JSON("admin","test",appIns.Db))) //fmt.Println(common.ObjToStr(makeCode.Db2JSON("admin","test",appIns.Db)))
appIns.Run(hotime.Router{ appIns.Run(hotime.Router{
"admin": admin.Project, //"admin": admin.Project,
"app": hotime.Proj{ "app": hotime.Proj{
"index": hotime.Ctr{ "index": hotime.Ctr{
"test": func(this *hotime.Context) { "test": func(this *hotime.Context) {