添加数据库转 结构体和markdown文档的帮助接口

master
zcy 2021-02-27 16:49:31 +08:00
parent 89eb397c5a
commit 6517252bc8
4 changed files with 106 additions and 0 deletions

View File

@ -35,3 +35,24 @@ func (this *OpenApiController) OndiffCallback(c *gin.Context) {
resp.Msg = "OK" resp.Msg = "OK"
} }
type ReqDDL struct {
Data string `json:"data"`
}
func (this *OpenApiController) DDL2ORM(c *gin.Context) {
var req ReqDDL
var resp RespBase
defer func() {
c.JSON(200, resp)
}()
e := c.Bind(&req)
if e != nil {
log.Println(e.Error())
resp.Msg = "ParaErr"
return
}
resp.Msg = "OK"
}

View File

@ -187,6 +187,7 @@ func main() {
openapi := r.Group("openapi") openapi := r.Group("openapi")
{ {
openapi.POST("/diff") openapi.POST("/diff")
openapi.POST("/ddl2orm")
} }
e := r.Run(":" + strconv.Itoa(config.GetPort())) e := r.Run(":" + strconv.Itoa(config.GetPort()))
if nil != e { if nil != e {

21
test/utils_test.go Normal file
View File

@ -0,0 +1,21 @@
package test
import (
"background/utils"
"log"
"testing"
)
func TestDDL2ORM(t *testing.T) {
ddl := `
CREATE TABLE project (
id int(13) NOT NULL AUTO_INCREMENT,
title varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
content longblob,
contact_info varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
`
tbname, fields := utils.DDL2Field(ddl)
log.Print(tbname, fields)
}

63
utils/helper.go Normal file
View File

@ -0,0 +1,63 @@
package utils
import (
"log"
"strings"
)
type FieldDesc struct {
FiledName string `json:"field_name"`
Type string `json:"type"`
Primary bool `json:"primary"`
}
func TrimUnWanted(in string) string {
ret := ""
ret = strings.Trim(in, "\t")
ret = strings.Trim(in, "\n")
ret = strings.Trim(in, "\x09")
ret = strings.Trim(in, " ")
return ret
}
func DDL2Field(ddl string) (string, []FieldDesc) {
if "" == ddl {
return "", nil
}
ret := make([]FieldDesc, 0)
indexStart := strings.Index(ddl, "CREATE TABLE")
indexFirstParentheses := strings.Index(ddl, "(")
indexLastParentheses := strings.LastIndex(ddl, ")")
sTbNameUnTrim := ddl[indexStart+len("CREATE TABLE") : indexFirstParentheses]
sTableName := strings.Trim(sTbNameUnTrim, " ")
sTbDesc := ddl[indexFirstParentheses+1 : indexLastParentheses]
fields := strings.Split(sTbDesc, ",")
log.Print(fields)
primarykey := []string{}
for _, v := range fields {
if strings.Contains(v, "PRIMARY KEY") {
start := strings.Index(v, "(")
end := strings.LastIndex(v, ")")
primarykey = append(primarykey, v[start+1:end])
} else {
tmp := strings.Split(v, " ")
if len(tmp) > 1 {
ret = append(ret, FieldDesc{
FiledName: strings.Trim(tmp[0], "\n\x09\x09"),
Type: strings.Trim(tmp[1], " "),
Primary: false,
})
}
}
}
for _, key := range primarykey {
for k := range ret {
if 0 == strings.Compare(ret[k].FiledName, key) {
ret[k].Primary = true
}
}
}
return sTableName, ret
}