/
schema.go
90 lines (81 loc) · 1.94 KB
/
schema.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
package schema
import (
"bytes"
"database/sql"
"fmt"
"github.com/didi/gendry/scanner"
"io"
"text/template"
"github.com/didi/gendry/builder"
)
const (
cDefaultTable = "COLUMNS"
cTimeFormat = "2006-01-02 15:04:05"
)
type columnSlice []column
func readTableStruct(db *sql.DB, tableName string, dbName string) (columnSlice, error) {
var where = map[string]interface{}{
"TABLE_NAME": tableName,
"TABLE_SCHEMA": dbName,
}
var selectFields = []string{"COLUMN_NAME", "COLUMN_TYPE", "COLUMN_COMMENT"}
cond, vals, err := builder.BuildSelect(cDefaultTable, where, selectFields)
if nil != err {
return nil, err
}
rows, err := db.Query(cond, vals...)
if nil != err {
return nil, err
}
defer rows.Close()
var ts columnSlice
scanner.SetTagName("json")
err = scanner.Scan(rows, &ts)
if nil != err {
return nil, err
}
return ts, nil
}
func createStructSourceCode(cols columnSlice, tableName string) (io.Reader, string, error) {
structName := convertUnderScoreToCammel(tableName)
fillData := sourceCode{
StructName: structName,
TableName: tableName,
FieldList: make([]sourceColumn, len(cols)),
}
for idx, col := range cols {
colType, err := col.GetType()
if nil != err {
continue
}
fillData.FieldList[idx] = sourceColumn{
Name: col.GetName(),
Type: colType,
StructTag: fmt.Sprintf("`json:\"%s\" ddb:\"%s\"`", col.Name, col.Name),
}
}
var buff bytes.Buffer
err := template.Must(template.New("struct").Parse(codeTemplate)).Execute(&buff, fillData)
if nil != err {
return nil, "", err
}
return &buff, structName, nil
}
type sourceCode struct {
StructName string
TableName string
FieldList []sourceColumn
}
type sourceColumn struct {
Name string
Type string
StructTag string
}
const codeTemplate = `
// {{ .StructName }} is a mapping object for {{ .TableName }} table in mysql
type {{.StructName}} struct {
{{- range .FieldList }}
{{ .Name }} {{ .Type }} {{ .StructTag }}
{{- end}}
}
`