-
-
Notifications
You must be signed in to change notification settings - Fork 956
Expand file tree
/
Copy pathconn.go
More file actions
1954 lines (1772 loc) · 51.7 KB
/
conn.go
File metadata and controls
1954 lines (1772 loc) · 51.7 KB
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
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package pq
import (
"bufio"
"context"
"crypto/md5"
"crypto/sha256"
"database/sql"
"database/sql/driver"
"encoding/binary"
"errors"
"fmt"
"io"
"math"
"net"
"os"
"reflect"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/lib/pq/internal/pgpass"
"github.com/lib/pq/internal/pqsql"
"github.com/lib/pq/internal/pqutil"
"github.com/lib/pq/internal/proto"
"github.com/lib/pq/oid"
"github.com/lib/pq/scram"
)
// Common error types
var (
ErrNotSupported = errors.New("pq: unsupported command")
ErrInFailedTransaction = errors.New("pq: could not complete operation in a failed transaction")
ErrSSLNotSupported = errors.New("pq: SSL is not enabled on the server")
ErrCouldNotDetectUsername = errors.New("pq: could not detect default username; please provide one explicitly")
ErrSSLKeyUnknownOwnership = pqutil.ErrSSLKeyUnknownOwnership
ErrSSLKeyHasWorldPermissions = pqutil.ErrSSLKeyHasWorldPermissions
errQueryInProgress = errors.New("pq: there is already a query being processed on this connection")
errUnexpectedReady = errors.New("unexpected ReadyForQuery")
errNoRowsAffected = errors.New("no RowsAffected available after the empty statement")
errNoLastInsertID = errors.New("no LastInsertId available after the empty statement")
)
// Compile time validation that our types implement the expected interfaces
var (
_ driver.Driver = Driver{}
//_ driver.DriverContext = Driver{} // TODO: https://github.com/lib/pq/pull/900
_ driver.Connector = (*Connector)(nil)
_ driver.Conn = (*conn)(nil)
_ driver.ConnBeginTx = (*conn)(nil)
_ driver.ConnPrepareContext = (*conn)(nil)
_ driver.ExecerContext = (*conn)(nil)
_ driver.NamedValueChecker = (*conn)(nil)
_ driver.Pinger = (*conn)(nil)
_ driver.QueryerContext = (*conn)(nil)
_ driver.SessionResetter = (*conn)(nil)
_ driver.Validator = (*conn)(nil)
_ driver.Stmt = (*stmt)(nil)
_ driver.StmtExecContext = (*stmt)(nil)
_ driver.StmtQueryContext = (*stmt)(nil)
_ driver.Rows = (*rows)(nil)
_ driver.RowsColumnTypeDatabaseTypeName = (*rows)(nil)
_ driver.RowsColumnTypeLength = (*rows)(nil)
//_ driver.RowsColumnTypeNullable = (*rows)(nil) // TODO
_ driver.RowsColumnTypePrecisionScale = (*rows)(nil)
_ driver.RowsColumnTypeScanType = (*rows)(nil)
_ driver.RowsNextResultSet = (*rows)(nil)
)
func init() {
sql.Register("postgres", &Driver{})
}
var debugProto = func() bool {
// Check for exactly "1" (rather than mere existence) so we can add
// options/flags in the future. I don't know if we ever want that, but it's
// nice to leave the option open.
return os.Getenv("PQGO_DEBUG") == "1"
}()
// Driver is the Postgres database driver.
type Driver struct{}
// Open opens a new connection to the database. name is a connection string.
// Most users should only use it through database/sql package from the standard
// library.
func (d Driver) Open(name string) (driver.Conn, error) {
return Open(name)
}
// Parameters sent by PostgreSQL on startup.
type parameterStatus struct {
serverVersion int
currentLocation *time.Location
inHotStandby, defaultTransactionReadOnly sql.NullBool
isRedshift bool
}
type format int
const (
formatText format = 0
formatBinary format = 1
)
var (
// One result-column format code with the value 1 (i.e. all binary).
colFmtDataAllBinary = []byte{0, 1, 0, 1}
// No result-column format codes (i.e. all text).
colFmtDataAllText = []byte{0, 0}
)
type transactionStatus byte
const (
txnStatusIdle transactionStatus = 'I'
txnStatusIdleInTransaction transactionStatus = 'T'
txnStatusInFailedTransaction transactionStatus = 'E'
)
func (s transactionStatus) String() string {
switch s {
case txnStatusIdle:
return "idle"
case txnStatusIdleInTransaction:
return "idle in transaction"
case txnStatusInFailedTransaction:
return "in a failed transaction"
default:
panic(fmt.Sprintf("pq: unknown transactionStatus %d", s))
}
}
// Dialer is the dialer interface. It can be used to obtain more control over
// how pq creates network connections.
type Dialer interface {
Dial(network, address string) (net.Conn, error)
DialTimeout(network, address string, timeout time.Duration) (net.Conn, error)
}
// DialerContext is the context-aware dialer interface.
type DialerContext interface {
DialContext(ctx context.Context, network, address string) (net.Conn, error)
}
type defaultDialer struct {
d net.Dialer
}
func (d defaultDialer) Dial(network, address string) (net.Conn, error) {
return d.d.Dial(network, address)
}
func (d defaultDialer) DialTimeout(network, address string, timeout time.Duration) (net.Conn, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
return d.DialContext(ctx, network, address)
}
func (d defaultDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
return d.d.DialContext(ctx, network, address)
}
type conn struct {
c net.Conn
buf *bufio.Reader
namei int
scratch [512]byte
txnStatus transactionStatus
txnFinish func()
// Save connection arguments to use during CancelRequest.
dialer Dialer
cfg Config
parameterStatus parameterStatus
saveMessageType proto.ResponseCode
saveMessageBuffer []byte
// If an error is set this connection is bad and all public-facing
// functions should return the appropriate error by calling get()
// (ErrBadConn) or getForNext().
err syncErr
secretKey []byte // Cancellation key for CancelRequest messages.
pid int // Cancellation PID.
inProgress atomic.Bool // This connection is in the middle of a processing a request.
noticeHandler func(*Error) // If not nil, notices will be synchronously sent here
notificationHandler func(*Notification) // If not nil, notifications will be synchronously sent here
gss GSS // GSSAPI context
}
type syncErr struct {
err error
sync.Mutex
}
// Return ErrBadConn if connection is bad.
func (e *syncErr) get() error {
e.Lock()
defer e.Unlock()
if e.err != nil {
return driver.ErrBadConn
}
return nil
}
// Return the error set on the connection. Currently only used by rows.Next.
func (e *syncErr) getForNext() error {
e.Lock()
defer e.Unlock()
return e.err
}
// Set error, only if it isn't set yet.
func (e *syncErr) set(err error) {
if err == nil {
panic("attempt to set nil err")
}
e.Lock()
defer e.Unlock()
if e.err == nil {
e.err = err
}
}
func (cn *conn) writeBuf(b proto.RequestCode) *writeBuf {
cn.scratch[0] = byte(b)
return &writeBuf{
buf: cn.scratch[:5],
pos: 1,
}
}
// Open opens a new connection to the database. dsn is a connection string. Most
// users should only use it through database/sql package from the standard
// library.
func Open(dsn string) (_ driver.Conn, err error) {
return DialOpen(defaultDialer{}, dsn)
}
// DialOpen opens a new connection to the database using a dialer.
func DialOpen(d Dialer, dsn string) (_ driver.Conn, err error) {
c, err := NewConnector(dsn)
if err != nil {
return nil, err
}
c.Dialer(d)
return c.open(context.Background())
}
func (c *Connector) open(ctx context.Context) (*conn, error) {
tsa := c.cfg.TargetSessionAttrs
restartAll:
var (
errs []error
app = func(err error, cfg Config) bool {
if err != nil {
if debugProto {
fmt.Fprintln(os.Stderr, "CONNECT (error)", err)
}
errs = append(errs, fmt.Errorf("connecting to %s:%d: %w", cfg.Host, cfg.Port, err))
}
return err != nil
}
)
for _, cfg := range c.cfg.hosts() {
mode := cfg.SSLMode
if mode == "" {
mode = SSLModePrefer
}
restartHost:
if debugProto {
fmt.Fprintln(os.Stderr, "CONNECT ", cfg.string())
}
cfg.SSLMode = mode
cn := &conn{cfg: cfg, dialer: c.dialer}
cn.cfg.Password = pgpass.PasswordFromPgpass(cn.cfg.Passfile, cn.cfg.User, cn.cfg.Password,
cn.cfg.Host, strconv.Itoa(int(cn.cfg.Port)), cn.cfg.Database)
var err error
cn.c, err = dial(ctx, c.dialer, cn.cfg)
if app(err, cfg) {
continue
}
err = cn.ssl(cn.cfg, mode)
if err != nil && mode == SSLModePrefer {
mode = SSLModeDisable
goto restartHost
}
if app(err, cfg) {
if cn.c != nil {
_ = cn.c.Close()
}
continue
}
cn.buf = bufio.NewReader(cn.c)
err = cn.startup(cn.cfg)
if err != nil && mode == SSLModeAllow {
mode = SSLModeRequire
goto restartHost
}
if app(err, cfg) {
_ = cn.c.Close()
continue
}
// Reset the deadline, in case one was set (see dial)
if cn.cfg.ConnectTimeout > 0 {
err := cn.c.SetDeadline(time.Time{})
if app(err, cfg) {
_ = cn.c.Close()
continue
}
}
err = cn.checkTSA(tsa)
if app(err, cfg) {
_ = cn.c.Close()
continue
}
return cn, nil
}
// target_session_attrs=prefer-standby is treated as standby in checkTSA; we
// ran out of hosts so none are on standby. Clear the setting and try again.
if c.cfg.TargetSessionAttrs == TargetSessionAttrsPreferStandby {
tsa = TargetSessionAttrsAny
goto restartAll
}
if len(c.cfg.Multi) == 0 {
// Remove the "connecting to [..]" when we have just one host, so the
// error is identical to what we had before.
return nil, errors.Unwrap(errs[0])
}
return nil, fmt.Errorf("pq: could not connect to any of the hosts:\n%w", errors.Join(errs...))
}
func (cn *conn) getBool(query string) (bool, error) {
res, err := cn.simpleQuery(query)
if err != nil {
return false, err
}
defer res.Close()
v := make([]driver.Value, 1)
err = res.Next(v)
if err != nil {
return false, err
}
switch vv := v[0].(type) {
default:
return false, fmt.Errorf("parseBool: unknown type %T: %[1]v", v[0])
case bool:
return vv, nil
case string:
vv, ok := v[0].(string)
if !ok {
return false, err
}
return vv == "on", nil
}
}
func (cn *conn) checkTSA(tsa TargetSessionAttrs) error {
var (
geths = func() (hs bool, err error) {
hs = cn.parameterStatus.inHotStandby.Bool
if !cn.parameterStatus.inHotStandby.Valid {
hs, err = cn.getBool("select pg_catalog.pg_is_in_recovery()")
}
return hs, err
}
getro = func() (ro bool, err error) {
ro = cn.parameterStatus.defaultTransactionReadOnly.Bool
if !cn.parameterStatus.defaultTransactionReadOnly.Valid {
ro, err = cn.getBool("show transaction_read_only")
}
return ro, err
}
)
switch tsa {
default:
panic("unreachable")
case "", TargetSessionAttrsAny:
return nil
case TargetSessionAttrsReadWrite, TargetSessionAttrsReadOnly:
readonly, err := getro()
if err != nil {
return err
}
if !cn.parameterStatus.defaultTransactionReadOnly.Valid {
var err error
readonly, err = cn.getBool("show transaction_read_only")
if err != nil {
return err
}
}
switch {
case tsa == TargetSessionAttrsReadOnly && !readonly:
return errors.New("session is not read-only")
case tsa == TargetSessionAttrsReadWrite:
if readonly {
return errors.New("session is read-only")
}
hs, err := geths()
if err != nil {
return err
}
if hs {
return errors.New("server is in hot standby mode")
}
return nil
default:
return nil
}
case TargetSessionAttrsPrimary, TargetSessionAttrsStandby, TargetSessionAttrsPreferStandby:
hs, err := geths()
if err != nil {
return err
}
switch {
case (tsa == TargetSessionAttrsStandby || tsa == TargetSessionAttrsPreferStandby) && !hs:
return errors.New("server is not in hot standby mode")
case tsa == TargetSessionAttrsPrimary && hs:
return errors.New("server is in hot standby mode")
default:
return nil
}
}
}
func dial(ctx context.Context, d Dialer, cfg Config) (net.Conn, error) {
network, address := cfg.network()
// Zero or not specified means wait indefinitely.
if cfg.ConnectTimeout > 0 {
// connect_timeout should apply to the entire connection establishment
// procedure, so we both use a timeout for the TCP connection
// establishment and set a deadline for doing the initial handshake. The
// deadline is then reset after startup() is done.
var (
deadline = time.Now().Add(cfg.ConnectTimeout)
conn net.Conn
err error
)
if dctx, ok := d.(DialerContext); ok {
ctx, cancel := context.WithTimeout(ctx, cfg.ConnectTimeout)
defer cancel()
conn, err = dctx.DialContext(ctx, network, address)
} else {
conn, err = d.DialTimeout(network, address, cfg.ConnectTimeout)
}
if err != nil {
return nil, err
}
err = conn.SetDeadline(deadline)
return conn, err
}
if dctx, ok := d.(DialerContext); ok {
return dctx.DialContext(ctx, network, address)
}
return d.Dial(network, address)
}
func (cn *conn) isInTransaction() bool {
return cn.txnStatus == txnStatusIdleInTransaction ||
cn.txnStatus == txnStatusInFailedTransaction
}
func (cn *conn) checkIsInTransaction(intxn bool) error {
if cn.isInTransaction() != intxn {
cn.err.set(driver.ErrBadConn)
return fmt.Errorf("pq: unexpected transaction status %v", cn.txnStatus)
}
return nil
}
// Implement [driver.ConnBeginTx].
func (cn *conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) {
var mode string
switch sql.IsolationLevel(opts.Isolation) {
case sql.LevelDefault:
// Don't touch mode: use the server's default
case sql.LevelReadUncommitted:
mode = " ISOLATION LEVEL READ UNCOMMITTED"
case sql.LevelReadCommitted:
mode = " ISOLATION LEVEL READ COMMITTED"
case sql.LevelRepeatableRead:
mode = " ISOLATION LEVEL REPEATABLE READ"
case sql.LevelSerializable:
mode = " ISOLATION LEVEL SERIALIZABLE"
default:
return nil, fmt.Errorf("pq: isolation level not supported: %d", opts.Isolation)
}
if opts.ReadOnly {
mode += " READ ONLY"
} else {
mode += " READ WRITE"
}
if err := cn.err.get(); err != nil {
return nil, err
}
if err := cn.checkIsInTransaction(false); err != nil {
return nil, err
}
_, commandTag, err := cn.simpleExec("BEGIN" + mode)
if err != nil {
return nil, cn.handleError(err)
}
if commandTag != "BEGIN" {
cn.err.set(driver.ErrBadConn)
return nil, fmt.Errorf("unexpected command tag %s", commandTag)
}
if cn.txnStatus != txnStatusIdleInTransaction {
cn.err.set(driver.ErrBadConn)
return nil, fmt.Errorf("unexpected transaction status %v", cn.txnStatus)
}
cn.txnFinish = cn.watchCancel(ctx, false)
return cn, nil
}
func (cn *conn) Commit() error {
defer func() {
if cn.txnFinish != nil {
cn.txnFinish()
}
}()
if err := cn.err.get(); err != nil {
return err
}
if err := cn.checkIsInTransaction(true); err != nil {
return err
}
// We don't want the client to think that everything is okay if it tries
// to commit a failed transaction. However, no matter what we return,
// database/sql will release this connection back into the free connection
// pool so we have to abort the current transaction here. Note that you
// would get the same behaviour if you issued a COMMIT in a failed
// transaction, so it's also the least surprising thing to do here.
if cn.txnStatus == txnStatusInFailedTransaction {
if err := cn.rollback(); err != nil {
return err
}
return ErrInFailedTransaction
}
_, commandTag, err := cn.simpleExec("COMMIT")
if err != nil {
if cn.isInTransaction() {
cn.err.set(driver.ErrBadConn)
}
return cn.handleError(err)
}
if commandTag != "COMMIT" {
cn.err.set(driver.ErrBadConn)
return fmt.Errorf("unexpected command tag %s", commandTag)
}
return cn.checkIsInTransaction(false)
}
func (cn *conn) Rollback() error {
defer func() {
if cn.txnFinish != nil {
cn.txnFinish()
}
}()
if err := cn.err.get(); err != nil {
return err
}
err := cn.rollback()
return cn.handleError(err)
}
func (cn *conn) rollback() (err error) {
if err := cn.checkIsInTransaction(true); err != nil {
return err
}
_, commandTag, err := cn.simpleExec("ROLLBACK")
if err != nil {
if cn.isInTransaction() {
cn.err.set(driver.ErrBadConn)
}
return err
}
if commandTag != "ROLLBACK" {
return fmt.Errorf("unexpected command tag %s", commandTag)
}
return cn.checkIsInTransaction(false)
}
func (cn *conn) gname() string {
cn.namei++
return strconv.FormatInt(int64(cn.namei), 10)
}
func (cn *conn) simpleExec(q string) (res driver.Result, commandTag string, resErr error) {
if debugProto {
fmt.Fprintln(os.Stderr, " START conn.simpleExec")
defer fmt.Fprintln(os.Stderr, " END conn.simpleExec")
}
b := cn.writeBuf(proto.Query)
b.string(q)
err := cn.send(b)
if err != nil {
return nil, "", err
}
for {
t, r, err := cn.recv1()
if err != nil {
return nil, "", err
}
switch t {
case proto.CommandComplete:
res, commandTag, err = cn.parseComplete(r.string())
if err != nil {
return nil, "", err
}
case proto.ReadyForQuery:
cn.processReadyForQuery(r)
if res == nil && resErr == nil {
resErr = errUnexpectedReady
}
return res, commandTag, resErr
case proto.ErrorResponse:
resErr = parseError(r, q)
case proto.EmptyQueryResponse:
res = emptyRows
case proto.RowDescription, proto.DataRow:
// ignore any results
default:
cn.err.set(driver.ErrBadConn)
return nil, "", fmt.Errorf("pq: unknown response for simple query: %q", t)
}
}
}
func (cn *conn) simpleQuery(q string) (*rows, error) {
if debugProto {
fmt.Fprintln(os.Stderr, " START conn.simpleQuery")
defer fmt.Fprintln(os.Stderr, " END conn.simpleQuery")
}
b := cn.writeBuf(proto.Query)
b.string(q)
err := cn.send(b)
if err != nil {
return nil, cn.handleError(err, q)
}
var (
res *rows
resErr error
)
for {
t, r, err := cn.recv1()
if err != nil {
return nil, cn.handleError(err, q)
}
switch t {
case proto.CommandComplete, proto.EmptyQueryResponse:
// We allow queries which don't return any results through Query as
// well as Exec. We still have to give database/sql a rows object
// the user can close, though, to avoid connections from being
// leaked. A "rows" with done=true works fine for that purpose.
if resErr != nil {
cn.err.set(driver.ErrBadConn)
return nil, fmt.Errorf("pq: unexpected message %q in simple query execution", t)
}
if res == nil {
res = &rows{cn: cn}
}
// Set the result and tag to the last command complete if there wasn't a
// query already run. Although queries usually return from here and cede
// control to Next, a query with zero results does not.
if t == proto.CommandComplete {
res.result, res.tag, err = cn.parseComplete(r.string())
if err != nil {
return nil, cn.handleError(err, q)
}
if res.colNames != nil {
return res, cn.handleError(resErr, q)
}
}
res.done = true
case proto.ReadyForQuery:
cn.processReadyForQuery(r)
if err == nil && res == nil {
res = &rows{done: true}
}
return res, cn.handleError(resErr, q) // done
case proto.ErrorResponse:
res = nil
resErr = parseError(r, q)
case proto.DataRow:
if res == nil {
cn.err.set(driver.ErrBadConn)
return nil, fmt.Errorf("pq: unexpected DataRow in simple query execution")
}
return res, cn.saveMessage(t, r) // The query didn't fail; kick off to Next
case proto.RowDescription:
// res might be non-nil here if we received a previous
// CommandComplete, but that's fine and just overwrite it.
res = &rows{cn: cn, rowsHeader: parsePortalRowDescribe(r)}
// To work around a bug in QueryRow in Go 1.2 and earlier, wait
// until the first DataRow has been received.
default:
cn.err.set(driver.ErrBadConn)
return nil, fmt.Errorf("pq: unknown response for simple query: %q", t)
}
}
}
// Decides which column formats to use for a prepared statement. The input is
// an array of type oids, one element per result column.
func decideColumnFormats(colTyps []fieldDesc, forceText bool) (colFmts []format, colFmtData []byte, _ error) {
if len(colTyps) == 0 {
return nil, colFmtDataAllText, nil
}
colFmts = make([]format, len(colTyps))
if forceText {
return colFmts, colFmtDataAllText, nil
}
allBinary := true
allText := true
for i, t := range colTyps {
switch t.OID {
// This is the list of types to use binary mode for when receiving them
// through a prepared statement. If a type appears in this list, it
// must also be implemented in binaryDecode in encode.go.
case oid.T_bytea:
fallthrough
case oid.T_int8:
fallthrough
case oid.T_int4:
fallthrough
case oid.T_int2:
fallthrough
case oid.T_uuid:
colFmts[i] = formatBinary
allText = false
default:
allBinary = false
}
}
if allBinary {
return colFmts, colFmtDataAllBinary, nil
} else if allText {
return colFmts, colFmtDataAllText, nil
} else {
colFmtData = make([]byte, 2+len(colFmts)*2)
if len(colFmts) > math.MaxUint16 {
return nil, nil, fmt.Errorf("pq: too many columns (%d > math.MaxUint16)", len(colFmts))
}
binary.BigEndian.PutUint16(colFmtData, uint16(len(colFmts)))
for i, v := range colFmts {
binary.BigEndian.PutUint16(colFmtData[2+i*2:], uint16(v))
}
return colFmts, colFmtData, nil
}
}
func (cn *conn) prepareTo(q, stmtName string) (*stmt, error) {
if debugProto {
fmt.Fprintln(os.Stderr, " START conn.prepareTo")
defer fmt.Fprintln(os.Stderr, " END conn.prepareTo")
}
st := &stmt{cn: cn, name: stmtName}
b := cn.writeBuf(proto.Parse)
b.string(st.name)
b.string(q)
b.int16(0)
b.next(proto.Describe)
b.byte(proto.Sync)
b.string(st.name)
b.next(proto.Sync)
err := cn.send(b)
if err != nil {
return nil, err
}
err = cn.readParseResponse()
if err != nil {
return nil, err
}
st.paramTyps, st.colNames, st.colTyps, err = cn.readStatementDescribeResponse()
if err != nil {
return nil, err
}
st.colFmts, st.colFmtData, err = decideColumnFormats(st.colTyps, cn.cfg.DisablePreparedBinaryResult)
if err != nil {
return nil, err
}
err = cn.readReadyForQuery()
if err != nil {
return nil, err
}
return st, nil
}
// Implement [driver.ConnPrepareContext].
func (cn *conn) PrepareContext(ctx context.Context, q string) (driver.Stmt, error) {
defer cn.watchCancel(ctx, false)()
if err := cn.err.get(); err != nil {
return nil, err
}
if pqsql.StartsWithCopy(q) {
s, err := cn.prepareCopyIn(q)
if err == nil {
cn.inProgress.Store(true)
}
return s, cn.handleError(err, q)
}
s, err := cn.prepareTo(q, cn.gname())
if err != nil {
return nil, cn.handleError(err, q)
}
return s, nil
}
func (cn *conn) Close() error {
// Don't go through send(); ListenerConn relies on us not scribbling on the
// scratch buffer of this connection.
err := cn.sendSimpleMessage(proto.Terminate)
if err != nil {
_ = cn.c.Close() // Ensure that cn.c.Close is always run.
return cn.handleError(err)
}
return cn.c.Close()
}
// CheckNamedValue implements [driver.NamedValueChecker].
func (cn *conn) CheckNamedValue(nv *driver.NamedValue) error {
if cn.cfg.BinaryParameters {
if bin, ok := nv.Value.(interface{ BinaryValue() ([]byte, error) }); ok {
var err error
nv.Value, err = bin.BinaryValue()
return err
}
}
// Ignore Valuer, for backward compatibility with pq.Array().
if _, ok := nv.Value.(driver.Valuer); ok {
return driver.ErrSkip
}
v := reflect.ValueOf(nv.Value)
if !v.IsValid() {
return driver.ErrSkip
}
t := v.Type()
for t.Kind() == reflect.Pointer {
t, v = t.Elem(), v.Elem()
}
// Ignore []byte and related types: *[]byte, json.RawMessage, etc.
if t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Uint8 {
return driver.ErrSkip
}
switch v.Kind() {
default:
return driver.ErrSkip
case reflect.Slice:
var err error
nv.Value, err = Array(v.Interface()).Value()
return err
case reflect.Uint64:
value := v.Uint()
if value >= math.MaxInt64 {
nv.Value = strconv.FormatUint(value, 10)
} else {
nv.Value = int64(value)
}
return nil
}
}
// Implement [driver.QueryerContext].
func (cn *conn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) {
finish := cn.watchCancel(ctx, false)
r, err := cn.query(query, args)
if err != nil {
if finish != nil {
finish()
}
return nil, err
}
r.finish = finish
return r, nil
}
func (cn *conn) query(query string, args []driver.NamedValue) (*rows, error) {
if debugProto {
fmt.Fprintln(os.Stderr, " START conn.query")
defer fmt.Fprintln(os.Stderr, " END conn.query")
}
if err := cn.err.get(); err != nil {
return nil, err
}
if !cn.inProgress.CompareAndSwap(false, true) {
return nil, errQueryInProgress
}
// Check to see if we can use the "simpleQuery" interface, which is
// *much* faster than going through prepare/exec
if len(args) == 0 {
return cn.simpleQuery(query)
}
if cn.cfg.BinaryParameters {
err := cn.sendBinaryModeQuery(query, args)
if err != nil {
return nil, cn.handleError(err, query)
}
err = cn.readParseResponse()
if err != nil {
return nil, cn.handleError(err, query)
}
err = cn.readBindResponse()
if err != nil {
return nil, cn.handleError(err, query)
}
rows := &rows{cn: cn}
rows.rowsHeader, err = cn.readPortalDescribeResponse()
if err != nil {
return nil, cn.handleError(err, query)
}
err = cn.postExecuteWorkaround()
if err != nil {
return nil, cn.handleError(err, query)
}
return rows, nil
}
st, err := cn.prepareTo(query, "")
if err != nil {
return nil, cn.handleError(err, query)
}
err = st.exec(args)
if err != nil {
return nil, cn.handleError(err, query)
}
return &rows{
cn: cn,
rowsHeader: st.rowsHeader,
}, nil
}
// Implement [driver.ExecerContext].
func (cn *conn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) {
defer cn.watchCancel(ctx, false)()
if err := cn.err.get(); err != nil {
return nil, err
}
if !cn.inProgress.CompareAndSwap(false, true) {
return nil, errQueryInProgress
}
// simpleExec is *much* faster than going through prepare/exec.
if len(args) == 0 {
r, _, err := cn.simpleExec(query) // Ignore commandTag, our caller doesn't care.
return r, cn.handleError(err, query)
}
if cn.cfg.BinaryParameters {
err := cn.sendBinaryModeQuery(query, args)
if err != nil {
return nil, cn.handleError(err, query)