-
Notifications
You must be signed in to change notification settings - Fork 27
/
query.sql.go
349 lines (302 loc) · 11.2 KB
/
query.sql.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
// Code generated by pggen. DO NOT EDIT.
package device
import (
"context"
"fmt"
"github.com/jackc/pgconn"
"github.com/jackc/pgtype"
"github.com/jackc/pgx/v4"
)
// Querier is a typesafe Go interface backed by SQL queries.
type Querier interface {
FindDevicesByUser(ctx context.Context, id int) ([]FindDevicesByUserRow, error)
CompositeUser(ctx context.Context) ([]CompositeUserRow, error)
CompositeUserOne(ctx context.Context) (User, error)
CompositeUserOneTwoCols(ctx context.Context) (CompositeUserOneTwoColsRow, error)
CompositeUserMany(ctx context.Context) ([]User, error)
InsertUser(ctx context.Context, userID int, name string) (pgconn.CommandTag, error)
InsertDevice(ctx context.Context, mac pgtype.Macaddr, owner int) (pgconn.CommandTag, error)
}
var _ Querier = &DBQuerier{}
type DBQuerier struct {
conn genericConn // underlying Postgres transport to use
types *typeResolver // resolve types by name
}
// genericConn is a connection like *pgx.Conn, pgx.Tx, or *pgxpool.Pool.
type genericConn interface {
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error)
}
// NewQuerier creates a DBQuerier that implements Querier.
func NewQuerier(conn genericConn) *DBQuerier {
return &DBQuerier{conn: conn, types: newTypeResolver()}
}
// User represents the Postgres composite type "user".
type User struct {
ID *int `json:"id"`
Name *string `json:"name"`
}
// DeviceType represents the Postgres enum "device_type".
type DeviceType string
const (
DeviceTypeUndefined DeviceType = "undefined"
DeviceTypePhone DeviceType = "phone"
DeviceTypeLaptop DeviceType = "laptop"
DeviceTypeIpad DeviceType = "ipad"
DeviceTypeDesktop DeviceType = "desktop"
DeviceTypeIot DeviceType = "iot"
)
func (d DeviceType) String() string { return string(d) }
// typeResolver looks up the pgtype.ValueTranscoder by Postgres type name.
type typeResolver struct {
connInfo *pgtype.ConnInfo // types by Postgres type name
}
func newTypeResolver() *typeResolver {
ci := pgtype.NewConnInfo()
return &typeResolver{connInfo: ci}
}
// findValue find the OID, and pgtype.ValueTranscoder for a Postgres type name.
func (tr *typeResolver) findValue(name string) (uint32, pgtype.ValueTranscoder, bool) {
typ, ok := tr.connInfo.DataTypeForName(name)
if !ok {
return 0, nil, false
}
v := pgtype.NewValue(typ.Value)
return typ.OID, v.(pgtype.ValueTranscoder), true
}
// setValue sets the value of a ValueTranscoder to a value that should always
// work and panics if it fails.
func (tr *typeResolver) setValue(vt pgtype.ValueTranscoder, val interface{}) pgtype.ValueTranscoder {
if err := vt.Set(val); err != nil {
panic(fmt.Sprintf("set ValueTranscoder %T to %+v: %s", vt, val, err))
}
return vt
}
type compositeField struct {
name string // name of the field
typeName string // Postgres type name
defaultVal pgtype.ValueTranscoder // default value to use
}
func (tr *typeResolver) newCompositeValue(name string, fields ...compositeField) pgtype.ValueTranscoder {
if _, val, ok := tr.findValue(name); ok {
return val
}
fs := make([]pgtype.CompositeTypeField, len(fields))
vals := make([]pgtype.ValueTranscoder, len(fields))
isBinaryOk := true
for i, field := range fields {
oid, val, ok := tr.findValue(field.typeName)
if !ok {
oid = unknownOID
val = field.defaultVal
}
isBinaryOk = isBinaryOk && oid != unknownOID
fs[i] = pgtype.CompositeTypeField{Name: field.name, OID: oid}
vals[i] = val
}
// Okay to ignore error because it's only thrown when the number of field
// names does not equal the number of ValueTranscoders.
typ, _ := pgtype.NewCompositeTypeValues(name, fs, vals)
if !isBinaryOk {
return textPreferrer{ValueTranscoder: typ, typeName: name}
}
return typ
}
func (tr *typeResolver) newArrayValue(name, elemName string, defaultVal func() pgtype.ValueTranscoder) pgtype.ValueTranscoder {
if _, val, ok := tr.findValue(name); ok {
return val
}
elemOID, elemVal, ok := tr.findValue(elemName)
elemValFunc := func() pgtype.ValueTranscoder {
return pgtype.NewValue(elemVal).(pgtype.ValueTranscoder)
}
if !ok {
elemOID = unknownOID
elemValFunc = defaultVal
}
typ := pgtype.NewArrayType(name, elemOID, elemValFunc)
if elemOID == unknownOID {
return textPreferrer{ValueTranscoder: typ, typeName: name}
}
return typ
}
// newUser creates a new pgtype.ValueTranscoder for the Postgres
// composite type 'user'.
func (tr *typeResolver) newUser() pgtype.ValueTranscoder {
return tr.newCompositeValue(
"user",
compositeField{name: "id", typeName: "int8", defaultVal: &pgtype.Int8{}},
compositeField{name: "name", typeName: "text", defaultVal: &pgtype.Text{}},
)
}
const findDevicesByUserSQL = `SELECT
id,
name,
(SELECT array_agg(mac) FROM device WHERE owner = id) AS mac_addrs
FROM "user"
WHERE id = $1;`
type FindDevicesByUserRow struct {
ID int `json:"id"`
Name string `json:"name"`
MacAddrs pgtype.MacaddrArray `json:"mac_addrs"`
}
// FindDevicesByUser implements Querier.FindDevicesByUser.
func (q *DBQuerier) FindDevicesByUser(ctx context.Context, id int) ([]FindDevicesByUserRow, error) {
ctx = context.WithValue(ctx, "pggen_query_name", "FindDevicesByUser")
rows, err := q.conn.Query(ctx, findDevicesByUserSQL, id)
if err != nil {
return nil, fmt.Errorf("query FindDevicesByUser: %w", err)
}
defer rows.Close()
items := []FindDevicesByUserRow{}
for rows.Next() {
var item FindDevicesByUserRow
if err := rows.Scan(&item.ID, &item.Name, &item.MacAddrs); err != nil {
return nil, fmt.Errorf("scan FindDevicesByUser row: %w", err)
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("close FindDevicesByUser rows: %w", err)
}
return items, err
}
const compositeUserSQL = `SELECT
d.mac,
d.type,
ROW (u.id, u.name)::"user" AS "user"
FROM device d
LEFT JOIN "user" u ON u.id = d.owner;`
type CompositeUserRow struct {
Mac pgtype.Macaddr `json:"mac"`
Type DeviceType `json:"type"`
User User `json:"user"`
}
// CompositeUser implements Querier.CompositeUser.
func (q *DBQuerier) CompositeUser(ctx context.Context) ([]CompositeUserRow, error) {
ctx = context.WithValue(ctx, "pggen_query_name", "CompositeUser")
rows, err := q.conn.Query(ctx, compositeUserSQL)
if err != nil {
return nil, fmt.Errorf("query CompositeUser: %w", err)
}
defer rows.Close()
items := []CompositeUserRow{}
userRow := q.types.newUser()
for rows.Next() {
var item CompositeUserRow
if err := rows.Scan(&item.Mac, &item.Type, userRow); err != nil {
return nil, fmt.Errorf("scan CompositeUser row: %w", err)
}
if err := userRow.AssignTo(&item.User); err != nil {
return nil, fmt.Errorf("assign CompositeUser row: %w", err)
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("close CompositeUser rows: %w", err)
}
return items, err
}
const compositeUserOneSQL = `SELECT ROW (15, 'qux')::"user" AS "user";`
// CompositeUserOne implements Querier.CompositeUserOne.
func (q *DBQuerier) CompositeUserOne(ctx context.Context) (User, error) {
ctx = context.WithValue(ctx, "pggen_query_name", "CompositeUserOne")
row := q.conn.QueryRow(ctx, compositeUserOneSQL)
var item User
userRow := q.types.newUser()
if err := row.Scan(userRow); err != nil {
return item, fmt.Errorf("query CompositeUserOne: %w", err)
}
if err := userRow.AssignTo(&item); err != nil {
return item, fmt.Errorf("assign CompositeUserOne row: %w", err)
}
return item, nil
}
const compositeUserOneTwoColsSQL = `SELECT 1 AS num, ROW (15, 'qux')::"user" AS "user";`
type CompositeUserOneTwoColsRow struct {
Num int32 `json:"num"`
User User `json:"user"`
}
// CompositeUserOneTwoCols implements Querier.CompositeUserOneTwoCols.
func (q *DBQuerier) CompositeUserOneTwoCols(ctx context.Context) (CompositeUserOneTwoColsRow, error) {
ctx = context.WithValue(ctx, "pggen_query_name", "CompositeUserOneTwoCols")
row := q.conn.QueryRow(ctx, compositeUserOneTwoColsSQL)
var item CompositeUserOneTwoColsRow
userRow := q.types.newUser()
if err := row.Scan(&item.Num, userRow); err != nil {
return item, fmt.Errorf("query CompositeUserOneTwoCols: %w", err)
}
if err := userRow.AssignTo(&item.User); err != nil {
return item, fmt.Errorf("assign CompositeUserOneTwoCols row: %w", err)
}
return item, nil
}
const compositeUserManySQL = `SELECT ROW (15, 'qux')::"user" AS "user";`
// CompositeUserMany implements Querier.CompositeUserMany.
func (q *DBQuerier) CompositeUserMany(ctx context.Context) ([]User, error) {
ctx = context.WithValue(ctx, "pggen_query_name", "CompositeUserMany")
rows, err := q.conn.Query(ctx, compositeUserManySQL)
if err != nil {
return nil, fmt.Errorf("query CompositeUserMany: %w", err)
}
defer rows.Close()
items := []User{}
userRow := q.types.newUser()
for rows.Next() {
var item User
if err := rows.Scan(userRow); err != nil {
return nil, fmt.Errorf("scan CompositeUserMany row: %w", err)
}
if err := userRow.AssignTo(&item); err != nil {
return nil, fmt.Errorf("assign CompositeUserMany row: %w", err)
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("close CompositeUserMany rows: %w", err)
}
return items, err
}
const insertUserSQL = `INSERT INTO "user" (id, name)
VALUES ($1, $2);`
// InsertUser implements Querier.InsertUser.
func (q *DBQuerier) InsertUser(ctx context.Context, userID int, name string) (pgconn.CommandTag, error) {
ctx = context.WithValue(ctx, "pggen_query_name", "InsertUser")
cmdTag, err := q.conn.Exec(ctx, insertUserSQL, userID, name)
if err != nil {
return cmdTag, fmt.Errorf("exec query InsertUser: %w", err)
}
return cmdTag, err
}
const insertDeviceSQL = `INSERT INTO device (mac, owner)
VALUES ($1, $2);`
// InsertDevice implements Querier.InsertDevice.
func (q *DBQuerier) InsertDevice(ctx context.Context, mac pgtype.Macaddr, owner int) (pgconn.CommandTag, error) {
ctx = context.WithValue(ctx, "pggen_query_name", "InsertDevice")
cmdTag, err := q.conn.Exec(ctx, insertDeviceSQL, mac, owner)
if err != nil {
return cmdTag, fmt.Errorf("exec query InsertDevice: %w", err)
}
return cmdTag, err
}
// textPreferrer wraps a pgtype.ValueTranscoder and sets the preferred encoding
// format to text instead binary (the default). pggen uses the text format
// when the OID is unknownOID because the binary format requires the OID.
// Typically occurs for unregistered types.
type textPreferrer struct {
pgtype.ValueTranscoder
typeName string
}
// PreferredParamFormat implements pgtype.ParamFormatPreferrer.
func (t textPreferrer) PreferredParamFormat() int16 { return pgtype.TextFormatCode }
func (t textPreferrer) NewTypeValue() pgtype.Value {
return textPreferrer{ValueTranscoder: pgtype.NewValue(t.ValueTranscoder).(pgtype.ValueTranscoder), typeName: t.typeName}
}
func (t textPreferrer) TypeName() string {
return t.typeName
}
// unknownOID means we don't know the OID for a type. This is okay for decoding
// because pgx call DecodeText or DecodeBinary without requiring the OID. For
// encoding parameters, pggen uses textPreferrer if the OID is unknown.
const unknownOID = 0