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 (
|
|
|
|
"fmt"
|
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 20:38:21 +08:00
|
|
|
func ParseCreateTableSql(sql string) {
|
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 {
|
|
|
|
fmt.Println(err.Error(), string(sql[786:]))
|
2021-10-25 18:07:12 +08:00
|
|
|
return
|
|
|
|
}
|
2021-10-25 20:38:21 +08:00
|
|
|
|
|
|
|
r := stmt.(*sqlparser.DDL)
|
|
|
|
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 20:58:11 +08:00
|
|
|
fmt.Println(val)
|
2021-10-25 20:38:21 +08:00
|
|
|
}
|
|
|
|
// fmt.Println(r.TableSpec)
|
2021-10-25 18:07:12 +08:00
|
|
|
}
|