-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqlboiler.go
376 lines (318 loc) · 9.79 KB
/
sqlboiler.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
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
package utils
import (
"fmt"
"go/ast"
"go/token"
"path"
"strings"
)
///////////////////////////////////////////////////////////////
// Cache
///////////////////////////////////////////////////////////////
var (
modelImports = []string{}
enumCacheMap = map[string]SQLBoilerTableColumnEnum{}
)
///////////////////////////////////////////////////////////////
// SQLBoiler Types
///////////////////////////////////////////////////////////////
type SQLBoilerName struct {
PascalCase string
SnakeCase string
CamelCase string
}
type SQLBoilerType struct {
OriginalName string
FormattedName string
IsEnum bool
}
///////////////////////////////////////////////////////////////
// Main Function | Get SQLBoiler Models and Enums
///////////////////////////////////////////////////////////////
type SQLBoilerTable struct {
Name SQLBoilerName
Relations []SQLBoilerTableRelation
Columns []SQLBoilerTableColumn
Imports []string
}
type SQLBoilerTableRelation struct {
Name SQLBoilerName
MainTableName SQLBoilerName
IsMany bool
Type SQLBoilerType
}
type SQLBoilerTableColumn struct {
IsPrimaryKey bool
Name SQLBoilerName
Type SQLBoilerType
IsRelation bool
}
func (c *Config) getSQLBoilerTablesAndEnums() ([]SQLBoilerTable, []SQLBoilerTableColumnEnum, error) {
enums, err := c.readSQLBoilerEnumsFromFile()
if err != nil {
return nil, nil, err
}
tables, err := c.readSQLBoilerTablesFromFile()
if err != nil {
return nil, nil, err
}
for i, table := range tables {
columns, relations, err := c.readSQLBoilerColumnsAndRelationsFromFile(table)
if err != nil {
return nil, nil, err
}
tables[i] = SQLBoilerTable{
Name: table.Name,
Columns: columns,
Relations: relations,
Imports: c.getERGDefaultImports(true),
}
// reset the model imports
modelImports = []string{}
}
return tables, enums, nil
}
///////////////////////////////////////////////////////////////
// Get SQLBoiler Enums
///////////////////////////////////////////////////////////////
type SQLBoilerTableColumnEnum struct {
Name SQLBoilerName
Values []SQLBoilerTableColumnEnumValue
Type SQLBoilerType
}
type SQLBoilerTableColumnEnumValue struct {
Label string
Value string
}
func (c *Config) readSQLBoilerEnumsFromFile() ([]SQLBoilerTableColumnEnum, error) {
f, err := parseFile(c.getSQLBoilerModelsFilePath("boil_types.go"))
if err != nil {
return nil, err
}
var currentType string
ast.Inspect(f, func(n ast.Node) bool {
if typeSpec, ok := n.(*ast.TypeSpec); ok {
currentType = typeSpec.Name.Name
if basicLit, ok := typeSpec.Type.(*ast.Ident); ok {
enumCacheMap[currentType] = SQLBoilerTableColumnEnum{
Type: SQLBoilerType{
OriginalName: basicLit.Name,
},
}
}
}
if currentType != "" {
if genDecl, ok := n.(*ast.GenDecl); ok && genDecl.Tok == token.CONST {
for _, spec := range genDecl.Specs {
if valueSpec, ok := spec.(*ast.ValueSpec); ok {
for i, name := range valueSpec.Names {
if i < len(valueSpec.Values) {
if basicLit, ok := valueSpec.Values[i].(*ast.BasicLit); ok {
enumCacheMap[currentType] = SQLBoilerTableColumnEnum{
Name: SQLBoilerName{
PascalCase: currentType,
SnakeCase: toSnakeCase(currentType),
CamelCase: toCamelCase(currentType),
},
Values: append(enumCacheMap[currentType].Values, SQLBoilerTableColumnEnumValue{
Label: strings.TrimPrefix(name.Name, currentType),
Value: basicLit.Value,
}),
Type: enumCacheMap[currentType].Type,
}
}
}
}
}
}
}
}
return true
})
var enums []SQLBoilerTableColumnEnum
for _, enum := range enumCacheMap {
enums = append(enums, enum)
}
return enums, err
}
///////////////////////////////////////////////////////////////
// Get SQLBoiler Tables
///////////////////////////////////////////////////////////////
func (c *Config) readSQLBoilerTablesFromFile() ([]SQLBoilerTable, error) {
f, err := parseFile(c.getSQLBoilerModelsFilePath("boil_table_names.go"))
if err != nil {
return nil, err
}
var models []SQLBoilerTable
ast.Inspect(f, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.ValueSpec:
for i, name := range x.Names {
if name.Name == "TableNames" {
values := x.Values[i].(*ast.CompositeLit)
for _, elt := range values.Elts {
if kv, ok := elt.(*ast.KeyValueExpr); ok {
if label, ok := kv.Key.(*ast.Ident); ok {
if strVal, ok := kv.Value.(*ast.BasicLit); ok {
// Extract the string value and unquote it
value := strings.ReplaceAll(strVal.Value, `"`, "")
if c.isBlackListed(value, "") {
continue
}
models = append(models, SQLBoilerTable{
Name: SQLBoilerName{
PascalCase: label.Name,
SnakeCase: value,
CamelCase: toCamelCase(label.Name),
},
})
}
}
}
}
}
}
}
return true
})
return models, nil
}
///////////////////////////////////////////////////////////////
// Get SQLBoiler Model Columns and Relations
///////////////////////////////////////////////////////////////
func (c *Config) readSQLBoilerColumnsAndRelationsFromFile(table SQLBoilerTable) ([]SQLBoilerTableColumn, []SQLBoilerTableRelation, error) {
f, err := parseFile(c.getSQLBoilerModelsFilePath(table.Name.SnakeCase + ".go"))
if err != nil {
return nil, nil, err
}
var columns []SQLBoilerTableColumn
var relations []SQLBoilerTableRelation
ast.Inspect(f, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.TypeSpec:
if structType, isStruct := x.Type.(*ast.StructType); isStruct && x.Name.Name == table.Name.CamelCase+"R" {
for _, field := range structType.Fields.List {
pascalCase := field.Names[0].Name
t := getTypeFromFieldType(field.Type)
mainTableNamePascalCase := strings.TrimSuffix(t.OriginalName, "Slice")
if c.isBlackListed(toSnakeCase(mainTableNamePascalCase), "") {
continue
}
relations = append(relations, SQLBoilerTableRelation{
Name: SQLBoilerName{
PascalCase: pascalCase,
SnakeCase: toSnakeCase(pascalCase),
CamelCase: toCamelCase(pascalCase),
},
MainTableName: SQLBoilerName{
PascalCase: mainTableNamePascalCase,
SnakeCase: toSnakeCase(mainTableNamePascalCase),
CamelCase: toCamelCase(mainTableNamePascalCase),
},
IsMany: strings.HasSuffix(t.OriginalName, "Slice"),
Type: t,
})
}
}
if structType, isStruct := x.Type.(*ast.StructType); isStruct && x.Name.Name == table.Name.PascalCase {
for _, field := range structType.Fields.List {
if !hasTag(field, "-") {
t := getTypeFromFieldType(field.Type)
pascalCase := field.Names[0].Name
snakeCase := getSnakeCaseFromTag(field) // Can be named differently than the field name
if c.isBlackListed(table.Name.SnakeCase, snakeCase) {
continue
}
columns = append(columns, SQLBoilerTableColumn{
Name: SQLBoilerName{
PascalCase: pascalCase,
SnakeCase: snakeCase,
CamelCase: snakeCaseToCamelCase(snakeCase),
},
Type: t,
IsRelation: false,
})
}
}
}
case *ast.GenDecl:
if x.Tok == token.VAR {
for _, spec := range x.Specs {
valueSpec := spec.(*ast.ValueSpec)
name := valueSpec.Names[0].Name
if strings.HasSuffix(name, "PrimaryKeyColumns") {
arrayLit := valueSpec.Values[0].(*ast.CompositeLit)
for _, elt := range arrayLit.Elts {
if kv, ok := elt.(*ast.BasicLit); ok {
for i, column := range columns {
if column.Name.SnakeCase == strings.Trim(kv.Value, `"`) {
columns[i].IsPrimaryKey = true
}
}
}
}
}
}
}
}
return true
})
// if table.Name.SnakeCase != "account" {
// return columns, relations, nil
// }
// for i, column := range columns {
// snakeCaseWithoutID := strings.Replace(column.Name.SnakeCase, "_id", "", -1)
// for _, relation := range relations {
// if relation.Name.SnakeCase == snakeCaseWithoutID {
// columns[i].IsRelation = true
// }
// }
// }
return columns, relations, nil
}
///////////////////////////////////////////////////////////////
// Write SQLBoiler Models to ERG Files
///////////////////////////////////////////////////////////////
func (c *Config) writeSQLBoilerTablesToERGFiles(tables []SQLBoilerTable) error {
for _, table := range tables {
if err := c.writeTemplate("main/erg_table.gotpl", path.Join(c.sqlBoilerConfig.Erg.Output, fmt.Sprintf("%v.go", table.Name.SnakeCase)), table); err != nil {
return err
}
}
return nil
}
func (c *Config) writeSQLBoilerEnumsToERGFiles(enums []SQLBoilerTableColumnEnum) error {
if err := c.writeTemplate("main/erg_enums.gotpl", path.Join(c.sqlBoilerConfig.Erg.Output, "erg_types.go"), enums); err != nil {
return err
}
return nil
}
type ergModel struct {
Imports []string
Tables []SQLBoilerTable
}
func (c *Config) writeSQLBoilerTablesToERGFile(tables []SQLBoilerTable) error {
return c.writeTemplate("main/erg_tables.gotpl", path.Join(c.sqlBoilerConfig.Erg.Output, "erg_tables.go"), ergModel{
Imports: c.getERGDefaultImports(false),
Tables: tables,
})
}
func (c *Config) writeERGHelperFunctionsToFile() error {
return c.writeTemplate("main/erg_helpers.gotpl", path.Join(c.sqlBoilerConfig.Erg.Output, "erg_helpers.go"), nil)
}
type tsModel struct {
Tables []SQLBoilerTable
Enums []SQLBoilerTableColumnEnum
}
func (c *Config) writeSQLBoilerTablesToTypeScriptFiles(tables []SQLBoilerTable, enums []SQLBoilerTableColumnEnum) error {
if !c.isTSEnabled() {
return nil
}
if err := c.writeTemplate("main/ts_tables.tpl", c.sqlBoilerConfig.Erg.OutputTS, tsModel{
Tables: tables,
Enums: enums,
}); err != nil {
return err
}
return nil
}