package pg

import (
	
	
	
	
	
	
	
	
	
	
	

	
)

// Options contains database connection options.
type Options struct {
	// Network type, either tcp or unix.
	// Default is tcp.
	Network string
	// TCP host:port or Unix socket depending on Network.
	Addr string

	// Dialer creates new network connection and has priority over
	// Network and Addr options.
	Dialer func(ctx context.Context, network, addr string) (net.Conn, error)

	// Hook that is called after new connection is established
	// and user is authenticated.
	OnConnect func(ctx context.Context, cn *Conn) error

	User     string
	Password string
	Database string

	// ApplicationName is the application name. Used in logs on Pg side.
	// Only available from pg-9.0.
	ApplicationName string

	// TLS config for secure connections.
	TLSConfig *tls.Config

	// Dial timeout for establishing new connections.
	// Default is 5 seconds.
	DialTimeout time.Duration

	// Timeout for socket reads. If reached, commands will fail
	// with a timeout instead of blocking.
	ReadTimeout time.Duration
	// Timeout for socket writes. If reached, commands will fail
	// with a timeout instead of blocking.
	WriteTimeout time.Duration

	// Maximum number of retries before giving up.
	// Default is to not retry failed queries.
	MaxRetries int
	// Whether to retry queries cancelled because of statement_timeout.
	RetryStatementTimeout bool
	// Minimum backoff between each retry.
	// Default is 250 milliseconds; -1 disables backoff.
	MinRetryBackoff time.Duration
	// Maximum backoff between each retry.
	// Default is 4 seconds; -1 disables backoff.
	MaxRetryBackoff time.Duration

	// Maximum number of socket connections.
	// Default is 10 connections per every CPU as reported by runtime.NumCPU.
	PoolSize int
	// Minimum number of idle connections which is useful when establishing
	// new connection is slow.
	MinIdleConns int
	// Connection age at which client retires (closes) the connection.
	// It is useful with proxies like PgBouncer and HAProxy.
	// Default is to not close aged connections.
	MaxConnAge time.Duration
	// Time for which client waits for free connection if all
	// connections are busy before returning an error.
	// Default is 30 seconds if ReadTimeOut is not defined, otherwise,
	// ReadTimeout + 1 second.
	PoolTimeout time.Duration
	// Amount of time after which client closes idle connections.
	// Should be less than server's timeout.
	// Default is 5 minutes. -1 disables idle timeout check.
	IdleTimeout time.Duration
	// Frequency of idle checks made by idle connections reaper.
	// Default is 1 minute. -1 disables idle connections reaper,
	// but idle connections are still discarded by the client
	// if IdleTimeout is set.
	IdleCheckFrequency time.Duration
}

func ( *Options) () {
	if .Network == "" {
		.Network = "tcp"
	}

	if .Addr == "" {
		switch .Network {
		case "tcp":
			 := env("PGHOST", "localhost")
			 := env("PGPORT", "5432")
			.Addr = fmt.Sprintf("%s:%s", , )
		case "unix":
			.Addr = "/var/run/postgresql/.s.PGSQL.5432"
		}
	}

	if .DialTimeout == 0 {
		.DialTimeout = 5 * time.Second
	}
	if .Dialer == nil {
		.Dialer = func( context.Context, ,  string) (net.Conn, error) {
			 := &net.Dialer{
				Timeout:   .DialTimeout,
				KeepAlive: 5 * time.Minute,
			}
			return .DialContext(, , )
		}
	}

	if .User == "" {
		.User = env("PGUSER", "postgres")
	}

	if .Database == "" {
		.Database = env("PGDATABASE", "postgres")
	}

	if .PoolSize == 0 {
		.PoolSize = 10 * runtime.NumCPU()
	}

	if .PoolTimeout == 0 {
		if .ReadTimeout != 0 {
			.PoolTimeout = .ReadTimeout + time.Second
		} else {
			.PoolTimeout = 30 * time.Second
		}
	}

	if .IdleTimeout == 0 {
		.IdleTimeout = 5 * time.Minute
	}
	if .IdleCheckFrequency == 0 {
		.IdleCheckFrequency = time.Minute
	}

	switch .MinRetryBackoff {
	case -1:
		.MinRetryBackoff = 0
	case 0:
		.MinRetryBackoff = 250 * time.Millisecond
	}
	switch .MaxRetryBackoff {
	case -1:
		.MaxRetryBackoff = 0
	case 0:
		.MaxRetryBackoff = 4 * time.Second
	}
}

func (,  string) string {
	 := os.Getenv()
	if  != "" {
		return 
	}
	return 
}

// ParseURL parses an URL into options that can be used to connect to PostgreSQL.
func ( string) (*Options, error) {
	,  := url.Parse()
	if  != nil {
		return nil, 
	}

	// scheme
	if .Scheme != "postgres" && .Scheme != "postgresql" {
		return nil, errors.New("pg: invalid scheme: " + .Scheme)
	}

	// host and port
	 := &Options{
		Addr: .Host,
	}
	if !strings.Contains(.Addr, ":") {
		.Addr += ":5432"
	}

	// username and password
	if .User != nil {
		.User = .User.Username()

		if ,  := .User.Password();  {
			.Password = 
		}
	}

	if .User == "" {
		.User = "postgres"
	}

	// database
	if len(strings.Trim(.Path, "/")) > 0 {
		.Database = .Path[1:]
	} else {
		return nil, errors.New("pg: database name not provided")
	}

	// ssl mode
	,  := url.ParseQuery(.RawQuery)
	if  != nil {
		return nil, 
	}

	if ,  := ["sslmode"];  && len() > 0 {
		switch [0] {
		case "verify-ca", "verify-full":
			.TLSConfig = &tls.Config{}
		case "allow", "prefer", "require":
			.TLSConfig = &tls.Config{InsecureSkipVerify: true} //nolint
		case "disable":
			.TLSConfig = nil
		default:
			return nil, fmt.Errorf("pg: sslmode '%v' is not supported", [0])
		}
	} else {
		.TLSConfig = &tls.Config{InsecureSkipVerify: true} //nolint
	}

	delete(, "sslmode")

	if ,  := ["application_name"];  && len() > 0 {
		.ApplicationName = [0]
	}

	delete(, "application_name")

	if ,  := ["connect_timeout"];  && len() > 0 {
		,  := strconv.Atoi([0])
		if  != nil {
			return nil, fmt.Errorf("pg: cannot parse connect_timeout option as int")
		}
		.DialTimeout = time.Second * time.Duration()
	}

	delete(, "connect_timeout")

	if len() > 0 {
		return nil, errors.New("pg: options other than 'sslmode', 'application_name' and 'connect_timeout' are not supported")
	}

	return , nil
}

func ( *Options) () func(context.Context) (net.Conn, error) {
	return func( context.Context) (net.Conn, error) {
		return .Dialer(, .Network, .Addr)
	}
}

func ( *Options) *pool.ConnPool {
	return pool.NewConnPool(&pool.Options{
		Dialer:  .getDialer(),
		OnClose: terminateConn,

		PoolSize:           .PoolSize,
		MinIdleConns:       .MinIdleConns,
		MaxConnAge:         .MaxConnAge,
		PoolTimeout:        .PoolTimeout,
		IdleTimeout:        .IdleTimeout,
		IdleCheckFrequency: .IdleCheckFrequency,
	})
}