|
|
|
@ -11,6 +11,7 @@ import ( |
|
|
|
"sync" |
|
|
|
"text/template" |
|
|
|
"time" |
|
|
|
"unicode" |
|
|
|
|
|
|
|
"github.com/gin-contrib/cors" |
|
|
|
"github.com/gin-gonic/gin" |
|
|
|
@ -45,6 +46,7 @@ type options struct { |
|
|
|
Package string |
|
|
|
GormType bool |
|
|
|
ForceTableName bool |
|
|
|
Camel bool // 是否json字段驼峰
|
|
|
|
} |
|
|
|
|
|
|
|
var defaultOptions = options{ |
|
|
|
@ -106,6 +108,12 @@ func WithPackage(pkg string) Option { |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
func WithCamel() Option { |
|
|
|
return func(o *options) { |
|
|
|
o.Camel = true |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
// WithGormType will write type in gorm tag
|
|
|
|
func WithGormType() Option { |
|
|
|
return func(o *options) { |
|
|
|
@ -215,6 +223,29 @@ type tmplField struct { |
|
|
|
Comment string |
|
|
|
} |
|
|
|
|
|
|
|
// 下划线写法转为小驼峰写法
|
|
|
|
func Case2Camel(name string) string { |
|
|
|
name = strings.Replace(name, "_", " ", -1) |
|
|
|
name = strings.Title(name) |
|
|
|
return Lcfirst(strings.Replace(name, " ", "", -1)) |
|
|
|
} |
|
|
|
|
|
|
|
// 首字母大写
|
|
|
|
func Ucfirst(str string) string { |
|
|
|
for i, v := range str { |
|
|
|
return string(unicode.ToUpper(v)) + str[i+1:] |
|
|
|
} |
|
|
|
return "" |
|
|
|
} |
|
|
|
|
|
|
|
// 首字母小写
|
|
|
|
func Lcfirst(str string) string { |
|
|
|
for i, v := range str { |
|
|
|
return string(unicode.ToLower(v)) + str[i+1:] |
|
|
|
} |
|
|
|
return "" |
|
|
|
} |
|
|
|
|
|
|
|
func makeCode(stmt *ast.CreateTableStmt, opt options) (string, []string, error) { |
|
|
|
importPath := make([]string, 0, 1) |
|
|
|
data := tmplData{ |
|
|
|
@ -309,7 +340,11 @@ func makeCode(stmt *ast.CreateTableStmt, opt options) (string, []string, error) |
|
|
|
tags = append(tags, "gorm", gormTag.String()) |
|
|
|
|
|
|
|
if opt.JsonTag { |
|
|
|
tags = append(tags, "json", colName) |
|
|
|
if opt.Camel { |
|
|
|
tags = append(tags, "json", Case2Camel(colName)) |
|
|
|
} else { |
|
|
|
tags = append(tags, "json", colName) |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
if opt.ZhTag { |
|
|
|
@ -479,16 +514,22 @@ func main() { |
|
|
|
r.POST("/sql", func(c *gin.Context) { |
|
|
|
var req struct { |
|
|
|
Content string `json:"content"` |
|
|
|
Camel bool `json:"camel"` |
|
|
|
} |
|
|
|
err := c.BindJSON(&req) |
|
|
|
if err != nil { |
|
|
|
c.String(http.StatusBadRequest, err.Error()) |
|
|
|
return |
|
|
|
} |
|
|
|
opts := []Option{} |
|
|
|
opts = append(opts, WithGormType()) |
|
|
|
opts = append(opts, WithJsonTag()) |
|
|
|
opts = append(opts, WithZhTag()) |
|
|
|
if req.Camel { |
|
|
|
opts = append(opts, WithCamel()) |
|
|
|
} |
|
|
|
res, err := ParseSqlFormat(req.Content, |
|
|
|
WithGormType(), |
|
|
|
WithJsonTag(), |
|
|
|
WithZhTag(), |
|
|
|
opts..., |
|
|
|
) |
|
|
|
if err != nil { |
|
|
|
c.String(http.StatusInternalServerError, err.Error()) |
|
|
|
|