-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmysql.go
606 lines (536 loc) · 13.6 KB
/
mysql.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
package ormtool
import (
"database/sql"
"fmt"
"log"
"strings"
)
type serviceInterface interface {
genStruct() (fileData FileInfo, data []StructInfo)
listTables() []tableInfo
listColumns() map[string][]column
dealColumn(t *tableInfo)
dealStructContent(t tableInfo) string
dealType(c Config, typeSimple, typeDetail string) string
getCreateSQL(tableName string) string
gen()
}
func GenerateMySQL(c Config) {
newService(c).gen()
log.Println("-----generate done-----")
}
type service struct {
DB *sql.DB
Info []StructInfo
// save model file
FileSave FileInfo
dbName string
Conf Config
}
func newService(c Config) serviceInterface {
conn, err := mysqlConn(c.ConnStr)
if err != nil {
log.Fatalln(err)
}
return service{DB: conn, dbName: c.Database, Conf: c}
}
func (s service) gen() {
defer func(db *sql.DB) {
err := db.Close()
if err != nil {
log.Fatalln(err)
}
}(s.DB)
fileSave, data := s.genStruct()
// write into file
Write(fileSave, data, s.Conf.IsGenInOneFile)
}
type tableInfo struct {
// 表名
TableName string
// 表备注
TableComment string
// 字段数组
column []column
}
type column struct {
ColumnDBName string
ColumnName string
//example: varchar
DataType string
//example: varchar(32)
// 字段类型
ColumnType string
//default value
// 默认值
Default interface{}
TableName string
// 字段备注
ColumnComment string
//Length interface{}
IsNullable string
//ColumnKey string
// 结构体tag值
Tag string
}
// GenStruct struct info, include: struct comment, create table sql
func (s service) genStruct() (fileSave FileInfo, data []StructInfo) {
// save file info
s.FileSave.PackageName, s.FileSave.FileDir, s.FileSave.FileName = DealFilePath(s.Conf.SavePath, s.dbName)
// 查询所有表
tables := s.listTables()
// 查询所有字段
columns := s.listColumns()
// deal per table
for _, table := range tables {
if v, ok := columns[table.TableName]; ok {
table.column = v
}
var info StructInfo
// table name
info.TableName = table.TableName
// create table sql
if s.Conf.IsGenCreateSQL {
info.CreateSQL = s.getCreateSQL(table.TableName)
}
// deal column
s.dealColumn(&table)
// struct info
info.StructContent = s.dealStructContent(table)
info.FileName = lowerCamel(table.TableName)
info.Name = UpperCamel(table.TableName)
// table comment
// add if table comment exists
if table.TableComment != "" || s.Conf.IsGenCreateSQL {
info.Note = "// " + info.Name + "\t" + table.TableComment + "\n"
}
if s.Conf.IsGenFunction {
// simple function
if s.Conf.IsGenFunctionWithCache {
info.ImportInfo = []string{"context", "encoding/json", "strconv", "github.com/go-redis/redis/v8",
"gorm.io/gorm", "time"}
info.Function = s.genFunctionWithCache(info.Name)
} else {
info.ImportInfo = []string{"gorm.io/gorm"}
info.Function = s.genFunction(info.Name)
}
}
s.Info = append(s.Info, info)
}
return s.FileSave, s.Info
}
func (s service) genFunction(name string) string {
var info strings.Builder
info.WriteString("// function\n")
interfaceName := name + "ModelInterface"
interfaceContent := `
type %s interface{
Create(tx *gorm.DB,data *%s) error
Get(tx *gorm.DB,id int) (%s,error)
Find(tx *gorm.DB,page,limit int) ([]%s,int64,error)
Update(tx *gorm.DB, update map[string]interface{}) error
DeleteByID(tx *gorm.DB,id int) error
}
`
info.WriteString(fmt.Sprintf(interfaceContent, interfaceName, name, name, name))
info.WriteString("\n")
// 2
modelServiceName := strings.ToLower(name[0:1]) + name[1:] + "ModelService"
modelService := `
type %s struct{
}
`
info.WriteString(fmt.Sprintf(modelService, modelServiceName))
info.WriteString("\n")
newModelService := `
func New%sModelService() %s {
return %s{}
}
`
info.WriteString(fmt.Sprintf(newModelService, name, interfaceName, modelServiceName))
info.WriteString("\n")
// 3
create := `
func (s %s) Create(tx *gorm.DB,data *%s) error{
err:=tx.Create(data).Error
if err != nil{
return err
}
return nil
}
`
info.WriteString(fmt.Sprintf(create, modelServiceName, name))
info.WriteString("\n")
//func (s userModelService) Get(id int) (User, error) {
// var u User
// err := s.db.Where(id).Find(&u).Limit(1).Error
// if err != nil {
// return User{}, err
// }
// return u, nil
//}
get := `
func (s %s) Get(tx *gorm.DB,id int) (%s,error){
var data %s
err:=tx.Where(id).Limit(1).Find(&data).Error
if err != nil{
return %s{},err
}
return data,nil
}
`
info.WriteString(fmt.Sprintf(get, modelServiceName, name, name, name))
info.WriteString("\n")
find := `
func (s %s) Find(tx *gorm.DB,page,limit int) ([]%s,int64,error){
var list []%s
tx=tx.Model(&%s{})
err:=tx.Offset(limit * (page - 1)).Limit(limit).Find(&list).Error
if err != nil{
return nil,0,err
}
var count int64
err = tx.Count(&count).Error
if err != nil {
return nil,0,err
}
return list,count,nil
}
`
info.WriteString(fmt.Sprintf(find, modelServiceName, name, name, name))
info.WriteString("\n")
update := `
func (s %s) Update(tx *gorm.DB, update map[string]interface{}) error {
err:=tx.Model(&%s{}).Updates(update).Error
if err != nil{
return err
}
return nil
}
`
info.WriteString(fmt.Sprintf(update, modelServiceName, name))
info.WriteString("\n")
del := `
func (s %s) DeleteByID(tx *gorm.DB,id int) error {
err:=tx.Where(id).Delete(&%s{}).Error
if err != nil{
return err
}
return nil
}
`
info.WriteString(fmt.Sprintf(del, modelServiceName, name))
info.WriteString("\n")
return info.String()
}
func (s service) genFunctionWithCache(name string) string {
var info strings.Builder
camelName := strings.ToLower(name[0:1]) + name[1:]
info.WriteString("// function\n")
cacheName := fmt.Sprintf("%sCache", camelName)
invalidCacheName := fmt.Sprintf("%sInvalidCache", camelName)
info.WriteString(fmt.Sprintf("var %s=\"cache%s:\"\n", cacheName, name))
info.WriteString(fmt.Sprintf("var %s=\"invalidCache%s:\"\n", invalidCacheName, name))
interfaceName := name + "ModelInterface"
interfaceContent := `
type %s interface{
Create(tx *gorm.DB,data *%s) error
Get(tx *gorm.DB,id int) (%s,error)
Find(tx *gorm.DB,page,limit int) ([]%s,int64,error)
Update(tx *gorm.DB, update map[string]interface{}) error
DeleteByID(tx *gorm.DB,id int) error
DeleteCache(id int)
}
`
info.WriteString(fmt.Sprintf(interfaceContent, interfaceName, name, name, name))
info.WriteString("\n")
// 2
modelServiceName := camelName + "ModelService"
modelService := `
type %s struct{
rdb *redis.Client
}
`
info.WriteString(fmt.Sprintf(modelService, modelServiceName))
info.WriteString("\n")
newModelService := `
func New%sModelService(redisDB *redis.Client) %s {
return %s{rdb:redisDB}
}
`
info.WriteString(fmt.Sprintf(newModelService, name, interfaceName, modelServiceName))
info.WriteString("\n")
// 3
create := `
func (s %s) Create(tx *gorm.DB,data *%s) error{
err:=tx.Create(data).Error
if err != nil{
return err
}
marshal, err := json.Marshal(data)
if err != nil {
return err
}
s.rdb.Set(context.Background(),%s+strconv.Itoa(data.Id),string(marshal),time.Hour*48)
return nil
}
`
info.WriteString(fmt.Sprintf(create, modelServiceName, name, cacheName))
info.WriteString("\n")
get := `
func (s %s) Get(tx *gorm.DB,id int) (%s,error){
invalidKey := %s + strconv.Itoa(id)
if s.rdb.Exists(context.Background(), invalidKey).Val() > 0 {
return %s{}, nil
}
var data %s
key := %s + strconv.Itoa(id)
if s.rdb.Exists(context.Background(), key).Val() > 0 {
bytes, err := s.rdb.Get(context.Background(), key).Bytes()
if err != nil {
return %s{}, err
}
err = json.Unmarshal(bytes, &data)
if err != nil {
return %s{}, err
}
return data, nil
}
err:=tx.Where(id).Limit(1).Find(&data).Error
if err != nil{
return %s{},err
}
if data.Id!=0 {
// exist
marshal, err := json.Marshal(data)
if err != nil {
return data,err
}
s.rdb.Set(context.Background(),%s+strconv.Itoa(data.Id),string(marshal),time.Hour*48)
return data,nil
}
s.rdb.Set(context.Background(),invalidKey,"",time.Minute*2)
return data,nil
}
`
info.WriteString(fmt.Sprintf(get, modelServiceName, name, invalidCacheName, name, name, cacheName, name, name, name, cacheName))
info.WriteString("\n")
find := `
func (s %s) Find(tx *gorm.DB,page,limit int) ([]%s,int64,error){
var list []%s
var count int64
tx=tx.Model(&%s{})
err := tx.Count(&count).Error
if err != nil {
return nil,0,err
}
err=tx.Offset(limit * (page - 1)).Limit(limit).Find(&list).Error
if err != nil{
return nil,0,err
}
return list,count,nil
}
`
info.WriteString(fmt.Sprintf(find, modelServiceName, name, name, name))
info.WriteString("\n")
update := `
func (s %s) Update(tx *gorm.DB, update map[string]interface{}) error {
err:=tx.Model(&%s{}).Updates(update).Error
if err != nil{
return err
}
return nil
}
`
info.WriteString(fmt.Sprintf(update, modelServiceName, name))
info.WriteString("\n")
del := `
func (s %s) DeleteByID(tx *gorm.DB,id int) error {
err:=tx.Where(id).Delete(&%s{}).Error
if err != nil{
return err
}
s.DeleteCache(id)
return nil
}
`
info.WriteString(fmt.Sprintf(del, modelServiceName, name))
info.WriteString("\n")
delCache := `
func (s %s) DeleteCache(id int){
s.rdb.Del(context.Background(),%s+strconv.Itoa(id))
}
`
info.WriteString(fmt.Sprintf(delCache, modelServiceName, cacheName))
info.WriteString("\n")
return info.String()
}
// DealColumn deal column type and generate struct tag info
func (s service) dealColumn(t *tableInfo) {
for i := 0; i < len(t.column); i++ {
var f bool
if s.Conf.IsGenJsonTag {
//生成 json tag
f = true
t.column[i].Tag = "`json:\"" + JsonTag(s.Conf.JsonTagType, t.column[i].ColumnName) + "\""
}
if s.Conf.GenDBInfoType == 2 {
t.column[i].Tag = t.column[i].Tag + " "
}
switch s.Conf.GenDBInfoType {
case 1:
case 2:
if !f {
t.column[i].Tag += "`"
}
f = true
t.column[i].Tag += "db:\"" + t.column[i].ColumnType
var sNull string
if t.column[i].IsNullable == "NO" {
sNull = " not null"
}
t.column[i].Tag += sNull
if t.column[i].Default != nil {
t.column[i].Tag += " default " + string(t.column[i].Default.([]uint8))
}
t.column[i].Tag += "\""
}
if f {
t.column[i].Tag += "`"
}
t.column[i].ColumnName = UpperCamel(t.column[i].ColumnName)
t.column[i].ColumnType = s.dealType(s.Conf, t.column[i].DataType, t.column[i].ColumnType)
}
}
func (s service) dealStructContent(t tableInfo) string {
var info strings.Builder
// struct name
structName := UpperCamel(t.TableName)
info.WriteString("type " + structName + " struct {\n")
for _, v := range t.column {
info.WriteString("\t")
info.WriteString(v.ColumnName)
info.WriteString("\t")
info.WriteString(v.ColumnType)
info.WriteString("\t")
info.WriteString(v.Tag)
info.WriteString("\t")
if v.ColumnComment != "" {
info.WriteString(" // ")
info.WriteString(v.ColumnComment)
}
info.WriteString("\n")
}
info.WriteString("}\n\n")
if s.Conf.IsGenTableName {
// function for get table name in database
info.WriteString("func (*" + structName + ") TableName() string {\n")
info.WriteString("return \"" + t.TableName + "\"")
info.WriteString("\n}\n")
}
info.WriteString("var " + structName + "Col = struct {\n")
for _, v := range t.column {
info.WriteString(v.ColumnName)
info.WriteString("\t" + "string\n")
}
info.WriteString("}{\n")
for _, v := range t.column {
info.WriteString(v.ColumnName)
info.WriteString(":\t\"" + strings.ToLower(v.ColumnDBName) + "\"" + ",\n")
}
info.WriteString("\n}\n")
return info.String()
}
// 判断字段类型,优先使用自定义对应类型
func (s service) dealType(c Config, typeSimple, typeDetail string) string {
if v, ok := c.CustomType[typeDetail]; ok {
return v
}
switch typeSimple {
case "int":
return mysqlToGo[typeDetail]
default:
return mysqlToGo[typeSimple]
}
}
type CreateSQL struct {
Table string `json:"Table"`
SQL string `json:"Create Table"`
}
// GetCreateSQL sql of creating table in the database
// 表创建语句
func (s service) getCreateSQL(tableName string) string {
sqlStr := "show create table " + tableName
rows, err := s.DB.Query(sqlStr)
if err != nil {
log.Fatalln(err.Error())
}
defer func(rows *sql.Rows) {
err := rows.Close()
if err != nil {
log.Fatalln(err)
}
}(rows)
var cSql CreateSQL
for rows.Next() {
err = rows.Scan(&cSql.Table, &cSql.SQL)
if err != nil {
log.Fatalln(err.Error())
}
}
var info strings.Builder
info.WriteString("/*")
info.WriteString(cSql.SQL)
info.WriteString("*/\n")
return info.String()
}
func (s service) listColumns() map[string][]column {
tables := make(map[string][]column)
sqlStr := `SELECT COLUMN_NAME,DATA_TYPE,COLUMN_TYPE,COLUMN_DEFAULT,TABLE_NAME,
COLUMN_COMMENT
FROM information_schema.COLUMNS WHERE table_schema = ? order by ORDINAL_POSITION`
rows, err := s.DB.Query(sqlStr, s.dbName)
if err != nil {
log.Fatalln(err.Error())
}
defer func(rows *sql.Rows) {
err := rows.Close()
if err != nil {
log.Fatalln(err)
}
}(rows)
for rows.Next() {
col := column{}
err = rows.Scan(&col.ColumnName, &col.DataType, &col.ColumnType, &col.Default,
&col.TableName, &col.ColumnComment)
if err != nil {
log.Fatalln(err.Error())
}
col.ColumnDBName = col.ColumnName
tables[col.TableName] = append(tables[col.TableName], col)
}
return tables
}
func (s service) listTables() []tableInfo {
sqlStr := `select Table_Name,Table_Comment from information_schema.TABLES where TABLE_SCHEMA=?`
rows, err := s.DB.Query(sqlStr, s.dbName)
if err != nil {
log.Fatalln(err.Error())
}
defer func(rows *sql.Rows) {
err := rows.Close()
if err != nil {
log.Fatalln(err)
}
}(rows)
var list []tableInfo
for rows.Next() {
var i tableInfo
err := rows.Scan(&i.TableName, &i.TableComment)
if err != nil {
log.Fatalln(err)
}
list = append(list, i)
}
return list
}