Skip to content

Commit c0f27a8

Browse files
committed
Clarify need for connect_timeout in the DSN
Add connect_timeout to the examples and clarify why this is a good idea in the README: database/sql may open new connections asynchronously so it doesn't use the context from QueryContext(), PingContext(), etc. This makes sense, but is somewhat unexpected. Fixes #1020
1 parent 1f3e3d9 commit c0f27a8

2 files changed

Lines changed: 11 additions & 6 deletions

File tree

README.md

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ import (
2222

2323
func main() {
2424
// Or as URL: postgresql://localhost/pqgo
25-
db, err := sql.Open("postgres", "host=localhost dbname=pqgo")
25+
db, err := sql.Open("postgres", "host=localhost dbname=pqgo connect_timeout=5")
2626
if err != nil {
2727
log.Fatal(err)
2828
}
@@ -42,9 +42,10 @@ You can also use the `pq.Config` struct:
4242

4343
```go
4444
cfg := pq.Config{
45-
Host: "localhost",
46-
Port: 5432,
47-
User: "pqgo",
45+
Host: "localhost",
46+
Port: 5432,
47+
User: "pqgo",
48+
ConnectTimeout: 5 * time.Second,
4849
}
4950
// Or: create a new Config from the defaults, environment, and DSN.
5051
// cfg, err := pq.NewConfig("host=postgres dbname=pqgo")
@@ -85,6 +86,10 @@ The libpq way (which also works in pq) is to use `options='-c k=v'` like so:
8586

8687
sql.Open("postgres", "dbname=pqgo options='-c work_mem=100kB -c search_path=xyz'")
8788

89+
It's recommended to add `connect_timeout` to the DSN – database/sql may open new
90+
connections asynchronously so it doesn't use the context from QueryContext(),
91+
PingContext(), etc. The default is to wait indefinitely.
92+
8893
[Config struct]: https://pkg.go.dev/github.com/lib/pq#Config
8994
[run-time parameter]: http://www.postgresql.org/docs/current/static/runtime-config.html
9095

doc.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ directly. For example:
1111
)
1212
1313
func main() {
14-
dsn := "user=pqgo dbname=pqgo sslmode=verify-full"
14+
dsn := "user=pqgo dbname=pqgo sslmode=verify-full connect_timeout=5"
1515
db, err := sql.Open("postgres", dsn)
1616
if err != nil {
1717
log.Fatal(err)
@@ -24,7 +24,7 @@ directly. For example:
2424
2525
You can also connect with an URL:
2626
27-
dsn := "postgres://pqgo:password@localhost/pqgo?sslmode=verify-full"
27+
dsn := "postgres://pqgo:password@localhost/pqgo?sslmode=verify-full&connect_timeout=5"
2828
db, err := sql.Open("postgres", dsn)
2929
3030
# Connection String Parameters

0 commit comments

Comments
 (0)