From 6c4492dec0a2e80a2a1ab88c859ae45d544e7481 Mon Sep 17 00:00:00 2001 From: Martin Tournoij Date: Wed, 8 Apr 2026 14:48:50 +0100 Subject: [PATCH] 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 --- README.md | 13 +++++++++---- doc.go | 4 ++-- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 159b86721..79bf136b4 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ import ( func main() { // Or as URL: postgresql://localhost/pqgo - db, err := sql.Open("postgres", "host=localhost dbname=pqgo") + db, err := sql.Open("postgres", "host=localhost dbname=pqgo connect_timeout=5") if err != nil { log.Fatal(err) } @@ -42,9 +42,10 @@ You can also use the `pq.Config` struct: ```go cfg := pq.Config{ - Host: "localhost", - Port: 5432, - User: "pqgo", + Host: "localhost", + Port: 5432, + User: "pqgo", + ConnectTimeout: 5 * time.Second, } // Or: create a new Config from the defaults, environment, and DSN. // 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: sql.Open("postgres", "dbname=pqgo options='-c work_mem=100kB -c search_path=xyz'") +It's recommended to add `connect_timeout` to the DSN – database/sql may open new +connections asynchronously so it doesn't use the context from QueryContext(), +PingContext(), etc. The default is to wait indefinitely. + [Config struct]: https://pkg.go.dev/github.com/lib/pq#Config [run-time parameter]: http://www.postgresql.org/docs/current/static/runtime-config.html diff --git a/doc.go b/doc.go index 9d9d78e46..a2408176f 100644 --- a/doc.go +++ b/doc.go @@ -11,7 +11,7 @@ directly. For example: ) func main() { - dsn := "user=pqgo dbname=pqgo sslmode=verify-full" + dsn := "user=pqgo dbname=pqgo sslmode=verify-full connect_timeout=5" db, err := sql.Open("postgres", dsn) if err != nil { log.Fatal(err) @@ -24,7 +24,7 @@ directly. For example: You can also connect with an URL: - dsn := "postgres://pqgo:password@localhost/pqgo?sslmode=verify-full" + dsn := "postgres://pqgo:password@localhost/pqgo?sslmode=verify-full&connect_timeout=5" db, err := sql.Open("postgres", dsn) # Connection String Parameters