-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
conn_test.go
1567 lines (1408 loc) · 45.5 KB
/
conn_test.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 (
"bytes"
"context"
gosql "database/sql"
"fmt"
"io"
"io/ioutil"
"net"
"net/url"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/hba"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"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/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondatapb"
"github.com/cockroachdb/cockroach/pkg/sql/sqlutil"
"github.com/cockroachdb/cockroach/pkg/sql/tests"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/metric"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"github.com/cockroachdb/errors"
"github.com/jackc/pgproto3/v2"
"github.com/jackc/pgx"
"github.com/stretchr/testify/require"
"golang.org/x/sync/errgroup"
)
// Test the conn struct: check that it marshalls the correct commands to the
// stmtBuf.
//
// This test is weird because it aims to be a "unit test" for the conn with
// minimal dependencies, but it needs a producer speaking the pgwire protocol
// on the other end of the connection. We use the pgx Postgres driver for this.
// We're going to simulate a client sending various commands to the server. We
// don't have proper execution of those commands in this test, so we synthesize
// responses.
//
// This test depends on recognizing the queries sent by pgx when it opens a
// connection. If that set of queries changes, this test will probably fail
// complaining that the stmtBuf has an unexpected entry in it.
func TestConn(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// The test server is used only incidentally by this test: this is not the
// server that the client will connect to; we just use it on the side to
// execute some metadata queries that pgx sends whenever it opens a
// connection.
s, _, _ := serverutils.StartServer(t, base.TestServerArgs{Insecure: true, UseDatabase: "system"})
defer s.Stopper().Stop(context.Background())
// Start a pgwire "server".
addr := util.TestAddr
ln, err := net.Listen(addr.Network(), addr.String())
if err != nil {
t.Fatal(err)
}
serverAddr := ln.Addr()
log.Infof(context.Background(), "started listener on %s", serverAddr)
var g errgroup.Group
ctx := context.Background()
var clientWG sync.WaitGroup
clientWG.Add(1)
g.Go(func() error {
return client(ctx, serverAddr, &clientWG)
})
// Wait for the client to connect and perform the handshake.
conn, err := waitForClientConn(ln)
if err != nil {
t.Fatal(err)
}
// Run the conn's loop in the background - it will push commands to the
// buffer.
serveCtx, stopServe := context.WithCancel(ctx)
g.Go(func() error {
conn.serveImpl(
serveCtx,
func() bool { return false }, /* draining */
// sqlServer - nil means don't create a command processor and a write side of the conn
nil,
mon.BoundAccount{}, /* reserved */
authOptions{testingSkipAuth: true, connType: hba.ConnHostAny},
)
return nil
})
defer stopServe()
if err := processPgxStartup(ctx, s, conn); err != nil {
t.Fatal(err)
}
// Now we'll expect to receive the commands corresponding to the operations in
// client().
rd := sql.MakeStmtBufReader(&conn.stmtBuf)
expectExecStmt(ctx, t, "SELECT 1", &rd, conn, queryStringComplete)
expectSync(ctx, t, &rd)
expectExecStmt(ctx, t, "SELECT 2", &rd, conn, queryStringComplete)
expectSync(ctx, t, &rd)
expectPrepareStmt(ctx, t, "p1", "SELECT 'p1'", &rd, conn)
expectDescribeStmt(ctx, t, "p1", pgwirebase.PrepareStatement, &rd, conn)
expectSync(ctx, t, &rd)
expectBindStmt(ctx, t, "p1", &rd, conn)
expectExecPortal(ctx, t, "", &rd, conn)
// Check that a query string with multiple queries sent using the simple
// protocol is broken up.
expectSync(ctx, t, &rd)
expectExecStmt(ctx, t, "SELECT 4", &rd, conn, queryStringIncomplete)
expectExecStmt(ctx, t, "SELECT 5", &rd, conn, queryStringIncomplete)
expectExecStmt(ctx, t, "SELECT 6", &rd, conn, queryStringComplete)
expectSync(ctx, t, &rd)
// Check that the batching works like the client intended.
// pgx wraps batchs in transactions.
expectExecStmt(ctx, t, "BEGIN TRANSACTION", &rd, conn, queryStringComplete)
expectSync(ctx, t, &rd)
expectPrepareStmt(ctx, t, "", "SELECT 7", &rd, conn)
expectBindStmt(ctx, t, "", &rd, conn)
expectDescribeStmt(ctx, t, "", pgwirebase.PreparePortal, &rd, conn)
expectExecPortal(ctx, t, "", &rd, conn)
expectPrepareStmt(ctx, t, "", "SELECT 8", &rd, conn)
// Now we'll send an error, in the middle of this batch. pgx will stop waiting
// for results for commands in the batch. We'll then test that seeking to the
// next batch advances us to the correct statement.
if err := finishQuery(generateError, conn); err != nil {
t.Fatal(err)
}
// We're about to seek to the next batch but, as per seek's contract, seeking
// can only be called when there is something in the buffer. Since the buffer
// is filled concurrently with this code, we call CurCmd to ensure that
// there's something in there.
if _, err := rd.CurCmd(); err != nil {
t.Fatal(err)
}
// Skip all the remaining messages in the batch.
if err := rd.SeekToNextBatch(); err != nil {
t.Fatal(err)
}
// We got to the COMMIT that pgx pushed to match the BEGIN it generated for
// the batch.
expectSync(ctx, t, &rd)
expectExecStmt(ctx, t, "COMMIT TRANSACTION", &rd, conn, queryStringComplete)
expectSync(ctx, t, &rd)
expectExecStmt(ctx, t, "SELECT 9", &rd, conn, queryStringComplete)
expectSync(ctx, t, &rd)
// Test that parse error turns into SendError.
expectSendError(ctx, t, pgcode.Syntax, &rd, conn)
clientWG.Done()
if err := g.Wait(); err != nil {
t.Fatal(err)
}
}
func TestConnMessageTooBig(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
params, _ := tests.CreateTestServerParams()
s, mainDB, _ := serverutils.StartServer(t, params)
defer s.Stopper().Stop(context.Background())
// Form a 1MB string.
longStr := "a"
for len(longStr) < 1<<20 {
longStr += longStr
}
shortStr := "b"
_, err := mainDB.Exec("CREATE TABLE tbl(str TEXT)")
require.NoError(t, err)
testCases := []struct {
desc string
shortStrAction func(*pgx.Conn) error
longStrAction func(*pgx.Conn) error
postLongStrAction func(*pgx.Conn) error
expectedErrRegex string
}{
{
desc: "simple query",
shortStrAction: func(c *pgx.Conn) error {
_, err := c.Exec(fmt.Sprintf(`SELECT '%s'`, shortStr))
return err
},
longStrAction: func(c *pgx.Conn) error {
_, err := c.Exec(fmt.Sprintf(`SELECT '%s'`, longStr))
return err
},
postLongStrAction: func(c *pgx.Conn) error {
_, err := c.Exec("SELECT 1")
return err
},
expectedErrRegex: "message size 1.0 MiB bigger than maximum allowed message size 32 KiB",
},
{
desc: "copy",
shortStrAction: func(c *pgx.Conn) error {
_, err := c.CopyFrom(
pgx.Identifier{"tbl"},
[]string{"str"},
pgx.CopyFromRows([][]interface{}{
{shortStr},
}),
)
return err
},
longStrAction: func(c *pgx.Conn) error {
_, err := c.CopyFrom(
pgx.Identifier{"tbl"},
[]string{"str"},
pgx.CopyFromRows([][]interface{}{
{longStr},
}),
)
return err
},
postLongStrAction: func(c *pgx.Conn) error {
_, err := c.CopyFrom(
pgx.Identifier{"tbl"},
[]string{"str"},
pgx.CopyFromRows([][]interface{}{
{shortStr},
}),
)
return err
},
expectedErrRegex: "message size 1.0 MiB bigger than maximum allowed message size 32 KiB",
},
{
desc: "prepared statement has string",
shortStrAction: func(c *pgx.Conn) error {
_, err := c.Prepare("short_statement", fmt.Sprintf("SELECT $1::string, '%s'", shortStr))
if err != nil {
return err
}
r := c.QueryRow("short_statement", shortStr)
var str string
return r.Scan(&str, &str)
},
longStrAction: func(c *pgx.Conn) error {
_, err := c.Prepare("long_statement", fmt.Sprintf("SELECT $1::string, '%s'", longStr))
if err != nil {
return err
}
r := c.QueryRow("long_statement", shortStr)
var str string
return r.Scan(&str, &str)
},
expectedErrRegex: "(EOF)|(broken pipe)|(connection reset by peer)|(write tcp)",
},
{
desc: "prepared statement with argument",
shortStrAction: func(c *pgx.Conn) error {
_, err := c.Prepare("short_arg", "SELECT $1::string")
if err != nil {
return err
}
r := c.QueryRow("short_arg", shortStr)
var str string
return r.Scan(&str)
},
longStrAction: func(c *pgx.Conn) error {
_, err := c.Prepare("long_arg", "SELECT $1::string")
if err != nil {
return err
}
r := c.QueryRow("long_arg", longStr)
var str string
return r.Scan(&str)
},
expectedErrRegex: "(EOF)|(broken pipe)|(connection reset by peer)|(write tcp)",
},
}
pgURL, cleanup := sqlutils.PGUrl(
t,
s.ServingSQLAddr(),
"TestBigClientMessage",
url.User(security.RootUser),
)
defer cleanup()
t.Run("allow big messages", func(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
conf, err := pgx.ParseConnectionString(pgURL.String())
require.NoError(t, err)
t.Run("short string", func(t *testing.T) {
c, err := pgx.Connect(conf)
require.NoError(t, err)
defer func() { _ = c.Close() }()
require.NoError(t, tc.shortStrAction(c))
})
t.Run("long string", func(t *testing.T) {
c, err := pgx.Connect(conf)
require.NoError(t, err)
defer func() { _ = c.Close() }()
require.NoError(t, tc.longStrAction(c))
})
})
}
})
// Set the cluster setting to be less than 1MB.
_, err = mainDB.Exec(`SET CLUSTER SETTING sql.conn.max_read_buffer_message_size = '32 KiB'`)
require.NoError(t, err)
t.Run("disallow big messages", func(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
conf, err := pgx.ParseConnectionString(pgURL.String())
require.NoError(t, err)
t.Run("short string", func(t *testing.T) {
c, err := pgx.Connect(conf)
require.NoError(t, err)
defer func() { _ = c.Close() }()
require.NoError(t, tc.shortStrAction(c))
})
t.Run("long string", func(t *testing.T) {
var gotErr error
var c *pgx.Conn
defer func() {
if c != nil {
_ = c.Close()
}
}()
// Allow the cluster setting to propagate.
testutils.SucceedsSoon(t, func() error {
var err error
c, err = pgx.Connect(conf)
require.NoError(t, err)
err = tc.longStrAction(c)
if err != nil {
gotErr = err
return nil
}
defer func() { _ = c.Close() }()
return errors.Newf("expected error")
})
// We should still be able to use the connection afterwards.
require.Error(t, gotErr)
require.Regexp(t, tc.expectedErrRegex, gotErr.Error())
if tc.postLongStrAction != nil {
require.NoError(t, tc.postLongStrAction(c))
}
})
})
}
})
}
// processPgxStartup processes the first few queries that the pgx driver
// automatically sends on a new connection that has been established.
func processPgxStartup(ctx context.Context, s serverutils.TestServerInterface, c *conn) error {
rd := sql.MakeStmtBufReader(&c.stmtBuf)
for {
cmd, err := rd.CurCmd()
if err != nil {
log.Errorf(ctx, "CurCmd error: %v", err)
return err
}
if _, ok := cmd.(sql.Sync); ok {
log.Infof(ctx, "advancing Sync")
rd.AdvanceOne()
continue
}
exec, ok := cmd.(sql.ExecStmt)
if !ok {
log.Infof(ctx, "stop wait at: %v", cmd)
return nil
}
query := exec.AST.String()
if !strings.HasPrefix(query, "SELECT t.oid") {
log.Infof(ctx, "stop wait at query: %s", query)
return nil
}
if err := execQuery(ctx, query, s, c); err != nil {
log.Errorf(ctx, "execQuery %s error: %v", query, err)
return err
}
log.Infof(ctx, "executed query: %s", query)
rd.AdvanceOne()
}
}
// execQuery executes a query on the passed-in server and send the results on c.
func execQuery(
ctx context.Context, query string, s serverutils.TestServerInterface, c *conn,
) error {
rows, cols, err := s.InternalExecutor().(sqlutil.InternalExecutor).QueryWithCols(
ctx, "test", nil, /* txn */
sessiondata.InternalExecutorOverride{User: security.RootUserName(), Database: "system"},
query,
)
if err != nil {
return err
}
return sendResult(ctx, c, cols, rows)
}
func client(ctx context.Context, serverAddr net.Addr, wg *sync.WaitGroup) error {
host, ports, err := net.SplitHostPort(serverAddr.String())
if err != nil {
return err
}
port, err := strconv.Atoi(ports)
if err != nil {
return err
}
conn, err := pgx.Connect(
pgx.ConnConfig{
Logger: pgxTestLogger{},
Host: host,
Port: uint16(port),
User: "root",
// Setting this so that the queries sent by pgx to initialize the
// connection are not using prepared statements. That simplifies the
// scaffolding of the test.
PreferSimpleProtocol: true,
Database: "system",
})
if err != nil {
return err
}
if _, err := conn.Exec("select 1"); err != nil {
return err
}
if _, err := conn.Exec("select 2"); err != nil {
return err
}
if _, err := conn.Prepare("p1", "select 'p1'"); err != nil {
return err
}
if _, err := conn.ExecEx(
ctx, "p1",
// We set these options because apparently that's how I tell pgx that it
// should check whether "p1" is a prepared statement.
&pgx.QueryExOptions{SimpleProtocol: false}); err != nil {
return err
}
// Send a group of statements as one query string using the simple protocol.
// We'll check that we receive them one by one, but marked as a batch.
if _, err := conn.Exec("select 4; select 5; select 6;"); err != nil {
return err
}
batch := conn.BeginBatch()
batch.Queue("select 7", nil, nil, nil)
batch.Queue("select 8", nil, nil, nil)
if err := batch.Send(context.Background(), &pgx.TxOptions{}); err != nil {
return err
}
if err := batch.Close(); err != nil {
// Swallow the error that we injected.
if !strings.Contains(err.Error(), "injected") {
return err
}
}
if _, err := conn.Exec("select 9"); err != nil {
return err
}
if _, err := conn.Exec("bogus statement failing to parse"); err != nil {
return err
}
wg.Wait()
return conn.Close()
}
// waitForClientConn blocks until a client connects and performs the pgwire
// handshake. This emulates what pgwire.Server does.
func waitForClientConn(ln net.Listener) (*conn, error) {
conn, _, err := getSessionArgs(ln, false /* trustRemoteAddr */)
if err != nil {
return nil, err
}
metrics := makeServerMetrics(sql.MemoryMetrics{} /* sqlMemMetrics */, metric.TestSampleInterval)
pgwireConn := newConn(conn, sql.SessionArgs{ConnResultsBufferSize: 16 << 10}, &metrics, nil)
return pgwireConn, nil
}
// getSessionArgs blocks until a client connects and returns the connection
// together with session arguments or an error.
func getSessionArgs(ln net.Listener, trustRemoteAddr bool) (net.Conn, sql.SessionArgs, error) {
conn, err := ln.Accept()
if err != nil {
return nil, sql.SessionArgs{}, err
}
buf := pgwirebase.MakeReadBuffer()
_, err = buf.ReadUntypedMsg(conn)
if err != nil {
return nil, sql.SessionArgs{}, err
}
version, err := buf.GetUint32()
if err != nil {
return nil, sql.SessionArgs{}, err
}
if version != version30 {
return nil, sql.SessionArgs{}, errors.Errorf("unexpected protocol version: %d", version)
}
args, err := parseClientProvidedSessionParameters(
context.Background(), nil, &buf, conn.RemoteAddr(), trustRemoteAddr,
)
return conn, args, err
}
func makeTestingConvCfg() (sessiondatapb.DataConversionConfig, *time.Location) {
return sessiondatapb.DataConversionConfig{
BytesEncodeFormat: sessiondatapb.BytesEncodeHex,
}, time.UTC
}
// sendResult serializes a set of rows in pgwire format and sends them on a
// connection.
//
// TODO(andrei): Tests using this should probably switch to using the similar
// routines in the connection once conn learns how to write rows.
func sendResult(
ctx context.Context, c *conn, cols colinfo.ResultColumns, rows []tree.Datums,
) error {
if err := c.writeRowDescription(ctx, cols, nil /* formatCodes */, c.conn); err != nil {
return err
}
defaultConv, defaultLoc := makeTestingConvCfg()
for _, row := range rows {
c.msgBuilder.initMsg(pgwirebase.ServerMsgDataRow)
c.msgBuilder.putInt16(int16(len(row)))
for i, col := range row {
c.msgBuilder.writeTextDatum(ctx, col, defaultConv, defaultLoc, cols[i].Typ)
}
if err := c.msgBuilder.finishMsg(c.conn); err != nil {
return err
}
}
return finishQuery(execute, c)
}
type executeType int
const (
queryStringComplete executeType = iota
queryStringIncomplete
)
func expectExecStmt(
ctx context.Context, t *testing.T, expSQL string, rd *sql.StmtBufReader, c *conn, typ executeType,
) {
t.Helper()
cmd, err := rd.CurCmd()
if err != nil {
t.Fatal(err)
}
rd.AdvanceOne()
es, ok := cmd.(sql.ExecStmt)
if !ok {
t.Fatalf("expected command ExecStmt, got: %T (%+v)", cmd, cmd)
}
if es.AST.String() != expSQL {
t.Fatalf("expected %s, got %s", expSQL, es.AST.String())
}
if es.ParseStart == (time.Time{}) {
t.Fatalf("ParseStart not filled in")
}
if es.ParseEnd == (time.Time{}) {
t.Fatalf("ParseEnd not filled in")
}
if typ == queryStringComplete {
if err := finishQuery(execute, c); err != nil {
t.Fatal(err)
}
} else {
if err := finishQuery(cmdComplete, c); err != nil {
t.Fatal(err)
}
}
}
func expectPrepareStmt(
ctx context.Context, t *testing.T, expName string, expSQL string, rd *sql.StmtBufReader, c *conn,
) {
t.Helper()
cmd, err := rd.CurCmd()
if err != nil {
t.Fatal(err)
}
rd.AdvanceOne()
pr, ok := cmd.(sql.PrepareStmt)
if !ok {
t.Fatalf("expected command PrepareStmt, got: %T (%+v)", cmd, cmd)
}
if pr.Name != expName {
t.Fatalf("expected name %s, got %s", expName, pr.Name)
}
if pr.AST.String() != expSQL {
t.Fatalf("expected %s, got %s", expSQL, pr.AST.String())
}
if err := finishQuery(prepare, c); err != nil {
t.Fatal(err)
}
}
func expectDescribeStmt(
ctx context.Context,
t *testing.T,
expName string,
expType pgwirebase.PrepareType,
rd *sql.StmtBufReader,
c *conn,
) {
t.Helper()
cmd, err := rd.CurCmd()
if err != nil {
t.Fatal(err)
}
rd.AdvanceOne()
desc, ok := cmd.(sql.DescribeStmt)
if !ok {
t.Fatalf("expected command DescribeStmt, got: %T (%+v)", cmd, cmd)
}
if desc.Name != expName {
t.Fatalf("expected name %s, got %s", expName, desc.Name)
}
if desc.Type != expType {
t.Fatalf("expected type %s, got %s", expType, desc.Type)
}
if err := finishQuery(describe, c); err != nil {
t.Fatal(err)
}
}
func expectBindStmt(
ctx context.Context, t *testing.T, expName string, rd *sql.StmtBufReader, c *conn,
) {
t.Helper()
cmd, err := rd.CurCmd()
if err != nil {
t.Fatal(err)
}
rd.AdvanceOne()
bd, ok := cmd.(sql.BindStmt)
if !ok {
t.Fatalf("expected command BindStmt, got: %T (%+v)", cmd, cmd)
}
if bd.PreparedStatementName != expName {
t.Fatalf("expected name %s, got %s", expName, bd.PreparedStatementName)
}
if err := finishQuery(bind, c); err != nil {
t.Fatal(err)
}
}
func expectSync(ctx context.Context, t *testing.T, rd *sql.StmtBufReader) {
t.Helper()
cmd, err := rd.CurCmd()
if err != nil {
t.Fatal(err)
}
rd.AdvanceOne()
_, ok := cmd.(sql.Sync)
if !ok {
t.Fatalf("expected command Sync, got: %T (%+v)", cmd, cmd)
}
}
func expectExecPortal(
ctx context.Context, t *testing.T, expName string, rd *sql.StmtBufReader, c *conn,
) {
t.Helper()
cmd, err := rd.CurCmd()
if err != nil {
t.Fatal(err)
}
rd.AdvanceOne()
ep, ok := cmd.(sql.ExecPortal)
if !ok {
t.Fatalf("expected command ExecPortal, got: %T (%+v)", cmd, cmd)
}
if ep.Name != expName {
t.Fatalf("expected name %s, got %s", expName, ep.Name)
}
if err := finishQuery(execPortal, c); err != nil {
t.Fatal(err)
}
}
func expectSendError(
ctx context.Context, t *testing.T, pgErrCode pgcode.Code, rd *sql.StmtBufReader, c *conn,
) {
t.Helper()
cmd, err := rd.CurCmd()
if err != nil {
t.Fatal(err)
}
rd.AdvanceOne()
se, ok := cmd.(sql.SendError)
if !ok {
t.Fatalf("expected command SendError, got: %T (%+v)", cmd, cmd)
}
if code := pgerror.GetPGCode(se.Err); code != pgErrCode {
t.Fatalf("expected code %s, got: %s", pgErrCode, code)
}
if err := finishQuery(execPortal, c); err != nil {
t.Fatal(err)
}
}
type finishType int
const (
execute finishType = iota
// cmdComplete is like execute, except that it marks the completion of a query
// in a larger query string and so no ReadyForQuery message should be sent.
cmdComplete
prepare
bind
describe
execPortal
generateError
)
// Send a CommandComplete/ReadyForQuery to signal that the rows are done.
func finishQuery(t finishType, c *conn) error {
var skipFinish bool
switch t {
case execPortal:
fallthrough
case cmdComplete:
fallthrough
case execute:
c.msgBuilder.initMsg(pgwirebase.ServerMsgCommandComplete)
// HACK: This message is supposed to contains a command tag but this test is
// not sure about how to produce one and it works without it.
c.msgBuilder.nullTerminate()
case prepare:
// pgx doesn't send a Sync in between prepare (Parse protocol message) and
// the subsequent Describe, so we're not going to send a ReadyForQuery
// below.
c.msgBuilder.initMsg(pgwirebase.ServerMsgParseComplete)
case describe:
skipFinish = true
if err := c.writeRowDescription(
context.Background(), nil /* columns */, nil /* formatCodes */, c.conn,
); err != nil {
return err
}
case bind:
// pgx doesn't send a Sync mesage in between Bind and Execute, so we're not
// going to send a ReadyForQuery below.
c.msgBuilder.initMsg(pgwirebase.ServerMsgBindComplete)
case generateError:
c.msgBuilder.initMsg(pgwirebase.ServerMsgErrorResponse)
c.msgBuilder.putErrFieldMsg(pgwirebase.ServerErrFieldSeverity)
c.msgBuilder.writeTerminatedString("ERROR")
c.msgBuilder.putErrFieldMsg(pgwirebase.ServerErrFieldMsgPrimary)
c.msgBuilder.writeTerminatedString("injected")
c.msgBuilder.nullTerminate()
if err := c.msgBuilder.finishMsg(c.conn); err != nil {
return err
}
}
if !skipFinish {
if err := c.msgBuilder.finishMsg(c.conn); err != nil {
return err
}
}
if t != cmdComplete && t != bind && t != prepare {
c.msgBuilder.initMsg(pgwirebase.ServerMsgReady)
c.msgBuilder.writeByte('I') // transaction status: no txn
if err := c.msgBuilder.finishMsg(c.conn); err != nil {
return err
}
}
return nil
}
type pgxTestLogger struct{}
func (l pgxTestLogger) Log(level pgx.LogLevel, msg string, data map[string]interface{}) {
log.Infof(context.Background(), "pgx log [%s] %s - %s", level, msg, data)
}
// pgxTestLogger implements pgx.Logger.
var _ pgx.Logger = pgxTestLogger{}
// Test that closing a pgwire connection causes transactions to be rolled back
// and release their locks.
func TestConnCloseReleasesLocks(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// We're going to test closing the connection in both the Open and Aborted
// state.
testutils.RunTrueAndFalse(t, "open state", func(t *testing.T, open bool) {
s, _, _ := serverutils.StartServer(t, base.TestServerArgs{})
ctx := context.Background()
defer s.Stopper().Stop(ctx)
pgURL, cleanupFunc := sqlutils.PGUrl(
t, s.ServingSQLAddr(), "testConnClose" /* prefix */, url.User(security.RootUser),
)
defer cleanupFunc()
db, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer db.Close()
r := sqlutils.MakeSQLRunner(db)
r.Exec(t, "CREATE DATABASE test")
r.Exec(t, "CREATE TABLE test.t (x int primary key)")
pgxConfig, err := pgx.ParseConnectionString(pgURL.String())
if err != nil {
t.Fatal(err)
}
conn, err := pgx.Connect(pgxConfig)
require.NoError(t, err)
tx, err := conn.Begin()
require.NoError(t, err)
_, err = tx.Exec("INSERT INTO test.t(x) values (1)")
require.NoError(t, err)
readCh := make(chan error)
go func() {
conn2, err := pgx.Connect(pgxConfig)
require.NoError(t, err)
_, err = conn2.Exec("SELECT * FROM test.t")
readCh <- err
}()
select {
case err := <-readCh:
t.Fatalf("unexpected read unblocked: %v", err)
case <-time.After(10 * time.Millisecond):
}
if !open {
_, err = tx.Exec("bogus")
require.NotNil(t, err)
}
err = conn.Close()
require.NoError(t, err)
select {
case readErr := <-readCh:
require.NoError(t, readErr)
case <-time.After(10 * time.Second):
t.Fatal("read not unblocked in a timely manner")
}
})
}
// Test that closing a client connection such that producing results rows
// encounters network errors doesn't crash the server (#23694).
//
// We'll run a query that produces a bunch of rows and close the connection as
// soon as the client received anything, this way ensuring that:
// a) the query started executing when the connection is closed, and so it's
// likely to observe a network error and not a context cancelation, and
// b) the connection's server-side results buffer has overflowed, and so
// attempting to produce results (through CommandResult.AddRow()) observes
// network errors.
func TestConnCloseWhileProducingRows(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s, db, _ := serverutils.StartServer(t, base.TestServerArgs{})
ctx := context.Background()
defer s.Stopper().Stop(ctx)
// Disable results buffering.
if _, err := db.Exec(
`SET CLUSTER SETTING sql.defaults.results_buffer.size = '0'`,
); err != nil {
t.Fatal(err)
}
pgURL, cleanupFunc := sqlutils.PGUrl(
t, s.ServingSQLAddr(), "testConnClose" /* prefix */, url.User(security.RootUser),
)
defer cleanupFunc()
noBufferDB, err := gosql.Open("postgres", pgURL.String())
if err != nil {
t.Fatal(err)
}
defer noBufferDB.Close()
r := sqlutils.MakeSQLRunner(noBufferDB)
r.Exec(t, "CREATE DATABASE test")
r.Exec(t, "CREATE TABLE test.test AS SELECT * FROM generate_series(1,100)")
pgxConfig, err := pgx.ParseConnectionString(pgURL.String())
if err != nil {
t.Fatal(err)
}
// We test both with and without DistSQL, as the way that network errors are
// observed depends on the engine.
testutils.RunTrueAndFalse(t, "useDistSQL", func(t *testing.T, useDistSQL bool) {
conn, err := pgx.Connect(pgxConfig)
if err != nil {
t.Fatal(err)
}
var query string
if useDistSQL {
query = `SET DISTSQL = 'always'`
} else {
query = `SET DISTSQL = 'off'`
}
if _, err := conn.Exec(query); err != nil {
t.Fatal(err)
}
rows, err := conn.Query("SELECT * FROM test.test")
if err != nil {
t.Fatal(err)
}
if hasResults := rows.Next(); !hasResults {
t.Fatal("expected results")
}
if err := conn.Close(); err != nil {
t.Fatal(err)
}
})
}
// TestMaliciousInputs verifies that known malicious inputs sent to
// a v3Conn don't crash the server.