65 lines
1.7 KiB
Go
65 lines
1.7 KiB
Go
// Package sql2go...
|
|
//
|
|
// Description : sql2go...
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 2021-10-25 4:49 下午
|
|
package sql2go
|
|
|
|
import (
|
|
"strings"
|
|
|
|
"git.zhangdeman.cn/zhangdeman/gopkg/util"
|
|
|
|
"github.com/xwb1989/sqlparser"
|
|
)
|
|
|
|
const (
|
|
// CreateSQLColumnTPL 每个字段的模版
|
|
CreateSQLColumnTPL = "{FIELD} {TYPE} `json:\"{JSON_TAG}\" gorm:\"column:{COLUMN};default:{DEFAULT_VALUE};{NOT_NULL}\"` // {COMMENT}"
|
|
)
|
|
|
|
// ParseCreateTableSql 解析建表sql
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 4:49 下午 2021/10/25
|
|
func ParseCreateTableSql(sql string) (string, error) {
|
|
var (
|
|
stmt sqlparser.Statement
|
|
err error
|
|
)
|
|
sql = strings.ReplaceAll(strings.ToUpper(sql), "CURRENT_TIMESTAMP()", "CURRENT_TIMESTAMP")
|
|
if stmt, err = sqlparser.ParseStrictDDL(sql); nil != err {
|
|
return "", err
|
|
}
|
|
|
|
r := stmt.(*sqlparser.DDL)
|
|
structResult := "type " + util.SnakeCaseToCamel(sqlparser.String(r.NewName)) + " struct { \n"
|
|
|
|
for _, item := range r.TableSpec.Columns {
|
|
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)
|
|
}
|
|
structResult += val + "\n"
|
|
}
|
|
structResult = structResult + "}"
|
|
return structResult, nil
|
|
}
|