-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
v3.go
1118 lines (1010 loc) · 32.7 KB
/
v3.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
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
// Copyright 2015 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// Author: Ben Darnell
// Author: Tamir Duberstein ([email protected])
package pgwire
import (
"bufio"
"crypto/tls"
"fmt"
"net"
"strconv"
"time"
"github.com/lib/pq/oid"
"github.com/pkg/errors"
"golang.org/x/net/context"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/mon"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
)
//go:generate stringer -type=clientMessageType
type clientMessageType byte
//go:generate stringer -type=serverMessageType
type serverMessageType byte
// http://www.postgresql.org/docs/9.4/static/protocol-message-formats.html
const (
clientMsgBind clientMessageType = 'B'
clientMsgClose clientMessageType = 'C'
clientMsgCopyData clientMessageType = 'd'
clientMsgCopyDone clientMessageType = 'c'
clientMsgCopyFail clientMessageType = 'f'
clientMsgDescribe clientMessageType = 'D'
clientMsgExecute clientMessageType = 'E'
clientMsgFlush clientMessageType = 'H'
clientMsgParse clientMessageType = 'P'
clientMsgPassword clientMessageType = 'p'
clientMsgSimpleQuery clientMessageType = 'Q'
clientMsgSync clientMessageType = 'S'
clientMsgTerminate clientMessageType = 'X'
serverMsgAuth serverMessageType = 'R'
serverMsgBindComplete serverMessageType = '2'
serverMsgCommandComplete serverMessageType = 'C'
serverMsgCloseComplete serverMessageType = '3'
serverMsgCopyInResponse serverMessageType = 'G'
serverMsgDataRow serverMessageType = 'D'
serverMsgEmptyQuery serverMessageType = 'I'
serverMsgErrorResponse serverMessageType = 'E'
serverMsgNoData serverMessageType = 'n'
serverMsgParameterDescription serverMessageType = 't'
serverMsgParameterStatus serverMessageType = 'S'
serverMsgParseComplete serverMessageType = '1'
serverMsgReady serverMessageType = 'Z'
serverMsgRowDescription serverMessageType = 'T'
)
//go:generate stringer -type=serverErrFieldType
type serverErrFieldType byte
// http://www.postgresql.org/docs/current/static/protocol-error-fields.html
const (
serverErrFieldSeverity serverErrFieldType = 'S'
serverErrFieldSQLState serverErrFieldType = 'C'
serverErrFieldMsgPrimary serverErrFieldType = 'M'
serverErrFileldDetail serverErrFieldType = 'D'
serverErrFileldHint serverErrFieldType = 'H'
serverErrFieldSrcFile serverErrFieldType = 'F'
serverErrFieldSrcLine serverErrFieldType = 'L'
serverErrFieldSrcFunction serverErrFieldType = 'R'
)
//go:generate stringer -type=prepareType
type prepareType byte
const (
prepareStatement prepareType = 'S'
preparePortal prepareType = 'P'
)
const (
authOK int32 = 0
authCleartextPassword int32 = 3
)
// preparedStatementMeta is pgwire-specific metadata which is attached to each
// sql.PreparedStatement on a v3Conn's sql.Session.
type preparedStatementMeta struct {
inTypes []oid.Oid
}
// preparedPortalMeta is pgwire-specific metadata which is attached to each
// sql.PreparedPortal on a v3Conn's sql.Session.
type preparedPortalMeta struct {
outFormats []formatCode
}
// readTimeoutConn overloads net.Conn.Read by periodically calling
// checkExitConds() and aborting the read if an error is returned.
type readTimeoutConn struct {
net.Conn
checkExitConds func() error
}
func newReadTimeoutConn(c net.Conn, checkExitConds func() error) net.Conn {
// net.Pipe does not support setting deadlines. See
// https://github.com/golang/go/blob/go1.7.4/src/net/pipe.go#L57-L67
if c.LocalAddr().Network() == "pipe" {
return c
}
return &readTimeoutConn{
Conn: c,
checkExitConds: checkExitConds,
}
}
func (c *readTimeoutConn) Read(b []byte) (int, error) {
// readTimeout is the amount of time ReadTimeoutConn should wait on a
// read before checking for exit conditions. The tradeoff is between the
// time it takes to react to session context cancellation and the overhead
// of waking up and checking for exit conditions.
const readTimeout = 150 * time.Millisecond
// Remove the read deadline when returning from this function to avoid
// unexpected behavior.
defer func() { _ = c.SetReadDeadline(time.Time{}) }()
for {
if err := c.checkExitConds(); err != nil {
return 0, err
}
if err := c.SetReadDeadline(timeutil.Now().Add(readTimeout)); err != nil {
return 0, err
}
n, err := c.Conn.Read(b)
// Continue if the error is due to timing out.
if err, ok := err.(net.Error); ok && err.Timeout() {
continue
}
return n, err
}
}
type v3Conn struct {
conn net.Conn
rd *bufio.Reader
wr *bufio.Writer
executor *sql.Executor
readBuf readBuffer
writeBuf writeBuffer
tagBuf [64]byte
sessionArgs sql.SessionArgs
session *sql.Session
// The logic governing these guys is hairy, and is not sufficiently
// specified in documentation. Consult the sources before you modify:
// https://github.com/postgres/postgres/blob/master/src/backend/tcop/postgres.c
doingExtendedQueryMessage, ignoreTillSync bool
metrics *ServerMetrics
sqlMemoryPool *mon.MemoryMonitor
}
func makeV3Conn(
conn net.Conn, metrics *ServerMetrics, sqlMemoryPool *mon.MemoryMonitor, executor *sql.Executor,
) v3Conn {
return v3Conn{
conn: conn,
rd: bufio.NewReader(conn),
wr: bufio.NewWriter(conn),
writeBuf: writeBuffer{bytecount: metrics.BytesOutCount},
metrics: metrics,
executor: executor,
sqlMemoryPool: sqlMemoryPool,
}
}
func (c *v3Conn) finish(ctx context.Context) {
// This is better than always flushing on error.
if err := c.wr.Flush(); err != nil {
log.Error(ctx, err)
}
_ = c.conn.Close()
}
func parseOptions(data []byte) (sql.SessionArgs, error) {
args := sql.SessionArgs{}
buf := readBuffer{msg: data}
for {
key, err := buf.getString()
if err != nil {
return sql.SessionArgs{}, errors.Errorf("error reading option key: %s", err)
}
if len(key) == 0 {
break
}
value, err := buf.getString()
if err != nil {
return sql.SessionArgs{}, errors.Errorf("error reading option value: %s", err)
}
switch key {
case "database":
args.Database = value
case "user":
args.User = value
default:
if log.V(1) {
log.Warningf(context.TODO(), "unrecognized configuration parameter %q", key)
}
}
}
return args, nil
}
// statusReportParams is a static mapping from run-time parameters to their respective
// hard-coded values, each of which is to be returned as part of the status report
// during connection initialization.
var statusReportParams = map[string]string{
"client_encoding": "UTF8",
"DateStyle": "ISO",
// All datetime binary formats expect 64-bit integer microsecond values.
// This param needs to be provided to clients or some may provide 64-bit
// floating-point microsecond values instead, which was a legacy datetime
// binary format.
"integer_datetimes": "on",
// The latest version of the docs that was consulted during the development
// of this package. We specify this version to avoid having to support old
// code paths which various client tools fall back to if they can't
// determine that the server is new enough.
"server_version": sql.PgServerVersion,
}
// handleAuthentication should discuss with the client to arrange
// authentication and update c.sessionArgs with the authenticated user's
// name, if different from the one given initially. Note: at this
// point the sql.Session does not exist yet! If need exists to access the
// database to look up authentication data, use the internal executor.
func (c *v3Conn) handleAuthentication(ctx context.Context, insecure bool) error {
if tlsConn, ok := c.conn.(*tls.Conn); ok {
var authenticationHook security.UserAuthHook
// Check that the requested user exists and retrieve the hashed
// password in case password authentication is needed.
hashedPassword, err := sql.GetUserHashedPassword(
ctx, c.executor, c.metrics.internalMemMetrics, c.sessionArgs.User,
)
if err != nil {
return c.sendError(err)
}
tlsState := tlsConn.ConnectionState()
// If no certificates are provided, default to password
// authentication.
if len(tlsState.PeerCertificates) == 0 {
password, err := c.sendAuthPasswordRequest()
if err != nil {
return c.sendError(err)
}
authenticationHook = security.UserAuthPasswordHook(
insecure, password, hashedPassword,
)
} else {
// Normalize the username contained in the certificate.
tlsState.PeerCertificates[0].Subject.CommonName = parser.Name(
tlsState.PeerCertificates[0].Subject.CommonName,
).Normalize()
var err error
authenticationHook, err = security.UserAuthCertHook(insecure, &tlsState)
if err != nil {
return c.sendError(err)
}
}
if err := authenticationHook(c.sessionArgs.User, true /* public */); err != nil {
return c.sendError(err)
}
}
c.writeBuf.initMsg(serverMsgAuth)
c.writeBuf.putInt32(authOK)
return c.writeBuf.finishMsg(c.wr)
}
func (c *v3Conn) setupSession(ctx context.Context, reserved mon.BoundAccount) error {
c.session = sql.NewSession(
ctx, c.sessionArgs, c.executor, c.conn.RemoteAddr(), &c.metrics.SQLMemMetrics,
)
c.session.StartMonitor(c.sqlMemoryPool, reserved)
return nil
}
func (c *v3Conn) closeSession(ctx context.Context) {
c.session.Finish(c.executor)
c.session = nil
}
func (c *v3Conn) serve(ctx context.Context, draining func() bool, reserved mon.BoundAccount) error {
for key, value := range statusReportParams {
c.writeBuf.initMsg(serverMsgParameterStatus)
c.writeBuf.writeTerminatedString(key)
c.writeBuf.writeTerminatedString(value)
if err := c.writeBuf.finishMsg(c.wr); err != nil {
return err
}
}
if err := c.wr.Flush(); err != nil {
return err
}
ctx = log.WithLogTagStr(ctx, "user", c.sessionArgs.User)
if err := c.setupSession(ctx, reserved); err != nil {
return err
}
defer func() {
// If we're panicking, don't bother trying to close the session; it would
// pollute the logs.
if r := recover(); r != nil {
panic(r)
}
c.closeSession(ctx)
}()
// Once a session has been set up, the underlying net.Conn is switched to
// a conn that exits if the session's context is cancelled or if the server
// is draining and the session does not have an ongoing transaction.
c.conn = newReadTimeoutConn(c.conn, func() error {
if err := func() error {
if draining() && c.session.TxnState.State == sql.NoTxn {
return errors.New(ErrDraining)
}
return c.session.Ctx().Err()
}(); err != nil {
return newAdminShutdownErr(err)
}
return nil
})
c.rd = bufio.NewReader(c.conn)
for {
if !c.doingExtendedQueryMessage {
c.writeBuf.initMsg(serverMsgReady)
var txnStatus byte
switch c.session.TxnState.State {
case sql.Aborted, sql.RestartWait:
// We send status "InFailedTransaction" also for state RestartWait
// because GO's lib/pq freaks out if we invent a new status.
txnStatus = 'E'
case sql.Open:
txnStatus = 'T'
case sql.NoTxn:
// We're not in a txn (i.e. the last txn was committed).
txnStatus = 'I'
case sql.CommitWait:
// We need to lie to pgwire and claim that we're still
// in a txn. Otherwise drivers freak out.
// This state is not part of the Postgres protocol.
txnStatus = 'T'
}
if log.V(2) {
log.Infof(ctx, "pgwire: %s: %q", serverMsgReady, txnStatus)
}
c.writeBuf.writeByte(txnStatus)
if err := c.writeBuf.finishMsg(c.wr); err != nil {
return err
}
// We only flush on every message if not doing an extended query.
// If we are, wait for an explicit Flush message. See:
// http://www.postgresql.org/docs/current/static/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY.
if err := c.wr.Flush(); err != nil {
return err
}
}
typ, n, err := c.readBuf.readTypedMsg(c.rd)
c.metrics.BytesInCount.Inc(int64(n))
if err != nil {
return err
}
// When an error occurs handling an extended query message, we have to ignore
// any messages until we get a sync.
if c.ignoreTillSync && typ != clientMsgSync {
if log.V(2) {
log.Infof(ctx, "pgwire: ignoring %s till sync", typ)
}
continue
}
if log.V(2) {
log.Infof(ctx, "pgwire: processing %s", typ)
}
switch typ {
case clientMsgSync:
c.doingExtendedQueryMessage = false
c.ignoreTillSync = false
case clientMsgSimpleQuery:
c.doingExtendedQueryMessage = false
err = c.handleSimpleQuery(ctx, &c.readBuf)
case clientMsgTerminate:
return nil
case clientMsgParse:
c.doingExtendedQueryMessage = true
err = c.handleParse(ctx, &c.readBuf)
case clientMsgDescribe:
c.doingExtendedQueryMessage = true
err = c.handleDescribe(ctx, &c.readBuf)
case clientMsgClose:
c.doingExtendedQueryMessage = true
err = c.handleClose(&c.readBuf)
case clientMsgBind:
c.doingExtendedQueryMessage = true
err = c.handleBind(&c.readBuf)
case clientMsgExecute:
c.doingExtendedQueryMessage = true
err = c.handleExecute(ctx, &c.readBuf)
case clientMsgFlush:
c.doingExtendedQueryMessage = true
err = c.wr.Flush()
case clientMsgCopyData, clientMsgCopyDone, clientMsgCopyFail:
// The spec says to drop any extra of these messages.
default:
return c.sendError(newUnrecognizedMsgTypeErr(typ))
}
if err != nil {
return err
}
}
}
// sendAuthPasswordRequest requests a cleartext password from the client and
// returns it.
func (c *v3Conn) sendAuthPasswordRequest() (string, error) {
c.writeBuf.initMsg(serverMsgAuth)
c.writeBuf.putInt32(authCleartextPassword)
if err := c.writeBuf.finishMsg(c.wr); err != nil {
return "", err
}
if err := c.wr.Flush(); err != nil {
return "", err
}
typ, n, err := c.readBuf.readTypedMsg(c.rd)
c.metrics.BytesInCount.Inc(int64(n))
if err != nil {
return "", err
}
if typ != clientMsgPassword {
return "", errors.Errorf("invalid response to authentication request: %s", typ)
}
return c.readBuf.getString()
}
func (c *v3Conn) handleSimpleQuery(ctx context.Context, buf *readBuffer) error {
query, err := buf.getString()
if err != nil {
return err
}
return c.executeStatements(ctx, query, nil, nil, true, 0)
}
func (c *v3Conn) handleParse(ctx context.Context, buf *readBuffer) error {
name, err := buf.getString()
if err != nil {
return err
}
// The unnamed prepared statement can be freely overwritten.
if name != "" {
if c.session.PreparedStatements.Exists(name) {
return c.sendInternalError(fmt.Sprintf("prepared statement %q already exists", name))
}
}
query, err := buf.getString()
if err != nil {
return err
}
// The client may provide type information for (some of) the
// placeholders. Read this first.
numQArgTypes, err := buf.getUint16()
if err != nil {
return err
}
inTypeHints := make([]oid.Oid, numQArgTypes)
for i := range inTypeHints {
typ, err := buf.getUint32()
if err != nil {
return err
}
inTypeHints[i] = oid.Oid(typ)
}
// Prepare the mapping of SQL placeholder names to
// types. Pre-populate it with the type hints received from the
// client, if any.
sqlTypeHints := make(parser.PlaceholderTypes)
for i, t := range inTypeHints {
if t == 0 {
continue
}
v, ok := parser.OidToType[t]
if !ok {
return c.sendInternalError(fmt.Sprintf("unknown oid type: %v", t))
}
sqlTypeHints[strconv.Itoa(i+1)] = v
}
// Create the new PreparedStatement in the connection's Session.
stmt, err := c.session.PreparedStatements.New(ctx, c.executor, name, query, sqlTypeHints)
if err != nil {
return c.sendError(err)
}
// Convert the inferred SQL types back to an array of pgwire Oids.
inTypes := make([]oid.Oid, 0, len(stmt.SQLTypes))
for k, t := range stmt.SQLTypes {
i, err := strconv.Atoi(k)
if err != nil || i < 1 {
return c.sendInternalError(fmt.Sprintf("invalid placeholder name: $%s", k))
}
// Placeholder names are 1-indexed; the arrays in the protocol are
// 0-indexed.
i--
// Grow inTypes to be at least as large as i. Prepopulate all
// slots with the hints provided, if any.
for j := len(inTypes); j <= i; j++ {
inTypes = append(inTypes, 0)
if j < len(inTypeHints) {
inTypes[j] = inTypeHints[j]
}
}
// OID to Datum is not a 1-1 mapping (for example, int4 and int8
// both map to TypeInt), so we need to maintain the types sent by
// the client.
if inTypes[i] != 0 {
continue
}
inTypes[i] = t.Oid()
}
for i, t := range inTypes {
if t == 0 {
return c.sendInternalError(
fmt.Sprintf("could not determine data type of placeholder $%d", i+1))
}
}
// Attach pgwire-specific metadata to the PreparedStatement.
stmt.ProtocolMeta = preparedStatementMeta{inTypes: inTypes}
c.writeBuf.initMsg(serverMsgParseComplete)
return c.writeBuf.finishMsg(c.wr)
}
// canSendNoData returns true if describing a result of the input statement
// type should return NoData.
func canSendNoData(statementType parser.StatementType) bool {
return statementType != parser.Rows
}
func (c *v3Conn) handleDescribe(ctx context.Context, buf *readBuffer) error {
typ, err := buf.getPrepareType()
if err != nil {
return c.sendError(err)
}
name, err := buf.getString()
if err != nil {
return err
}
switch typ {
case prepareStatement:
stmt, ok := c.session.PreparedStatements.Get(name)
if !ok {
return c.sendInternalError(fmt.Sprintf("unknown prepared statement %q", name))
}
stmtMeta := stmt.ProtocolMeta.(preparedStatementMeta)
c.writeBuf.initMsg(serverMsgParameterDescription)
c.writeBuf.putInt16(int16(len(stmtMeta.inTypes)))
for _, t := range stmtMeta.inTypes {
c.writeBuf.putInt32(int32(t))
}
if err := c.writeBuf.finishMsg(c.wr); err != nil {
return err
}
return c.sendRowDescription(ctx, stmt.Columns, nil, canSendNoData(stmt.Type))
case preparePortal:
portal, ok := c.session.PreparedPortals.Get(name)
if !ok {
return c.sendInternalError(fmt.Sprintf("unknown portal %q", name))
}
portalMeta := portal.ProtocolMeta.(preparedPortalMeta)
return c.sendRowDescription(ctx, portal.Stmt.Columns, portalMeta.outFormats, canSendNoData(portal.Stmt.Type))
default:
return errors.Errorf("unknown describe type: %s", typ)
}
}
func (c *v3Conn) handleClose(buf *readBuffer) error {
typ, err := buf.getPrepareType()
if err != nil {
return c.sendError(err)
}
name, err := buf.getString()
if err != nil {
return err
}
switch typ {
case prepareStatement:
c.session.PreparedStatements.Delete(name)
case preparePortal:
c.session.PreparedPortals.Delete(name)
default:
return errors.Errorf("unknown close type: %s", typ)
}
c.writeBuf.initMsg(serverMsgCloseComplete)
return c.writeBuf.finishMsg(c.wr)
}
func (c *v3Conn) handleBind(buf *readBuffer) error {
portalName, err := buf.getString()
if err != nil {
return err
}
// The unnamed portal can be freely overwritten.
if portalName != "" {
if c.session.PreparedPortals.Exists(portalName) {
return c.sendInternalError(fmt.Sprintf("portal %q already exists", portalName))
}
}
statementName, err := buf.getString()
if err != nil {
return err
}
stmt, ok := c.session.PreparedStatements.Get(statementName)
if !ok {
return c.sendInternalError(fmt.Sprintf("unknown prepared statement %q", statementName))
}
stmtMeta := stmt.ProtocolMeta.(preparedStatementMeta)
numQArgs := uint16(len(stmtMeta.inTypes))
qArgFormatCodes := make([]formatCode, numQArgs)
// From the docs on number of argument format codes to bind:
// This can be zero to indicate that there are no arguments or that the
// arguments all use the default format (text); or one, in which case the
// specified format code is applied to all arguments; or it can equal the
// actual number of arguments.
// http://www.postgresql.org/docs/current/static/protocol-message-formats.html
numQArgFormatCodes, err := buf.getUint16()
if err != nil {
return err
}
switch numQArgFormatCodes {
case 0:
case 1:
// `1` means read one code and apply it to every argument.
c, err := buf.getUint16()
if err != nil {
return err
}
fmtCode := formatCode(c)
for i := range qArgFormatCodes {
qArgFormatCodes[i] = fmtCode
}
case numQArgs:
// Read one format code for each argument and apply it to that argument.
for i := range qArgFormatCodes {
c, err := buf.getUint16()
if err != nil {
return err
}
qArgFormatCodes[i] = formatCode(c)
}
default:
return c.sendInternalError(fmt.Sprintf("wrong number of format codes specified: %d for %d arguments", numQArgFormatCodes, numQArgs))
}
numValues, err := buf.getUint16()
if err != nil {
return err
}
if numValues != numQArgs {
return c.sendInternalError(fmt.Sprintf("expected %d arguments, got %d", numQArgs, numValues))
}
qargs := parser.QueryArguments{}
for i, t := range stmtMeta.inTypes {
plen, err := buf.getUint32()
if err != nil {
return err
}
k := strconv.Itoa(i + 1)
if int32(plen) == -1 {
// The argument is a NULL value.
qargs[k] = parser.DNull
continue
}
b, err := buf.getBytes(int(plen))
if err != nil {
return err
}
d, err := decodeOidDatum(t, qArgFormatCodes[i], b)
if err != nil {
return c.sendInternalError(fmt.Sprintf("error in argument for $%d: %s", i+1, err))
}
qargs[k] = d
}
numColumns := uint16(len(stmt.Columns))
columnFormatCodes := make([]formatCode, numColumns)
// From the docs on number of result-column format codes to bind:
// This can be zero to indicate that there are no result columns or that
// the result columns should all use the default format (text); or one, in
// which case the specified format code is applied to all result columns
// (if any); or it can equal the actual number of result columns of the
// query.
// http://www.postgresql.org/docs/current/static/protocol-message-formats.html
numColumnFormatCodes, err := buf.getUint16()
if err != nil {
return err
}
switch numColumnFormatCodes {
case 0:
case 1:
// Read one code and apply it to every column.
c, err := buf.getUint16()
if err != nil {
return err
}
fmtCode := formatCode(c)
for i := range columnFormatCodes {
columnFormatCodes[i] = fmtCode
}
case numColumns:
// Read one format code for each column and apply it to that column.
for i := range columnFormatCodes {
c, err := buf.getUint16()
if err != nil {
return err
}
columnFormatCodes[i] = formatCode(c)
}
default:
return c.sendInternalError(fmt.Sprintf("expected 0, 1, or %d for number of format codes, got %d", numColumns, numColumnFormatCodes))
}
// Create the new PreparedPortal in the connection's Session.
portal, err := c.session.PreparedPortals.New(portalName, stmt, qargs)
if err != nil {
return err
}
// Attach pgwire-specific metadata to the PreparedPortal.
portal.ProtocolMeta = preparedPortalMeta{outFormats: columnFormatCodes}
c.writeBuf.initMsg(serverMsgBindComplete)
return c.writeBuf.finishMsg(c.wr)
}
func (c *v3Conn) handleExecute(ctx context.Context, buf *readBuffer) error {
portalName, err := buf.getString()
if err != nil {
return err
}
portal, ok := c.session.PreparedPortals.Get(portalName)
if !ok {
return c.sendInternalError(fmt.Sprintf("unknown portal %q", portalName))
}
limit, err := buf.getUint32()
if err != nil {
return err
}
stmt := portal.Stmt
portalMeta := portal.ProtocolMeta.(preparedPortalMeta)
pinfo := parser.PlaceholderInfo{
Types: stmt.SQLTypes,
Values: portal.Qargs,
}
return c.executeStatements(ctx, stmt.Query, &pinfo, portalMeta.outFormats, false, int(limit))
}
func (c *v3Conn) executeStatements(
ctx context.Context,
stmts string,
pinfo *parser.PlaceholderInfo,
formatCodes []formatCode,
sendDescription bool,
limit int,
) error {
tracing.AnnotateTrace()
// Note: sql.Executor gets its Context from c.session.context, which
// has been bound by v3Conn.setupSession().
results := c.executor.ExecuteStatements(c.session, stmts, pinfo)
defer results.Close()
tracing.AnnotateTrace()
if results.Empty {
// Skip executor and just send EmptyQueryResponse.
c.writeBuf.initMsg(serverMsgEmptyQuery)
return c.writeBuf.finishMsg(c.wr)
}
return c.sendResponse(ctx, results.ResultList, formatCodes, sendDescription, limit)
}
func (c *v3Conn) sendCommandComplete(tag []byte) error {
c.writeBuf.initMsg(serverMsgCommandComplete)
c.writeBuf.write(tag)
c.writeBuf.nullTerminate()
return c.writeBuf.finishMsg(c.wr)
}
// TODO(andrei): Figure out the correct codes to send for all the errors
// in this file and remove this function.
func (c *v3Conn) sendInternalError(errToSend string) error {
err := errors.Errorf(errToSend)
err = pgerror.WithPGCode(err, pgerror.CodeInternalError)
err = pgerror.WithSourceContext(err, 1)
return c.sendError(err)
}
func (c *v3Conn) sendError(err error) error {
if c.doingExtendedQueryMessage {
c.ignoreTillSync = true
}
c.writeBuf.initMsg(serverMsgErrorResponse)
c.writeBuf.putErrFieldMsg(serverErrFieldSeverity)
c.writeBuf.writeTerminatedString("ERROR")
code, ok := pgerror.PGCode(err)
if !ok {
code = pgerror.CodeInternalError
}
c.writeBuf.putErrFieldMsg(serverErrFieldSQLState)
c.writeBuf.writeTerminatedString(code)
if detail, ok := pgerror.Detail(err); ok {
c.writeBuf.putErrFieldMsg(serverErrFileldDetail)
c.writeBuf.writeTerminatedString(detail)
}
if hint, ok := pgerror.Hint(err); ok {
c.writeBuf.putErrFieldMsg(serverErrFileldHint)
c.writeBuf.writeTerminatedString(hint)
}
if errCtx, ok := pgerror.SourceContext(err); ok {
if errCtx.File != "" {
c.writeBuf.putErrFieldMsg(serverErrFieldSrcFile)
c.writeBuf.writeTerminatedString(errCtx.File)
}
if errCtx.Line > 0 {
c.writeBuf.putErrFieldMsg(serverErrFieldSrcLine)
c.writeBuf.writeTerminatedString(strconv.Itoa(errCtx.Line))
}
if errCtx.Function != "" {
c.writeBuf.putErrFieldMsg(serverErrFieldSrcFunction)
c.writeBuf.writeTerminatedString(errCtx.Function)
}
}
c.writeBuf.putErrFieldMsg(serverErrFieldMsgPrimary)
c.writeBuf.writeTerminatedString(err.Error())
c.writeBuf.nullTerminate()
if err := c.writeBuf.finishMsg(c.wr); err != nil {
return err
}
return c.wr.Flush()
}
// sendResponse sends the results as a query response.
func (c *v3Conn) sendResponse(
ctx context.Context,
results sql.ResultList,
formatCodes []formatCode,
sendDescription bool,
limit int,
) error {
if len(results) == 0 {
return c.sendCommandComplete(nil)
}
for _, result := range results {
if result.Err != nil {
if err := c.sendError(result.Err); err != nil {
return err
}
break
}
if limit != 0 && result.Rows != nil && result.Rows.Len() > limit {
if err := c.sendInternalError(fmt.Sprintf("execute row count limits not supported: %d of %d", limit, result.Rows.Len())); err != nil {
return err
}
break
}
if result.PGTag == "INSERT" {
// From the postgres docs (49.5. Message Formats):
// `INSERT oid rows`... oid is the object ID of the inserted row if
// rows is 1 and the target table has OIDs; otherwise oid is 0.
result.PGTag = "INSERT 0"
}
tag := append(c.tagBuf[:0], result.PGTag...)
switch result.Type {
case parser.RowsAffected:
// Send CommandComplete.
tag = append(tag, ' ')
tag = strconv.AppendInt(tag, int64(result.RowsAffected), 10)
if err := c.sendCommandComplete(tag); err != nil {
return err
}
case parser.Rows:
if sendDescription {
// We're not allowed to send a NoData message here, even if there are
// 0 result columns, since we're responding to a "Simple Query".
if err := c.sendRowDescription(ctx, result.Columns, formatCodes, false); err != nil {
return err
}
}
// Send DataRows.
nRows := result.Rows.Len()
for rowIdx := 0; rowIdx < nRows; rowIdx++ {
row := result.Rows.At(rowIdx)
c.writeBuf.initMsg(serverMsgDataRow)
c.writeBuf.putInt16(int16(len(row)))
for i, col := range row {
fmtCode := formatText
if formatCodes != nil {
fmtCode = formatCodes[i]
}
switch fmtCode {
case formatText:
c.writeBuf.writeTextDatum(col, c.session.Location)
case formatBinary:
c.writeBuf.writeBinaryDatum(col, c.session.Location)
default:
c.writeBuf.setError(errors.Errorf("unsupported format code %s", fmtCode))
}
}
if err := c.writeBuf.finishMsg(c.wr); err != nil {
return err
}
}
// Send CommandComplete.
tag = append(tag, ' ')
tag = strconv.AppendUint(tag, uint64(result.Rows.Len()), 10)
if err := c.sendCommandComplete(tag); err != nil {
return err
}
case parser.Ack, parser.DDL:
if err := c.sendCommandComplete(tag); err != nil {
return err
}
case parser.CopyIn:
rows, err := c.copyIn(result.Columns)
if err != nil {
return err
}
// Send CommandComplete.
tag = append(tag, ' ')
tag = strconv.AppendInt(tag, rows, 10)
if err := c.sendCommandComplete(tag); err != nil {
return err
}