-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathpgxutil.go
902 lines (763 loc) · 29.2 KB
/
pgxutil.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
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
package pgxutil
import (
"context"
"errors"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
var errNotFound = errors.New("no rows in result set")
var errNoColumns = errors.New("no columns in result set")
var errMultipleColumns = errors.New("multiple columns in result set")
var errMultipleRows = errors.New("multiple rows in result set")
var errTooManyRows = fmt.Errorf("too many rows")
type Queryer interface {
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
}
type Execer interface {
Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
}
// DB is the interface pgxutil uses to access the database. It is satisfied by *pgx.Conn, pgx.Tx, *pgxpool.Pool, etc.
type DB interface {
// Begin starts a new pgx.Tx. It may be a true transaction or a pseudo nested transaction implemented by savepoints.
Begin(ctx context.Context) (pgx.Tx, error)
CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error)
Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error)
Query(ctx context.Context, sql string, optionsAndArgs ...interface{}) (pgx.Rows, error)
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
SendBatch(ctx context.Context, b *pgx.Batch) (br pgx.BatchResults)
}
// SQLValue is a SQL expression intended for use where a value would normally be expected. It is not escaped or sanitized.
type SQLValue string
// Select executes sql with args on db and returns the []T produced by scanFn.
func Select[T any](ctx context.Context, db Queryer, sql string, args []any, scanFn pgx.RowToFunc[T]) ([]T, error) {
rows, _ := db.Query(ctx, sql, args...)
collectedRows, err := pgx.CollectRows(rows, scanFn)
if err != nil {
return nil, err
}
return collectedRows, nil
}
// QueueSelect queues sql with args into batch. scanFn will be used to populate result when the response to this query
// is received.
func QueueSelect[T any](batch *pgx.Batch, sql string, args []any, scanFn pgx.RowToFunc[T], result *[]T) {
batch.Queue(sql, args...).Query(func(rows pgx.Rows) error {
collectedRows, err := pgx.CollectRows(rows, scanFn)
if err != nil {
return err
}
*result = collectedRows
return nil
})
}
// SelectRow executes sql with args on db and returns the T produced by scanFn. The query should return one row. If no
// rows are found returns an error where errors.Is(pgx.ErrNoRows) is true. Returns an error if more than one row is
// returned.
func SelectRow[T any](ctx context.Context, db Queryer, sql string, args []any, scanFn pgx.RowToFunc[T]) (T, error) {
rows, _ := db.Query(ctx, sql, args...)
collectedRow, err := pgx.CollectOneRow(rows, scanFn)
if err != nil {
var zero T
return zero, err
}
if rows.CommandTag().RowsAffected() > 1 {
return collectedRow, errTooManyRows
}
return collectedRow, nil
}
// QueueSelectRow queues sql with args into batch. scanFn will be used to populate result when the response to this query
// is received.
func QueueSelectRow[T any](batch *pgx.Batch, sql string, args []any, scanFn pgx.RowToFunc[T], result *T) {
batch.Queue(sql, args...).Query(func(rows pgx.Rows) error {
collectedRow, err := pgx.CollectOneRow(rows, scanFn)
if err != nil {
return err
}
if rows.CommandTag().RowsAffected() > 1 {
return errTooManyRows
}
*result = collectedRow
return nil
})
}
// Insert inserts rows into tableName. tableName must be a string or pgx.Identifier. rows can include SQLValue to use a
// raw SQL expression as a value.
func Insert(ctx context.Context, db Queryer, tableName any, rows []map[string]any) (pgconn.CommandTag, error) {
if len(rows) == 0 {
return pgconn.CommandTag{}, nil
}
tableIdent, err := makePgxIdentifier(tableName)
if err != nil {
return pgconn.CommandTag{}, fmt.Errorf("Insert invalid tableName: %w", err)
}
sql, args := insertSQL(tableIdent, rows, "")
return exec(ctx, db, sql, args)
}
// QueueInsert queues the insert of rows into tableName. tableName must be a string or pgx.Identifier. rows can include SQLValue to use a
// raw SQL expression as a value.
func QueueInsert(batch *pgx.Batch, tableName any, rows []map[string]any) {
if len(rows) == 0 {
// Since nothing is queued, the number of queries in the batch may be lower than expected. Not sure if anything can
// or should be done about this.
return
}
tableIdent, err := makePgxIdentifier(tableName)
if err != nil {
// Panicking is undesirable, but we don't want to have this function return an error or silently ignore the error.
// Possibly pgx.Batch should be modified to allow queueing an error.
panic(fmt.Sprintf("QueueInsert invalid tableName: %v", err))
}
sql, args := insertSQL(tableIdent, rows, "")
batch.Queue(sql, args...)
}
// InsertReturning inserts rows into tableName with returningClause and returns the []T produced by scanFn. tableName
// must be a string or pgx.Identifier. rows can include SQLValue to use a raw SQL expression as a value.
func InsertReturning[T any](ctx context.Context, db Queryer, tableName any, rows []map[string]any, returningClause string, scanFn pgx.RowToFunc[T]) ([]T, error) {
if len(rows) == 0 {
return nil, nil
}
tableIdent, err := makePgxIdentifier(tableName)
if err != nil {
return nil, fmt.Errorf("InsertReturning invalid tableName: %w", err)
}
sql, args := insertSQL(tableIdent, rows, returningClause)
return Select(ctx, db, sql, args, scanFn)
}
// QueueInsertReturning queues the insert of rows into tableName with returningClause. tableName must be a string or
// pgx.Identifier. rows can include SQLValue to use a raw SQL expression as a value. scanFn will be used to populate
// result when the response to this query is received.
func QueueInsertReturning[T any](batch *pgx.Batch, tableName any, rows []map[string]any, returningClause string, scanFn pgx.RowToFunc[T], result *[]T) {
if len(rows) == 0 {
// Since nothing is queued, the number of queries in the batch may be lower than expected. Not sure if anything can
// or should be done about this.
return
}
tableIdent, err := makePgxIdentifier(tableName)
if err != nil {
// Panicking is undesirable, but we don't want to have this function return an error or silently ignore the error.
// Possibly pgx.Batch should be modified to allow queueing an error.
panic(fmt.Sprintf("QueueInsertReturning invalid tableName: %v", err))
}
sql, args := insertSQL(tableIdent, rows, returningClause)
QueueSelect(batch, sql, args, scanFn, result)
}
// insertSQL builds an insert statement that inserts rows into tableName with returningClause. len(rows) must be > 0.
func insertSQL(tableName pgx.Identifier, rows []map[string]any, returningClause string) (sql string, args []any) {
b := &strings.Builder{}
b.WriteString("insert into ")
if len(tableName) == 1 {
b.WriteString(sanitizeIdentifier(tableName[0]))
} else {
b.WriteString(tableName.Sanitize())
}
b.WriteString(" (")
// Go maps are iterated in random order. The generated SQL should be stable so sort the keys.
keys := make([]string, 0, len(rows[0]))
for k := range rows[0] {
keys = append(keys, k)
}
sort.Strings(keys)
for i, k := range keys {
if i > 0 {
b.WriteString(", ")
}
sanitizedKey := sanitizeIdentifier(k)
b.WriteString(sanitizedKey)
}
args = make([]any, 0, len(keys))
for i, values := range rows {
if i == 0 {
b.WriteString(") values (")
} else {
b.WriteString("), (")
}
for j, key := range keys {
if j > 0 {
b.WriteString(", ")
}
if SQLValue, ok := values[key].(SQLValue); ok {
b.WriteString(string(SQLValue))
} else {
args = append(args, values[key])
b.WriteByte('$')
b.WriteString(strconv.FormatInt(int64(len(args)), 10))
}
}
}
b.WriteString(")")
if returningClause != "" {
b.WriteString(" returning ")
b.WriteString(returningClause)
}
return b.String(), args
}
// InsertRow inserts values into tableName. tableName must be a string or pgx.Identifier. values can include SQLValue to
// use a raw SQL expression as a value.
func InsertRow(ctx context.Context, db Queryer, tableName any, values map[string]any) error {
tableIdent, err := makePgxIdentifier(tableName)
if err != nil {
return fmt.Errorf("InsertRow invalid tableName: %w", err)
}
sql, args := insertRowSQL(tableIdent, values, "")
_, err = exec(ctx, db, sql, args)
return err
}
// QueueInsertRow queues the insert of values into tableName. tableName must be a string or pgx.Identifier. values can include SQLValue to
// use a raw SQL expression as a value.
func QueueInsertRow(batch *pgx.Batch, tableName any, values map[string]any) {
tableIdent, err := makePgxIdentifier(tableName)
if err != nil {
// Panicking is undesirable, but we don't want to have this function return an error or silently ignore the error.
// Possibly pgx.Batch should be modified to allow queueing an error.
panic(fmt.Sprintf("QueueInsertRow invalid tableName: %v", err))
}
sql, args := insertRowSQL(tableIdent, values, "")
batch.Queue(sql, args...)
}
// InsertRowReturning inserts values into tableName with returningClause and returns the T produced by scanFn. tableName
// must be a string or pgx.Identifier. values can include SQLValue to use a raw SQL expression as a value.
func InsertRowReturning[T any](ctx context.Context, db Queryer, tableName any, values map[string]any, returningClause string, scanFn pgx.RowToFunc[T]) (T, error) {
tableIdent, err := makePgxIdentifier(tableName)
if err != nil {
var zero T
return zero, fmt.Errorf("InsertRowReturning invalid tableName: %w", err)
}
sql, args := insertRowSQL(tableIdent, values, returningClause)
return SelectRow(ctx, db, sql, args, scanFn)
}
// QueueInsertRowReturning queues the insert of values into tableName with returningClause. tableName must be a string
// or pgx.Identifier. values can include SQLValue to use a raw SQL expression as a value. scanFn will be used to
// populate result when the response to this query is received.
func QueueInsertRowReturning[T any](batch *pgx.Batch, tableName any, values map[string]any, returningClause string, scanFn pgx.RowToFunc[T], result *T) {
tableIdent, err := makePgxIdentifier(tableName)
if err != nil {
// Panicking is undesirable, but we don't want to have this function return an error or silently ignore the error.
// Possibly pgx.Batch should be modified to allow queueing an error.
panic(fmt.Sprintf("QueueInsertRowReturning invalid tableName: %v", err))
}
sql, args := insertRowSQL(tableIdent, values, returningClause)
QueueSelectRow(batch, sql, args, scanFn, result)
}
func sanitizeIdentifier(s string) string {
return pgx.Identifier{s}.Sanitize()
}
func insertRowSQL(tableName pgx.Identifier, values map[string]any, returningClause string) (sql string, args []any) {
b := &strings.Builder{}
b.WriteString("insert into ")
if len(tableName) == 1 {
b.WriteString(sanitizeIdentifier(tableName[0]))
} else {
b.WriteString(tableName.Sanitize())
}
b.WriteString(" (")
// Go maps are iterated in random order. The generated SQL should be stable so sort the keys.
keys := make([]string, 0, len(values))
for k := range values {
keys = append(keys, k)
}
sort.Strings(keys)
for i, k := range keys {
if i > 0 {
b.WriteString(", ")
}
sanitizedKey := sanitizeIdentifier(k)
b.WriteString(sanitizedKey)
}
b.WriteString(") values (")
args = make([]any, 0, len(keys))
for _, k := range keys {
if len(args) > 0 {
b.WriteString(", ")
}
if SQLValue, ok := values[k].(SQLValue); ok {
b.WriteString(string(SQLValue))
} else {
args = append(args, values[k])
b.WriteByte('$')
b.WriteString(strconv.FormatInt(int64(len(args)), 10))
}
}
b.WriteString(")")
if returningClause != "" {
b.WriteString(" returning ")
b.WriteString(returningClause)
}
return b.String(), args
}
// ExecRow executes SQL with args on db. It returns an error unless exactly one row is affected.
func ExecRow(ctx context.Context, db Queryer, sql string, args ...any) (pgconn.CommandTag, error) {
ct, err := exec(ctx, db, sql, args)
if err != nil {
return ct, err
}
rowsAffected := ct.RowsAffected()
if rowsAffected == 0 {
return ct, pgx.ErrNoRows
} else if rowsAffected > 1 {
return ct, errTooManyRows
}
return ct, nil
}
// QueueExecRow queues sql with args. The response is considered an error unless exactly one row is affected.
func QueueExecRow(batch *pgx.Batch, sql string, args ...any) {
batch.Queue(sql, args...).Exec(func(ct pgconn.CommandTag) error {
rowsAffected := ct.RowsAffected()
if rowsAffected == 0 {
return pgx.ErrNoRows
} else if rowsAffected > 1 {
return errTooManyRows
}
return nil
})
}
// Update updates rows matching whereValues in tableName with setValues. tableName must be a string or pgx.Identifier.
// setValues and whereValues can include SQLValue to use a raw SQL expression as a value.
func Update(ctx context.Context, db Queryer, tableName any, setValues, whereValues map[string]any) (pgconn.CommandTag, error) {
tableIdent, err := makePgxIdentifier(tableName)
if err != nil {
return pgconn.CommandTag{}, fmt.Errorf("Update invalid tableName: %w", err)
}
sql, args := updateSQL(tableIdent, setValues, whereValues, "")
return exec(ctx, db, sql, args)
}
// QueueUpdate queues the update of rows matching whereValues in tableName with setValues. tableName must be a string or
// pgx.Identifier. setValues and whereValues can include SQLValue to use a raw SQL expression as a value. commandTag
// will be populated when the response to this query is received. commandTag may be nil.
func QueueUpdate(batch *pgx.Batch, tableName any, setValues, whereValues map[string]any, commandTag *pgconn.CommandTag) {
tableIdent, err := makePgxIdentifier(tableName)
if err != nil {
// Panicking is undesirable, but we don't want to have this function return an error or silently ignore the error.
// Possibly pgx.Batch should be modified to allow queueing an error.
panic(fmt.Sprintf("QueueUpdate invalid tableName: %v", err))
}
sql, args := updateSQL(tableIdent, setValues, whereValues, "")
qq := batch.Queue(sql, args...)
if commandTag != nil {
qq.Exec(func(ct pgconn.CommandTag) error {
*commandTag = ct
return nil
})
}
}
// UpdateReturning updates rows matching whereValues in tableName with setValues. It includes returningClause and
// returns the []T produced by scanFn. tableName must be a string or pgx.Identifier. setValues and whereValues can
// include SQLValue to use a raw SQL expression as a value.
func UpdateReturning[T any](ctx context.Context, db Queryer, tableName any, setValues, whereValues map[string]any, returningClause string, scanFn pgx.RowToFunc[T]) ([]T, error) {
tableIdent, err := makePgxIdentifier(tableName)
if err != nil {
return nil, fmt.Errorf("UpdateReturning invalid tableName: %w", err)
}
sql, args := updateSQL(tableIdent, setValues, whereValues, returningClause)
return Select(ctx, db, sql, args, scanFn)
}
// QueueUpdateReturning queues the update of rows matching whereValues in tableName with setValues. tableName must be a
// string or pgx.Identifier. setValues and whereValues can include SQLValue to use a raw SQL expression as a value.
// scanFn will be used to populate the result when the response to this query is received.
func QueueUpdateReturning[T any](batch *pgx.Batch, tableName any, setValues, whereValues map[string]any, returningClause string, scanFn pgx.RowToFunc[T], result *[]T) {
tableIdent, err := makePgxIdentifier(tableName)
if err != nil {
// Panicking is undesirable, but we don't want to have this function return an error or silently ignore the error.
// Possibly pgx.Batch should be modified to allow queueing an error.
panic(fmt.Sprintf("QueueUpdateReturning invalid tableName: %v", err))
}
sql, args := updateSQL(tableIdent, setValues, whereValues, returningClause)
QueueSelect(batch, sql, args, scanFn, result)
}
// UpdateRow updates a row matching whereValues in tableName with setValues. Returns an error unless exactly one row is
// updated. tableName must be a string or pgx.Identifier. setValues and whereValues can include SQLValue to use a raw
// SQL expression as a value.
func UpdateRow(ctx context.Context, db Queryer, tableName any, setValues, whereValues map[string]any) error {
tableIdent, err := makePgxIdentifier(tableName)
if err != nil {
return fmt.Errorf("UpdateRow invalid tableName: %w", err)
}
sql, args := updateSQL(tableIdent, setValues, whereValues, "")
_, err = ExecRow(ctx, db, sql, args...)
return err
}
// QueueUpdateRow queues the update of a row matching whereValues in tableName with setValues. tableName must be a
// string or pgx.Identifier. setValues and whereValues can include SQLValue to use a raw SQL expression as a value. The
// response is considered an error unless exactly one row is affected.
func QueueUpdateRow(batch *pgx.Batch, tableName any, setValues, whereValues map[string]any) {
tableIdent, err := makePgxIdentifier(tableName)
if err != nil {
// Panicking is undesirable, but we don't want to have this function return an error or silently ignore the error.
// Possibly pgx.Batch should be modified to allow queueing an error.
panic(fmt.Sprintf("QueueUpdateRow invalid tableName: %v", err))
}
sql, args := updateSQL(tableIdent, setValues, whereValues, "")
QueueExecRow(batch, sql, args...)
}
// UpdateRowReturning updates a row matching whereValues in tableName with setValues. It includes returningClause and
// returns the T produced by scanFn. Returns an error unless exactly one row is updated. tableName must be a string or
// pgx.Identifier. setValues and whereValues can include SQLValue to use a raw SQL expression as a value.
func UpdateRowReturning[T any](ctx context.Context, db Queryer, tableName any, setValues, whereValues map[string]any, returningClause string, scanFn pgx.RowToFunc[T]) (T, error) {
tableIdent, err := makePgxIdentifier(tableName)
if err != nil {
var zero T
return zero, fmt.Errorf("UpdateRow invalid tableName: %w", err)
}
sql, args := updateSQL(tableIdent, setValues, whereValues, returningClause)
return SelectRow(ctx, db, sql, args, scanFn)
}
// QueueUpdateRowReturning queues the update of a row matching whereValues in tableName with setValues. tableName must
// be a string or pgx.Identifier. setValues and whereValues can include SQLValue to use a raw SQL expression as a value.
// scanFn will be used to populate the result when the response to this query is received. The response is considered an
// error unless exactly one row is affected.
func QueueUpdateRowReturning[T any](batch *pgx.Batch, tableName any, setValues, whereValues map[string]any, returningClause string, scanFn pgx.RowToFunc[T], result *T) {
tableIdent, err := makePgxIdentifier(tableName)
if err != nil {
// Panicking is undesirable, but we don't want to have this function return an error or silently ignore the error.
// Possibly pgx.Batch should be modified to allow queueing an error.
panic(fmt.Sprintf("QueueUpdateRowReturning invalid tableName: %v", err))
}
sql, args := updateSQL(tableIdent, setValues, whereValues, returningClause)
QueueSelectRow(batch, sql, args, scanFn, result)
}
func updateSQL(tableName pgx.Identifier, setValues, whereValues map[string]any, returningClause string) (sql string, args []any) {
b := &strings.Builder{}
b.WriteString("update ")
if len(tableName) == 1 {
b.WriteString(sanitizeIdentifier(tableName[0]))
} else {
b.WriteString(tableName.Sanitize())
}
b.WriteString(" set ")
args = make([]any, 0, len(setValues)+len(whereValues))
// Go maps are iterated in random order. The generated SQL should be stable so sort the setValueKeys.
setValueKeys := make([]string, 0, len(setValues))
for k := range setValues {
setValueKeys = append(setValueKeys, k)
}
sort.Strings(setValueKeys)
for i, k := range setValueKeys {
if i > 0 {
b.WriteString(", ")
}
sanitizedKey := sanitizeIdentifier(k)
b.WriteString(sanitizedKey)
if SQLValue, ok := setValues[k].(SQLValue); ok {
b.WriteString(" = ")
b.WriteString(string(SQLValue))
} else {
b.WriteString(" = $")
args = append(args, setValues[k])
b.WriteString(strconv.FormatInt(int64(len(args)), 10))
}
}
if len(whereValues) > 0 {
b.WriteString(" where ")
whereValueKeys := make([]string, 0, len(whereValues))
for k := range whereValues {
whereValueKeys = append(whereValueKeys, k)
}
sort.Strings(whereValueKeys)
for i, k := range whereValueKeys {
if i > 0 {
b.WriteString(" and ")
}
sanitizedKey := sanitizeIdentifier(k)
b.WriteString(sanitizedKey)
if SQLValue, ok := whereValues[k].(SQLValue); ok {
b.WriteString(" = ")
b.WriteString(string(SQLValue))
} else {
b.WriteString(" = $")
args = append(args, whereValues[k])
b.WriteString(strconv.FormatInt(int64(len(args)), 10))
}
}
}
if returningClause != "" {
b.WriteString(" returning ")
b.WriteString(returningClause)
}
return b.String(), args
}
// exec builds Exec-like functionality on top of DB. This allows pgxutil to have the convenience of Exec with needing
// it as part of the DB interface.
func exec(ctx context.Context, db Queryer, sql string, args []any) (pgconn.CommandTag, error) {
rows, err := db.Query(ctx, sql, args...)
if err != nil {
return pgconn.CommandTag{}, err
}
rows.Close()
return rows.CommandTag(), rows.Err()
}
func makePgxIdentifier(v any) (pgx.Identifier, error) {
switch v := v.(type) {
case string:
return pgx.Identifier{v}, nil
case pgx.Identifier:
return v, nil
default:
return nil, fmt.Errorf("expected string or pgx.Identifier, got %T", v)
}
}
func selectOneRow(ctx context.Context, db Queryer, sql string, args []any, rowFn func(pgx.Rows) error) error {
rowCount := 0
err := selectRows(ctx, db, sql, args, func(rows pgx.Rows) error {
rowCount += 1
return rowFn(rows)
})
if err != nil {
return err
}
if rowCount == 0 {
return errNotFound
}
if rowCount > 1 {
return errMultipleRows
}
return nil
}
func selectRows(ctx context.Context, db Queryer, sql string, args []any, rowFn func(pgx.Rows) error) error {
rows, _ := db.Query(ctx, sql, args...)
for rows.Next() {
err := rowFn(rows)
if err != nil {
rows.Close()
return err
}
}
if rows.Err() != nil {
return rows.Err()
}
return nil
}
// SelectMap selects a single row into a map. An error will be returned if no rows are found.
//
// Deprecated: Prefer SelectRow with pgx.RowToMap.
func SelectMap(ctx context.Context, db Queryer, sql string, args ...any) (map[string]any, error) {
var v map[string]any
err := selectOneRow(ctx, db, sql, args, func(rows pgx.Rows) error {
return rows.Scan((*mapRowScanner)(&v))
})
if err != nil {
return nil, err
}
return v, nil
}
// SelectAllMap selects rows into a map slice.
//
// Deprecated: Prefer Select with pgx.RowToMap.
func SelectAllMap(ctx context.Context, db Queryer, sql string, args ...any) ([]map[string]any, error) {
var v []map[string]any
err := selectRows(ctx, db, sql, args, func(rows pgx.Rows) error {
var m map[string]any
err := rows.Scan((*mapRowScanner)(&m))
if err != nil {
return err
}
v = append(v, m)
return nil
})
if err != nil {
return nil, err
}
return v, nil
}
type mapRowScanner map[string]any
func (rs *mapRowScanner) ScanRow(rows pgx.Rows) error {
values, err := rows.Values()
if err != nil {
return err
}
*rs = make(mapRowScanner, len(values))
for i := range values {
(*rs)[string(rows.FieldDescriptions()[i].Name)] = values[i]
}
return nil
}
// SelectStringMap selects a single row into a map where all values are strings. An error will be returned if no rows
// are found.
//
// Deprecated: Prefer SelectRow.
func SelectStringMap(ctx context.Context, db Queryer, sql string, args ...any) (map[string]string, error) {
var v map[string]string
args = append([]any{pgx.QueryResultFormats{pgx.TextFormatCode}}, args...)
err := selectOneRow(ctx, db, sql, args, func(rows pgx.Rows) error {
values := rows.RawValues()
v = make(map[string]string, len(values))
for i := range values {
v[string(rows.FieldDescriptions()[i].Name)] = string(values[i])
}
return nil
})
if err != nil {
return nil, err
}
return v, nil
}
// SelectAllStringMap selects rows into a map slice where all values are strings.
//
// Deprecated: Prefer Select.
func SelectAllStringMap(ctx context.Context, db Queryer, sql string, args ...any) ([]map[string]string, error) {
var v []map[string]string
args = append([]any{pgx.QueryResultFormats{pgx.TextFormatCode}}, args...)
err := selectRows(ctx, db, sql, args, func(rows pgx.Rows) error {
values := rows.RawValues()
m := make(map[string]string, len(values))
for i := range values {
m[string(rows.FieldDescriptions()[i].Name)] = string(values[i])
}
v = append(v, m)
return nil
})
if err != nil {
return nil, err
}
return v, nil
}
// SelectStruct selects a single row into struct dst. An error will be returned if no rows are found. The values are
// assigned positionally to the exported struct fields.
//
// Deprecated: Prefer SelectRow with pgx.RowToAddrOfStruct.
func SelectStruct(ctx context.Context, db Queryer, dst any, sql string, args ...any) error {
dstValue := reflect.ValueOf(dst)
if dstValue.Kind() != reflect.Ptr {
return fmt.Errorf("dst not a pointer")
}
dstElemValue := dstValue.Elem()
dstElemType := dstElemValue.Type()
exportedFields := make([]int, 0, dstElemType.NumField())
for i := 0; i < dstElemType.NumField(); i++ {
sf := dstElemType.Field(i)
if sf.PkgPath == "" {
exportedFields = append(exportedFields, i)
}
}
err := selectOneRow(ctx, db, sql, args, func(rows pgx.Rows) error {
rowFieldCount := len(rows.RawValues())
if rowFieldCount > len(exportedFields) {
return fmt.Errorf("got %d values, but dst struct has only %d fields", rowFieldCount, len(exportedFields))
}
scanTargets := make([]any, rowFieldCount)
for i := 0; i < rowFieldCount; i++ {
scanTargets[i] = dstElemValue.Field(exportedFields[i]).Addr().Interface()
}
return rows.Scan(scanTargets...)
})
if err != nil {
return err
}
return nil
}
// SelectAllStruct selects rows into dst. dst must be a slice of struct or pointer to struct. The values are assigned
// positionally to the exported struct fields.
//
// Deprecated: Prefer Select with pgx.RowToAddrOfStruct.
func SelectAllStruct(ctx context.Context, db Queryer, dst any, sql string, args ...any) error {
ptrSliceValue := reflect.ValueOf(dst)
if ptrSliceValue.Kind() != reflect.Ptr {
return fmt.Errorf("dst not a pointer")
}
sliceType := ptrSliceValue.Elem().Type()
if sliceType.Kind() != reflect.Slice {
return fmt.Errorf("dst not a pointer to slice")
}
var isPtr bool
sliceElemType := sliceType.Elem()
var structType reflect.Type
switch sliceElemType.Kind() {
case reflect.Ptr:
isPtr = true
structType = sliceElemType.Elem()
case reflect.Struct:
structType = sliceElemType
default:
return fmt.Errorf("dst not a pointer to slice of struct or pointer to struct")
}
if structType.Kind() != reflect.Struct {
return fmt.Errorf("dst not a pointer to slice of struct or pointer to struct")
}
exportedFields := make([]int, 0, structType.NumField())
for i := 0; i < structType.NumField(); i++ {
sf := structType.Field(i)
if sf.PkgPath == "" {
exportedFields = append(exportedFields, i)
}
}
sliceValue := reflect.New(sliceType).Elem()
err := selectRows(ctx, db, sql, args, func(rows pgx.Rows) error {
rowFieldCount := len(rows.RawValues())
if rowFieldCount > len(exportedFields) {
return fmt.Errorf("got %d values, but dst struct has only %d fields", rowFieldCount, len(exportedFields))
}
var appendableValue reflect.Value
var fieldableValue reflect.Value
if isPtr {
appendableValue = reflect.New(structType)
fieldableValue = appendableValue.Elem()
} else {
appendableValue = reflect.New(structType).Elem()
fieldableValue = appendableValue
}
scanTargets := make([]any, rowFieldCount)
for i := 0; i < rowFieldCount; i++ {
scanTargets[i] = fieldableValue.Field(exportedFields[i]).Addr().Interface()
}
err := rows.Scan(scanTargets...)
if err != nil {
return err
}
sliceValue = reflect.Append(sliceValue, appendableValue)
return nil
})
if err != nil {
return err
}
ptrSliceValue.Elem().Set(sliceValue)
return nil
}
// SelectValue selects a single T. An error will be returned if no rows are found.
//
// Deprecated: Prefer SelectRow with pgx.RowTo.
func SelectValue[T any](ctx context.Context, db Queryer, sql string, args ...any) (T, error) {
var v T
err := selectOneRow(ctx, db, sql, args, func(rows pgx.Rows) error {
if len(rows.RawValues()) == 0 {
return errNoColumns
}
if len(rows.RawValues()) > 1 {
return errMultipleColumns
}
return rows.Scan(&v)
})
if err != nil {
// Explicitly returning zero value T instead of v because it is possible, though unlikely, that v was partially
// written before an error occurred and the the caller of SelectValue is not checking the error.
var zero T
return zero, err
}
return v, nil
}
// SelectColumn selects a column of T.
//
// Deprecated: Prefer Select with pgx.RowTo.
func SelectColumn[T any](ctx context.Context, db Queryer, sql string, args ...any) ([]T, error) {
column := []T{}
err := selectRows(ctx, db, sql, args, func(rows pgx.Rows) error {
if len(rows.RawValues()) == 0 {
return errNoColumns
}
if len(rows.RawValues()) > 1 {
return errMultipleColumns
}
var v T
err := rows.Scan(&v)
if err != nil {
return err
}
column = append(column, v)
return nil
})
if err != nil {
return nil, err
}
return column, nil
}