pgx
v2.10.0+incompatible
Documentation
pkg.go.dev ↗Package pgx is a PostgreSQL database driver.
pgx provides lower level access to PostgreSQL than the standard database/sql It remains as similar to the database/sql interface as possible while providing better speed and access to PostgreSQL specific features. Import github.com/jack/pgx/stdlib to use pgx as a database/sql compatible driver.
Query Interface
pgx implements Query and Scan in the familiar database/sql style.
var sum int32
// Send the query to the server. The returned rows MUST be closed
// before conn can be used again.
rows, err := conn.Query("select generate_series(1,$1)", 10)
if err != nil {
return err
}
// rows.Close is called by rows.Next when all rows are read
// or an error occurs in Next or Scan. So it may optionally be
// omitted if nothing in the rows.Next loop can panic. It is
// safe to close rows multiple times.
defer rows.Close()
// Iterate through the result set
for rows.Next() {
var n int32
err = rows.Scan(&n)
if err != nil {
return err
}
sum += n
}
// Any errors encountered by rows.Next or rows.Scan will be returned here
if rows.Err() != nil {
return err
}
// No errors found - do something with sum
pgx also implements QueryRow in the same style as database/sql.
var name string
var weight int64
err := conn.QueryRow("select name, weight from widgets where id=$1", 42).Scan(&name, &weight)
if err != nil {
return err
}
Use Exec to execute a query that does not return a result set.
commandTag, err := conn.Exec("delete from widgets where id=$1", 42)
if err != nil {
return err
}
if commandTag.RowsAffected() != 1 {
return errors.New("No row found to delete")
}
Connection Pool
Connection pool usage is explicit and configurable. In pgx, a connection can be created and managed directly, or a connection pool with a configurable maximum connections can be used. Also, the connection pool offers an after connect hook that allows every connection to be automatically setup before being made available in the connection pool. This is especially useful to ensure all connections have the same prepared statements available or to change any other connection settings.
It delegates Query, QueryRow, Exec, and Begin functions to an automatically checked out and released connection so you can avoid manually acquiring and releasing connections when you do not need that level of control.
var name string
var weight int64
err := pool.QueryRow("select name, weight from widgets where id=$1", 42).Scan(&name, &weight)
if err != nil {
return err
}
Base Type Mapping
pgx maps between all common base types directly between Go and PostgreSQL. In particular:
Go PostgreSQL
-----------------------
string varchar
text
// Integers are automatically be converted to any other integer type if
// it can be done without overflow or underflow.
int8
int16 smallint
int32 int
int64 bigint
int
uint8
uint16
uint32
uint64
uint
// Floats are strict and do not automatically convert like integers.
float32 float4
float64 float8
time.Time date
timestamp
timestamptz
[]byte bytea
Null Mapping
pgx can map nulls in two ways. The first is Null* types that have a data field and a valid field. They work in a similar fashion to database/sql. The second is to use a pointer to a pointer.
var foo pgx.NullString
var bar *string
err := conn.QueryRow("select foo, bar from widgets where id=$1", 42).Scan(&a, &b)
if err != nil {
return err
}
Array Mapping
pgx maps between int16, int32, int64, float32, float64, and string Go slices and the equivalent PostgreSQL array type. Go slices of native types do not support nulls, so if a PostgreSQL array that contains a null is read into a native Go slice an error will occur.
Hstore Mapping
pgx includes an Hstore type and a NullHstore type. Hstore is simply a map[string]string and is preferred when the hstore contains no nulls. NullHstore follows the Null* pattern and supports null values.
JSON and JSONB Mapping
pgx includes built-in support to marshal and unmarshal between Go types and the PostgreSQL JSON and JSONB.
Inet and Cidr Mapping
pgx encodes from net.IPNet to and from inet and cidr PostgreSQL types. In addition, as a convenience pgx will encode from a net.IP; it will assume a /32 netmask for IPv4 and a /128 for IPv6.
Custom Type Support
pgx includes support for the common data types like integers, floats, strings, dates, and times that have direct mappings between Go and SQL. Support can be added for additional types like point, hstore, numeric, etc. that do not have direct mappings in Go by the types implementing ScannerPgx and Encoder.
Custom types can support text or binary formats. Binary format can provide a large performance increase. The natural place for deciding the format for a value would be in ScannerPgx as it is responsible for decoding the returned data. However, that is impossible as the query has already been sent by the time the ScannerPgx is invoked. The solution to this is the global DefaultTypeFormats. If a custom type prefers binary format it should register it there.
pgx.DefaultTypeFormats["point"] = pgx.BinaryFormatCode
Note that the type is referred to by name, not by OID. This is because custom PostgreSQL types like hstore will have different OIDs on different servers. When pgx establishes a connection it queries the pg_type table for all types. It then matches the names in DefaultTypeFormats with the returned OIDs and stores it in Conn.PgTypes.
See example_custom_type_test.go for an example of a custom type for the PostgreSQL point type.
pgx also includes support for custom types implementing the database/sql.Scanner and database/sql/driver.Valuer interfaces.
Raw Bytes Mapping
[]byte passed as arguments to Query, QueryRow, and Exec are passed unmodified to PostgreSQL. In like manner, a *[]byte passed to Scan will be filled with the raw bytes returned by PostgreSQL. This can be especially useful for reading varchar, text, json, and jsonb values directly into a []byte and avoiding the type conversion from string.
Transactions
Transactions are started by calling Begin or BeginIso. The BeginIso variant creates a transaction with a specified isolation level.
tx, err := conn.Begin()
if err != nil {
return err
}
// Rollback is safe to call even if the tx is already closed, so if
// the tx commits successfully, this is a no-op
defer tx.Rollback()
_, err = tx.Exec("insert into foo(id) values (1)")
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
Copy Protocol
Use CopyFrom to efficiently insert multiple rows at a time using the PostgreSQL copy protocol. CopyFrom accepts a CopyFromSource interface. If the data is already in a [][]interface{} use CopyFromRows to wrap it in a CopyFromSource interface. Or implement CopyFromSource to avoid buffering the entire data set in memory.
rows := [][]interface{}{
{"John", "Smith", int32(36)},
{"Jane", "Doe", int32(29)},
}
copyCount, err := conn.CopyFrom(
"people",
[]string{"first_name", "last_name", "age"},
pgx.CopyFromRows(rows),
)
CopyFrom can be faster than an insert with as few as 5 rows.
Listen and Notify
pgx can listen to the PostgreSQL notification system with the WaitForNotification function. It takes a maximum time to wait for a notification.
err := conn.Listen("channelname")
if err != nil {
return nil
}
if notification, err := conn.WaitForNotification(time.Second); err != nil {
// do something with notification
}
TLS
The pgx ConnConfig struct has a TLSConfig field. If this field is nil, then TLS will be disabled. If it is present, then it will be used to configure the TLS connection. This allows total configuration of the TLS connection.
Logging
pgx defines a simple logger interface. Connections optionally accept a logger that satisfies this interface. The log15 package (http://gopkg.in/inconshreveable/log15.v2) satisfies this interface and it is simple to define adapters for other loggers. Set LogLevel to control logging verbosity.
Constants
LogLevelTrace (6 declarations)
const ( LogLevelTrace = 6 LogLevelDebug = 5 LogLevelInfo = 4 LogLevelWarn = 3 LogLevelError = 2 LogLevelNone = 1 )
The values for log levels are chosen such that the zero value means that no log level was specified and we can default to LogLevelDebug to preserve the behavior that existed prior to log level introduction.
Serializable (4 declarations)
const ( Serializable = "serializable" RepeatableRead = "repeatable read" ReadCommitted = "read committed" ReadUncommitted = "read uncommitted" )
Transaction isolation levels
TxStatusInProgress (5 declarations)
const ( TxStatusInProgress = 0 TxStatusCommitFailure = -1 TxStatusRollbackFailure = -2 TxStatusCommitSuccess = 1 TxStatusRollbackSuccess = 2 )
BoolOid (40 declarations)
const ( BoolOid = 16 ByteaOid = 17 CharOid = 18 NameOid = 19 Int8Oid = 20 Int2Oid = 21 Int4Oid = 23 TextOid = 25 OidOid = 26 TidOid = 27 XidOid = 28 CidOid = 29 JsonOid = 114 CidrOid = 650 CidrArrayOid = 651 Float4Oid = 700 Float8Oid = 701 UnknownOid = 705 InetOid = 869 BoolArrayOid = 1000 Int2ArrayOid = 1005 Int4ArrayOid = 1007 TextArrayOid = 1009 ByteaArrayOid = 1001 VarcharArrayOid = 1015 Int8ArrayOid = 1016 Float4ArrayOid = 1021 Float8ArrayOid = 1022 AclItemOid = 1033 AclItemArrayOid = 1034 InetArrayOid = 1041 VarcharOid = 1043 DateOid = 1082 TimestampOid = 1114 TimestampArrayOid = 1115 TimestampTzOid = 1184 TimestampTzArrayOid = 1185 RecordOid = 2249 UuidOid = 2950 JsonbOid = 3802 )
PostgreSQL oids for common types
TextFormatCode (2 declarations)
const ( TextFormatCode = 0 BinaryFormatCode = 1 )
PostgreSQL format codes
Variables
DefaultTypeFormats
var DefaultTypeFormats map[string]int16
DefaultTypeFormats maps type names to their default requested format (text or binary). In theory the Scanner interface should be the one to determine the format of the returned values. However, the query has already been executed by the time Scan is called so it has no chance to set the format. So for types that should always be returned in binary the format should be set here.
ErrAcquireTimeout
var ErrAcquireTimeout = errors.New("timeout acquiring connection from pool")
ErrAcquireTimeout occurs when an attempt to acquire a connection times out.
ErrConnBusy
var ErrConnBusy = errors.New("conn is busy")
ErrConnBusy occurs when the connection is busy (for example, in the middle of reading query results) and another action is attempts.
ErrDeadConn
var ErrDeadConn = errors.New("conn is dead")
ErrDeadConn occurs on an attempt to use a dead connection
ErrInvalidLogLevel
var ErrInvalidLogLevel = errors.New("invalid log level")
ErrInvalidLogLevel occurs on attempt to set an invalid log level.
ErrNoRows
var ErrNoRows = errors.New("no rows in result set")
ErrNoRows occurs when rows are expected but none are returned.
ErrNotificationTimeout
var ErrNotificationTimeout = errors.New("notification timeout")
ErrNotificationTimeout occurs when WaitForNotification times out.
ErrTLSRefused
var ErrTLSRefused = errors.New("server refused TLS connection")
ErrTLSRefused occurs when the connection attempt requires TLS and the PostgreSQL server refuses to use TLS
ErrTxClosed
var ErrTxClosed = errors.New("tx is closed")
ErrTxCommitRollback
var ErrTxCommitRollback = errors.New("commit unexpectedly resulted in rollback")
ErrTxCommitRollback occurs when an error has occurred in a transaction and Commit() is called. PostgreSQL accepts COMMIT on aborted transactions, but it is treated as ROLLBACK.
Functions
Decode
func Decode(vr *ValueReader, d interface{}) error
Decode decodes from vr into d. d must be a pointer. This allows implementations of the Decoder interface to delegate the actual work of decoding to the built-in functionality.
Encode
func Encode(wbuf *WriteBuf, oid Oid, arg interface{}) error
Encode encodes arg into wbuf as the type oid. This allows implementations of the Encoder interface to delegate the actual work of encoding to the built-in functionality.
FormatLSN
func FormatLSN(lsn uint64) string
Format the given 64bit LSN value into the XXX/XXX format, which is the format reported by postgres.
LogLevelFromString
func LogLevelFromString(s string) (int, error)
LogLevelFromString converts log level string to constant
Valid levels:
trace debug info warn error none
ParseLSN
func ParseLSN(lsn string) (outputLsn uint64, err error)
Parse the given XXX/XXX format LSN as reported by postgres, into a 64 bit integer as used internally by the wire procotols
Types
AclItem
type AclItem string
AclItem is used for PostgreSQL's aclitem data type. A sample aclitem might look like this:
postgres=arwdDxt/postgres
Note, however, that because the user/role name part of an aclitem is an identifier, it follows all the usual formatting rules for SQL identifiers: if it contains spaces and other special characters, it should appear in double-quotes:
postgres=arwdDxt/"role with spaces"
Char
type Char byte
The pgx.Char type is for PostgreSQL's special 8-bit-only "char" type more akin to the C language's char type, or Go's byte type. (Note that the name in PostgreSQL itself is "char", in double-quotes, and not char.) It gets used a lot in PostgreSQL's system tables to hold a single ASCII character value (eg pg_class.relkind).
Cid
type Cid uint32
Cid is PostgreSQL's Command Identifier type.
When one does
select cmin, cmax, * from some_table;
it is the data type of the cmin and cmax hidden system columns.
It is currently implemented as an unsigned four byte integer. Its definition can be found in src/include/c.h as CommandId in the PostgreSQL sources.
CommandTag
type CommandTag string
CommandTag is the result of an Exec function
CommandTag.RowsAffected
func (ct CommandTag) RowsAffected() int64
RowsAffected returns the number of rows affected. If the CommandTag was not for a row affecting command (such as "CREATE TABLE") then it returns 0
Conn
type Conn struct {
Pid int32 // backend pid
SecretKey int32 // key to use to send a cancel query message to the server
RuntimeParams map[string]string // parameters that have been reported by the server
PgTypes map[Oid]PgType // oids to PgTypes
TxStatus byte
// contains filtered or unexported fields
}
Conn is a PostgreSQL connection handle. It is not safe for concurrent usage. Use ConnPool to manage access to multiple database connections from multiple goroutines.
Connect
func Connect(config ConnConfig) (c *Conn, err error)
Connect establishes a connection with a PostgreSQL server using config. config.Host must be specified. config.User will default to the OS user name. Other config fields are optional.
Conn.Begin
func (c *Conn) Begin() (*Tx, error)
Begin starts a transaction with the default isolation level for the current connection. To use a specific isolation level see BeginIso.
Conn.BeginIso
func (c *Conn) BeginIso(isoLevel string) (*Tx, error)
BeginIso starts a transaction with isoLevel as the transaction isolation level.
Valid isolation levels (and their constants) are:
serializable (pgx.Serializable) repeatable read (pgx.RepeatableRead) read committed (pgx.ReadCommitted) read uncommitted (pgx.ReadUncommitted)
Conn.CauseOfDeath
func (c *Conn) CauseOfDeath() error
Conn.Close
func (c *Conn) Close() (err error)
Close closes a connection. It is safe to call Close on a already closed connection.
Conn.CopyFrom
func (c *Conn) CopyFrom(tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int, error)
CopyFrom uses the PostgreSQL copy protocol to perform bulk data insertion. It returns the number of rows copied and an error.
CopyFrom requires all values use the binary format. Almost all types implemented by pgx use the binary format by default. Types implementing Encoder can only be used if they encode to the binary format.
Conn.CopyTo
func (c *Conn) CopyTo(tableName string, columnNames []string, rowSrc CopyToSource) (int, error)
Deprecated. Use CopyFrom instead. CopyTo uses the PostgreSQL copy protocol to perform bulk data insertion. It returns the number of rows copied and an error.
CopyTo requires all values use the binary format. Almost all types implemented by pgx use the binary format by default. Types implementing Encoder can only be used if they encode to the binary format.
Conn.Deallocate
func (c *Conn) Deallocate(name string) (err error)
Deallocate released a prepared statement
Conn.Exec
func (c *Conn) Exec(sql string, arguments ...interface{}) (commandTag CommandTag, err error)
Exec executes sql. sql can be either a prepared statement name or an SQL string. arguments should be referenced positionally from the sql string as $1, $2, etc.
Conn.IsAlive
func (c *Conn) IsAlive() bool
Conn.Listen
func (c *Conn) Listen(channel string) error
Listen establishes a PostgreSQL listen/notify to channel
Conn.Prepare
func (c *Conn) Prepare(name, sql string) (ps *PreparedStatement, err error)
Prepare creates a prepared statement with name and sql. sql can contain placeholders for bound parameters. These placeholders are referenced positional as $1, $2, etc.
Prepare is idempotent; i.e. it is safe to call Prepare multiple times with the same name and sql arguments. This allows a code path to Prepare and Query/Exec without concern for if the statement has already been prepared.
Conn.PrepareEx
func (c *Conn) PrepareEx(name, sql string, opts *PrepareExOptions) (ps *PreparedStatement, err error)
PrepareEx creates a prepared statement with name and sql. sql can contain placeholders for bound parameters. These placeholders are referenced positional as $1, $2, etc. It defers from Prepare as it allows additional options (such as parameter OIDs) to be passed via struct
PrepareEx is idempotent; i.e. it is safe to call PrepareEx multiple times with the same name and sql arguments. This allows a code path to PrepareEx and Query/Exec without concern for if the statement has already been prepared.
Conn.Query
func (c *Conn) Query(sql string, args ...interface{}) (*Rows, error)
Query executes sql with args. If there is an error the returned *Rows will be returned in an error state. So it is allowed to ignore the error returned from Query and handle it in *Rows.