forked from jschaf/pggen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
declarer_composite.go
340 lines (303 loc) · 10.5 KB
/
declarer_composite.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
package golang
import (
"strconv"
"strings"
"github.com/eddiefisher/pggen/internal/codegen/golang/gotype"
"github.com/eddiefisher/pggen/internal/pg"
)
// NameCompositeTranscoderFunc returns the function name that creates a
// pgtype.ValueTranscoder for the composite type that's used to decode rows
// returned by Postgres.
func NameCompositeTranscoderFunc(typ *gotype.CompositeType) string {
return "new" + typ.Name
}
// NameCompositeInitFunc returns the name of the function that creates an
// initialized pgtype.ValueTranscoder for the composite type used as a query
// parameters. This function is only necessary for top-level types. Descendant
// types use the raw functions, named by NameCompositeRawFunc.
func NameCompositeInitFunc(typ *gotype.CompositeType) string {
return "new" + typ.Name + "Init"
}
// NameCompositeRawFunc returns the function name that creates the
// []interface{} array for the composite type so that we can use it with a
// parent encoder function, like NameCompositeInitFunc, in the pgtype.Value
// Set call.
func NameCompositeRawFunc(typ *gotype.CompositeType) string {
return "new" + typ.Name + "Raw"
}
// CompositeTypeDeclarer declares a new Go struct to represent a Postgres
// composite type.
type CompositeTypeDeclarer struct {
comp *gotype.CompositeType
}
func NewCompositeTypeDeclarer(comp *gotype.CompositeType) CompositeTypeDeclarer {
return CompositeTypeDeclarer{comp: comp}
}
func (c CompositeTypeDeclarer) DedupeKey() string {
return "composite::" + c.comp.Name
}
func (c CompositeTypeDeclarer) Declare(pkgPath string) (string, error) {
sb := &strings.Builder{}
// Doc string
if c.comp.PgComposite.Name != "" {
sb.WriteString("// ")
sb.WriteString(c.comp.Name)
sb.WriteString(" represents the Postgres composite type ")
sb.WriteString(strconv.Quote(c.comp.PgComposite.Name))
sb.WriteString(".\n")
}
// Struct declaration.
sb.WriteString("type ")
sb.WriteString(c.comp.Name)
sb.WriteString(" struct")
if len(c.comp.FieldNames) == 0 {
sb.WriteString("{") // type Foo struct{}
} else {
sb.WriteString(" {\n") // type Foo struct {\n
}
// Struct fields.
nameLen, typeLen := getLongestNameTypes(c.comp, pkgPath)
for i, name := range c.comp.FieldNames {
// Name
sb.WriteRune('\t')
sb.WriteString(name)
// Type
qualType := gotype.QualifyType(c.comp.FieldTypes[i], pkgPath)
sb.WriteString(strings.Repeat(" ", nameLen-len(name)))
sb.WriteString(qualType)
// JSON struct tag
sb.WriteString(strings.Repeat(" ", typeLen-len(qualType)))
sb.WriteString("`json:")
sb.WriteString(strconv.Quote(c.comp.PgComposite.ColumnNames[i]))
sb.WriteString("`")
sb.WriteRune('\n')
}
sb.WriteString("}")
return sb.String(), nil
}
// getLongestNameTypes returns the length of the longest name and type name for
// all child fields of a composite type. Useful for aligning struct definitions.
func getLongestNameTypes(typ *gotype.CompositeType, pkgPath string) (int, int) {
nameLen := 0
for _, name := range typ.FieldNames {
if n := len(name); n > nameLen {
nameLen = n
}
}
nameLen++ // 1 space to separate name from type
typeLen := 0
for _, childType := range typ.FieldTypes {
if n := len(gotype.QualifyType(childType, pkgPath)); n > typeLen {
typeLen = n
}
}
typeLen++ // 1 space to separate type from struct tags.
return nameLen, typeLen
}
// CompositeTranscoderDeclarer declares a new Go function that creates a pgx
// decoder for the Postgres type represented by the gotype.CompositeType.
type CompositeTranscoderDeclarer struct {
typ *gotype.CompositeType
}
func NewCompositeTranscoderDeclarer(typ *gotype.CompositeType) CompositeTranscoderDeclarer {
return CompositeTranscoderDeclarer{typ}
}
func (c CompositeTranscoderDeclarer) DedupeKey() string {
return "type_resolver::" + c.typ.Name + "_01_transcoder"
}
func (c CompositeTranscoderDeclarer) Declare(pkgPath string) (string, error) {
funcName := NameCompositeTranscoderFunc(c.typ)
sb := &strings.Builder{}
sb.Grow(256)
// Doc comment
sb.WriteString("// ")
sb.WriteString(funcName)
sb.WriteString(" creates a new pgtype.ValueTranscoder for the Postgres\n")
sb.WriteString("// composite type '")
sb.WriteString(c.typ.PgComposite.Name)
sb.WriteString("'.\n")
// Function signature
sb.WriteString("func (tr *typeResolver) ")
sb.WriteString(funcName)
sb.WriteString("() pgtype.ValueTranscoder {\n\t")
// newCompositeValue call
sb.WriteString("return tr.newCompositeValue(\n\t\t")
sb.WriteString(strconv.Quote(c.typ.PgComposite.Name))
sb.WriteString(",")
// newCompositeValue - field names of the composite type
for i := range c.typ.FieldNames {
sb.WriteString("\n\t\t")
sb.WriteString(`compositeField{name: `)
sb.WriteString(strconv.Quote(c.typ.PgComposite.ColumnNames[i])) // field name
sb.WriteString(", typeName: ")
sb.WriteString(strconv.Quote(c.typ.PgComposite.ColumnTypes[i].String())) // field type name
sb.WriteString(", defaultVal: ")
// field default pgtype.ValueTranscoder
switch fieldType := gotype.UnwrapNestedType(c.typ.FieldTypes[i]).(type) {
case *gotype.CompositeType:
childFuncName := NameCompositeTranscoderFunc(fieldType)
sb.WriteString("tr.")
sb.WriteString(childFuncName)
sb.WriteString("()")
case *gotype.EnumType:
sb.WriteString(NameEnumTranscoderFunc(fieldType))
sb.WriteString("()")
case *gotype.ArrayType:
if typ, ok := gotype.FindKnownTypePgx(fieldType.PgArray.OID()); ok {
sb.WriteString("&") // pgx needs pointers to types
sb.WriteString(gotype.QualifyType(typ, pkgPath))
sb.WriteString("{}")
break
}
sb.WriteString("tr.")
sb.WriteString(NameArrayTranscoderFunc(fieldType))
sb.WriteString("()")
case *gotype.VoidType:
// skip
default:
sb.WriteString("&") // pgx needs pointers to types
// TODO: support builtin types and builtin wrappers that use a different
// initialization syntax.
pgType := c.typ.PgComposite.ColumnTypes[i]
if pgType == nil || pgType == (pg.VoidType{}) {
sb.WriteString("nil,")
} else {
var qualType string
if decoderType, ok := gotype.FindKnownTypePgx(pgType.OID()); ok {
// Look for the pgx variant it matches the interface expected by
// newCompositeValue, pgtype.ValueTranscoder.
qualType = gotype.QualifyType(decoderType, pkgPath)
} else {
// Attempt to use the original, provided type.
qualType = gotype.QualifyType(c.typ.FieldTypes[i], pkgPath)
}
sb.WriteString(qualType)
sb.WriteString("{}")
}
}
sb.WriteString(`},`)
}
sb.WriteString("\n\t")
sb.WriteString(")")
sb.WriteString("\n")
sb.WriteString("}")
return sb.String(), nil
}
// CompositeInitDeclarer declares a new Go function that creates an initialized
// pgtype.ValueTranscoder for the Postgres type represented by the
// gotype.CompositeType.
//
// We need a separate encoder because setting a pgtype.ValueTranscoder is much
// less flexible on the values allowed compared to AssignTo. We can assign a
// pgtype.CompositeType to any struct but we can only set it with an
// []interface{}.
//
// Additionally, we need to use the Postgres text format exclusively because the
// Postgres binary format requires the type OID but pggen doesn't necessarily
// know the OIDs of the types. The text format, however, doesn't require OIDs.
type CompositeInitDeclarer struct {
typ *gotype.CompositeType
}
func NewCompositeInitDeclarer(typ *gotype.CompositeType) CompositeInitDeclarer {
return CompositeInitDeclarer{typ}
}
func (c CompositeInitDeclarer) DedupeKey() string {
return "type_resolver::" + c.typ.Name + "_02_init"
}
func (c CompositeInitDeclarer) Declare(string) (string, error) {
funcName := NameCompositeInitFunc(c.typ)
sb := &strings.Builder{}
sb.Grow(256)
// Doc comment
sb.WriteString("// ")
sb.WriteString(funcName)
sb.WriteString(" creates an initialized pgtype.ValueTranscoder for the\n")
sb.WriteString("// Postgres composite type '")
sb.WriteString(c.typ.PgComposite.Name)
sb.WriteString("' to encode query parameters.\n")
// Function signature
sb.WriteString("func (tr *typeResolver) ")
sb.WriteString(funcName)
sb.WriteString("(v ")
sb.WriteString(c.typ.Name)
sb.WriteString(") pgtype.ValueTranscoder {\n\t")
// Function body
sb.WriteString("return tr.setValue(tr.")
sb.WriteString(NameCompositeTranscoderFunc(c.typ))
sb.WriteString("(), tr.")
sb.WriteString(NameCompositeRawFunc(c.typ))
sb.WriteString("(v))\n")
sb.WriteString("}")
return sb.String(), nil
}
// CompositeRawDeclarer declares a new Go function that returns all fields
// of a composite type as a generic array: []interface{}. Necessary because we
// can only set pgtype.CompositeType from a []interface{}.
//
// Revisit after https://github.com/jackc/pgtype/pull/100 to see if we can
// simplify.
type CompositeRawDeclarer struct {
typ *gotype.CompositeType
}
func NewCompositeRawDeclarer(typ *gotype.CompositeType) CompositeRawDeclarer {
return CompositeRawDeclarer{typ}
}
func (c CompositeRawDeclarer) DedupeKey() string {
return "type_resolver::" + c.typ.Name + "_03_raw"
}
func (c CompositeRawDeclarer) Declare(string) (string, error) {
funcName := NameCompositeRawFunc(c.typ)
sb := &strings.Builder{}
sb.Grow(256)
// Doc comment
sb.WriteString("// ")
sb.WriteString(funcName)
sb.WriteString(" returns all composite fields for the Postgres composite\n")
sb.WriteString("// type '")
sb.WriteString(c.typ.PgComposite.Name)
sb.WriteString("' as a slice of interface{} to encode query parameters.\n")
// Function signature
sb.WriteString("func (tr *typeResolver) ")
sb.WriteString(funcName)
sb.WriteString("(v ")
sb.WriteString(c.typ.Name)
sb.WriteString(") []interface{} {\n\t")
// Function body
sb.WriteString("return []interface{}{")
// Field Assigners of the composite type
for i, fieldType := range c.typ.FieldTypes {
fieldName := c.typ.FieldNames[i]
sb.WriteString("\n\t\t")
switch fieldType := gotype.UnwrapNestedType(fieldType).(type) {
case *gotype.CompositeType:
childFuncName := NameCompositeRawFunc(fieldType)
sb.WriteString("tr.")
sb.WriteString(childFuncName)
sb.WriteString("(v.")
sb.WriteString(fieldName)
sb.WriteString(")")
case *gotype.ArrayType:
if _, ok := gotype.FindKnownTypePgx(fieldType.PgArray.OID()); ok {
sb.WriteString("v.")
sb.WriteString(fieldName)
break
}
sb.WriteString("tr.")
sb.WriteString(NameArrayRawFunc(fieldType))
sb.WriteString("(v.")
sb.WriteString(fieldName)
sb.WriteString(")")
case *gotype.VoidType:
sb.WriteString("nil")
default:
sb.WriteString("v.")
sb.WriteString(fieldName)
}
sb.WriteString(",")
}
sb.WriteString("\n\t")
sb.WriteString("}")
sb.WriteString("\n")
sb.WriteString("}")
return sb.String(), nil
}