-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqlhandlerwriter.go
93 lines (74 loc) · 1.63 KB
/
sqlhandlerwriter.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
package sqlhandler
import (
"github.com/clipperhouse/typewriter"
"io"
"text/template"
)
func init() {
err := typewriter.Register(NewSQLHandlerWriter())
if err != nil {
panic(err)
}
}
func HandlerName(typ typewriter.Type) string {
return typ.Name + "Handler"
}
type SQLHandlerWriter struct{}
func NewSQLHandlerWriter() *SQLHandlerWriter {
return &SQLHandlerWriter{}
}
func (sw *SQLHandlerWriter) Name() string {
return "sqlhandler"
}
func (sw *SQLHandlerWriter) Imports(typ typewriter.Type) (result []typewriter.ImportSpec) {
result = append(result, typewriter.ImportSpec{
Path: "github.com/jinzhu/gorm",
})
return
}
func (sw *SQLHandlerWriter) Write(w io.Writer, typ typewriter.Type) error {
tag, found := typ.FindTag(sw)
if !found {
return nil
}
// start with the sqlhandler template
tmpl, err := templates.ByTag(typ, tag)
if err != nil {
return err
}
m := model{
Type: typ,
HandlerName: HandlerName(typ),
}
if err := tmpl.Execute(w, m); err != nil {
return err
}
for _, v := range tag.Values {
m := model{
Type: typ,
HandlerName: HandlerName(typ),
TypeParameters: v.TypeParameters,
TagValue: v,
}
var (
tmpl *template.Template
err error
)
// in order to support dynamic parameters for some templates, we must manually parse them
switch v.Name {
case "FindAssociation":
tmpl, err = findAssociation.Parse()
case "FindAssociations":
tmpl, err = findAssociations.Parse()
default:
tmpl, err = templates.ByTagValue(typ, v)
}
if err != nil {
return err
}
if err := tmpl.Execute(w, m); err != nil {
return err
}
}
return nil
}