package pgconn

import (
	
	
	
	
	
	
	
	
	
	
	
	
	
	

	
	
	
	
)

type (
	AfterConnectFunc    func(ctx context.Context, pgconn *PgConn) error
	ValidateConnectFunc func(ctx context.Context, pgconn *PgConn) error
	GetSSLPasswordFunc  func(ctx context.Context) string
)

// 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

	// 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.
	MaxProtocolMessageBodyLen int

	// BuildContextWatcherHandler is called to create a ContextWatcherHandler for a connection. The handler is called
	// when a context passed to a PgConn method is canceled.
	BuildContextWatcherHandler func(*PgConn) ctxwatch.Handler

	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

	SSLNegotiation string // sslnegotiation=postgres or sslnegotiation=direct

	// 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.
	SSLCertMode string

	// 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.
	AfterNetConnect func(ctx context.Context, config *Config, conn net.Conn) (net.Conn, error)

	// 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

	// 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.
	OAuthTokenProvider func(context.Context) (string, error)

	// 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".
	MinProtocolVersion string

	// 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.
	MaxProtocolVersion string

	// ChannelBinding is the channel_binding parameter for SCRAM-SHA-256-PLUS authentication.
	// Valid values: "disable", "prefer", "require". Defaults to "prefer".
	ChannelBinding string

	// 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.
	RequireAuth string

	createdByParseConfig bool // Used to enforce created by ParseConfig rule.
}

// 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.
const defaultPort = "5432"

// 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.
var connStringKeyAliases = map[string]string{
	"dbname": "database",
}

// canonicalConnStringKey returns the canonical settings-map key for a libpq parameter keyword.
func ( string) string {
	if ,  := connStringKeyAliases[];  {
		return 
	}
	return 
}

// 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 libpq function
	// PQsetSSLKeyPassHook_OpenSSL.
	GetSSLPassword GetSSLPasswordFunc

	// 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.
	ConnStringAllowedKeys []string
}

// 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 ( *Config) () *Config {
	 := new(Config)
	* = *
	if .TLSConfig != nil {
		.TLSConfig = .TLSConfig.Clone()
	}
	if .RuntimeParams != nil {
		.RuntimeParams = make(map[string]string, len(.RuntimeParams))
		maps.Copy(.RuntimeParams, .RuntimeParams)
	}
	if .Fallbacks != nil {
		.Fallbacks = make([]*FallbackConfig, len(.Fallbacks))
		for ,  := range .Fallbacks {
			 := new(FallbackConfig)
			* = *
			if .TLSConfig != nil {
				.TLSConfig = .TLSConfig.Clone()
			}
			.Fallbacks[] = 
		}
	}
	return 
}

// 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
}

// connectOneConfig is the configuration for a single attempt to connect to a single host.
type connectOneConfig struct {
	network          string
	address          string
	originalHostname string      // original hostname before resolving
	tlsConfig        *tls.Config // nil disables TLS
}

// 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).
func ( string) bool {
	 := func( string) bool {
		if len() < 3 {
			return false
		}
		 := [0]
		 := [1]
		 := [2]
		if  >= 'A' &&  <= 'Z' &&  == ':' &&  == '\\' {
			return true
		}
		return false
	}
	return strings.HasPrefix(, "/") || ()
}

// NetworkAddress converts a PostgreSQL host and port into network and address suitable for use with
// net.Dial.
func ( string,  uint16) (,  string) {
	if isAbsolutePath() {
		 = "unix"
		 = filepath.Join(, ".s.PGSQL.") + strconv.FormatInt(int64(), 10)
	} else {
		 = "tcp"
		 = net.JoinHostPort(, strconv.Itoa(int()))
	}
	return , 
}

// 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.
func ( string) (*Config, error) {
	var  ParseConfigOptions
	return ParseConfigWithOptions(, )
}

// 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 ( string,  ParseConfigOptions) (*Config, error) {
	 := defaultSettings()
	 := parseEnvSettings()

	 := make(map[string]string)
	var  parseURLMeta
	if  != "" {
		var  error
		// connString may be a database URL or in PostgreSQL keyword/value format
		if strings.HasPrefix(, "postgres://") || strings.HasPrefix(, "postgresql://") {
			, ,  = parseURLSettings()
			if  != nil {
				return nil, &ParseConfigError{ConnString: , msg: "failed to parse as URL", err: }
			}
		} else {
			,  = parseKeywordValueSettings()
			if  != nil {
				return nil, &ParseConfigError{ConnString: , msg: "failed to parse as keyword/value", err: }
			}
		}
	}

	if .ConnStringAllowedKeys != nil {
		 := make(map[string]struct{}, len(.ConnStringAllowedKeys))
		for ,  := range .ConnStringAllowedKeys {
			[canonicalConnStringKey()] = struct{}{}
		}
		 := func( string) error {
			return &ParseConfigError{ConnString: , msg: fmt.Sprintf("connection string key %q is not in ConnStringAllowedKeys", )}
		}
		,  := ["ssl"]
		,  := ["sslmode"]

		// Repeated-key handling and the URI ssl=true alias rewrite can remove
		// ssl/sslmode occurrences from the final settings map, so those two keys
		// are validated from what the user actually wrote -- every occurrence,
		// fail closed -- rather than from what survived. The alias itself is
		// accepted under either spelling, the same way dbname/database are
		// interchangeable; an explicit sslmode key or a non-"true" ssl value
		// only matches its own spelling.
		if .sawRawSSLKey && ! {
			return nil, ("ssl")
		}
		if .sawExplicitSSLModeKey && ! {
			return nil, ("sslmode")
		}
		if .sawSSLTrueAlias && ! && ! {
			return nil, ("ssl")
		}

		for  := range  {
			if ,  := [];  {
				continue
			}
			// A multi-host URI with no explicit ports produces an implied
			// all-empty port list (e.g. ","), matching libpq. Only that list
			// -- identified by the parser from the raw syntax, not inferred
			// from the value -- is exempt from the allow-list: it carries no
			// user-supplied port text. An explicit empty port (?port= in a
			// URI or port= in keyword/value form) is user-supplied, and
			// because a present-but-empty port still shadows PGPORT it must
			// pass the allow-list like any other key.
			if  == "port" && .impliedEmptyPortList {
				continue
			}
			// A surviving ssl or sslmode entry from a URI was already
			// validated above against every spelling the user wrote.
			if  == "ssl" && .sawRawSSLKey {
				continue
			}
			if  == "sslmode" && (.sawSSLTrueAlias || .sawExplicitSSLModeKey) {
				continue
			}
			return nil, ()
		}
	}

	 := mergeSettings(, , )

	// The home-directory-derived defaults (passfile, servicefile, sslcert,
	// sslkey, sslrootcert) are already present in settings at this point:
	// defaultSettings resolves them via the user's home directory, which is
	// safe and cheap to look up (see defaults.go / defaults_windows.go).
	//
	// The default PostgreSQL user name is different: resolving it requires
	// looking up the OS user account, which can be slow or, in some
	// restricted container environments, crash the process. So that lookup
	// is memoized and only performed lazily below, the first time it is
	// actually needed -- i.e. only when a connection string or environment
	// does not already supply a user.
	var  map[string]string
	 := func() map[string]string {
		if  == nil {
			 = osUserSettings()
		}
		return 
	}

	if ,  := ["service"];  {
		,  := parseServiceSettings(["servicefile"], )
		if  != nil {
			return nil, &ParseConfigError{ConnString: , msg: "failed to read service", err: }
		}

		 = mergeSettings(, , , )
	}

	// Only fall back to the OS user account for the default PostgreSQL user
	// name when it was not already supplied by the connection string,
	// environment, or service file.
	if ["user"] == "" {
		 = mergeSettings((), )
	}

	 := &Config{
		createdByParseConfig: true,
		Database:             ["database"],
		User:                 ["user"],
		Password:             ["password"],
		RuntimeParams:        make(map[string]string),
		BuildFrontend:        pgproto3.NewFrontend,
		BuildContextWatcherHandler: func( *PgConn) ctxwatch.Handler {
			return &DeadlineContextWatcherHandler{Conn: .conn}
		},
		OnPgError: func( *PgConn,  *PgError) bool {
			// we want to automatically close any fatal errors
			if strings.EqualFold(.Severity, "FATAL") {
				return false
			}
			return true
		},
	}

	,  := ["sslcertmode"]
	if ! {
		 = "allow"
	}
	var  error
	.SSLCertMode,  = parseSSLCertMode()
	if  != nil {
		return nil, &ParseConfigError{ConnString: , msg: "invalid sslcertmode", err: }
	}

	if ,  := ["connect_timeout"];  {
		,  := parseConnectTimeoutSetting()
		if  != nil {
			return nil, &ParseConfigError{ConnString: , msg: "invalid connect_timeout", err: }
		}
		.ConnectTimeout = 
		.DialFunc = makeConnectTimeoutDialFunc()
	} else {
		 := makeDefaultDialer()
		.DialFunc = .DialContext
	}

	.LookupFunc = makeDefaultResolver().LookupHost

	 := map[string]struct{}{
		"host":                 {},
		"port":                 {},
		"database":             {},
		"user":                 {},
		"password":             {},
		"passfile":             {},
		"connect_timeout":      {},
		"sslmode":              {},
		"sslkey":               {},
		"sslcert":              {},
		"sslcertmode":          {},
		"sslrootcert":          {},
		"sslnegotiation":       {},
		"sslpassword":          {},
		"sslsni":               {},
		"krbspn":               {},
		"krbsrvname":           {},
		"target_session_attrs": {},
		"service":              {},
		"servicefile":          {},
		"min_protocol_version": {},
		"max_protocol_version": {},
		"channel_binding":      {},
		"require_auth":         {},
	}

	// Adding kerberos configuration
	if ,  := ["krbsrvname"];  {
		.KerberosSrvName = ["krbsrvname"]
	}
	if ,  := ["krbspn"];  {
		.KerberosSpn = ["krbspn"]
	}

	for ,  := range  {
		if ,  := [];  {
			continue
		}
		.RuntimeParams[] = 
	}

	 := []*FallbackConfig{}

	 := strings.Split(["host"], ",")
	 := strings.Split(["port"], ",")

	// Like libpq, if exactly one port is given it applies to all hosts;
	// otherwise there must be exactly one port per host. Empty list elements
	// mean "use the default".
	if len() > 1 && len() != len() {
		return nil, &ParseConfigError{ConnString: , msg: fmt.Sprintf("could not match %d port numbers to %d hosts", len(), len())}
	}

	// defaultHost stats candidate socket directories, so resolve it at most
	// once even when several host list elements are empty. It never returns "".
	 := ""
	for ,  := range  {
		if  == "" {
			if  == "" {
				 = defaultHost()
			}
			 = 
		}

		 := [0]
		if len() > 1 {
			 = []
		}
		if  == "" {
			 = defaultPort
		}

		// The strconv error is deliberately not wrapped: it quotes the
		// offending text, and in a malformed URI the bytes that land in the
		// port position can be a mislaid password (postgres://u:sec:ret@h
		// parses "sec:ret@h" as the port). The best-effort-redacted connection
		// string in ParseConfigError provides the available context without
		// deliberately quoting the offending port text again.
		,  := parsePort()
		if  != nil {
			return nil, &ParseConfigError{ConnString: , msg: "invalid port"}
		}

		var  []*tls.Config

		// Ignore TLS settings if Unix domain socket like libpq
		if ,  := NetworkAddress(, );  == "unix" {
			 = append(, nil)
		} else {
			var  error
			,  = configTLS(, , )
			if  != nil {
				return nil, &ParseConfigError{ConnString: , msg: "failed to configure TLS", err: }
			}
		}

		for ,  := range  {
			 = append(, &FallbackConfig{
				Host:      ,
				Port:      ,
				TLSConfig: ,
			})
		}
	}

	.Host = [0].Host
	.Port = [0].Port
	.TLSConfig = [0].TLSConfig
	.Fallbacks = [1:]
	.SSLNegotiation = ["sslnegotiation"]

	if .Password == "" {
		,  := pgpassfile.ReadPassfile(["passfile"])
		if  == nil {
			 := .Host
			if ,  := NetworkAddress(.Host, .Port);  == "unix" {
				 = "localhost"
			}
			.Password = .FindPassword(, strconv.Itoa(int(.Port)), .Database, .User)
		}
	}

	switch  := ["target_session_attrs"];  {
	case "read-write":
		.ValidateConnect = ValidateConnectTargetSessionAttrsReadWrite
	case "read-only":
		.ValidateConnect = ValidateConnectTargetSessionAttrsReadOnly
	case "primary":
		.ValidateConnect = ValidateConnectTargetSessionAttrsPrimary
	case "standby":
		.ValidateConnect = ValidateConnectTargetSessionAttrsStandby
	case "prefer-standby":
		.ValidateConnect = ValidateConnectTargetSessionAttrsPreferStandby
	case "any":
		// do nothing
	default:
		return nil, &ParseConfigError{ConnString: , msg: fmt.Sprintf("unknown target_session_attrs value: %v", )}
	}

	,  := parseProtocolVersion(["min_protocol_version"])
	if  != nil {
		return nil, &ParseConfigError{ConnString: , msg: fmt.Sprintf("invalid min_protocol_version: %q", ["min_protocol_version"]), err: }
	}
	,  := parseProtocolVersion(["max_protocol_version"])
	if  != nil {
		return nil, &ParseConfigError{ConnString: , msg: fmt.Sprintf("invalid max_protocol_version: %q", ["max_protocol_version"]), err: }
	}

	.MinProtocolVersion = ["min_protocol_version"]
	.MaxProtocolVersion = ["max_protocol_version"]

	if .MinProtocolVersion == "" {
		.MinProtocolVersion = "3.0"
	}

	// When max_protocol_version is not explicitly set, default based on
	// min_protocol_version. This matches libpq behavior: if min > 3.0,
	// default max to latest; otherwise default to 3.0 for compatibility
	// with older servers/poolers that don't support NegotiateProtocolVersion.
	if .MaxProtocolVersion == "" {
		if  > pgproto3.ProtocolVersion30 {
			.MaxProtocolVersion = "latest"
		} else {
			.MaxProtocolVersion = "3.0"
		}
	}

	// Only error when max_protocol_version was explicitly set and conflicts
	// with min_protocol_version. When max_protocol_version is not explicitly
	// set, the auto-raise logic above already ensures a valid default.
	if  >  && ["max_protocol_version"] != "" {
		return nil, &ParseConfigError{ConnString: , msg: "min_protocol_version cannot be greater than max_protocol_version"}
	}

	switch  := ["channel_binding"];  {
	case "", "prefer":
		.ChannelBinding = "prefer"
	case "disable":
		.ChannelBinding = "disable"
	case "require":
		.ChannelBinding = "require"
	default:
		return nil, &ParseConfigError{ConnString: , msg: fmt.Sprintf("unknown channel_binding value: %v", )}
	}

	.RequireAuth = ["require_auth"]
	if ,  := parseRequireAuth(.RequireAuth);  != nil {
		return nil, &ParseConfigError{ConnString: , msg: "invalid require_auth", err: }
	}

	return , nil
}

func ( ...map[string]string) map[string]string {
	 := make(map[string]string)

	for ,  := range  {
		maps.Copy(, )
	}

	return 
}

func () map[string]string {
	 := make(map[string]string)

	 := map[string]string{
		"PGHOST":               "host",
		"PGPORT":               "port",
		"PGDATABASE":           "database",
		"PGUSER":               "user",
		"PGPASSWORD":           "password",
		"PGPASSFILE":           "passfile",
		"PGAPPNAME":            "application_name",
		"PGCONNECT_TIMEOUT":    "connect_timeout",
		"PGSSLMODE":            "sslmode",
		"PGSSLKEY":             "sslkey",
		"PGSSLCERT":            "sslcert",
		"PGSSLCERTMODE":        "sslcertmode",
		"PGSSLSNI":             "sslsni",
		"PGSSLROOTCERT":        "sslrootcert",
		"PGSSLPASSWORD":        "sslpassword",
		"PGSSLNEGOTIATION":     "sslnegotiation",
		"PGTARGETSESSIONATTRS": "target_session_attrs",
		"PGSERVICE":            "service",
		"PGSERVICEFILE":        "servicefile",
		"PGTZ":                 "timezone",
		"PGOPTIONS":            "options",
		"PGMINPROTOCOLVERSION": "min_protocol_version",
		"PGMAXPROTOCOLVERSION": "max_protocol_version",
		"PGCHANNELBINDING":     "channel_binding",
		"PGREQUIREAUTH":        "require_auth",
	}

	for ,  := range  {
		,  := os.LookupEnv()
		// Preserve an explicitly empty sslcertmode so it is rejected, like libpq.
		if  != "" || ( &&  == "sslcertmode") {
			[] = 
		}
	}

	return 
}

var asciiSpace = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1}

// 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.
func ( string) string {
	if !strings.ContainsRune(, '\\') {
		return 
	}

	var  strings.Builder
	.Grow(len())
	for  := 0;  < len(); ++ {
		if [] == '\\' {
			++
			if  == len() {
				break
			}
		}
		.WriteByte([])
	}
	return .String()
}

func ( string) (map[string]string, error) {
	 := make(map[string]string)

	// Reject NUL bytes up front, as parseURLSettings does. libpq never sees one
	// because its conninfo strings are NUL-terminated C strings; a Go string can
	// carry a NUL through to the startup packet, where it acts as a parameter
	// delimiter rather than data. StartupMessage.Encode refuses such parameters,
	// but failing here reports the problem against the input that caused it.
	if strings.IndexByte(, 0) >= 0 {
		return nil, errors.New("forbidden NUL byte in connection string")
	}

	// Trim any leading whitespace so that the loop exits cleanly when only
	// spaces remain (e.g. trailing spaces after the last value).
	 = strings.TrimLeft(, " \t\n\r\v\f")
	for len() > 0 {
		var ,  string
		 := strings.IndexRune(, '=')
		if  < 0 {
			return nil, errors.New("invalid keyword/value")
		}

		 = strings.Trim([:], " \t\n\r\v\f")
		// libpq reads a keyword as a run of non-space characters and then
		// requires the next non-space character to be '=', so whitespace
		// inside a keyword terminates it and is an error. Trimming alone would
		// accept the space as part of the key and turn a typo into a bogus
		// RuntimeParam that only the server rejects. Report it as libpq does,
		// naming the keyword it had read.
		if  := strings.IndexAny(, " \t\n\r\v\f");  >= 0 {
			return nil, fmt.Errorf(`missing "=" after %q in connection info string`, [:])
		}
		 = strings.TrimLeft([+1:], " \t\n\r\v\f")
		switch {
		case len() == 0:
		case [0] != '\'':
			 := 0
			for ;  < len(); ++ {
				if asciiSpace[[]] == 1 {
					break
				}
				if [] == '\\' {
					++
					// A trailing backslash escapes the end of the string.
					// libpq drops it and ends the value there. Break rather
					// than let the loop's post-increment push end past len(s).
					if  == len() {
						break
					}
				}
			}
			 = unescapeKeywordValue([:])
			// Consume the value and trim any subsequent whitespace so that
			// multiple trailing spaces don't cause a spurious parse failure.
			 = strings.TrimLeft([:], " \t\n\r\v\f")
		default: // quoted string
			 = [1:]
			 := 0
			for ;  < len(); ++ {
				if [] == '\'' {
					break
				}
				if [] == '\\' {
					++
					if  == len() {
						return nil, errors.New("unterminated quoted string in connection info string")
					}
				}
			}
			if  == len() {
				return nil, errors.New("unterminated quoted string in connection info string")
			}
			 = unescapeKeywordValue([:])
			// Consume the closing quote and any subsequent whitespace.
			 = strings.TrimLeft([+1:], " \t\n\r\v\f")
		}

		 = canonicalConnStringKey()

		if  == "" {
			return nil, errors.New("invalid keyword/value")
		}

		if  == "user" &&  == "" {
			continue
		}
		[] = 
	}

	return , nil
}

func (,  string) (map[string]string, error) {
	,  := pgservicefile.ReadServicefile()
	if  != nil {
		return nil, fmt.Errorf("failed to read service file: %v", )
	}

	,  := .GetService()
	if  != nil {
		return nil, fmt.Errorf("unable to find service: %v", )
	}

	 := make(map[string]string, len(.Settings))
	for ,  := range .Settings {
		[canonicalConnStringKey()] = 
	}

	return , nil
}

// 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.
func ( map[string]string,  string,  ParseConfigOptions) ([]*tls.Config, error) {
	 := 
	 := ["sslmode"]
	 := ["sslrootcert"]
	 := ["sslcert"]
	 := ["sslkey"]
	if ["sslcertmode"] == "disable" {
		// Like libpq, do not read client certificate or key files in this mode.
		,  = "", ""
	}
	 := ["sslpassword"]
	 := ["sslsni"]
	 := ["sslnegotiation"]

	// Match libpq default behavior
	if  == "" {
		 = "prefer"
	}
	if  == "" {
		 = "1"
	}

	 := &tls.Config{}

	if  == "direct" {
		.NextProtos = []string{"postgresql"}
		if  == "prefer" {
			 = "require"
		}
	}

	if  != "" {
		var  *x509.CertPool

		if  == "system" {
			var  error

			,  = x509.SystemCertPool()
			if  != nil {
				return nil, fmt.Errorf("unable to load system certificate pool: %w", )
			}

			 = "verify-full"
		} else {
			 = x509.NewCertPool()

			 := 
			,  := os.ReadFile()
			if  != nil {
				return nil, fmt.Errorf("unable to read CA file: %w", )
			}

			if !.AppendCertsFromPEM() {
				return nil, errors.New("unable to add CA to cert pool")
			}
		}

		.RootCAs = 
		.ClientCAs = 
	}

	switch  {
	case "disable":
		return []*tls.Config{nil}, nil
	case "allow", "prefer":
		.InsecureSkipVerify = true
	case "require":
		// According to PostgreSQL documentation, if a root CA file exists,
		// the behavior of sslmode=require should be the same as that of verify-ca
		//
		// See https://www.postgresql.org/docs/current/libpq-ssl.html
		if  != "" {
			goto 
		}
		.InsecureSkipVerify = true
		break
	:
		fallthrough
	case "verify-ca":
		// Don't perform the default certificate verification because it
		// will verify the hostname. Instead, verify the server's
		// certificate chain ourselves in VerifyPeerCertificate and
		// ignore the server name. This emulates libpq's verify-ca
		// behavior.
		//
		// See https://github.com/golang/go/issues/21971#issuecomment-332693931
		// and https://pkg.go.dev/crypto/tls?tab=doc#example-Config-VerifyPeerCertificate
		// for more info.
		.InsecureSkipVerify = true
		.VerifyPeerCertificate = func( [][]byte,  [][]*x509.Certificate) error {
			 := make([]*x509.Certificate, len())
			for ,  := range  {
				,  := x509.ParseCertificate()
				if  != nil {
					return errors.New("failed to parse certificate from server: " + .Error())
				}
				[] = 
			}

			// Leave DNSName empty to skip hostname verification.
			 := x509.VerifyOptions{
				Roots:         .RootCAs,
				Intermediates: x509.NewCertPool(),
			}
			// Skip the first cert because it's the leaf. All others
			// are intermediates.
			for ,  := range [1:] {
				.Intermediates.AddCert()
			}
			,  := [0].Verify()
			return 
		}
	case "verify-full":
		.ServerName = 
	default:
		return nil, errors.New("sslmode is invalid")
	}

	if ( != "" &&  == "") || ( == "" &&  != "") {
		return nil, errors.New(`both "sslcert" and "sslkey" are required`)
	}

	if  != "" &&  != "" {
		,  := os.ReadFile()
		if  != nil {
			return nil, fmt.Errorf("unable to read sslkey: %w", )
		}
		,  := pem.Decode()
		if  == nil {
			return nil, errors.New("failed to decode sslkey")
		}
		var  []byte
		var  []byte
		var  error
		// If PEM is encrypted, attempt to decrypt using pass phrase
		if x509.IsEncryptedPEMBlock() {
			// Attempt decryption with pass phrase
			// NOTE: only supports RSA (PKCS#1)
			if  != "" {
				,  = x509.DecryptPEMBlock(, []byte()) //nolint:ineffassign
			}
			// if sslpassword not provided or has decryption error when use it
			// try to find sslpassword with callback function
			if  == "" ||  != nil {
				if .GetSSLPassword != nil {
					 = .GetSSLPassword(context.Background())
				}
				if  == "" {
					return nil, fmt.Errorf("unable to find sslpassword")
				}
			}
			,  = x509.DecryptPEMBlock(, []byte())
			// Should we also provide warning for PKCS#1 needed?
			if  != nil {
				return nil, fmt.Errorf("unable to decrypt key: %w", )
			}

			 := pem.Block{
				Type:  "RSA PRIVATE KEY",
				Bytes: ,
			}
			 = pem.EncodeToMemory(&)
		} else {
			 = pem.EncodeToMemory()
		}
		,  := os.ReadFile()
		if  != nil {
			return nil, fmt.Errorf("unable to read cert: %w", )
		}
		,  := tls.X509KeyPair(, )
		if  != nil {
			return nil, fmt.Errorf("unable to load cert: %w", )
		}
		.Certificates = []tls.Certificate{}
	}

	// Set Server Name Indication (SNI), if enabled by connection parameters.
	// Per RFC 6066, do not set it if the host is a literal IP address (IPv4
	// or IPv6).
	if  == "1" && net.ParseIP() == nil {
		.ServerName = 
	}

	switch  {
	case "allow":
		return []*tls.Config{nil, }, nil
	case "prefer":
		return []*tls.Config{, nil}, nil
	case "require", "verify-ca", "verify-full":
		return []*tls.Config{}, nil
	default:
		panic("BUG: bad sslmode should already have been caught")
	}
}

type sslCertState struct {
	requested bool
	sent      bool
}

// checkRequired verifies the required certificate exchange during connection startup.
// In require mode, a nil state means that no TLS connection was made.
func ( *sslCertState) () error {
	if  == nil || !.requested {
		return &sslCertModeError{msg: "server did not request an SSL certificate"}
	}
	if !.sent {
		return &sslCertModeError{msg: "server accepted connection without a valid SSL certificate"}
	}
	return nil
}

// 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.
func ( *tls.Config,  string) (*tls.Config, *sslCertState) {
	switch  {
	case "disable":
		 = .Clone()
		.Certificates = nil
		.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
			return new(tls.Certificate), nil
		}
		return , nil
	case "require":
		 := new(sslCertState)
		 := 
		 = .Clone()
		// Resumed sessions skip the certificate exchange and its callback.
		.ClientSessionCache = nil
		.GetClientCertificate = func( *tls.CertificateRequestInfo) (*tls.Certificate, error) {
			.requested = true
			var  *tls.Certificate
			var  error
			if .GetClientCertificate != nil {
				,  = .GetClientCertificate()
			} else {
				// Preserve crypto/tls's default certificate selection, including its
				// signature scheme and acceptable CA checks.
				 = new(tls.Certificate)
				for  := range .Certificates {
					if .SupportsCertificate(&.Certificates[]) == nil {
						 = &.Certificates[]
						break
					}
				}
			}
			.sent =  == nil &&  != nil && len(.Certificate) > 0
			return , 
		}
		return , 
	default:
		return , nil
	}
}

func ( string) (string, error) {
	switch  {
	case "disable", "allow", "require":
		return , nil
	default:
		return "", fmt.Errorf("unknown sslcertmode value: %v", )
	}
}

func ( string) (uint16, error) {
	,  := strconv.ParseUint(, 10, 16)
	if  != nil {
		return 0, 
	}
	if  < 1 ||  > math.MaxUint16 {
		return 0, errors.New("outside range")
	}
	return uint16(), nil
}

func () *net.Dialer {
	// rely on GOLANG KeepAlive settings
	return &net.Dialer{}
}

func () *net.Resolver {
	return net.DefaultResolver
}

func ( string) (time.Duration, error) {
	,  := strconv.ParseInt(, 10, 64)
	if  != nil {
		return 0, 
	}
	if  < 0 {
		return 0, errors.New("negative timeout")
	}
	return time.Duration() * time.Second, nil
}

func ( time.Duration) DialFunc {
	 := makeDefaultDialer()
	.Timeout = 
	return .DialContext
}

var (
	// ErrReadOnlyConnection is returned when a read-write connection is required but the connection is read-only.
	ErrReadOnlyConnection = errors.New("read only connection")
	// ErrReadWriteConnection is returned when a read-only connection is required but the connection is read-write.
	ErrReadWriteConnection = errors.New("connection is not read only")
	// ErrPrimaryConnection is returned when a standby connection is required but the server is primary.
	ErrPrimaryConnection = errors.New("server is not in hot standby mode")
	// ErrStandbyConnection is returned when a primary connection is required but the server is in standby mode.
	ErrStandbyConnection = errors.New("server is in standby mode")
)

// ValidateConnectTargetSessionAttrsReadWrite is a ValidateConnectFunc that implements libpq compatible
// target_session_attrs=read-write.
func ( context.Context,  *PgConn) error {
	,  := .Exec(, "show transaction_read_only").ReadAll()
	if  != nil {
		return 
	}

	if string([0].Rows[0][0]) == "on" {
		return ErrReadOnlyConnection
	}

	return nil
}

// ValidateConnectTargetSessionAttrsReadOnly is a ValidateConnectFunc that implements libpq compatible
// target_session_attrs=read-only.
func ( context.Context,  *PgConn) error {
	,  := .Exec(, "show transaction_read_only").ReadAll()
	if  != nil {
		return 
	}

	if string([0].Rows[0][0]) != "on" {
		return ErrReadWriteConnection
	}

	return nil
}

// ValidateConnectTargetSessionAttrsStandby is a ValidateConnectFunc that implements libpq compatible
// target_session_attrs=standby.
func ( context.Context,  *PgConn) error {
	,  := .Exec(, "select pg_is_in_recovery()").ReadAll()
	if  != nil {
		return 
	}

	if string([0].Rows[0][0]) != "t" {
		return ErrPrimaryConnection
	}

	return nil
}

// ValidateConnectTargetSessionAttrsPrimary is a ValidateConnectFunc that implements libpq compatible
// target_session_attrs=primary.
func ( context.Context,  *PgConn) error {
	,  := .Exec(, "select pg_is_in_recovery()").ReadAll()
	if  != nil {
		return 
	}

	if string([0].Rows[0][0]) == "t" {
		return ErrStandbyConnection
	}

	return nil
}

// ValidateConnectTargetSessionAttrsPreferStandby is a ValidateConnectFunc that implements libpq compatible
// target_session_attrs=prefer-standby.
func ( context.Context,  *PgConn) error {
	,  := .Exec(, "select pg_is_in_recovery()").ReadAll()
	if  != nil {
		return 
	}

	if string([0].Rows[0][0]) != "t" {
		return &NotPreferredError{err: ErrPrimaryConnection}
	}

	return nil
}

func ( string) (uint32, error) {
	switch  {
	case "", "3.0":
		return pgproto3.ProtocolVersion30, nil
	case "3.2", "latest":
		return pgproto3.ProtocolVersion32, nil
	default:
		return 0, fmt.Errorf("invalid protocol version: %q", )
	}
}