gopkg/tool/sql2go/parser.go

93 lines
2.4 KiB
Go
Raw Permalink 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 (
2022-01-14 18:34:28 +08:00
"errors"
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}"
)
// BasicTableInfo ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 11:47 上午 2021/11/17
type BasicTableInfo struct {
TableName string
ModelStruct string
PrimaryField string
PrimaryFieldType string
}
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
func ParseCreateTableSql(sql string) (string, *BasicTableInfo, error) {
2021-10-25 18:07:12 +08:00
var (
stmt sqlparser.Statement
err error
basic *BasicTableInfo
2021-10-25 18:07:12 +08:00
)
basic = &BasicTableInfo{
TableName: "",
ModelStruct: "",
PrimaryField: "ID",
PrimaryFieldType: "",
}
2021-11-17 11:32:13 +08:00
sql = strings.ReplaceAll(strings.ReplaceAll(sql, "CURRENT_TIMESTAMP()", "CURRENT_TIMESTAMP"), "current_timestamp()", "CURRENT_TIMESTAMP")
2021-10-25 20:38:21 +08:00
if stmt, err = sqlparser.ParseStrictDDL(sql); nil != err {
return "", nil, err
2021-10-25 18:07:12 +08:00
}
2021-10-25 20:38:21 +08:00
2022-01-14 18:34:28 +08:00
r, ok := stmt.(*sqlparser.DDL)
if !ok {
return "", nil, errors.New("input sql is not ddl")
}
basic.TableName = sqlparser.String(r.NewName)
basic.ModelStruct = util.SnakeCaseToCamel(basic.TableName)
structResult := "type " + basic.ModelStruct + " struct { \n"
2021-10-25 21:05:42 +08:00
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 data["{FIELD}"] == "ID" {
basic.PrimaryFieldType = data["{TYPE}"]
}
2021-10-25 20:58:11 +08:00
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, basic, nil
2021-10-25 18:07:12 +08:00
}