From 90cb23d8c984d7ad343fc0c6cb204df9d61a949a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Wed, 17 Nov 2021 12:14:55 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A7=A3=E6=9E=90=E8=A1=A8=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E7=BB=93=E6=9E=84,=E5=A2=9E=E5=8A=A0=E8=A1=A8=E5=9F=BA?= =?UTF-8?q?=E7=A1=80=E4=BF=A1=E6=81=AF=E8=BF=94=E5=9B=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tool/sql2go/parser.go | 36 ++++++++++++++++++++++++++++++------ 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/tool/sql2go/parser.go b/tool/sql2go/parser.go index ea12b53..6cbb3a0 100644 --- a/tool/sql2go/parser.go +++ b/tool/sql2go/parser.go @@ -20,23 +20,44 @@ const ( 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 // // Author : go_developer@163.com<白茶清欢> // // Date : 4:49 下午 2021/10/25 -func ParseCreateTableSql(sql string) (string, error) { +func ParseCreateTableSql(sql string) (string, *BasicTableInfo, error) { var ( - stmt sqlparser.Statement - err error + stmt sqlparser.Statement + 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") if stmt, err = sqlparser.ParseStrictDDL(sql); nil != err { - return "", err + return "", nil, err } 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 { data := map[string]string{ @@ -47,6 +68,9 @@ func ParseCreateTableSql(sql string) (string, error) { "{COMMENT}": item.Name.String() + " " + string(item.Type.Comment.Val), "{TYPE}": sqlTypeMap[item.Type.Type], } + if data["{FIELD}"] == "ID" { + basic.PrimaryFieldType = data["{TYPE}"] + } if item.Type.NotNull { data["{NOT_NULL}"] = "NOT NULL" } @@ -60,5 +84,5 @@ func ParseCreateTableSql(sql string) (string, error) { structResult += val + "\n" } structResult = structResult + "}" - return structResult, nil + return structResult, basic, nil }