-
Notifications
You must be signed in to change notification settings - Fork 40
/
templates.go
319 lines (272 loc) · 7.91 KB
/
templates.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
package main
import (
"text/template"
)
var header string = `// Code generated by ModelQ
// {{.TableName}}.go contains model for the database table [{{.DbName}}.{{.TableName}}]
package {{.PkgName}}
import (
"encoding/json"
"encoding/gob"
{{if .ImportFmt}}"fmt"{{end}}
"strings"
"github.com/mijia/modelq/gmq"
"database/sql"
{{if .ImportTime}}"time"{{end}}
)
`
var modelStruct string = `type {{.Name}} struct {
{{range .Fields}}{{.Name}} {{.Type}} {{.JsonMeta}}{{if .Comment}} // {{.Comment}}{{end}}
{{end}}
}
`
var objApi string = `
// Start of the {{.Name}} APIs.
func (obj {{.Name}}) String() string {
if data, err := json.Marshal(obj); err != nil {
{{if .PrimaryFields}}return fmt.Sprintf({{ call .PrimaryFields.FormatObject .Name }}){{else}}return "<{{.Name}}>"{{end}}
} else {
return string(data)
}
}
func (obj {{.Name}}) Get(dbtx gmq.DbTx) ({{.Name}}, error) {
{{if .PrimaryFields}}{{ call .PrimaryFields.FormatFilters .Name }}
if result, err := {{.Name}}Objs.Select().Where(filter).One(dbtx); err != nil {
return obj, err
} else {
return result, nil
}{{else}}return obj, gmq.ErrNoPrimaryKeyDefined{{end}}
}
func (obj {{.Name}}) Insert(dbtx gmq.DbTx) ({{.Name}}, error) {
{{if .HasAutoIncrementPrimaryKey}}if result, err := {{.Name}}Objs.Insert(obj).Run(dbtx); err != nil {
return obj, err
}else {
if dbtx.DriverName() != "postgres" {
if id, err := result.LastInsertId(); err != nil {
return obj, err
} else {
{{ call .PrimaryFields.FormatIncrementId }}
return obj, err
}
}
return obj, nil
}{{else}}_, err := {{.Name}}Objs.Insert(obj).Run(dbtx)
return obj, err{{end}}
}
func (obj {{.Name}}) Update(dbtx gmq.DbTx) (int64, error) {
{{if .PrimaryFields}}fields := []string{ {{.UpdatableFields}} }
{{ call .PrimaryFields.FormatFilters .Name }}
if result, err := {{.Name}}Objs.Update(obj, fields...).Where(filter).Run(dbtx); err != nil {
return 0, err
} else {
return result.RowsAffected()
}{{else}}return 0, gmq.ErrNoPrimaryKeyDefined{{end}}
}
func (obj {{.Name}}) Delete(dbtx gmq.DbTx) (int64, error) {
{{if .PrimaryFields}}{{ call .PrimaryFields.FormatFilters .Name }}
if result, err := {{.Name}}Objs.Delete().Where(filter).Run(dbtx); err != nil {
return 0, err
} else {
return result.RowsAffected()
}{{else}}return 0, gmq.ErrNoPrimaryKeyDefined{{end}}
}
`
var queryApi string = `
// Start of the inner Query Api
type _{{.Name}}Query struct {
gmq.Query
}
func (q _{{.Name}}Query) Where(f gmq.Filter) _{{.Name}}Query {
q.Query = q.Query.Where(f)
return q
}
func (q _{{.Name}}Query) OrderBy(by ...string) _{{.Name}}Query {
tBy := make([]string, 0, len(by))
for _, b := range by {
sortDir := ""
if b[0] == '-' || b[0] == '+' {
sortDir = string(b[0])
b = b[1:]
}
if col, ok := {{.Name}}Objs.fcMap[b]; ok {
tBy = append(tBy, sortDir+col)
}
}
q.Query = q.Query.OrderBy(tBy...)
return q
}
func (q _{{.Name}}Query) GroupBy(by ...string) _{{.Name}}Query {
tBy := make([]string, 0, len(by))
for _, b := range by {
if col, ok := {{.Name}}Objs.fcMap[b]; ok {
tBy = append(tBy, col)
}
}
q.Query = q.Query.GroupBy(tBy...)
return q
}
func (q _{{.Name}}Query) Limit(offsets ...int64) _{{.Name}}Query {
q.Query = q.Query.Limit(offsets...)
return q
}
func (q _{{.Name}}Query) Page(number, size int) _{{.Name}}Query {
q.Query = q.Query.Page(number, size)
return q
}
func (q _{{.Name}}Query) Run(dbtx gmq.DbTx) (sql.Result, error) {
return q.Query.Exec(dbtx)
}
type {{.Name}}RowVisitor func(obj {{.Name}}) bool
func (q _{{.Name}}Query) Iterate(dbtx gmq.DbTx, functor {{.Name}}RowVisitor) error {
return q.Query.SelectList(dbtx, func(columns []gmq.Column, rb []sql.RawBytes) bool {
obj := {{.Name}}Objs.to{{.Name}}(columns, rb)
return functor(obj)
})
}
func (q _{{.Name}}Query) One(dbtx gmq.DbTx) ({{.Name}}, error) {
var obj {{.Name}}
err := q.Query.SelectOne(dbtx, func(columns []gmq.Column, rb []sql.RawBytes) bool {
obj = {{.Name}}Objs.to{{.Name}}(columns, rb)
return true
})
return obj, err
}
func (q _{{.Name}}Query) List(dbtx gmq.DbTx) ([]{{.Name}}, error) {
result := make([]{{.Name}}, 0, 10)
err := q.Query.SelectList(dbtx, func(columns []gmq.Column, rb []sql.RawBytes) bool {
obj := {{.Name}}Objs.to{{.Name}}(columns, rb)
result = append(result, obj)
return true
})
return result, err
}
func (q _{{.Name}}Query) Count(dbtx gmq.DbTx) (int, error) {
result := 0
err := q.Query.SelectCount(dbtx, func(columns []gmq.Column, rb []sql.RawBytes) bool {
if len(columns) == len(rb) {
for i := range columns {
if "_count" == columns[i].Name {
result = gmq.AsInt(rb[i])
return true
}
}
}
return true
})
return result, err
}
`
var managedApi string = `
// Start of the model facade Apis.
type _{{.Name}}Objs struct {
fcMap map[string]string
}
func (o _{{.Name}}Objs) Names() (schema, tbl, alias string) {
return "{{.DbName}}", "{{.TableName}}", "{{.Name}}"
}
func (o _{{.Name}}Objs) Select(fields ...string) _{{.Name}}Query {
q := _{{.Name}}Query{}
if len(fields) == 0 {
fields = []string{ {{.AllFields}} }
}
q.Query = gmq.Select(o, o.columns(fields...))
return q
}
func (o _{{.Name}}Objs) Insert(obj {{.Name}}) _{{.Name}}Query {
q := _{{.Name}}Query{}
q.Query = gmq.Insert(o, o.columnsWithData(obj, {{.InsertableFields}}))
return q
}
func (o _{{.Name}}Objs) Update(obj {{.Name}}, fields ...string) _{{.Name}}Query {
q := _{{.Name}}Query{}
q.Query = gmq.Update(o, o.columnsWithData(obj, fields...))
return q
}
func (o _{{.Name}}Objs) Delete() _{{.Name}}Query {
q := _{{.Name}}Query{}
q.Query = gmq.Delete(o)
return q
}
{{$ModelName := .Name }}
///// Managed Objects Filters definition
{{range .Fields}}
func (o _{{$ModelName}}Objs) Filter{{.Name}}(op string, p {{.Type}}, ps ...{{.Type}}) gmq.Filter {
params := make([]interface{}, 1+len(ps))
params[0] = p
for i := range ps {
params[i+1] = ps[i]
}
return o.newFilter("{{.ColumnName}}", op, params...)
}
{{end}}
///// Managed Objects Columns definition
{{range .Fields}}
func (o _{{$ModelName}}Objs) Column{{.Name}}(p ...{{.Type}}) gmq.Column {
var value interface{}
if len(p) > 0 {
value = p[0]
}
return gmq.Column{"{{.ColumnName}}", value}
}
{{end}}
////// Internal helper funcs
func (o _{{.Name}}Objs) newFilter(name, op string, params ...interface{}) gmq.Filter {
if strings.ToUpper(op) == "IN" {
return gmq.InFilter(name, params)
}
return gmq.UnitFilter(name, op, params[0])
}
func (o _{{.Name}}Objs) to{{.Name}}(columns []gmq.Column, rb []sql.RawBytes) {{.Name}} {
obj := {{.Name}}{}
if len(columns) == len(rb) {
for i := range columns {
switch columns[i].Name {
{{range .Fields}}case "{{.ColumnName}}":
obj.{{.Name}} = gmq.{{.ConverterFuncName}}(rb[i])
{{end}} }
}
}
return obj
}
func (o _{{.Name}}Objs) columns(fields ...string) []gmq.Column {
data := make([]gmq.Column, 0, len(fields))
for _, f := range fields {
switch f {
{{range .Fields}}case "{{.Name}}":
data = append(data, o.Column{{.Name}}())
{{end}} }
}
return data
}
func (o _{{.Name}}Objs) columnsWithData(obj {{.Name}}, fields ...string) []gmq.Column {
data := make([]gmq.Column, 0, len(fields))
for _, f := range fields {
switch f {
{{range .Fields}}case "{{.Name}}":
data = append(data, o.Column{{.Name}}(obj.{{.Name}}))
{{end}} }
}
return data
}
var {{.Name}}Objs _{{.Name}}Objs
func init() {
{{.Name}}Objs.fcMap = map[string]string{
{{range .Fields}}"{{.Name}}": "{{.ColumnName}}",
{{end}} }
gob.Register({{.Name}}{})
}
`
var (
tmHeader *template.Template
tmStruct *template.Template
tmObjApi *template.Template
tmQueryApi *template.Template
tmManagedObjApi *template.Template
)
func init() {
tmHeader = template.Must(template.New("header").Parse(header))
tmStruct = template.Must(template.New("modelStruct").Parse(modelStruct))
tmObjApi = template.Must(template.New("objApi").Parse(objApi))
tmQueryApi = template.Must(template.New("queryApi").Parse(queryApi))
tmManagedObjApi = template.Must(template.New("managedApi").Parse(managedApi))
}