Repository navigation
Expand file tree
/
Copy pathgen.go
More file actions
521 lines (471 loc) · 13.6 KB
/
Copy pathgen.go
File metadata and controls
521 lines (471 loc) · 13.6 KB
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
package wicked
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"go/format"
"strings"
"text/template"
"github.com/sqlc-dev/sqlc/internal/codegen/golang/opts"
"github.com/sqlc-dev/sqlc/internal/codegen/sdk"
"github.com/sqlc-dev/sqlc/internal/metadata"
"github.com/sqlc-dev/sqlc/internal/plugin"
)
type tmplCtx struct {
Q string
Package string
SQLDriver opts.SQLDriver
Enums []Enum
Structs []Struct
GoQueries []Query
SqlcVersion string
DumpLoader *DumpLoader
RawSchemaSQL string
// The query file currently being rendered by this generation invocation.
SourceName string
EmitJSONTags bool
JsonTagsIDUppercase bool
EmitDBTags bool
EmitPreparedQueries bool
EmitInterface bool
HasEach bool
EmitEmptySlices bool
EmitMethodsWithDBArgument bool
EmitEnumValidMethod bool
EmitAllEnumValues bool
UsesCopyFrom bool
UsesBatch bool
OmitSqlcVersion bool
BuildTags string
WrapErrors bool
}
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":
if t.WrapErrors {
return "result, err :=", nil
}
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) {
if req == nil || req.Settings == nil || req.Catalog == nil {
return nil, errors.New("wicked: missing settings or catalog")
}
options, err := parseOptions(req)
if err != nil {
return nil, err
}
if err := opts.ValidateOpts(options); err != nil {
return nil, err
}
if req.GetWicked() == nil || req.GetWicked().PrimaryRelation == nil {
return nil, errors.New("wicked: missing primary schema metadata")
}
if strings.TrimSpace(req.GetWicked().PrimarySchemaSql) == "" {
return nil, errors.New("wicked: missing primary schema source")
}
for _, query := range req.Queries {
switch query.Cmd {
case metadata.CmdOne, metadata.CmdMany, metadata.CmdExec, metadata.CmdExecRows, metadata.CmdExecResult, metadata.CmdCopyFrom:
default:
return nil, fmt.Errorf("wicked: %s: unsupported command %s", query.Name, query.Cmd)
}
}
if req.Settings.Engine != "postgresql" {
return nil, errors.New("wicked: only PostgreSQL is supported")
}
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 := buildQueryInvalidates(queries); err != nil {
return nil, err
}
var missing []error
for _, q := range queries {
if q.Option.Timeout == 0 {
missing = append(missing, fmt.Errorf("%s/%s does not have a timeout option", options.Package, q.MethodName))
}
}
if len(missing) != 0 {
return nil, errors.Join(missing...)
}
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 {
if hasEach(queries) {
if err := validateEachNames(options, enums, structs, queries); err != nil {
return err
}
}
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,
}
dumploader, err := buildDumpLoader(structs)
if err != nil {
return nil, err
}
tctx := tmplCtx{
DumpLoader: dumploader,
RawSchemaSQL: req.GetWicked().PrimarySchemaSql,
EmitInterface: false,
HasEach: hasEach(queries),
EmitJSONTags: true,
JsonTagsIDUppercase: false,
EmitDBTags: false,
EmitPreparedQueries: false,
EmitEmptySlices: false,
EmitMethodsWithDBArgument: false,
EmitEnumValidMethod: true,
EmitAllEnumValues: true,
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,
WrapErrors: options.WrapErrors,
}
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 {
return fmt.Errorf("formatting generated %s: %w", name, 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[strings.TrimPrefix(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]
_, keepPointer := keepTypes["*"+enum.Name]
if keep || keepNull || keepPointer {
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
}
func hasEach(queries []Query) bool {
for _, query := range queries {
if query.Option.Each {
return true
}
}
return false
}
// Check only declarations introduced by Each. Existing queries without the
// annotation retain the original naming rules and output.
func validateEachNames(options *opts.Options, enums []Enum, structs []Struct, queries []Query) error {
methods := map[string]bool{
"WithTx": true, "WithCache": true, "AsReadOnly": true,
"UseReplica": true, "GetCache": true, "GetConn": true,
"Dump": true, "Load": true,
}
declarations := make(map[string]string)
for _, enum := range enums {
declarations[enum.Name] = "enum"
declarations["Null"+enum.Name] = "enum"
for _, constant := range enum.Constants {
declarations[constant.Name] = "enum constant"
}
}
for _, strct := range structs {
declarations[strct.Name] = "model"
}
for _, query := range queries {
methods[query.MethodName] = true
if query.Cmd != metadata.CmdCopyFrom {
declarations[query.ConstantName] = "query constant"
}
if query.Cmd == metadata.CmdOne || query.Cmd == metadata.CmdMany {
declarations["_"+query.MethodName] = "helper"
}
if query.Arg.EmitStruct() {
declarations[query.Arg.Type()] = "parameter type"
}
if query.Ret.EmitStruct() {
declarations[query.Ret.Type()] = "row type"
}
}
for _, query := range queries {
if !query.Option.Each {
continue
}
name := query.MethodName + "Each"
if methods[name] {
return fmt.Errorf("%s/%s: Each companion name conflicts: %s", options.Package, query.MethodName, name)
}
if kind := declarations["_"+name]; kind != "" {
return fmt.Errorf("%s/%s: Each companion name conflicts with %s: _%s", options.Package, query.MethodName, kind, name)
}
}
if options.EmitInterface {
if kind := declarations["EachQuerier"]; kind != "" {
return fmt.Errorf("Each companion name conflicts with %s: EachQuerier", kind)
}
}
return nil
}