jackc/pgx · error

invalid backslash

Error message

invalid backslash

What it means

Returned by parseKeywordValueSettings while parsing an UNQUOTED value: a backslash is encountered as the last character of the string with nothing following it. The parser increments past the backslash expecting an escaped character and hits end-of-string.

Source

Thrown at pgconn/config.go:743

		eqIdx := strings.IndexRune(s, '=')
		if eqIdx < 0 {
			return nil, errors.New("invalid keyword/value")
		}

		key = strings.Trim(s[:eqIdx], " \t\n\r\v\f")
		s = strings.TrimLeft(s[eqIdx+1:], " \t\n\r\v\f")
		switch {
		case len(s) == 0:
		case s[0] != '\'':
			end := 0
			for ; end < len(s); end++ {
				if asciiSpace[s[end]] == 1 {
					break
				}
				if s[end] == '\\' {
					end++
					if end == len(s) {
						return nil, errors.New("invalid backslash")
					}
				}
			}
			val = strings.ReplaceAll(strings.ReplaceAll(s[:end], "\\\\", "\\"), "\\'", "'")
			// Consume the value and trim any subsequent whitespace so that
			// multiple trailing spaces don't cause a spurious parse failure.
			s = strings.TrimLeft(s[end:], " \t\n\r\v\f")
		default: // quoted string
			s = s[1:]
			end := 0
			for ; end < len(s); end++ {
				if s[end] == '\'' {
					break
				}
				if s[end] == '\\' {
					end++
				}
			}

View on GitHub (pinned to ec1a0befd2)

Solutions

  1. Quote the value and escape properly, or remove the trailing backslash.
  2. Double the backslash to represent a literal backslash: 'host=localhost\\'.
  3. Prefer a URL-style connection string or a *ConnConfig struct to avoid conninfo escaping pitfalls.

Example fix

// before
pgx.ParseConfig(`host=localhost\`)

// after (literal backslash)
pgx.ParseConfig(`host=localhost\\`)
Defensive patterns

Strategy: validation

Validate before calling

// Reject conninfo values ending in a lone backslash before parsing.
func checkTrailingBackslash(s string) error {
    if strings.HasSuffix(strings.TrimSpace(s), "\\") && !strings.HasSuffix(strings.TrimSpace(s), "\\\\") {
        return errors.New("connection string value ends with a lone backslash")
    }
    return nil
}

Try / catch

if _, err := pgx.ParseConfig(connStr); err != nil {
    if strings.Contains(err.Error(), "invalid backslash") {
        return fmt.Errorf("connection string has an incomplete backslash escape: %w", err)
    }
}

Prevention

When it happens

Trigger: A keyword/value string whose unquoted value ends with a lone backslash, e.g. 'host=localhost\' or 'password=ab\'. The escape sequence is incomplete.

Common situations: Shell/env-var interpolation leaving a trailing backslash; mis-escaping of Windows paths or regex-like values in conninfo.

Related errors


AI-assisted analysis of jackc/pgx@ec1a0befd2 (2026-08-04). Data as JSON: /data/errors/3290cfe83a0d1514.json. Report an issue: GitHub.