sql转golang sructcode 实现

master
DESKTOP-4RNDQIC\29019 2021-02-28 01:45:34 +08:00
parent 6517252bc8
commit 214b3203e7
4 changed files with 90 additions and 13 deletions

View File

@ -1,6 +1,7 @@
package controller package controller
import ( import (
"background/utils"
"log" "log"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@ -42,7 +43,9 @@ type ReqDDL struct {
func (this *OpenApiController) DDL2ORM(c *gin.Context) { func (this *OpenApiController) DDL2ORM(c *gin.Context) {
var req ReqDDL var req ReqDDL
var resp RespBase resp := RespBase{
Msg: "err",
}
defer func() { defer func() {
c.JSON(200, resp) c.JSON(200, resp)
}() }()
@ -53,6 +56,10 @@ func (this *OpenApiController) DDL2ORM(c *gin.Context) {
resp.Msg = "ParaErr" resp.Msg = "ParaErr"
return return
} }
tbname, fields := utils.DDL2Field(req.Data)
log.Print(tbname, fields)
gocode := utils.CreateGoStruct(tbname,fields)
resp.Data = gocode
resp.Msg = "OK" resp.Msg = "OK"
resp.Status = 0
} }

View File

@ -28,6 +28,7 @@ var (
mailContoller = controller.MailController{} mailContoller = controller.MailController{}
fileController = controller.FileController{} fileController = controller.FileController{}
planController = controller.PlanController{} planController = controller.PlanController{}
openapiController = controller.OpenApiController{}
) )
func CORSMiddleware(c *gin.Context) { func CORSMiddleware(c *gin.Context) {
@ -36,7 +37,7 @@ func CORSMiddleware(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "https://testingcloud.club") c.Writer.Header().Set("Access-Control-Allow-Origin", "https://testingcloud.club")
} else { } else {
c.Writer.Header().Set("Access-Control-Allow-Origin", "http://localhost:8080") c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
} }
c.Writer.Header().Set("Access-Control-Max-Age", "86400") c.Writer.Header().Set("Access-Control-Max-Age", "86400")
c.Writer.Header().Set("Access-Control-Allow-Headers", c.Writer.Header().Set("Access-Control-Allow-Headers",
@ -187,7 +188,7 @@ func main() {
openapi := r.Group("openapi") openapi := r.Group("openapi")
{ {
openapi.POST("/diff") openapi.POST("/diff")
openapi.POST("/ddl2orm") openapi.POST("/ddl2orm",openapiController.DDL2ORM)
} }
e := r.Run(":" + strconv.Itoa(config.GetPort())) e := r.Run(":" + strconv.Itoa(config.GetPort()))
if nil != e { if nil != e {

View File

@ -18,4 +18,6 @@ func TestDDL2ORM(t *testing.T) {
` `
tbname, fields := utils.DDL2Field(ddl) tbname, fields := utils.DDL2Field(ddl)
log.Print(tbname, fields) log.Print(tbname, fields)
gocode := utils.CreateGoStruct(tbname,fields)
log.Print(gocode)
} }

View File

@ -1,30 +1,94 @@
package utils package utils
import ( import (
"fmt"
"log" "log"
"strings" "strings"
) )
// 蛇形转驼峰
func toCamelString(s string) string {
data := make([]byte, 0, len(s))
j := false
k := false
num := len(s) - 1
for i := 0; i <= num; i++ {
d := s[i]
if k == false && d >= 'A' && d <= 'Z' {
k = true
}
if d >= 'a' && d <= 'z' && (j || k == false) {
d = d - 32
j = false
k = true
}
if k && d == '_' && num > i && s[i+1] >= 'a' && s[i+1] <= 'z' {
j = true
continue
}
data = append(data, d)
}
return string(data[:])
}
type FieldDesc struct { type FieldDesc struct {
FiledName string `json:"field_name"` FiledName string `json:"field_name"`
Type string `json:"type"` Type string `json:"type"`
Primary bool `json:"primary"` Primary bool `json:"primary"`
} }
func TrimUnWanted(in string) string { func DDLType2Golang(types string)string{
ret := "" if strings.Contains(types,"int"){
ret = strings.Trim(in, "\t") return "int32"
ret = strings.Trim(in, "\n") }
ret = strings.Trim(in, "\x09") if strings.Contains(types,"varchar"){
ret = strings.Trim(in, " ") return "string"
}
if strings.Contains(types,"longblob"){
return "[]byte"
}
if strings.Contains(types,"date"){
return "time.Time"
}
return "interface"
}
func CreateGoStruct(name string,doc []FieldDesc) string{
if name == "" {
return ""
}
if len(doc) == 0{
return ""
}
ret := fmt.Sprintf("type %s struct{\r\n",toCamelString(name))
for _,v := range doc{
filed := "\t\t"
camelField := toCamelString(v.FiledName)
filed += camelField
tag := fmt.Sprintf("`json:\"%s\" gorm:\"column:%s\" sql:\"%s\"`",v.FiledName,v.FiledName,v.FiledName)
filed += " " + DDLType2Golang(v.Type) + " " + tag + " \r\n"
ret += filed
}
ret += "}"
return ret return ret
} }
func TrimUnWanted(in string) string {
ret := strings.ReplaceAll(in, "\t","")
ret = strings.ReplaceAll(ret, "\n","")
ret = strings.ReplaceAll(ret, "\x09","")
ret = strings.ReplaceAll(ret, "\r","")
ret = strings.ReplaceAll(ret, "\x0a","")
ret = strings.TrimLeft(ret," ")
return ret
}
func DDL2Field(ddl string) (string, []FieldDesc) { func DDL2Field(ddl string) (string, []FieldDesc) {
if "" == ddl { if "" == ddl {
return "", nil return "", nil
} }
ret := make([]FieldDesc, 0) ret := make([]FieldDesc, 0)
ddl = strings.ReplaceAll(ddl,"`","")
log.Print(ddl)
indexStart := strings.Index(ddl, "CREATE TABLE") indexStart := strings.Index(ddl, "CREATE TABLE")
indexFirstParentheses := strings.Index(ddl, "(") indexFirstParentheses := strings.Index(ddl, "(")
indexLastParentheses := strings.LastIndex(ddl, ")") indexLastParentheses := strings.LastIndex(ddl, ")")
@ -34,7 +98,7 @@ func DDL2Field(ddl string) (string, []FieldDesc) {
sTbDesc := ddl[indexFirstParentheses+1 : indexLastParentheses] sTbDesc := ddl[indexFirstParentheses+1 : indexLastParentheses]
fields := strings.Split(sTbDesc, ",") fields := strings.Split(sTbDesc, ",")
log.Print(fields)
primarykey := []string{} primarykey := []string{}
for _, v := range fields { for _, v := range fields {
if strings.Contains(v, "PRIMARY KEY") { if strings.Contains(v, "PRIMARY KEY") {
@ -42,11 +106,14 @@ func DDL2Field(ddl string) (string, []FieldDesc) {
end := strings.LastIndex(v, ")") end := strings.LastIndex(v, ")")
primarykey = append(primarykey, v[start+1:end]) primarykey = append(primarykey, v[start+1:end])
} else { } else {
v = TrimUnWanted(v)
log.Print(v)
tmp := strings.Split(v, " ") tmp := strings.Split(v, " ")
if len(tmp) > 1 { if len(tmp) > 1 {
log.Print(tmp[0])
ret = append(ret, FieldDesc{ ret = append(ret, FieldDesc{
FiledName: strings.Trim(tmp[0], "\n\x09\x09"), FiledName: TrimUnWanted(tmp[0]),
Type: strings.Trim(tmp[1], " "), Type: strings.Trim(tmp[1], " "),
Primary: false, Primary: false,
}) })
} }