forked from lib/pq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn_test.go
1659 lines (1459 loc) · 36.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
package pq
import (
"context"
"database/sql"
"database/sql/driver"
"fmt"
"io"
"net"
"os"
"reflect"
"strings"
"testing"
"time"
)
type Fatalistic interface {
Fatal(args ...interface{})
}
func forceBinaryParameters() bool {
bp := os.Getenv("PQTEST_BINARY_PARAMETERS")
if bp == "yes" {
return true
} else if bp == "" || bp == "no" {
return false
} else {
panic("unexpected value for PQTEST_BINARY_PARAMETERS")
}
}
func testConninfo(conninfo string) string {
defaultTo := func(envvar string, value string) {
if os.Getenv(envvar) == "" {
os.Setenv(envvar, value)
}
}
defaultTo("PGDATABASE", "pqgotest")
defaultTo("PGSSLMODE", "disable")
defaultTo("PGCONNECT_TIMEOUT", "20")
if forceBinaryParameters() &&
!strings.HasPrefix(conninfo, "postgres://") &&
!strings.HasPrefix(conninfo, "postgresql://") {
conninfo = conninfo + " binary_parameters=yes"
}
return conninfo
}
func openTestConnConninfo(conninfo string) (*sql.DB, error) {
return sql.Open("postgres", testConninfo(conninfo))
}
func openTestConn(t Fatalistic) *sql.DB {
conn, err := openTestConnConninfo("")
if err != nil {
t.Fatal(err)
}
return conn
}
func getServerVersion(t *testing.T, db *sql.DB) int {
var version int
err := db.QueryRow("SHOW server_version_num").Scan(&version)
if err != nil {
t.Fatal(err)
}
return version
}
func TestReconnect(t *testing.T) {
db1 := openTestConn(t)
defer db1.Close()
tx, err := db1.Begin()
if err != nil {
t.Fatal(err)
}
var pid1 int
err = tx.QueryRow("SELECT pg_backend_pid()").Scan(&pid1)
if err != nil {
t.Fatal(err)
}
db2 := openTestConn(t)
defer db2.Close()
_, err = db2.Exec("SELECT pg_terminate_backend($1)", pid1)
if err != nil {
t.Fatal(err)
}
// The rollback will probably "fail" because we just killed
// its connection above
_ = tx.Rollback()
const expected int = 42
var result int
err = db1.QueryRow(fmt.Sprintf("SELECT %d", expected)).Scan(&result)
if err != nil {
t.Fatal(err)
}
if result != expected {
t.Errorf("got %v; expected %v", result, expected)
}
}
func TestCommitInFailedTransaction(t *testing.T) {
db := openTestConn(t)
defer db.Close()
txn, err := db.Begin()
if err != nil {
t.Fatal(err)
}
rows, err := txn.Query("SELECT error")
if err == nil {
rows.Close()
t.Fatal("expected failure")
}
err = txn.Commit()
if err != ErrInFailedTransaction {
t.Fatalf("expected ErrInFailedTransaction; got %#v", err)
}
}
func TestOpenURL(t *testing.T) {
testURL := func(url string) {
db, err := openTestConnConninfo(url)
if err != nil {
t.Fatal(err)
}
defer db.Close()
// database/sql might not call our Open at all unless we do something with
// the connection
txn, err := db.Begin()
if err != nil {
t.Fatal(err)
}
txn.Rollback()
}
testURL("postgres://")
testURL("postgresql://")
}
const pgpassFile = "/tmp/pqgotest_pgpass"
func TestPgpass(t *testing.T) {
if os.Getenv("TRAVIS") != "true" {
t.Skip("not running under Travis, skipping pgpass tests")
}
testAssert := func(conninfo string, expected string, reason string) {
conn, err := openTestConnConninfo(conninfo)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
txn, err := conn.Begin()
if err != nil {
if expected != "fail" {
t.Fatalf(reason, err)
}
return
}
rows, err := txn.Query("SELECT USER")
if err != nil {
txn.Rollback()
if expected != "fail" {
t.Fatalf(reason, err)
}
} else {
rows.Close()
if expected != "ok" {
t.Fatalf(reason, err)
}
}
txn.Rollback()
}
testAssert("", "ok", "missing .pgpass, unexpected error %#v")
os.Setenv("PGPASSFILE", pgpassFile)
testAssert("host=/tmp", "fail", ", unexpected error %#v")
os.Remove(pgpassFile)
pgpass, err := os.OpenFile(pgpassFile, os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
t.Fatalf("Unexpected error writing pgpass file %#v", err)
}
_, err = pgpass.WriteString(`# comment
server:5432:some_db:some_user:pass_A
*:5432:some_db:some_user:pass_B
localhost:*:*:*:pass_C
*:*:*:*:pass_fallback
`)
if err != nil {
t.Fatalf("Unexpected error writing pgpass file %#v", err)
}
pgpass.Close()
assertPassword := func(extra values, expected string) {
o := values{
"host": "localhost",
"sslmode": "disable",
"connect_timeout": "20",
"user": "majid",
"port": "5432",
"extra_float_digits": "2",
"dbname": "pqgotest",
"client_encoding": "UTF8",
"datestyle": "ISO, MDY",
}
for k, v := range extra {
o[k] = v
}
(&conn{}).handlePgpass(o)
if pw := o["password"]; pw != expected {
t.Fatalf("For %v expected %s got %s", extra, expected, pw)
}
}
// wrong permissions for the pgpass file means it should be ignored
assertPassword(values{"host": "example.com", "user": "foo"}, "")
// fix the permissions and check if it has taken effect
os.Chmod(pgpassFile, 0600)
assertPassword(values{"host": "server", "dbname": "some_db", "user": "some_user"}, "pass_A")
assertPassword(values{"host": "example.com", "user": "foo"}, "pass_fallback")
assertPassword(values{"host": "example.com", "dbname": "some_db", "user": "some_user"}, "pass_B")
// localhost also matches the default "" and UNIX sockets
assertPassword(values{"host": "", "user": "some_user"}, "pass_C")
assertPassword(values{"host": "/tmp", "user": "some_user"}, "pass_C")
// cleanup
os.Remove(pgpassFile)
os.Setenv("PGPASSFILE", "")
}
func TestExec(t *testing.T) {
db := openTestConn(t)
defer db.Close()
_, err := db.Exec("CREATE TEMP TABLE temp (a int)")
if err != nil {
t.Fatal(err)
}
r, err := db.Exec("INSERT INTO temp VALUES (1)")
if err != nil {
t.Fatal(err)
}
if n, _ := r.RowsAffected(); n != 1 {
t.Fatalf("expected 1 row affected, not %d", n)
}
r, err = db.Exec("INSERT INTO temp VALUES ($1), ($2), ($3)", 1, 2, 3)
if err != nil {
t.Fatal(err)
}
if n, _ := r.RowsAffected(); n != 3 {
t.Fatalf("expected 3 rows affected, not %d", n)
}
// SELECT doesn't send the number of returned rows in the command tag
// before 9.0
if getServerVersion(t, db) >= 90000 {
r, err = db.Exec("SELECT g FROM generate_series(1, 2) g")
if err != nil {
t.Fatal(err)
}
if n, _ := r.RowsAffected(); n != 2 {
t.Fatalf("expected 2 rows affected, not %d", n)
}
r, err = db.Exec("SELECT g FROM generate_series(1, $1) g", 3)
if err != nil {
t.Fatal(err)
}
if n, _ := r.RowsAffected(); n != 3 {
t.Fatalf("expected 3 rows affected, not %d", n)
}
}
}
func TestStatment(t *testing.T) {
db := openTestConn(t)
defer db.Close()
st, err := db.Prepare("SELECT 1")
if err != nil {
t.Fatal(err)
}
st1, err := db.Prepare("SELECT 2")
if err != nil {
t.Fatal(err)
}
r, err := st.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)
}
// st1
r1, err := st1.Query()
if err != nil {
t.Fatal(err)
}
defer r1.Close()
if !r1.Next() {
if r.Err() != nil {
t.Fatal(r1.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 TestRowsCloseBeforeDone(t *testing.T) {
db := openTestConn(t)
defer db.Close()
r, err := db.Query("SELECT 1")
if err != nil {
t.Fatal(err)
}
err = r.Close()
if err != nil {
t.Fatal(err)
}
if r.Next() {
t.Fatal("unexpected row")
}
if r.Err() != nil {
t.Fatal(r.Err())
}
}
func TestParameterCountMismatch(t *testing.T) {
db := openTestConn(t)
defer db.Close()
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 := openTestConn(t)
defer db.Close()
res, err := db.Exec("")
if err != nil {
t.Fatal(err)
}
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 := db.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())
}
stmt, err := db.Prepare("")
if err != nil {
t.Fatal(err)
}
res, err = stmt.Exec()
if err != nil {
t.Fatal(err)
}
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 := openTestConn(t)
defer db.Close()
rows, err := db.Query("SELECT 1 AS a, text 'bar' AS bar WHERE FALSE")
if err != nil {
t.Fatal(err)
}
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)
}
stmt, err := db.Prepare("SELECT $1::int AS a, text 'bar' AS bar WHERE FALSE")
if err != nil {
t.Fatal(err)
}
rows, err = stmt.Query(1)
if err != nil {
t.Fatal(err)
}
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 := openTestConn(t)
defer db.Close()
q := `
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
`
// AND '2000-1-1 12:00:00.000000-7'::timestamp = $3
exp1 := []byte{0, 1, 2}
exp2 := "foobar"
r, err := db.Query(q, exp1, exp2, nil)
if err != nil {
t.Fatal(err)
}
defer r.Close()
if !r.Next() {
if r.Err() != nil {
t.Fatal(r.Err())
}
t.Fatal("expected row")
}
var got1 []byte
var got2 string
var got3 = sql.NullInt64{Valid: true}
var got4 time.Time
var got5, got6, got7, got8 interface{}
err = r.Scan(&got1, &got2, &got3, &got4, &got5, &got6, &got7, &got8)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(exp1, got1) {
t.Errorf("expected %q byte: %q", exp1, got1)
}
if !reflect.DeepEqual(exp2, got2) {
t.Errorf("expected %q byte: %q", exp2, got2)
}
if got3.Valid {
t.Fatal("expected invalid")
}
if got4.Year() != 2000 {
t.Fatal("wrong year")
}
if got5 != false {
t.Fatalf("expected false, got %q", got5)
}
if got6 != int64(123) {
t.Fatalf("expected 123, got %d", got6)
}
if got7 != int64(-321) {
t.Fatalf("expected -321, got %d", got7)
}
if got8 != float64(3.14) {
t.Fatalf("expected 3.14, got %f", got8)
}
}
func TestNoData(t *testing.T) {
db := openTestConn(t)
defer db.Close()
st, err := db.Prepare("SELECT 1 WHERE true = false")
if err != nil {
t.Fatal(err)
}
defer st.Close()
r, err := st.Query()
if err != nil {
t.Fatal(err)
}
defer r.Close()
if r.Next() {
if r.Err() != nil {
t.Fatal(r.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) {
// Don't use the normal connection setup, this is intended to
// blow up in the startup packet from a non-existent user.
db, err := openTestConnConninfo("user=thisuserreallydoesntexist")
if err != nil {
t.Fatal(err)
}
defer db.Close()
_, err = db.Begin()
if err == nil {
t.Fatal("expected error")
}
e, ok := err.(*Error)
if !ok {
t.Fatalf("expected Error, got %#v", err)
} else if e.Code.Name() != "invalid_authorization_specification" && e.Code.Name() != "invalid_password" {
t.Fatalf("expected invalid_authorization_specification or invalid_password, got %s (%+v)", e.Code.Name(), err)
}
}
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, testConninfo("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) {
var err error
cn := conn{}
func() {
defer cn.errRecover(&err)
panic(io.EOF)
}()
if err != driver.ErrBadConn {
t.Fatalf("expected driver.ErrBadConn, got: %#v", err)
}
if !cn.bad {
t.Fatalf("expected cn.bad")
}
cn = conn{}
func() {
defer cn.errRecover(&err)
e := &Error{Severity: Efatal}
panic(e)
}()
if err != driver.ErrBadConn {
t.Fatalf("expected driver.ErrBadConn, got: %#v", err)
}
if !cn.bad {
t.Fatalf("expected cn.bad")
}
}
// TestCloseBadConn tests that the underlying connection can be closed with
// Close after an error.
func TestCloseBadConn(t *testing.T) {
nc, err := net.Dial("tcp", "localhost:5432")
if err != nil {
t.Fatal(err)
}
cn := conn{c: nc}
func() {
defer cn.errRecover(&err)
panic(io.EOF)
}()
// Verify we can write before closing.
if _, err := nc.Write(nil); err != nil {
t.Fatal(err)
}
// First close should close the connection.
if err := cn.Close(); err != nil {
t.Fatal(err)
}
// During the Go 1.9 cycle, https://github.com/golang/go/commit/3792db5
// changed this error from
//
// net.errClosing = errors.New("use of closed network connection")
//
// to
//
// internal/poll.ErrClosing = errors.New("use of closed file or network connection")
const errClosing = "use of closed"
// Verify write after closing fails.
if _, err := nc.Write(nil); err == nil {
t.Fatal("expected error")
} else if !strings.Contains(err.Error(), errClosing) {
t.Fatalf("expected %s error, got %s", errClosing, err)
}
// Verify second close fails.
if err := cn.Close(); err == nil {
t.Fatal("expected error")
} else if !strings.Contains(err.Error(), errClosing) {
t.Fatalf("expected %s error, got %s", errClosing, err)
}
}
func TestErrorOnExec(t *testing.T) {
db := openTestConn(t)
defer db.Close()
txn, err := db.Begin()
if err != nil {
t.Fatal(err)
}
defer txn.Rollback()
_, err = txn.Exec("CREATE TEMPORARY TABLE foo(f1 int PRIMARY KEY)")
if err != nil {
t.Fatal(err)
}
_, err = txn.Exec("INSERT INTO foo VALUES (0), (0)")
if err == nil {
t.Fatal("Should have raised error")
}
e, ok := err.(*Error)
if !ok {
t.Fatalf("expected Error, got %#v", err)
} else if e.Code.Name() != "unique_violation" {
t.Fatalf("expected unique_violation, got %s (%+v)", e.Code.Name(), err)
}
}
func TestErrorOnQuery(t *testing.T) {
db := openTestConn(t)
defer db.Close()
txn, err := db.Begin()
if err != nil {
t.Fatal(err)
}
defer txn.Rollback()
_, err = txn.Exec("CREATE TEMPORARY TABLE foo(f1 int PRIMARY KEY)")
if err != nil {
t.Fatal(err)
}
_, err = txn.Query("INSERT INTO foo VALUES (0), (0)")
if err == nil {
t.Fatal("Should have raised error")
}
e, ok := err.(*Error)
if !ok {
t.Fatalf("expected Error, got %#v", err)
} else if e.Code.Name() != "unique_violation" {
t.Fatalf("expected unique_violation, got %s (%+v)", e.Code.Name(), err)
}
}
func TestErrorOnQueryRowSimpleQuery(t *testing.T) {
db := openTestConn(t)
defer db.Close()
txn, err := db.Begin()
if err != nil {
t.Fatal(err)
}
defer txn.Rollback()
_, err = txn.Exec("CREATE TEMPORARY TABLE foo(f1 int PRIMARY KEY)")
if err != nil {
t.Fatal(err)
}
var v int
err = txn.QueryRow("INSERT INTO foo VALUES (0), (0)").Scan(&v)
if err == nil {
t.Fatal("Should have raised error")
}
e, ok := err.(*Error)
if !ok {
t.Fatalf("expected Error, got %#v", err)
} else if e.Code.Name() != "unique_violation" {
t.Fatalf("expected unique_violation, got %s (%+v)", e.Code.Name(), err)
}
}
// Test the QueryRow bug workarounds in stmt.exec() and simpleQuery()
func TestQueryRowBugWorkaround(t *testing.T) {
db := openTestConn(t)
defer db.Close()
// stmt.exec()
_, err := db.Exec("CREATE TEMP TABLE notnulltemp (a varchar(10) not null)")
if err != nil {
t.Fatal(err)
}
var a string
err = db.QueryRow("INSERT INTO notnulltemp(a) values($1) RETURNING a", nil).Scan(&a)
if err == sql.ErrNoRows {
t.Fatalf("expected constraint violation error; got: %v", err)
}
pge, ok := err.(*Error)
if !ok {
t.Fatalf("expected *Error; got: %#v", err)
}
if pge.Code.Name() != "not_null_violation" {
t.Fatalf("expected not_null_violation; got: %s (%+v)", pge.Code.Name(), err)
}
// Test workaround in simpleQuery()
tx, err := db.Begin()
if err != nil {
t.Fatalf("unexpected error %s in Begin", err)
}
defer tx.Rollback()
_, err = tx.Exec("SET LOCAL check_function_bodies TO FALSE")
if err != nil {
t.Fatalf("could not disable check_function_bodies: %s", err)
}
_, err = tx.Exec(`
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`)
if err != nil {
t.Fatalf("could not create function: %s", err)
}
err = tx.QueryRow("SELECT * FROM bad_function()").Scan(&a)
if err == nil {
t.Fatalf("expected error")
}
pge, ok = err.(*Error)
if !ok {
t.Fatalf("expected *Error; got: %#v", err)
}
if pge.Code.Name() != "invalid_function_definition" {
t.Fatalf("expected invalid_function_definition; got: %s (%+v)", pge.Code.Name(), err)
}
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)
}
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")
}
pge, ok = rows.Err().(*Error)
if !ok {
t.Fatalf("expected *Error; got: %#v", err)
}
if pge.Code.Name() != "cardinality_violation" {
t.Fatalf("expected cardinality_violation; got: %s (%+v)", pge.Code.Name(), rows.Err())
}
}
func TestSimpleQuery(t *testing.T) {
db := openTestConn(t)
defer db.Close()
r, err := db.Query("select 1")
if err != nil {
t.Fatal(err)
}
defer r.Close()
if !r.Next() {
t.Fatal("expected row")
}
}
func TestBindError(t *testing.T) {
db := openTestConn(t)
defer db.Close()
_, err := db.Exec("create temp table test (i integer)")
if err != nil {
t.Fatal(err)
}
_, err = db.Query("select * from test where i=$1", "hhh")
if err == nil {
t.Fatal("expected an error")
}
// Should not get error here
r, err := db.Query("select * from test where i=$1", 1)
if err != nil {
t.Fatal(err)
}
defer r.Close()
}
func TestParseErrorInExtendedQuery(t *testing.T) {
db := openTestConn(t)
defer db.Close()
_, err := db.Query("PARSE_ERROR $1", 1)
pqErr, _ := err.(*Error)
// Expecting a syntax error.
if err == nil || pqErr == nil || pqErr.Code != "42601" {
t.Fatalf("expected syntax error, got %s", err)
}
rows, err := db.Query("SELECT 1")