Involved Source Filesbatch.goconn.gocopy_from.go
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/jackc/pgx/v4/stdlib to use pgx as a database/sql compatible driver.
Establishing a Connection
The primary way of establishing a connection is with `pgx.Connect`.
conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL"))
The database connection string can be in URL or DSN format. Both PostgreSQL settings and pgx settings can be specified
here. In addition, a config struct can be created by `ParseConfig` and modified before establishing the connection with
`ConnectConfig`.
config, err := pgx.ParseConfig(os.Getenv("DATABASE_URL"))
if err != nil {
// ...
}
config.Logger = log15adapter.NewLogger(log.New("module", "pgx"))
conn, err := pgx.ConnectConfig(context.Background(), config)
Connection Pool
`*pgx.Conn` represents a single connection to the database and is not concurrency safe. Use sub-package pgxpool for a
concurrency safe connection pool.
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(context.Background(), "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 rows.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(context.Background(), "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(context.Background(), "delete from widgets where id=$1", 42)
if err != nil {
return err
}
if commandTag.RowsAffected() != 1 {
return errors.New("No row found to delete")
}
QueryFunc can be used to execute a callback function for every row. This is often easier to use than Query.
var sum, n int32
_, err = conn.QueryFunc(
context.Background(),
"select generate_series(1,$1)",
[]interface{}{10},
[]interface{}{&n},
func(pgx.QueryFuncRow) error {
sum += n
return nil
},
)
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 package pgtype provides types that have a data field and a status field.
They work in a similar fashion to database/sql. The second is to use a pointer to a pointer.
var foo pgtype.Varchar
var bar *string
err := conn.QueryRow("select foo, bar from widgets where id=$1", 42).Scan(&foo, &bar)
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. The pgtype package includes many more array types for PostgreSQL types that do not directly
map to native Go types.
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. In addition, pgx uses the github.com/jackc/pgtype library to support more types. See
documention for that library for instructions on how to implement custom types.
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.
If pgx does cannot natively encode a type and that type is a renamed type (e.g. type MyTime time.Time) pgx will attempt
to encode the underlying type. While this is usually desired behavior it can produce surprising behavior if one the
underlying type and the renamed type each implement database/sql interfaces and the other implements pgx interfaces. It
is recommended that this situation be avoided by implementing pgx interfaces on the renamed type.
Composite types and row values
Row values and composite types are represented as pgtype.Record (https://pkg.go.dev/github.com/jackc/pgtype?tab=doc#Record).
It is possible to get values of your custom type by implementing DecodeBinary interface. Decoding into
pgtype.Record first can simplify process by avoiding dealing with raw protocol directly.
For example:
type MyType struct {
a int // NULL will cause decoding error
b *string // there can be NULL in this position in SQL
}
func (t *MyType) DecodeBinary(ci *pgtype.ConnInfo, src []byte) error {
r := pgtype.Record{
Fields: []pgtype.Value{&pgtype.Int4{}, &pgtype.Text{}},
}
if err := r.DecodeBinary(ci, src); err != nil {
return err
}
if r.Status != pgtype.Present {
return errors.New("BUG: decoding should not be called on NULL value")
}
a := r.Fields[0].(*pgtype.Int4)
b := r.Fields[1].(*pgtype.Text)
// type compatibility is checked by AssignTo
// only lossless assignments will succeed
if err := a.AssignTo(&t.a); err != nil {
return err
}
// AssignTo also deals with null value handling
if err := b.AssignTo(&t.b); err != nil {
return err
}
return nil
}
result := MyType{}
err := conn.QueryRow(context.Background(), "select row(1, 'foo'::text)", pgx.QueryResultFormats{pgx.BinaryFormatCode}).Scan(&r)
Raw Bytes Mapping
[]byte passed as arguments to Query, QueryRow, and Exec are passed unmodified to PostgreSQL.
Transactions
Transactions are started by calling Begin.
tx, err := conn.Begin(context.Background())
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(context.Background())
_, err = tx.Exec(context.Background(), "insert into foo(id) values (1)")
if err != nil {
return err
}
err = tx.Commit(context.Background())
if err != nil {
return err
}
The Tx returned from Begin also implements the Begin method. This can be used to implement pseudo nested transactions.
These are internally implemented with savepoints.
Use BeginTx to control the transaction mode.
BeginFunc and BeginTxFunc are variants that begin a transaction, execute a function, and commit or rollback the
transaction depending on the return value of the function. These can be simpler and less error prone to use.
err = conn.BeginFunc(context.Background(), func(tx pgx.Tx) error {
_, err := tx.Exec(context.Background(), "insert into foo(id) values (1)")
return err
})
if err != nil {
return err
}
Prepared Statements
Prepared statements can be manually created with the Prepare method. However, this is rarely necessary because pgx
includes an automatic statement cache by default. Queries run through the normal Query, QueryRow, and Exec functions are
automatically prepared on first execution and the prepared statement is reused on subsequent executions. See ParseConfig
for information on how to customize or disable the statement cache.
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(
context.Background(),
pgx.Identifier{"people"},
[]string{"first_name", "last_name", "age"},
pgx.CopyFromRows(rows),
)
When you already have a typed array using CopyFromSlice can be more convenient.
rows := []User{
{"John", "Smith", 36},
{"Jane", "Doe", 29},
}
copyCount, err := conn.CopyFrom(
context.Background(),
pgx.Identifier{"people"},
[]string{"first_name", "last_name", "age"},
pgx.CopyFromSlice(len(rows), func(i int) ([]interface{}, error) {
return []interface{}{rows[i].FirstName, rows[i].LastName, rows[i].Age}, nil
}),
)
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 `Conn.WaitForNotification` method. It blocks until a
context is received or the context is canceled.
_, err := conn.Exec(context.Background(), "listen channelname")
if err != nil {
return nil
}
if notification, err := conn.WaitForNotification(context.Background()); err != nil {
// do something with notification
}
Logging
pgx defines a simple logger interface. Connections optionally accept a logger that satisfies this interface. Set
LogLevel to control logging verbosity. Adapters for github.com/inconshreveable/log15, github.com/sirupsen/logrus,
go.uber.org/zap, github.com/rs/zerolog, and the testing log are provided in the log directory.
Lower Level PostgreSQL Functionality
pgx is implemented on top of github.com/jackc/pgconn a lower level PostgreSQL driver. The Conn.PgConn() method can be
used to access this lower layer.
PgBouncer
pgx is compatible with PgBouncer in two modes. One is when the connection has a statement cache in "describe" mode. The
other is when the connection is using the simple protocol. This can be set with the PreferSimpleProtocol config option.
extended_query_builder.gogo_stdlib.golarge_objects.gologger.gomessages.gorows.gotx.govalues.go
Code Examples
package main
import (
"context"
"fmt"
"os"
"regexp"
"strconv"
"github.com/jackc/pgtype"
"github.com/jackc/pgx/v4"
)
var pointRegexp *regexp.Regexp = regexp.MustCompile(`^\((.*),(.*)\)$`)
// Point represents a point that may be null.
type Point struct {
X, Y float64 // Coordinates of point
Status pgtype.Status
}
func (dst *Point) Set(src interface{}) error {
return fmt.Errorf("cannot convert %v to Point", src)
}
func (dst *Point) Get() interface{} {
switch dst.Status {
case pgtype.Present:
return dst
case pgtype.Null:
return nil
default:
return dst.Status
}
}
func (src *Point) AssignTo(dst interface{}) error {
return fmt.Errorf("cannot assign %v to %T", src, dst)
}
func (dst *Point) DecodeText(ci *pgtype.ConnInfo, src []byte) error {
if src == nil {
*dst = Point{Status: pgtype.Null}
return nil
}
s := string(src)
match := pointRegexp.FindStringSubmatch(s)
if match == nil {
return fmt.Errorf("Received invalid point: %v", s)
}
x, err := strconv.ParseFloat(match[1], 64)
if err != nil {
return fmt.Errorf("Received invalid point: %v", s)
}
y, err := strconv.ParseFloat(match[2], 64)
if err != nil {
return fmt.Errorf("Received invalid point: %v", s)
}
*dst = Point{X: x, Y: y, Status: pgtype.Present}
return nil
}
func (src *Point) String() string {
if src.Status == pgtype.Null {
return "null point"
}
return fmt.Sprintf("%.1f, %.1f", src.X, src.Y)
}
func main() {
conn, err := pgx.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE"))
if err != nil {
fmt.Printf("Unable to establish connection: %v", err)
return
}
defer conn.Close(context.Background())
if conn.PgConn().ParameterStatus("crdb_version") != "" {
// Skip test / example when running on CockroachDB which doesn't support the point type. Since an example can't be
// skipped fake success instead.
fmt.Println("null point")
fmt.Println("1.5, 2.5")
return
}
// Override registered handler for point
conn.ConnInfo().RegisterDataType(pgtype.DataType{
Value: &Point{},
Name: "point",
OID: 600,
})
p := &Point{}
err = conn.QueryRow(context.Background(), "select null::point").Scan(p)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(p)
err = conn.QueryRow(context.Background(), "select point(1.5,2.5)").Scan(p)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(p)
}
{
conn, err := pgx.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE"))
if err != nil {
fmt.Printf("Unable to establish connection: %v", err)
return
}
type person struct {
Name string `json:"name"`
Age int `json:"age"`
}
input := person{
Name: "John",
Age: 42,
}
var output person
err = conn.QueryRow(context.Background(), "select $1::json", input).Scan(&output)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(output.Name, output.Age)
}
Package-Level Type Names (total 36, in which 25 are exported)
/* sort exporteds by: | */
Batch queries are a way of bundling multiple queries together to avoid
unnecessary network round trips.
items[]*batchItem
Len returns number of queries that have been queued so far.
Queue queues a query to batch b. query can be an SQL query or the name of a prepared statement.
*T : github.com/aws/aws-sdk-go/aws/corehandlers.lener
func (*Conn).SendBatch(ctx context.Context, b *Batch) BatchResults
func Tx.SendBatch(ctx context.Context, b *Batch) BatchResults
Close closes the batch operation. This must be called before the underlying connection can be used again. Any error
that occurred during a batch operation may have made it impossible to resyncronize the connection with the server.
In this case the underlying connection will have been closed.
Exec reads the results from the next query in the batch as if the query has been sent with Conn.Exec.
Query reads the results from the next query in the batch as if the query has been sent with Conn.Query.
QueryRow reads the results from the next query in the batch as if the query has been sent with Conn.QueryRow.
*batchResults
T : io.Closer
func (*Conn).SendBatch(ctx context.Context, b *Batch) BatchResults
func Tx.SendBatch(ctx context.Context, b *Batch) BatchResults
BuildStatementCacheFunc is a function that can be used to create a stmtcache.Cache implementation for connection.
Conn is a PostgreSQL connection handle. It is not safe for concurrent usage. Use a connection pool to manage access
to multiple database connections from multiple goroutines.
closedChanchan error
// config used when establishing this connection
connInfo*pgtype.ConnInfodoneChanchan struct{}eqbextendedQueryBuilderlogLevelLogLevelloggerLoggernotifications[]*pgconn.NotificationpgConn*pgconn.PgConnpreallocatedRows[]connRowspreparedStatementsmap[string]*pgconn.StatementDescriptionstmtcachestmtcache.Cachewbuf[]byte
Begin starts a transaction. Unlike database/sql, the context only affects the begin command. i.e. there is no
auto-rollback on context cancellation.
BeginFunc starts a transaction and calls f. If f does not return an error the transaction is committed. If f returns
an error the transaction is rolled back. The context will be used when executing the transaction control statements
(BEGIN, ROLLBACK, and COMMIT) but does not otherwise affect the execution of f.
BeginTx starts a transaction with txOptions determining the transaction mode. Unlike database/sql, the context only
affects the begin command. i.e. there is no auto-rollback on context cancellation.
BeginTxFunc starts a transaction with txOptions determining the transaction mode and calls f. If f does not return
an error the transaction is committed. If f returns an error the transaction is rolled back. The context will be
used when executing the transaction control statements (BEGIN, ROLLBACK, and COMMIT) but does not otherwise affect
the execution of f.
Close closes a connection. It is safe to call Close on a already closed
connection.
Config returns a copy of config that was used to establish this connection.
ConnInfo returns the connection info used for this connection.
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.
Deallocate released a prepared statement
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.
(*T) IsClosed() bool
PgConn returns the underlying *pgconn.PgConn. This is an escape hatch method that allows lower level access to the
PostgreSQL connection than pgx exposes.
It is strongly recommended that the connection be idle (no in-progress queries) before the underlying *pgconn.PgConn
is used and the connection must be returned to the same state before any *pgx.Conn methods are again used.
(*T) Ping(ctx context.Context) 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.
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.
For extra control over how the query is executed, the types QuerySimpleProtocol, QueryResultFormats, and
QueryResultFormatsByOID may be used as the first args to control exactly how the query is executed. This is rarely
needed. See the documentation for those types for details.
QueryFunc executes sql with args. For each row returned by the query the values will scanned into the elements of
scans and f will be called. If any row fails to scan or f returns an error the query will be aborted and the error
will be returned.
QueryRow is a convenience wrapper over Query. Any error that occurs while
querying is deferred until calling Scan on the returned Row. That Row will
error with ErrNoRows if no rows are returned.
SendBatch sends all queued queries to the server at once. All queries are run in an implicit transaction unless
explicit transaction control statements are executed. The returned BatchResults must be closed before the connection
is used again.
StatementCache returns the statement cache used for this connection.
WaitForNotification waits for a PostgreSQL notification. It wraps the underlying pgconn notification system in a
slightly more convenient form.
(*T) bufferNotifications(_ *pgconn.PgConn, n *pgconn.Notification)(*T) die(err error)(*T) exec(ctx context.Context, sql string, arguments ...interface{}) (commandTag pgconn.CommandTag, err error)(*T) execParams(ctx context.Context, sd *pgconn.StatementDescription, arguments []interface{}) (pgconn.CommandTag, error)(*T) execParamsAndPreparedPrefix(sd *pgconn.StatementDescription, arguments []interface{}) error(*T) execPrepared(ctx context.Context, sd *pgconn.StatementDescription, arguments []interface{}) (pgconn.CommandTag, error)(*T) execSimpleProtocol(ctx context.Context, sql string, arguments []interface{}) (commandTag pgconn.CommandTag, err error)(*T) getRows(ctx context.Context, sql string, args []interface{}) *connRows(*T) log(ctx context.Context, lvl LogLevel, msg string, data map[string]interface{})(*T) sanitizeForSimpleQuery(sql string, args ...interface{}) (string, error)(*T) shouldLog(lvl LogLevel) bool
*T : database/sql/driver.Pinger
*T : rowLog
func Connect(ctx context.Context, connString string) (*Conn, error)
func ConnectConfig(ctx context.Context, connConfig *ConnConfig) (*Conn, error)
func Tx.Conn() *Conn
func github.com/jackc/pgx/v4/stdlib.AcquireConn(db *sql.DB) (*Conn, error)
func github.com/jackc/pgx/v4/stdlib.(*Conn).Conn() *Conn
func connect(ctx context.Context, config *ConnConfig) (c *Conn, err error)
func github.com/jackc/pgx/v4/stdlib.ReleaseConn(db *sql.DB, conn *Conn) error
ConnConfig contains all the options used to establish a connection. It must be created by ParseConfig and
then it can be modified. A manually initialized ConnConfig will cause ConnectConfig to panic.
BuildStatementCache creates the stmtcache.Cache implementation for connections created with this config. Set
to nil to disable automatic prepared statements.
Configpgconn.Config
AfterConnect is called after ValidateConnect. It can be used to set up the connection (e.g. Set session variables
or prepare statements). If this returns an error the connection attempt fails.
Config.BuildFrontendpgconn.BuildFrontendFuncConfig.ConnectTimeouttime.DurationConfig.Databasestring
// e.g. net.Dialer.DialContext
Config.Fallbacks[]*pgconn.FallbackConfig
// host (e.g. localhost) or absolute path to unix domain socket directory (e.g. /private/tmp)
// e.g. net.Resolver.LookupHost
OnNotice is a callback function called when a notice response is received.
OnNotification is a callback function called when a notification from the LISTEN/NOTIFY system is received.
Config.PasswordstringConfig.Portuint16
// Run-time parameters to set on connection as session default values (e.g. search_path or application_name)
// nil disables TLS
Config.Userstring
ValidateConnect is called during a connection attempt after a successful authentication with the PostgreSQL server.
It can be used to validate that the server is acceptable. If this returns an error the connection is closed and the next
fallback config is tried. This allows implementing high availability behavior such as libpq does with target_session_attrs.
LogLevelLogLevelLoggerLogger
PreferSimpleProtocol disables implicit prepared statement usage. By default pgx automatically uses the extended
protocol. This can improve performance due to being able to use the binary format. It also does not rely on client
side parameter sanitization. However, it does incur two round-trips per query (unless using a prepared statement)
and may be incompatible proxies such as PGBouncer. Setting PreferSimpleProtocol causes the simple protocol to be
used by default. The same functionality can be controlled on a per query basis by setting
QueryExOptions.SimpleProtocol.
// Used to enforce created by ParseConfig rule.
Original connection string that was parsed into config.
// Used to enforce created by ParseConfig rule.
(*T) ConnString() string
Copy returns a deep copy of the config that is safe to use and modify.
The only exception is the tls.Config:
according to the tls.Config docs it must not be modified after creation.
func ParseConfig(connString string) (*ConnConfig, error)
func (*Conn).Config() *ConnConfig
func (*ConnConfig).Copy() *ConnConfig
func ConnectConfig(ctx context.Context, connConfig *ConnConfig) (*Conn, error)
func github.com/jackc/pgx/v4/stdlib.OpenDB(config ConnConfig, opts ...stdlib.OptionOpenDB) *sql.DB
func github.com/jackc/pgx/v4/stdlib.RegisterConnConfig(c *ConnConfig) string
func connect(ctx context.Context, config *ConnConfig) (c *Conn, err error)
func github.com/jackc/pgx/v4/stdlib.(*Driver).registerConnConfig(c *ConnConfig) string
CopyFromSource is the interface used by *Conn.CopyFrom as the source for copy data.
Err returns any error that has been encountered by the CopyFromSource. If
this is not nil *Conn.CopyFrom will abort the copy.
Next returns true if there is another row and makes the next row data
available to Values(). When there are no more rows available or an error
has occurred it returns false.
Values returns the values for the current row.
Rows(interface)
*connRows
*copyFromRows
*copyFromSlice
*golang.org/x/pkgsite/internal/database.chanCopySource
func CopyFromRows(rows [][]interface{}) CopyFromSource
func CopyFromSlice(length int, next func(int) ([]interface{}, error)) CopyFromSource
func golang.org/x/pkgsite/internal/database.CopyFromChan(c <-chan database.RowItem) CopyFromSource
func (*Conn).CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, error)
func Tx.CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, error)
func golang.org/x/pkgsite/internal/database.(*DB).CopyUpsert(ctx context.Context, table string, columns []string, src CopyFromSource, conflictColumns []string, dropColumn string) (err error)
Identifier a PostgreSQL identifier or name. Identifiers can be composed of
multiple parts such as ["schema", "table"] or ["table", "column"].
Sanitize returns a sanitized string safe for SQL interpolation.
func (*Conn).CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, error)
func Tx.CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, error)
A LargeObject is a large object stored on the server. It is only valid within the transaction that it was initialized
in. It uses the context it was initialized with for all operations. It implements these interfaces:
io.Writer
io.Reader
io.Seeker
io.Closer
ctxcontext.Contextfdint32txTx
Close closees the large object descriptor.
Read reads up to len(p) bytes into p returning the number of bytes read.
Seek moves the current location pointer to the new location specified by offset.
Tell returns the current read or write location of the large object descriptor.
Trunctes the large object to size.
Write writes p to the large object and returns the number of bytes written and an error if not all of p was written.
*T : github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband.Progress
*T : github.com/jbenet/go-context/io.Reader
*T : github.com/jbenet/go-context/io.Writer
*T : io.Closer
*T : io.ReadCloser
*T : io.Reader
*T : io.ReadSeekCloser
*T : io.ReadSeeker
*T : io.ReadWriteCloser
*T : io.ReadWriter
*T : io.ReadWriteSeeker
*T : io.Seeker
*T : io.WriteCloser
*T : io.Writer
*T : io.WriteSeeker
func (*LargeObjects).Open(ctx context.Context, oid uint32, mode LargeObjectMode) (*LargeObject, error)
LargeObjects is a structure used to access the large objects API. It is only valid within the transaction where it
was created.
For more details see: http://www.postgresql.org/docs/current/static/largeobjects.html
txTx
Create creates a new large object. If oid is zero, the server assigns an unused OID.
Open opens an existing large object with the given mode. ctx will also be used for all operations on the opened large
object.
Unlink removes a large object from the database.
func Tx.LargeObjects() LargeObjects
Logger is the interface used to get logging from pgx internals.
Log a message at the given level with data key/value pairs. data may be nil.
QueryFuncRow is the argument to the QueryFunc callback function.
QueryFuncRow is an interface instead of a struct to allow tests to mock QueryFunc. However, adding a method to an
interface is technically a breaking change. Because of this the QueryFuncRow interface is partially excluded from
semantic version requirements. Methods will not be removed or changed, but new methods may be added.
( T) FieldDescriptions() []pgproto3.FieldDescription
RawValues returns the unparsed bytes of the row values. The returned [][]byte is only valid during the current
function call. However, the underlying byte data is safe to retain a reference to and mutate.
Rows(interface)
*connRows
QueryResultFormats controls the result format (text=0, binary=1) of a query by result column position.
QueryResultFormatsByOID controls the result format (text=0, binary=1) of a query by the result column OID.
var github.com/jackc/pgx/v4/stdlib.databaseSQLResultFormats
QuerySimpleProtocol controls whether the simple or extended protocol is used to send the query.
Row is a convenience wrapper over Rows that is returned by QueryRow.
Row is an interface instead of a struct to allow tests to mock QueryRow. However,
adding a method to an interface is technically a breaking change. Because of this
the Row interface is partially excluded from semantic version requirements.
Methods will not be removed or changed, but new methods may be added.
( T) Scan(...interface{}) errorRows(interface)
github.com/Masterminds/squirrel.InsertBuilder
*github.com/Masterminds/squirrel.Row
github.com/Masterminds/squirrel.RowScanner(interface)
github.com/Masterminds/squirrel.SelectBuilder
github.com/Masterminds/squirrel.UpdateBuilder
*database/sql.Row
*database/sql.Rows
*connRow
*connRows
T : github.com/Masterminds/squirrel.RowScanner
func BatchResults.QueryRow() Row
func (*Conn).QueryRow(ctx context.Context, sql string, args ...interface{}) Row
func Tx.QueryRow(ctx context.Context, sql string, args ...interface{}) Row
Rows is the result set returned from *Conn.Query. Rows must be closed before
the *Conn can be used again. Rows are closed by explicitly calling Close(),
calling Next() until it returns false, or when a fatal error occurs.
Once a Rows is closed the only methods that may be called are Close(), Err(), and CommandTag().
Rows is an interface instead of a struct to allow tests to mock Query. However,
adding a method to an interface is technically a breaking change. Because of this
the Rows interface is partially excluded from semantic version requirements.
Methods will not be removed or changed, but new methods may be added.
Close closes the rows, making the connection ready for use again. It is safe
to call Close after rows is already closed.
CommandTag returns the command tag from this query. It is only available after Rows is closed.
Err returns any error that occurred while reading.
( T) FieldDescriptions() []pgproto3.FieldDescription
Next prepares the next row for reading. It returns true if there is another
row and false if no more rows are available. It automatically closes rows
when all rows are read.
RawValues returns the unparsed bytes of the row values. The returned [][]byte is only valid until the next Next
call or the Rows is closed. However, the underlying byte data is safe to retain a reference to and mutate.
Scan reads the values from the current row into dest values positionally.
dest can include pointers to core types, values implementing the Scanner
interface, and nil. nil will skip the value entirely.
Values returns the decoded row values.
*connRows
T : CopyFromSource
T : QueryFuncRow
T : Row
T : github.com/Masterminds/squirrel.RowScanner
func BatchResults.Query() (Rows, error)
func (*Conn).Query(ctx context.Context, sql string, args ...interface{}) (Rows, error)
func Tx.Query(ctx context.Context, sql string, args ...interface{}) (Rows, error)
func connInfoFromRows(rows Rows, err error) (map[string]uint32, error)
SerializationError occurs on failure to encode or decode a value
( T) Error() string
T : error
Tx represents a database transaction.
Tx is an interface instead of a struct to enable connection pools to be implemented without relying on internal pgx
state, to support pseudo-nested transactions with savepoints, and to allow tests to mock transactions. However,
adding a method to an interface is technically a breaking change. If new methods are added to Conn it may be
desirable to add them to Tx as well. Because of this the Tx interface is partially excluded from semantic version
requirements. Methods will not be removed or changed, but new methods may be added.
Begin starts a pseudo nested transaction.
BeginFunc starts a pseudo nested transaction and executes f. If f does not return an err the pseudo nested
transaction will be committed. If it does then it will be rolled back.
Commit commits the transaction if this is a real transaction or releases the savepoint if this is a pseudo nested
transaction. Commit will return ErrTxClosed if the Tx is already closed, but is otherwise safe to call multiple
times. If the commit fails with a rollback status (e.g. the transaction was already in a broken state) then
ErrTxCommitRollback will be returned.
Conn returns the underlying *Conn that on which this transaction is executing.
( T) CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, error)( T) Exec(ctx context.Context, sql string, arguments ...interface{}) (commandTag pgconn.CommandTag, err error)( T) LargeObjects() LargeObjects( T) Prepare(ctx context.Context, name, sql string) (*pgconn.StatementDescription, error)( T) Query(ctx context.Context, sql string, args ...interface{}) (Rows, error)( T) QueryFunc(ctx context.Context, sql string, args []interface{}, scans []interface{}, f func(QueryFuncRow) error) (pgconn.CommandTag, error)( T) QueryRow(ctx context.Context, sql string, args ...interface{}) Row
Rollback rolls back the transaction if this is a real transaction or rolls back to the savepoint if this is a
pseudo nested transaction. Rollback will return ErrTxClosed if the Tx is already closed, but is otherwise safe to
call multiple times. Hence, a defer tx.Rollback() is safe even if tx.Commit() will be called first in a non-error
condition. Any other failure of a real transaction will result in the connection being closed.
( T) SendBatch(ctx context.Context, b *Batch) BatchResults
*dbSavepoint
*dbTx
func (*Conn).Begin(ctx context.Context) (Tx, error)
func (*Conn).BeginTx(ctx context.Context, txOptions TxOptions) (Tx, error)
func Tx.Begin(ctx context.Context) (Tx, error)
b*Batchconn*Connctxcontext.Contexterrerrorixintmrr*pgconn.MultiResultReader
Close closes the batch operation. Any error that occurred during a batch operation may have made it impossible to
resyncronize the connection with the server. In this case the underlying connection will have been closed.
Exec reads the results from the next query in the batch as if the query has been sent with Exec.
Query reads the results from the next query in the batch as if the query has been sent with Query.
QueryRow reads the results from the next query in the batch as if the query has been sent with QueryRow.
(*T) nextQueryAndArgs() (query string, args []interface{}, ok bool)
*T : BatchResults
*T : io.Closer
dbSavepoint represents a nested transaction implemented by a savepoint.
closedboolsavepointNumint64txTx
Begin starts a pseudo nested transaction implemented with a savepoint.
(*T) BeginFunc(ctx context.Context, f func(Tx) error) (err error)
Commit releases the savepoint essentially committing the pseudo nested transaction.
(*T) Conn() *Conn
CopyFrom delegates to the underlying *Conn
Exec delegates to the underlying Tx
(*T) LargeObjects() LargeObjects
Prepare delegates to the underlying Tx
Query delegates to the underlying Tx
QueryFunc delegates to the underlying Tx.
QueryRow delegates to the underlying Tx
Rollback rolls back to the savepoint essentially rolling back the pseudo nested transaction. Rollback will return
ErrTxClosed if the dbSavepoint is already closed, but is otherwise safe to call multiple times. Hence, a defer sp.Rollback()
is safe even if sp.Commit() will be called first in a non-error condition.
SendBatch delegates to the underlying *Conn
*T : Tx
dbTx represents a database transaction.
All dbTx methods return ErrTxClosed if Commit or Rollback has already been
called on the dbTx.
closedboolconn*ConnerrerrorsavepointNumint64
Begin starts a pseudo nested transaction implemented with a savepoint.
(*T) BeginFunc(ctx context.Context, f func(Tx) error) (err error)
Commit commits the transaction.
(*T) Conn() *Conn
CopyFrom delegates to the underlying *Conn
Exec delegates to the underlying *Conn
LargeObjects returns a LargeObjects instance for the transaction.
Prepare delegates to the underlying *Conn
Query delegates to the underlying *Conn
QueryFunc delegates to the underlying *Conn.
QueryRow delegates to the underlying *Conn
Rollback rolls back the transaction. Rollback will return ErrTxClosed if the
Tx is already closed, but is otherwise safe to call multiple times. Hence, a
defer tx.Rollback() is safe even if tx.Commit() will be called first in a
non-error condition.
SendBatch delegates to the underlying *Conn
*T : Tx
Package-Level Functions (total 17, in which 7 are exported)
Connect establishes a connection with a PostgreSQL server with a connection string. See
pgconn.Connect for details.
Connect establishes a connection with a PostgreSQL server with a configuration struct. connConfig must have been
created by ParseConfig.
CopyFromRows returns a CopyFromSource interface over the provided rows slice
making it usable by *Conn.CopyFrom.
CopyFromSlice returns a CopyFromSource interface over a dynamic func
making it usable by *Conn.CopyFrom.
LogLevelFromString converts log level string to constant
Valid levels:
trace
debug
info
warn
error
none
ParseConfig creates a ConnConfig from a connection string. ParseConfig handles all options that pgconn.ParseConfig
does. In addition, it accepts the following options:
statement_cache_capacity
The maximum size of the automatic statement cache. Set to 0 to disable automatic statement caching. Default: 512.
statement_cache_mode
Possible values: "prepare" and "describe". "prepare" will create prepared statements on the PostgreSQL server.
"describe" will use the anonymous prepared statement to describe a statement without creating a statement on the
server. "describe" is primarily useful when the environment does not allow prepared statements such as when
running a connection pooler like PgBouncer. Default: "prepare"
prefer_simple_protocol
Possible values: "true" and "false". Use the simple protocol instead of extended protocol. Default: false
ScanRow decodes raw row data into dest. It can be used to scan rows read from the lower level pgconn interface.
connInfo - OID to Go type mapping.
fieldDescriptions - OID and format of values
values - the raw data as returned from the PostgreSQL server
dest - the destination that values will be decoded into
callValuerValue returns vr.Value(), with one exception:
If vr.Value is an auto-generated method on a pointer type and the
pointer is nil, it would panic at runtime in the panicwrap
method. Treat it like nil instead.
Issue 8415.
This is so people can implement driver.Value on value types and
still use nil pointers to those types to mean nil/NULL, just like
string/*string.
This function is mirrored in the database/sql/driver package.
chooseParameterFormatCode determines the correct format code for an
argument to a prepared statement. It defaults to TextFormatCode if no
determination can be made.
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.
The values for log levels are chosen such that the zero value means that no
log level was specified.
The values for log levels are chosen such that the zero value means that no
log level was specified.
The values for log levels are chosen such that the zero value means that no
log level was specified.
The values for log levels are chosen such that the zero value means that no
log level was specified.
The values for log levels are chosen such that the zero value means that no
log level was specified.
The values for log levels are chosen such that the zero value means that no
log level was specified.
Transaction deferrable modes
Transaction isolation levels
Transaction access modes
Transaction isolation levels
Transaction access modes
Transaction isolation levels
Transaction isolation levels
PostgreSQL format codes
The pages are generated with Goldsv0.3.2-preview. (GOOS=darwin GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds.