The values for log levels are chosen such that the zero value means that no log level was specified.
const ( LogLevelTrace = 6 LogLevelDebug = 5 LogLevelInfo = 4 LogLevelWarn = 3 LogLevelError = 2 LogLevelNone = 1 )
PostgreSQL format codes
const ( TextFormatCode = 0 BinaryFormatCode = 1 )
ErrInvalidLogLevel occurs on attempt to set an invalid log level.
var ErrInvalidLogLevel = errors.New("invalid log level")
ErrNoRows occurs when rows are expected but none are returned.
var ErrNoRows = errors.New("no rows in result set")
var ErrTxClosed = errors.New("tx is closed")
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.
var ErrTxCommitRollback = errors.New("commit unexpectedly resulted in rollback")
func ScanRow(connInfo *pgtype.ConnInfo, fieldDescriptions []pgproto3.FieldDescription, values [][]byte, dest ...interface{}) error
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
Batch queries are a way of bundling multiple queries together to avoid unnecessary network round trips.
type Batch struct {
// contains filtered or unexported fields
}
func (b *Batch) Len() int
Len returns number of queries that have been queued so far.
func (b *Batch) Queue(query string, arguments ...interface{})
Queue queues a query to batch b. query can be an SQL query or the name of a prepared statement.
type BatchResults interface { // Exec reads the results from the next query in the batch as if the query has been sent with Conn.Exec. Exec() (pgconn.CommandTag, error) // Query reads the results from the next query in the batch as if the query has been sent with Conn.Query. Query() (Rows, error) // QueryRow reads the results from the next query in the batch as if the query has been sent with Conn.QueryRow. QueryRow() Row // QueryFunc reads the results from the next query in the batch as if the query has been sent with Conn.QueryFunc. QueryFunc(scans []interface{}, f func(QueryFuncRow) error) (pgconn.CommandTag, error) // 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. Close is safe to call multiple times. Close() error }
BuildStatementCacheFunc is a function that can be used to create a stmtcache.Cache implementation for connection.
type BuildStatementCacheFunc func(conn *pgconn.PgConn) stmtcache.Cache
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.
type Conn struct {
// contains filtered or unexported fields
}
func Connect(ctx context.Context, connString string) (*Conn, error)
Connect establishes a connection with a PostgreSQL server with a connection string. See pgconn.Connect for details.
func ConnectConfig(ctx context.Context, connConfig *ConnConfig) (*Conn, error)
ConnectConfig establishes a connection with a PostgreSQL server with a configuration struct. connConfig must have been created by ParseConfig.
func (c *Conn) Begin(ctx context.Context) (Tx, error)
Begin starts a transaction. Unlike database/sql, the context only affects the begin command. i.e. there is no auto-rollback on context cancellation.
func (c *Conn) BeginFunc(ctx context.Context, f func(Tx) error) (err error)
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.
func (c *Conn) BeginTx(ctx context.Context, txOptions TxOptions) (Tx, error)
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.
func (c *Conn) BeginTxFunc(ctx context.Context, txOptions TxOptions, f func(Tx) error) (err error)
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.
func (c *Conn) Close(ctx context.Context) error
Close closes a connection. It is safe to call Close on a already closed connection.
func (c *Conn) Config() *ConnConfig
Config returns a copy of config that was used to establish this connection.
func (c *Conn) ConnInfo() *pgtype.ConnInfo
ConnInfo returns the connection info used for this connection.
func (c *Conn) CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, 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.
func (c *Conn) Deallocate(ctx context.Context, name string) error
Deallocate released a prepared statement
func (c *Conn) Exec(ctx context.Context, sql string, arguments ...interface{}) (pgconn.CommandTag, 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.
func (c *Conn) IsClosed() bool
IsClosed reports if the connection has been closed.
func (c *Conn) PgConn() *pgconn.PgConn
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.
func (c *Conn) Ping(ctx context.Context) error
Ping executes an empty sql statement against the *Conn If the sql returns without error, the database Ping is considered successful, otherwise, the error is returned.
func (c *Conn) Prepare(ctx context.Context, name, sql string) (sd *pgconn.StatementDescription, 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.
func (c *Conn) Query(ctx context.Context, sql string, args ...interface{}) (Rows, error)
Query sends a query to the server and returns a Rows to read the results. Only errors encountered sending the query and initializing Rows will be returned. Err() on the returned Rows must be checked after the Rows is closed to determine if the query executed successfully.
The returned Rows must be closed before the connection can be used again. It is safe to attempt to read from the returned Rows even if an error is returned. The error will be the available in rows.Err() after rows are closed. It is allowed to ignore the error returned from Query and handle it in Rows.
Err() on the returned Rows must be checked after the Rows is closed to determine if the query executed successfully as some errors can only be detected by reading the entire response. e.g. A divide by zero error on the last row.
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.
func (c *Conn) QueryFunc(ctx context.Context, sql string, args []interface{}, scans []interface{}, f func(QueryFuncRow) error) (pgconn.CommandTag, error)
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.
▹ Example
func (c *Conn) QueryRow(ctx context.Context, sql string, args ...interface{}) Row
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.
func (c *Conn) SendBatch(ctx context.Context, b *Batch) BatchResults
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.
func (c *Conn) StatementCache() stmtcache.Cache
StatementCache returns the statement cache used for this connection.
func (c *Conn) WaitForNotification(ctx context.Context) (*pgconn.Notification, error)
WaitForNotification waits for a PostgreSQL notification. It wraps the underlying pgconn notification system in a slightly more convenient form.
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.
type ConnConfig struct { pgconn.Config Logger Logger LogLevel LogLevel // BuildStatementCache creates the stmtcache.Cache implementation for connections created with this config. Set // to nil to disable automatic prepared statements. BuildStatementCache BuildStatementCacheFunc // 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. PreferSimpleProtocol bool // contains filtered or unexported fields }
func ParseConfig(connString string) (*ConnConfig, error)
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
func (cc *ConnConfig) ConnString() string
ConnString returns the connection string as parsed by pgx.ParseConfig into pgx.ConnConfig.
func (cc *ConnConfig) Copy() *ConnConfig
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.
CopyFromSource is the interface used by *Conn.CopyFrom as the source for copy data.
type CopyFromSource interface { // 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. Next() bool // Values returns the values for the current row. Values() ([]interface{}, error) // Err returns any error that has been encountered by the CopyFromSource. If // this is not nil *Conn.CopyFrom will abort the copy. Err() error }
func CopyFromRows(rows [][]interface{}) CopyFromSource
CopyFromRows returns a CopyFromSource interface over the provided rows slice making it usable by *Conn.CopyFrom.
func CopyFromSlice(length int, next func(int) ([]interface{}, error)) CopyFromSource
CopyFromSlice returns a CopyFromSource interface over a dynamic func making it usable by *Conn.CopyFrom.
Identifier a PostgreSQL identifier or name. Identifiers can be composed of multiple parts such as ["schema", "table"] or ["table", "column"].
type Identifier []string
func (ident Identifier) Sanitize() string
Sanitize returns a sanitized string safe for SQL interpolation.
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
type LargeObject struct {
// contains filtered or unexported fields
}
func (o *LargeObject) Close() error
Close the large object descriptor.
func (o *LargeObject) Read(p []byte) (int, error)
Read reads up to len(p) bytes into p returning the number of bytes read.
func (o *LargeObject) Seek(offset int64, whence int) (n int64, err error)
Seek moves the current location pointer to the new location specified by offset.
func (o *LargeObject) Tell() (n int64, err error)
Tell returns the current read or write location of the large object descriptor.
func (o *LargeObject) Truncate(size int64) (err error)
Truncate the large object to size.
func (o *LargeObject) Write(p []byte) (int, error)
Write writes p to the large object and returns the number of bytes written and an error if not all of p was written.
type LargeObjectMode int32
const ( LargeObjectModeWrite LargeObjectMode = 0x20000 LargeObjectModeRead LargeObjectMode = 0x40000 )
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
type LargeObjects struct {
// contains filtered or unexported fields
}
func (o *LargeObjects) Create(ctx context.Context, oid uint32) (uint32, error)
Create creates a new large object. If oid is zero, the server assigns an unused OID.
func (o *LargeObjects) Open(ctx context.Context, oid uint32, mode LargeObjectMode) (*LargeObject, error)
Open opens an existing large object with the given mode. ctx will also be used for all operations on the opened large object.
func (o *LargeObjects) Unlink(ctx context.Context, oid uint32) error
Unlink removes a large object from the database.
LogLevel represents the pgx logging level. See LogLevel* constants for possible values.
type LogLevel int
func LogLevelFromString(s string) (LogLevel, error)
LogLevelFromString converts log level string to constant
Valid levels:
trace debug info warn error none
func (ll LogLevel) String() string
Logger is the interface used to get logging from pgx internals.
type Logger interface { // Log a message at the given level with data key/value pairs. data may be nil. Log(ctx context.Context, level LogLevel, msg string, data map[string]interface{}) }
LoggerFunc is a wrapper around a function to satisfy the pgx.Logger interface
type LoggerFunc func(ctx context.Context, level LogLevel, msg string, data map[string]interface{})
func (f LoggerFunc) Log(ctx context.Context, level LogLevel, msg string, data map[string]interface{})
Log delegates the logging request to the wrapped function
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.
type QueryFuncRow interface { 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. RawValues() [][]byte }
QueryResultFormats controls the result format (text=0, binary=1) of a query by result column position.
type QueryResultFormats []int16
QueryResultFormatsByOID controls the result format (text=0, binary=1) of a query by the result column OID.
type QueryResultFormatsByOID map[uint32]int16
QuerySimpleProtocol controls whether the simple or extended protocol is used to send the query.
type QuerySimpleProtocol bool
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.
type Row interface { // Scan works the same as Rows. with the following exceptions. If no // rows were found it returns ErrNoRows. If multiple rows are returned it // ignores all but the first. Scan(dest ...interface{}) error }
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.
type Rows interface { // Close closes the rows, making the connection ready for use again. It is safe // to call Close after rows is already closed. Close() // Err returns any error that occurred while reading. Err() error // CommandTag returns the command tag from this query. It is only available after Rows is closed. CommandTag() pgconn.CommandTag 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. Next() bool // 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. It is an error to // call Scan without first calling Next() and checking that it returned true. Scan(dest ...interface{}) error // Values returns the decoded row values. As with Scan(), it is an error to // call Values without first calling Next() and checking that it returned // true. Values() ([]interface{}, error) // 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. RawValues() [][]byte }
type ScanArgError struct { ColumnIndex int Err error }
func (e ScanArgError) Error() string
func (e ScanArgError) Unwrap() error
SerializationError occurs on failure to encode or decode a value
type SerializationError string
func (e SerializationError) Error() string
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.
type Tx interface { // Begin starts a pseudo nested transaction. Begin(ctx context.Context) (Tx, error) // 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. BeginFunc(ctx context.Context, f func(Tx) error) (err error) // 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. Commit(ctx context.Context) error // 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. Rollback(ctx context.Context) error CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, error) SendBatch(ctx context.Context, b *Batch) BatchResults LargeObjects() LargeObjects Prepare(ctx context.Context, name, sql string) (*pgconn.StatementDescription, error) Exec(ctx context.Context, sql string, arguments ...interface{}) (commandTag pgconn.CommandTag, err error) Query(ctx context.Context, sql string, args ...interface{}) (Rows, error) QueryRow(ctx context.Context, sql string, args ...interface{}) Row QueryFunc(ctx context.Context, sql string, args []interface{}, scans []interface{}, f func(QueryFuncRow) error) (pgconn.CommandTag, error) // Conn returns the underlying *Conn that on which this transaction is executing. Conn() *Conn }
TxAccessMode is the transaction access mode (read write or read only)
type TxAccessMode string
Transaction access modes
const ( ReadWrite TxAccessMode = "read write" ReadOnly TxAccessMode = "read only" )
TxDeferrableMode is the transaction deferrable mode (deferrable or not deferrable)
type TxDeferrableMode string
Transaction deferrable modes
const ( Deferrable TxDeferrableMode = "deferrable" NotDeferrable TxDeferrableMode = "not deferrable" )
TxIsoLevel is the transaction isolation level (serializable, repeatable read, read committed or read uncommitted)
type TxIsoLevel string
Transaction isolation levels
const ( Serializable TxIsoLevel = "serializable" RepeatableRead TxIsoLevel = "repeatable read" ReadCommitted TxIsoLevel = "read committed" ReadUncommitted TxIsoLevel = "read uncommitted" )
TxOptions are transaction modes within a transaction block
type TxOptions struct { IsoLevel TxIsoLevel AccessMode TxAccessMode DeferrableMode TxDeferrableMode }
Name | Synopsis |
---|---|
.. | |
examples | |
chat | |
todo | |
url_shortener | |
log | |
kitlogadapter | |
log15adapter | Package log15adapter provides a logger that writes to a github.com/inconshreveable/log15.Logger log. |
logrusadapter | Package logrusadapter provides a logger that writes to a github.com/sirupsen/logrus.Logger log. |
testingadapter | Package testingadapter provides a logger that writes to a test or benchmark log. |
zapadapter | Package zapadapter provides a logger that writes to a go.uber.org/zap.Logger. |
zerologadapter | Package zerologadapter provides a logger that writes to a github.com/rs/zerolog. |
pgxpool | Package pgxpool is a concurrency-safe connection pool for pgx. |
stdlib | Package stdlib is the compatibility layer from pgx to database/sql. |