stdlib
v5.13.0
Documentation
pkg.go.dev ↗Package stdlib is the compatibility layer from pgx to database/sql.
A database/sql connection can be established through sql.Open.
db, err := sql.Open("pgx", "postgres://pgx_md5:secret@localhost:5432/pgx_test?sslmode=disable")
if err != nil {
return err
}
Or from a keyword/value string.
db, err := sql.Open("pgx", "user=postgres password=secret host=localhost port=5432 dbname=pgx_test sslmode=disable")
if err != nil {
return err
}
Or from a *pgxpool.Pool.
pool, err := pgxpool.New(context.Background(), os.Getenv("DATABASE_URL"))
if err != nil {
return err
}
db := stdlib.OpenDBFromPool(pool)
Or a pgx.ConnConfig can be used to set configuration not accessible via connection string. In this case the pgx.ConnConfig must first be registered with the driver. This registration returns a connection string which is used with sql.Open.
connConfig, _ := pgx.ParseConfig(os.Getenv("DATABASE_URL"))
connConfig.Tracer = &tracelog.TraceLog{Logger: myLogger, LogLevel: tracelog.LogLevelInfo}
connStr := stdlib.RegisterConnConfig(connConfig)
db, _ := sql.Open("pgx", connStr)
pgx uses standard PostgreSQL positional parameters in queries. e.g. $1, $2. It does not support named parameters.
db.QueryRow("select * from users where id=$1", userID)
(*sql.Conn) Raw() can be used to get a *pgx.Conn from the standard database/sql.DB connection pool. This allows operations that use pgx specific functionality.
// Given db is a *sql.DB
conn, err := db.Conn(context.Background())
if err != nil {
// handle error from acquiring connection from DB pool
}
err = conn.Raw(func(driverConn any) error {
conn := driverConn.(*stdlib.Conn).Conn() // conn is a *pgx.Conn
// Do pgx specific stuff with conn
conn.CopyFrom(...)
return nil
})
if err != nil {
// handle error that occurred while using *pgx.Conn
}
PostgreSQL Specific Data Types
As of Go 1.27, database/sql allows drivers to implement their own scanning logic by implementing the driver.RowsColumnScanner interface. This allows PostgreSQL types such as arrays to be scanned directly into Go values such as slices.
var a []int64
err := db.QueryRow("select '{1,2,3}'::bigint[]").Scan(&a)
In older versions of Go, *pgtype.Map.SQLScanner can be used as an adapter that makes these types usable as a sql.Scanner.
m := pgtype.NewMap()
var a []int64
err := db.QueryRow("select '{1,2,3}'::bigint[]").Scan(m.SQLScanner(&a))
The pgtype package provides support for PostgreSQL specific types. These types can be used directly in Go 1.27 and with *pgtype.Map.SQLScanner in older Go versions.
var r pgtype.Range[pgtype.Int4]
err := db.QueryRow("select int4range(1, 5)").Scan(&r)
Functions
GetConnector
func GetConnector(config pgx.ConnConfig, opts ...OptionOpenDB) driver.Connector
GetDefaultDriver
func GetDefaultDriver() driver.Driver
GetDefaultDriver returns the driver initialized in the init function and used when the pgx driver is registered.
GetPoolConnector
func GetPoolConnector(pool *pgxpool.Pool, opts ...OptionOpenDB) driver.Connector
GetPoolConnector creates a new driver.Connector from the given *pgxpool.Pool. By using this be sure to set the maximum idle connections of the *sql.DB created with this connector to zero since they must be managed from the *pgxpool.Pool. This is required to avoid acquiring all the connections from the pgxpool and starving any direct users of the pgxpool.
OpenDB
func OpenDB(config pgx.ConnConfig, opts ...OptionOpenDB) *sql.DB
OpenDBFromPool
func OpenDBFromPool(pool *pgxpool.Pool, opts ...OptionOpenDB) *sql.DB
OpenDBFromPool creates a new *sql.DB from the given *pgxpool.Pool. Note that this method automatically sets the maximum number of idle connections in *sql.DB to zero, since they must be managed from the *pgxpool.Pool. This is required to avoid acquiring all the connections from the pgxpool and starving any direct users of the pgxpool. Note that closing the returned *sql.DB will not close the *pgxpool.Pool.
RandomizeHostOrderFunc
func RandomizeHostOrderFunc(ctx context.Context, connConfig *pgx.ConnConfig) error
RandomizeHostOrderFunc is a BeforeConnect hook that randomizes the host order in the provided connConfig, so that a new host becomes primary each time. This is useful to distribute connections for multi-master databases like CockroachDB. If you use this you likely should set https://golang.org/pkg/database/sql/#DB.SetConnMaxLifetime as well to ensure that connections are periodically rebalanced across your nodes.
RegisterConnConfig
func RegisterConnConfig(c *pgx.ConnConfig) string
RegisterConnConfig registers a ConnConfig and returns the connection string to use with Open.
UnregisterConnConfig
func UnregisterConnConfig(connStr string)
UnregisterConnConfig removes the ConnConfig registration for connStr.
Types
Conn
type Conn struct {
// contains filtered or unexported fields
}
Conn.Begin
func (c *Conn) Begin() (driver.Tx, error)
Conn.BeginTx
func (c *Conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error)
Conn.CheckNamedValue
func (c *Conn) CheckNamedValue(*driver.NamedValue) error
Conn.Close
func (c *Conn) Close() error
Conn.Conn
func (c *Conn) Conn() *pgx.Conn
Conn returns the underlying *pgx.Conn
Conn.ExecContext
func (c *Conn) ExecContext(ctx context.Context, query string, argsV []driver.NamedValue) (driver.Result, error)
Conn.Ping
func (c *Conn) Ping(ctx context.Context) error
Conn.Prepare
func (c *Conn) Prepare(query string) (driver.Stmt, error)
Conn.PrepareContext
func (c *Conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error)
Conn.QueryContext
func (c *Conn) QueryContext(ctx context.Context, query string, argsV []driver.NamedValue) (driver.Rows, error)
Conn.ResetSession
func (c *Conn) ResetSession(ctx context.Context) error
Driver
type Driver struct {
// contains filtered or unexported fields
}
Driver.Open
func (d *Driver) Open(name string) (driver.Conn, error)
Driver.OpenConnector
func (d *Driver) OpenConnector(name string) (driver.Connector, error)
OptionOpenDB
type OptionOpenDB func(*connector)
OptionOpenDB options for configuring the driver when opening a new db pool.
OptionAfterConnect
func OptionAfterConnect(ac func(context.Context, *pgx.Conn) error) OptionOpenDB
OptionAfterConnect provides a callback for after connect. Used only if db is opened with *pgx.ConnConfig.
OptionBeforeConnect
func OptionBeforeConnect(bc func(context.Context, *pgx.ConnConfig) error) OptionOpenDB
OptionBeforeConnect provides a callback for before connect. It is passed a shallow copy of the ConnConfig that will be used to connect, so only its immediate members should be modified. Used only if db is opened with *pgx.ConnConfig.
OptionResetSession
func OptionResetSession(rs func(context.Context, *pgx.Conn) error) OptionOpenDB
OptionResetSession provides a callback that can be used to add custom logic prior to executing a query on the connection if the connection has been used before. If ResetSessionFunc returns ErrBadConn error the connection will be discarded.
OptionShouldPing
func OptionShouldPing(f func(context.Context, ShouldPingParams) bool) OptionOpenDB
OptionShouldPing controls whether stdlib should issue a liveness ping before reusing a connection. If the function returns true, stdlib will ping. If it returns false, stdlib will skip the ping. If not provided, default is ping only when IdleDuration > 1s.
Rows
type Rows struct {
// contains filtered or unexported fields
}
Rows.Close
func (r *Rows) Close() error
Rows.ColumnTypeDatabaseTypeName
func (r *Rows) ColumnTypeDatabaseTypeName(index int) string
ColumnTypeDatabaseTypeName returns the database system type name. If the name is unknown the OID is returned.
Rows.ColumnTypeLength
func (r *Rows) ColumnTypeLength(index int) (int64, bool)
ColumnTypeLength returns the length of the column type if the column is a variable length type. If the column is not a variable length type ok should return false.
Rows.ColumnTypePrecisionScale
func (r *Rows) ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool)
ColumnTypePrecisionScale returns the precision and scale for numeric types with a declared precision. For timestamp, timestamptz, time, timetz, and interval, it returns a precision of 0 and the fractional seconds precision as the scale, defaulting to 6 when no fractional seconds precision was declared. For unconstrained numeric and other types, ok is false.
Rows.ColumnTypeScanType
func (r *Rows) ColumnTypeScanType(index int) reflect.Type
ColumnTypeScanType returns the value type that can be used to scan types into.
Rows.Columns
func (r *Rows) Columns() []string
Rows.Next
func (r *Rows) Next(dest []driver.Value) error
Rows.NextRow
func (r *Rows) NextRow() error
NextRow implements the driver.RowsColumnScanner interface. It advances to the next row of data and returns io.EOF when there are no more rows.
Rows.ScanColumn
func (r *Rows) ScanColumn(scanCtx driver.ScanContext, index int, dest any) error
ScanColumn implements the driver.RowsColumnScanner interface. It preserves database/sql conversions for scalar destinations and sql.Scanner implementations. Other destinations, such as Go slices, pgtype.Array, and pgtype.Range, are scanned directly using the pgx type map.
ShouldPingParams
type ShouldPingParams struct {
// Conn is the underlying pgx connection.
Conn *pgx.Conn
// IdleDuration is how long it has been since ResetSession last ran.
IdleDuration time.Duration
}
ShouldPingParams are passed to OptionShouldPing to decide whether to ping before reusing a connection.
Stmt
type Stmt struct {
// contains filtered or unexported fields
}
Stmt.Close
func (s *Stmt) Close() error
Stmt.Exec
func (s *Stmt) Exec(argsV []driver.Value) (driver.Result, error)
Stmt.ExecContext
func (s *Stmt) ExecContext(ctx context.Context, argsV []driver.NamedValue) (driver.Result, error)
Stmt.NumInput
func (s *Stmt) NumInput() int
Stmt.Query
func (s *Stmt) Query(argsV []driver.Value) (driver.Rows, error)
Stmt.QueryContext
func (s *Stmt) QueryContext(ctx context.Context, argsV []driver.NamedValue) (driver.Rows, error)