package pq

import (
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

	
	
)
Common error types
var (
	ErrNotSupported              = errors.New("pq: Unsupported command")
	ErrInFailedTransaction       = errors.New("pq: Could not complete operation in a failed transaction")
	ErrSSLNotSupported           = errors.New("pq: SSL is not enabled on the server")
	ErrSSLKeyHasWorldPermissions = errors.New("pq: Private key file has group or world access. Permissions should be u=rw (0600) or less")
	ErrCouldNotDetectUsername    = errors.New("pq: Could not detect default username. Please provide one explicitly")

	errUnexpectedReady = errors.New("unexpected ReadyForQuery")
	errNoRowsAffected  = errors.New("no RowsAffected available after the empty statement")
	errNoLastInsertID  = errors.New("no LastInsertId available after the empty statement")
)
Driver is the Postgres database driver.
type Driver struct{}
Open opens a new connection to the database. name is a connection string. Most users should only use it through database/sql package from the standard library.
func ( *Driver) ( string) (driver.Conn, error) {
	return Open()
}

func () {
	sql.Register("postgres", &Driver{})
}

server version in the same format as server_version_num, or 0 if unavailable
the current location based on the TimeZone value of the session, if available
	currentLocation *time.Location
}

type transactionStatus byte

const (
	txnStatusIdle                transactionStatus = 'I'
	txnStatusIdleInTransaction   transactionStatus = 'T'
	txnStatusInFailedTransaction transactionStatus = 'E'
)

func ( transactionStatus) () string {
	switch  {
	case txnStatusIdle:
		return "idle"
	case txnStatusIdleInTransaction:
		return "idle in transaction"
	case txnStatusInFailedTransaction:
		return "in a failed transaction"
	default:
		errorf("unknown transactionStatus %d", )
	}

	panic("not reached")
}
Dialer is the dialer interface. It can be used to obtain more control over how pq creates network connections.
type Dialer interface {
	Dial(network, address string) (net.Conn, error)
	DialTimeout(network, address string, timeout time.Duration) (net.Conn, error)
}
DialerContext is the context-aware dialer interface.
type DialerContext interface {
	DialContext(ctx context.Context, network, address string) (net.Conn, error)
}

type defaultDialer struct {
	d net.Dialer
}

func ( defaultDialer) (,  string) (net.Conn, error) {
	return .d.Dial(, )
}
func ( defaultDialer) (,  string,  time.Duration) (net.Conn, error) {
	,  := context.WithTimeout(context.Background(), )
	defer ()
	return .DialContext(, , )
}
func ( defaultDialer) ( context.Context, ,  string) (net.Conn, error) {
	return .d.DialContext(, , )
}

type conn struct {
	c         net.Conn
	buf       *bufio.Reader
	namei     int
	scratch   [512]byte
	txnStatus transactionStatus
	txnFinish func()
Save connection arguments to use during CancelRequest.
Cancellation key data for use with CancelRequest messages.
If true, this connection is bad and all public-facing functions should return ErrBadConn.
If set, this connection should never use the binary format when receiving query results from prepared statements. Only provided for debugging.
Whether to always send []byte parameters over as binary. Enables single round-trip mode for non-prepared Query calls.
If true this connection is in the middle of a COPY
Handle driver-side settings in parsed connection string.
func ( *conn) ( values) ( error) {
	 := func( string,  *bool) error {
		if ,  := [];  {
			if  == "yes" {
				* = true
			} else if  == "no" {
				* = false
			} else {
				return fmt.Errorf("unrecognized value %q for %s", , )
			}
		}
		return nil
	}

	 = ("disable_prepared_binary_result", &.disablePreparedBinaryResult)
	if  != nil {
		return 
	}
	return ("binary_parameters", &.binaryParameters)
}

if a password was supplied, do not process .pgpass
	if ,  := ["password"];  {
		return
	}
	 := os.Getenv("PGPASSFILE")
XXX this code doesn't work on Windows where the default filename is XXX %APPDATA%\postgresql\pgpass.conf Prefer $HOME over user.Current due to glibc bug: golang.org/issue/13470
		 := os.Getenv("HOME")
		if  == "" {
			,  := user.Current()
			if  != nil {
				return
			}
			 = .HomeDir
		}
		 = filepath.Join(, ".pgpass")
	}
	,  := os.Stat()
	if  != nil {
		return
	}
	 := .Mode()
XXX should warn about incorrect .pgpass permissions as psql does
		return
	}
	,  := os.Open()
	if  != nil {
		return
	}
	defer .Close()
	 := bufio.NewScanner(io.Reader())
	 := ["host"]
	,  := network()
	 := ["port"]
	 := ["dbname"]
From: https://github.com/tg/pgpass/blob/master/reader.go
	 := func( string) []string {
		 := make([]string, 0, 5)
		 := make([]rune, 0, len())

		var  bool
		for ,  := range  {
			switch {
			case :
				 = append(, )
				 = false
			case  == '\\':
				 = true
			case  == ':':
				 = append(, string())
				 = [:0]
			default:
				 = append(, )
			}
		}
		return append(, string())
	}
	for .Scan() {
		 := .Text()
		if len() == 0 || [0] == '#' {
			continue
		}
		 := ()
		if len() != 5 {
			continue
		}
		if ([0] == "*" || [0] ==  || ([0] == "localhost" && ( == "" ||  == "unix"))) && ([1] == "*" || [1] == ) && ([2] == "*" || [2] == ) && ([3] == "*" || [3] == ) {
			["password"] = [4]
			return
		}
	}
}

func ( *conn) ( byte) *writeBuf {
	.scratch[0] = 
	return &writeBuf{
		buf: .scratch[:5],
		pos: 1,
	}
}
Open opens a new connection to the database. dsn is a connection string. Most users should only use it through database/sql package from the standard library.
func ( string) ( driver.Conn,  error) {
	return DialOpen(defaultDialer{}, )
}
DialOpen opens a new connection to the database using a dialer.
func ( Dialer,  string) ( driver.Conn,  error) {
	,  := NewConnector()
	if  != nil {
		return nil, 
	}
	.dialer = 
	return .open(context.Background())
}

Handle any panics during connection initialization. Note that we specifically do *not* want to use errRecover(), as that would turn any connection errors into ErrBadConns, hiding the real error message from the user.
	defer errRecoverNoErrBadConn(&)

	 := .opts

	 = &conn{
		opts:   ,
		dialer: .dialer,
	}
	 = .handleDriverSettings()
	if  != nil {
		return nil, 
	}
	.handlePgpass()

	.c,  = dial(, .dialer, )
	if  != nil {
		return nil, 
	}

	 = .ssl()
	if  != nil {
		if .c != nil {
			.c.Close()
		}
		return nil, 
	}
cn.startup panics on error. Make sure we don't leak cn.c.
	 := true
	defer func() {
		if  {
			.c.Close()
		}
	}()

	.buf = bufio.NewReader(.c)
	.startup()
reset the deadline, in case one was set (see dial)
	if ,  := ["connect_timeout"];  &&  != "0" {
		 = .c.SetDeadline(time.Time{})
	}
	 = false
	return , 
}

func ( context.Context,  Dialer,  values) (net.Conn, error) {
SSL is not necessary or supported over UNIX domain sockets
	if  == "unix" {
		["sslmode"] = "disable"
	}
Zero or not specified means wait indefinitely.
	if ,  := ["connect_timeout"];  &&  != "0" {
		,  := strconv.ParseInt(, 10, 0)
		if  != nil {
			return nil, fmt.Errorf("invalid value for parameter connect_timeout: %s", )
		}
		 := time.Duration() * time.Second
connect_timeout should apply to the entire connection establishment procedure, so we both use a timeout for the TCP connection establishment and set a deadline for doing the initial handshake. The deadline is then reset after startup() is done.
		 := time.Now().Add()
		var  net.Conn
		if ,  := .(DialerContext);  {
			,  := context.WithTimeout(, )
			defer ()
			,  = .DialContext(, , )
		} else {
			,  = .DialTimeout(, , )
		}
		if  != nil {
			return nil, 
		}
		 = .SetDeadline()
		return , 
	}
	if ,  := .(DialerContext);  {
		return .DialContext(, , )
	}
	return .Dial(, )
}

func ( values) (string, string) {
	 := ["host"]

	if strings.HasPrefix(, "/") {
		 := path.Join(, ".s.PGSQL."+["port"])
		return "unix", 
	}

	return "tcp", net.JoinHostPort(, ["port"])
}

type values map[string]string
scanner implements a tokenizer for libpq-style option strings.
type scanner struct {
	s []rune
	i int
}
newScanner returns a new scanner initialized with the option string s.
func ( string) *scanner {
	return &scanner{[]rune(), 0}
}
Next returns the next rune. It returns 0, false if the end of the text has been reached.
func ( *scanner) () (rune, bool) {
	if .i >= len(.s) {
		return 0, false
	}
	 := .s[.i]
	.i++
	return , true
}
SkipSpaces returns the next non-whitespace rune. It returns 0, false if the end of the text has been reached.
func ( *scanner) () (rune, bool) {
	,  := .Next()
	for unicode.IsSpace() &&  {
		,  = .Next()
	}
	return , 
}
parseOpts parses the options from name and adds them to the values. The parsing code is based on conninfo_parse from libpq's fe-connect.c
func ( string,  values) error {
	 := newScanner()

	for {
		var (
			,  []rune
			                  rune
			                 bool
		)

		if ,  = .SkipSpaces(); ! {
			break
		}
Scan the key
		for !unicode.IsSpace() &&  != '=' {
			 = append(, )
			if ,  = .Next(); ! {
				break
			}
		}
Skip any whitespace if we're not at the = yet
		if  != '=' {
			,  = .SkipSpaces()
		}
The current character should be =
		if  != '=' || ! {
			return fmt.Errorf(`missing "=" after %q in connection info string"`, string())
		}
Skip any whitespace after the =
If we reach the end here, the last value is just an empty string as per libpq.
			[string()] = ""
			break
		}

		if  != '\'' {
			for !unicode.IsSpace() {
				if  == '\\' {
					if ,  = .Next(); ! {
						return fmt.Errorf(`missing character after backslash`)
					}
				}
				 = append(, )

				if ,  = .Next(); ! {
					break
				}
			}
		} else {
		:
			for {
				if ,  = .Next(); ! {
					return fmt.Errorf(`unterminated quoted string literal in connection string`)
				}
				switch  {
				case '\'':
					break 
				case '\\':
					, _ = .Next()
					fallthrough
				default:
					 = append(, )
				}
			}
		}

		[string()] = string()
	}

	return nil
}

func ( *conn) () bool {
	return .txnStatus == txnStatusIdleInTransaction ||
		.txnStatus == txnStatusInFailedTransaction
}

func ( *conn) ( bool) {
	if .isInTransaction() !=  {
		.bad = true
		errorf("unexpected transaction status %v", .txnStatus)
	}
}

func ( *conn) () ( driver.Tx,  error) {
	return .begin("")
}

func ( *conn) ( string) ( driver.Tx,  error) {
	if .bad {
		return nil, driver.ErrBadConn
	}
	defer .errRecover(&)

	.checkIsInTransaction(false)
	, ,  := .simpleExec("BEGIN" + )
	if  != nil {
		return nil, 
	}
	if  != "BEGIN" {
		.bad = true
		return nil, fmt.Errorf("unexpected command tag %s", )
	}
	if .txnStatus != txnStatusIdleInTransaction {
		.bad = true
		return nil, fmt.Errorf("unexpected transaction status %v", .txnStatus)
	}
	return , nil
}

func ( *conn) () {
	if  := .txnFinish;  != nil {
		()
	}
}

func ( *conn) () ( error) {
	defer .closeTxn()
	if .bad {
		return driver.ErrBadConn
	}
	defer .errRecover(&)

We don't want the client to think that everything is okay if it tries to commit a failed transaction. However, no matter what we return, database/sql will release this connection back into the free connection pool so we have to abort the current transaction here. Note that you would get the same behaviour if you issued a COMMIT in a failed transaction, so it's also the least surprising thing to do here.
	if .txnStatus == txnStatusInFailedTransaction {
		if  := .rollback();  != nil {
			return 
		}
		return ErrInFailedTransaction
	}

	, ,  := .simpleExec("COMMIT")
	if  != nil {
		if .isInTransaction() {
			.bad = true
		}
		return 
	}
	if  != "COMMIT" {
		.bad = true
		return fmt.Errorf("unexpected command tag %s", )
	}
	.checkIsInTransaction(false)
	return nil
}

func ( *conn) () ( error) {
	defer .closeTxn()
	if .bad {
		return driver.ErrBadConn
	}
	defer .errRecover(&)
	return .rollback()
}

func ( *conn) () ( error) {
	.checkIsInTransaction(true)
	, ,  := .simpleExec("ROLLBACK")
	if  != nil {
		if .isInTransaction() {
			.bad = true
		}
		return 
	}
	if  != "ROLLBACK" {
		return fmt.Errorf("unexpected command tag %s", )
	}
	.checkIsInTransaction(false)
	return nil
}

func ( *conn) () string {
	.namei++
	return strconv.FormatInt(int64(.namei), 10)
}

func ( *conn) ( string) ( driver.Result,  string,  error) {
	 := .writeBuf('Q')
	.string()
	.send()

	for {
		,  := .recv1()
		switch  {
		case 'C':
			,  = .parseComplete(.string())
		case 'Z':
			.processReadyForQuery()
			if  == nil &&  == nil {
				 = errUnexpectedReady
done
			return
		case 'E':
			 = parseError()
		case 'I':
			 = emptyRows
ignore any results
		default:
			.bad = true
			errorf("unknown response for simple query: %q", )
		}
	}
}

func ( *conn) ( string) ( *rows,  error) {
	defer .errRecover(&)

	 := .writeBuf('Q')
	.string()
	.send()

	for {
		,  := .recv1()
		switch  {
We allow queries which don't return any results through Query as well as Exec. We still have to give database/sql a rows object the user can close, though, to avoid connections from being leaked. A "rows" with done=true works fine for that purpose.
			if  != nil {
				.bad = true
				errorf("unexpected message %q in simple query execution", )
			}
			if  == nil {
				 = &rows{
					cn: ,
				}
Set the result and tag to the last command complete if there wasn't a query already run. Although queries usually return from here and cede control to Next, a query with zero results does not.
			if  == 'C' && .colNames == nil {
				.result, .tag = .parseComplete(.string())
			}
			.done = true
		case 'Z':
done
			return
		case 'E':
			 = nil
			 = parseError()
		case 'D':
			if  == nil {
				.bad = true
				errorf("unexpected DataRow in simple query execution")
the query didn't fail; kick off to Next
			.saveMessage(, )
			return
res might be non-nil here if we received a previous CommandComplete, but that's fine; just overwrite it
			 = &rows{cn: }
			.rowsHeader = parsePortalRowDescribe()
To work around a bug in QueryRow in Go 1.2 and earlier, wait until the first DataRow has been received.
		default:
			.bad = true
			errorf("unknown response for simple query: %q", )
		}
	}
}

type noRows struct{}

var emptyRows noRows

var _ driver.Result = noRows{}

func (noRows) () (int64, error) {
	return 0, errNoLastInsertID
}

func (noRows) () (int64, error) {
	return 0, errNoRowsAffected
}
Decides which column formats to use for a prepared statement. The input is an array of type oids, one element per result column.
func ( []fieldDesc,  bool) ( []format,  []byte) {
	if len() == 0 {
		return nil, colFmtDataAllText
	}

	 = make([]format, len())
	if  {
		return , colFmtDataAllText
	}

	 := true
	 := true
	for ,  := range  {
This is the list of types to use binary mode for when receiving them through a prepared statement. If a type appears in this list, it must also be implemented in binaryDecode in encode.go.
		case oid.T_bytea:
			fallthrough
		case oid.T_int8:
			fallthrough
		case oid.T_int4:
			fallthrough
		case oid.T_int2:
			fallthrough
		case oid.T_uuid:
			[] = formatBinary
			 = false

		default:
			 = false
		}
	}

	if  {
		return , colFmtDataAllBinary
	} else if  {
		return , colFmtDataAllText
	} else {
		 = make([]byte, 2+len()*2)
		binary.BigEndian.PutUint16(, uint16(len()))
		for ,  := range  {
			binary.BigEndian.PutUint16([2+*2:], uint16())
		}
		return , 
	}
}

func ( *conn) (,  string) *stmt {
	 := &stmt{cn: , name: }

	 := .writeBuf('P')
	.string(.name)
	.string()
	.int16(0)

	.next('D')
	.byte('S')
	.string(.name)

	.next('S')
	.send()

	.readParseResponse()
	.paramTyps, .colNames, .colTyps = .readStatementDescribeResponse()
	.colFmts, .colFmtData = decideColumnFormats(.colTyps, .disablePreparedBinaryResult)
	.readReadyForQuery()
	return 
}

func ( *conn) ( string) ( driver.Stmt,  error) {
	if .bad {
		return nil, driver.ErrBadConn
	}
	defer .errRecover(&)

	if len() >= 4 && strings.EqualFold([:4], "COPY") {
		,  := .prepareCopyIn()
		if  == nil {
			.inCopy = true
		}
		return , 
	}
	return .prepareTo(, .gname()), nil
}

Skip cn.bad return here because we always want to close a connection.
	defer .errRecover(&)
Ensure that cn.c.Close is always run. Since error handling is done with panics and cn.errRecover, the Close must be in a defer.
	defer func() {
		 := .c.Close()
		if  == nil {
			 = 
		}
	}()
Don't go through send(); ListenerConn relies on us not scribbling on the scratch buffer of this connection.
	return .sendSimpleMessage('X')
}
Implement the "Queryer" interface
func ( *conn) ( string,  []driver.Value) (driver.Rows, error) {
	return .query(, )
}

func ( *conn) ( string,  []driver.Value) ( *rows,  error) {
	if .bad {
		return nil, driver.ErrBadConn
	}
	if .inCopy {
		return nil, errCopyInProgress
	}
	defer .errRecover(&)
Check to see if we can use the "simpleQuery" interface, which is *much* faster than going through prepare/exec
	if len() == 0 {
		return .simpleQuery()
	}

	if .binaryParameters {
		.sendBinaryModeQuery(, )

		.readParseResponse()
		.readBindResponse()
		 := &rows{cn: }
		.rowsHeader = .readPortalDescribeResponse()
		.postExecuteWorkaround()
		return , nil
	}
	 := .prepareTo(, "")
	.exec()
	return &rows{
		cn:         ,
		rowsHeader: .rowsHeader,
	}, nil
}
Implement the optional "Execer" interface for one-shot queries
func ( *conn) ( string,  []driver.Value) ( driver.Result,  error) {
	if .bad {
		return nil, driver.ErrBadConn
	}
	defer .errRecover(&)
Check to see if we can use the "simpleExec" interface, which is *much* faster than going through prepare/exec
ignore commandTag, our caller doesn't care
		, ,  := .simpleExec()
		return , 
	}

	if .binaryParameters {
		.sendBinaryModeQuery(, )

		.readParseResponse()
		.readBindResponse()
		.readPortalDescribeResponse()
		.postExecuteWorkaround()
		, _,  = .readExecuteResponse("Execute")
		return , 
Use the unnamed statement to defer planning until bind time, or else value-based selectivity estimates cannot be used.
	 := .prepareTo(, "")
	,  := .Exec()
	if  != nil {
		panic()
	}
	return , 
}

func ( *conn) ( *writeBuf) {
	,  := .c.Write(.wrap())
	if  != nil {
		panic()
	}
}

func ( *conn) ( *writeBuf) error {
	,  := .c.Write((.wrap())[1:])
	return 
}
Send a message of type typ to the server on the other end of cn. The message should have no payload. This method does not use the scratch buffer.
func ( *conn) ( byte) ( error) {
	_,  = .c.Write([]byte{, '\x00', '\x00', '\x00', '\x04'})
	return 
}
saveMessage memorizes a message and its buffer in the conn struct. recvMessage will then return these values on the next call to it. This method is useful in cases where you have to see what the next message is going to be (e.g. to see whether it's an error or not) but you can't handle the message yourself.
func ( *conn) ( byte,  *readBuf) {
	if .saveMessageType != 0 {
		.bad = true
		errorf("unexpected saveMessageType %d", .saveMessageType)
	}
	.saveMessageType = 
	.saveMessageBuffer = *
}
recvMessage receives any message from the backend, or returns an error if a problem occurred while reading the message.
workaround for a QueryRow bug, see exec
	if .saveMessageType != 0 {
		 := .saveMessageType
		* = .saveMessageBuffer
		.saveMessageType = 0
		.saveMessageBuffer = nil
		return , nil
	}

	 := .scratch[:5]
	,  := io.ReadFull(.buf, )
	if  != nil {
		return 0, 
	}
read the type and length of the message that follows
	 := [0]
	 := int(binary.BigEndian.Uint32([1:])) - 4
	var  []byte
	if  <= len(.scratch) {
		 = .scratch[:]
	} else {
		 = make([]byte, )
	}
	_,  = io.ReadFull(.buf, )
	if  != nil {
		return 0, 
	}
	* = 
	return , nil
}
recv receives a message from the backend, but if an error happened while reading the message or the received message was an ErrorResponse, it panics. NoticeResponses are ignored. This function should generally be used only during the startup sequence.
func ( *conn) () ( byte,  *readBuf) {
	for {
		var  error
		 = &readBuf{}
		,  = .recvMessage()
		if  != nil {
			panic()
		}
		switch  {
		case 'E':
			panic(parseError())
ignore
		default:
			return
		}
	}
}
recv1Buf is exactly equivalent to recv1, except it uses a buffer supplied by the caller to avoid an allocation.
func ( *conn) ( *readBuf) byte {
	for {
		,  := .recvMessage()
		if  != nil {
			panic()
		}

		switch  {
ignore
		case 'S':
			.processParameterStatus()
		default:
			return 
		}
	}
}
recv1 receives a message from the backend, panicking if an error occurs while attempting to read it. All asynchronous messages are ignored, with the exception of ErrorResponse.
func ( *conn) () ( byte,  *readBuf) {
	 = &readBuf{}
	 = .recv1Buf()
	return , 
}

func ( *conn) ( values) error {
	,  := ssl()
	if  != nil {
		return 
	}

Nothing to do
		return nil
	}

	 := .writeBuf(0)
	.int32(80877103)
	if  = .sendStartupPacket();  != nil {
		return 
	}

	 := .scratch[:1]
	_,  = io.ReadFull(.c, )
	if  != nil {
		return 
	}

	if [0] != 'S' {
		return ErrSSLNotSupported
	}

	.c,  = (.c)
	return 
}
isDriverSetting returns true iff a setting is purely for configuring the driver's options and should not be sent to the server in the connection startup packet.
func ( string) bool {
	switch  {
	case "host", "port":
		return true
	case "password":
		return true
	case "sslmode", "sslcert", "sslkey", "sslrootcert":
		return true
	case "fallback_application_name":
		return true
	case "connect_timeout":
		return true
	case "disable_prepared_binary_result":
		return true
	case "binary_parameters":
		return true

	default:
		return false
	}
}

func ( *conn) ( values) {
	 := .writeBuf(0)
Send the backend the name of the database we want to connect to, and the user we want to connect as. Additionally, we send over any run-time parameters potentially included in the connection string. If the server doesn't recognize any of them, it will reply with an error.
	for ,  := range  {
skip options which can't be run-time parameters
			continue
The protocol requires us to supply the database name as "database" instead of "dbname".
		if  == "dbname" {
			 = "database"
		}
		.string()
		.string()
	}
	.string("")
	if  := .sendStartupPacket();  != nil {
		panic()
	}

	for {
		,  := .recv()
		switch  {
		case 'K':
			.processBackendKeyData()
		case 'S':
			.processParameterStatus()
		case 'R':
			.auth(, )
		case 'Z':
			.processReadyForQuery()
			return
		default:
			errorf("unknown response for startup: %q", )
		}
	}
}

func ( *conn) ( *readBuf,  values) {
	switch  := .int32();  {
OK
	case 3:
		 := .writeBuf('p')
		.string(["password"])
		.send()

		,  := .recv()
		if  != 'R' {
			errorf("unexpected password response: %q", )
		}

		if .int32() != 0 {
			errorf("unexpected authentication response: %q", )
		}
	case 5:
		 := string(.next(4))
		 := .writeBuf('p')
		.string("md5" + md5s(md5s(["password"]+["user"])+))
		.send()

		,  := .recv()
		if  != 'R' {
			errorf("unexpected password response: %q", )
		}

		if .int32() != 0 {
			errorf("unexpected authentication response: %q", )
		}
	case 10:
		 := scram.NewClient(sha256.New, ["user"], ["password"])
		.Step(nil)
		if .Err() != nil {
			errorf("SCRAM-SHA-256 error: %s", .Err().Error())
		}
		 := .Out()

		 := .writeBuf('p')
		.string("SCRAM-SHA-256")
		.int32(len())
		.bytes()
		.send()

		,  := .recv()
		if  != 'R' {
			errorf("unexpected password response: %q", )
		}

		if .int32() != 11 {
			errorf("unexpected authentication response: %q", )
		}

		 := .next(len(*))
		.Step()
		if .Err() != nil {
			errorf("SCRAM-SHA-256 error: %s", .Err().Error())
		}

		 = .Out()
		 = .writeBuf('p')
		.bytes()
		.send()

		,  = .recv()
		if  != 'R' {
			errorf("unexpected password response: %q", )
		}

		if .int32() != 12 {
			errorf("unexpected authentication response: %q", )
		}

		 = .next(len(*))
		.Step()
		if .Err() != nil {
			errorf("SCRAM-SHA-256 error: %s", .Err().Error())
		}

	default:
		errorf("unknown authentication response: %d", )
	}
}

type format int

const formatText format = 0
const formatBinary format = 1
One result-column format code with the value 1 (i.e. all binary).
var colFmtDataAllBinary = []byte{0, 1, 0, 1}
No result-column format codes (i.e. all text).
var colFmtDataAllText = []byte{0, 0}

type stmt struct {
	cn   *conn
	name string
	rowsHeader
	colFmtData []byte
	paramTyps  []oid.Oid
	closed     bool
}

func ( *stmt) () ( error) {
	if .closed {
		return nil
	}
	if .cn.bad {
		return driver.ErrBadConn
	}
	defer .cn.errRecover(&)

	 := .cn.writeBuf('C')
	.byte('S')
	.string(.name)
	.cn.send()

	.cn.send(.cn.writeBuf('S'))

	,  := .cn.recv1()
	if  != '3' {
		.cn.bad = true
		errorf("unexpected close response: %q", )
	}
	.closed = true

	,  := .cn.recv1()
	if  != 'Z' {
		.cn.bad = true
		errorf("expected ready for query, but got: %q", )
	}
	.cn.processReadyForQuery()

	return nil
}

func ( *stmt) ( []driver.Value) ( driver.Rows,  error) {
	if .cn.bad {
		return nil, driver.ErrBadConn
	}
	defer .cn.errRecover(&)

	.exec()
	return &rows{
		cn:         .cn,
		rowsHeader: .rowsHeader,
	}, nil
}

func ( *stmt) ( []driver.Value) ( driver.Result,  error) {
	if .cn.bad {
		return nil, driver.ErrBadConn
	}
	defer .cn.errRecover(&)

	.exec()
	, _,  = .cn.readExecuteResponse("simple query")
	return , 
}

func ( *stmt) ( []driver.Value) {
	if len() >= 65536 {
		errorf("got %d parameters but PostgreSQL only supports 65535 parameters", len())
	}
	if len() != len(.paramTyps) {
		errorf("got %d parameters but the statement requires %d", len(), len(.paramTyps))
	}

	 := .cn
	 := .writeBuf('B')
	.byte(0) // unnamed portal
	.string(.name)

	if .binaryParameters {
		.sendBinaryParameters(, )
	} else {
		.int16(0)
		.int16(len())
		for ,  := range  {
			if  == nil {
				.int32(-1)
			} else {
				 := encode(&.parameterStatus, , .paramTyps[])
				.int32(len())
				.bytes()
			}
		}
	}
	.bytes(.colFmtData)

	.next('E')
	.byte(0)
	.int32(0)

	.next('S')
	.send()

	.readBindResponse()
	.postExecuteWorkaround()

}

func ( *stmt) () int {
	return len(.paramTyps)
}
parseComplete parses the "command tag" from a CommandComplete message, and returns the number of rows affected (if applicable) and a string identifying only the command that was executed, e.g. "ALTER TABLE". If the command tag could not be parsed, parseComplete panics.
func ( *conn) ( string) (driver.Result, string) {
	 := []string{
INSERT is handled below
		"UPDATE ",
		"DELETE ",
		"FETCH ",
		"MOVE ",
		"COPY ",
	}

	var  *string
	for ,  := range  {
		if strings.HasPrefix(, ) {
			 := [len():]
			 = &
			 = [:len()-1]
			break
		}
INSERT also includes the oid of the inserted row in its command tag. Oids in user tables are deprecated, and the oid is only returned when exactly one row is inserted, so it's unlikely to be of value to any real-world application and we can ignore it.
	if  == nil && strings.HasPrefix(, "INSERT ") {
		 := strings.Split(, " ")
		if len() != 3 {
			.bad = true
			errorf("unexpected INSERT command tag %s", )
		}
		 = &[len()-1]
		 = "INSERT"
There should be no affected rows attached to the tag, just return it
	if  == nil {
		return driver.RowsAffected(0), 
	}
	,  := strconv.ParseInt(*, 10, 64)
	if  != nil {
		.bad = true
		errorf("could not parse commandTag: %s", )
	}
	return driver.RowsAffected(), 
}

type rowsHeader struct {
	colNames []string
	colTyps  []fieldDesc
	colFmts  []format
}

type rows struct {
	cn     *conn
	finish func()
	rowsHeader
	done   bool
	rb     readBuf
	result driver.Result
	tag    string

	next *rowsHeader
}

func ( *rows) () error {
	if  := .finish;  != nil {
		defer ()
no need to look at cn.bad as Next() will
	for {
		 := .Next(nil)
		switch  {
		case nil:
rs.Next can return io.EOF on both 'Z' (ready for query) and 'T' (row description, used with HasNextResultSet). We need to fetch messages until we hit a 'Z', which is done by waiting for done to be set.
			if .done {
				return nil
			}
		default:
			return 
		}
	}
}

func ( *rows) () []string {
	return .colNames
}

func ( *rows) () driver.Result {
	if .result == nil {
		return emptyRows
	}
	return .result
}

func ( *rows) () string {
	return .tag
}

func ( *rows) ( []driver.Value) ( error) {
	if .done {
		return io.EOF
	}

	 := .cn
	if .bad {
		return driver.ErrBadConn
	}
	defer .errRecover(&)

	for {
		 := .recv1Buf(&.rb)
		switch  {
		case 'E':
			 = parseError(&.rb)
		case 'C', 'I':
			if  == 'C' {
				.result, .tag = .parseComplete(.rb.string())
			}
			continue
		case 'Z':
			.processReadyForQuery(&.rb)
			.done = true
			if  != nil {
				return 
			}
			return io.EOF
		case 'D':
			 := .rb.int16()
			if  != nil {
				.bad = true
				errorf("unexpected DataRow after error %s", )
			}
			if  < len() {
				 = [:]
			}
			for  := range  {
				 := .rb.int32()
				if  == -1 {
					[] = nil
					continue
				}
				[] = decode(&.parameterStatus, .rb.next(), .colTyps[].OID, .colFmts[])
			}
			return
		case 'T':
			 := parsePortalRowDescribe(&.rb)
			.next = &
			return io.EOF
		default:
			errorf("unexpected message after execute: %q", )
		}
	}
}

func ( *rows) () bool {
	 := .next != nil && !.done
	return 
}

func ( *rows) () error {
	if .next == nil {
		return io.EOF
	}
	.rowsHeader = *.next
	.next = nil
	return nil
}
QuoteIdentifier quotes an "identifier" (e.g. a table or a column name) to be used as part of an SQL statement. For example: tblname := "my_table" data := "my_data" quoted := pq.QuoteIdentifier(tblname) err := db.Exec(fmt.Sprintf("INSERT INTO %s VALUES ($1)", quoted), data) Any double quotes in name will be escaped. The quoted identifier will be case sensitive when used in a query. If the input string contains a zero byte, the result will be truncated immediately before it.
func ( string) string {
	 := strings.IndexRune(, 0)
	if  > -1 {
		 = [:]
	}
	return `"` + strings.Replace(, `"`, `""`, -1) + `"`
}
QuoteLiteral quotes a 'literal' (e.g. a parameter, often used to pass literal to DDL and other statements that do not accept parameters) to be used as part of an SQL statement. For example: exp_date := pq.QuoteLiteral("2023-01-05 15:00:00Z") err := db.Exec(fmt.Sprintf("CREATE ROLE my_user VALID UNTIL %s", exp_date)) Any single quotes in name will be escaped. Any backslashes (i.e. "\") will be replaced by two backslashes (i.e. "\\") and the C-style escape identifier that PostgreSQL provides ('E') will be prepended to the string.
This follows the PostgreSQL internal algorithm for handling quoted literals from libpq, which can be found in the "PQEscapeStringInternal" function, which is found in the libpq/fe-exec.c source file: https://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/interfaces/libpq/fe-exec.c substitute any single-quotes (') with two single-quotes ('')
determine if the string has any backslashes (\) in it. if it does, replace any backslashes (\) with two backslashes (\\) then, we need to wrap the entire string with a PostgreSQL C-style escape. Per how "PQEscapeStringInternal" handles this case, we also add a space before the "E"
	if strings.Contains(, `\`) {
		 = strings.Replace(, `\`, `\\`, -1)
		 = ` E'` +  + `'`
otherwise, we can just wrap the literal with a pair of single quotes
		 = `'` +  + `'`
	}
	return 
}

func ( string) string {
	 := md5.New()
	.Write([]byte())
	return fmt.Sprintf("%x", .Sum(nil))
}

Do one pass over the parameters to see if we're going to send any of them over in binary. If we are, create a paramFormats array at the same time.
	var  []int
	for ,  := range  {
		,  := .([]byte)
		if  {
			if  == nil {
				 = make([]int, len())
			}
			[] = 1
		}
	}
	if  == nil {
		.int16(0)
	} else {
		.int16(len())
		for ,  := range  {
			.int16()
		}
	}

	.int16(len())
	for ,  := range  {
		if  == nil {
			.int32(-1)
		} else {
			 := binaryEncode(&.parameterStatus, )
			.int32(len())
			.bytes()
		}
	}
}

func ( *conn) ( string,  []driver.Value) {
	if len() >= 65536 {
		errorf("got %d parameters but PostgreSQL only supports 65535 parameters", len())
	}

	 := .writeBuf('P')
	.byte(0) // unnamed statement
	.string()
	.int16(0)

	.next('B')
	.int16(0) // unnamed portal and statement
	.sendBinaryParameters(, )
	.bytes(colFmtDataAllText)

	.next('D')
	.byte('P')
	.byte(0) // unnamed portal

	.next('E')
	.byte(0)
	.int32(0)

	.next('S')
	.send()
}

func ( *conn) ( *readBuf) {
	var  error

	 := .string()
	switch  {
	case "server_version":
		var  int
		var  int
		var  int
		_,  = fmt.Sscanf(.string(), "%d.%d.%d", &, &, &)
		if  == nil {
			.parameterStatus.serverVersion = *10000 + *100 + 
		}

	case "TimeZone":
		.parameterStatus.currentLocation,  = time.LoadLocation(.string())
		if  != nil {
			.parameterStatus.currentLocation = nil
		}

ignore
	}
}

func ( *conn) ( *readBuf) {
	.txnStatus = transactionStatus(.byte())
}

func ( *conn) () {
	,  := .recv1()
	switch  {
	case 'Z':
		.processReadyForQuery()
		return
	default:
		.bad = true
		errorf("unexpected message %q; expected ReadyForQuery", )
	}
}

func ( *conn) ( *readBuf) {
	.processID = .int32()
	.secretKey = .int32()
}

func ( *conn) () {
	,  := .recv1()
	switch  {
	case '1':
		return
	case 'E':
		 := parseError()
		.readReadyForQuery()
		panic()
	default:
		.bad = true
		errorf("unexpected Parse response %q", )
	}
}

func ( *conn) () ( []oid.Oid,  []string,  []fieldDesc) {
	for {
		,  := .recv1()
		switch  {
		case 't':
			 := .int16()
			 = make([]oid.Oid, )
			for  := range  {
				[] = .oid()
			}
		case 'n':
			return , nil, nil
		case 'T':
			,  = parseStatementRowDescribe()
			return , , 
		case 'E':
			 := parseError()
			.readReadyForQuery()
			panic()
		default:
			.bad = true
			errorf("unexpected Describe statement response %q", )
		}
	}
}

func ( *conn) () rowsHeader {
	,  := .recv1()
	switch  {
	case 'T':
		return parsePortalRowDescribe()
	case 'n':
		return rowsHeader{}
	case 'E':
		 := parseError()
		.readReadyForQuery()
		panic()
	default:
		.bad = true
		errorf("unexpected Describe response %q", )
	}
	panic("not reached")
}

func ( *conn) () {
	,  := .recv1()
	switch  {
	case '2':
		return
	case 'E':
		 := parseError()
		.readReadyForQuery()
		panic()
	default:
		.bad = true
		errorf("unexpected Bind response %q", )
	}
}

Work around a bug in sql.DB.QueryRow: in Go 1.2 and earlier it ignores any errors from rows.Next, which masks errors that happened during the execution of the query. To avoid the problem in common cases, we wait here for one more message from the database. If it's not an error the query will likely succeed (or perhaps has already, if it's a CommandComplete), so we push the message into the conn struct; recv1 will return it as the next message for rows.Next or rows.Close. However, if it's an error, we wait until ReadyForQuery and then return the error to our caller.
	for {
		,  := .recv1()
		switch  {
		case 'E':
			 := parseError()
			.readReadyForQuery()
			panic()
the query didn't fail, but we can't process this message
			.saveMessage(, )
			return
		default:
			.bad = true
			errorf("unexpected message during extended query execution: %q", )
		}
	}
}
Only for Exec(), since we ignore the returned data
func ( *conn) ( string) ( driver.Result,  string,  error) {
	for {
		,  := .recv1()
		switch  {
		case 'C':
			if  != nil {
				.bad = true
				errorf("unexpected CommandComplete after error %s", )
			}
			,  = .parseComplete(.string())
		case 'Z':
			.processReadyForQuery()
			if  == nil &&  == nil {
				 = errUnexpectedReady
			}
			return , , 
		case 'E':
			 = parseError()
		case 'T', 'D', 'I':
			if  != nil {
				.bad = true
				errorf("unexpected %q after error %s", , )
			}
			if  == 'I' {
				 = emptyRows
ignore any results
		default:
			.bad = true
			errorf("unknown %s response: %q", , )
		}
	}
}

func ( *readBuf) ( []string,  []fieldDesc) {
	 := .int16()
	 = make([]string, )
	 = make([]fieldDesc, )
	for  := range  {
		[] = .string()
		.next(6)
		[].OID = .oid()
		[].Len = .int16()
format code not known when describing a statement; always 0
		.next(2)
	}
	return
}

func ( *readBuf) rowsHeader {
	 := .int16()
	 := make([]string, )
	 := make([]format, )
	 := make([]fieldDesc, )
	for  := range  {
		[] = .string()
		.next(6)
		[].OID = .oid()
		[].Len = .int16()
		[].Mod = .int32()
		[] = format(.int16())
	}
	return rowsHeader{
		colNames: ,
		colFmts:  ,
		colTyps:  ,
	}
}
parseEnviron tries to mimic some of libpq's environment handling To ease testing, it does not directly reference os.Environ, but is designed to accept its output. Environment-set connection information is intended to have a higher precedence than a library default but lower than any explicitly passed information (such as in the URL or connection string).
func ( []string) ( map[string]string) {
	 = make(map[string]string)

	for ,  := range  {
		 := strings.SplitN(, "=", 2)

		 := func( string) {
			[] = [1]
		}
		 := func() {
			panic(fmt.Sprintf("setting %v not supported", [0]))
		}
The order of these is the same as is seen in the PostgreSQL 9.1 manual. Unsupported but well-defined keys cause a panic; these should be unset prior to execution. Options which pq expects to be set to a certain value are allowed, but must be set to that value if present (they can, of course, be absent).
		switch [0] {
		case "PGHOST":
			("host")
		case "PGHOSTADDR":
			()
		case "PGPORT":
			("port")
		case "PGDATABASE":
			("dbname")
		case "PGUSER":
			("user")
		case "PGPASSWORD":
			("password")
		case "PGSERVICE", "PGSERVICEFILE", "PGREALM":
			()
		case "PGOPTIONS":
			("options")
		case "PGAPPNAME":
			("application_name")
		case "PGSSLMODE":
			("sslmode")
		case "PGSSLCERT":
			("sslcert")
		case "PGSSLKEY":
			("sslkey")
		case "PGSSLROOTCERT":
			("sslrootcert")
		case "PGREQUIRESSL", "PGSSLCRL":
			()
		case "PGREQUIREPEER":
			()
		case "PGKRBSRVNAME", "PGGSSLIB":
			()
		case "PGCONNECT_TIMEOUT":
			("connect_timeout")
		case "PGCLIENTENCODING":
			("client_encoding")
		case "PGDATESTYLE":
			("datestyle")
		case "PGTZ":
			("timezone")
		case "PGGEQO":
			("geqo")
		case "PGSYSCONFDIR", "PGLOCALEDIR":
			()
		}
	}

	return 
}
isUTF8 returns whether name is a fuzzy variation of the string "UTF-8".
Recognize all sorts of silly things as "UTF-8", like Postgres does
	 := strings.Map(alnumLowerASCII, )
	return  == "utf8" ||  == "unicode"
}

func ( rune) rune {
	if 'A' <=  &&  <= 'Z' {
		return  + ('a' - 'A')
	}
	if 'a' <=  &&  <= 'z' || '0' <=  &&  <= '9' {
		return 
	}
	return -1 // discard