Involved Source Filesauth_oauth.goauth_scram.goconfig.godefaults.go Package pgconn is a low-level PostgreSQL database driver.
pgconn provides lower level access to a PostgreSQL connection than a database/sql or pgx connection. It operates at
nearly the same level is the C library libpq.
Establishing a Connection
Use Connect to establish a connection. It accepts a connection string in URL or keyword/value format and will read the
environment for libpq style environment variables.
Connecting Securely
By default ParseConfig matches libpq and uses sslmode=prefer, which silently falls back to an unencrypted connection
if the server does not offer TLS. For connections that traverse an untrusted network, set the following parameters
explicitly:
# URL form
postgres://user@db.example.com/mydb?sslmode=verify-full&sslrootcert=/path/to/root.crt&channel_binding=require&require_auth=scram-sha-256
# keyword/value form
host=db.example.com user=user dbname=mydb sslmode=verify-full sslrootcert=/path/to/root.crt channel_binding=require require_auth=scram-sha-256
sslmode=verify-full Require TLS, verify the server certificate against sslrootcert, and verify that the
certificate's host name matches the host being connected to. Weaker modes (disable,
allow, prefer, require) either permit plaintext fallback or skip certificate
verification, allowing a network attacker to impersonate the server.
channel_binding=require Require SCRAM-SHA-256-PLUS, which binds the authentication exchange to the TLS channel
so that a TLS-terminating intermediary cannot relay credentials to the real server.
require_auth=scram-sha-256
Refuse to respond to AuthenticationCleartextPassword or AuthenticationMD5Password
requests from the server. Without this, a server (or interceptor) can request the
password in cleartext and the client will send it.
These parameters may also be set via the PGSSLMODE, PGSSLROOTCERT, PGCHANNELBINDING, and PGREQUIREAUTH environment
variables.
Client Certificates
The sslcertmode connection parameter (or PGSSLCERTMODE environment variable) controls whether a client certificate
is sent. The default, allow, sends a certificate if the server requests one and a suitable certificate is available.
The disable mode prevents sending a certificate, including certificates supplied through Config.TLSConfig, and skips
loading sslcert and sslkey files. The require mode fails if the server successfully authenticates the client without
requesting and receiving a client certificate. It does not guarantee that the server validated the certificate.
If this check fails, no further TLS or host fallbacks are tried.
TLS session resumption is disabled in require mode so every connection exchanges a certificate.
An explicitly empty sslcertmode parameter or PGSSLCERTMODE environment variable is invalid.
This parameter is independent of sslmode, which controls TLS and server certificate verification.
Executing a Query
ExecParams and ExecPrepared execute a single query. They return readers that iterate over each row. The Read method
reads all rows into memory.
Executing Multiple Queries in a Single Round Trip
Exec and ExecBatch can execute multiple queries in a single round trip. They return readers that iterate over each query
result. The ReadAll method reads all query results into memory.
Pipeline Mode
Pipeline mode allows sending queries without having read the results of previously sent queries. It allows control of
exactly how many and when network round trips occur.
Context Support
All potentially blocking operations take a context.Context. The default behavior when a context is canceled is for the
method to immediately return. In most circumstances, this will also close the underlying connection. This behavior can
be customized by using BuildContextWatcherHandler on the Config to create a ctxwatch.Handler with different behavior.
This can be especially useful when queries that are frequently canceled and the overhead of creating new connections is
a problem. DeadlineContextWatcherHandler and CancelRequestContextWatcherHandler can be used to introduce a delay before
interrupting the query in such a way as to close the connection.
The CancelRequest method may be used to request the PostgreSQL server cancel an in-progress query without forcing the
client to abort.errors.gokrb5.goparse_url.gopgconn.gorequire_auth.gosaslprep_unassigned.go
Package-Level Type Names (total 50, in which 35 are exported)
Batch is a collection of queries that can be sent to the PostgreSQL server in a single round-trip.buf[]byteerrerrorresultFormats[][]int16statementDescriptions[]*StatementDescription ExecParams appends an ExecParams command to the batch. See PgConn.ExecParams for parameter descriptions. ExecPrepared appends an ExecPrepared e command to the batch. See PgConn.ExecPrepared for parameter descriptions. ExecStatement appends an ExecStatement command to the batch. See PgConn.ExecPrepared for parameter descriptions.
This differs from ExecPrepared in that it takes a *StatementDescription instead of just the prepared statement name.
Because it has the *StatementDescription it can avoid the Describe Portal message that ExecPrepared must send to get
the result column descriptions. However, if the statement description has no fields then a Describe is still sent, as
an empty Fields may mean the results were not knowable at prepare time, e.g. a FETCH from a cursor that did not exist
yet.
func (*PgConn).ExecBatch(ctx context.Context, batch *Batch) *MultiResultReader
BuildFrontendFunc is a function that can be used to create Frontend implementation for connection.
CancelRequestContextWatcherHandler handles canceled contexts by sending a cancel request to the server. It also sets
a deadline on a net.Conn as a fallback. CancelRequestDelay is the delay before sending the cancel request to the server.Conn*PgConn DeadlineDelay is the delay to set on the deadline set on net.Conn when the context is canceled.cancelFinishedChanchan struct{}handleUnwatchAfterCancelCalledfunc()(*CancelRequestContextWatcherHandler) HandleCancel(context.Context)(*CancelRequestContextWatcherHandler) HandleUnwatchAfterCancel()
*CancelRequestContextWatcherHandler : github.com/jackc/pgx/v5/pgconn/ctxwatch.Handler
CloseComplete is returned by GetResults when a CloseComplete message is received.
func (*Pipeline).getResultsDeallocate() (*CloseComplete, error)
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. 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. AfterNetConnect is called after the network connection, including TLS if applicable, is established but before any
PostgreSQL protocol communication. It takes the established net.Conn and returns a net.Conn that will be used in
its place. It can be used to wrap the net.Conn (e.g. for logging, diagnostics, or testing). Its functionality has
some overlap with DialFunc. However, DialFunc takes place before TLS is established and cannot be used to control
the final net.Conn used for PostgreSQL protocol communication while AfterNetConnect can. BuildContextWatcherHandler is called to create a ContextWatcherHandler for a connection. The handler is called
when a context passed to a PgConn method is canceled.BuildFrontendBuildFrontendFunc ChannelBinding is the channel_binding parameter for SCRAM-SHA-256-PLUS authentication.
Valid values: "disable", "prefer", "require". Defaults to "prefer".ConnectTimeouttime.DurationDatabasestring // e.g. net.Dialer.DialContextFallbacks[]*FallbackConfig // host (e.g. localhost) or absolute path to unix domain socket directory (e.g. /private/tmp)KerberosSpnstringKerberosSrvNamestring // e.g. net.Resolver.LookupHost MaxProtocolMessageBodyLen is the maximum length of a PostgreSQL wire protocol message body in octets. If a
message body exceeds this length, reading the message will fail with pgproto3.ExceededMaxBodyLenErr. The default
value is 0, which means no maximum is enforced. MaxProtocolVersion is the maximum PostgreSQL protocol version to request from the server.
Valid values: "3.0", "3.2", "latest". Defaults to "3.0" for compatibility. MinProtocolVersion is the minimum acceptable PostgreSQL protocol version.
If the server does not support at least this version, the connection will fail.
Valid values: "3.0", "3.2", "latest". Defaults to "3.0". OAuthTokenProvider is a function that returns an OAuth token for authentication. If set, it will be used for
OAUTHBEARER SASL authentication when the server requests it. 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. 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.PasswordstringPortuint16 RequireAuth restricts which authentication methods the client will accept from the server,
matching libpq's require_auth parameter. It is a comma-separated list of method names
(password, md5, gss, sspi, scram-sha-256, oauth, none). A leading "!" on every entry negates
the list (forbid these methods, allow all others). Empty (the default) means all methods are
accepted. // Run-time parameters to set on connection as session default values (e.g. search_path or application_name) SSLCertMode controls client certificate usage. Valid values are "disable", "allow", and "require".
The default is "allow"; an empty field is also treated as "allow".
"disable" prevents sending a certificate, even if TLSConfig supplies one.
"require" rejects successful authentication unless the server requested and the client sent a certificate.
TLS session resumption is disabled in "require" mode so that every connection exchanges a certificate.
It does not guarantee that the server validated the certificate. // sslnegotiation=postgres or sslnegotiation=direct // nil disables TLSUserstring 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. // Used to enforce created by ParseConfig rule. 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.
func ParseConfig(connString string) (*Config, error)
func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Config, error)
func (*Config).Copy() *Config
func ConnectConfig(ctx context.Context, config *Config) (*PgConn, error)
func buildConnectOneConfigs(ctx context.Context, config *Config) ([]*connectOneConfig, []error)
func connectOne(ctx context.Context, config *Config, connectConfig *connectOneConfig, ignoreNotPreferredErr bool) (*PgConn, error)
func connectPreferred(ctx context.Context, config *Config, connectOneConfigs []*connectOneConfig) (*PgConn, []error)
ConnectError is the error returned when a connection attempt fails. // The configuration that was used in the connection attempt.errerror(*ConnectError) Error() string(*ConnectError) Unwrap() error
*ConnectError : error
DeadlineContextWatcherHandler handles canceled contexts by setting a deadline on a net.Conn.Connnet.Conn DeadlineDelay is the delay to set on the deadline set on net.Conn when the context is canceled.(*DeadlineContextWatcherHandler) HandleCancel(ctx context.Context)(*DeadlineContextWatcherHandler) HandleUnwatchAfterCancel()
*DeadlineContextWatcherHandler : github.com/jackc/pgx/v5/pgconn/ctxwatch.Handler
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. // host (e.g. localhost) or path to unix domain socket directory (e.g. /private/tmp)Portuint16 // nil disables TLS
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.Config*ConfigConnnet.ConnCustomDatamap[string]anyFrontend*pgproto3.Frontend // backend pid // parameters that have been reported by the server // key to use to send a cancel query message to the server // tls.Config that Conn was negotiated with; nil if Conn is not TLSTxStatusbyte
func (*PgConn).Hijack() (*HijackedConn, error)
func Construct(hc *HijackedConn) (*PgConn, error)
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.
MultiResultReader is a reader for a command that could return multiple results such as Exec or ExecBatch.closedboolctxcontext.ContextcurrentResultFormats[]int16 Statement data for the command currently being processed. Popped from the queues above at each BindComplete.errerrorpgConn*PgConnresultFormats[][]int16rr*ResultReader Data from when the batch was queued. There is one entry per command in the batch. Entries are nil for commands
other than Batch.ExecStatement, which is the only command that does not request a RowDescription from the server. Close closes the MultiResultReader and returns the first error that occurred during the MultiResultReader's use. NextResult returns advances the MultiResultReader to the next result and returns true if a result is available. ReadAll reads all available results. Calling ReadAll is mutually exclusive with all other MultiResultReader methods. ResultReader returns the current ResultReader.(*MultiResultReader) receiveMessage() (pgproto3.BackendMessage, error)
*MultiResultReader : io.Closer
func (*PgConn).Exec(ctx context.Context, sql string) *MultiResultReader
func (*PgConn).ExecBatch(ctx context.Context, batch *Batch) *MultiResultReader
NewGSSFunc creates a GSS authentication provider, for use with
RegisterGSSProvider.
func RegisterGSSProvider(newGSSArg NewGSSFunc)
var newGSS
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.
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.
ParseConfigError is the error returned when a connection string cannot be
parsed. Its error text masks recognizable passwords on a best-effort basis,
but malformed input can be too ambiguous to redact completely. // The original, unredacted connection string that could not be parsed.errerrormsgstring(*ParseConfigError) Error() string(*ParseConfigError) Unwrap() error
*ParseConfigError : error
ParseConfigOptions contains options that control how a config is built such as GetSSLPassword. ConnStringAllowedKeys, if non-nil, restricts which parameter keys may appear in connString
itself. Any other key (whether connString is in keyword/value or URL form) causes
ParseConfigWithOptions to return an error before any filesystem access or network
resolution is attempted. Environment variables (PGHOST, PGSERVICEFILE, ...) and built-in
defaults are not checked: only keys that originate from the connString argument.
Keys may be given in either their libpq spelling ("dbname") or pgx-internal spelling
("database"); both are accepted. The URI-only ssl=true alias for sslmode=require is
accepted when either "ssl" or "sslmode" is allowed; an explicit sslmode key or a
non-"true" ssl value only matches its own spelling. Every ssl/sslmode occurrence in
the connection string is validated, including occurrences superseded by a later
repeated parameter.
A nil slice (the default) applies no restriction and matches libpq behaviour. An empty
non-nil slice rejects every key, i.e. connString must be empty.
Use this when any part of connString is built from input the application does not fully
control (tenant configuration, RPC parameters, admin UI fields). List only the keys that
input is expected to supply. This fails closed: a future libpq parameter that pgconn learns
to parse will be rejected unless the application has explicitly allowed it, rather than
silently passing through. GetSSLPassword gets the password to decrypt a SSL client certificate. This is analogous to the libpq function
PQsetSSLKeyPassHook_OpenSSL.
func ConnectWithOptions(ctx context.Context, connString string, parseConfigOptions ParseConfigOptions) (*PgConn, error)
func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Config, error)
func configTLS(settings map[string]string, thisHost string, parseConfigOptions ParseConfigOptions) ([]*tls.Config, error)
PgConn is a low-level PostgreSQL connection handle. It is not safe for concurrent usage.bgReader*bgreader.BGReaderbgReaderStartedchan struct{}bufferingReceiveboolbufferingReceiveErrerrorbufferingReceiveMsgpgproto3.BackendMessagebufferingReceiveMuxsync.MutexcleanupDonechan struct{}config*Configconnnet.ConncontextWatcher*ctxwatch.ContextWatchercustomDatamap[string]anyfieldDescriptions[16]FieldDescriptionfrontend*pgproto3.FrontendmultiResultReaderMultiResultReader // parameters that have been reported by the serverpeekedMsgpgproto3.BackendMessage // backend pidpipelinePipeline Reusable / preallocated resources // key to use to send a cancel query message to the serverslowWriteTimer*time.Timer // One of connStatus* constants // tls.Config that conn was negotiated with; nil if conn is not TLStxStatusbyte 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/current/protocol-flow.html#PROTOCOL-FLOW-CANCELING-REQUESTS 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. 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. 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. 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. 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. CopyTo executes the copy command sql and copies the results to w. CustomData returns a map that can be used to associate custom data with the connection. 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.
- Deallocate can succeed in an aborted transaction.
- Deallocating a non-existent prepared statement is not an 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. 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 [PgConn.ExecParams] unless executing arbitrary SQL that may contain multiple queries. 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. 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. 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. ExecStatement enqueues the execution of a prepared statement via the PostgreSQL extended query protocol.
This differs from [PgConn.ExecPrepared] in that it takes a [*StatementDescription] instead of the prepared statement name.
Because it has the [*StatementDescription] it can avoid the Describe Portal message that [PgConn.ExecPrepared] must send to get
the result column descriptions. However, if the statement description has no fields then a Describe is still sent, as
an empty Fields may mean the results were not knowable at prepare time, e.g. a FETCH from a cursor that did not exist
yet.
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. ExecStatement 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. Frontend returns the underlying *pgproto3.Frontend. This rarely necessary. 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. IsBusy reports if the connection is busy. IsClosed reports if the connection has been closed.
CleanupDone() can be used to determine if all cleanup has been completed. PID returns the backend PID. ParameterStatus returns the value of a parameter reported by the server (e.g.
server_version). Returns an empty string for unknown parameters. 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. 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.
In extremely rare cases, Prepare may fail after the Parse is successful, but before the Describe is complete. In this
case, the returned error will be an error where errors.As with a *PrepareError succeeds and the *PrepareError has
ParseComplete set to true. 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 [PgConn.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. SecretKey returns the backend secret key used to send a cancel query message to the server. 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. 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. 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. WaitForNotification waits for a LISTEN/NOTIFY message to be received. It returns an error if a notification was not
received. asyncClose marks the connection as closed and asynchronously sends a cancel query message and closes the underlying
connection. enterPotentialWriteReadDeadlock must be called before a write that could deadlock if the server is simultaneously
blocked writing to us.(*PgConn) execExtendedPrefix(ctx context.Context, paramValues [][]byte) *ResultReader(*PgConn) execExtendedSuffix(result *ResultReader, statementDescription *StatementDescription, resultFormats []int16) exitPotentialWriteReadDeadlock must be called after a call to enterPotentialWriteReadDeadlock.(*PgConn) flushWithPotentialWriteReadDeadlock() error(*PgConn) getFieldDescriptionSlice(n int) []FieldDescription(*PgConn) gssAuth() error lock locks the connection. makeCommandTag makes a CommandTag. It does not retain a reference to buf or buf's underlying memory.(*PgConn) oauthAuth(ctx context.Context) error peekMessage peeks at the next message without setting up context cancellation. receiveMessage receives a message without setting up context cancellation(*PgConn) rxGSSContinue() (*pgproto3.AuthenticationGSSContinue, error)(*PgConn) rxSASLContinue() (*pgproto3.AuthenticationSASLContinue, error)(*PgConn) rxSASLFinal() (*pgproto3.AuthenticationSASLFinal, error) Perform SCRAM authentication and report whether the completed exchange used
channel binding. A mechanism selection alone is not proof of authentication;
the server signature must be verified before returning channelBound=true.(*PgConn) signalMessage() chan struct{}(*PgConn) txPasswordMessage(password string) (err error)(*PgConn) unlock()
*PgConn : database/sql/driver.Pinger
func Connect(ctx context.Context, connString string) (*PgConn, error)
func ConnectConfig(ctx context.Context, config *Config) (*PgConn, error)
func ConnectWithOptions(ctx context.Context, connString string, parseConfigOptions ParseConfigOptions) (*PgConn, error)
func Construct(hc *HijackedConn) (*PgConn, error)
func github.com/jackc/pgx/v5.(*Conn).PgConn() *PgConn
func connectOne(ctx context.Context, config *Config, connectConfig *connectOneConfig, ignoreNotPreferredErr bool) (*PgConn, error)
func connectPreferred(ctx context.Context, config *Config, connectOneConfigs []*connectOneConfig) (*PgConn, []error)
func ValidateConnectTargetSessionAttrsPreferStandby(ctx context.Context, pgConn *PgConn) error
func ValidateConnectTargetSessionAttrsPrimary(ctx context.Context, pgConn *PgConn) error
func ValidateConnectTargetSessionAttrsReadOnly(ctx context.Context, pgConn *PgConn) error
func ValidateConnectTargetSessionAttrsReadWrite(ctx context.Context, pgConn *PgConn) error
func ValidateConnectTargetSessionAttrsStandby(ctx context.Context, pgConn *PgConn) error
func github.com/jackc/pgx/v5.(*Conn).bufferNotifications(_ *PgConn, n *Notification)
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.
Pipeline represents a connection in pipeline mode.
SendPrepare, SendQueryParams, SendQueryPrepared, and SendQueryStatement 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).closedboolconn*PgConnctxcontext.ContexterrerrorstatepipelineState Close closes the pipeline and returns the connection to normal mode. Flush flushes the queued requests without establishing a synchronization point. 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. SendDeallocate deallocates a prepared statement. SendFlushRequest sends a request for the server to flush its output buffer.
The server flushes its output buffer automatically as a result of Sync being called,
or on any request when not in pipeline mode; this function is useful to cause the server
to flush its output buffer in pipeline mode without establishing a synchronization point.
Note that the request is not itself flushed to the server automatically; use Flush if
necessary. This copies the behavior of libpq PQsendFlushRequest. SendPipelineSync marks a synchronization point in a pipeline by sending a sync message
without flushing the send buffer. This serves as the delimiter of an implicit
transaction and an error recovery point.
Note that the request is not itself flushed to the server automatically; use Flush if
necessary. This copies the behavior of libpq PQsendPipelineSync. SendPrepare is the pipeline version of *PgConn.Prepare. SendQueryParams is the pipeline version of *PgConn.ExecParams. SendQueryPrepared is the pipeline version of *PgConn.ExecPrepared. SendQueryStatement is the pipeline version of *PgConn.ExecStatement. Sync establishes a synchronization point and flushes the queued requests.(*Pipeline) getResults() (results any, err error)(*Pipeline) getResultsDeallocate() (*CloseComplete, error)(*Pipeline) getResultsPrepare() (*StatementDescription, error)(*Pipeline) getResultsQueryParams() (*ResultReader, error)(*Pipeline) getResultsQueryPrepared() (*ResultReader, error)(*Pipeline) getResultsQueryStatement() (*ResultReader, error)(*Pipeline) getResultsSync() (*PipelineSync, error)(*Pipeline) handleUnexpectedMessage(errStr string, msg pgproto3.BackendMessage) error(*Pipeline) receiveBindComplete(errStr string) error(*Pipeline) receiveDescribedResultReader(errStr string) (*ResultReader, error)(*Pipeline) receiveMessage() (pgproto3.BackendMessage, error)(*Pipeline) receiveParseComplete(errStr string) error
*Pipeline : io.Closer
func (*PgConn).StartPipeline(ctx context.Context) *Pipeline
PipelineSync is returned by GetResults when a ReadyForQuery message is received.
func (*Pipeline).getResultsSync() (*PipelineSync, error)
// Indicates whether the error occurred after a ParseComplete message was received.errerror(*PrepareError) Error() string(*PrepareError) Unwrap() error
*PrepareError : error
errTimeout occurs when an error was caused by a timeout. Specifically, it wraps an error which is
context.Canceled, context.DeadlineExceeded, or an implementer of net.Error where Timeout() is true.errerror(*errTimeout) Error() string(*errTimeout) SafeToRetry() bool(*errTimeout) Unwrap() error
*errTimeout : error
parseURLMeta reports provenance facts about a parsed URI that
ParseConfigWithOptions needs for ConnStringAllowedKeys validation and that
cannot be recovered from the settings map itself. impliedEmptyPortList: the "port" entry is an all-empty list synthesized
from the host list (postgres://h1,h2 yields port=",") with no port
bytes supplied by the user. Determined from the raw port syntax, not
the decoded value: a port of literal spaces (postgres://h: /db)
decodes to empty but was user-supplied. // key "sslmode" sawRawSSLKey / sawSSLTrueAlias / sawExplicitSSLModeKey record which
spellings of the ssl and sslmode query keys appeared anywhere in the
URI -- including occurrences later superseded under last-occurrence-
wins. The ssl=true alias rewrite and ordinary repeated-key handling can
remove those occurrences from the final settings map, so
ConnStringAllowedKeys cannot fail closed from that map alone; it must see
every key the user actually wrote. // key "ssl" with a value other than "true" // key "ssl" with value "true" (stored as sslmode=require)
func parseURLSettings(connString string) (settings map[string]string, meta parseURLMeta, err error)
func parseURLQueryParams(params string, settings map[string]string, meta *parseURLMeta) error
requireAuth is the parsed form of the require_auth connection parameter. It mirrors libpq's
auth_required / allowed_auth_methods bookkeeping (see fe-connect.c, conn->allowed_auth_methods). allowed is a bitmask of permitted authMethod values. authRequired is true when the server must complete an authentication exchange before sending
AuthenticationOk. It is false when the parameter is unset, fully negated, or "none" is in the
allowed set. raw is the original parameter value, used in error messages.( requireAuth) allows(m authMethod) bool check returns an error if method m is not permitted by the policy. The reason is phrased to
follow libpq's "authentication method requirement \"%s\" failed: %s" form so users migrating
from libpq see familiar diagnostics.
func parseRequireAuth(s string) (requireAuth, error)
sslCertModeError is a client-side authentication failure that must stop
connection fallback, matching libpq's sslcertmode=require behavior.msgstring(*sslCertModeError) Error() string
*sslCertModeError : error
Package-Level Functions (total 64, in which 18 are exported)
Connect establishes a connection to a PostgreSQL server using the environment and connString (in URL or keyword/value
format) to provide configuration. See documentation for [ParseConfig] for details. ctx can be used to cancel a
connect attempt.
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/current/libpq-connect.html#LIBPQ-MULTIPLE-HOSTS) and be returned as the error.
Connect establishes a connection to a PostgreSQL server using the environment and connString (in URL or keyword/value
format) and ParseConfigOptions to provide additional configuration. See documentation for [ParseConfig] for details.
ctx can be used to cancel a connect attempt.
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.
ErrorResponseToPgError converts a wire protocol error message to a *PgError.
NetworkAddress converts a PostgreSQL host and port into network and address suitable for use with
net.Dial.
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. 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 Keyword/Value
user=jack password=secret host=pg.example.com port=5432 dbname=mydb sslmode=verify-full
# Example URL
postgres://jack:secret@pg.example.com:5432/mydb?sslmode=verify-full
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/current/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 keyword/value:
PGHOST
PGPORT
PGDATABASE
PGUSER
PGPASSWORD
PGPASSFILE
PGSERVICE
PGSERVICEFILE
PGSSLMODE
PGSSLCERT
PGSSLKEY
PGSSLROOTCERT
PGSSLPASSWORD
PGOPTIONS
PGAPPNAME
PGCONNECT_TIMEOUT
PGTARGETSESSIONATTRS
PGTZ
PGMINPROTOCOLVERSION
PGMAXPROTOCOLVERSION
See http://www.postgresql.org/docs/current/static/libpq-envars.html for details on the meaning of environment variables.
See https://www.postgresql.org/docs/current/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/current/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.
Several connection parameters cause ParseConfig to read files from the local filesystem: servicefile, passfile,
sslkey, sslcert, and sslrootcert. Applications that build connection strings from untrusted input must not allow
these keys to be set by that input. In particular, servicefile (which pgconn accepts in the connection string;
libpq does not) is read as an INI file whose entries override other connection settings including host, port, and
sslmode, so an attacker who controls servicefile and service can redirect the connection. If any portion of the
connection string is externally supplied, use ParseConfigWithOptions and set ParseConfigOptions.ConnStringAllowedKeys
to an allow-list of the keys that input is expected to supply; any other key in the connection string is then
rejected before any filesystem access occurs.
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.
URL query parameters that libpq does not recognize cause libpq to fail with an "invalid URI query parameter" error.
ParseConfig accepts them: they become runtime parameters or pgx-specific options (e.g. pool_max_conns).
Connection strings containing a NUL byte are rejected, in both URI and keyword/value form. libpq cannot encounter
one because its conninfo strings are NUL-terminated C strings, but a Go string can carry a NUL into the startup
packet, where it delimits parameters rather than being data. Settings reaching Config by other routes (a service
file, or direct assignment to Config.RuntimeParams, User, or Database) are not checked here; a NUL in those is
caught when the startup message is encoded, and Connect fails rather than sending it.
Error messages from ParseConfig avoid quoting the unredacted connection string and attempt to redact recognizable
password fields, while libpq quotes the failing input verbatim. This redaction is best effort. An invalid connection
string can be structurally ambiguous, so pgconn cannot guarantee that every password in malformed input will be
identified or redacted. Applications should not assume that parse errors are safe to expose when connection strings
may contain secrets.
In addition, ParseConfig accepts the following options:
- servicefile.
libpq only reads servicefile from the PGSERVICEFILE environment variable. ParseConfig accepts servicefile as a
part of the connection string.
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.
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() })
}
SafeToRetry checks if the err is guaranteed to have occurred before sending any data to the server.
Timeout checks if err 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.
ValidateConnectTargetSessionAttrsPreferStandby is a ValidateConnectFunc that implements libpq compatible
target_session_attrs=prefer-standby.
ValidateConnectTargetSessionAttrsPrimary is a ValidateConnectFunc that implements libpq compatible
target_session_attrs=primary.
ValidateConnectTargetSessionAttrsReadOnly is a ValidateConnectFunc that implements libpq compatible
target_session_attrs=read-only.
ValidateConnectTargetSessionAttrsReadWrite is a ValidateConnectFunc that implements libpq compatible
target_session_attrs=read-write.
ValidateConnectTargetSessionAttrsStandby is a ValidateConnectFunc that implements libpq compatible
target_session_attrs=standby.
buildConnectOneConfigs resolves hostnames and builds a list of connectOneConfigs to try connecting to. It returns a
slice of successfully resolved connectOneConfigs and a slice of errors. It is possible for both slices to contain
values if some hosts were successfully resolved and others were not.
canonicalConnStringKey returns the canonical settings-map key for a libpq parameter keyword.
configTLS uses libpq's TLS parameters to construct []*tls.Config. It is
necessary to allow returning multiple TLS configs as sslmode "allow" and
"prefer" allow fallback.
connectOne makes one connection attempt to a single host.
connectPreferred attempts to connect to the preferred host from connectOneConfigs. The connections are attempted in
order. If a connection is successful it is returned. If no connection is successful then all errors are returned. If
a connection attempt returns a [NotPreferredError], then that host will be used if no other hosts are successful.
defaultHost attempts to mimic libpq's default host. libpq uses the default unix socket location on *nix and localhost
on Windows. The default socket location is compiled into libpq. Since pgx does not have access to that default it
checks the existence of common locations.
isAbsolutePath checks if the provided value is an absolute path either
beginning with a forward slash (as on Linux-based systems) or with a capital
letter A-Z followed by a colon and a backslash, e.g., "C:\", (as on Windows).
normalizeScramPassword preserves PostgreSQL's raw-password fallback for
characters that SASLprep considers unassigned. SASLprep uses Unicode 3.2,
while PRECIS uses newer Unicode tables that can change with x/text or Go
upgrades. Check the original password before PRECIS can change any bytes.
osUserSettings returns the default PostgreSQL user name derived from the
current OS user account.
Resolving this requires looking up the OS user account, which can be slow
or, in some restricted container environments (e.g. distroless images
with a broken NSS/CGO setup), crash the process. Callers must only call
osUserSettings when the default user name is not already supplied by the
connection string, environment, or service file.
parseRequireAuth parses the require_auth connection parameter with libpq-compatible semantics:
a comma-separated list of method names, optionally each prefixed with "!" to negate. Negated and
non-negated entries cannot be mixed; duplicate entries are rejected. An empty string yields a
permissive policy (all methods allowed, no authentication required).
parseURLQueryParams parses the query part of a connection URI into settings,
mirroring libpq's conninfo_uri_parse_params: '&'-separated pairs, exactly
one raw '=' per pair, both halves percent-decoded, last occurrence wins. It
records in meta which spellings of the ssl/sslmode keys it saw (see
parseURLMeta).
parseURLSettings parses a connection URI into a settings map. connString
must start with "postgres://" or "postgresql://".
Multiple hosts are represented in the returned map the same way libpq
represents them internally: settings["host"] and settings["port"] are
comma-separated lists that are positionally aligned, with empty elements
meaning "use the default". The lists are split in ParseConfigWithOptions.
peekByte returns the first byte of s, or 0 if s is empty. A NUL byte is a
safe end-of-input sentinel because parseURLSettings rejects literal NULs.
prepareTLSConfigForConnect prepares the TLS config for one connection's sslcertmode.
In require mode, the returned state must be checked before accepting AuthenticationOk or ReadyForQuery.
Configs may be shared by concurrent connection attempts, so any callback state must
belong to a clone made for this attempt, not the original config.
redactPW masks recognizable password fields on a best-effort basis. It
cannot guarantee redaction when malformed input makes component boundaries
ambiguous.
redactURLPassword masks recognizable password values in a connection URI.
For a URI that parses cleanly the component boundaries are certain, and
every password position -- the userinfo password and password/sslpassword
query values -- is reliably masked with the rest of the string left intact.
It is also deliberately usable without a successful parse -- the strings
that reach ParseConfigError are often exactly the ones that failed to parse
-- but malformed syntax can make component boundaries ambiguous, so for
such input redaction is best-effort and may over-mask.
For URI shapes it recognizes, it mirrors parseURLSettings structurally
rather than pattern-matching the raw text: the userinfo password is whatever
follows the first ':' before the terminating '@' (found with the parser's
lookahead), and a query value is masked when its percent-decoded key
canonicalizes to password or sslpassword. This uses the same decoding as the
parser, so encoded spellings like pass%77ord are caught and the whole
recognized raw value is masked no matter what bytes it contains.
unescapeKeywordValue applies libpq's backslash rule to the raw text of a
keyword/value value: a backslash is dropped and whatever follows it is taken
literally, whatever that character is. A backslash at the very end escapes
the end of the string, so it is dropped and contributes nothing -- which is
how libpq accepts `host=a\`. Only the unquoted branch can reach that case;
inside quotes the escaped terminator leaves the string unterminated and the
caller has already rejected it.
uriDecode percent-decodes a URI component with the same rules as libpq's
conninfo_uri_decode: '%' followed by exactly two case-insensitive hex
digits, %00 forbidden, leading and trailing ASCII spaces skipped, interior
spaces rejected. Decoded bytes are emitted raw with no character set
validation.
If secretName is non-empty, error messages identify that component by name
instead of quoting its raw value. This prevents the known component's raw
contents from being copied into the decode error; it does not make the
separate, best-effort redaction of an invalid connection string complete.
uriDecodeLenient is a non-failing variant of uriDecode used for best-effort
redaction: valid percent-encodings are decoded, anything uriDecode would
reject passes through unchanged. Redaction processing itself must not fail,
and it must see the same key spelling the parser would (pass%77ord decodes
to password), so encoded password keys are recognized even in connection
strings that do not parse. This helps recognize keys but cannot make
redaction complete when malformed input has ambiguous component boundaries.
uriQueryStart returns the index of the '?' that begins the query component
of p (the post-scheme, post-userinfo part of a connection URI), or -1 if
there is none. It follows parseURLSettings' structure: '[' at the start of
a netloc element opens an IPv6 bracket whose contents -- deliberately
unvalidated -- may contain a literal '?' that is host data, not the query
delimiter. On an unterminated bracket (the parser errors there) it falls
back to the first '?' anywhere. With no valid structure to follow,
over-including text gives the best-effort redactor more candidate pairs to
inspect.
uriStructureUnambiguous reports whether connString parses as a connection
URI whose component boundaries are certain, meaning redactURLPassword's
structural walk is exact and no password bytes can sit outside the two
positions it masks (the userinfo password and password-keyed query values).
That requires parseURLSettings to accept the string and every port element
to be numeric or empty: the parser accepts arbitrary text in the port slot
(postgres://a@u:sec:ret@h parses with port "sec:ret@h"), so a non-numeric
port may be a mislaid password and keeps the string in best-effort
territory.
Package-Level Variables (total 12, in which 5 are exported)
ErrConnClosed is returned (possibly wrapped) when an operation is attempted
on a connection that the driver has already closed, e.g. because a prior
query was cancelled mid-flight or the underlying socket went away. Use
errors.Is to test for it, since it shows up wrapped inside connLockError.
ErrPrimaryConnection is returned when a standby connection is required but the server is primary.
ErrReadOnlyConnection is returned when a read-write connection is required but the connection is read-only.
ErrReadWriteConnection is returned when a read-only connection is required but the connection is read-write.
ErrStandbyConnection is returned when a primary connection is required but the server is in standby mode.
connStringKeyAliases maps libpq parameter keywords to the canonical key names this package
uses internally in the parsed-settings map. Most keywords are already canonical; this map
holds only those whose pgx-internal name differs from the libpq spelling.
currentOSUser resolves the current OS user account. It is a seam so tests
can simulate os/user.Current failing -- including the unrecoverable
crashes reported in some restricted/broken-NSS container environments --
without needing such an environment.
saslprepUnassigned is RFC 3454 table A.1: code points unassigned in
Unicode 3.2. This table must not track the Go toolchain's Unicode version.
https://www.rfc-editor.org/rfc/rfc3454#appendix-A.1
userHomeDir resolves the current user's home directory. It is a seam so
tests can simulate os.UserHomeDir failing without needing to unset $HOME
for the whole process.
os.UserHomeDir only reads the $HOME environment variable on this platform;
it never calls into cgo or NSS, so unlike os/user.Current it cannot crash
in restricted/broken container environments. That also means it can
resolve a different directory than the OS account's passwd-file home
directory if $HOME has been overridden -- this is an accepted tradeoff so
that home-directory-derived defaults (pgpass, pg_service.conf, client SSL
certificate/key/root files) keep resolving even when the OS user account
lookup itself is unavailable or unsafe to call.
Package-Level Constants (total 25, none are exported)
defaultPort is the port used when neither the connection string, the environment, nor the
service file supplies one. It is also the per-element fallback for empty entries in a
multi-host port list.