-
Notifications
You must be signed in to change notification settings - Fork 9
/
generate.go
211 lines (182 loc) · 4.67 KB
/
generate.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
package main
import (
"bytes"
"go/format"
"html/template"
"io"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/LUSHDigital/modelgen/sqlfmt"
"github.com/LUSHDigital/modelgen/sqltypes"
"github.com/LUSHDigital/modelgen/tmpl"
"github.com/spf13/cobra"
)
func generate(cmd *cobra.Command, args []string) {
validate()
connect()
// get the list of tables from the database
tables := getTables()
if len(tables) == 0 {
log.Fatal("No tables to read")
}
// make structs from tables
asStructs := ToStructs(tables)
// load the model template
modelTpl, err := box.MustBytes("model.html")
if err != nil {
log.Fatal("cannot load model template")
}
t := template.Must(template.New("model").Funcs(tmpl.FuncMap).Parse(string(modelTpl)))
writeModels(asStructs, t)
// copy in helpers and test suite
copyFile("x_helpers.html", "x_helpers.go", "helpers")
copyFile("x_helpers_test.html", "x_helpers_test.go", "helperstest")
}
func writeModels(models []tmpl.TmplStruct, t *template.Template) {
for _, model := range models {
m := tmpl.StructTmplData{
Model: model,
Receiver: strings.ToLower(string(model.Name[0])),
PackageName: *pkgName,
}
buf := new(bytes.Buffer)
err := t.Execute(buf, m)
if err != nil {
log.Fatal(err)
}
formatted, err := format.Source(buf.Bytes())
if err != nil {
log.Fatal(err)
}
buf = bytes.NewBuffer(formatted)
out := *output
os.Mkdir(out, 0777)
p := filepath.Join(out, model.TableName)
f, err := os.Create(p + ".go")
if err != nil {
log.Fatal(err)
}
buf.WriteTo(f)
f.Close()
}
}
func getTables() (tables map[string]string) {
tables = make(map[string]string)
const stmt = `SELECT table_name, column_comment
FROM information_schema.columns AS c
WHERE c.column_key = "PRI"
AND c.table_schema = ?
AND column_name = "id"`
rows, err := database.Query(stmt, *dbName)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var name string
var comment string
if err := rows.Scan(&name, &comment); err != nil {
log.Fatal(err)
}
tables[name] = comment
}
return tables
}
// GetOrderFromComment reads the modelgen:1 type comments and returns
// the integer part on the right
func GetOrderFromComment(comment string) (order int) {
if !strings.HasPrefix(comment, "modelgen") {
return
}
parts := strings.SplitN(comment, ":", 2)
if len(parts) != 2 {
return
}
var err error
if order, err = strconv.Atoi(parts[1]); err != nil {
log.Printf("could not parse id comment [%v], make sure to only use numbers in order comments", parts[1])
return
}
return
}
// backtick is needed is the user picked a table name
// which conflicts with a builtin keyword, example "order"
func backtick(s string) string { return "`" + s + "`" }
// ToStructs takes an 'EXPLAIN' statement and transforms it's output
// into structs.
func ToStructs(tables map[string]string) []tmpl.TmplStruct {
var explained = make(map[string][]sqltypes.Explain)
for table := range tables {
var expl []sqltypes.Explain
rows, err := database.Query("EXPLAIN " + backtick(table))
if err != nil {
log.Fatal(err)
}
for rows.Next() {
var ex sqltypes.Explain
if err := rows.Scan(&ex.Field, &ex.Type, &ex.Null, &ex.Key, &ex.Default, &ex.Extra); err != nil {
log.Fatal(err)
}
expl = append(expl, ex)
}
rows.Close()
explained[table] = expl
}
var structStore tmpl.TmplStructs
for k, explain := range explained {
t := tmpl.TmplStruct{
Name: sqlfmt.ToPascalCase(k),
TableName: k,
Imports: make(map[string]struct{}),
}
for _, expl := range explain {
f := tmpl.TmplField{
Name: sqlfmt.ToPascalCase(*expl.Field),
Type: sqltypes.AssertType(*expl.Type, *expl.Null),
ColumnName: strings.ToLower(*expl.Field),
Nullable: *expl.Null == "YES",
}
t.Fields = append(t.Fields, f)
if imp, ok := sqltypes.NeedsImport(f.Type); ok {
t.Imports[imp] = struct{}{}
}
}
structStore = append(structStore, t)
}
return structStore
}
func copyFile(src, dst, templateName string) {
dbFile, err := box.MustBytes(src)
if err != nil {
log.Fatalf("cannot retrieve template file: %v", err)
}
t := template.Must(template.New(templateName).Parse(string(dbFile)))
buf := new(bytes.Buffer)
err = t.Execute(buf, map[string]string{
"PackageName": *pkgName,
})
if err != nil {
log.Fatal(err)
}
formatted, err := format.Source(buf.Bytes())
if err != nil {
log.Fatal(err)
}
buf = bytes.NewBuffer(formatted)
if err != nil {
log.Fatal("cannot copy file")
}
out := filepath.Join(*output, dst)
to, err := os.Create(out)
if err != nil {
log.Fatal(err)
}
defer to.Close()
_, err = io.Copy(to, buf)
if err != nil {
log.Fatal(err)
}
}