-
-
Notifications
You must be signed in to change notification settings - Fork 955
Expand file tree
/
Copy pathconn_test.go
More file actions
2025 lines (1789 loc) · 54.4 KB
/
conn_test.go
File metadata and controls
2025 lines (1789 loc) · 54.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package pq
import (
"bufio"
"bytes"
"context"
"database/sql"
"database/sql/driver"
"encoding/json"
"fmt"
"io"
"maps"
"math"
"net"
"os"
"reflect"
"runtime"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/lib/pq/internal/pgpass"
"github.com/lib/pq/internal/pqtest"
"github.com/lib/pq/internal/pqutil"
"github.com/lib/pq/internal/proto"
"github.com/lib/pq/pqerror"
)
func TestReconnect(t *testing.T) {
pqtest.SkipCockroach(t) // Doesn't implement pg_terminate_backend()
t.Parallel()
db := pqtest.MustDB(t)
tx := pqtest.Begin(t, db)
pid := pqtest.Query[int64](t, tx, `select pg_backend_pid() as p`)[0]["p"]
pqtest.Exec(t, pqtest.MustDB(t), `select pg_terminate_backend($1)`, pid)
tx.Rollback()
have := pqtest.Query[int64](t, db, `select 42 as n`)[0]["n"]
if have != 42 {
t.Errorf("\nwant: 42\nhave: %v", have)
}
}
func TestCommitInFailedTransaction(t *testing.T) {
tx := pqtest.Begin(t, pqtest.MustDB(t))
rows, err := tx.Query("select error")
if err == nil {
rows.Close()
t.Fatal("expected failure")
}
err = tx.Commit()
if err != ErrInFailedTransaction {
t.Fatalf("expected ErrInFailedTransaction; got %#v", err)
}
}
func TestOpen(t *testing.T) {
tests := []struct {
dsn, wantErr string
}{
{"postgres://", ""},
{"postgresql://", ""},
{"host=doesnotexist hostaddr=127.0.0.1", ""}, // Should ignore the host
{"hostaddr=255.255.255.255", "dial tcp 255.255.255.255"},
}
for _, tt := range tests {
t.Run(tt.dsn, func(t *testing.T) {
t.Parallel()
_, err := pqtest.DB(t, tt.dsn)
if !pqtest.ErrorContains(err, tt.wantErr) {
t.Errorf("wrong error:\nhave: %s\nwant: %s", err, tt.wantErr)
}
})
}
}
func TestPgpass(t *testing.T) {
warnbuf := new(bytes.Buffer)
pqutil.WarnFD = warnbuf
defer func() { pqutil.WarnFD = os.Stderr }()
assertPassword := func(want string, extra map[string]string) {
o := map[string]string{
"host": "localhost",
"sslmode": "disable",
"connect_timeout": "20",
"user": "majid",
"port": "5432",
"dbname": "pqgo",
"client_encoding": "UTF8",
"datestyle": "ISO, MDY",
}
maps.Copy(o, extra)
have := pgpass.PasswordFromPgpass(o["passfile"], o["user"], o["password"], o["host"], o["port"], o["dbname"])
if have != want {
t.Fatalf("wrong password\nhave: %q\nwant: %q", have, want)
}
}
file := pqtest.TempFile(t, "pgpass", pqtest.NormalizeIndent(`
# comment
server:5432:some_db:some_user:pass_A
*:5432:some_db:some_user:pass_B
localhost:*:*:*:pass_C
*:*:*:*:pass_fallback
`))
// Missing passfile means empty password.
assertPassword("", map[string]string{"host": "server", "dbname": "some_db", "user": "some_user"})
// wrong permissions for the pgpass file means it should be ignored
assertPassword("", map[string]string{"host": "example.com", "passfile": file, "user": "foo"})
if h := "has group or world access"; !strings.Contains(warnbuf.String(), h) {
t.Errorf("unexpected warning\nhave: %s\nwant: %s", warnbuf, h)
}
warnbuf.Reset()
pqtest.Chmod(t, 0o600, file) // Fix the permissions
assertPassword("pass_A", map[string]string{"host": "server", "passfile": file, "dbname": "some_db", "user": "some_user"})
assertPassword("pass_fallback", map[string]string{"host": "example.com", "passfile": file, "user": "foo"})
assertPassword("pass_B", map[string]string{"host": "example.com", "passfile": file, "dbname": "some_db", "user": "some_user"})
// localhost also matches the default "" and UNIX sockets
assertPassword("pass_C", map[string]string{"host": "", "passfile": file, "user": "some_user"})
assertPassword("pass_C", map[string]string{"host": "/tmp", "passfile": file, "user": "some_user"})
// Connection parameter takes precedence
t.Setenv("PGPASSFILE", "/tmp")
assertPassword("pass_A", map[string]string{"host": "server", "passfile": file, "dbname": "some_db", "user": "some_user"})
if warnbuf.String() != "" {
t.Errorf("warnbuf not empty: %s", warnbuf)
}
}
func TestExecNilSlice(t *testing.T) {
db := pqtest.MustDB(t)
pqtest.Exec(t, db, `create temp table x (b1 text, b2 text, b3 text)`)
var (
b1 []byte
b2 []string
b3 = []byte{}
)
pqtest.Exec(t, db, `insert into x (b1, b2, b3) values ($1, $2, $3)`, b1, b2, b3)
have := pqtest.QueryRow[*string](t, db, `select * from x`)
var s string
want := map[string]*string{"b1": nil, "b2": nil, "b3": &s}
if !reflect.DeepEqual(have, want) {
t.Errorf("\nhave: %#v\nwant: %#v", have, want)
}
}
func TestExec(t *testing.T) {
tests := []struct {
query string
args []any
rows int64
}{
{`insert into tbl values (1)`, nil, 1},
{`insert into tbl values ($1), ($2), ($3)`, []any{1, 2, 3}, 3},
{`select g from generate_series(1, 2) g`, nil, 2},
{`select g from generate_series(1, $1) g`, []any{3}, 3},
}
db := pqtest.MustDB(t)
pqtest.Exec(t, db, `create temp table tbl (a int)`)
for _, tt := range tests {
t.Run("", func(t *testing.T) {
r, err := db.Exec(tt.query, tt.args...)
if err != nil {
t.Fatal(err)
}
if n, _ := r.RowsAffected(); n != tt.rows {
t.Fatalf("want %d row affected, not %d", tt.rows, n)
}
})
}
}
func TestStatment(t *testing.T) {
db := pqtest.MustDB(t)
stmt1 := pqtest.Prepare(t, db, "select 1")
stmt2 := pqtest.Prepare(t, db, "select 2")
r, err := stmt1.Query()
if err != nil {
t.Fatal(err)
}
defer r.Close()
if !r.Next() {
t.Fatal("expected row")
}
var i int
err = r.Scan(&i)
if err != nil {
t.Fatal(err)
}
if i != 1 {
t.Fatalf("expected 1, got %d", i)
}
r1, err := stmt2.Query()
if err != nil {
t.Fatal(err)
}
defer r1.Close()
if !r1.Next() {
if r.Err() != nil {
t.Fatal(r.Err())
}
t.Fatal("expected row")
}
err = r1.Scan(&i)
if err != nil {
t.Fatal(err)
}
if i != 2 {
t.Fatalf("expected 2, got %d", i)
}
}
func TestParameterCountMismatch(t *testing.T) {
db := pqtest.MustDB(t)
var notused int
err := db.QueryRow("SELECT false", 1).Scan(¬used)
if err == nil {
t.Fatal("expected err")
}
// make sure we clean up correctly
err = db.QueryRow("SELECT 1").Scan(¬used)
if err != nil {
t.Fatal(err)
}
err = db.QueryRow("SELECT $1").Scan(¬used)
if err == nil {
t.Fatal("expected err")
}
// make sure we clean up correctly
err = db.QueryRow("SELECT 1").Scan(¬used)
if err != nil {
t.Fatal(err)
}
}
// Test that EmptyQueryResponses are handled correctly.
func TestEmptyQuery(t *testing.T) {
db := pqtest.MustDB(t)
res, err := db.Exec("")
if err != nil {
t.Fatal(err)
}
if _, err := res.RowsAffected(); err != errNoRowsAffected {
t.Fatalf("want %s, got %v", errNoRowsAffected, err)
}
if _, err := res.LastInsertId(); err != errNoLastInsertID {
t.Fatalf("want %s, got %v", errNoLastInsertID, err)
}
have := pqtest.Query[any](t, db, ``)
want := []map[string]any{}
if !reflect.DeepEqual(have, want) {
t.Errorf("\nhave: %#v\nwant: %#v", have, want)
}
stmt := pqtest.Prepare(t, db, "")
stmt.MustExec(t)
res = stmt.MustExec(t)
if _, err := res.RowsAffected(); err != errNoRowsAffected {
t.Fatalf("expected %s, got %v", errNoRowsAffected, err)
}
if _, err := res.LastInsertId(); err != errNoLastInsertID {
t.Fatalf("expected %s, got %v", errNoLastInsertID, err)
}
rows, err := stmt.Query()
if err != nil {
t.Fatal(err)
}
cols, err := rows.Columns()
if err != nil {
t.Fatal(err)
}
if len(cols) != 0 {
t.Fatalf("unexpected number of columns %d in response to an empty query", len(cols))
}
if rows.Next() {
t.Fatal("unexpected row")
}
if rows.Err() != nil {
t.Fatal(rows.Err())
}
}
// Test that rows.Columns() is correct even if there are no result rows.
func TestEmptyResultSetColumns(t *testing.T) {
db := pqtest.MustDB(t)
t.Run("query", func(t *testing.T) {
rows, err := db.Query("select 1 as a, 'bar'::text as bar where false")
if err != nil {
t.Fatal(err)
}
defer rows.Close()
cols, err := rows.Columns()
if err != nil {
t.Fatal(err)
}
if len(cols) != 2 {
t.Fatalf("unexpected number of columns %d in response to an empty query", len(cols))
}
if rows.Next() {
t.Fatal("unexpected row")
}
if rows.Err() != nil {
t.Fatal(rows.Err())
}
if cols[0] != "a" || cols[1] != "bar" {
t.Fatalf("unexpected Columns result %v", cols)
}
})
t.Run("prepared", func(t *testing.T) {
rows, err := pqtest.Prepare(t, db, "select $1::int as a, text 'bar' AS bar where false").Query(1)
if err != nil {
t.Fatal(err)
}
defer rows.Close()
cols, err := rows.Columns()
if err != nil {
t.Fatal(err)
}
if len(cols) != 2 {
t.Fatalf("unexpected number of columns %d in response to an empty query", len(cols))
}
if rows.Next() {
t.Fatal("unexpected row")
}
if rows.Err() != nil {
t.Fatal(rows.Err())
}
if cols[0] != "a" || cols[1] != "bar" {
t.Fatalf("unexpected Columns result %v", cols)
}
})
}
func TestEncodeDecode(t *testing.T) {
db := pqtest.MustDB(t)
type h struct {
got1 []byte
got2 string
got3 sql.NullInt64
got4 time.Time
got5, got6, got7, got8 any
}
have := h{got3: sql.NullInt64{Valid: true}}
err := db.QueryRow(`
select
E'\\000\\001\\002'::bytea,
'foobar'::text,
NULL::integer,
'2000-1-1 01:02:03.04-7'::timestamptz,
0::boolean,
123,
-321,
3.14::float8
where
E'\\000\\001\\002'::bytea = $1 and
'foobar'::text = $2 and
$3::integer is NULL
`, []byte{0, 1, 2}, "foobar", nil).Scan(
&have.got1, &have.got2, &have.got3, &have.got4, &have.got5, &have.got6, &have.got7, &have.got8,
)
if err != nil {
t.Fatal(err)
}
want := h{
got1: []byte{0, 1, 2},
got2: "foobar",
got3: sql.NullInt64{},
got4: time.Date(2000, 1, 1, 8, 2, 3, 40000000, time.UTC),
got5: false,
got6: int64(123),
got7: int64(-321),
got8: 3.14,
}
if !reflect.DeepEqual(have, want) {
t.Errorf("\nhave: %+v\nwant: %+v", have, want)
}
}
func TestNoData(t *testing.T) {
db := pqtest.MustDB(t)
rows, err := pqtest.Prepare(t, db, "select 1 where true = false").Query()
if err != nil {
t.Fatal(err)
}
defer rows.Close()
if rows.Next() {
if rows.Err() != nil {
t.Fatal(rows.Err())
}
t.Fatal("unexpected row")
}
_, err = db.Query("select * from nonexistenttable where age=$1", 20)
if err == nil {
t.Fatal("Should have raised an error on non existent table")
}
_, err = db.Query("select * from nonexistenttable")
if err == nil {
t.Fatal("Should have raised an error on non existent table")
}
}
func TestErrorDuringStartup(t *testing.T) {
// TODO: fails with wrong error:
// wrong error code "protocol_violation": pq: "trust" authentication failed
// May be an issue in how pgbouncer is configured, or just that pgbouncer
// sends a different error.
pqtest.SkipPgbouncer(t)
// TODO: this one also:
// wrong error code "internal_error": pq: unable to get session context
pqtest.SkipPgpool(t)
t.Parallel()
// Don't use the normal connection setup, this is intended to blow up in the
// startup packet from a non-existent user.
_, err := pqtest.DB(t, "user=thisuserreallydoesntexist")
mustAs(t, err, pqerror.InvalidAuthorizationSpecification, pqerror.InvalidPassword)
}
type testConn struct {
closed bool
net.Conn
}
func (c *testConn) Close() error {
c.closed = true
return c.Conn.Close()
}
type testDialer struct {
conns []*testConn
}
func (d *testDialer) Dial(ntw, addr string) (net.Conn, error) {
c, err := net.Dial(ntw, addr)
if err != nil {
return nil, err
}
tc := &testConn{Conn: c}
d.conns = append(d.conns, tc)
return tc, nil
}
func (d *testDialer) DialTimeout(ntw, addr string, timeout time.Duration) (net.Conn, error) {
c, err := net.DialTimeout(ntw, addr, timeout)
if err != nil {
return nil, err
}
tc := &testConn{Conn: c}
d.conns = append(d.conns, tc)
return tc, nil
}
func TestErrorDuringStartupClosesConn(t *testing.T) {
// Don't use the normal connection setup, this is intended to
// blow up in the startup packet from a non-existent user.
var d testDialer
c, err := DialOpen(&d, pqtest.DSN("user=thisuserreallydoesntexist"))
if err == nil {
c.Close()
t.Fatal("expected dial error")
}
if len(d.conns) != 1 {
t.Fatalf("got len(d.conns) = %d, want = %d", len(d.conns), 1)
}
if !d.conns[0].closed {
t.Error("connection leaked")
}
}
func TestBadConn(t *testing.T) {
t.Parallel()
for _, tt := range []error{io.EOF, &Error{Severity: pqerror.SeverityFatal}, io.ErrUnexpectedEOF} {
t.Run(fmt.Sprintf("%s", tt), func(t *testing.T) {
var cn conn
err := cn.handleError(tt)
if err != driver.ErrBadConn {
t.Fatalf("expected driver.ErrBadConn, got: %#v", err)
}
if err := cn.err.get(); err != driver.ErrBadConn {
t.Fatalf("expected driver.ErrBadConn, got %#v", err)
}
})
}
}
func TestUnexpectedEOF(t *testing.T) {
t.Parallel()
// On the first "select truncate" it sends a correct RowDescription followed
// by a truncated DataRow (header declares 96 body bytes, only 5 are sent)
// and then close the connection. database/sql should discard the connection
// and retry, and subsequent queries succeed.
var failed atomic.Bool
f := pqtest.NewFake(t, func(f pqtest.Fake, cn net.Conn) {
f.Startup(cn, nil)
for {
code, q, ok := f.ReadMsg(cn)
if !ok {
return
}
switch code {
case proto.Terminate:
cn.Close()
return
case proto.Query:
switch q := string(q[:bytes.IndexByte(q, 0)]); {
case q == ";": // Ping()
f.WriteMsg(cn, proto.EmptyQueryResponse, "")
f.WriteMsg(cn, proto.ReadyForQuery, "I")
case q == "select truncate" && !failed.Swap(true):
f.WriteMsg(cn, proto.RowDescription, "\x00\x01truncate\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x19\xff\xff\xff\xff\xff\xff\x00\x00")
cn.Write([]byte("D\x00\x00\x00\x64short"))
cn.Close()
return
case q == "select truncate":
f.SimpleQuery(cn, "SELECT", "truncate", "1")
f.WriteMsg(cn, proto.ReadyForQuery, "I")
case q == "select okay":
f.SimpleQuery(cn, "SELECT", "okay", "1")
f.WriteMsg(cn, proto.ReadyForQuery, "I")
default:
panic(fmt.Sprintf("unexpected query: %q", q))
}
}
}
})
defer f.Close()
db := pqtest.MustDB(t, f.DSN())
db.SetMaxOpenConns(1)
db.SetMaxIdleConns(1)
// This should work as database/sql retries for us.
pqtest.QueryRow[int](t, db, `select truncate`)
if !failed.Load() {
t.Fatal("select truncate never failed")
}
// Make sure it doesn't break the connection.
pqtest.QueryRow[int](t, db, `select okay`)
}
func TestConnClose(t *testing.T) {
// Ensure the underlying connection can be closed with Close after an error.
t.Run("CloseBadConn", func(t *testing.T) {
host := os.Getenv("PGHOST")
if host == "" {
host = "localhost"
}
if host[0] == '/' {
t.Skip("cannot test bad connection close with a Unix-domain PGHOST")
}
port := os.Getenv("PGPORT")
if port == "" {
port = "5432"
}
nc, err := net.Dial("tcp", host+":"+port)
if err != nil {
t.Fatal(err)
}
cn := conn{c: nc}
cn.handleError(io.EOF)
// Verify we can write before closing and then close.
if _, err := nc.Write(nil); err != nil {
t.Fatal(err)
}
if err := cn.Close(); err != nil {
t.Fatal(err)
}
// Verify write after closing fails.
const errClosing = "use of closed"
_, err = nc.Write(nil)
if err == nil {
t.Fatal("expected error")
}
if !strings.Contains(err.Error(), errClosing) {
t.Fatalf("expected %s error, got %s", errClosing, err)
}
// Verify second close fails.
err = cn.Close()
if err == nil {
t.Fatal("expected error")
}
if !strings.Contains(err.Error(), errClosing) {
t.Fatalf("expected %s error, got %s", errClosing, err)
}
})
}
func TestErrorOnExec(t *testing.T) {
tx := pqtest.Begin(t, pqtest.MustDB(t))
pqtest.Exec(t, tx, `create temp table foo(f1 int primary key)`)
_, err := tx.Exec("insert into foo values (0), (0)")
mustAs(t, err, pqerror.UniqueViolation)
}
func TestErrorOnQuery(t *testing.T) {
tx := pqtest.Begin(t, pqtest.MustDB(t))
pqtest.Exec(t, tx, `create temp table foo(f1 int primary key)`)
_, err := tx.Query("insert into foo values (0), (0)")
mustAs(t, err, pqerror.UniqueViolation)
}
func TestErrorOnQueryRowSimpleQuery(t *testing.T) {
tx := pqtest.Begin(t, pqtest.MustDB(t))
pqtest.Exec(t, tx, `create temp table foo(f1 int primary key)`)
var v int
err := tx.QueryRow("insert into foo values (0), (0)").Scan(&v)
mustAs(t, err, pqerror.UniqueViolation)
}
// Test the QueryRow bug workarounds in stmt.exec() and simpleQuery()
func TestQueryRowBugWorkaround(t *testing.T) {
pqtest.SkipCockroach(t) // check_function_bodies=false doesn't really work
db := pqtest.MustDB(t)
pqtest.Exec(t, db, "create temp table notnulltemp (a varchar(10) not null)")
var a string
err := db.QueryRow("insert into notnulltemp(a) values($1) returning a", nil).Scan(&a)
mustAs(t, err, pqerror.NotNullViolation)
// Test workaround in simpleQuery()
tx := pqtest.Begin(t, db)
pqtest.Exec(t, tx, `set local check_function_bodies to false`)
pqtest.Exec(t, tx, `
create or replace function bad_function()
returns integer
-- hack to prevent the function from being inlined
set check_function_bodies to true
as $$
select text 'bad'
$$ language sql
`)
err = tx.QueryRow("select * from bad_function()").Scan(&a)
mustAs(t, err, pqerror.InvalidFunctionDefinition)
err = tx.Rollback()
if err != nil {
t.Fatalf("unexpected error %s in Rollback", err)
}
// Also test that simpleQuery()'s workaround works when the query fails
// after a row has been received.
rows, err := db.Query(`
select (select generate_series(1, ss.i))
from (select gs.i
from generate_series(1, 2) gs(i)
order by gs.i limit 2) ss
`)
if err != nil {
t.Fatalf("query failed: %s", err)
}
defer rows.Close()
if !rows.Next() {
t.Fatalf("expected at least one result row; got %s", rows.Err())
}
var i int
err = rows.Scan(&i)
if err != nil {
t.Fatalf("rows.Scan() failed: %s", err)
}
if i != 1 {
t.Fatalf("unexpected value for i: %d", i)
}
if rows.Next() {
t.Fatalf("unexpected row")
}
mustAs(t, rows.Err(), pqerror.CardinalityViolation)
}
func TestSimpleQuery(t *testing.T) {
have := pqtest.QueryRow[int](t, pqtest.MustDB(t), `select 1`)
want := map[string]int{"?column?": 1}
if !reflect.DeepEqual(have, want) {
t.Errorf("\nhave: %#v\nwant: %#v", have, want)
}
}
// Make sure SimpleQuery doesn't panic if there is no query response. See #1059
// and #1173
func TestSimpleQueryWithoutResponse(t *testing.T) {
t.Parallel()
f := pqtest.NewFake(t, func(f pqtest.Fake, cn net.Conn) {
f.Startup(cn, nil)
for {
code, _, ok := f.ReadMsg(cn)
if !ok {
return
}
switch code {
case proto.Query:
// Make sure we DON'T send this
//f.WriteMsg(cn, proto.EmptyQueryResponse, "")
f.WriteMsg(cn, proto.ReadyForQuery, "I")
case proto.Terminate:
cn.Close()
return
}
}
})
defer f.Close()
err := pqtest.MustDB(t, f.DSN()).Ping()
if err != nil {
t.Fatal(err)
}
}
func TestBindError(t *testing.T) {
t.Parallel()
db := pqtest.MustDB(t)
pqtest.Exec(t, db, `create temp table tbl (i integer)`)
_, err := db.Query(`select * from tbl where i=$1`, "hhh")
if err == nil {
t.Fatal("expected an error")
}
have := pqtest.QueryRow[int](t, db, `select * from tbl where i=$1`, 1)
var want map[string]int
if !reflect.DeepEqual(have, want) {
t.Errorf("\nhave: %#v\nwant: %#v", have, want)
}
}
func TestParseErrorInExtendedQuery(t *testing.T) {
t.Parallel()
db := pqtest.MustDB(t)
_, err := db.Query("parse_error $1", 1)
mustAs(t, err, pqerror.SyntaxError)
rows, err := db.Query("select 1")
if err != nil {
t.Fatal(err)
}
rows.Close()
}
// TestReturning tests that an INSERT query using the RETURNING clause returns a row.
func TestReturning(t *testing.T) {
t.Parallel()
db := pqtest.MustDB(t)
pqtest.Exec(t, db, `create temp table tbl (did integer default 0, dname text)`)
have := pqtest.Query[int](t, db, `insert into tbl (did, dname) values (default, 'a'), (5, 'b') returning did;`)
want := []map[string]int{{"did": 0}, {"did": 5}}
if !reflect.DeepEqual(have, want) {
t.Errorf("\nhave: %#v\nwant: %#v", have, want)
}
}
func TestExecNoData(t *testing.T) { // See #186
t.Parallel()
db := pqtest.MustDB(t)
// Exec() a query which returns results
pqtest.Exec(t, db, "values (1), (2), (3)")
pqtest.Exec(t, db, "values ($1::int), ($2::int), ($3::int)", 1, 2, 3)
// Query() a query which doesn't return any results
tx := pqtest.Begin(t, db)
have := pqtest.QueryRow[any](t, tx, `create temp table foo(f1 int)`)
var want map[string]any
if !reflect.DeepEqual(have, want) {
t.Errorf("\nhave: %#v\nwant: %#v", have, want)
}
if !pqtest.Cockroach() { // "unimplemented: this syntax (0A000)"
// Get NoData from a parameterized query.
pqtest.Exec(t, tx, `create rule nodata as on insert to foo do instead nothing`)
have = pqtest.QueryRow[any](t, tx, `insert into foo values ($1)`, 1)
if !reflect.DeepEqual(have, want) {
t.Errorf("\nhave: %#v\nwant: %#v", have, want)
}
}
}
// Test that any CommandComplete messages sent before the query results are
// ignored.
func TestIssue282(t *testing.T) {
t.Parallel()
db := pqtest.MustDB(t)
have := pqtest.QueryRow[string](t, db, `
set search_path to pg_catalog;
set local search_path to pg_catalog;
show search_path`)
want := map[string]string{"search_path": "pg_catalog"}
if !reflect.DeepEqual(have, want) {
t.Errorf("\nhave: %#v\nwant: %#v", have, want)
}
}
func TestFloatPrecision(t *testing.T) { // See #196
// encode() sends float32 as a float64, which adds extra precision: 0.10000122338533401
// This is done by driver.DefaultParameterConverter(); we can maybe fix it,
// but it's really a cockroach bug.
// https://github.com/cockroachdb/cockroach/issues/73743
// https://github.com/cockroachdb/cockroach/issues/84326
pqtest.SkipCockroach(t)
t.Parallel()
db := pqtest.MustDB(t)
have := pqtest.QueryRow[bool](t, db, `select '0.10000122'::float4 = $1::float4 as f4, '35.03554004971999'::float8 = $2 as f8`,
float32(0.10000122), float64(35.03554004971999))
want := map[string]bool{"f4": true, "f8": true}
if !reflect.DeepEqual(have, want) {
t.Errorf("\nhave: %#v\nwant: %#v", have, want)
}
type h struct {
F4 float32
F8, F4Short float64
}
var have2 h
err := db.QueryRow("select '0.10000122'::float4, '35.03554004971999'::float8, '1.2'::float4").
Scan(&have2.F4, &have2.F8, &have2.F4Short)
if err != nil {
t.Fatal(err)
}
want2 := h{0.10000122, 35.03554004971999, 1.2}
if !reflect.DeepEqual(have2, want2) {
t.Errorf("\nhave: %#v\nwant: %#v", have2, want2)
}
}
func TestParseComplete(t *testing.T) {
tests := []struct {
in, want string
wantRows int64
wantErr string
}{
{"ALTER TABLE", "ALTER TABLE", 0, ``},
{"INSERT 0 1", "INSERT", 1, ``},
{"UPDATE 100", "UPDATE", 100, ``},
{"SELECT 100", "SELECT", 100, ``},
{"FETCH 100", "FETCH", 100, ``},
{"COPY", "COPY", 0, ``}, // allow COPY (and others) without row count
{"UNKNOWNCOMMANDTAG", "UNKNOWNCOMMANDTAG", 0, ``}, // don't fail on command tags we don't recognize
{"INSERT 1", "", 0, `pq: unexpected INSERT command tag INSERT 1`}, // missing oid
{"UPDATE 0 1", "", 0, `pq: could not parse commandTag: strconv.ParseInt: parsing "0 1": invalid syntax`}, // too many numbers
{"SELECT foo", "", 0, `pq: could not parse commandTag: strconv.ParseInt: parsing "foo": invalid syntax`}, // invalid row count
}
for _, tt := range tests {
t.Run("", func(t *testing.T) {
res, have, err := (&conn{}).parseComplete(tt.in)
if !pqtest.ErrorContains(err, tt.wantErr) {
t.Errorf("wrong error:\nhave: %s\nwant: %s", err, tt.wantErr)
}
if tt.wantErr != "" {
return
}
if have != tt.want {
t.Fatalf("\nhave: %q\nwant: %q", have, tt.want)
}
haveRows, err := res.RowsAffected()
if err != nil {
t.Fatal(err)
}
if haveRows != tt.wantRows {
t.Fatalf("\nhave: %q\nwant: %q", haveRows, tt.wantRows)
}
})
}
}
func TestNullAfterNonNull(t *testing.T) {
t.Parallel()
have := pqtest.Query[sql.NullInt64](t, pqtest.MustDB(t), `select 9::integer union select NULL::integer`)
want := []map[string]sql.NullInt64{{"int4": {Int64: 9, Valid: true}}, {"int4": {}}}
if !reflect.DeepEqual(have, want) {
t.Errorf("\nhave: %#v\nwant: %#v", have, want)
}
}
func Test64BitErrorChecking(t *testing.T) {
defer func() {
if err := recover(); err != nil {
t.Fatal("panic due to 0xFFFFFFFF != -1 when int is 64 bits")
}
}()
have := pqtest.Query[any](t, pqtest.MustDB(t), `select * from (values (0::integer, NULL::text), (1, 'test string')) as t`)
want := []map[string]any{{"column1": int64(0), "column2": any(nil)}, {"column1": int64(1), "column2": "test string"}}
if !reflect.DeepEqual(have, want) {
t.Errorf("\nhave: %#v\nwant: %#v", have, want)
}
}
func TestCommit(t *testing.T) {
db := pqtest.MustDB(t)
pqtest.Exec(t, db, "create temp table tbl (a int)")
tx := pqtest.Begin(t, db)
pqtest.Exec(t, tx, `insert into tbl values (1)`)
err := tx.Commit()
if err != nil {
t.Fatal(err)
}
var i int
err = db.QueryRow(`select * from tbl`).Scan(&i)
if err != nil {
t.Fatal(err)
}
if i != 1 {
t.Fatalf("expected 1, got %d", i)
}
}
func TestRowsResultTag(t *testing.T) {
tests := []struct {
query string
tag string
ra int64
}{
{"CREATE TEMP TABLE temp (a int)", "CREATE TABLE", 0},
{"INSERT INTO temp VALUES (1), (2)", "INSERT", 2},
{"SELECT 1", "", 0},
// A SELECT anywhere should take precedent.
{"SELECT 1; INSERT INTO temp VALUES (1), (2)", "", 0},
{"INSERT INTO temp VALUES (1), (2); SELECT 1", "", 0},
// Multiple statements that don't return rows should return the last tag.
{"CREATE TEMP TABLE t (a int); DROP TABLE t", "DROP TABLE", 0},
// Ensure a rows-returning query in any position among various tags-returing
// statements will prefer the rows.
{"SELECT 1; CREATE TEMP TABLE t (a int); DROP TABLE t", "", 0},
{"CREATE TEMP TABLE t (a int); SELECT 1; DROP TABLE t", "", 0},
{"CREATE TEMP TABLE t (a int); DROP TABLE t; SELECT 1", "", 0},
}
type ResultTag interface {
Result() driver.Result
Tag() string
}
conn, err := Open("")
if err != nil {
t.Fatal(err)
}
defer conn.Close()
q := conn.(driver.QueryerContext)
for _, tt := range tests {
rows, err := q.QueryContext(context.Background(), tt.query, nil)