package pgconnimport ()// SafeToRetry checks if the err is guaranteed to have occurred before sending any data to the server.func ( error) bool {varinterface{ () bool }iferrors.As(, &) {return .() }returnfalse}// 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.func ( error) bool {var *errTimeoutreturnerrors.As(, &)}// PgError represents an error reported by the PostgreSQL server. See// http://www.postgresql.org/docs/current/static/protocol-error-fields.html for// detailed field description.typePgErrorstruct {SeveritystringSeverityUnlocalizedstringCodestringMessagestringDetailstringHintstringPositionint32InternalPositionint32InternalQuerystringWherestringSchemaNamestringTableNamestringColumnNamestringDataTypeNamestringConstraintNamestringFilestringLineint32Routinestring}func ( *PgError) () string {return .Severity + ": " + .Message + " (SQLSTATE " + .Code + ")"}// SQLState returns the SQLState of the error.func ( *PgError) () string {return .Code}// ConnectError is the error returned when a connection attempt fails.typeConnectErrorstruct {Config *Config// The configuration that was used in the connection attempt.errerror}func ( *ConnectError) () string { := fmt.Sprintf("failed to connect to `user=%s database=%s`:", .Config.User, .Config.Database) := .err.Error()ifstrings.Contains(, "\n") {return + "\n\t" + strings.ReplaceAll(, "\n", "\n\t") } else {return + " " + }}func ( *ConnectError) () error {return .err}typeperDialConnectErrorstruct {addressstringoriginalHostnamestringerrerror}func ( *perDialConnectError) () string {returnfmt.Sprintf("%s (%s): %s", .address, .originalHostname, .err.Error())}func ( *perDialConnectError) () error {return .err}// sslCertModeError is a client-side authentication failure that must stop// connection fallback, matching libpq's sslcertmode=require behavior.typesslCertModeErrorstruct {msgstring}func ( *sslCertModeError) () string {return .msg}// 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.varErrConnClosed = errors.New("conn closed")typeconnLockErrorstruct {statusstring}func ( *connLockError) () bool {returntrue// a lock failure by definition happens before the connection is used.}func ( *connLockError) () string {return .status}func ( *connLockError) () error {if .status == "conn closed" {returnErrConnClosed }returnnil}// 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.typeParseConfigErrorstruct {ConnStringstring// The original, unredacted connection string that could not be parsed.msgstringerrerror}func (, string, error) error {return &ParseConfigError{ConnString: ,msg: ,err: , }}func ( *ParseConfigError) () string {// redactPW is necessarily best effort: an invalid connection string can be // too ambiguous to identify every password. Returning only a static string // would be the way to guarantee that Error cannot leak one. The public // ConnString field would still allow access to the original string if // desired, and Unwrap would allow access to the underlying error. := redactPW(.ConnString)if .err == nil {returnfmt.Sprintf("cannot parse `%s`: %s", , .msg) }returnfmt.Sprintf("cannot parse `%s`: %s (%s)", , .msg, .err.Error())}func ( *ParseConfigError) () error {return .err}func ( context.Context, error) error {varnet.Erroriferrors.As(, &) && .Timeout() {switch .Err() {casecontext.Canceled:// Since the timeout was caused by a context cancellation, the actual error is context.Canceled not the timeout error.returncontext.Canceledcasecontext.DeadlineExceeded:return &errTimeout{err: .Err()}default:return &errTimeout{err: } } }return}typepgconnErrorstruct {msgstringerrerrorsafeToRetrybool}func ( *pgconnError) () string {if .msg == "" {return .err.Error() }if .err == nil {return .msg }returnfmt.Sprintf("%s: %s", .msg, .err.Error())}func ( *pgconnError) () bool {return .safeToRetry}func ( *pgconnError) () error {return .err}// 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.typeerrTimeoutstruct {errerror}func ( *errTimeout) () string {returnfmt.Sprintf("timeout: %s", .err.Error())}func ( *errTimeout) () bool {returnSafeToRetry(.err)}func ( *errTimeout) () error {return .err}typecontextAlreadyDoneErrorstruct {errerror}func ( *contextAlreadyDoneError) () string {returnfmt.Sprintf("context already done: %s", .err.Error())}func ( *contextAlreadyDoneError) () bool {returntrue}func ( *contextAlreadyDoneError) () error {return .err}// newContextAlreadyDoneError double-wraps a context error in `contextAlreadyDoneError` and `errTimeout`.func ( context.Context) ( error) {return &errTimeout{&contextAlreadyDoneError{err: .Err()}}}// redactPW masks recognizable password fields on a best-effort basis. It// cannot guarantee redaction when malformed input makes component boundaries// ambiguous.func ( string) string {ifstrings.HasPrefix(, "postgres://") || strings.HasPrefix(, "postgresql://") {returnredactURLPassword() } := regexp.MustCompile(`password='[^']*'`) = .ReplaceAllLiteralString(, "password=xxxxx") := regexp.MustCompile(`password=[^ ]*`) = .ReplaceAllLiteralString(, "password=xxxxx") := regexp.MustCompile(`:[^:@]+?@`) = .ReplaceAllLiteralString(, ":xxxxxx@")return}// 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.func ( string) string {const = "xxxxx"varstrings.Builder .Grow(len()) := for , := range []string{"postgresql://", "postgres://"} {if , := strings.CutPrefix(, ); { .WriteString() = break } }// Userinfo: same lookahead as parseURLSettings.if := strings.IndexAny(, "@/"); >= 0 && [] == '@' { , , := strings.Cut([:], ":") = [+1:] .WriteString()if { .WriteString(":" + ) } .WriteByte('@') }// Nothing after the userinfo is a password position, but a password can // land there in malformed URIs: an unencoded '/' or '?' in a userinfo // password turns everything after it into path or query, stranding the // '@' (postgres://user:pass/word?x=y@host). As a best-effort heuristic, // while an '@' remains, mask everything shaped like // ":candidate-credential@" across the whole // remainder -- before the query is split off, or a stranded '@' inside // the query would hide the pattern, and greedily up to each '@', so a // ':' inside the stranded password (user:sec:ret@host) cannot split the // mask and leak the part before it. // // The heuristic must not run when the connection string is structurally // unambiguous: then nothing can be stranded, a remaining '@' is ordinary // data (typically in a query value), and the greedy mask would swallow // the '/' and '?' delimiters -- hiding the query from the password-key // masking below, so a password=... query parameter would leak. Valid // URIs must always redact exactly; the heuristic is reserved for // malformed input, where only best effort is possible.ifstrings.IndexByte(, '@') >= 0 && !uriStructureUnambiguous() { := regexp.MustCompile(`:[^@]+@`) = .ReplaceAllLiteralString(, ":xxxxxx@") } := uriQueryStart()if < 0 { .WriteString()return .String() } .WriteString([:]) := [+1:] .WriteByte('?')for , := rangestrings.Split(, "&") {if > 0 { .WriteByte('&') } , , := strings.Cut(, "=")if ! { .WriteString()continue }switchcanonicalConnStringKey(uriDecodeLenient()) {case"password", "sslpassword": .WriteString() .WriteByte('=') .WriteString()default: .WriteString() } }return .String()}// 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.func ( string) bool { , , := parseURLSettings()if != nil {returnfalse }for := rangestrings.SplitSeq(["port"], ",") {for := 0; < len(); ++ {if [] < '0' || [] > '9' {returnfalse } } }returntrue}// 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.func ( string) int { := 0for {if < len() && [] == '[' { := strings.IndexByte([:], ']')if < 0 {returnstrings.IndexByte(, '?') } += + 1 }// Host and port data: everything up to a '/', '?', or ','.for < len() && [] != '/' && [] != '?' && [] != ',' { ++ }if < len() && [] == ',' { ++continue }break }if == len() {return -1 }if [] == '?' {return }// p[i] == '/': a path follows; the first '?' after it starts the query.if := strings.IndexByte([:], '?'); >= 0 {return + }return -1}typeNotPreferredErrorstruct {errerrorsafeToRetrybool}func ( *NotPreferredError) () string {returnfmt.Sprintf("standby server not found: %s", .err.Error())}func ( *NotPreferredError) () bool {return .safeToRetry}func ( *NotPreferredError) () error {return .err}typePrepareErrorstruct {errerrorParseCompletebool// Indicates whether the error occurred after a ParseComplete message was received.}func ( *PrepareError) () string {if .ParseComplete {returnfmt.Sprintf("prepare failed after ParseComplete: %s", .err.Error()) }return .err.Error()}func ( *PrepareError) () error {return .err}
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)