-
Notifications
You must be signed in to change notification settings - Fork 0
/
genModel.go
565 lines (442 loc) · 13.8 KB
/
genModel.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
package gen
import (
"bufio"
"fmt"
"go/format"
"io/ioutil"
"log"
"os"
"path"
"sort"
"strings"
"time"
"github.com/macinnir/dvc/core/lib"
"github.com/macinnir/dvc/core/lib/cache"
"github.com/macinnir/dvc/core/lib/schema"
)
// GenModels generates models
func GenModels(modelsDir string, force bool, clean bool) error {
start := time.Now()
var schemaList *schema.SchemaList
var e error
schemaList, e = schema.LoadLocalSchemas()
if e != nil {
return e
}
fmt.Println("Generating models...")
if clean {
for k := range schemaList.Schemas {
CleanGoModels(modelsDir, schemaList.Schemas[k])
}
}
var tablesCache cache.TablesCache
tablesCache, e = cache.LoadTableCache()
if e != nil {
return e
}
generatedModelCount := 0
for k := range schemaList.Schemas {
schemaName := schemaList.Schemas[k].Name
for l := range schemaList.Schemas[k].Tables {
table := schemaList.Schemas[k].Tables[l]
tableKey := schemaName + "_" + table.Name
var tableHash string
tableHash, e = cache.HashTable(table)
// If the model has been hashed before...
if _, ok := tablesCache.Models[tableKey]; ok {
// And the hash hasn't changed, skip...
if tableHash == tablesCache.Models[tableKey] && !force {
// fmt.Printf("Table `%s` hasn't changed! Skipping...\n", table.Name)
continue
}
}
generatedModelCount++
// Update the models cache
tablesCache.Models[tableKey] = tableHash
// TODO verbose flag
// fmt.Printf("Generating model `%s`\n", table.Name)
e = GenerateGoModel(modelsDir, schemaName, table)
if e != nil {
return e
}
}
}
cache.SaveTableCache(tablesCache)
fmt.Printf("Generated %d models in %f seconds.\n", generatedModelCount, time.Since(start).Seconds())
return nil
}
// GenerateGoModel returns a string for a model in golang
func GenerateGoModel(dir string, schemaName string, table *schema.Table) (e error) {
lib.EnsureDir(dir)
p := path.Join(dir, table.Name+".go")
// if lib.FileExists(p) {
// lib.Infof("Updating `%s`", g.Options, table.Name)
// e = g.updateGoModel(p, table)
// return
// }
// lib.Infof("Creating `%s`", g.Options, table.Name)s
e = buildGoModel(p, schemaName, table)
return
}
// InspectFile inspects a file
func InspectFile(filePath string) (s *lib.GoStruct, e error) {
fileBytes, e := ioutil.ReadFile(filePath)
if e != nil {
panic(e)
}
s, e = buildGoStructFromFile(fileBytes)
if e != nil {
fmt.Println("ERROR: ", filePath)
panic(e)
}
return
}
// func (g *Gen) updateGoModel(p string, table *schema.Table) (e error) {
// var modelNode *lib.GoStruct
// var outFile []byte
// fileBytes, e := ioutil.ReadFile(p)
// modelNode, e = buildGoStructFromFile(fileBytes)
// resolveTableToModel(modelNode, table)
// if e != nil {
// return
// }
// outFile, e = buildFileFromModelNode(modelNode)
// if e != nil {
// return
// }
// e = ioutil.WriteFile(p, outFile, 0644)
// return
// }
func buildGoModel(p string, schemaName string, table *schema.Table) (e error) {
var modelNode *lib.GoStruct
var outFile []byte
// lib.Debugf("Generating model for table %s", g.Options, table.Name)
modelNode, e = buildModelNodeFromTable(table)
if e != nil {
return
}
outFile, e = buildFileFromModelNode(schemaName, table, modelNode)
if e != nil {
return
}
e = ioutil.WriteFile(p, outFile, 0644)
return
}
// buildModelNodeFromFile builds a node representation of a struct from a file
func buildModelNodeFromTable(table *schema.Table) (modelNode *lib.GoStruct, e error) {
modelNode = lib.NewGoStruct()
modelNode.Package = "models"
modelNode.Name = table.Name
modelNode.Comments = fmt.Sprintf("%s is a `%s` data model\n", table.Name, table.Name)
modelNode.Imports.Append("\"github.com/macinnir/dvc/core/lib/utils/query\"")
modelNode.Imports.Append("\"encoding/json\"")
hasNull := false
sortedColumns := make(schema.SortedColumns, 0, len(table.Columns))
for _, column := range table.Columns {
sortedColumns = append(sortedColumns, column)
}
sort.Sort(sortedColumns)
for _, col := range sortedColumns {
fieldType := schema.DataTypeToGoTypeString(col)
if fieldDataTypeIsNull(fieldType) {
hasNull = true
}
modelNode.Fields.Append(&lib.GoStructField{
Name: col.Name,
DataType: fieldType,
Tags: []*lib.GoStructFieldTag{
{Name: "db", Value: col.Name, Options: []string{}},
{Name: "json", Value: col.Name, Options: []string{}},
},
Comments: "",
})
}
if hasNull {
modelNode.Imports.Append(NullPackage)
}
return
}
func buildFileFromModelNode(schemaName string, table *schema.Table, modelNode *lib.GoStruct) (file []byte, e error) {
insertColumns := fetchInsertColumns(table.ToSortedColumns())
updateColumns := fetchUpdateColumns(table.ToSortedColumns())
primaryKey := fetchTablePrimaryKeyName(table)
var b strings.Builder
b.WriteString("// Generated Code; DO NOT EDIT.\n\npackage " + modelNode.Package + "\n\n")
if modelNode.Imports.Len() > 0 {
b.WriteString(modelNode.Imports.ToString() + "\n")
}
b.WriteString(`
const (
// ` + modelNode.Name + `_SchemaName is the name of the schema group this model is in
` + modelNode.Name + `_SchemaName = "` + schemaName + `"
// ` + modelNode.Name + `_TableName is the name of the table
` + modelNode.Name + `_TableName query.TableName = "` + modelNode.Name + `"
// Columns
`)
for _, f := range *modelNode.Fields {
b.WriteString("\t" + modelNode.Name + "_Column_" + f.Name + " query.Column = \"" + f.Name + "\"\n")
}
b.WriteString(`
)
var (
// ` + modelNode.Name + `_Columns is a list of all the columns
` + modelNode.Name + `_Columns = []query.Column{
`)
for k, f := range *modelNode.Fields {
b.WriteString(modelNode.Name + "_Column_" + f.Name)
if k < len(*modelNode.Fields)-1 {
b.WriteByte(',')
}
}
b.WriteString(` }
// ` + modelNode.Name + `_Column_Types maps columns to their string types
` + modelNode.Name + `_Column_Types = map[query.Column]string{
`)
// Column Types
for k, f := range *modelNode.Fields {
b.WriteString(modelNode.Name + "_Column_" + f.Name + ": \"" + schema.GoTypeFormatString(f.DataType) + "\"")
if k < len(*modelNode.Fields)-1 {
b.WriteByte(',')
}
}
b.WriteString("}\n")
// Update columns
b.WriteString("\t// " + modelNode.Name + "_UpdateColumns is a list of all update columns for this model\n")
b.WriteString("\t" + modelNode.Name + "_UpdateColumns = []query.Column{")
for k := range updateColumns {
col := updateColumns[k]
b.WriteString(modelNode.Name + "_Column_" + col.Name)
if k < len(updateColumns)-1 {
b.WriteByte(',')
}
}
b.WriteString("}\n")
// Insert columns
b.WriteString("\t// " + modelNode.Name + "_InsertColumns is a list of all insert columns for this model\n")
b.WriteString("\t" + modelNode.Name + "_InsertColumns = []query.Column{")
for k := range insertColumns {
col := insertColumns[k]
b.WriteString(modelNode.Name + "_Column_" + col.Name)
if k < len(insertColumns)-1 {
b.WriteByte(',')
}
}
b.WriteString("}\n")
// Primary Key
b.WriteString("\t// " + modelNode.Name + "_PrimaryKey is the name of the table's primary key\n")
b.WriteString("\t" + modelNode.Name + "_PrimaryKey query.Column = \"" + primaryKey + "\"\n)")
// Model
if len(modelNode.Comments) > 0 {
b.WriteString("\n// " + modelNode.Comments)
}
b.WriteString("type " + modelNode.Name + " struct {\n")
for _, f := range *modelNode.Fields {
b.WriteString("\t" + f.ToString())
}
b.WriteString("}\n")
b.WriteString(`
// ` + modelNode.Name + `_TableName is the name of the table
func (c *` + modelNode.Name + `) Table_Name() query.TableName {
return ` + modelNode.Name + `_TableName
}
func (c *` + modelNode.Name + `) Table_Columns() []query.Column {
return ` + modelNode.Name + `_Columns
}
// Table_ColumnTypes returns a map of tableColumn names with their fmt string types
func (c *` + modelNode.Name + `) Table_Column_Types() map[query.Column]string {
return ` + modelNode.Name + `_Column_Types
}
// Table_PrimaryKey returns the name of this table's primary key
func (c *` + modelNode.Name + `) Table_PrimaryKey() query.Column {
return ` + modelNode.Name + `_PrimaryKey
}
// Table_PrimaryKey_Value returns the value of this table's primary key
func (c *` + modelNode.Name + `) Table_PrimaryKey_Value() int64 {
return c.` + primaryKey + `
}
// Table_InsertColumns is a list of all insert columns for this model
func (c *` + modelNode.Name + `) Table_InsertColumns() []query.Column {
return ` + modelNode.Name + `_InsertColumns
}
// Table_UpdateColumns is a list of all update columns for this model
func (c *` + modelNode.Name + `) Table_UpdateColumns() []query.Column {
return ` + modelNode.Name + `_UpdateColumns
}
// ` + modelNode.Name + `_SchemaName is the name of this table's schema
func (c *` + modelNode.Name + `) Table_SchemaName() string {
return ` + modelNode.Name + `_SchemaName
}
// Select starts a select statement
func (c *` + modelNode.Name + `) Select() *query.Q {
return query.Select(c)
}
// Select starts a select statement
func (c *` + modelNode.Name + `) FromID(id int64) string {
q, _ := query.Select(c).Where(query.EQ(` + modelNode.Name + "_Column_" + primaryKey + `, id)).String()
return q
}
// String returns a json marshalled string of the object
func (c *` + modelNode.Name + `) String() string {
bytes, _ := json.Marshal(c)
return string(bytes)
}
// Update updates a ` + modelNode.Name + ` record
func (c *` + modelNode.Name + `) Update() string {
var sql string
sql, _ = query.Update(c).
`)
for k := range updateColumns {
col := updateColumns[k]
var value string
if col.GoType == "null.String" {
value = "c." + col.Name + ".String"
} else {
value = "c." + col.Name
}
b.WriteString("\t\tSet(" + modelNode.Name + "_Column_" + col.Name + ", " + value + ").\n")
}
b.WriteString(`
Where(query.EQ(` + modelNode.Name + "_Column_" + primaryKey + `, c.` + primaryKey + `)).
String()
return sql
}
// Create inserts a ` + modelNode.Name + ` record
func (c *` + modelNode.Name + `) Create() string {
var sql string
q := query.Insert(c)
if c.` + primaryKey + ` > 0 {
q.Set(` + modelNode.Name + "_Column_" + primaryKey + `, c.` + primaryKey + `)
}
`)
for k := range insertColumns {
col := insertColumns[k]
var value string
if col.GoType == "null.String" {
value = "c." + col.Name + ".String"
} else {
value = "c." + col.Name
}
b.WriteString("\tq.Set(" + modelNode.Name + "_Column_" + col.Name + ", " + value + ")\n")
}
b.WriteString(`
sql, _ = q.String()
return sql
}
`)
b.WriteString(`
// Destroy deletes a ` + modelNode.Name + ` record
func (c *` + modelNode.Name + `) Destroy() string {
sql, _ := query.Delete(c).
Where(
query.EQ(` + modelNode.Name + "_Column_" + primaryKey + `, c.` + primaryKey + `),
).String()
return sql
}
`)
// Write the file
file = []byte(b.String())
file, e = format.Source(file)
if e != nil {
log.Fatalf("FORMAT ERROR: File: %s; Error: %s\n%s", modelNode.Name, e.Error(), b.String())
}
return
}
// func (g *Gen) buildGoModelOld(p string, table *schema.Table) (e error) {
// oneToMany := g.Config.OneToMany[table.Name]
// oneToOne := g.Config.OneToOne[table.Name]
// lib.Debugf("Generating model for table %s", g.Options, table.Name)
// type Column struct {
// Name string
// Type string
// IsPrimaryKey bool
// IsNull bool
// Ordinal int
// }
// data := struct {
// OneToMany string
// OneToOne string
// Name string
// IncludeNullPackage bool
// Columns []Column
// }{
// OneToMany: oneToMany,
// OneToOne: oneToOne,
// Name: table.Name,
// IncludeNullPackage: false,
// Columns: []Column{},
// }
// tpl := `// Generated Code; DO NOT EDIT.
// package models
// {{if .IncludeNullPackage}}
// import (
// "gopkg.in/guregu/null.v3"
// )
// {{end}}
// // {{.Name}} represents a {{.Name}} domain object
// type {{.Name}} struct {
// {{range .Columns}}
// {{.Name}} {{.Type}} ` + "`db:\"{{.Name}}\" json:\"{{.Name}}\"`" + `{{end}}
// }`
// var sortedColumns = make(lib.SortedColumns, 0, len(table.Columns))
// for _, column := range table.Columns {
// sortedColumns = append(sortedColumns, column)
// }
// sort.Sort(sortedColumns)
// includeNullPackage := false
// for _, column := range sortedColumns {
// fieldType := schema.DataTypeToGoTypeString(column)
// if column.IsNullable {
// includeNullPackage = true
// }
// data.Columns = append(data.Columns, Column{
// Name: column.Name,
// Type: fieldType,
// IsPrimaryKey: column.ColumnKey == "PRI",
// IsNull: column.IsNullable,
// Ordinal: len(data.Columns),
// })
// }
// data.IncludeNullPackage = includeNullPackage
// t := template.Must(template.New("model-" + table.Name).Parse(tpl))
// f, err := os.Create(p)
// if err != nil {
// fmt.Println("ERROR: ", err.Error())
// return
// }
// err = t.Execute(f, data)
// if err != nil {
// fmt.Println("Execute ERROR: ", err.Error())
// return
// }
// f.Close()
// lib.FmtGoCode(p)
// return
// }
// CleanGoModels removes model files that are not found in the database.Tables map
func CleanGoModels(dir string, database *schema.Schema) (e error) {
lib.EnsureDir(dir)
dirHandle, err := os.Open(dir)
if err != nil {
panic(err)
}
defer dirHandle.Close()
var dirFileNames []string
dirFileNames, err = dirHandle.Readdirnames(-1)
if err != nil {
panic(err)
}
reader := bufio.NewReader(os.Stdin)
for _, name := range dirFileNames {
fileNameNoExt := name[0 : len(name)-3]
if _, ok := database.Tables[fileNameNoExt]; !ok {
fullFilePath := path.Join(dir, name)
// log.Printf("Removing %s\n", fullFilePath)
result := lib.ReadCliInput(reader, fmt.Sprintf("Delete unused model `%s` (Y/n)?", fileNameNoExt))
if result == "Y" {
fmt.Printf("Deleting model `%s` at path `%s`...\n", fileNameNoExt, fullFilePath)
os.Remove(fullFilePath)
}
}
}
return
}