-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
conn.go
1640 lines (1482 loc) · 50.9 KB
/
conn.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 2018 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.
package pgwire
import (
"bufio"
"bytes"
"context"
"crypto/tls"
"fmt"
"io"
"net"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/hba"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgwirebase"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sem/types"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/sql/sqltelemetry"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/log/logtags"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/lib/pq/oid"
"github.com/pkg/errors"
)
const (
authOK int32 = 0
authCleartextPassword int32 = 3
)
// conn implements a pgwire network connection (version 3 of the protocol,
// implemented by Postgres v7.4 and later). conn.serve() reads protocol
// messages, transforms them into commands that it pushes onto a StmtBuf (where
// they'll be picked up and executed by the connExecutor).
// The connExecutor produces results for the commands, which are delivered to
// the client through the sql.ClientComm interface, implemented by this conn
// (code is in command_result.go).
type conn struct {
conn net.Conn
sessionArgs sql.SessionArgs
metrics *ServerMetrics
// rd is a buffered reader consuming conn. All reads from conn go through
// this.
rd bufio.Reader
// parser is used to avoid allocating a parser each time.
parser parser.Parser
// stmtBuf is populated with commands queued for execution by this conn.
stmtBuf sql.StmtBuf
// err is an error, accessed atomically. It represents any error encountered
// while accessing the underlying network connection. This can read via
// GetErr() by anybody. If it is found to be != nil, the conn is no longer to
// be used.
err atomic.Value
// writerState groups together all aspects of the write-side state of the
// connection.
writerState struct {
fi flushInfo
// buf contains command results (rows, etc.) until they're flushed to the
// network connection.
buf bytes.Buffer
tagBuf [64]byte
}
readBuf pgwirebase.ReadBuffer
msgBuilder writeBuffer
sv *settings.Values
}
// serveConn creates a conn that will serve the netConn. It returns once the
// network connection is closed.
//
// Internally, a connExecutor will be created to execute commands. Commands read
// from the network are buffered in a stmtBuf which is consumed by the
// connExecutor. The connExecutor produces results which are buffered and
// sometimes synchronously flushed to the network.
//
// The reader goroutine (this one) outlives the connExecutor's goroutine (the
// "processor goroutine").
// However, they can both signal each other to stop. Here's how the different
// cases work:
// 1) The reader receives a ClientMsgTerminate protocol packet: the reader
// closes the stmtBuf and also cancels the command processing context. These
// actions will prompt the command processor to finish.
// 2) The reader gets a read error from the network connection: like above, the
// reader closes the command processor.
// 3) The reader's context is canceled (happens when the server is draining but
// the connection was busy and hasn't quit yet): the reader notices the canceled
// context and, like above, closes the processor.
// 4) The processor encouters an error. This error can come from various fatal
// conditions encoutered internally by the processor, or from a network
// communication error encountered while flushing results to the network.
// The processor will cancel the reader's context and terminate.
// Note that query processing errors are different; they don't cause the
// termination of the connection.
//
// Draining notes:
//
// The reader notices that the server is draining by polling the draining()
// closure passed to serveConn. At that point, the reader delegates the
// responsibility of closing the connection to the statement processor: it will
// push a DrainRequest to the stmtBuf which signal the processor to quit ASAP.
// The processor will quit immediately upon seeing that command if it's not
// currently in a transaction. If it is in a transaction, it will wait until the
// first time a Sync command is processed outside of a transaction - the logic
// being that we want to stop when we're both outside transactions and outside
// batches.
func serveConn(
ctx context.Context,
netConn net.Conn,
sArgs sql.SessionArgs,
metrics *ServerMetrics,
reserved mon.BoundAccount,
sqlServer *sql.Server,
draining func() bool,
ie *sql.InternalExecutor,
stopper *stop.Stopper,
insecure bool,
auth *hba.Conf,
) error {
sArgs.RemoteAddr = netConn.RemoteAddr()
if log.V(2) {
log.Infof(ctx, "new connection with options: %+v", sArgs)
}
c := newConn(netConn, sArgs, metrics, &sqlServer.GetExecutorConfig().Settings.SV)
if err := c.handleAuthentication(ctx, insecure, ie, auth, sqlServer.GetExecutorConfig()); err != nil {
_ = c.conn.Close()
reserved.Close(ctx)
return err
}
// Do the reading of commands from the network.
readingErr := c.serveImpl(ctx, draining, sqlServer, reserved, stopper)
return readingErr
}
func newConn(
netConn net.Conn, sArgs sql.SessionArgs, metrics *ServerMetrics, sv *settings.Values,
) *conn {
c := &conn{
conn: netConn,
sessionArgs: sArgs,
metrics: metrics,
rd: *bufio.NewReader(netConn),
sv: sv,
}
c.stmtBuf.Init()
c.writerState.fi.buf = &c.writerState.buf
c.writerState.fi.lastFlushed = -1
c.writerState.fi.cmdStarts = make(map[sql.CmdPos]int)
c.msgBuilder.init(metrics.BytesOutCount)
return c
}
func (c *conn) setErr(err error) {
c.err.Store(err)
}
func (c *conn) GetErr() error {
err := c.err.Load()
if err != nil {
return err.(error)
}
return nil
}
// serveImpl continuously reads from the network connection and pushes execution
// instructions into a sql.StmtBuf.
// The method returns when the pgwire termination message is received, when
// network communication fails, when the server is draining or when ctx is
// canceled (which also happens when draining, but not from the get-go).
//
// serveImpl always closes the network connection before returning.
//
// sqlServer is used to create the command processor. As a special facility for
// tests, sqlServer can be nil, in which case the command processor and the
// write-side of the connection will not be created.
func (c *conn) serveImpl(
ctx context.Context,
draining func() bool,
sqlServer *sql.Server,
reserved mon.BoundAccount,
stopper *stop.Stopper,
) error {
defer func() { _ = c.conn.Close() }()
ctx = logtags.AddTag(ctx, "user", c.sessionArgs.User)
// NOTE: We're going to write a few messages to the connection in this method,
// for the handshake. After that, all writes are done async, in the
// startWriter() goroutine.
sendStatusParam := func(param, value string) error {
c.msgBuilder.initMsg(pgwirebase.ServerMsgParameterStatus)
c.msgBuilder.writeTerminatedString(param)
c.msgBuilder.writeTerminatedString(value)
return c.msgBuilder.finishMsg(c.conn)
}
var connHandler sql.ConnectionHandler
if sqlServer != nil {
var err error
connHandler, err = sqlServer.SetupConn(
ctx, c.sessionArgs, &c.stmtBuf, c, c.metrics.SQLMemMetrics)
if err != nil {
_ /* err */ = writeErr(ctx, &sqlServer.GetExecutorConfig().Settings.SV,
err, &c.msgBuilder, c.conn)
return err
}
// Send the initial "status parameters" to the client. This
// overlaps partially with session variables. The client wants to
// see the values that result of the combination of server-side
// defaults with client-provided values.
// For details see: https://www.postgresql.org/docs/10/static/libpq-status.html
for _, param := range statusReportParams {
value := connHandler.GetStatusParam(ctx, param)
if err := sendStatusParam(param, value); err != nil {
return err
}
}
// The two following status parameters have no equivalent session
// variable.
if err := sendStatusParam("session_authorization", c.sessionArgs.User); err != nil {
return err
}
// TODO(knz): this should retrieve the admin status during
// authentication using the roles table, instead of using a
// simple/naive username match.
isSuperUser := c.sessionArgs.User == security.RootUser
superUserVal := "off"
if isSuperUser {
superUserVal = "on"
}
if err := sendStatusParam("is_superuser", superUserVal); err != nil {
return err
}
} else {
// sqlServer == nil means we are in a local test. In this case
// we only need the minimum to make pgx happy.
for param, value := range testingStatusReportParams {
if err := sendStatusParam(param, value); err != nil {
return err
}
}
}
// An initial readyForQuery message is part of the handshake.
c.msgBuilder.initMsg(pgwirebase.ServerMsgReady)
c.msgBuilder.writeByte(byte(sql.IdleTxnBlock))
if err := c.msgBuilder.finishMsg(c.conn); err != nil {
return err
}
ctx, cancelConn := context.WithCancel(ctx)
defer cancelConn() // This calms the linter that wants these callbacks to always be called.
var ctxCanceled bool
// Once a session has been set up, the underlying net.Conn is switched to
// a conn that exits if the session's context is canceled.
c.conn = newReadTimeoutConn(c.conn, func() error {
// If the context was closed, it's time to bail. Either a higher-level
// server or the command processor have canceled us.
if ctx.Err() != nil {
ctxCanceled = true
return ctx.Err()
}
// If the server is draining, we'll let the processor know by pushing a
// DrainRequest. This will make the processor quit whenever it finds a good
// time.
if draining() {
_ /* err */ = c.stmtBuf.Push(ctx, sql.DrainRequest{})
}
return nil
})
c.rd = *bufio.NewReader(c.conn)
var wg sync.WaitGroup
var writerErr error
if sqlServer != nil {
wg.Add(1)
go func() {
defer func() {
if sqlServer.GetExecutorConfig().TestingKnobs.CatchPanics {
if r := recover(); r != nil {
// Catch the panic and return it to the client as an error.
err := pgerror.NewAssertionErrorf("caught fatal error: %v", r)
_ = writeErr(ctx, &sqlServer.GetExecutorConfig().Settings.SV,
err, &c.msgBuilder, &c.writerState.buf)
_ /* n */, _ /* err */ = c.writerState.buf.WriteTo(c.conn)
c.stmtBuf.Close()
// Send a ready for query to make sure the client can react.
c.bufferReadyForQuery('I')
}
}
wg.Done()
cancelConn()
}()
writerErr = sqlServer.ServeConn(ctx, connHandler, reserved, cancelConn)
// TODO(andrei): Should we sometimes transmit the writerErr's to the
// client?
}()
}
var err error
var terminateSeen bool
var doingExtendedQueryMessage bool
Loop:
for {
var typ pgwirebase.ClientMessageType
var n int
typ, n, err = c.readBuf.ReadTypedMsg(&c.rd)
c.metrics.BytesInCount.Inc(int64(n))
if err != nil {
break Loop
}
if log.V(2) {
log.Infof(ctx, "pgwire: processing %s", typ)
}
timeReceived := timeutil.Now()
switch typ {
case pgwirebase.ClientMsgSimpleQuery:
if doingExtendedQueryMessage {
if err = c.stmtBuf.Push(
ctx,
sql.SendError{
Err: pgwirebase.NewProtocolViolationErrorf(
"SimpleQuery not allowed while in extended protocol mode"),
},
); err != nil {
break
}
}
if err = c.handleSimpleQuery(ctx, &c.readBuf, timeReceived, connHandler); err != nil {
break
}
err = c.stmtBuf.Push(ctx, sql.Sync{})
case pgwirebase.ClientMsgExecute:
doingExtendedQueryMessage = true
err = c.handleExecute(ctx, &c.readBuf, timeReceived)
case pgwirebase.ClientMsgParse:
doingExtendedQueryMessage = true
err = c.handleParse(ctx, &c.readBuf, connHandler)
case pgwirebase.ClientMsgDescribe:
doingExtendedQueryMessage = true
err = c.handleDescribe(ctx, &c.readBuf)
case pgwirebase.ClientMsgBind:
doingExtendedQueryMessage = true
err = c.handleBind(ctx, &c.readBuf)
case pgwirebase.ClientMsgClose:
doingExtendedQueryMessage = true
err = c.handleClose(ctx, &c.readBuf)
case pgwirebase.ClientMsgTerminate:
terminateSeen = true
break Loop
case pgwirebase.ClientMsgSync:
doingExtendedQueryMessage = false
// We're starting a batch here. If the client continues using the extended
// protocol and encounters an error, everything until the next sync
// message has to be skipped. See:
// https://www.postgresql.org/docs/current/10/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY
err = c.stmtBuf.Push(ctx, sql.Sync{})
case pgwirebase.ClientMsgFlush:
doingExtendedQueryMessage = true
err = c.handleFlush(ctx)
case pgwirebase.ClientMsgCopyData, pgwirebase.ClientMsgCopyDone, pgwirebase.ClientMsgCopyFail:
// We're supposed to ignore these messages, per the protocol spec. This
// state will happen when an error occurs on the server-side during a copy
// operation: the server will send an error and a ready message back to
// the client, and must then ignore further copy messages. See:
// https://github.com/postgres/postgres/blob/6e1dd2773eb60a6ab87b27b8d9391b756e904ac3/src/backend/tcop/postgres.c#L4295
default:
err = c.stmtBuf.Push(
ctx,
sql.SendError{Err: pgwirebase.NewUnrecognizedMsgTypeErr(typ)})
}
if err != nil {
break Loop
}
}
// Signal command processing to stop. It might be the case that the processor
// canceled our context and that's how we got here; in that case, this will
// be a no-op.
c.stmtBuf.Close()
cancelConn() // This cancels the processor's context.
wg.Wait()
if terminateSeen {
return nil
}
// If we're draining, let the client know by piling on an AdminShutdownError
// and flushing the buffer.
if ctxCanceled || draining() {
_ /* err */ = writeErr(ctx, &sqlServer.GetExecutorConfig().Settings.SV,
newAdminShutdownErr(err), &c.msgBuilder, &c.writerState.buf)
_ /* n */, _ /* err */ = c.writerState.buf.WriteTo(c.conn)
// Swallow whatever error we might have gotten from the writer. If we're
// draining, it's probably a canceled context error.
return nil
}
if writerErr != nil {
return writerErr
}
return nil
}
// An error is returned iff the statement buffer has been closed. In that case,
// the connection should be considered toast.
func (c *conn) handleSimpleQuery(
ctx context.Context, buf *pgwirebase.ReadBuffer, timeReceived time.Time, ch sql.ConnectionHandler,
) error {
query, err := buf.GetString()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
tracing.AnnotateTrace()
startParse := timeutil.Now()
stmts, err := c.parser.ParseWithInt(query, ch.GetDefaultIntSize())
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
endParse := timeutil.Now()
if len(stmts) == 0 {
return c.stmtBuf.Push(
ctx, sql.ExecStmt{
Statement: parser.Statement{},
TimeReceived: timeReceived,
ParseStart: startParse,
ParseEnd: endParse,
})
}
for i := range stmts {
// The CopyFrom statement is special. We need to detect it so we can hand
// control of the connection, through the stmtBuf, to a copyMachine, and
// block this network routine until control is passed back.
if cp, ok := stmts[i].AST.(*tree.CopyFrom); ok {
if len(stmts) != 1 {
// NOTE(andrei): I don't know if Postgres supports receiving a COPY
// together with other statements in the "simple" protocol, but I'd
// rather not worry about it since execution of COPY is special - it
// takes control over the connection.
return c.stmtBuf.Push(
ctx,
sql.SendError{
Err: pgwirebase.NewProtocolViolationErrorf(
"COPY together with other statements in a query string is not supported"),
})
}
copyDone := sync.WaitGroup{}
copyDone.Add(1)
if err := c.stmtBuf.Push(ctx, sql.CopyIn{Conn: c, Stmt: cp, CopyDone: ©Done}); err != nil {
return err
}
copyDone.Wait()
return nil
}
if err := c.stmtBuf.Push(
ctx,
sql.ExecStmt{
Statement: stmts[i],
TimeReceived: timeReceived,
ParseStart: startParse,
ParseEnd: endParse,
}); err != nil {
return err
}
}
return nil
}
// An error is returned iff the statement buffer has been closed. In that case,
// the connection should be considered toast.
func (c *conn) handleParse(
ctx context.Context, buf *pgwirebase.ReadBuffer, ch sql.ConnectionHandler,
) error {
// protocolErr is set if a protocol error has to be sent to the client. A
// stanza at the bottom of the function pushes instructions for sending this
// error.
var protocolErr *pgerror.Error
name, err := buf.GetString()
if protocolErr != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
query, err := buf.GetString()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
// The client may provide type information for (some of) the placeholders.
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 c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
inTypeHints[i] = oid.Oid(typ)
}
startParse := timeutil.Now()
stmts, err := c.parser.ParseWithInt(query, ch.GetDefaultIntSize())
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
if len(stmts) > 1 {
err := pgerror.NewWrongNumberOfPreparedStatements(len(stmts))
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
var stmt parser.Statement
if len(stmts) == 1 {
stmt = stmts[0]
}
// len(stmts) == 0 results in a nil (empty) statement.
if len(inTypeHints) > stmt.NumPlaceholders {
err := pgwirebase.NewProtocolViolationErrorf(
"received too many type hints: %d vs %d placeholders in query",
len(inTypeHints), stmt.NumPlaceholders,
)
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
var sqlTypeHints tree.PlaceholderTypes
if len(inTypeHints) > 0 {
// Prepare the mapping of SQL placeholder names to types. Pre-populate it with
// the type hints received from the client, if any.
sqlTypeHints = make(tree.PlaceholderTypes, stmt.NumPlaceholders)
for i, t := range inTypeHints {
if t == 0 {
continue
}
v, ok := types.OidToType[t]
if !ok {
err := pgwirebase.NewProtocolViolationErrorf("unknown oid type: %v", t)
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
sqlTypeHints[i] = v
}
}
endParse := timeutil.Now()
if _, ok := stmt.AST.(*tree.CopyFrom); ok {
// We don't support COPY in extended protocol because it'd be complicated:
// it wouldn't be the preparing, but the execution that would need to
// execute the copyMachine.
// Also note that COPY FROM in extended mode seems to be quite broken in
// Postgres too:
// https://www.postgresql.org/message-id/flat/CAMsr%2BYGvp2wRx9pPSxaKFdaObxX8DzWse%2BOkWk2xpXSvT0rq-g%40mail.gmail.com#CAMsr+YGvp2wRx9pPSxaKFdaObxX8DzWse+OkWk2xpXSvT0rq-g@mail.gmail.com
return c.stmtBuf.Push(ctx, sql.SendError{Err: fmt.Errorf("CopyFrom not supported in extended protocol mode")})
}
return c.stmtBuf.Push(
ctx,
sql.PrepareStmt{
Name: name,
Statement: stmt,
TypeHints: sqlTypeHints,
RawTypeHints: inTypeHints,
ParseStart: startParse,
ParseEnd: endParse,
})
}
// An error is returned iff the statement buffer has been closed. In that case,
// the connection should be considered toast.
func (c *conn) handleDescribe(ctx context.Context, buf *pgwirebase.ReadBuffer) error {
typ, err := buf.GetPrepareType()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
name, err := buf.GetString()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
return c.stmtBuf.Push(
ctx,
sql.DescribeStmt{
Name: name,
Type: typ,
})
}
// An error is returned iff the statement buffer has been closed. In that case,
// the connection should be considered toast.
func (c *conn) handleClose(ctx context.Context, buf *pgwirebase.ReadBuffer) error {
typ, err := buf.GetPrepareType()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
name, err := buf.GetString()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
return c.stmtBuf.Push(
ctx,
sql.DeletePreparedStmt{
Name: name,
Type: typ,
})
}
// handleBind queues instructions for creating a portal from a prepared
// statement.
// An error is returned iff the statement buffer has been closed. In that case,
// the connection should be considered toast.
func (c *conn) handleBind(ctx context.Context, buf *pgwirebase.ReadBuffer) error {
portalName, err := buf.GetString()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
statementName, err := buf.GetString()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
// 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 c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
lenCodes := numQArgFormatCodes
if lenCodes == 0 {
lenCodes = 1
}
qArgFormatCodes := make([]pgwirebase.FormatCode, lenCodes)
switch numQArgFormatCodes {
case 0:
// No format codes means all arguments are passed as text.
qArgFormatCodes[0] = pgwirebase.FormatText
case 1:
// `1` means read one code and apply it to every argument.
ch, err := buf.GetUint16()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
fmtCode := pgwirebase.FormatCode(ch)
qArgFormatCodes[0] = fmtCode
default:
// Read one format code for each argument and apply it to that argument.
for i := range qArgFormatCodes {
code, err := buf.GetUint16()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
qArgFormatCodes[i] = pgwirebase.FormatCode(code)
}
}
numValues, err := buf.GetUint16()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
qargs := make([][]byte, numValues)
for i := 0; i < int(numValues); i++ {
plen, err := buf.GetUint32()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
if int32(plen) == -1 {
// The argument is a NULL value.
qargs[i] = nil
continue
}
b, err := buf.GetBytes(int(plen))
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
qargs[i] = b
}
// 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 c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
var columnFormatCodes []pgwirebase.FormatCode
switch numColumnFormatCodes {
case 0:
// All columns will use the text format.
columnFormatCodes = make([]pgwirebase.FormatCode, 1)
columnFormatCodes[0] = pgwirebase.FormatText
case 1:
// All columns will use the one specficied format.
ch, err := buf.GetUint16()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
fmtCode := pgwirebase.FormatCode(ch)
columnFormatCodes = make([]pgwirebase.FormatCode, 1)
columnFormatCodes[0] = fmtCode
default:
columnFormatCodes = make([]pgwirebase.FormatCode, numColumnFormatCodes)
// Read one format code for each column and apply it to that column.
for i := range columnFormatCodes {
ch, err := buf.GetUint16()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
columnFormatCodes[i] = pgwirebase.FormatCode(ch)
}
}
return c.stmtBuf.Push(
ctx,
sql.BindStmt{
PreparedStatementName: statementName,
PortalName: portalName,
Args: qargs,
ArgFormatCodes: qArgFormatCodes,
OutFormats: columnFormatCodes,
})
}
// An error is returned iff the statement buffer has been closed. In that case,
// the connection should be considered toast.
func (c *conn) handleExecute(
ctx context.Context, buf *pgwirebase.ReadBuffer, timeReceived time.Time,
) error {
portalName, err := buf.GetString()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
limit, err := buf.GetUint32()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
return c.stmtBuf.Push(ctx, sql.ExecPortal{
Name: portalName,
TimeReceived: timeReceived,
Limit: int(limit),
})
}
func (c *conn) handleFlush(ctx context.Context) error {
return c.stmtBuf.Push(ctx, sql.Flush{})
}
// BeginCopyIn is part of the pgwirebase.Conn interface.
func (c *conn) BeginCopyIn(ctx context.Context, columns []sqlbase.ResultColumn) error {
c.msgBuilder.initMsg(pgwirebase.ServerMsgCopyInResponse)
c.msgBuilder.writeByte(byte(pgwirebase.FormatText))
c.msgBuilder.putInt16(int16(len(columns)))
for range columns {
c.msgBuilder.putInt16(int16(pgwirebase.FormatText))
}
return c.msgBuilder.finishMsg(c.conn)
}
// SendCommandComplete is part of the pgwirebase.Conn interface.
func (c *conn) SendCommandComplete(tag []byte) error {
c.bufferCommandComplete(tag)
return nil
}
// Rd is part of the pgwirebase.Conn interface.
func (c *conn) Rd() pgwirebase.BufferedReader {
return &pgwireReader{conn: c}
}
// flushInfo encapsulates information about what results have been flushed to
// the network.
type flushInfo struct {
// buf is a reference to writerState.buf.
buf *bytes.Buffer
// lastFlushed indicates the highest command for which results have been
// flushed. The command may have further results in the buffer that haven't
// been flushed.
lastFlushed sql.CmdPos
// map from CmdPos to the index of the buffer where the results for the
// respective result begins.
cmdStarts map[sql.CmdPos]int
}
// registerCmd updates cmdStarts when the first result for a new command is
// received.
func (fi *flushInfo) registerCmd(pos sql.CmdPos) {
if _, ok := fi.cmdStarts[pos]; ok {
return
}
fi.cmdStarts[pos] = fi.buf.Len()
}
// convertToErrWithPGCode recognizes errs that should have SQL error codes to be
// reported to the client and converts err to them. If this doesn't apply, err
// is returned.
// Note that this returns a new error, and details from the original error are
// not preserved in any way (except possibly the message).
//
// TODO(andrei): sqlbase.ConvertBatchError() seems to serve similar purposes, but
// it's called from more specialized contexts. Consider unifying the two.
func convertToErrWithPGCode(err error) error {
if err == nil {
return nil
}
switch tErr := err.(type) {
case *roachpb.TransactionRetryWithProtoRefreshError:
return sqlbase.NewRetryError(err)
case *roachpb.AmbiguousResultError:
// TODO(andrei): Once DistSQL starts executing writes, we'll need a
// different mechanism to marshal AmbiguousResultErrors from the executing
// nodes.
return sqlbase.NewStatementCompletionUnknownError(tErr)
default:
return err
}
}
func cookTag(tagStr string, buf []byte, stmtType tree.StatementType, rowsAffected int) []byte {
if tagStr == "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.
tagStr = "INSERT 0"
}
tag := append(buf, tagStr...)
switch stmtType {
case tree.RowsAffected:
tag = append(tag, ' ')
tag = strconv.AppendInt(tag, int64(rowsAffected), 10)
case tree.Rows:
tag = append(tag, ' ')
tag = strconv.AppendUint(tag, uint64(rowsAffected), 10)
case tree.Ack, tree.DDL:
if tagStr == "SELECT" {
tag = append(tag, ' ')
tag = strconv.AppendInt(tag, int64(rowsAffected), 10)
}
case tree.CopyIn:
// Nothing to do. The CommandComplete message has been sent elsewhere.
panic(fmt.Sprintf("CopyIn statements should have been handled elsewhere " +
"and not produce results"))
default:
panic(fmt.Sprintf("unexpected result type %v", stmtType))
}
return tag
}
// bufferRow serializes a row and adds it to the buffer.
//
// formatCodes describes the desired encoding for each column. It can be nil, in
// which case all columns are encoded using the text encoding. Otherwise, it
// needs to contain an entry for every column.
func (c *conn) bufferRow(
ctx context.Context,
row tree.Datums,
formatCodes []pgwirebase.FormatCode,
conv sessiondata.DataConversionConfig,
oids []oid.Oid,
) {
c.msgBuilder.initMsg(pgwirebase.ServerMsgDataRow)
c.msgBuilder.putInt16(int16(len(row)))
for i, col := range row {
fmtCode := pgwirebase.FormatText
if formatCodes != nil {
fmtCode = formatCodes[i]
}
switch fmtCode {
case pgwirebase.FormatText:
c.msgBuilder.writeTextDatum(ctx, col, conv)
case pgwirebase.FormatBinary:
c.msgBuilder.writeBinaryDatum(ctx, col, conv.Location, oids[i])
default:
c.msgBuilder.setError(errors.Errorf("unsupported format code %s", fmtCode))
}
}
if err := c.msgBuilder.finishMsg(&c.writerState.buf); err != nil {
panic(fmt.Sprintf("unexpected err from buffer: %s", err))
}
}
func (c *conn) bufferReadyForQuery(txnStatus byte) {
c.msgBuilder.initMsg(pgwirebase.ServerMsgReady)
c.msgBuilder.writeByte(txnStatus)
if err := c.msgBuilder.finishMsg(&c.writerState.buf); err != nil {
panic(fmt.Sprintf("unexpected err from buffer: %s", err))
}
}
func (c *conn) bufferParseComplete() {
c.msgBuilder.initMsg(pgwirebase.ServerMsgParseComplete)
if err := c.msgBuilder.finishMsg(&c.writerState.buf); err != nil {
panic(fmt.Sprintf("unexpected err from buffer: %s", err))
}
}
func (c *conn) bufferBindComplete() {
c.msgBuilder.initMsg(pgwirebase.ServerMsgBindComplete)
if err := c.msgBuilder.finishMsg(&c.writerState.buf); err != nil {
panic(fmt.Sprintf("unexpected err from buffer: %s", err))
}
}
func (c *conn) bufferCloseComplete() {
c.msgBuilder.initMsg(pgwirebase.ServerMsgCloseComplete)
if err := c.msgBuilder.finishMsg(&c.writerState.buf); err != nil {
panic(fmt.Sprintf("unexpected err from buffer: %s", err))
}
}
func (c *conn) bufferCommandComplete(tag []byte) {
c.msgBuilder.initMsg(pgwirebase.ServerMsgCommandComplete)
c.msgBuilder.write(tag)
c.msgBuilder.nullTerminate()
if err := c.msgBuilder.finishMsg(&c.writerState.buf); err != nil {
panic(fmt.Sprintf("unexpected err from buffer: %s", err))
}
}
func (c *conn) bufferErr(err error) {
// TODO(andrei,knz): This would benefit from a context with the
// current connection log tags.
if err := writeErr(context.Background(), c.sv,
err, &c.msgBuilder, &c.writerState.buf); err != nil {
panic(fmt.Sprintf("unexpected err from buffer: %s", err))
}
}
func (c *conn) bufferEmptyQueryResponse() {
c.msgBuilder.initMsg(pgwirebase.ServerMsgEmptyQuery)
if err := c.msgBuilder.finishMsg(&c.writerState.buf); err != nil {
panic(fmt.Sprintf("unexpected err from buffer: %s", err))
}
}