gopkg/tool/sql2go/parser.go

65 lines
1.6 KiB
Go
Raw Normal View History

2021-10-25 18:07:12 +08:00
// Package sql2go...
//
// Description : sql2go...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2021-10-25 4:49 下午
package sql2go
import (
2021-10-25 20:38:21 +08:00
"strings"
2021-10-25 18:07:12 +08:00
2021-10-25 20:58:11 +08:00
"git.zhangdeman.cn/zhangdeman/gopkg/util"
2021-10-25 18:07:12 +08:00
"github.com/xwb1989/sqlparser"
)
2021-10-25 20:58:11 +08:00
const (
// CreateSQLColumnTPL 每个字段的模版
CreateSQLColumnTPL = "{FIELD} {TYPE} `json:\"{JSON_TAG}\" gorm:\"column:{COLUMN};default:{DEFAULT_VALUE};{NOT_NULL}\"` // {COMMENT}"
)
2021-10-25 20:38:21 +08:00
// ParseCreateTableSql 解析建表sql
2021-10-25 18:07:12 +08:00
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 4:49 下午 2021/10/25
2021-10-25 21:01:01 +08:00
func ParseCreateTableSql(sql string) (string, error) {
2021-10-25 18:07:12 +08:00
var (
stmt sqlparser.Statement
err error
)
2021-10-25 20:38:21 +08:00
sql = strings.ReplaceAll(sql, " ", "")
if stmt, err = sqlparser.ParseStrictDDL(sql); nil != err {
2021-10-25 21:01:01 +08:00
return "", err
2021-10-25 18:07:12 +08:00
}
2021-10-25 20:38:21 +08:00
r := stmt.(*sqlparser.DDL)
2021-10-25 21:05:42 +08:00
structResult := "type " + util.SnakeCaseToCamel(sqlparser.String(r.NewName)) + " struct { \n"
2021-10-25 20:38:21 +08:00
for _, item := range r.TableSpec.Columns {
2021-10-25 20:58:11 +08:00
data := map[string]string{
"{FIELD}": util.SnakeCaseToCamel(item.Name.String()),
"{COLUMN}": item.Name.String(),
"{JSON_TAG}": item.Name.String(),
"{DEFAULT_VALUE}": "",
"{COMMENT}": item.Name.String() + " " + string(item.Type.Comment.Val),
"{TYPE}": sqlTypeMap[item.Type.Type],
}
if item.Type.NotNull {
data["{NOT_NULL}"] = "NOT NULL"
}
if nil != item.Type.Default {
data["{DEFAULT_VALUE}"] += string(item.Type.Default.Val)
}
val := CreateSQLColumnTPL
for k, v := range data {
val = strings.ReplaceAll(val, k, v)
2021-10-25 20:38:21 +08:00
}
2021-10-25 21:05:42 +08:00
structResult += val + "\n"
2021-10-25 20:38:21 +08:00
}
2021-10-25 21:05:42 +08:00
structResult = structResult + "}"
return structResult, nil
2021-10-25 18:07:12 +08:00
}