-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathconn.go
1549 lines (1403 loc) · 50.7 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.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package pgwire
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"net"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/cockroachdb/cockroach/pkg/col/coldata"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/clusterunique"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/parser/statements"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgnotice"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgwirebase"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgwirecancel"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondatapb"
"github.com/cockroachdb/cockroach/pkg/sql/sqltelemetry"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"github.com/cockroachdb/cockroach/pkg/util/ring"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
"github.com/lib/pq/oid"
)
// 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 {
// errWriter is used to send back error payloads to the client.
errWriter
conn net.Conn
cancelConn context.CancelFunc
sessionArgs sql.SessionArgs
metrics *tenantSpecificMetrics
// startTime is the time when the connection attempt was first received
// by the server.
startTime time.Time
// 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
// res is used to avoid allocations in the conn's ClientComm implementation.
res commandResult
// 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
// vecsScratch is a scratch space used by bufferBatch.
vecsScratch coldata.TypedVecs
sv *settings.Values
// alwaysLogAuthActivity is used force-enables logging of authn events.
alwaysLogAuthActivity bool
}
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
}
func (c *conn) sendError(ctx context.Context, execCfg *sql.ExecutorConfig, err error) error {
// We could, but do not, report server-side network errors while
// trying to send the client error. This is because clients that
// receive error payload are highly correlated with clients
// disconnecting abruptly.
_ /* err */ = c.writeErr(ctx, err, c.conn)
return err
}
func (c *conn) checkMaxConnections(ctx context.Context, sqlServer *sql.Server) error {
// Root user is not affected by connection limits.
if c.sessionArgs.User.IsRootUser() {
sqlServer.IncrementRootConnectionCount()
return nil
}
// First check maxNumNonRootConnections.
// Note(alyshan): maxNumNonRootConnections is used by Cockroach Cloud for limiting connections to
// serverless clusters.
maxNonRootConnectionsValue := maxNumNonRootConnections.Get(&sqlServer.GetExecutorConfig().Settings.SV)
if maxNonRootConnectionsValue >= 0 && sqlServer.GetNonRootConnectionCount() >= maxNonRootConnectionsValue {
// Check if there is a reason to use in the error message.
msg := "cluster connections are limited"
if reason := maxNumNonRootConnectionsReason.Get(&sqlServer.GetExecutorConfig().Settings.SV); reason != "" {
msg = reason
}
return c.sendError(ctx, sqlServer.GetExecutorConfig(), errors.WithHintf(
pgerror.Newf(pgcode.TooManyConnections, "%s", msg),
"the maximum number of allowed connections is %d",
maxNonRootConnectionsValue,
))
}
// Then check maxNumNonAdminConnections.
if c.sessionArgs.IsSuperuser {
// This user is a super user and is therefore not affected by maxNumNonAdminConnections.
sqlServer.IncrementConnectionCount()
return nil
}
maxNumConnectionsValue := maxNumNonAdminConnections.Get(&sqlServer.GetExecutorConfig().Settings.SV)
if maxNumConnectionsValue < 0 {
// Unlimited connections are allowed.
sqlServer.IncrementConnectionCount()
return nil
}
if !sqlServer.IncrementConnectionCountIfLessThan(maxNumConnectionsValue) {
return c.sendError(ctx, sqlServer.GetExecutorConfig(), errors.WithHintf(
pgerror.New(pgcode.TooManyConnections, "sorry, too many clients already"),
"the maximum number of allowed connections is %d and can be modified using the %s config key",
maxNumConnectionsValue,
maxNumNonAdminConnections.Key(),
))
}
return nil
}
func (c *conn) authLogEnabled() bool {
return c.alwaysLogAuthActivity || logSessionAuth.Get(c.sv)
}
// processCommandsAsync spawns a goroutine that authenticates the connection and
// then processes commands from c.stmtBuf.
//
// It returns a channel that will be signaled when this goroutine is done.
// Whatever error is returned on that channel has already been written to the
// client connection, if applicable.
//
// If authentication fails, this goroutine finishes and, as always, cancelConn
// is called.
//
// Args:
// ac: An interface used by the authentication process to receive password data
// and to ultimately declare the authentication successful.
// reserved: Reserved memory. This method takes ownership and guarantees that it
// will be closed when this function returns.
// cancelConn: A function to be called when this goroutine exits. Its goal is to
// cancel the connection's context, thus stopping the connection's goroutine.
// The returned channel is also closed before this goroutine dies, but the
// connection's goroutine is not expected to be reading from that channel
// (instead, it's expected to always be monitoring the network connection).
func (c *conn) processCommandsAsync(
ctx context.Context,
authOpt authOptions,
ac AuthConn,
sqlServer *sql.Server,
reserved *mon.BoundAccount,
onDefaultIntSizeChange func(newSize int32),
sessionID clusterunique.ID,
) <-chan error {
// reservedOwned is true while we own reserved, false when we pass ownership
// away.
reservedOwned := true
retCh := make(chan error, 1)
go func() {
var retErr error
var connHandler sql.ConnectionHandler
var authOK bool
var connCloseAuthHandler func()
defer func() {
// Release resources, if we still own them.
if reservedOwned {
reserved.Close(ctx)
}
// Notify the connection's goroutine that we're terminating. The
// connection might know already, as it might have triggered this
// goroutine's finish, but it also might be us that we're triggering the
// connection's death. This context cancelation serves to interrupt a
// network read on the connection's goroutine.
c.cancelConn()
pgwireKnobs := sqlServer.GetExecutorConfig().PGWireTestingKnobs
if pgwireKnobs != nil && pgwireKnobs.CatchPanics {
if r := recover(); r != nil {
// Catch the panic and return it to the client as an error.
if err, ok := r.(error); ok {
// Mask the cause but keep the details.
retErr = errors.Handled(err)
} else {
retErr = errors.Newf("%+v", r)
}
retErr = pgerror.WithCandidateCode(retErr, pgcode.CrashShutdown)
// Add a prefix. This also adds a stack trace.
retErr = errors.Wrap(retErr, "caught fatal error")
_ = c.writeErr(ctx, retErr, &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.
// TODO(andrei, jordan): Why are we sending this exactly?
c.bufferReadyForQuery('I')
}
}
if !authOK {
ac.AuthFail(retErr)
}
if connCloseAuthHandler != nil {
connCloseAuthHandler()
}
// Inform the connection goroutine of success or failure.
retCh <- retErr
}()
// Authenticate the connection.
if connCloseAuthHandler, retErr = c.handleAuthentication(
ctx, ac, authOpt, sqlServer.GetExecutorConfig(),
); retErr != nil {
// Auth failed or some other error.
return
}
if retErr = c.checkMaxConnections(ctx, sqlServer); retErr != nil {
return
}
if c.sessionArgs.User.IsRootUser() {
defer sqlServer.DecrementRootConnectionCount()
} else {
defer sqlServer.DecrementConnectionCount()
}
if retErr = c.authOKMessage(); retErr != nil {
return
}
// Inform the client of the default session settings.
connHandler, retErr = c.sendInitialConnData(ctx, sqlServer, onDefaultIntSizeChange, sessionID)
if retErr != nil {
return
}
// Signal the connection was established to the authenticator.
ac.AuthOK(ctx)
ac.LogAuthOK(ctx)
// We count the connection establish latency until we are ready to
// serve a SQL query. It includes the time it takes to authenticate and
// send the initial ReadyForQuery message.
duration := timeutil.Since(c.startTime).Nanoseconds()
c.metrics.ConnLatency.RecordValue(duration)
// Mark the authentication as succeeded in case a panic
// is thrown below and we need to report to the client
// using the defer above.
authOK = true
// Now actually process commands.
reservedOwned = false // We're about to pass ownership away.
retErr = sqlServer.ServeConn(
ctx,
connHandler,
reserved,
c.cancelConn,
)
}()
return retCh
}
func (c *conn) bufferParamStatus(param, value string) error {
c.msgBuilder.initMsg(pgwirebase.ServerMsgParameterStatus)
c.msgBuilder.writeTerminatedString(param)
c.msgBuilder.writeTerminatedString(value)
return c.msgBuilder.finishMsg(&c.writerState.buf)
}
func (c *conn) bufferNotice(ctx context.Context, noticeErr pgnotice.Notice) error {
c.msgBuilder.initMsg(pgwirebase.ServerMsgNoticeResponse)
return c.writeErrFields(ctx, noticeErr, &c.writerState.buf)
}
func (c *conn) sendInitialConnData(
ctx context.Context,
sqlServer *sql.Server,
onDefaultIntSizeChange func(newSize int32),
sessionID clusterunique.ID,
) (sql.ConnectionHandler, error) {
connHandler, err := sqlServer.SetupConn(
ctx,
c.sessionArgs,
&c.stmtBuf,
c,
c.metrics.SQLMemMetrics,
onDefaultIntSizeChange,
sessionID,
)
if err != nil {
_ /* err */ = c.writeErr(ctx, err, c.conn)
return sql.ConnectionHandler{}, err
}
// Send the initial "status parameters" to the client. This
// overlaps partially with session variables. The client wants to
// see the values that result from 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 {
param := param
value := connHandler.GetParamStatus(ctx, param)
if err := c.bufferParamStatus(param, value); err != nil {
return sql.ConnectionHandler{}, err
}
}
// The two following status parameters have no equivalent session
// variable.
if err := c.bufferParamStatus("session_authorization", c.sessionArgs.User.Normalized()); err != nil {
return sql.ConnectionHandler{}, err
}
if err := c.bufferInitialReadyForQuery(connHandler.GetQueryCancelKey()); err != nil {
return sql.ConnectionHandler{}, err
}
// We don't have a CmdPos to pass in, since we haven't received any commands
// yet, so we just use the initial lastFlushed value.
if err := c.Flush(c.writerState.fi.lastFlushed); err != nil {
return sql.ConnectionHandler{}, err
}
return connHandler, nil
}
// bufferInitialReadyForQuery sends the final messages of the connection
// handshake. This includes a BackendKeyData message and a ServerMsgReady
// message indicating that there is no active transaction.
func (c *conn) bufferInitialReadyForQuery(queryCancelKey pgwirecancel.BackendKeyData) error {
// Send our BackendKeyData to the client, so they can cancel the connection.
c.msgBuilder.initMsg(pgwirebase.ServerMsgBackendKeyData)
c.msgBuilder.putInt64(int64(queryCancelKey))
if err := c.msgBuilder.finishMsg(&c.writerState.buf); err != nil {
return err
}
// An initial ServerMsgReady message is part of the handshake.
c.msgBuilder.initMsg(pgwirebase.ServerMsgReady)
c.msgBuilder.writeByte(byte(sql.IdleTxnBlock))
if err := c.msgBuilder.finishMsg(&c.writerState.buf); 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) handleSimpleQuery(
ctx context.Context,
buf *pgwirebase.ReadBuffer,
timeReceived time.Time,
unqualifiedIntSize *types.T,
) error {
query, err := buf.GetString()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
startParse := timeutil.Now()
stmts, err := c.parser.ParseWithInt(query, unqualifiedIntSize)
if err != nil {
log.SqlExec.Infof(ctx, "could not parse simple query: %s", query)
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
endParse := timeutil.Now()
if len(stmts) == 0 {
return c.stmtBuf.Push(
ctx, sql.ExecStmt{
Statement: statements.Statement[tree.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,
ParsedStmt: stmts[i],
Stmt: cp,
CopyDone: ©Done,
TimeReceived: timeReceived,
ParseStart: startParse,
ParseEnd: endParse,
},
); err != nil {
return err
}
copyDone.Wait()
return nil
}
if cp, ok := stmts[i].AST.(*tree.CopyTo); 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"),
})
}
if err := c.stmtBuf.Push(
ctx,
sql.CopyOut{
ParsedStmt: stmts[i],
Stmt: cp,
TimeReceived: timeReceived,
ParseStart: startParse,
ParseEnd: endParse,
},
); err != nil {
return err
}
return nil
}
// Determine whether there is only SHOW COMMIT TIMESTAMP after this
// statement in the batch. That case should be treated as though it
// were the last statement in the batch.
lastBeforeShowCommitTimestamp := func() bool {
n := len(stmts)
isShowCommitTimestamp := func(s statements.Statement[tree.Statement]) bool {
_, ok := s.AST.(*tree.ShowCommitTimestamp)
return ok
}
return n > 1 && i == n-2 && isShowCommitTimestamp(stmts[n-1])
}
if err := c.stmtBuf.Push(
ctx,
sql.ExecStmt{
Statement: stmts[i],
TimeReceived: timeReceived,
ParseStart: startParse,
ParseEnd: endParse,
LastInBatch: i == len(stmts)-1,
LastInBatchBeforeShowCommitTimestamp: lastBeforeShowCommitTimestamp(),
}); 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, nakedIntSize *types.T,
) error {
telemetry.Inc(sqltelemetry.ParseRequestCounter)
name, err := buf.GetString()
if err != 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, nakedIntSize)
if err != nil {
log.SqlExec.Infof(ctx, "could not parse: %s", query)
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
if len(stmts) > 1 {
err := pgerror.WrongNumberOfPreparedStatements(len(stmts))
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
var stmt statements.Statement[tree.Statement]
if len(stmts) == 1 {
stmt = stmts[0]
}
// len(stmts) == 0 results in a nil (empty) statement.
// We take max(len(s.Types), stmt.NumPlaceHolders) as the length of types.
numParams := len(inTypeHints)
if stmt.NumPlaceholders > numParams {
numParams = stmt.NumPlaceholders
}
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, numParams)
for i, t := range inTypeHints {
if t == 0 {
continue
}
// If the OID is user defined or unknown, then write nil into the type
// hints and let the consumer of the PrepareStmt resolve the types.
if t == oid.T_unknown || types.IsOIDUserDefinedType(t) {
sqlTypeHints[i] = nil
continue
}
// This special case for json, json[] is here so we can support decoding
// parameters with oid=json/json[] without adding full support for these
// type.
// TODO(sql-exp): Remove this if we support JSON.
if t == oid.T_json {
sqlTypeHints[i] = types.Json
continue
}
if t == oid.T__json {
sqlTypeHints[i] = types.JSONArrayForDecodingOnly
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.
// Be aware that the copyMachine assumes it always runs in the simple
// protocol, so if we ever support this, many parts of the copyMachine
// would need to be changed.
// 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 {
telemetry.Inc(sqltelemetry.DescribeRequestCounter)
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: tree.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 {
telemetry.Inc(sqltelemetry.CloseRequestCounter)
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,
})
}
// If no format codes are provided then all arguments/result-columns use
// the default format, text.
var formatCodesAllText = []pgwirebase.FormatCode{pgwirebase.FormatText}
// 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 {
telemetry.Inc(sqltelemetry.BindRequestCounter)
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})
}
var qArgFormatCodes []pgwirebase.FormatCode
switch numQArgFormatCodes {
case 0:
// No format codes means all arguments are passed as text.
qArgFormatCodes = formatCodesAllText
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})
}
code := pgwirebase.FormatCode(ch)
if code == pgwirebase.FormatText {
qArgFormatCodes = formatCodesAllText
} else {
qArgFormatCodes = []pgwirebase.FormatCode{code}
}
default:
qArgFormatCodes = make([]pgwirebase.FormatCode, numQArgFormatCodes)
// Read one format code for each argument and apply it to that argument.
for i := range qArgFormatCodes {
ch, err := buf.GetUint16()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
qArgFormatCodes[i] = pgwirebase.FormatCode(ch)
}
}
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 = formatCodesAllText
case 1:
// All columns will use the one specified format.
ch, err := buf.GetUint16()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
code := pgwirebase.FormatCode(ch)
if code == pgwirebase.FormatText {
columnFormatCodes = formatCodesAllText
} else {
columnFormatCodes = []pgwirebase.FormatCode{code}
}
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, followedBySync bool,
) error {
telemetry.Inc(sqltelemetry.ExecuteRequestCounter)
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),
FollowedBySync: followedBySync,
})
}
func (c *conn) handleFlush(ctx context.Context) error {
telemetry.Inc(sqltelemetry.FlushRequestCounter)
return c.stmtBuf.Push(ctx, sql.Flush{})
}
// BeginCopyIn is part of the pgwirebase.Conn interface.
func (c *conn) BeginCopyIn(
ctx context.Context, columns []colinfo.ResultColumn, format pgwirebase.FormatCode,
) error {
c.msgBuilder.initMsg(pgwirebase.ServerMsgCopyInResponse)
c.msgBuilder.writeByte(byte(format))
c.msgBuilder.putInt16(int16(len(columns)))
for range columns {
c.msgBuilder.putInt16(int16(format))
}
return c.msgBuilder.finishMsg(c.conn)
}
// 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
// cmdStarts maintains the state about where the results for the respective
// positions begin. We utilize the invariant that positions are
// monotonically increasing sequences.
cmdStarts ring.Buffer[cmdIdx]
}
type cmdIdx struct {
pos sql.CmdPos
idx int
}
// registerCmd updates cmdStarts buffer when the first result for a new command
// is received.
func (fi *flushInfo) registerCmd(pos sql.CmdPos) {
if fi.cmdStarts.Len() > 0 && fi.cmdStarts.GetLast().pos >= pos {
// Not a new command, nothing to do.
return
}
fi.cmdStarts.AddLast(cmdIdx{pos: pos, idx: fi.buf.Len()})
}
func cookTag(
tagStr string, buf []byte, stmtType tree.StatementReturnType, 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, tree.CopyIn, tree.CopyOut:
tag = append(tag, ' ')
tag = strconv.AppendInt(tag, int64(rowsAffected), 10)
case tree.Rows:
if tagStr != "SHOW" {
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)
}
default:
panic(errors.AssertionFailedf("unexpected result type %v", stmtType))
}
return tag
}
// bufferRow serializes a row and adds it to the buffer. Depending on the buffer
// size limit, bufferRow may flush the buffered data to the connection.
func (c *conn) bufferRow(ctx context.Context, row tree.Datums, r *commandResult) error {
c.msgBuilder.initMsg(pgwirebase.ServerMsgDataRow)
c.msgBuilder.putInt16(int16(len(row)))
for i, col := range row {
fmtCode := pgwirebase.FormatText
if r.formatCodes != nil {
if i >= len(r.formatCodes) {
return errors.AssertionFailedf("could not find format code for column %d in %v", i, r.formatCodes)
}
fmtCode = r.formatCodes[i]
}
switch fmtCode {
case pgwirebase.FormatText:
c.msgBuilder.writeTextDatum(ctx, col, r.conv, r.location, r.types[i])
case pgwirebase.FormatBinary:
c.msgBuilder.writeBinaryDatum(ctx, col, r.location, r.types[i])
default:
c.msgBuilder.setError(errors.Errorf("unsupported format code %s", fmtCode))
}
}
if err := c.msgBuilder.finishMsg(&c.writerState.buf); err != nil {
return errors.NewAssertionErrorWithWrappedErrf(err, "unexpected err from buffer")
}
if err := c.maybeFlush(r.pos, r.bufferingDisabled); err != nil {
return errors.NewAssertionErrorWithWrappedErrf(err, "unexpected err from buffer")
}
c.maybeReallocate()
return nil
}
// bufferBatch serializes a batch and adds all the rows from it to the buffer.
// It is a noop for zero-length batch. Depending on the buffer size limit,
// bufferBatch may flush the buffered data to the connection.
func (c *conn) bufferBatch(ctx context.Context, batch coldata.Batch, r *commandResult) error {
sel := batch.Selection()
n := batch.Length()
if n > 0 {
c.vecsScratch.SetBatch(batch)
// Make sure that c doesn't hold on to the memory of the batch.
defer c.vecsScratch.Reset()
width := int16(len(c.vecsScratch.Vecs))
for i := 0; i < n; i++ {
rowIdx := i
if sel != nil {
rowIdx = sel[rowIdx]
}
c.msgBuilder.initMsg(pgwirebase.ServerMsgDataRow)
c.msgBuilder.putInt16(width)
for vecIdx := 0; vecIdx < len(c.vecsScratch.Vecs); vecIdx++ {
fmtCode := pgwirebase.FormatText
if r.formatCodes != nil {
if vecIdx >= len(r.formatCodes) {
return errors.AssertionFailedf("could not find format code for column %d in %v", vecIdx, r.formatCodes)
}
fmtCode = r.formatCodes[vecIdx]
}
switch fmtCode {
case pgwirebase.FormatText:
c.msgBuilder.writeTextColumnarElement(ctx, &c.vecsScratch, vecIdx, rowIdx, r.conv, r.location)
case pgwirebase.FormatBinary:
c.msgBuilder.writeBinaryColumnarElement(ctx, &c.vecsScratch, vecIdx, rowIdx, r.location)
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))
}
if err := c.maybeFlush(r.pos, r.bufferingDisabled); err != nil {
return err
}
c.maybeReallocate()
}
}
return nil
}
// tenantEgressCounter implements the sql.TenantNetworkEgressCounter interface.
type tenantEgressCounter struct {
buf writeBuffer
vecs coldata.TypedVecs
}