-
Notifications
You must be signed in to change notification settings - Fork 4
/
querier.go
363 lines (303 loc) · 8.1 KB
/
querier.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
package pgkit
import (
"bytes"
"context"
"fmt"
"strings"
sq "github.com/Masterminds/squirrel"
"github.com/georgysavva/scany/v2/pgxscan"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
)
type Querier struct {
pool *pgxpool.Pool
tx pgx.Tx
Scan *pgxscan.API
SQL *StatementBuilder
}
func (q *Querier) Exec(ctx context.Context, query Sqlizer) (pgconn.CommandTag, error) {
// check for query errors
if getErr, ok := query.(hasErr); ok && getErr.Err() != nil {
return pgconn.CommandTag{}, wrapErr(getErr.Err())
}
sql, args, err := query.ToSql()
if err != nil {
return pgconn.CommandTag{}, wrapErr(err)
}
var tag pgconn.CommandTag
if q.tx != nil {
tag, err = q.tx.Exec(ctx, sql, args...)
} else {
tag, err = q.pool.Exec(ctx, sql, args...)
}
if err != nil {
return pgconn.CommandTag{}, wrapErr(err)
}
return tag, nil
}
func (q *Querier) QueryRows(ctx context.Context, query Sqlizer) (pgx.Rows, error) {
// check for query errors
if getErr, ok := query.(hasErr); ok && getErr.Err() != nil {
return nil, wrapErr(getErr.Err())
}
sql, args, err := query.ToSql()
if err != nil {
return nil, wrapErr(err)
}
var rows pgx.Rows
if q.tx != nil {
rows, err = q.tx.Query(ctx, sql, args...)
} else {
rows, err = q.pool.Query(ctx, sql, args...)
}
if err != nil {
return nil, wrapErr(err)
}
return rows, nil
}
func (q *Querier) QueryRow(ctx context.Context, query Sqlizer) pgx.Row {
// check for query errors
if getErr, ok := query.(hasErr); ok && getErr.Err() != nil {
return errRow{wrapErr(getErr.Err())}
}
sql, args, err := query.ToSql()
if err != nil {
return errRow{wrapErr(err)}
}
if q.tx != nil {
return q.tx.QueryRow(ctx, sql, args...)
} else {
return q.pool.QueryRow(ctx, sql, args...)
}
}
func (q *Querier) GetAll(ctx context.Context, query Sqlizer, dest interface{}) error {
rows, err := q.QueryRows(ctx, query)
if err != nil {
return wrapErr(err)
}
return wrapErr(q.Scan.ScanAll(dest, rows))
}
func (q *Querier) GetOne(ctx context.Context, query Sqlizer, dest interface{}) error {
switch builder := query.(type) {
case sq.SelectBuilder:
query = builder.Limit(1)
case sq.DeleteBuilder:
query = builder.Limit(1)
}
rows, err := q.QueryRows(ctx, query)
if err != nil {
return wrapErr(err)
}
return wrapErr(q.Scan.ScanOne(dest, rows))
}
func (q *Querier) BatchExec(ctx context.Context, queries Queries) ([]pgconn.CommandTag, error) {
if len(queries) == 0 {
return nil, wrapErr(fmt.Errorf("empty query"))
}
// check for query errors
for _, query := range queries {
if getErr, ok := query.(hasErr); ok && getErr.Err() != nil {
return nil, wrapErr(getErr.Err())
}
}
// Prepare queries
batch := &pgx.Batch{}
for _, query := range queries {
sql, args, err := query.ToSql()
if err != nil {
return nil, wrapErr(err)
}
batch.Queue(sql, args...)
}
// Send batch
var results pgx.BatchResults
if q.tx != nil {
results = q.tx.SendBatch(ctx, batch)
} else {
results = q.pool.SendBatch(ctx, batch)
}
defer results.Close()
// Exec the number of times as we have queries in the batch so we may get the exec
// result and potential error response.
tags := make([]pgconn.CommandTag, 0, batch.Len())
for i := 0; i < batch.Len(); i++ {
tag, err := results.Exec()
if err != nil {
return tags, wrapErr(err)
}
tags = append(tags, tag)
}
return tags, nil
}
func (q *Querier) BatchQuery(ctx context.Context, queries Queries) (pgx.BatchResults, int, error) {
if len(queries) == 0 {
return nil, 0, wrapErr(fmt.Errorf("empty query"))
}
// check for query errors
for _, query := range queries {
if getErr, ok := query.(hasErr); ok && getErr.Err() != nil {
return nil, 0, wrapErr(getErr.Err())
}
}
// Prepare queries
batch := &pgx.Batch{}
for _, query := range queries {
sql, args, err := query.ToSql()
if err != nil {
return nil, 0, wrapErr(err)
}
batch.Queue(sql, args...)
}
// Send batch
var batchResults pgx.BatchResults
if q.tx != nil {
batchResults = q.tx.SendBatch(ctx, batch)
} else {
batchResults = q.pool.SendBatch(ctx, batch)
}
// defer results.Close()
// NOTE: the caller of BatchQuery must close the `batchResults` themselves.
return batchResults, batch.Len(), nil
}
// NOTE: WIP/experimentation to offer sugar to scan a batch of the same kinds of queries.
// func (q *Querier) BatchGetAll(ctx context.Context, queries Queries, dest interface{}) error {
// batchResults, batchLen, err := q.BatchQuery(ctx, queries)
// if err != nil {
// return wrapErr(err)
// }
// defer batchResults.Close()
// // for i, rows := range batchRows {
// // err := q.scan.ScanAll(dest[i], rows)
// // if err != nil {
// // return wrapErr(err)
// // }
// // }
// for i := 0; i < batchLen; i++ {
// rows, err := batchResults.Query()
// if err != nil {
// return wrapErr(err)
// }
// err = q.scan.ScanAll(dest, rows)
// if err != nil {
// return wrapErr(err)
// }
// }
// return nil
// }
type Sqlizer interface {
// ToSql converts a runtime builder structure to an executable SQL query, returns:
// query string, query values, and optional error
ToSql() (string, []interface{}, error)
}
type Query Sqlizer
type Queries []Query
func (q *Queries) Add(query Sqlizer) {
*q = append(*q, query)
}
func (q Queries) Len() int {
return len(q)
}
// RawSQL allows you to build queries by hand easily. Note, it will auto-replace `?“ placeholders
// to postgres $X format. As well, if you run the same query over and over, consider to use
// `RawQuery(..)` instead, as it's a cached version of RawSQL.
type RawSQL struct {
Query string
Args []interface{}
statement bool
err error
}
func (r RawSQL) Prepare(query string) (string, int, error) {
if query == "" {
return "", 0, fmt.Errorf("pgkit: empty query")
}
n := strings.Count(query, "?")
if !r.statement && n != len(r.Args) {
return "", 0, fmt.Errorf("pgkit: expecting %d args but received %d", n, len(r.Args))
}
parts := strings.Split(query, "?")
q := bytes.Buffer{}
for i, p := range parts {
if p == "" {
continue
}
q.WriteString(p)
if i < n {
q.WriteString(fmt.Sprintf("$%d", i+1))
}
}
return q.String(), n, nil
}
func (r RawSQL) Err() error {
return r.err
}
func (r RawSQL) ToSql() (string, []interface{}, error) {
if r.Query == "" {
return "", nil, fmt.Errorf("pgkit: empty query called with ToSql")
}
if r.err != nil {
// error may have occured somewhere when building the query
return "", nil, r.err
}
if r.statement {
// for statement queries, we assume its prepared correctly by RawStatement
return r.Query, r.Args, nil
}
if r.Args == nil || len(r.Args) == 0 {
return r.Query, r.Args, nil // assume no params passed
}
q, _, err := r.Prepare(r.Query)
if err != nil {
return "", nil, err
}
// NOTE: below doesnt appear to be necessary, the driver below will do it
// args := make([]interface{}, len(r.Args))
// for i, arg := range r.Args {
// v, ok := arg.(driver.Valuer)
// if ok {
// args[i] = v
// } else {
// args[i] = arg
// }
// }
return q, r.Args, nil
}
// RawStatement allows you to build query statements by hand, where the query will remain the same
// but the arguments can change. The number of arguments must always be the same.
type RawStatement struct {
query RawSQL
numArgs int
err error
}
func (r RawStatement) Err() error {
return r.err
}
func (r RawStatement) GetQuery() string {
return r.query.Query
}
func (r RawStatement) NumArgs() int {
return r.numArgs
}
func (r RawStatement) Build(args ...interface{}) Sqlizer {
if len(args) != r.numArgs {
return RawSQL{err: fmt.Errorf("pgkit: invalid arguments passed to statement, expecting %d args but received %d", r.numArgs, len(args))}
}
return RawSQL{Query: r.query.Query, Args: args, statement: true}
}
func RawQuery(query string) RawStatement {
rs := RawStatement{}
rq := RawSQL{Query: query, statement: true}
q, n, err := rq.Prepare(query)
if err != nil {
rs.query = rq
rs.err = err
return rs
}
rq.Query = q
rs.query = rq
rs.numArgs = n
return rs
}
func RawQueryf(queryFormat string, a ...interface{}) RawStatement {
return RawQuery(fmt.Sprintf(queryFormat, a...))
}