/
make_model_fromdb.go
371 lines (334 loc) · 9.81 KB
/
make_model_fromdb.go
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package codemake
import (
"bufio"
"fmt"
"log"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
"time"
"github.com/leancodebox/dbhelper/util"
"github.com/leancodebox/dbhelper/util/config"
"github.com/leancodebox/dbhelper/util/eh"
"github.com/leancodebox/dbhelper/util/str"
"github.com/spf13/cobra"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
)
func init() {
appendCommand(GModel)
}
var GModel = &cobra.Command{
Use: "make:model",
Short: "从db创建gorm",
Run: runGModel,
//Args: cobra.ExactArgs(1), // 只允许且必须传 1 个参数
}
type modelEm struct {
Name string // 字段名
Notes string // 注释
Type string // 字段类型
}
type genColumns struct {
Field string `gorm:"column:Field"`
Type string `gorm:"column:Type"`
Key string `gorm:"column:Key"`
Desc string `gorm:"column:Comment"`
Null string `gorm:"column:Null"`
Default *string `gorm:"column:Default"`
}
func runGModel(_ *cobra.Command, _ []string) {
// init
dataSourceName := config.GetString("ORIGIN_DATABASE_URL")
outputRoot := config.GetString("MODEL_OUTPUT_DIR", "./storage/tmp/model/")
newLogger := logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer(日志输出的目标,前缀和日志包含的内容——译者注)
logger.Config{
SlowThreshold: time.Second, // 慢 SQL 阈值
LogLevel: logger.Error, // 日志级别
IgnoreRecordNotFoundError: true, // 忽略ErrRecordNotFound(记录未找到)错误
Colorful: false, // 禁用彩色打印
},
)
db, err := gorm.Open(mysql.Open(dataSourceName), &gorm.Config{PrepareStmt: false,
NamingStrategy: schema.NamingStrategy{SingularTable: true}, // 全局禁用表名复数
Logger: newLogger})
if eh.PrIF(err) {
return
}
rows, err := db.Raw("show tables").Rows()
tbDesc := make(map[string]string)
if eh.PrIF(err) {
return
}
for rows.Next() {
var table string
eh.PrIF(rows.Scan(&table))
tbDesc[table] = table
}
eh.PrIF(rows.Close())
for tmpTableName, _ := range tbDesc {
var list []genColumns
// Get table annotations.获取表注释
db.Raw("show FULL COLUMNS from " + tmpTableName).Scan(&list)
modelStr, connectStr, repStr := buildModelContent(tmpTableName, list)
modelPath := str.Camel(tmpTableName)
modelEntityPath := outputRoot + modelPath + "/" + modelPath + ".go"
connectPath := outputRoot + modelPath + "/" + modelPath + "_connect.go"
repPath := outputRoot + modelPath + "/" + modelPath + "_rep.go"
util.PutContent(modelEntityPath, modelStr)
util.PutContent(connectPath, connectStr)
if !util.IsExist(repPath) {
util.PutContent(repPath, repStr)
}
}
o, e := exec.Command("gofmt", "-w", outputRoot).Output()
if e != nil {
fmt.Println(e)
} else {
fmt.Println("fmt success", string(o))
}
fmt.Println("build end")
}
type Field struct {
Name string
DBFieldName string
FieldName string
Type string
Index string
StructFieldName string
JsonName string
Pid bool
NullTag string
DefaultTag string
TypeTag string
Comment string
Field string
}
func buildModelContent(tmpTableName string, list []genColumns) (string, string, string) {
dbStd := fmt.Sprintf(`"%v"`, config.GetString("DB_CONNECT", `thh/conf/dbconnect`))
importList := map[string]string{}
var fieldList []Field
for _, value := range list {
var field string
if IsNum(string(value.Field[0])) {
field = "Column" + str.Camel(value.Field)
} else {
field = str.Camel(value.Field)
}
if pkgName, ok := EImportsHead[getTypeName(value.Type, false)]; ok {
importList[pkgName] = pkgName
}
nullTag := ""
if value.Null == "NO" {
nullTag = "not null;"
}
defaultStr := ""
if value.Default != nil {
defaultStr = "default:"
if len(*value.Default) == 0 {
defaultStr += "''"
} else {
defaultStr += *value.Default
}
defaultStr += ";"
}
fieldName := "field" + str.Camel(str.LowerCamel(value.Field))
typeString := `type:` + value.Type
if value.Key == "PRI" {
typeString = `autoIncrement`
fieldName = `pid`
}
typeString += ";"
fieldList = append(fieldList, Field{
Name: value.Field,
DBFieldName: value.Field,
Field: value.Field,
FieldName: fieldName,
StructFieldName: field,
JsonName: str.LowerCamel(value.Field),
Index: value.Key,
Type: getTypeName(value.Type, value.Null != "NO"),
Pid: value.Key == "PRI",
NullTag: nullTag,
DefaultTag: defaultStr,
TypeTag: typeString,
Comment: strings.ReplaceAll(value.Desc, "\n", ""),
})
}
if IsNum(string(tmpTableName[0])) {
tmpTableName = "M" + tmpTableName
}
modelStr := buildByTmpl(
map[string]any{
"TableName": tmpTableName,
"ModelName": str.Camel(tmpTableName),
"importList": importList,
"fieldList": fieldList,
},
"tmpl/db/entity.tmpl",
)
connectStr := buildByTmpl(
map[string]any{
"TableName": tmpTableName,
"ModelName": str.Camel(tmpTableName),
"importList": importList,
"fieldList": fieldList,
"DBPkg": dbStd,
},
"tmpl/db/connect.tmpl",
)
repStr := buildByTmpl(
map[string]any{
"TableName": tmpTableName,
"ModelName": str.Camel(tmpTableName),
"importList": importList,
"fieldList": fieldList,
},
"tmpl/db/rep.tmpl",
)
return modelStr, connectStr, repStr
}
func getFileLine(path string) int {
file, _ := os.Open(path)
defer file.Close()
fileScanner := bufio.NewScanner(file)
lineCount := 0
for fileScanner.Scan() {
lineCount++
}
return lineCount
}
// IsNum 判断是否是数字 用来处理数字开头的字段
func IsNum(s string) bool {
_, err := strconv.ParseFloat(s, 64)
return err == nil
}
// getTypeName Type acquisition filtering.类型获取过滤
func getTypeName(name string, isNull bool) string {
// 优先匹配自定义类型
// Precise matching first.先精确匹配
if v, ok := TypeMysqlDicMp[name]; ok {
return fixNullToPointer(v, isNull)
}
// Fuzzy Regular Matching.模糊正则匹配
for _, l := range TypeMysqlMatchList {
if ok, _ := regexp.MatchString(l.Key, name); ok {
return fixNullToPointer(l.Value, isNull)
}
}
panic(fmt.Sprintf("type (%v) not match in any way.maybe need to add on (https://github.com/xxjwxc/gormt/blob/master/data/view/cnf/def.go)", name))
}
// fixNullToPointer 修复为指针 目前针对所在项目,仅time,设置可设置为nil
func fixNullToPointer(name string, isNull bool) string {
if isNull {
//if strings.HasPrefix(name, "uint") {
// return "*" + name
//}
//if strings.HasPrefix(name, "int") {
// return "*" + name
//}
//if strings.HasPrefix(name, "float") {
// return "*" + name
//}
//if strings.HasPrefix(name, "date") {
// return "*" + name
//}
if strings.HasPrefix(name, "time") {
return "*" + name
}
//if strings.HasPrefix(name, "bool") {
// return "*" + name
//}
//if strings.HasPrefix(name, "string") {
// return "*" + name
//}
}
return name
}
var EImportsHead = map[string]string{
"stirng": `"string"`,
"time.Time": `"time"`,
"gorm.Model": `"gorm.io/gorm"`,
"fmt": `"fmt"`,
"datatypes.JSON": `"gorm.io/datatypes"`,
"datatypes.Date": `"gorm.io/datatypes"`,
}
var TypeMysqlDicMp = map[string]string{
"smallint": "int16",
"smallint unsigned": "uint16",
"int": "int",
"int unsigned": "uint",
"bigint": "int64",
"bigint unsigned": "uint64",
"mediumint": "int32",
"mediumint unsigned": "uint32",
"varchar": "string",
"char": "string",
"date": "time.Time",
"datetime": "time.Time",
"bit(1)": "[]uint8",
"tinyint": "int8",
"tinyint unsigned": "uint8",
"tinyint(1)": "int", // tinyint(1) 默认设置成bool
"tinyint(1) unsigned": "int", // tinyint(1) 默认设置成bool
"json": "string",
"text": "string",
"timestamp": "time.Time",
"double": "float64",
"double unsigned": "float64",
"mediumtext": "string",
"longtext": "string",
"float": "float32",
"float unsigned": "float32",
"tinytext": "string",
"enum": "string",
"time": "time.Time",
"tinyblob": "[]byte",
"blob": "[]byte",
"mediumblob": "[]byte",
"longblob": "[]byte",
"integer": "int64",
"numeric": "float64",
"smalldatetime": "time.Time", //sqlserver
"nvarchar": "string",
"real": "float32",
"binary": "[]byte",
}
var TypeMysqlMatchList = []struct {
Key string
Value string
}{
{`^(tinyint)[(]\d+[)] unsigned`, "uint8"},
{`^(smallint)[(]\d+[)] unsigned`, "uint16"},
{`^(int)[(]\d+[)] unsigned`, "uint32"},
{`^(bigint)[(]\d+[)] unsigned`, "uint64"},
{`^(float)[(]\d+,\d+[)] unsigned`, "float64"},
{`^(double)[(]\d+,\d+[)] unsigned`, "float64"},
{`^(tinyint)[(]\d+[)]`, "int8"},
{`^(smallint)[(]\d+[)]`, "int16"},
{`^(int)[(]\d+[)]`, "int"},
{`^(bigint)[(]\d+[)]`, "int64"},
{`^(char)[(]\d+[)]`, "string"},
{`^(enum)[(](.)+[)]`, "string"},
{`^(varchar)[(]\d+[)]`, "string"},
{`^(varbinary)[(]\d+[)]`, "[]byte"},
{`^(blob)[(]\d+[)]`, "[]byte"},
{`^(binary)[(]\d+[)]`, "[]byte"},
{`^(decimal)[(]\d+,\d+[)]`, "float64"},
{`^(mediumint)[(]\d+[)]`, "int16"},
{`^(mediumint)[(]\d+[)] unsigned`, "uint16"},
{`^(double)[(]\d+,\d+[)]`, "float64"},
{`^(float)[(]\d+,\d+[)]`, "float64"},
{`^(datetime)[(]\d+[)]`, "time.Time"},
{`^(bit)[(]\d+[)]`, "[]uint8"},
{`^(text)[(]\d+[)]`, "string"},
{`^(integer)[(]\d+[)]`, "int"},
{`^(timestamp)[(]\d+[)]`, "time.Time"},
{`^(geometry)[(]\d+[)]`, "[]byte"},
{`^(set)[(][\s\S]+[)]`, "string"},
}