-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
89 lines (76 loc) · 2 KB
/
Copy pathparser.go
File metadata and controls
89 lines (76 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"errors"
"fmt"
"github.com/xwb1989/sqlparser"
"sync"
)
func ParseSQLToFileStruct(sql string, packageName string) (*Table, error) {
stmt, err := sqlparser.Parse(sql)
if err != nil {
return nil, err
}
switch ddl := stmt.(type) {
default:
return nil, errors.New("sql is not DDL")
case *sqlparser.DDL:
//获取表名
tableName := ddl.NewName.Name.String()
//驼峰转换成Go的类型名
goTableName, err := ToCase(cfg.Case.Old, cfg.Case.New, tableName)
if err != nil {
return nil, err
}
//构建模版文件需要的结构体
table := &Table{
TableName: tableName,
GoTableName: goTableName,
PackageName: packageName,
Fields: make([]*Column, 0, len(ddl.TableSpec.Columns)),
ImportPackages: make([]string, 0, 0),
}
var once sync.Once
//字段获取
for _, column := range ddl.TableSpec.Columns {
columnName := column.Name.String()
columnType := column.Type.Type
goColumnName, err := ToCase(cfg.Case.Old, cfg.Case.New, columnName)
if err != nil {
return nil, err
}
//go对应的类型
goColumnType, ok := cfg.TypeMap[columnType]
if !ok {
goColumnType = GoTypeString
}
if goColumnType == GoTypeTime {
once.Do(func() {
table.ImportPackages = append(table.ImportPackages, `"time"`)
})
}
fileColumn := &Column{
GoColumnName: goColumnName,
GoColumnType: goColumnType,
ColumnName: columnName,
ColumnType: columnType,
Tag: make([]*Tag, 0, len(cfg.Tag)),
}
//获取字段的备注
if column.Type.Comment != nil {
fileColumn.ColumnComment = BytesToStr(column.Type.Comment.Val)
}
//组装反射的字段
for _, t := range cfg.Tag {
tagType := TagTypeMap[t]
tagValue := fmt.Sprintf("%s%s%s", tagType.Prefix, columnName, tagType.Suffix)
tag := &Tag{
TagKey: t,
TagValue: tagValue,
}
fileColumn.Tag = append(fileColumn.Tag, tag)
}
table.Fields = append(table.Fields, fileColumn)
}
return table, nil
}
}