Documentation
¶
Overview ¶
Package pq is a Go PostgreSQL driver for database/sql.
Most clients will use the database/sql package instead of using this package directly. For example:
import (
"database/sql"
_ "github.com/lib/pq"
)
func main() {
dsn := "user=pqgo dbname=pqgo sslmode=verify-full"
db, err := sql.Open("postgres", dsn)
if err != nil {
log.Fatal(err)
}
age := 21
rows, err := db.Query("select name from users where age = $1", age)
// …
}
You can also connect with an URL:
dsn := "postgres://pqgo:password@localhost/pqgo?sslmode=verify-full"
db, err := sql.Open("postgres", dsn)
Connection String Parameters ¶
See NewConfig.
Queries ¶
database/sql does not dictate any specific format for parameter placeholders, and pq uses the PostgreSQL-native ordinal markers ($1, $2, etc.). The same placeholder can be used more than once:
rows, err := db.Query( `select * from users where name = $1 or age between $2 and $2 + 3`, "Duck", 64)
pq does not support sql.Result.LastInsertId. Use the RETURNING clause with a Query or QueryRow call instead to return the identifier:
row := db.QueryRow(`insert into users(name, age) values('Scrooge McDuck', 93) returning id`)
var userid int
err := row.Scan(&userid)
Data Types ¶
Parameters pass through driver.DefaultParameterConverter before they are handled by this package. When the binary_parameters connection option is enabled, []byte values are sent directly to the backend as data in binary format.
This package returns the following types for values from the PostgreSQL backend:
- integer types smallint, integer, and bigint are returned as int64
- floating-point types real and double precision are returned as float64
- character types char, varchar, and text are returned as string
- temporal types date, time, timetz, timestamp, and timestamptz are returned as time.Time
- the boolean type is returned as bool
- the bytea type is returned as []byte
All other types are returned directly from the backend as []byte values in text format.
Errors ¶
pq may return errors of type *pq.Error which contain error details:
pqErr := new(pq.Error)
if errors.As(err, &pqErr) {
fmt.Println("pq error:", pqErr.Code.Name())
}
Bulk imports ¶
You can perform bulk imports by preparing a statement returned by CopyIn (or CopyInSchema) in an explicit transaction (sql.Tx). The returned statement handle can then be repeatedly "executed" to copy data into the target table. After all data has been processed you should call Exec() once with no arguments to flush all buffered data. Any call to Exec() might return an error which should be handled appropriately, but because of the internal buffering an error returned by Exec() might not be related to the data passed in the call that failed.
CopyIn uses COPY FROM internally. It is not possible to COPY outside of an explicit transaction in pq.
Notifications ¶
PostgreSQL supports a simple publish/subscribe model using PostgreSQL's NOTIFY mechanism.
To start listening for notifications, you first have to open a new connection to the database by calling NewListener. This connection can not be used for anything other than LISTEN / NOTIFY. Calling Listen will open a "notification channel"; once a notification channel is open, a notification generated on that channel will effect a send on the Listener.Notify channel. A notification channel will remain open until Unlisten is called, though connection loss might result in some notifications being lost. To solve this problem, Listener sends a nil pointer over the Notify channel any time the connection is re-established following a connection loss. The application can get information about the state of the underlying connection by setting an event callback in the call to NewListener.
A single Listener can safely be used from concurrent goroutines, which means that there is often no need to create more than one Listener in your application. However, a Listener is always connected to a single database, so you will need to create a new Listener instance for every database you want to receive notifications in.
The channel name in both Listen and Unlisten is case sensitive, and can contain any characters legal in an identifier. Note that the channel name will be truncated to 63 bytes by the PostgreSQL server.
You can find a complete, working example of Listener usage at cmd/pqlisten.
Kerberos Support ¶
If you need support for Kerberos authentication, add the following to your main package:
import "github.com/lib/pq/auth/kerberos"
func init() {
pq.RegisterGSSProvider(func() (pq.Gss, error) { return kerberos.NewGSS() })
}
This package is in a separate module so that users who don't need Kerberos don't have to add unnecessary dependencies.
Index ¶
- Constants
- Variables
- func Array(a any) interface{ ... }
- func BufferQuoteIdentifier(name string, buffer *bytes.Buffer)
- func ConnectorNoticeHandler(c driver.Connector) func(*Error)
- func ConnectorNotificationHandler(c driver.Connector) func(*Notification)
- func CopyIn(table string, columns ...string) string
- func CopyInSchema(schema, table string, columns ...string) string
- func DialOpen(d Dialer, dsn string) (_ driver.Conn, err error)
- func EnableInfinityTs(negative time.Time, positive time.Time)
- func FormatTimestamp(t time.Time) []byte
- func NoticeHandler(c driver.Conn) func(*Error)
- func Open(dsn string) (_ driver.Conn, err error)
- func ParseTimestamp(currentLocation *time.Location, str string) (time.Time, error)
- func ParseURL(url string) (string, error)deprecated
- func QuoteIdentifier(name string) string
- func QuoteLiteral(literal string) string
- func RegisterGSSProvider(newGssArg NewGSSFunc)
- func RegisterTLSConfig(key string, config *tls.Config) error
- func SetNoticeHandler(c driver.Conn, handler func(*Error))
- func SetNotificationHandler(c driver.Conn, handler func(*Notification))
- type ArrayDelimiter
- type BoolArray
- type ByteaArray
- type Config
- type ConfigMultihost
- type Connector
- type Dialer
- type DialerContext
- type Driver
- type Error
- type ErrorClass
- type ErrorCode
- type EventCallbackType
- type Float32Array
- type Float64Array
- type GSS
- type GenericArray
- type Int32Array
- type Int64Array
- type Listener
- type ListenerConn
- func (l *ListenerConn) Close() error
- func (l *ListenerConn) Err() error
- func (l *ListenerConn) ExecSimpleQuery(q string) (executed bool, err error)
- func (l *ListenerConn) Listen(channel string) (bool, error)
- func (l *ListenerConn) Ping() error
- func (l *ListenerConn) Unlisten(channel string) (bool, error)
- func (l *ListenerConn) UnlistenAll() (bool, error)
- type ListenerEventType
- type LoadBalanceHosts
- type NewGSSFunc
- type NoticeHandlerConnector
- type Notification
- type NotificationHandlerConnector
- type NullTimedeprecated
- type PGErrordeprecated
- type SSLMode
- type SSLNegotiation
- type StringArray
- type TargetSessionAttrs
Examples ¶
Constants ¶
const ( // disable: No SSL SSLModeDisable = SSLMode("disable") // require: require SSL, but skip verification. SSLModeRequire = SSLMode("require") // verify-ca: require SSL and verify that the certificate was signed by a // trusted CA. SSLModeVerifyCA = SSLMode("verify-ca") // verify-full: require SSK and verify that the certificate was signed by a // trusted CA and the server host name matches the one in the certificate. SSLModeVerifyFull = SSLMode("verify-full") )
Values for SSLMode that pq supports.
const ( // Negotiate whether SSL should be used. This is the default. SSLNegotiationPostgres = SSLNegotiation("postgres") // Always use SSL, don't try to negotiate. SSLNegotiationDirect = SSLNegotiation("direct") )
Values for SSLNegotiation that pq supports.
const ( // Any successful connection is acceptable. This is the default. TargetSessionAttrsAny = TargetSessionAttrs("any") // Session must accept read-write transactions by default: the server must // not be in hot standby mode and default_transaction_read_only must be // off. TargetSessionAttrsReadWrite = TargetSessionAttrs("read-write") // Session must not accept read-write transactions by default. TargetSessionAttrsReadOnly = TargetSessionAttrs("read-only") // Server must not be in hot standby mode. TargetSessionAttrsPrimary = TargetSessionAttrs("primary") // Server must be in hot standby mode. TargetSessionAttrsStandby = TargetSessionAttrs("standby") // First try to find a standby server, but if none of the listed hosts is a // standby server, try again in any mode. TargetSessionAttrsPreferStandby = TargetSessionAttrs("prefer-standby") )
Values for TargetSessionAttrs that pq supports.
const ( // Don't load balance; try hosts in the order in which they're provided. // This is the default. LoadBalanceHostsDisable = LoadBalanceHosts("disable") // Hosts are tried in random order to balance connections across multiple // PostgreSQL servers. // // When using this value it's recommended to also configure a reasonable // value for connect_timeout. Because then, if one of the nodes that are // used for load balancing is not responding, a new node will be tried. LoadBalanceHostsRandom = LoadBalanceHosts("random") )
Values for LoadBalanceHosts that pq supports.
const ( Efatal = "FATAL" Epanic = "PANIC" Ewarning = "WARNING" Enotice = "NOTICE" Edebug = "DEBUG" Einfo = "INFO" Elog = "LOG" )
pq.Error.Severity values.
Variables ¶
var ( ErrNotSupported = errors.New("pq: unsupported command") ErrInFailedTransaction = errors.New("pq: could not complete operation in a failed transaction") ErrSSLNotSupported = errors.New("pq: SSL is not enabled on the server") ErrCouldNotDetectUsername = errors.New("pq: could not detect default username; please provide one explicitly") ErrSSLKeyUnknownOwnership = pqutil.ErrSSLKeyUnknownOwnership ErrSSLKeyHasWorldPermissions = pqutil.ErrSSLKeyHasWorldPermissions )
Common error types
var ErrChannelAlreadyOpen = errors.New("pq: channel is already open")
ErrChannelAlreadyOpen is returned from Listen when a channel is already open.
var ErrChannelNotOpen = errors.New("pq: channel is not open")
ErrChannelNotOpen is returned from Unlisten when a channel is not open.
Functions ¶
func Array ¶
Array returns the optimal driver.Valuer and sql.Scanner for an array or slice of any dimension.
For example:
db.Query(`SELECT * FROM t WHERE id = ANY($1)`, pq.Array([]int{235, 401}))
var x []sql.NullInt64
db.QueryRow(`SELECT ARRAY[235, 401]`).Scan(pq.Array(&x))
Scanning multi-dimensional arrays is not supported. Arrays where the lower bound is not one (such as `[0:0]={1}') are not supported.
func BufferQuoteIdentifier ¶ added in v1.10.8
BufferQuoteIdentifier satisfies the same purpose as QuoteIdentifier, but backed by a byte buffer.
func ConnectorNoticeHandler ¶ added in v1.4.0
ConnectorNoticeHandler returns the currently set notice handler, if any. If the given connector is not a result of ConnectorWithNoticeHandler, nil is returned.
func ConnectorNotificationHandler ¶ added in v1.5.1
func ConnectorNotificationHandler(c driver.Connector) func(*Notification)
ConnectorNotificationHandler returns the currently set notification handler, if any. If the given connector is not a result of ConnectorWithNotificationHandler, nil is returned.
func CopyIn ¶
CopyIn creates a COPY FROM statement which can be prepared with Tx.Prepare(). The target table should be visible in search_path.
It copies all columns if the list of columns is empty.
Example ¶
package main
import (
"database/sql"
"fmt"
"log"
"github.com/lib/pq"
)
func main() {
// Connect and create table.
db, err := sql.Open("postgres", "")
if err != nil {
log.Fatal(err)
}
_, err = db.Exec(`create temp table users (name text, age int)`)
if err != nil {
log.Fatal(err)
}
// Need to start transaction and prepare a statement.
tx, err := db.Begin()
if err != nil {
log.Fatal(err)
}
stmt, err := tx.Prepare(pq.CopyIn("users", "name", "age"))
if err != nil {
log.Fatal(err)
}
// Insert rows.
users := []struct {
Name string
Age int
}{
{"Donald Duck", 36},
{"Scrooge McDuck", 86},
}
for _, user := range users {
_, err = stmt.Exec(user.Name, int64(user.Age))
if err != nil {
log.Fatal(err)
}
}
// Finalize copy and statement, and commit transaction.
if _, err := stmt.Exec(); err != nil {
log.Fatal(err)
}
if err := stmt.Close(); err != nil {
log.Fatal(err)
}
if err := tx.Commit(); err != nil {
log.Fatal(err)
}
// Query rows to verify.
rows, err := db.Query(`select * from users order by name`)
if err != nil {
log.Fatal(err)
}
for rows.Next() {
var (
name string
age int
)
err := rows.Scan(&name, &age)
if err != nil {
log.Fatal(err)
}
fmt.Println(name, age)
}
}
Output: Donald Duck 36 Scrooge McDuck 86
func CopyInSchema ¶
CopyInSchema creates a COPY FROM statement which can be prepared with Tx.Prepare().
func EnableInfinityTs ¶
EnableInfinityTs controls the handling of Postgres' "-infinity" and "infinity" "timestamp"s.
If EnableInfinityTs is not called, "-infinity" and "infinity" will return []byte("-infinity") and []byte("infinity") respectively, and potentially cause error "sql: Scan error on column index 0: unsupported driver -> Scan pair: []uint8 -> *time.Time", when scanning into a time.Time value.
Once EnableInfinityTs has been called, all connections created using this driver will decode Postgres' "-infinity" and "infinity" for "timestamp", "timestamp with time zone" and "date" types to the predefined minimum and maximum times, respectively. When encoding time.Time values, any time which equals or precedes the predefined minimum time will be encoded to "-infinity". Any values at or past the maximum time will similarly be encoded to "infinity".
If EnableInfinityTs is called with negative >= positive, it will panic. Calling EnableInfinityTs after a connection has been established results in undefined behavior. If EnableInfinityTs is called more than once, it will panic.
func FormatTimestamp ¶
FormatTimestamp formats t into Postgres' text format for timestamps.
func NoticeHandler ¶ added in v1.4.0
NoticeHandler returns the notice handler on the given connection, if any. A runtime panic occurs if c is not a pq connection. This is rarely used directly, use ConnectorNoticeHandler and ConnectorWithNoticeHandler instead.
func Open ¶
Open opens a new connection to the database. dsn is a connection string. Most users should only use it through database/sql package from the standard library.
func ParseTimestamp ¶
ParseTimestamp parses Postgres' text format. It returns a time.Time in currentLocation iff that time's offset agrees with the offset sent from the Postgres server. Otherwise, ParseTimestamp returns a time.Time with the fixed offset offset provided by the Postgres server.
func QuoteIdentifier ¶
QuoteIdentifier quotes an "identifier" (e.g. a table or a column name) to be used as part of an SQL statement. For example:
tblname := "my_table"
data := "my_data"
quoted := pq.QuoteIdentifier(tblname)
err := db.Exec(fmt.Sprintf("INSERT INTO %s VALUES ($1)", quoted), data)
Any double quotes in name will be escaped. The quoted identifier will be case sensitive when used in a query. If the input string contains a zero byte, the result will be truncated immediately before it.
func QuoteLiteral ¶ added in v1.2.0
QuoteLiteral quotes a 'literal' (e.g. a parameter, often used to pass literal to DDL and other statements that do not accept parameters) to be used as part of an SQL statement. For example:
exp_date := pq.QuoteLiteral("2023-01-05 15:00:00Z")
err := db.Exec(fmt.Sprintf("CREATE ROLE my_user VALID UNTIL %s", exp_date))
Any single quotes in name will be escaped. Any backslashes (i.e. "\") will be replaced by two backslashes (i.e. "\\") and the C-style escape identifier that PostgreSQL provides ('E') will be prepended to the string.
func RegisterGSSProvider ¶ added in v1.7.0
func RegisterGSSProvider(newGssArg NewGSSFunc)
RegisterGSSProvider registers a GSS authentication provider. For example, if you need to use Kerberos to authenticate with your server, add this to your main package:
import "github.com/lib/pq/auth/kerberos"
func init() {
pq.RegisterGSSProvider(func() (pq.GSS, error) { return kerberos.NewGSS() })
}
func RegisterTLSConfig ¶ added in v1.11.0
RegisterTLSConfig registers a custom tls.Config. They are used by using sslmode=pqgo-«key» in the connection string.
Set the config to nil to remove a configuration.
Example ¶
package main
import (
"crypto/tls"
"crypto/x509"
"database/sql"
"log"
"os"
"github.com/lib/pq"
)
func main() {
pem, err := os.ReadFile("testdata/init/root.crt")
if err != nil {
log.Fatal(err)
}
root := x509.NewCertPool()
root.AppendCertsFromPEM(pem)
certs, err := tls.LoadX509KeyPair("testdata/init/postgresql.crt", "testdata/init/postgresql.key")
if err != nil {
log.Fatal(err)
}
pq.RegisterTLSConfig("mytls", &tls.Config{
RootCAs: root,
Certificates: []tls.Certificate{certs},
ServerName: "postgres",
})
db, err := sql.Open("postgres", "host=postgres dbname=pqgo sslmode=pqgo-mytls")
if err != nil {
log.Fatal(err)
}
err = db.Ping()
if err != nil {
log.Fatal(err)
}
}
func SetNoticeHandler ¶ added in v1.4.0
SetNoticeHandler sets the given notice handler on the given connection. A runtime panic occurs if c is not a pq connection. A nil handler may be used to unset it. This is rarely used directly, use ConnectorNoticeHandler and ConnectorWithNoticeHandler instead.
Note: Notice handlers are executed synchronously by pq meaning commands won't continue to be processed until the handler returns.
func SetNotificationHandler ¶ added in v1.5.0
func SetNotificationHandler(c driver.Conn, handler func(*Notification))
SetNotificationHandler sets the given notification handler on the given connection. A runtime panic occurs if c is not a pq connection. A nil handler may be used to unset it.
Note: Notification handlers are executed synchronously by pq meaning commands won't continue to be processed until the handler returns.
Types ¶
type ArrayDelimiter ¶
type ArrayDelimiter interface {
// ArrayDelimiter returns the delimiter character(s) for this element's type.
ArrayDelimiter() string
}
ArrayDelimiter may be optionally implemented by driver.Valuer or sql.Scanner to override the array delimiter used by GenericArray.
type BoolArray ¶
type BoolArray []bool
BoolArray represents a one-dimensional array of the PostgreSQL boolean type.
type ByteaArray ¶
type ByteaArray [][]byte
ByteaArray represents a one-dimensional array of the PostgreSQL bytea type.
func (*ByteaArray) Scan ¶
func (a *ByteaArray) Scan(src any) error
Scan implements the sql.Scanner interface.
type Config ¶ added in v1.11.0
type Config struct {
// The host to connect to. Absolute paths and values that start with @ are
// for unix domain sockets. Defaults to localhost.
//
// A comma-separated list of host names is also accepted, in which case each
// host name in the list is tried in order or randomly if load_balance_hosts
// is set. An empty item selects the default of localhost. The
// target_session_attrs option controls properties the host must have to be
// considered acceptable.
Host string `postgres:"host" env:"PGHOST"`
// IPv4 or IPv6 address to connect to. Using hostaddr allows the application
// to avoid a host name lookup, which might be important in applications
// with time constraints. A hostname is required for sslmode=verify-full and
// the GSSAPI or SSPI authentication methods.
//
// The following rules are used:
//
// - If host is given without hostaddr, a host name lookup occurs.
//
// - If hostaddr is given without host, the value for hostaddr gives the
// server network address. The connection attempt will fail if the
// authentication method requires a host name.
//
// - If both host and hostaddr are given, the value for hostaddr gives the
// server network address. The value for host is ignored unless the
// authentication method requires it, in which case it will be used as the
// host name.
//
// A comma-separated list of hostaddr values is also accepted, in which case
// each host in the list is tried in order or randonly if load_balance_hosts
// is set. An empty item causes the corresponding host name to be used, or
// the default host name if that is empty as well. The target_session_attrs
// option controls properties the host must have to be considered
// acceptable.
Hostaddr netip.Addr `postgres:"hostaddr" env:"PGHOSTADDR"`
// The port to connect to. Defaults to 5432.
//
// If multiple hosts were given in the host or hostaddr parameters, this
// parameter may specify a comma-separated list of ports of the same length
// as the host list, or it may specify a single port number to be used for
// all hosts. An empty string, or an empty item in a comma-separated list,
// specifies the default of 5432.
Port uint16 `postgres:"port" env:"PGPORT"`
// The name of the database to connect to.
Database string `postgres:"dbname" env:"PGDATABASE"`
// The user to sign in as. Defaults to the current user.
User string `postgres:"user" env:"PGUSER"`
// The user's password.
Password string `postgres:"password" env:"PGPASSWORD"`
// Path to [pgpass] file to store passwords; overrides Password.
//
// [pgpass]: http://www.postgresql.org/docs/current/static/libpq-pgpass.html
Passfile string `postgres:"passfile" env:"PGPASSFILE"`
// Commandline options to send to the server at connection start.
Options string `postgres:"options" env:"PGOPTIONS"`
// Application name, displayed in pg_stat_activity and log entries.
ApplicationName string `postgres:"application_name" env:"PGAPPNAME"`
// Used if application_name is not given. Specifying a fallback name is
// useful in generic utility programs that wish to set a default application
// name but allow it to be overridden by the user.
FallbackApplicationName string `postgres:"fallback_application_name" env:"-"`
// Whether to use SSL. Defaults to "require" (different from libpq's default
// of "prefer").
//
// [RegisterTLSConfig] can be used to registers a custom [tls.Config], which
// can be used by setting sslmode=pqgo-«key» in the connection string.
SSLMode SSLMode `postgres:"sslmode" env:"PGSSLMODE"`
// When set to "direct" it will use SSL without negotiation (PostgreSQL ≥17 only).
SSLNegotiation SSLNegotiation `postgres:"sslnegotiation" env:"PGSSLNEGOTIATION"`
// Cert file location. The file must contain PEM encoded data.
SSLCert string `postgres:"sslcert" env:"PGSSLCERT"`
// Key file location. The file must contain PEM encoded data.
SSLKey string `postgres:"sslkey" env:"PGSSLKEY"`
// The location of the root certificate file. The file must contain PEM encoded data.
SSLRootCert string `postgres:"sslrootcert" env:"PGSSLROOTCERT"`
// By default SNI is on, any value which is not starting with "1" disables
// SNI.
SSLSNI bool `postgres:"sslsni" env:"PGSSLSNI"`
// Interpert sslcert and sslkey as PEM encoded data, rather than a path to a
// PEM file. This is a pq extension, not supported in libpq.
SSLInline bool `postgres:"sslinline" env:"-"`
// GSS (Kerberos) service name when constructing the SPN (default is
// postgres). This will be combined with the host to form the full SPN:
// krbsrvname/host.
KrbSrvname string `postgres:"krbsrvname" env:"PGKRBSRVNAME"`
// GSS (Kerberos) SPN. This takes priority over krbsrvname if present. This
// is a pq extension, not supported in libpq.
KrbSpn string `postgres:"krbspn" env:"-"`
// Maximum time to wait while connecting, in seconds. Zero, negative, or not
// specified means wait indefinitely
ConnectTimeout time.Duration `postgres:"connect_timeout" env:"PGCONNECT_TIMEOUT"`
// Whether to always send []byte parameters over as binary. Enables single
// round-trip mode for non-prepared Query calls. This is a pq extension, not
// supported in libpq.
BinaryParameters bool `postgres:"binary_parameters" env:"-"`
// This connection should never use the binary format when receiving query
// results from prepared statements. Only provided for debugging. This is a
// pq extension, not supported in libpq.
DisablePreparedBinaryResult bool `postgres:"disable_prepared_binary_result" env:"-"`
// Client encoding; pq only supports UTF8 and this must be blank or "UTF8".
ClientEncoding string `postgres:"client_encoding" env:"PGCLIENTENCODING"`
// Date/time representation to use; pq only supports "ISO, MDY" and this
// must be blank or "ISO, MDY".
Datestyle string `postgres:"datestyle" env:"PGDATESTYLE"`
// Default time zone.
TZ string `postgres:"tz" env:"PGTZ"`
// Default mode for the genetic query optimizer.
Geqo string `postgres:"geqo" env:"PGGEQO"`
// Determine whether the session must have certain properties to be
// acceptable. It's typically used in combination with multiple host names
// to select the first acceptable alternative among several hosts.
TargetSessionAttrs TargetSessionAttrs `postgres:"target_session_attrs" env:"PGTARGETSESSIONATTRS"`
// Controls the order in which the client tries to connect to the available
// hosts. Once a connection attempt is successful no other hosts will be
// tried. This parameter is typically used in combination with multiple host
// names.
//
// This parameter can be used in combination with target_session_attrs to,
// for example, load balance over standby servers only. Once successfully
// connected, subsequent queries on the returned connection will all be sent
// to the same server.
LoadBalanceHosts LoadBalanceHosts `postgres:"load_balance_hosts" env:"PGLOADBALANCEHOSTS"`
// Runtime parameters: any unrecognized parameter in the DSN will be added
// to this and sent to PostgreSQL during startup.
Runtime map[string]string `postgres:"-" env:"-"`
// Multi contains additional connection details. The first value is
// available in [Config.Host], [Config.Hostaddr], and [Config.Port], and
// additional ones (if any) are available here.
Multi []ConfigMultihost
// contains filtered or unexported fields
}
Config holds options pq supports when connecting to PostgreSQL.
The postgres struct tag is used for the value from the DSN (e.g. "dbname=abc"), and the env struct tag is used for the environment variable (e.g. "PGDATABASE=abc")
func NewConfig ¶ added in v1.11.0
NewConfig creates a new Config from the current environment and given DSN.
A subset of the connection parameters supported by PostgreSQL are supported by pq; see the Config struct fields for supported parameters. pq also lets you specify any run-time parameter (such as search_path or work_mem) directly in the connection string. This is different from libpq, which does not allow run-time parameters in the connection string, instead requiring you to supply them in the options parameter.
key=value connection strings ¶
For key=value strings, use single quotes for values that contain whitespace or empty values. A backslash will escape the next character:
"user=pqgo password='with spaces'" "user=''" "user=space\ man password='it\'s valid'"
URL connection strings ¶
pq supports URL-style postgres:// or postgresql:// connection strings in the form:
postgres[ql]://[user[:pwd]@][net-location][:port][/dbname][?param1=value1&...]
Go's net/url.Parse is more strict than PostgreSQL's URL parser and will (correctly) reject %2F in the host part. This means that unix-socket URLs:
postgres://[user[:pwd]@][unix-socket][:port[/dbname]][?param1=value1&...] postgres://%2Ftmp%2Fpostgres/db
will not work. You will need to use "host=/tmp/postgres dbname=db".
Similarly, multiple ports also won't work, but ?port= will:
postgres://host1,host2:5432,6543/dbname Doesn't work postgres://host1,host2/dbname?port=5432,6543 Works
Environment ¶
Most PostgreSQL environment variables are supported by pq. Environment variables have a lower precedence than explicitly provided connection parameters. pq will return an error if environment variables it does not support are set. Environment variables have a lower precedence than explicitly provided connection parameters.
Example ¶
package main
import (
"database/sql"
"log"
"github.com/lib/pq"
)
func main() {
cfg, err := pq.NewConfig("host=postgres dbname=pqgo")
if err != nil {
log.Fatal(err)
}
if cfg.Host == "localhost" {
cfg.Host = "127.0.0.1"
}
c, err := pq.NewConnectorConfig(cfg)
if err != nil {
log.Fatal(err)
}
db := sql.OpenDB(c)
defer db.Close()
// Use the DB
tx, err := db.Begin()
if err != nil {
log.Fatalf("could not start transaction: %v", err)
}
tx.Rollback()
}
type ConfigMultihost ¶ added in v1.11.0
ConfigMultihost specifies an additional server to try to connect to.
type Connector ¶ added in v1.1.0
type Connector struct {
// contains filtered or unexported fields
}
Connector represents a fixed configuration for the pq driver with a given dsn. Connector satisfies the database/sql/driver.Connector interface and can be used to create any number of DB Conn's via sql.OpenDB.
func NewConnector ¶
NewConnector returns a connector for the pq driver in a fixed configuration with the given dsn. The returned connector can be used to create any number of equivalent Conn's. The returned connector is intended to be used with sql.OpenDB.
Example ¶
package main
import (
"database/sql"
"log"
"github.com/lib/pq"
)
func main() {
c, err := pq.NewConnector("host=postgres dbname=pqgo")
if err != nil {
log.Fatalf("could not create connector: %v", err)
}
db := sql.OpenDB(c)
defer db.Close()
// Use the DB
tx, err := db.Begin()
if err != nil {
log.Fatalf("could not start transaction: %v", err)
}
tx.Rollback()
}
func NewConnectorConfig ¶ added in v1.11.0
NewConnectorConfig returns a connector for the pq driver in a fixed configuration with the given Config. The returned connector can be used to create any number of equivalent Conn's. The returned connector is intended to be used with sql.OpenDB.
func (*Connector) Connect ¶ added in v1.1.0
Connect returns a connection to the database using the fixed configuration of this Connector. Context is not used.
type Dialer ¶
type Dialer interface {
Dial(network, address string) (net.Conn, error)
DialTimeout(network, address string, timeout time.Duration) (net.Conn, error)
}
Dialer is the dialer interface. It can be used to obtain more control over how pq creates network connections.
type DialerContext ¶ added in v1.1.0
type DialerContext interface {
DialContext(ctx context.Context, network, address string) (net.Conn, error)
}
DialerContext is the context-aware dialer interface.
type Error ¶
type Error struct {
// [Efatal], [Epanic], [Ewarning], [Enotice], [Edebug], [Einfo], or [Elog].
// Always present.
Severity string
// SQLSTATE code. Always present.
Code ErrorCode
// Primary human-readable error message. This should be accurate but terse
// (typically one line). Always present.
Message string
// Optional secondary error message carrying more detail about the problem.
// Might run to multiple lines.
Detail string
// Optional suggestion what to do about the problem. This is intended to
// differ from Detail in that it offers advice (potentially inappropriate)
// rather than hard facts. Might run to multiple lines.
Hint string
// error position as an index into the original query string, as decimal
// ASCII integer. The first character has index 1, and positions are
// measured in characters not bytes.
Position string
// This is defined the same as the Position field, but it is used when the
// cursor position refers to an internally generated command rather than the
// one submitted by the client. The InternalQuery field will always appear
// when this field appears.
InternalPosition string
// Text of a failed internally-generated command. This could be, for
// example, an SQL query issued by a PL/pgSQL function.
InternalQuery string
// An indication of the context in which the error occurred. Presently this
// includes a call stack traceback of active procedural language functions
// and internally-generated queries. The trace is one entry per line, most
// recent first.
Where string
// If the error was associated with a specific database object, the name of
// the schema containing that object, if any.
Schema string
// If the error was associated with a specific table, the name of the table.
// (Refer to the schema name field for the name of the table's schema.)
Table string
// If the error was associated with a specific table column, the name of the
// column. (Refer to the schema and table name fields to identify the
// table.)
Column string
// If the error was associated with a specific data type, the name of the
// data type. (Refer to the schema name field for the name of the data
// type's schema.)
DataTypeName string
// If the error was associated with a specific constraint, the name of the
// constraint. Refer to fields listed above for the associated table or
// domain. (For this purpose, indexes are treated as constraints, even if
// they weren't created with constraint syntax.)
Constraint string
// File name of the source-code location where the error was reported.
File string
// Line number of the source-code location where the error was reported.
Line string
// Name of the source-code routine reporting the error.
Routine string
// contains filtered or unexported fields
}
Error represents an error communicating with the server.
The Error method only returns the error message and error code:
pq: invalid input syntax for type json (22P02)
The [ErrorWithDetail] method also includes the error Detail, Hint, and location context (if any):
ERROR: invalid input syntax for type json (22P02)
DETAIL: Token "asd" is invalid.
CONTEXT: line 5, column 8:
3 | 'def',
4 | 123,
5 | 'foo', 'asd'::jsonb
^
See http://www.postgresql.org/docs/current/static/protocol-error-fields.html for details of the fields
func (*Error) ErrorWithDetail ¶ added in v1.11.0
ErrorWithDetail returns the error message with detailed information and location context (if any).
See the documentation on Error.
type ErrorClass ¶
type ErrorClass string
ErrorClass is only the class part of an error code.
func (ErrorClass) Name ¶
func (ec ErrorClass) Name() string
Name returns the condition name of an error class. It is equivalent to the condition name of the "standard" error code (i.e. the one having the last three characters "000").
type ErrorCode ¶
type ErrorCode string
ErrorCode is a five-character error code.
func (ErrorCode) Class ¶
func (ec ErrorCode) Class() ErrorClass
Class returns the error class, e.g. "28".
See http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html for details.
func (ErrorCode) Name ¶
Name returns a more human friendly rendering of the error code, namely the "condition name".
See http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html for details.
type EventCallbackType ¶
type EventCallbackType func(event ListenerEventType, err error)
EventCallbackType is the event callback type. See also ListenerEventType constants' documentation.
type Float32Array ¶ added in v1.9.0
type Float32Array []float32
Float32Array represents a one-dimensional array of the PostgreSQL double precision type.
func (*Float32Array) Scan ¶ added in v1.9.0
func (a *Float32Array) Scan(src any) error
Scan implements the sql.Scanner interface.
type Float64Array ¶
type Float64Array []float64
Float64Array represents a one-dimensional array of the PostgreSQL double precision type.
func (*Float64Array) Scan ¶
func (a *Float64Array) Scan(src any) error
Scan implements the sql.Scanner interface.
type GSS ¶ added in v1.7.0
type GSS interface {
GetInitToken(host string, service string) ([]byte, error)
GetInitTokenFromSpn(spn string) ([]byte, error)
Continue(inToken []byte) (done bool, outToken []byte, err error)
}
GSS provides GSSAPI authentication (e.g., Kerberos).
type GenericArray ¶
type GenericArray struct{ A any }
GenericArray implements the driver.Valuer and sql.Scanner interfaces for an array or slice of any dimension.
func (GenericArray) Scan ¶
func (a GenericArray) Scan(src any) error
Scan implements the sql.Scanner interface.
type Int32Array ¶ added in v1.9.0
type Int32Array []int32
Int32Array represents a one-dimensional array of the PostgreSQL integer types.
func (*Int32Array) Scan ¶ added in v1.9.0
func (a *Int32Array) Scan(src any) error
Scan implements the sql.Scanner interface.
type Int64Array ¶
type Int64Array []int64
Int64Array represents a one-dimensional array of the PostgreSQL integer types.
func (*Int64Array) Scan ¶
func (a *Int64Array) Scan(src any) error
Scan implements the sql.Scanner interface.
type Listener ¶
type Listener struct {
// Channel for receiving notifications from the database. In some cases a
// nil value will be sent. See section "Notifications" above.
Notify chan *Notification
// contains filtered or unexported fields
}
Listener provides an interface for listening to notifications from a PostgreSQL database. For general usage information, see section "Notifications".
Listener can safely be used from concurrently running goroutines.
func NewDialListener ¶
func NewDialListener(d Dialer, name string, minReconnectInterval time.Duration, maxReconnectInterval time.Duration, eventCallback EventCallbackType) *Listener
NewDialListener is like NewListener but it takes a Dialer.
func NewListener ¶
func NewListener(name string, minReconnectInterval time.Duration, maxReconnectInterval time.Duration, eventCallback EventCallbackType) *Listener
NewListener creates a new database connection dedicated to LISTEN / NOTIFY.
name should be set to a connection string to be used to establish the database connection (see section "Connection String Parameters" above).
minReconnectInterval controls the duration to wait before trying to re-establish the database connection after connection loss. After each consecutive failure this interval is doubled, until maxReconnectInterval is reached. Successfully completing the connection establishment procedure resets the interval back to minReconnectInterval.
The last parameter eventCallback can be set to a function which will be called by the Listener when the state of the underlying database connection changes. This callback will be called by the goroutine which dispatches the notifications over the Notify channel, so you should try to avoid doing potentially time-consuming operations from the callback.
func (*Listener) Close ¶
Close disconnects the Listener from the database and shuts it down. Subsequent calls to its methods will return an error. Close returns an error if the connection has already been closed.
func (*Listener) Listen ¶
Listen starts listening for notifications on a channel. Calls to this function will block until an acknowledgement has been received from the server. Note that Listener automatically re-establishes the connection after connection loss, so this function may block indefinitely if the connection can not be re-established.
Listen will only fail in three conditions:
- The channel is already open. The returned error will be ErrChannelAlreadyOpen.
- The query was executed on the remote server, but PostgreSQL returned an error message in response to the query. The returned error will be a pq.Error containing the information the server supplied.
- Close is called on the Listener before the request could be completed.
The channel name is case-sensitive.
func (*Listener) NotificationChannel ¶
func (l *Listener) NotificationChannel() <-chan *Notification
NotificationChannel returns the notification channel for this listener. This is the same channel as Notify, and will not be recreated during the life time of the Listener.
func (*Listener) Ping ¶
Ping the remote server to make sure it's alive. Non-nil return value means that there is no active connection.
func (*Listener) Unlisten ¶
Unlisten removes a channel from the Listener's channel list. Returns ErrChannelNotOpen if the Listener is not listening on the specified channel. Returns immediately with no error if there is no connection. Note that you might still get notifications for this channel even after Unlisten has returned.
The channel name is case-sensitive.
func (*Listener) UnlistenAll ¶
UnlistenAll removes all channels from the Listener's channel list. Returns immediately with no error if there is no connection. Note that you might still get notifications for any of the deleted channels even after UnlistenAll has returned.
type ListenerConn ¶
type ListenerConn struct {
// contains filtered or unexported fields
}
ListenerConn is a low-level interface for waiting for notifications. You should use Listener instead.
func NewListenerConn ¶
func NewListenerConn(name string, notificationChan chan<- *Notification) (*ListenerConn, error)
NewListenerConn creates a new ListenerConn. Use NewListener instead.
func (*ListenerConn) Err ¶
func (l *ListenerConn) Err() error
Err returns the reason the connection was closed. It is not safe to call this function until l.Notify has been closed.
func (*ListenerConn) ExecSimpleQuery ¶
func (l *ListenerConn) ExecSimpleQuery(q string) (executed bool, err error)
ExecSimpleQuery executes a "simple query" (i.e. one with no bindable parameters) on the connection. The possible return values are:
- "executed" is true; the query was executed to completion on the database server. If the query failed, err will be set to the error returned by the database, otherwise err will be nil.
- If "executed" is false, the query could not be executed on the remote server. err will be non-nil.
After a call to ExecSimpleQuery has returned an executed=false value, the connection has either been closed or will be closed shortly thereafter, and all subsequently executed queries will return an error.
func (*ListenerConn) Listen ¶
func (l *ListenerConn) Listen(channel string) (bool, error)
Listen sends a LISTEN query to the server. See ExecSimpleQuery.
func (*ListenerConn) Ping ¶
func (l *ListenerConn) Ping() error
Ping the remote server to make sure it's alive. Non-nil error means the connection has failed and should be abandoned.
func (*ListenerConn) Unlisten ¶
func (l *ListenerConn) Unlisten(channel string) (bool, error)
Unlisten sends an UNLISTEN query to the server. See ExecSimpleQuery.
func (*ListenerConn) UnlistenAll ¶
func (l *ListenerConn) UnlistenAll() (bool, error)
UnlistenAll sends an `UNLISTEN *` query to the server. See ExecSimpleQuery.
type ListenerEventType ¶
type ListenerEventType int
ListenerEventType is an enumeration of listener event types.
const ( // ListenerEventConnected is emitted only when the database connection // has been initially initialized. The err argument of the callback // will always be nil. ListenerEventConnected ListenerEventType = iota // ListenerEventDisconnected is emitted after a database connection has // been lost, either because of an error or because Close has been // called. The err argument will be set to the reason the database // connection was lost. ListenerEventDisconnected // ListenerEventReconnected is emitted after a database connection has // been re-established after connection loss. The err argument of the // callback will always be nil. After this event has been emitted, a // nil pq.Notification is sent on the Listener.Notify channel. ListenerEventReconnected // ListenerEventConnectionAttemptFailed is emitted after a connection // to the database was attempted, but failed. The err argument will be // set to an error describing why the connection attempt did not // succeed. ListenerEventConnectionAttemptFailed )
type LoadBalanceHosts ¶ added in v1.11.0
type LoadBalanceHosts string
LoadBalanceHosts is a load_balance_hosts setting.
type NewGSSFunc ¶ added in v1.7.0
NewGSSFunc creates a GSS authentication provider, for use with RegisterGSSProvider.
type NoticeHandlerConnector ¶ added in v1.4.0
NoticeHandlerConnector wraps a regular connector and sets a notice handler on it.
func ConnectorWithNoticeHandler ¶ added in v1.4.0
func ConnectorWithNoticeHandler(c driver.Connector, handler func(*Error)) *NoticeHandlerConnector
ConnectorWithNoticeHandler creates or sets the given handler for the given connector. If the given connector is a result of calling this function previously, it is simply set on the given connector and returned. Otherwise, this returns a new connector wrapping the given one and setting the notice handler. A nil notice handler may be used to unset it.
The returned connector is intended to be used with database/sql.OpenDB.
Note: Notice handlers are executed synchronously by pq meaning commands won't continue to be processed until the handler returns.
Example ¶
package main
import (
"database/sql"
"fmt"
"log"
"github.com/lib/pq"
)
func main() {
// Base connector to wrap
dsn := ""
base, err := pq.NewConnector(dsn)
if err != nil {
log.Fatal(err)
}
// Wrap the connector to simply print out the message
connector := pq.ConnectorWithNoticeHandler(base, func(notice *pq.Error) {
fmt.Println("Notice sent: " + notice.Message)
})
db := sql.OpenDB(connector)
defer db.Close()
// Raise a notice
sql := "DO language plpgsql $$ BEGIN RAISE NOTICE 'test notice'; END $$"
if _, err := db.Exec(sql); err != nil {
log.Fatal(err)
}
}
Output: Notice sent: test notice
type Notification ¶
type Notification struct {
// Process ID (PID) of the notifying postgres backend.
BePid int
// Name of the channel the notification was sent on.
Channel string
// Payload, or the empty string if unspecified.
Extra string
}
Notification represents a single notification from the database.
type NotificationHandlerConnector ¶ added in v1.5.1
type NotificationHandlerConnector struct {
driver.Connector
// contains filtered or unexported fields
}
NotificationHandlerConnector wraps a regular connector and sets a notification handler on it.
func ConnectorWithNotificationHandler ¶ added in v1.5.1
func ConnectorWithNotificationHandler(c driver.Connector, handler func(*Notification)) *NotificationHandlerConnector
ConnectorWithNotificationHandler creates or sets the given handler for the given connector. If the given connector is a result of calling this function previously, it is simply set on the given connector and returned. Otherwise, this returns a new connector wrapping the given one and setting the notification handler. A nil notification handler may be used to unset it.
The returned connector is intended to be used with database/sql.OpenDB.
Note: Notification handlers are executed synchronously by pq meaning commands won't continue to be processed until the handler returns.
type NullTime
deprecated
NullTime represents a time.Time that may be null. NullTime implements the sql.Scanner interface so it can be used as a scan destination, similar to sql.NullString.
Deprecated: this is an alias for sql.NullTime.
type SSLNegotiation ¶ added in v1.11.0
type SSLNegotiation string
SSLNegotiation is a sslnegotiation setting.
type StringArray ¶
type StringArray []string
StringArray represents a one-dimensional array of the PostgreSQL character types.
func (*StringArray) Scan ¶
func (a *StringArray) Scan(src any) error
Scan implements the sql.Scanner interface.
type TargetSessionAttrs ¶ added in v1.11.0
type TargetSessionAttrs string
TargetSessionAttrs is a target_session_attrs setting.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
auth
|
|
|
kerberos
module
|
|
|
cmd
|
|
|
pqlisten
command
Command pqlisten is a self-contained Go program which uses the LISTEN / NOTIFY mechanism to avoid polling the database while waiting for more work to arrive.
|
Command pqlisten is a self-contained Go program which uses the LISTEN / NOTIFY mechanism to avoid polling the database while waiting for more work to arrive. |
|
internal
|
|
|
Package oid contains OID constants as defined by the Postgres server.
|
Package oid contains OID constants as defined by the Postgres server. |
|
Package scram implements a SCRAM-{SHA-1,etc} client per RFC5802.
|
Package scram implements a SCRAM-{SHA-1,etc} client per RFC5802. |