forked from volatiletech/sqlboiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
templates.go
292 lines (232 loc) · 6.94 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
package boilingcore
import (
"crypto/sha256"
"encoding"
"encoding/base64"
"fmt"
"io/ioutil"
"path/filepath"
"sort"
"strings"
"text/template"
"github.com/pkg/errors"
"github.com/volatiletech/sqlboiler/drivers"
"github.com/volatiletech/sqlboiler/strmangle"
"github.com/volatiletech/sqlboiler/templatebin"
)
// templateData for sqlboiler templates
type templateData struct {
Tables []drivers.Table
Table drivers.Table
Aliases Aliases
// Controls what names are output
PkgName string
Schema string
// Helps tune the output
DriverName string
Dialect drivers.Dialect
// LQ and RQ contain a quoted quote that allows us to write
// the templates more easily.
LQ string
RQ string
// Control various generation features
AddGlobal bool
AddPanic bool
NoContext bool
NoHooks bool
NoAutoTimestamps bool
NoRowsAffected bool
// Tags control which tags are added to the struct
Tags []string
// Generate struct tags as camelCase or snake_case
StructTagCasing string
// StringFuncs are usable in templates with stringMap
StringFuncs map[string]func(string) string
}
func (t templateData) Quotes(s string) string {
return fmt.Sprintf("%s%s%s", t.LQ, s, t.RQ)
}
func (t templateData) SchemaTable(table string) string {
return strmangle.SchemaTable(t.LQ, t.RQ, t.Dialect.UseSchema, t.Schema, table)
}
type templateList struct {
*template.Template
}
type templateNameList []string
func (t templateNameList) Len() int {
return len(t)
}
func (t templateNameList) Swap(k, j int) {
t[k], t[j] = t[j], t[k]
}
func (t templateNameList) Less(k, j int) bool {
// Make sure "struct" goes to the front
if t[k] == "struct.tpl" {
return true
}
res := strings.Compare(t[k], t[j])
if res <= 0 {
return true
}
return false
}
// Templates returns the name of all the templates defined in the template list
func (t templateList) Templates() []string {
tplList := t.Template.Templates()
if len(tplList) == 0 {
return nil
}
ret := make([]string, 0, len(tplList))
for _, tpl := range tplList {
if name := tpl.Name(); strings.HasSuffix(name, ".tpl") {
ret = append(ret, name)
}
}
sort.Sort(templateNameList(ret))
return ret
}
func loadTemplates(lazyTemplates []lazyTemplate, testTemplates bool) (*templateList, error) {
tpl := template.New("")
for _, t := range lazyTemplates {
firstDir := strings.Split(t.Name, string(filepath.Separator))[0]
isTest := strings.HasSuffix(firstDir, "_test")
if testTemplates && !isTest || !testTemplates && isTest {
continue
}
byt, err := t.Loader.Load()
if err != nil {
return nil, errors.Wrapf(err, "failed to load template: %s", t.Name)
}
_, err = tpl.New(t.Name).Funcs(templateFunctions).Parse(string(byt))
if err != nil {
return nil, errors.Wrapf(err, "failed to parse template: %s", t.Name)
}
}
return &templateList{Template: tpl}, nil
}
type lazyTemplate struct {
Name string `json:"name"`
Loader templateLoader `json:"loader"`
}
type templateLoader interface {
encoding.TextMarshaler
Load() ([]byte, error)
}
type fileLoader string
func (f fileLoader) Load() ([]byte, error) {
fname := string(f)
b, err := ioutil.ReadFile(fname)
if err != nil {
return nil, errors.Wrapf(err, "failed to load template: %s", fname)
}
return b, nil
}
func (f fileLoader) MarshalText() ([]byte, error) {
return []byte(f.String()), nil
}
func (f fileLoader) String() string {
return "file:" + string(f)
}
type base64Loader string
func (b base64Loader) Load() ([]byte, error) {
byt, err := base64.StdEncoding.DecodeString(string(b))
if err != nil {
return nil, errors.Wrap(err, "failed to decode driver's template, should be base64)")
}
return byt, nil
}
func (b base64Loader) MarshalText() ([]byte, error) {
return []byte(b.String()), nil
}
func (b base64Loader) String() string {
byt, err := base64.StdEncoding.DecodeString(string(b))
if err != nil {
panic("trying to debug output base64 loader, but was not proper base64!")
}
sha := sha256.Sum256(byt)
return fmt.Sprintf("base64:(sha256 of content): %x", sha)
}
type assetLoader string
func (a assetLoader) Load() ([]byte, error) {
return templatebin.Asset(string(a))
}
func (a assetLoader) MarshalText() ([]byte, error) {
return []byte(a.String()), nil
}
func (a assetLoader) String() string {
return "asset:" + string(a)
}
// set is to stop duplication from named enums, allowing a template loop
// to keep some state
type once map[string]struct{}
func newOnce() once {
return make(once)
}
func (o once) Has(s string) bool {
_, ok := o[s]
return ok
}
func (o once) Put(s string) bool {
if _, ok := o[s]; ok {
return false
}
o[s] = struct{}{}
return true
}
// templateStringMappers are placed into the data to make it easy to use the
// stringMap function.
var templateStringMappers = map[string]func(string) string{
// String ops
"quoteWrap": func(a string) string { return fmt.Sprintf(`"%s"`, a) },
"replaceReserved": strmangle.ReplaceReservedWords,
// Casing
"titleCase": strmangle.TitleCase,
"camelCase": strmangle.CamelCase,
}
// templateFunctions is a map of all the functions that get passed into the
// templates. If you wish to pass a new function into your own template,
// add a function pointer here.
var templateFunctions = template.FuncMap{
// String ops
"quoteWrap": func(s string) string { return fmt.Sprintf(`"%s"`, s) },
"id": strmangle.Identifier,
// Pluralization
"singular": strmangle.Singular,
"plural": strmangle.Plural,
// Casing
"titleCase": strmangle.TitleCase,
"camelCase": strmangle.CamelCase,
// String Slice ops
"join": func(sep string, slice []string) string { return strings.Join(slice, sep) },
"joinSlices": strmangle.JoinSlices,
"stringMap": strmangle.StringMap,
"prefixStringSlice": strmangle.PrefixStringSlice,
"containsAny": strmangle.ContainsAny,
"generateTags": strmangle.GenerateTags,
"generateIgnoreTags": strmangle.GenerateIgnoreTags,
// Enum ops
"parseEnumName": strmangle.ParseEnumName,
"parseEnumVals": strmangle.ParseEnumVals,
"isEnumNormal": strmangle.IsEnumNormal,
"shouldTitleCaseEnum": strmangle.ShouldTitleCaseEnum,
"onceNew": newOnce,
"oncePut": once.Put,
"onceHas": once.Has,
// String Map ops
"makeStringMap": strmangle.MakeStringMap,
// Set operations
"setInclude": strmangle.SetInclude,
// Database related mangling
"whereClause": strmangle.WhereClause,
// Alias and text helping
"aliasCols": func(ta TableAlias) func(string) string { return func(s string) string { return ta.Column(s) } },
"usesPrimitives": usesPrimitives,
// dbdrivers ops
"filterColumnsByAuto": drivers.FilterColumnsByAuto,
"filterColumnsByDefault": drivers.FilterColumnsByDefault,
"filterColumnsByEnum": drivers.FilterColumnsByEnum,
"sqlColDefinitions": drivers.SQLColDefinitions,
"columnNames": drivers.ColumnNames,
"columnDBTypes": drivers.ColumnDBTypes,
"getTable": drivers.GetTable,
}