+1
Daily
9,974
stars
973
forks
144
watchers
637
prs
813
issues
27
releases
README
pq is a Go PostgreSQL driver for database/sql.
All [maintained versions of PostgreSQL] are supported. Older versions may work,
but this is not tested. [API docs].
[maintained versions of PostgreSQL]: https://www.postgresql.org/support/versioning
[API docs]: https://pkg.go.dev/github.com/lib/pq
Connecting
----------
Use the postgres driver name in the sql.Open() call:
go
package main
import (
"database/sql"
"log"
_ "github.com/lib/pq" // To register the driver.
)
func main() {
// Or as URL: postgresql://localhost/pqgo
db, err := sql.Open("postgres", "host=localhost dbname=pqgo connect_timeout=5")
if err != nil {
log.Fatal(err)
}
defer db.Close()
// db.Open() only creates a connection pool, and doesn't actually establish
// a connection. To ensure the connection works you need to do something
// with a connection.
err = db.Ping()
if err != nil {
log.Fatal(err)
}
}
You can also use the pq.Config struct:
go
cfg := pq.Config{
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")
// if err != nil {
// log.Fatal(err)
// }
c, err := pq.NewConnectorConfig(cfg)
if err != nil {
log.Fatal(err)
}
// Create connection pool.
db := sql.OpenDB(c)
defer db.Close()
// Make sure it works.
err = db.Ping()
if err != nil {
log.Fatal(err)
}
The DSN is identical to PostgreSQL's libpq; most parameters are supported and
should behave identical. Both key=value and postgres:// URL-style connection
strings are supported. See the doc comments on the [Config struct] for the full
list and documentation.
The most notable difference is that you can use any [run-time parameter] such as
search_path or work_mem in the connection string. This is different from
libpq, which uses the options parameter for this (which also works in pq).
For example:
sql.Open("postgres", "dbname=pqgo work_mem=100kB search_path=xyz")
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/pqConfig
[run-time parameter]: http://www.postgresql.org/docs/current/static/runtime-config.html
Errors
------
Errors from PostgreSQL are returned as [pq.Error]; [pq.As] can be used to
convert an error to pq.Error:
go
pqErr := pq.As(err, pqerror.UniqueViolation)
if pqErr != nil {
return fmt.Errorf("email %q already exsts", email)
}
the Error() string contains the error message and code:
pq: duplicate key value violates unique constraint "users_lower_idx" (23Top issues
#450Support read timeout for queries22 comments · 2016-03-28#360Add TcpKeepAlive22 comments · 2015-04-07#78Add support for scanning postgresql `interval` type into `time.Duration`20 comments · 2013-02-10#534Implement Named Parameters19 comments · 2016-11-07#620Context cancel hangs if there is no network connectivity16 comments · 2017-05-31#786Context support14 comments · 2018-09-07#213Better support for COPY operations11 comments · 2013-12-29#835At time DB reconnect fail with read tcp [::1]:49528->[::1]:5432: read: connection reset by peer8 comments · 2019-03-11
Latest release
v1.12.3 v1.12.3 2026-04-03- Send datestyle startup parameter, improving compatbility with database engines that use a different default datestyle such as EnterpriseDB ([1312]). [1312]: https://github.com/lib/pq/pull/1312