-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathgen.go
407 lines (359 loc) · 10.1 KB
/
gen.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
package golang
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"go/format"
"strings"
"text/template"
"github.com/sqlc-dev/sqlc-gen-go/internal/opts"
"github.com/sqlc-dev/plugin-sdk-go/sdk"
"github.com/sqlc-dev/plugin-sdk-go/metadata"
"github.com/sqlc-dev/plugin-sdk-go/plugin"
)
type tmplCtx struct {
Q string
Package string
SQLDriver opts.SQLDriver
Enums []Enum
Structs []Struct
GoQueries []Query
SqlcVersion string
// TODO: Race conditions
SourceName string
EmitJSONTags bool
JsonTagsIDUppercase bool
EmitDBTags bool
EmitPreparedQueries bool
EmitInterface bool
EmitEmptySlices bool
EmitMethodsWithDBArgument bool
EmitEnumValidMethod bool
EmitAllEnumValues bool
UsesCopyFrom bool
UsesBatch bool
OmitSqlcVersion bool
BuildTags string
}
func (t *tmplCtx) OutputQuery(sourceName string) bool {
return t.SourceName == sourceName
}
func (t *tmplCtx) codegenDbarg() string {
if t.EmitMethodsWithDBArgument {
return "db DBTX, "
}
return ""
}
// Called as a global method since subtemplate queryCodeStdExec does not have
// access to the toplevel tmplCtx
func (t *tmplCtx) codegenEmitPreparedQueries() bool {
return t.EmitPreparedQueries
}
func (t *tmplCtx) codegenQueryMethod(q Query) string {
db := "q.db"
if t.EmitMethodsWithDBArgument {
db = "db"
}
switch q.Cmd {
case ":one":
if t.EmitPreparedQueries {
return "q.queryRow"
}
return db + ".QueryRowContext"
case ":many":
if t.EmitPreparedQueries {
return "q.query"
}
return db + ".QueryContext"
default:
if t.EmitPreparedQueries {
return "q.exec"
}
return db + ".ExecContext"
}
}
func (t *tmplCtx) codegenQueryRetval(q Query) (string, error) {
switch q.Cmd {
case ":one":
return "row :=", nil
case ":many":
return "rows, err :=", nil
case ":exec":
return "_, err :=", nil
case ":execrows", ":execlastid":
return "result, err :=", nil
case ":execresult":
return "return", nil
default:
return "", fmt.Errorf("unhandled q.Cmd case %q", q.Cmd)
}
}
func Generate(ctx context.Context, req *plugin.GenerateRequest) (*plugin.GenerateResponse, error) {
options, err := opts.Parse(req)
if err != nil {
return nil, err
}
if err := opts.ValidateOpts(options); err != nil {
return nil, err
}
enums := buildEnums(req, options)
structs := buildStructs(req, options)
queries, err := buildQueries(req, options, structs)
if err != nil {
return nil, err
}
if options.OmitUnusedStructs {
enums, structs = filterUnusedStructs(enums, structs, queries)
}
if err := validate(options, enums, structs, queries); err != nil {
return nil, err
}
return generate(req, options, enums, structs, queries)
}
func validate(options *opts.Options, enums []Enum, structs []Struct, queries []Query) error {
enumNames := make(map[string]struct{})
for _, enum := range enums {
enumNames[enum.Name] = struct{}{}
enumNames["Null"+enum.Name] = struct{}{}
}
structNames := make(map[string]struct{})
for _, struckt := range structs {
if _, ok := enumNames[struckt.Name]; ok {
return fmt.Errorf("struct name conflicts with enum name: %s", struckt.Name)
}
structNames[struckt.Name] = struct{}{}
}
if !options.EmitExportedQueries {
return nil
}
for _, query := range queries {
if _, ok := enumNames[query.ConstantName]; ok {
return fmt.Errorf("query constant name conflicts with enum name: %s", query.ConstantName)
}
if _, ok := structNames[query.ConstantName]; ok {
return fmt.Errorf("query constant name conflicts with struct name: %s", query.ConstantName)
}
}
return nil
}
func generate(req *plugin.GenerateRequest, options *opts.Options, enums []Enum, structs []Struct, queries []Query) (*plugin.GenerateResponse, error) {
i := &importer{
Options: options,
Queries: queries,
Enums: enums,
Structs: structs,
}
tctx := tmplCtx{
EmitInterface: options.EmitInterface,
EmitJSONTags: options.EmitJsonTags,
JsonTagsIDUppercase: options.JsonTagsIdUppercase,
EmitDBTags: options.EmitDbTags,
EmitPreparedQueries: options.EmitPreparedQueries,
EmitEmptySlices: options.EmitEmptySlices,
EmitMethodsWithDBArgument: options.EmitMethodsWithDbArgument,
EmitEnumValidMethod: options.EmitEnumValidMethod,
EmitAllEnumValues: options.EmitAllEnumValues,
UsesCopyFrom: usesCopyFrom(queries),
UsesBatch: usesBatch(queries),
SQLDriver: parseDriver(options.SqlPackage),
Q: "`",
Package: options.Package,
Enums: enums,
Structs: structs,
SqlcVersion: req.SqlcVersion,
BuildTags: options.BuildTags,
OmitSqlcVersion: options.OmitSqlcVersion,
}
if tctx.UsesCopyFrom && !tctx.SQLDriver.IsPGX() && options.SqlDriver != opts.SQLDriverGoSQLDriverMySQL {
return nil, errors.New(":copyfrom is only supported by pgx and github.com/go-sql-driver/mysql")
}
if tctx.UsesCopyFrom && options.SqlDriver == opts.SQLDriverGoSQLDriverMySQL {
if err := checkNoTimesForMySQLCopyFrom(queries); err != nil {
return nil, err
}
tctx.SQLDriver = opts.SQLDriverGoSQLDriverMySQL
}
if tctx.UsesBatch && !tctx.SQLDriver.IsPGX() {
return nil, errors.New(":batch* commands are only supported by pgx")
}
funcMap := template.FuncMap{
"lowerTitle": sdk.LowerTitle,
"comment": sdk.DoubleSlashComment,
"escape": sdk.EscapeBacktick,
"imports": i.Imports,
"hasImports": i.HasImports,
"hasPrefix": strings.HasPrefix,
// These methods are Go specific, they do not belong in the codegen package
// (as that is language independent)
"dbarg": tctx.codegenDbarg,
"emitPreparedQueries": tctx.codegenEmitPreparedQueries,
"queryMethod": tctx.codegenQueryMethod,
"queryRetval": tctx.codegenQueryRetval,
}
tmpl := template.Must(
template.New("table").
Funcs(funcMap).
ParseFS(
templates,
"templates/*.tmpl",
"templates/*/*.tmpl",
),
)
output := map[string]string{}
execute := func(name, templateName string) error {
imports := i.Imports(name)
replacedQueries := replaceConflictedArg(imports, queries)
var b bytes.Buffer
w := bufio.NewWriter(&b)
tctx.SourceName = name
tctx.GoQueries = replacedQueries
err := tmpl.ExecuteTemplate(w, templateName, &tctx)
w.Flush()
if err != nil {
return err
}
code, err := format.Source(b.Bytes())
if err != nil {
fmt.Println(b.String())
return fmt.Errorf("source error: %w", err)
}
if templateName == "queryFile" && options.OutputFilesSuffix != "" {
name += options.OutputFilesSuffix
}
if !strings.HasSuffix(name, ".go") {
name += ".go"
}
output[name] = string(code)
return nil
}
dbFileName := "db.go"
if options.OutputDbFileName != "" {
dbFileName = options.OutputDbFileName
}
modelsFileName := "models.go"
if options.OutputModelsFileName != "" {
modelsFileName = options.OutputModelsFileName
}
querierFileName := "querier.go"
if options.OutputQuerierFileName != "" {
querierFileName = options.OutputQuerierFileName
}
copyfromFileName := "copyfrom.go"
if options.OutputCopyfromFileName != "" {
copyfromFileName = options.OutputCopyfromFileName
}
batchFileName := "batch.go"
if options.OutputBatchFileName != "" {
batchFileName = options.OutputBatchFileName
}
if err := execute(dbFileName, "dbFile"); err != nil {
return nil, err
}
if err := execute(modelsFileName, "modelsFile"); err != nil {
return nil, err
}
if options.EmitInterface {
if err := execute(querierFileName, "interfaceFile"); err != nil {
return nil, err
}
}
if tctx.UsesCopyFrom {
if err := execute(copyfromFileName, "copyfromFile"); err != nil {
return nil, err
}
}
if tctx.UsesBatch {
if err := execute(batchFileName, "batchFile"); err != nil {
return nil, err
}
}
files := map[string]struct{}{}
for _, gq := range queries {
files[gq.SourceName] = struct{}{}
}
for source := range files {
if err := execute(source, "queryFile"); err != nil {
return nil, err
}
}
resp := plugin.GenerateResponse{}
for filename, code := range output {
resp.Files = append(resp.Files, &plugin.File{
Name: filename,
Contents: []byte(code),
})
}
return &resp, nil
}
func usesCopyFrom(queries []Query) bool {
for _, q := range queries {
if q.Cmd == metadata.CmdCopyFrom {
return true
}
}
return false
}
func usesBatch(queries []Query) bool {
for _, q := range queries {
for _, cmd := range []string{metadata.CmdBatchExec, metadata.CmdBatchMany, metadata.CmdBatchOne} {
if q.Cmd == cmd {
return true
}
}
}
return false
}
func checkNoTimesForMySQLCopyFrom(queries []Query) error {
for _, q := range queries {
if q.Cmd != metadata.CmdCopyFrom {
continue
}
for _, f := range q.Arg.CopyFromMySQLFields() {
if f.Type == "time.Time" {
return fmt.Errorf("values with a timezone are not yet supported")
}
}
}
return nil
}
func filterUnusedStructs(enums []Enum, structs []Struct, queries []Query) ([]Enum, []Struct) {
keepTypes := make(map[string]struct{})
for _, query := range queries {
if !query.Arg.isEmpty() {
keepTypes[query.Arg.Type()] = struct{}{}
if query.Arg.IsStruct() {
for _, field := range query.Arg.Struct.Fields {
keepTypes[field.Type] = struct{}{}
}
}
}
if query.hasRetType() {
keepTypes[query.Ret.Type()] = struct{}{}
if query.Ret.IsStruct() {
for _, field := range query.Ret.Struct.Fields {
keepTypes[field.Type] = struct{}{}
for _, embedField := range field.EmbedFields {
keepTypes[embedField.Type] = struct{}{}
}
}
}
}
}
keepEnums := make([]Enum, 0, len(enums))
for _, enum := range enums {
_, keep := keepTypes[enum.Name]
_, keepNull := keepTypes["Null"+enum.Name]
if keep || keepNull {
keepEnums = append(keepEnums, enum)
}
}
keepStructs := make([]Struct, 0, len(structs))
for _, st := range structs {
if _, ok := keepTypes[st.Name]; ok {
keepStructs = append(keepStructs, st)
}
}
return keepEnums, keepStructs
}