-
Notifications
You must be signed in to change notification settings - Fork 34
/
logic.go
581 lines (557 loc) · 14.5 KB
/
logic.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
package main
import (
"bytes"
"fmt"
"html/template"
"log"
"strings"
"sync"
"time"
)
type Logic struct {
T *Tools
DB *ModelS
Path string
Once sync.Once
l sync.Mutex
}
// 生成结构实体文件
func (l *Logic) CreateEntity(formatList []string) (err error) {
// 表结构文件路径
path := CreateDir(l.Path+GODIR_Entity) + DS + GOFILE_ENTITY
// 将表结构写入文件
for idx, table := range l.DB.DoTables {
idx++
// 查询表结构信息
tableDesc, err := l.DB.GetTableDesc(table.Name)
if err != nil {
log.Fatal("CreateEntityErr>>", err)
continue
}
req := new(EntityReq)
req.Index = idx
req.EntityPath = path
req.TableName = table.Name
req.TableComment = table.Comment
req.TableDesc = tableDesc
req.FormatList = formatList
req.EntityPkg = PkgEntity
// 生成基础信息
err = l.GenerateDBEntity(req)
if err != nil {
log.Fatal("CreateEntityErr>>", err)
continue
}
}
return
}
// 生成原生的crud查询数据库
func (l *Logic) CreateCURD(formatList []string) (err error) {
tableNameList := make([]*TableList, 0)
// 表结构文件路径
// 将表结构写入文件
for _, table := range l.DB.DoTables {
tableNameList = append(tableNameList, &TableList{
UpperTableName: TablePrefix + l.T.ToUpper(table.Name),
TableName: table.Name,
Comment: table.Comment,
})
// 查询表结构信息
tableDesc, err := l.DB.GetTableDesc(table.Name)
if err != nil {
return err
}
req := new(EntityReq)
req.TableName = table.Name
req.TableComment = table.Comment
req.TableDesc = tableDesc
req.EntityPath = l.GetEntityDir() + GOFILE_ENTITY
req.FormatList = formatList
req.Pkg = PkgDbModels
req.EntityPkg = PkgEntity
// 生成基础信息
err = l.GenerateDBEntity(req)
if err != nil {
return err
}
// 生成增,删,改,查文件
err = l.GenerateCURDFile(table.Name, table.Comment, tableDesc)
if err != nil {
return err
}
}
// 生成所有表的文件
if err = l.GenerateTableList(tableNameList); err != nil {
return
}
//生成init文件
if err = l.GenerateInit(); err != nil {
return
}
//生成error文件
if err = l.GenerateError(); err != nil {
return
}
fmt.Println("`CURD` files created finish!")
return nil
}
// 生成mysql markdown文档
func (l *Logic) CreateMarkdown() (err error) {
data := new(MarkDownData)
// 将表结构写入文件
i := 1
for _, table := range l.DB.DoTables {
fmt.Println("Doing table:" + table.Name)
data.TableList = append(data.TableList, &TableList{
Index: i,
UpperTableName: l.T.ToUpper(table.Name),
TableName: table.Name,
Comment: table.Comment,
})
// 查询表结构信息
desc := new(MarkDownDataChild)
desc.List, err = l.DB.GetTableDesc(table.Name)
if err != nil {
log.Fatal("markdown>>", err)
continue
}
desc.Index = i
desc.TableName = table.Name
desc.Comment = table.Comment
data.DescList = append(data.DescList, desc)
i++
}
// 生成所有表的文件
err = l.GenerateMarkdown(data)
if err != nil {
return
}
return
}
// 创建和获取MYSQL目录
func (l *Logic) GetMysqlDir() string {
return CreateDir(l.Path + GODIR_MODELS + DS)
}
// 创建和获取MYSQL目录
func (l *Logic) GetConfigDir() string {
return CreateDir(l.Path + GODIR_MODELS + DS + GODIR_Config + DS)
}
// 创建和获取MYSQL目录
func (l *Logic) GetEntityDir() string {
return CreateDir(l.Path + GODIR_MODELS + DS + GODIR_Entity + DS)
}
// 获取根目录地址
func (l *Logic) GetRoot() string {
return GetRootPath(l.Path) + DS
}
// 创建结构体
func (l *Logic) GenerateDBStructure(tableName, tableComment, path string, tableDesc []*TableDesc) (err error) {
// 加入package
packageStr := `// 数据库表内结构体信息
package mysql
` // 判断package是否加载过
// 判断文件是否存在.
if l.T.CheckFileContainsChar(path, packageStr) == false {
l.T.WriteFile(path, packageStr)
}
// 判断import是否加载过
importStr := `import "database/sql"`
if l.T.CheckFileContainsChar(path, importStr) == false {
l.T.WriteFileAppend(path, importStr)
}
// 声明表结构变量
TableData := new(TableInfo)
TableData.Table = l.T.Capitalize(tableName)
TableData.NullTable = DbNullPrefix + TableData.Table
TableData.TableComment = tableComment
// 判断表结构是否加载过
if l.T.CheckFileContainsChar(path, "type "+TableData.Table+" struct") == true {
return
}
// 加载模板文件
tplByte, err := Asset(TPL_STRUCTURE)
if err != nil {
return
}
tpl, err := template.New("structure").Parse(string(tplByte))
if err != nil {
return
}
// 装载表字段信息
fts := []string{"json"}
if err != nil {
return
}
// 判断是否含json
if !InArrayString("json", fts) {
index0 := fts[0]
fts[0] = "json"
fts = append(fts, index0)
}
for _, val := range tableDesc {
TableData.Fields = append(TableData.Fields, &FieldsInfo{
Name: l.T.Capitalize(val.ColumnName),
Type: val.GolangType,
NullType: val.MysqlNullType,
DbOriField: val.ColumnName,
FormatFields: FormatField(val.ColumnName, fts),
Remark: val.ColumnComment,
})
}
content := bytes.NewBuffer([]byte{})
tpl.Execute(content, TableData)
// 表信息写入文件
err = WriteAppendFile(path, content.String())
if err != nil {
return
}
return
}
// 创建结构实体
func (l *Logic) GenerateDBEntity(req *EntityReq) (err error) {
l.l.Lock()
defer l.l.Unlock()
var s string
s = fmt.Sprintf(`// 判断package是否加载过
package %s
import (
"database/sql"
"github.com/go-sql-driver/mysql"
"time"
)
`, req.EntityPkg)
// 判断import是否加载过
check := "github.com/go-sql-driver/mysql"
if l.T.CheckFileContainsChar(req.EntityPath, check) == false {
l.T.WriteFile(req.EntityPath, s)
}
// 声明表结构变量
TableData := new(TableInfo)
TableData.Table = l.T.Capitalize(req.TableName)
TableData.NullTable = TableData.Table + DbNullPrefix
TableData.TableComment = AddToComment(req.TableComment, "")
TableData.TableCommentNull = AddToComment(req.TableComment, " Null Entity")
// 判断表结构是否加载过
if l.T.CheckFileContainsChar(req.EntityPath, "type "+TableData.Table+" struct") == true {
log.Println(req.EntityPath + "It already exists. Please delete it and regenerate it")
return
}
// 加载模板文件
tplByte, err := Asset(TPL_ENTITY)
if err != nil {
return
}
tpl, err := template.New("entity").Parse(string(tplByte))
if err != nil {
return
}
// 装载表字段信息
for _, val := range req.TableDesc {
TableData.Fields = append(TableData.Fields, &FieldsInfo{
Name: l.T.Capitalize(val.ColumnName),
Type: val.GolangType,
NullType: val.MysqlNullType,
DbOriField: val.ColumnName,
FormatFields: FormatField(val.ColumnName, req.FormatList),
Remark: AddToComment(val.ColumnComment, ""),
})
}
content := bytes.NewBuffer([]byte{})
tpl.Execute(content, TableData)
// 表信息写入文件
con := strings.Replace(content.String(), """, `"`, -1)
err = WriteAppendFile(req.EntityPath, con)
if err != nil {
return
}
return
}
// 生成C增,U删,R查,D改,的文件
func (l *Logic) GenerateCURDFile(tableName, tableComment string, tableDesc []*TableDesc) (err error) {
var (
allFields = make([]string, 0)
insertFields = make([]string, 0)
InsertInfo = make([]*SqlFieldInfo, 0)
fieldsList = make([]*SqlFieldInfo, 0)
nullFieldList = make([]*NullSqlFieldInfo, 0)
updateList = make([]string, 0)
updateListField = make([]string, 0)
PrimaryKey = ""
primaryType = ""
)
// 存放第个字段
var secondField string
for _, item := range tableDesc {
allFields = append(allFields, AddQuote(item.ColumnName))
if item.PrimaryKey == false && item.ColumnName != "updated_at" && item.ColumnName != "created_at" {
insertFields = append(insertFields, AddQuote(item.ColumnName))
InsertInfo = append(InsertInfo, &SqlFieldInfo{
HumpName: l.T.Capitalize(item.ColumnName),
Comment: item.ColumnComment,
})
if item.ColumnName == "identify" {
updateList = append(updateList, AddQuote(item.ColumnName)+"="+item.ColumnName+"+1")
} else {
updateList = append(updateList, AddQuote(item.ColumnName)+"=?")
if item.PrimaryKey == false {
updateListField = append(updateListField, "value."+l.T.Capitalize(item.ColumnName))
}
}
}
if item.PrimaryKey {
PrimaryKey = item.ColumnName
primaryType = item.GolangType
} else {
// 除了主键外的任意一个字段即可。
if secondField == "" {
secondField = item.ColumnName
}
}
fieldsList = append(fieldsList, &SqlFieldInfo{
HumpName: l.T.Capitalize(item.ColumnName),
Comment: item.ColumnComment,
})
nullFieldList = append(nullFieldList, &NullSqlFieldInfo{
HumpName: l.T.Capitalize(item.ColumnName),
OriFieldType: item.OriMysqlType,
GoType: MysqlTypeToGoType[item.OriMysqlType],
Comment: item.ColumnComment,
})
}
// 主键ID,用于更新
if PrimaryKey != "" {
updateListField = append(updateListField, "value."+l.T.Capitalize(PrimaryKey))
}
// 拼出SQL所需要结构数据
InsertMark := strings.Repeat("?,", len(insertFields))
if len(InsertMark) > 0 {
InsertMark = InsertMark[:len(InsertMark)-1]
}
sqlInfo := &SqlInfo{
TableName: tableName,
PrimaryKey: AddQuote(PrimaryKey),
PrimaryType: primaryType,
StructTableName: l.T.Capitalize(tableName),
NullStructTableName: l.T.Capitalize(tableName) + DbNullPrefix,
PkgEntity: PkgEntity + ".",
PkgTable: PkgTable + ".",
UpperTableName: TablePrefix + l.T.ToUpper(tableName),
AllFieldList: strings.Join(allFields, ","),
InsertFieldList: strings.Join(insertFields, ","),
InsertMark: InsertMark,
UpdateFieldList: strings.Join(updateList, ","),
UpdateListField: updateListField,
FieldsInfo: fieldsList,
NullFieldsInfo: nullFieldList,
InsertInfo: InsertInfo,
SecondField: AddQuote(secondField),
}
err = l.GenerateSQL(sqlInfo, tableComment)
// 添加一个实例
l.Once.Do(func() {
l.GenerateExample(sqlInfo.StructTableName)
})
if err != nil {
return
}
return
}
// 生成一个实例文件
func (l *Logic) GenerateExample(name string) {
// 写入表名
file := l.GetMysqlDir() + GoFile_Example
// 解析模板
tplByte, err := Asset(TPL_EXAMPLE)
if err != nil {
return
}
tpl, err := template.New("example").Parse(string(tplByte))
if err != nil {
return
}
type s struct {
Name string
}
ss := s{
Name: name,
}
// 解析
content := bytes.NewBuffer([]byte{})
err = tpl.Execute(content, ss)
if err != nil {
return
}
// 表信息写入文件
err = WriteFile(file, content.String())
if err != nil {
return
}
return
}
// 生成表列表
func (l *Logic) GenerateTableList(list []*TableList) (err error) {
// 写入表名
file := l.GetConfigDir() + GoFile_TableList
// 判断package是否加载过
checkStr := "package " + PkgTable
if l.T.CheckFileContainsChar(file, checkStr) == false {
l.T.WriteFile(file, checkStr+"\n")
}
checkStr = "const"
if l.T.CheckFileContainsChar(file, checkStr) {
log.Println(file + "It already exists. Please delete it and regenerate it")
return
}
tplByte, err := Asset(TPL_TABLES)
if err != nil {
return
}
tpl, err := template.New("table_list").Parse(string(tplByte))
if err != nil {
return
}
// 解析
content := bytes.NewBuffer([]byte{})
err = tpl.Execute(content, list)
if err != nil {
return
}
// 表信息写入文件
err = WriteAppendFile(file, content.String())
if err != nil {
return
}
return
}
// 生成init
func (l *Logic) GenerateInit() (err error) {
file := l.GetMysqlDir() + GoFile_Init
// 判断package是否加载过
checkStr := "package " + PkgDbModels
if l.T.CheckFileContainsChar(file, checkStr) == false {
l.T.WriteFile(file, checkStr+"\n")
}
checkStr = "DBConfig"
if l.T.CheckFileContainsChar(file, checkStr) {
log.Println(file + "It already exists. Please delete it and regenerate it")
return
}
tplByte, err := Asset(TPL_INIT)
if err != nil {
return
}
tpl, err := template.New("init").Parse(string(tplByte))
if err != nil {
return
}
// 解析
content := bytes.NewBuffer([]byte{})
err = tpl.Execute(content, nil)
if err != nil {
return
}
// 表信息写入文件
err = WriteAppendFile(file, content.String())
if err != nil {
return
}
return
}
// 生成init
func (l *Logic) GenerateError() (err error) {
file := l.GetMysqlDir() + GoFile_Error
// 判断package是否加载过
checkStr := "package " + PkgDbModels
if l.T.CheckFileContainsChar(file, checkStr) == false {
l.T.WriteFile(file, checkStr+"\n")
}
// 判断是否已经生成过此文件
checkStr = "Stack"
if l.T.CheckFileContainsChar(file, checkStr) {
log.Println(file + "It already exists. Please delete it and regenerate it")
return
}
tplByte, err := Asset(TPL_Error)
if err != nil {
return
}
tpl, err := template.New("error").Parse(string(tplByte))
if err != nil {
return
}
// analysis execute template
content := bytes.NewBuffer([]byte{})
err = tpl.Execute(content, nil)
if err != nil {
return
}
// append write to file
err = WriteAppendFile(file, content.String())
if err != nil {
return
}
return
}
// 生成SQL文件
func (l *Logic) GenerateSQL(info *SqlInfo, tableComment string) (err error) {
// 写入表名
goFile := l.GetMysqlDir() + info.TableName + ".go"
s := fmt.Sprintf(`
// %s
package %s
import(
"database/sql"
"strings"
_ "github.com/go-sql-driver/mysql"
)
`, tableComment, PkgDbModels)
// 判断package是否加载过
if l.T.CheckFileContainsChar(goFile, "database/sql") == false {
l.T.WriteFile(goFile, s)
}
// 解析模板
tplByte, err := Asset(TPL_CURD)
if err != nil {
return
}
tpl, err := template.New("CURD").Parse(string(tplByte))
if err != nil {
return
}
// 解析
content := bytes.NewBuffer([]byte{})
err = tpl.Execute(content, info)
if err != nil {
return
}
// 表信息写入文件
if l.T.CheckFileContainsChar(goFile, info.StructTableName) == false {
err = WriteAppendFile(goFile, content.String())
if err != nil {
return
}
}
return
}
// 生成表列表
func (l *Logic) GenerateMarkdown(data *MarkDownData) (err error) {
// 写入markdown
file := l.Path + fmt.Sprintf("markdown%s.md", time.Now().Format("2006-01-02_150405"))
tplByte, err := Asset(TPL_MARKDOWN)
if err != nil {
return
}
// 解析
content := bytes.NewBuffer([]byte{})
tpl, err := template.New("markdown").Parse(string(tplByte))
err = tpl.Execute(content, data)
if err != nil {
return
}
// 表信息写入文件
err = WriteAppendFile(file, content.String())
if err != nil {
return
}
return
}