Newer
Older
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
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"log"
"os"
"sort"
"strings"
"text/template"
"github.com/fatih/structtag"
)
// Package is the top-level package
type Package struct {
Name string
AllStructs map[string]*ast.StructType
DBStructs []DBStruct
}
func (p Package) getAllFields(structType *ast.StructType) []*ast.Field {
var fields []*ast.Field
for _, field := range structType.Fields.List {
if len(field.Names) == 0 {
if ident, ok := field.Type.(*ast.Ident); ok {
if sub, ok := p.AllStructs[ident.String()]; ok {
fields = append(fields, p.getAllFields(sub)...)
}
}
} else {
fields = append(fields, field)
}
}
return fields
}
// DBStruct is a struct mapped to a table
type DBStruct struct {
Name string
Tablename string
PKey DBField
Fields []DBField
}
// HasTable returns true if this structure is only a top level db struct that
// has is associated to a table
func (s DBStruct) HasTable() bool {
return s.Tablename != ""
}
// IsEmbedded returns true if this structure is only embedded in other db structs
func (s DBStruct) IsEmbedded() bool {
return s.Tablename == ""
}
// DBField is a field of a DBStruct
type DBField struct {
Name string
Column string
IsPKey bool
}
func main() {
var (
outputname = "db_helpers.go"
)
if len(os.Args) > 2 && os.Args[1] == "-o" {
outputname = os.Args[2]
}
fset := token.NewFileSet()
packages, err := parser.ParseDir(fset, ".", func(info os.FileInfo) bool {
return info.Name() != outputname
}, parser.ParseComments)
if err != nil {
log.Fatal(err)
}
if len(packages) != 1 {
log.Fatal("Expected to find 1 go package, got: ", len(packages), packages)
}
var pkg *ast.Package
for _, p := range packages {
pkg = p
}
topLevel := Package{Name: pkg.Name, AllStructs: make(map[string]*ast.StructType)}
for _, file := range pkg.Files {
if err := walkStructTypes(
file,
func(name, doc string, structType *ast.StructType) error {
topLevel.AllStructs[name] = structType
return nil
}); err != nil {
panic(err)
}
}
for _, file := range pkg.Files {
if err := walkDBStructType(
&topLevel,
file,
func(dbstruct DBStruct) error {
topLevel.DBStructs = append(topLevel.DBStructs, dbstruct)
return nil
}); err != nil {
panic(err)
}
}
sort.Slice(topLevel.DBStructs, func(i, j int) bool {
return strings.Compare(topLevel.DBStructs[i].Name, topLevel.DBStructs[j].Name) < 0
})
out, err := os.OpenFile(outputname, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
panic(err)
}
if err := headTmpl.Execute(out, topLevel); err != nil {
panic(err)
}
}
func walkStructTypes(
f *ast.File, visit func(name, doc string, structType *ast.StructType) error,
) error {
for _, decl := range f.Decls {
if genDecl, ok := decl.(*ast.GenDecl); ok {
if len(genDecl.Specs) == 1 {
spec := genDecl.Specs[0]
if typeSpec, ok := spec.(*ast.TypeSpec); ok {
if structType, ok := typeSpec.Type.(*ast.StructType); ok {
if err := visit(
typeSpec.Name.String(), genDecl.Doc.Text(), structType,
); err != nil {
return err
}
}
}
}
}
}
return nil
}
func walkDBStructType(
topLevel *Package, f *ast.File, visit func(DBStruct) error,
) error {
return walkStructTypes(
f,
func(name, doc string, structType *ast.StructType) error {
dbtag := findStructDocLineWithPrefix(doc, "dbtable:")
dbstruct, err := newDBStruct(topLevel, name, dbtag, structType)
if err != nil {
return err
}
if dbstruct != nil {
return visit(*dbstruct)
}
return nil
})
}
func findStructDocLineWithPrefix(doc, prefix string) string {
for _, line := range strings.Split(doc, "\n") {
if strings.HasPrefix(line, prefix) {
return line
}
}
return ""
}
func newDBStruct(topLevel *Package, name string, tag string, structType *ast.StructType) (*DBStruct, error) {
dbstruct := DBStruct{
Name: name,
}
tags, err := structtag.Parse(tag)
if err != nil {
return nil, fmt.Errorf("error parsing tag `%s`: %s", tag, err)
}
tableTag, err := tags.Get("dbtable")
if err != nil && err.Error() != "tag does not exist" {
return nil, err
}
pkeyTag, err := tags.Get("dbpkey")
if err != nil && err.Error() != "tag does not exist" {
return nil, err
}
pkey := ""
if tableTag != nil {
dbstruct.Tablename = tableTag.Name
if pkeyTag != nil {
pkey = pkeyTag.Name
}
}
if dbstruct.Fields, err = getDBFields(topLevel, structType); err != nil {
return nil, err
}
if len(dbstruct.Fields) == 0 {
return nil, nil
}
for i, field := range dbstruct.Fields {
if field.Column == pkey {
dbstruct.Fields[i].IsPKey = true
dbstruct.PKey = dbstruct.Fields[i]
}
}
return &dbstruct, nil
}
func getDBFields(topLevel *Package, structType *ast.StructType) ([]DBField, error) {
var dbfields []DBField
for _, field := range topLevel.getAllFields(structType) {
if field.Tag == nil || len(field.Tag.Value) < 2 {
continue
}
tags, err := structtag.Parse(
field.Tag.Value[1 : len(field.Tag.Value)-1])
if err != nil {
return nil, err
}
dbtag, err := tags.Get("db")
if err != nil {
continue
}
dbfields = append(dbfields, DBField{
Name: field.Names[0].String(),
Column: dbtag.Name,
})
}
return dbfields, nil
}
var (
headTmpl = template.Must(template.New("head").Parse(`// This file is generated by 'gendbfiles' - DO NOT EDIT
package {{.Name}}
// This file contains constants for all db names involved in a mapped struct
// It also add some accessors on the struct types so they implement a 'Mapped' interface
// Mapped is the common interface of all structs that are mapped in the database
type Mapped interface {
Table() string
PKeyColumn() string
Columns(withPKey bool) []string
Values(columns ...string) []interface{}
}
const (
// table and column names
{{- range $i, $dbstruct := .DBStructs}}
{{- if $dbstruct.HasTable}}
// {{.Name}}Table is the name of the table where {{.Name}} are stored
{{.Name}}Table = "{{.Tablename}}"
{{- end}}
{{- if .PKey.Name}}
// {{.Name}}PKeyColumn is the name of the primary key
{{.Name}}PKeyColumn = {{.Name}}{{.PKey.Name}}Column
{{- end}}
{{- range .Fields}}
// {{$dbstruct.Name}}{{.Name}}Column is the name of the column containing field "{{.Name}}" data
{{$dbstruct.Name}}{{.Name}}Column = "{{.Column}}"
{{- end}}
{{- end}}
)
var (
// DBAllTables is the list of all the database table names
DBAllTables = []string{
{{- range .DBStructs}}
{{- if .HasTable}}
{{.Name}}Table,
{{- end}}
{{- end}}
}
{{- range $dbstruct := .DBStructs}}
{{- if .HasTable}}
// {{.Name}}DataColumns is the list of the columns for the {{.Name}} structure, expect its primary key
{{.Name}}DataColumns = []string{
{{- range .Fields}}
{{- if not .IsPKey}}
{{$dbstruct.Name}}{{.Name}}Column,
{{- end}}
{{- end}}
}
// {{.Name}}Columns is the list of the columns for the {{.Name}} structure
{{- if .PKey.Name}}
{{.Name}}Columns = append(
[]string{ {{$dbstruct.Name}}{{.PKey.Name}}Column },
{{.Name}}DataColumns...,
)
{{- else }}
{{.Name}}Columns = {{.Name}}DataColumns
{{- end}}
{{- else}}
// {{.Name}}Columns is the list of the columns for the {{.Name}} structure
{{.Name}}Columns = []string{
{{- range .Fields}}
{{$dbstruct.Name}}{{.Name}}Column,
{{- end}}
}
{{- end}}
{{- end}}
)
{{- range $dbstruct := .DBStructs}}
{{- if .HasTable}}
// Table returns the database table name
func (s {{.Name}}) Table() string {
return {{.Name}}Table
}
{{- end}}
{{- if .PKey.Name}}
// PKeyColumn returns the database table primary key column name
func (s {{.Name}}) PKeyColumn() string {
return {{.Name}}PKeyColumn
}
{{- end}}
{{- if .HasTable}}
// Columns returns the database table column names
func (s {{.Name}}) Columns(withPKey bool) []string {
if withPKey {
return {{.Name}}Columns
}
return {{.Name}}DataColumns
}
{{- else}}
// Columns returns the database table column names
func (s {{.Name}}) Columns() []string {
return {{.Name}}Columns
}
{{- end}}
// Values returns the values for a list of columns. If a column does not exits,
// the corresponding value is left empty
func (s {{.Name}}) Values(columns ...string) []interface{} {
values := make([]interface{}, len(columns))
for i, column := range columns {
switch column {
{{- range .Fields}}
case "{{.Column}}":
values[i] = s.{{.Name}}
{{- end}}
}
}
return values
}
{{- end}}
`))
)