func NetworkAddress(host string, port uint16) (network, address string)
NetworkAddress converts a PostgreSQL host and port into network and address suitable for use with net.Dial.
func RegisterGSSProvider(newGSSArg NewGSSFunc)
RegisterGSSProvider registers a GSS authentication provider. For example, if you need to use Kerberos to authenticate with your server, add this to your main package:
import "github.com/otan/gopgkrb5" func init() { pgconn.RegisterGSSProvider(func() (pgconn.GSS, error) { return gopgkrb5.NewGSS() }) }
func SafeToRetry(err error) bool
SafeToRetry checks if the err is guaranteed to have occurred before sending any data to the server.
func Timeout(err error) bool
Timeout checks if err was was caused by a timeout. To be specific, it is true if err was caused within pgconn by a context.DeadlineExceeded or an implementer of net.Error where Timeout() is true.
func ValidateConnectTargetSessionAttrsPreferStandby(ctx context.Context, pgConn *PgConn) error
ValidateConnectTargetSessionAttrsPreferStandby is a ValidateConnectFunc that implements libpq compatible target_session_attrs=prefer-standby.
func ValidateConnectTargetSessionAttrsPrimary(ctx context.Context, pgConn *PgConn) error
ValidateConnectTargetSessionAttrsPrimary is a ValidateConnectFunc that implements libpq compatible target_session_attrs=primary.
func ValidateConnectTargetSessionAttrsReadOnly(ctx context.Context, pgConn *PgConn) error
ValidateConnectTargetSessionAttrsReadOnly is a ValidateConnectFunc that implements libpq compatible target_session_attrs=read-only.
func ValidateConnectTargetSessionAttrsReadWrite(ctx context.Context, pgConn *PgConn) error
ValidateConnectTargetSessionAttrsReadWrite is a ValidateConnectFunc that implements libpq compatible target_session_attrs=read-write.
func ValidateConnectTargetSessionAttrsStandby(ctx context.Context, pgConn *PgConn) error
ValidateConnectTargetSessionAttrsStandby is a ValidateConnectFunc that implements libpq compatible target_session_attrs=standby.
type AfterConnectFunc func(ctx context.Context, pgconn *PgConn) error
Batch is a collection of queries that can be sent to the PostgreSQL server in a single round-trip.
type Batch struct {
// contains filtered or unexported fields
}
func (batch *Batch) ExecParams(sql string, paramValues [][]byte, paramOIDs []uint32, paramFormats []int16, resultFormats []int16)
ExecParams appends an ExecParams command to the batch. See PgConn.ExecParams for parameter descriptions.
func (batch *Batch) ExecPrepared(stmtName string, paramValues [][]byte, paramFormats []int16, resultFormats []int16)
ExecPrepared appends an ExecPrepared e command to the batch. See PgConn.ExecPrepared for parameter descriptions.
BuildFrontendFunc is a function that can be used to create Frontend implementation for connection.
type BuildFrontendFunc func(r io.Reader, w io.Writer) *pgproto3.Frontend
CloseComplete is returned by GetResults when a CloseComplete message is received.
type CloseComplete struct{}
CommandTag is the status text returned by PostgreSQL for a query.
type CommandTag struct {
// contains filtered or unexported fields
}
func NewCommandTag(s string) CommandTag
NewCommandTag makes a CommandTag from s.
func (ct CommandTag) Delete() bool
Delete is true if the command tag starts with "DELETE".
func (ct CommandTag) Insert() bool
Insert is true if the command tag starts with "INSERT".
func (ct CommandTag) RowsAffected() int64
RowsAffected returns the number of rows affected. If the CommandTag was not for a row affecting command (e.g. "CREATE TABLE") then it returns 0.
func (ct CommandTag) Select() bool
Select is true if the command tag starts with "SELECT".
func (ct CommandTag) String() string
func (ct CommandTag) Update() bool
Update is true if the command tag starts with "UPDATE".
Config is the settings used to establish a connection to a PostgreSQL server. It must be created by ParseConfig. A manually initialized Config will cause ConnectConfig to panic.
type Config struct { Host string // host (e.g. localhost) or absolute path to unix domain socket directory (e.g. /private/tmp) Port uint16 Database string User string Password string TLSConfig *tls.Config // nil disables TLS ConnectTimeout time.Duration DialFunc DialFunc // e.g. net.Dialer.DialContext LookupFunc LookupFunc // e.g. net.Resolver.LookupHost BuildFrontend BuildFrontendFunc RuntimeParams map[string]string // Run-time parameters to set on connection as session default values (e.g. search_path or application_name) KerberosSrvName string KerberosSpn string Fallbacks []*FallbackConfig // 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. ValidateConnect ValidateConnectFunc // 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. AfterConnect AfterConnectFunc // OnNotice is a callback function called when a notice response is received. OnNotice NoticeHandler // OnNotification is a callback function called when a notification from the LISTEN/NOTIFY system is received. OnNotification NotificationHandler // OnPgError is a callback function called when a Postgres error is received by the server. The default handler will close // the connection on any FATAL errors. If you override this handler you should call the previously set handler or ensure // that you close on FATAL errors by returning false. OnPgError PgErrorHandler // contains filtered or unexported fields }
func ParseConfig(connString string) (*Config, error)
ParseConfig builds a *Config from connString with similar behavior to the PostgreSQL standard C library libpq. It uses the same defaults as libpq (e.g. port=5432) and understands most PG* environment variables. ParseConfig closely matches the parsing behavior of libpq. connString may either be in URL format or keyword = value format (DSN style). See https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING for details. connString also may be empty to only read from the environment. If a password is not supplied it will attempt to read the .pgpass file.
# Example DSN user=jack password=secret host=pg.example.com port=5432 dbname=mydb sslmode=verify-ca # Example URL postgres://jack:secret@pg.example.com:5432/mydb?sslmode=verify-ca
The returned *Config may be modified. However, it is strongly recommended that any configuration that can be done through the connection string be done there. In particular the fields Host, Port, TLSConfig, and Fallbacks can be interdependent (e.g. TLSConfig needs knowledge of the host to validate the server certificate). These fields should not be modified individually. They should all be modified or all left unchanged.
ParseConfig supports specifying multiple hosts in similar manner to libpq. Host and port may include comma separated values that will be tried in order. This can be used as part of a high availability system. See https://www.postgresql.org/docs/11/libpq-connect.html#LIBPQ-MULTIPLE-HOSTS for more information.
# Example URL postgres://jack:secret@foo.example.com:5432,bar.example.com:5432/mydb
ParseConfig currently recognizes the following environment variable and their parameter key word equivalents passed via database URL or DSN:
PGHOST PGPORT PGDATABASE PGUSER PGPASSWORD PGPASSFILE PGSERVICE PGSERVICEFILE PGSSLMODE PGSSLCERT PGSSLKEY PGSSLROOTCERT PGSSLPASSWORD PGAPPNAME PGCONNECT_TIMEOUT PGTARGETSESSIONATTRS
See http://www.postgresql.org/docs/11/static/libpq-envars.html for details on the meaning of environment variables.
See https://www.postgresql.org/docs/11/libpq-connect.html#LIBPQ-PARAMKEYWORDS for parameter key word names. They are usually but not always the environment variable name downcased and without the "PG" prefix.
Important Security Notes:
ParseConfig tries to match libpq behavior with regard to PGSSLMODE. This includes defaulting to "prefer" behavior if not set.
See http://www.postgresql.org/docs/11/static/libpq-ssl.html#LIBPQ-SSL-PROTECTION for details on what level of security each sslmode provides.
The sslmode "prefer" (the default), sslmode "allow", and multiple hosts are implemented via the Fallbacks field of the Config struct. If TLSConfig is manually changed it will not affect the fallbacks. For example, in the case of sslmode "prefer" this means it will first try the main Config settings which use TLS, then it will try the fallback which does not use TLS. This can lead to an unexpected unencrypted connection if the main TLS config is manually changed later but the unencrypted fallback is present. Ensure there are no stale fallbacks when manually setting TLSConfig.
Other known differences with libpq:
When multiple hosts are specified, libpq allows them to have different passwords set via the .pgpass file. pgconn does not.
In addition, ParseConfig accepts the following options:
func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Config, error)
ParseConfigWithOptions builds a *Config from connString and options with similar behavior to the PostgreSQL standard C library libpq. options contains settings that cannot be specified in a connString such as providing a function to get the SSL password.
func (c *Config) Copy() *Config
Copy returns a deep copy of the config that is safe to use and modify. The only exception is the TLSConfig field: according to the tls.Config docs it must not be modified after creation.
ConnectError is the error returned when a connection attempt fails.
type ConnectError struct { Config *Config // The configuration that was used in the connection attempt. // contains filtered or unexported fields }
func (e *ConnectError) Error() string
func (e *ConnectError) Unwrap() error
DialFunc is a function that can be used to connect to a PostgreSQL server.
type DialFunc func(ctx context.Context, network, addr string) (net.Conn, error)
FallbackConfig is additional settings to attempt a connection with when the primary Config fails to establish a network connection. It is used for TLS fallback such as sslmode=prefer and high availability (HA) connections.
type FallbackConfig struct { Host string // host (e.g. localhost) or path to unix domain socket directory (e.g. /private/tmp) Port uint16 TLSConfig *tls.Config // nil disables TLS }
type FieldDescription struct { Name string TableOID uint32 TableAttributeNumber uint16 DataTypeOID uint32 DataTypeSize int16 TypeModifier int32 Format int16 }
GSS provides GSSAPI authentication (e.g., Kerberos).
type GSS interface { GetInitToken(host string, service string) ([]byte, error) GetInitTokenFromSPN(spn string) ([]byte, error) Continue(inToken []byte) (done bool, outToken []byte, err error) }
type GetSSLPasswordFunc func(ctx context.Context) string
HijackedConn is the result of hijacking a connection.
Due to the necessary exposure of internal implementation details, it is not covered by the semantic versioning compatibility.
type HijackedConn struct { Conn net.Conn PID uint32 // backend pid SecretKey uint32 // key to use to send a cancel query message to the server ParameterStatuses map[string]string // parameters that have been reported by the server TxStatus byte Frontend *pgproto3.Frontend Config *Config }
LookupFunc is a function that can be used to lookup IPs addrs from host. Optionally an ip:port combination can be returned in order to override the connection string's port.
type LookupFunc func(ctx context.Context, host string) (addrs []string, err error)
MultiResultReader is a reader for a command that could return multiple results such as Exec or ExecBatch.
type MultiResultReader struct {
// contains filtered or unexported fields
}
func (mrr *MultiResultReader) Close() error
Close closes the MultiResultReader and returns the first error that occurred during the MultiResultReader's use.
func (mrr *MultiResultReader) NextResult() bool
NextResult returns advances the MultiResultReader to the next result and returns true if a result is available.
func (mrr *MultiResultReader) ReadAll() ([]*Result, error)
ReadAll reads all available results. Calling ReadAll is mutually exclusive with all other MultiResultReader methods.
func (mrr *MultiResultReader) ResultReader() *ResultReader
ResultReader returns the current ResultReader.
NewGSSFunc creates a GSS authentication provider, for use with RegisterGSSProvider.
type NewGSSFunc func() (GSS, error)
type NotPreferredError struct {
// contains filtered or unexported fields
}
func (e *NotPreferredError) Error() string
func (e *NotPreferredError) SafeToRetry() bool
func (e *NotPreferredError) Unwrap() error
Notice represents a notice response message reported by the PostgreSQL server. Be aware that this is distinct from LISTEN/NOTIFY notification.
type Notice PgError
NoticeHandler is a function that can handle notices received from the PostgreSQL server. Notices can be received at any time, usually during handling of a query response. The *PgConn is provided so the handler is aware of the origin of the notice, but it must not invoke any query method. Be aware that this is distinct from LISTEN/NOTIFY notification.
type NoticeHandler func(*PgConn, *Notice)
Notification is a message received from the PostgreSQL LISTEN/NOTIFY system
type Notification struct { PID uint32 // backend pid that sent the notification Channel string // channel from which notification was received Payload string }
NotificationHandler is a function that can handle notifications received from the PostgreSQL server. Notifications can be received at any time, usually during handling of a query response. The *PgConn is provided so the handler is aware of the origin of the notice, but it must not invoke any query method. Be aware that this is distinct from a notice event.
type NotificationHandler func(*PgConn, *Notification)
ParseConfigError is the error returned when a connection string cannot be parsed.
type ParseConfigError struct { ConnString string // The connection string that could not be parsed. // contains filtered or unexported fields }
func (e *ParseConfigError) Error() string
func (e *ParseConfigError) Unwrap() error
ParseConfigOptions contains options that control how a config is built such as GetSSLPassword.
type ParseConfigOptions struct { // GetSSLPassword gets the password to decrypt a SSL client certificate. This is analogous to the the libpq function // PQsetSSLKeyPassHook_OpenSSL. GetSSLPassword GetSSLPasswordFunc }
PgConn is a low-level PostgreSQL connection handle. It is not safe for concurrent usage.
type PgConn struct {
// contains filtered or unexported fields
}
func Connect(ctx context.Context, connString string) (*PgConn, error)
Connect establishes a connection to a PostgreSQL server using the environment and connString (in URL or DSN format) to provide configuration. See documentation for ParseConfig for details. ctx can be used to cancel a connect attempt.
func ConnectConfig(octx context.Context, config *Config) (pgConn *PgConn, err error)
Connect establishes a connection to a PostgreSQL server using config. config must have been constructed with ParseConfig. ctx can be used to cancel a connect attempt.
If config.Fallbacks are present they will sequentially be tried in case of error establishing network connection. An authentication error will terminate the chain of attempts (like libpq: https://www.postgresql.org/docs/11/libpq-connect.html#LIBPQ-MULTIPLE-HOSTS) and be returned as the error. Otherwise, if all attempts fail the last error is returned.
func ConnectWithOptions(ctx context.Context, connString string, parseConfigOptions ParseConfigOptions) (*PgConn, error)
Connect establishes a connection to a PostgreSQL server using the environment and connString (in URL or DSN format) and ParseConfigOptions to provide additional configuration. See documentation for ParseConfig for details. ctx can be used to cancel a connect attempt.
func Construct(hc *HijackedConn) (*PgConn, error)
Construct created a PgConn from an already established connection to a PostgreSQL server. This is the inverse of PgConn.Hijack. The connection must be in an idle state.
hc.Frontend is replaced by a new pgproto3.Frontend built by hc.Config.BuildFrontend.
Due to the necessary exposure of internal implementation details, it is not covered by the semantic versioning compatibility.
func (pgConn *PgConn) CancelRequest(ctx context.Context) error
CancelRequest sends a cancel request to the PostgreSQL server. It returns an error if unable to deliver the cancel request, but lack of an error does not ensure that the query was canceled. As specified in the documentation, there is no way to be sure a query was canceled. See https://www.postgresql.org/docs/11/protocol-flow.html#id-1.10.5.7.9
func (pgConn *PgConn) CheckConn() error
CheckConn checks the underlying connection without writing any bytes. This is currently implemented by doing a read with a very short deadline. This can be useful because a TCP connection can be broken such that a write will appear to succeed even though it will never actually reach the server. Reading immediately before a write will detect this condition. If this is done immediately before sending a query it reduces the chances a query will be sent that fails without the client knowing whether the server received it or not.
Deprecated: CheckConn is deprecated in favor of Ping. CheckConn cannot detect all types of broken connections where the write would still appear to succeed. Prefer Ping unless on a high latency connection.
func (pgConn *PgConn) CleanupDone() chan (struct{})
CleanupDone returns a channel that will be closed after all underlying resources have been cleaned up. A closed connection is no longer usable, but underlying resources, in particular the net.Conn, may not have finished closing yet. This is because certain errors such as a context cancellation require that the interrupted function call return immediately, but the error may also cause the connection to be closed. In these cases the underlying resources are closed asynchronously.
This is only likely to be useful to connection pools. It gives them a way avoid establishing a new connection while an old connection is still being cleaned up and thereby exceeding the maximum pool size.
func (pgConn *PgConn) Close(ctx context.Context) error
Close closes a connection. It is safe to call Close on an already closed connection. Close attempts a clean close by sending the exit message to PostgreSQL. However, this could block so ctx is available to limit the time to wait. The underlying net.Conn.Close() will always be called regardless of any other errors.
func (pgConn *PgConn) Conn() net.Conn
Conn returns the underlying net.Conn. This rarely necessary. If the connection will be directly used for reading or writing then SyncConn should usually be called before Conn.
func (pgConn *PgConn) CopyFrom(ctx context.Context, r io.Reader, sql string) (CommandTag, error)
CopyFrom executes the copy command sql and copies all of r to the PostgreSQL server.
Note: context cancellation will only interrupt operations on the underlying PostgreSQL network connection. Reads on r could still block.
func (pgConn *PgConn) CopyTo(ctx context.Context, w io.Writer, sql string) (CommandTag, error)
CopyTo executes the copy command sql and copies the results to w.
func (pgConn *PgConn) Deallocate(ctx context.Context, name string) error
Deallocate deallocates a prepared statement.
Deallocate does not send a DEALLOCATE statement to the server. It uses the PostgreSQL Close protocol message directly. This has slightly different behavior than executing DEALLOCATE statement.
func (pgConn *PgConn) EscapeString(s string) (string, error)
EscapeString escapes a string such that it can safely be interpolated into a SQL command string. It does not include the surrounding single quotes.
The current implementation requires that standard_conforming_strings=on and client_encoding="UTF8". If these conditions are not met an error will be returned. It is possible these restrictions will be lifted in the future.
func (pgConn *PgConn) Exec(ctx context.Context, sql string) *MultiResultReader
Exec executes SQL via the PostgreSQL simple query protocol. SQL may contain multiple queries. Execution is implicitly wrapped in a transaction unless a transaction is already in progress or SQL contains transaction control statements.
Prefer ExecParams unless executing arbitrary SQL that may contain multiple queries.
func (pgConn *PgConn) ExecBatch(ctx context.Context, batch *Batch) *MultiResultReader
ExecBatch executes all the queries in batch in a single round-trip. Execution is implicitly transactional unless a transaction is already in progress or SQL contains transaction control statements. This is a simpler way of executing multiple queries in a single round trip than using pipeline mode.
func (pgConn *PgConn) ExecParams(ctx context.Context, sql string, paramValues [][]byte, paramOIDs []uint32, paramFormats []int16, resultFormats []int16) *ResultReader
ExecParams executes a command via the PostgreSQL extended query protocol.
sql is a SQL command string. It may only contain one query. Parameter substitution is positional using $1, $2, $3, etc.
paramValues are the parameter values. It must be encoded in the format given by paramFormats.
paramOIDs is a slice of data type OIDs for paramValues. If paramOIDs is nil, the server will infer the data type for all parameters. Any paramOID element that is 0 that will cause the server to infer the data type for that parameter. ExecParams will panic if len(paramOIDs) is not 0, 1, or len(paramValues).
paramFormats is a slice of format codes determining for each paramValue column whether it is encoded in text or binary format. If paramFormats is nil all params are text format. ExecParams will panic if len(paramFormats) is not 0, 1, or len(paramValues).
resultFormats is a slice of format codes determining for each result column whether it is encoded in text or binary format. If resultFormats is nil all results will be in text format.
ResultReader must be closed before PgConn can be used again.
func (pgConn *PgConn) ExecPrepared(ctx context.Context, stmtName string, paramValues [][]byte, paramFormats []int16, resultFormats []int16) *ResultReader
ExecPrepared enqueues the execution of a prepared statement via the PostgreSQL extended query protocol.
paramValues are the parameter values. It must be encoded in the format given by paramFormats.
paramFormats is a slice of format codes determining for each paramValue column whether it is encoded in text or binary format. If paramFormats is nil all params are text format. ExecPrepared will panic if len(paramFormats) is not 0, 1, or len(paramValues).
resultFormats is a slice of format codes determining for each result column whether it is encoded in text or binary format. If resultFormats is nil all results will be in text format.
ResultReader must be closed before PgConn can be used again.
func (pgConn *PgConn) Frontend() *pgproto3.Frontend
Frontend returns the underlying *pgproto3.Frontend. This rarely necessary.
func (pgConn *PgConn) Hijack() (*HijackedConn, error)
Hijack extracts the internal connection data. pgConn must be in an idle state. SyncConn should be called immediately before Hijack. pgConn is unusable after hijacking. Hijacking is typically only useful when using pgconn to establish a connection, but taking complete control of the raw connection after that (e.g. a load balancer or proxy).
Due to the necessary exposure of internal implementation details, it is not covered by the semantic versioning compatibility.
func (pgConn *PgConn) IsBusy() bool
IsBusy reports if the connection is busy.
func (pgConn *PgConn) IsClosed() bool
IsClosed reports if the connection has been closed.
CleanupDone() can be used to determine if all cleanup has been completed.
func (pgConn *PgConn) PID() uint32
PID returns the backend PID.
func (pgConn *PgConn) ParameterStatus(key string) string
ParameterStatus returns the value of a parameter reported by the server (e.g. server_version). Returns an empty string for unknown parameters.
func (pgConn *PgConn) Ping(ctx context.Context) error
Ping pings the server. This can be useful because a TCP connection can be broken such that a write will appear to succeed even though it will never actually reach the server. Pinging immediately before sending a query reduces the chances a query will be sent that fails without the client knowing whether the server received it or not.
func (pgConn *PgConn) Prepare(ctx context.Context, name, sql string, paramOIDs []uint32) (*StatementDescription, error)
Prepare creates a prepared statement. If the name is empty, the anonymous prepared statement will be used. This allows Prepare to also to describe statements without creating a server-side prepared statement.
Prepare does not send a PREPARE statement to the server. It uses the PostgreSQL Parse and Describe protocol messages directly.
func (pgConn *PgConn) ReceiveMessage(ctx context.Context) (pgproto3.BackendMessage, error)
ReceiveMessage receives one wire protocol message from the PostgreSQL server. It must only be used when the connection is not busy. e.g. It is an error to call ReceiveMessage while reading the result of a query. The messages are still handled by the core pgconn message handling system so receiving a NotificationResponse will still trigger the OnNotification callback.
This is a very low level method that requires deep understanding of the PostgreSQL wire protocol to use correctly. See https://www.postgresql.org/docs/current/protocol.html.
func (pgConn *PgConn) SecretKey() uint32
SecretKey returns the backend secret key used to send a cancel query message to the server.
func (pgConn *PgConn) StartPipeline(ctx context.Context) *Pipeline
StartPipeline switches the connection to pipeline mode and returns a *Pipeline. In pipeline mode requests can be sent to the server without waiting for a response. Close must be called on the returned *Pipeline to return the connection to normal mode. While in pipeline mode, no methods that communicate with the server may be called except CancelRequest and Close. ctx is in effect for entire life of the *Pipeline.
Prefer ExecBatch when only sending one group of queries at once.
func (pgConn *PgConn) SyncConn(ctx context.Context) error
SyncConn prepares the underlying net.Conn for direct use. PgConn may internally buffer reads or use goroutines for background IO. This means that any direct use of the underlying net.Conn may be corrupted if a read is already buffered or a read is in progress. SyncConn drains read buffers and stops background IO. In some cases this may require sending a ping to the server. ctx can be used to cancel this operation. This should be called before any operation that will use the underlying net.Conn directly. e.g. Before Conn() or Hijack().
This should not be confused with the PostgreSQL protocol Sync message.
func (pgConn *PgConn) TxStatus() byte
TxStatus returns the current TxStatus as reported by the server in the ReadyForQuery message.
Possible return values:
'I' - idle / not in transaction 'T' - in a transaction 'E' - in a failed transaction
See https://www.postgresql.org/docs/current/protocol-message-formats.html.
func (pgConn *PgConn) WaitForNotification(ctx context.Context) error
WaitForNotification waits for a LISTEN/NOTIFY message to be received. It returns an error if a notification was not received.
PgError represents an error reported by the PostgreSQL server. See http://www.postgresql.org/docs/11/static/protocol-error-fields.html for detailed field description.
type PgError struct { Severity string Code string Message string Detail string Hint string Position int32 InternalPosition int32 InternalQuery string Where string SchemaName string TableName string ColumnName string DataTypeName string ConstraintName string File string Line int32 Routine string }
func ErrorResponseToPgError(msg *pgproto3.ErrorResponse) *PgError
ErrorResponseToPgError converts a wire protocol error message to a *PgError.
func (pe *PgError) Error() string
func (pe *PgError) SQLState() string
SQLState returns the SQLState of the error.
PgErrorHandler is a function that handles errors returned from Postgres. This function must return true to keep the connection open. Returning false will cause the connection to be closed immediately. You should return false on any FATAL-severity errors. This will not receive network errors. The *PgConn is provided so the handler is aware of the origin of the error, but it must not invoke any query method.
type PgErrorHandler func(*PgConn, *PgError) bool
Pipeline represents a connection in pipeline mode.
SendPrepare, SendQueryParams, and SendQueryPrepared queue requests to the server. These requests are not written until pipeline is flushed by Flush or Sync. Sync must be called after the last request is queued. Requests between synchronization points are implicitly transactional unless explicit transaction control statements have been issued.
The context the pipeline was started with is in effect for the entire life of the Pipeline.
For a deeper understanding of pipeline mode see the PostgreSQL documentation for the extended query protocol (https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY) and the libpq pipeline mode (https://www.postgresql.org/docs/current/libpq-pipeline-mode.html).
type Pipeline struct {
// contains filtered or unexported fields
}
func (p *Pipeline) Close() error
Close closes the pipeline and returns the connection to normal mode.
func (p *Pipeline) Flush() error
Flush flushes the queued requests without establishing a synchronization point.
func (p *Pipeline) GetResults() (results any, err error)
GetResults gets the next results. If results are present, results may be a *ResultReader, *StatementDescription, or *PipelineSync. If an ErrorResponse is received from the server, results will be nil and err will be a *PgError. If no results are available, results and err will both be nil.
func (p *Pipeline) SendDeallocate(name string)
SendDeallocate deallocates a prepared statement.
func (p *Pipeline) SendPrepare(name, sql string, paramOIDs []uint32)
SendPrepare is the pipeline version of *PgConn.Prepare.
func (p *Pipeline) SendQueryParams(sql string, paramValues [][]byte, paramOIDs []uint32, paramFormats []int16, resultFormats []int16)
SendQueryParams is the pipeline version of *PgConn.QueryParams.
func (p *Pipeline) SendQueryPrepared(stmtName string, paramValues [][]byte, paramFormats []int16, resultFormats []int16)
SendQueryPrepared is the pipeline version of *PgConn.QueryPrepared.
func (p *Pipeline) Sync() error
Sync establishes a synchronization point and flushes the queued requests.
PipelineSync is returned by GetResults when a ReadyForQuery message is received.
type PipelineSync struct{}
Result is the saved query response that is returned by calling Read on a ResultReader.
type Result struct { FieldDescriptions []FieldDescription Rows [][][]byte CommandTag CommandTag Err error }
ResultReader is a reader for the result of a single query.
type ResultReader struct {
// contains filtered or unexported fields
}
func (rr *ResultReader) Close() (CommandTag, error)
Close consumes any remaining result data and returns the command tag or error.
func (rr *ResultReader) FieldDescriptions() []FieldDescription
FieldDescriptions returns the field descriptions for the current result set. The returned slice is only valid until the ResultReader is closed. It may return nil (for example, if the query did not return a result set or an error was encountered.)
func (rr *ResultReader) NextRow() bool
NextRow advances the ResultReader to the next row and returns true if a row is available.
func (rr *ResultReader) Read() *Result
Read saves the query response to a Result.
func (rr *ResultReader) Values() [][]byte
Values returns the current row data. NextRow must have been previously been called. The returned [][]byte is only valid until the next NextRow call or the ResultReader is closed.
type StatementDescription struct { Name string SQL string ParamOIDs []uint32 Fields []FieldDescription }
type ValidateConnectFunc func(ctx context.Context, pgconn *PgConn) error
Name | Synopsis |
---|---|
.. |