解析表数据结构,增加表基础信息返回

This commit is contained in:
白茶清欢 2021-11-17 12:14:55 +08:00
parent c97a3b3bcb
commit 90cb23d8c9

View File

@ -20,23 +20,44 @@ const (
CreateSQLColumnTPL = "{FIELD} {TYPE} `json:\"{JSON_TAG}\" gorm:\"column:{COLUMN};default:{DEFAULT_VALUE};{NOT_NULL}\"` // {COMMENT}" 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
}
// ParseCreateTableSql 解析建表sql // ParseCreateTableSql 解析建表sql
// //
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 4:49 下午 2021/10/25 // Date : 4:49 下午 2021/10/25
func ParseCreateTableSql(sql string) (string, error) { func ParseCreateTableSql(sql string) (string, *BasicTableInfo, error) {
var ( var (
stmt sqlparser.Statement stmt sqlparser.Statement
err error err error
basic *BasicTableInfo
) )
basic = &BasicTableInfo{
TableName: "",
ModelStruct: "",
PrimaryField: "ID",
PrimaryFieldType: "",
}
sql = strings.ReplaceAll(strings.ReplaceAll(sql, "CURRENT_TIMESTAMP()", "CURRENT_TIMESTAMP"), "current_timestamp()", "CURRENT_TIMESTAMP") sql = strings.ReplaceAll(strings.ReplaceAll(sql, "CURRENT_TIMESTAMP()", "CURRENT_TIMESTAMP"), "current_timestamp()", "CURRENT_TIMESTAMP")
if stmt, err = sqlparser.ParseStrictDDL(sql); nil != err { if stmt, err = sqlparser.ParseStrictDDL(sql); nil != err {
return "", err return "", nil, err
} }
r := stmt.(*sqlparser.DDL) r := stmt.(*sqlparser.DDL)
structResult := "type " + util.SnakeCaseToCamel(sqlparser.String(r.NewName)) + " struct { \n" basic.TableName = sqlparser.String(r.NewName)
basic.ModelStruct = util.SnakeCaseToCamel(basic.TableName)
structResult := "type " + basic.ModelStruct + " struct { \n"
for _, item := range r.TableSpec.Columns { for _, item := range r.TableSpec.Columns {
data := map[string]string{ data := map[string]string{
@ -47,6 +68,9 @@ func ParseCreateTableSql(sql string) (string, error) {
"{COMMENT}": item.Name.String() + " " + string(item.Type.Comment.Val), "{COMMENT}": item.Name.String() + " " + string(item.Type.Comment.Val),
"{TYPE}": sqlTypeMap[item.Type.Type], "{TYPE}": sqlTypeMap[item.Type.Type],
} }
if data["{FIELD}"] == "ID" {
basic.PrimaryFieldType = data["{TYPE}"]
}
if item.Type.NotNull { if item.Type.NotNull {
data["{NOT_NULL}"] = "NOT NULL" data["{NOT_NULL}"] = "NOT NULL"
} }
@ -60,5 +84,5 @@ func ParseCreateTableSql(sql string) (string, error) {
structResult += val + "\n" structResult += val + "\n"
} }
structResult = structResult + "}" structResult = structResult + "}"
return structResult, nil return structResult, basic, nil
} }