forked from jschaf/pggen
/
customer.sql.go
468 lines (411 loc) · 18.1 KB
/
customer.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
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
// Code generated by pggen. DO NOT EDIT.
package order
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.
//
// Methods ending with Batch enqueue a query to run later in a pgx.Batch. After
// calling SendBatch on pgx.Conn, pgxpool.Pool, or pgx.Tx, use the Scan methods
// to parse the results.
type Querier interface {
CreateTenant(ctx context.Context, key string, name string) (CreateTenantRow, error)
// CreateTenantBatch enqueues a CreateTenant query into batch to be executed
// later by the batch.
CreateTenantBatch(batch genericBatch, key string, name string)
// CreateTenantScan scans the result of an executed CreateTenantBatch query.
CreateTenantScan(results pgx.BatchResults) (CreateTenantRow, error)
FindOrdersByCustomer(ctx context.Context, customerID int32) ([]FindOrdersByCustomerRow, error)
// FindOrdersByCustomerBatch enqueues a FindOrdersByCustomer query into batch to be executed
// later by the batch.
FindOrdersByCustomerBatch(batch genericBatch, customerID int32)
// FindOrdersByCustomerScan scans the result of an executed FindOrdersByCustomerBatch query.
FindOrdersByCustomerScan(results pgx.BatchResults) ([]FindOrdersByCustomerRow, error)
FindProductsInOrder(ctx context.Context, orderID int32) ([]FindProductsInOrderRow, error)
// FindProductsInOrderBatch enqueues a FindProductsInOrder query into batch to be executed
// later by the batch.
FindProductsInOrderBatch(batch genericBatch, orderID int32)
// FindProductsInOrderScan scans the result of an executed FindProductsInOrderBatch query.
FindProductsInOrderScan(results pgx.BatchResults) ([]FindProductsInOrderRow, error)
InsertCustomer(ctx context.Context, params InsertCustomerParams) (InsertCustomerRow, error)
// InsertCustomerBatch enqueues a InsertCustomer query into batch to be executed
// later by the batch.
InsertCustomerBatch(batch genericBatch, params InsertCustomerParams)
// InsertCustomerScan scans the result of an executed InsertCustomerBatch query.
InsertCustomerScan(results pgx.BatchResults) (InsertCustomerRow, error)
InsertOrder(ctx context.Context, params InsertOrderParams) (InsertOrderRow, error)
// InsertOrderBatch enqueues a InsertOrder query into batch to be executed
// later by the batch.
InsertOrderBatch(batch genericBatch, params InsertOrderParams)
// InsertOrderScan scans the result of an executed InsertOrderBatch query.
InsertOrderScan(results pgx.BatchResults) (InsertOrderRow, error)
FindOrdersByPrice(ctx context.Context, minTotal pgtype.Numeric) ([]FindOrdersByPriceRow, error)
// FindOrdersByPriceBatch enqueues a FindOrdersByPrice query into batch to be executed
// later by the batch.
FindOrdersByPriceBatch(batch genericBatch, minTotal pgtype.Numeric)
// FindOrdersByPriceScan scans the result of an executed FindOrdersByPriceBatch query.
FindOrdersByPriceScan(results pgx.BatchResults) ([]FindOrdersByPriceRow, error)
FindOrdersMRR(ctx context.Context) ([]FindOrdersMRRRow, error)
// FindOrdersMRRBatch enqueues a FindOrdersMRR query into batch to be executed
// later by the batch.
FindOrdersMRRBatch(batch genericBatch)
// FindOrdersMRRScan scans the result of an executed FindOrdersMRRBatch query.
FindOrdersMRRScan(results pgx.BatchResults) ([]FindOrdersMRRRow, error)
}
type DBQuerier struct {
conn genericConn // underlying Postgres transport to use
types *typeResolver // resolve types by name
}
var _ Querier = &DBQuerier{}
// genericConn is a connection to a Postgres database. This is usually backed by
// *pgx.Conn, pgx.Tx, or *pgxpool.Pool.
type genericConn interface {
// Query executes sql with args. If there is an error the returned Rows will
// be returned in an error state. So it is allowed to ignore the error
// returned from Query and handle it in Rows.
Query(ctx context.Context, sql string, args ...interface{}) (pgx.Rows, error)
// QueryRow is a convenience wrapper over Query. Any error that occurs while
// querying is deferred until calling Scan on the returned Row. That Row will
// error with pgx.ErrNoRows if no rows are returned.
QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row
// Exec executes sql. sql can be either a prepared statement name or an SQL
// string. arguments should be referenced positionally from the sql string
// as $1, $2, etc.
Exec(ctx context.Context, sql string, arguments ...interface{}) (pgconn.CommandTag, error)
}
// genericBatch batches queries to send in a single network request to a
// Postgres server. This is usually backed by *pgx.Batch.
type genericBatch interface {
// Queue queues a query to batch b. query can be an SQL query or the name of a
// prepared statement. See Queue on *pgx.Batch.
Queue(query string, arguments ...interface{})
}
// NewQuerier creates a DBQuerier that implements Querier. conn is typically
// *pgx.Conn, pgx.Tx, or *pgxpool.Pool.
func NewQuerier(conn genericConn) *DBQuerier {
return NewQuerierConfig(conn, QuerierConfig{})
}
type QuerierConfig struct {
// DataTypes contains pgtype.Value to use for encoding and decoding instead
// of pggen-generated pgtype.ValueTranscoder.
//
// If OIDs are available for an input parameter type and all of its
// transitive dependencies, pggen will use the binary encoding format for
// the input parameter.
DataTypes []pgtype.DataType
}
// NewQuerierConfig creates a DBQuerier that implements Querier with the given
// config. conn is typically *pgx.Conn, pgx.Tx, or *pgxpool.Pool.
func NewQuerierConfig(conn genericConn, cfg QuerierConfig) *DBQuerier {
return &DBQuerier{conn: conn, types: newTypeResolver(cfg.DataTypes)}
}
// WithTx creates a new DBQuerier that uses the transaction to run all queries.
func (q *DBQuerier) WithTx(tx pgx.Tx) (*DBQuerier, error) {
return &DBQuerier{conn: tx}, nil
}
// preparer is any Postgres connection transport that provides a way to prepare
// a statement, most commonly *pgx.Conn.
type preparer interface {
Prepare(ctx context.Context, name, sql string) (sd *pgconn.StatementDescription, err error)
}
// PrepareAllQueries executes a PREPARE statement for all pggen generated SQL
// queries in querier files. Typical usage is as the AfterConnect callback
// for pgxpool.Config
//
// pgx will use the prepared statement if available. Calling PrepareAllQueries
// is an optional optimization to avoid a network round-trip the first time pgx
// runs a query if pgx statement caching is enabled.
func PrepareAllQueries(ctx context.Context, p preparer) error {
if _, err := p.Prepare(ctx, createTenantSQL, createTenantSQL); err != nil {
return fmt.Errorf("prepare query 'CreateTenant': %w", err)
}
if _, err := p.Prepare(ctx, findOrdersByCustomerSQL, findOrdersByCustomerSQL); err != nil {
return fmt.Errorf("prepare query 'FindOrdersByCustomer': %w", err)
}
if _, err := p.Prepare(ctx, findProductsInOrderSQL, findProductsInOrderSQL); err != nil {
return fmt.Errorf("prepare query 'FindProductsInOrder': %w", err)
}
if _, err := p.Prepare(ctx, insertCustomerSQL, insertCustomerSQL); err != nil {
return fmt.Errorf("prepare query 'InsertCustomer': %w", err)
}
if _, err := p.Prepare(ctx, insertOrderSQL, insertOrderSQL); err != nil {
return fmt.Errorf("prepare query 'InsertOrder': %w", err)
}
if _, err := p.Prepare(ctx, findOrdersByPriceSQL, findOrdersByPriceSQL); err != nil {
return fmt.Errorf("prepare query 'FindOrdersByPrice': %w", err)
}
if _, err := p.Prepare(ctx, findOrdersMRRSQL, findOrdersMRRSQL); err != nil {
return fmt.Errorf("prepare query 'FindOrdersMRR': %w", err)
}
return nil
}
// typeResolver looks up the pgtype.ValueTranscoder by Postgres type name.
type typeResolver struct {
connInfo *pgtype.ConnInfo // types by Postgres type name
}
func newTypeResolver(types []pgtype.DataType) *typeResolver {
ci := pgtype.NewConnInfo()
for _, typ := range types {
if txt, ok := typ.Value.(textPreferrer); ok && typ.OID != unknownOID {
typ.Value = txt.ValueTranscoder
}
ci.RegisterDataType(typ)
}
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
}
const createTenantSQL = `INSERT INTO tenant (tenant_id, name)
VALUES (base36_decode($1::text)::tenant_id, $2::text)
RETURNING *;`
type CreateTenantRow struct {
TenantID int `json:"tenant_id"`
Rname *string `json:"rname"`
Name string `json:"name"`
}
// CreateTenant implements Querier.CreateTenant.
func (q *DBQuerier) CreateTenant(ctx context.Context, key string, name string) (CreateTenantRow, error) {
ctx = context.WithValue(ctx, "pggen_query_name", "CreateTenant")
row := q.conn.QueryRow(ctx, createTenantSQL, key, name)
var item CreateTenantRow
if err := row.Scan(&item.TenantID, &item.Rname, &item.Name); err != nil {
return item, fmt.Errorf("query CreateTenant: %w", err)
}
return item, nil
}
// CreateTenantBatch implements Querier.CreateTenantBatch.
func (q *DBQuerier) CreateTenantBatch(batch genericBatch, key string, name string) {
batch.Queue(createTenantSQL, key, name)
}
// CreateTenantScan implements Querier.CreateTenantScan.
func (q *DBQuerier) CreateTenantScan(results pgx.BatchResults) (CreateTenantRow, error) {
row := results.QueryRow()
var item CreateTenantRow
if err := row.Scan(&item.TenantID, &item.Rname, &item.Name); err != nil {
return item, fmt.Errorf("scan CreateTenantBatch row: %w", err)
}
return item, nil
}
const findOrdersByCustomerSQL = `SELECT *
FROM orders
WHERE customer_id = $1;`
type FindOrdersByCustomerRow struct {
OrderID int32 `json:"order_id"`
OrderDate pgtype.Timestamptz `json:"order_date"`
OrderTotal pgtype.Numeric `json:"order_total"`
CustomerID *int32 `json:"customer_id"`
}
// FindOrdersByCustomer implements Querier.FindOrdersByCustomer.
func (q *DBQuerier) FindOrdersByCustomer(ctx context.Context, customerID int32) ([]FindOrdersByCustomerRow, error) {
ctx = context.WithValue(ctx, "pggen_query_name", "FindOrdersByCustomer")
rows, err := q.conn.Query(ctx, findOrdersByCustomerSQL, customerID)
if err != nil {
return nil, fmt.Errorf("query FindOrdersByCustomer: %w", err)
}
defer rows.Close()
items := []FindOrdersByCustomerRow{}
for rows.Next() {
var item FindOrdersByCustomerRow
if err := rows.Scan(&item.OrderID, &item.OrderDate, &item.OrderTotal, &item.CustomerID); err != nil {
return nil, fmt.Errorf("scan FindOrdersByCustomer row: %w", err)
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("close FindOrdersByCustomer rows: %w", err)
}
return items, err
}
// FindOrdersByCustomerBatch implements Querier.FindOrdersByCustomerBatch.
func (q *DBQuerier) FindOrdersByCustomerBatch(batch genericBatch, customerID int32) {
batch.Queue(findOrdersByCustomerSQL, customerID)
}
// FindOrdersByCustomerScan implements Querier.FindOrdersByCustomerScan.
func (q *DBQuerier) FindOrdersByCustomerScan(results pgx.BatchResults) ([]FindOrdersByCustomerRow, error) {
rows, err := results.Query()
if err != nil {
return nil, fmt.Errorf("query FindOrdersByCustomerBatch: %w", err)
}
defer rows.Close()
items := []FindOrdersByCustomerRow{}
for rows.Next() {
var item FindOrdersByCustomerRow
if err := rows.Scan(&item.OrderID, &item.OrderDate, &item.OrderTotal, &item.CustomerID); err != nil {
return nil, fmt.Errorf("scan FindOrdersByCustomerBatch row: %w", err)
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("close FindOrdersByCustomerBatch rows: %w", err)
}
return items, err
}
const findProductsInOrderSQL = `SELECT o.order_id, p.product_id, p.name
FROM orders o
INNER JOIN order_product op USING (order_id)
INNER JOIN product p USING (product_id)
WHERE o.order_id = $1;`
type FindProductsInOrderRow struct {
OrderID *int32 `json:"order_id"`
ProductID *int32 `json:"product_id"`
Name *string `json:"name"`
}
// FindProductsInOrder implements Querier.FindProductsInOrder.
func (q *DBQuerier) FindProductsInOrder(ctx context.Context, orderID int32) ([]FindProductsInOrderRow, error) {
ctx = context.WithValue(ctx, "pggen_query_name", "FindProductsInOrder")
rows, err := q.conn.Query(ctx, findProductsInOrderSQL, orderID)
if err != nil {
return nil, fmt.Errorf("query FindProductsInOrder: %w", err)
}
defer rows.Close()
items := []FindProductsInOrderRow{}
for rows.Next() {
var item FindProductsInOrderRow
if err := rows.Scan(&item.OrderID, &item.ProductID, &item.Name); err != nil {
return nil, fmt.Errorf("scan FindProductsInOrder row: %w", err)
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("close FindProductsInOrder rows: %w", err)
}
return items, err
}
// FindProductsInOrderBatch implements Querier.FindProductsInOrderBatch.
func (q *DBQuerier) FindProductsInOrderBatch(batch genericBatch, orderID int32) {
batch.Queue(findProductsInOrderSQL, orderID)
}
// FindProductsInOrderScan implements Querier.FindProductsInOrderScan.
func (q *DBQuerier) FindProductsInOrderScan(results pgx.BatchResults) ([]FindProductsInOrderRow, error) {
rows, err := results.Query()
if err != nil {
return nil, fmt.Errorf("query FindProductsInOrderBatch: %w", err)
}
defer rows.Close()
items := []FindProductsInOrderRow{}
for rows.Next() {
var item FindProductsInOrderRow
if err := rows.Scan(&item.OrderID, &item.ProductID, &item.Name); err != nil {
return nil, fmt.Errorf("scan FindProductsInOrderBatch row: %w", err)
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("close FindProductsInOrderBatch rows: %w", err)
}
return items, err
}
const insertCustomerSQL = `INSERT INTO customer (first_name, last_name, email)
VALUES ($1, $2, $3)
RETURNING *;`
type InsertCustomerParams struct {
FirstName string
LastName string
Email string
}
type InsertCustomerRow struct {
CustomerID int32 `json:"customer_id"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Email string `json:"email"`
}
// InsertCustomer implements Querier.InsertCustomer.
func (q *DBQuerier) InsertCustomer(ctx context.Context, params InsertCustomerParams) (InsertCustomerRow, error) {
ctx = context.WithValue(ctx, "pggen_query_name", "InsertCustomer")
row := q.conn.QueryRow(ctx, insertCustomerSQL, params.FirstName, params.LastName, params.Email)
var item InsertCustomerRow
if err := row.Scan(&item.CustomerID, &item.FirstName, &item.LastName, &item.Email); err != nil {
return item, fmt.Errorf("query InsertCustomer: %w", err)
}
return item, nil
}
// InsertCustomerBatch implements Querier.InsertCustomerBatch.
func (q *DBQuerier) InsertCustomerBatch(batch genericBatch, params InsertCustomerParams) {
batch.Queue(insertCustomerSQL, params.FirstName, params.LastName, params.Email)
}
// InsertCustomerScan implements Querier.InsertCustomerScan.
func (q *DBQuerier) InsertCustomerScan(results pgx.BatchResults) (InsertCustomerRow, error) {
row := results.QueryRow()
var item InsertCustomerRow
if err := row.Scan(&item.CustomerID, &item.FirstName, &item.LastName, &item.Email); err != nil {
return item, fmt.Errorf("scan InsertCustomerBatch row: %w", err)
}
return item, nil
}
const insertOrderSQL = `INSERT INTO orders (order_date, order_total, customer_id)
VALUES ($1, $2, $3)
RETURNING *;`
type InsertOrderParams struct {
OrderDate pgtype.Timestamptz
OrderTotal pgtype.Numeric
CustID int32
}
type InsertOrderRow struct {
OrderID int32 `json:"order_id"`
OrderDate pgtype.Timestamptz `json:"order_date"`
OrderTotal pgtype.Numeric `json:"order_total"`
CustomerID *int32 `json:"customer_id"`
}
// InsertOrder implements Querier.InsertOrder.
func (q *DBQuerier) InsertOrder(ctx context.Context, params InsertOrderParams) (InsertOrderRow, error) {
ctx = context.WithValue(ctx, "pggen_query_name", "InsertOrder")
row := q.conn.QueryRow(ctx, insertOrderSQL, params.OrderDate, params.OrderTotal, params.CustID)
var item InsertOrderRow
if err := row.Scan(&item.OrderID, &item.OrderDate, &item.OrderTotal, &item.CustomerID); err != nil {
return item, fmt.Errorf("query InsertOrder: %w", err)
}
return item, nil
}
// InsertOrderBatch implements Querier.InsertOrderBatch.
func (q *DBQuerier) InsertOrderBatch(batch genericBatch, params InsertOrderParams) {
batch.Queue(insertOrderSQL, params.OrderDate, params.OrderTotal, params.CustID)
}
// InsertOrderScan implements Querier.InsertOrderScan.
func (q *DBQuerier) InsertOrderScan(results pgx.BatchResults) (InsertOrderRow, error) {
row := results.QueryRow()
var item InsertOrderRow
if err := row.Scan(&item.OrderID, &item.OrderDate, &item.OrderTotal, &item.CustomerID); err != nil {
return item, fmt.Errorf("scan InsertOrderBatch row: %w", err)
}
return item, nil
}
// 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 if the results from QueryAllDataTypes aren't passed to
// NewQuerierConfig.
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{pgtype.NewValue(t.ValueTranscoder).(pgtype.ValueTranscoder), 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