Documentation
¶
Overview ¶
Package pg is a pure-Go (cgo-free), interpreter-independent reimplementation of the deterministic core of Ruby's pg gem — the PostgreSQL v3 frontend/backend wire-protocol codec, the OID type decoders/encoders, and the PG::Result / PG::Connection value surface.
The library owns everything that is a pure function of bytes: encoding the frontend messages a client sends (StartupMessage, Query, the extended-query Parse/Bind/Describe/Execute/Sync suite, the SCRAM-SHA-256 / MD5 authentication math), decoding the backend messages a server replies with, mapping column OIDs to Ruby values (matching PG::TextDecoder / PG::BinaryDecoder), and the escaping helpers. The TCP/TLS socket is a *host seam*: a Conn is driven over any io.ReadWriter (or a RoundTripper), exactly as the go-ruby net-* libms inject their transport. No live PostgreSQL server is required to exercise the codec — canned backend byte streams decode to the same values a real server would produce.
Index ¶
- Constants
- func DecodeBinary(oid OID, raw []byte) (any, error)
- func DecodeText(oid OID, raw []byte) (any, error)
- func EncodeBind(portal, stmt string, params []BindParam, resultFormats []Format) []byte
- func EncodeCancelRequest(processID, secretKey int32) []byte
- func EncodeClosePortal(name string) []byte
- func EncodeCloseStatement(name string) []byte
- func EncodeCopyData(data []byte) []byte
- func EncodeCopyDone() []byte
- func EncodeCopyFail(reason string) []byte
- func EncodeDescribePortal(name string) []byte
- func EncodeDescribeStatement(name string) []byte
- func EncodeExecute(portal string, maxRows int32) []byte
- func EncodeFlush() []byte
- func EncodeParam(v any) ([]byte, error)
- func EncodeParse(name, sql string, paramOIDs []uint32) []byte
- func EncodePassword(password string) []byte
- func EncodeQuery(sql string) []byte
- func EncodeSASLInitialResponse(mechanism string, initial []byte) []byte
- func EncodeSASLResponse(data []byte) []byte
- func EncodeSSLRequest() []byte
- func EncodeStartup(params StartupParams) []byte
- func EncodeSync() []byte
- func EncodeTerminate() []byte
- func EscapeIdentifier(s string) string
- func EscapeLiteral(s string) string
- func EscapeString(s string) string
- func MD5Password(user, password string, salt []byte) string
- func ParseBindComplete(m Message) error
- func ParseCloseComplete(m Message) error
- func ParseCommandComplete(m Message) (string, error)
- func ParseCopyData(m Message) ([]byte, error)
- func ParseCopyDone(m Message) error
- func ParseEmptyQueryResponse(m Message) error
- func ParseNoData(m Message) error
- func ParseParseComplete(m Message) error
- func ParsePortalSuspended(m Message) error
- func QuoteIdent(s string) string
- type AuthType
- type Authentication
- type Authenticator
- type BackendKeyData
- type BindParam
- type Conn
- func (c *Conn) BackendKey() (*BackendKeyData, bool)
- func (c *Conn) CancelRequest() ([]byte, error)
- func (c *Conn) EscapeIdentifier(s string) string
- func (c *Conn) EscapeLiteral(s string) string
- func (c *Conn) EscapeString(s string) string
- func (c *Conn) Exec(sql string) (*Result, error)
- func (c *Conn) ExecParams(sql string, args ...any) (*Result, error)
- func (c *Conn) ExecPrepared(name string, args ...any) (*Result, error)
- func (c *Conn) OnNotice(fn func(*ErrorFields))
- func (c *Conn) OnNotification(fn func(*NotificationResponse))
- func (c *Conn) Parameter(name string) (string, bool)
- func (c *Conn) Prepare(name, sql string, paramOIDs []uint32) error
- func (c *Conn) QuoteIdent(s string) string
- func (c *Conn) Startup(auth Authenticator) error
- func (c *Conn) Terminate() error
- func (c *Conn) TransactionStatus() TransactionStatus
- type CopyResponse
- type DataRow
- type Error
- type ErrorFields
- type FieldDescription
- type Format
- type Message
- type NotificationResponse
- type OID
- type ParameterDescription
- type ParameterStatus
- type PasswordAuthenticator
- type Result
- func (r *Result) CmdStatus() string
- func (r *Result) CmdTuples() int
- func (r *Result) Each(fn func(map[string]any) error) error
- func (r *Result) Fields() []string
- func (r *Result) Fmod(i int) (int32, error)
- func (r *Result) Fname(i int) (string, error)
- func (r *Result) Fnumber(name string) int
- func (r *Result) Ftype(i int) (OID, error)
- func (r *Result) Getisnull(row, col int) (bool, error)
- func (r *Result) Getvalue(row, col int) (any, error)
- func (r *Result) GetvalueRaw(row, col int) ([]byte, error)
- func (r *Result) Nfields() int
- func (r *Result) Ntuples() int
- func (r *Result) Tuple(i int) (map[string]any, error)
- func (r *Result) Values() [][]any
- type RoundTripper
- type RowDescription
- type SCRAMClient
- type StartupParams
- type TransactionStatus
Constants ¶
const ( AuthOK = AuthType(authOK) AuthKerberosV5 = AuthType(authKerberosV5) AuthCleartextPassword = AuthType(authCleartextPassword) AuthMD5Password = AuthType(authMD5Password) AuthSCMCredential = AuthType(authSCMCredential) AuthGSS = AuthType(authGSS) AuthGSSContinue = AuthType(authGSSContinue) AuthSSPI = AuthType(authSSPI) AuthSASL = AuthType(authSASL) AuthSASLContinue = AuthType(authSASLContinue) AuthSASLFinal = AuthType(authSASLFinal) )
Exported AuthType values mirror the protocol sub-codes.
const ( FieldSeverity = 'S' FieldSeverityNonLocal = 'V' // non-localized severity (PG 9.6+) FieldSQLState = 'C' FieldMessage = 'M' FieldDetail = 'D' FieldHint = 'H' FieldPosition = 'P' FieldInternalPosition = 'p' FieldInternalQuery = 'q' FieldWhere = 'W' FieldSchemaName = 's' FieldTableName = 't' FieldColumnName = 'c' FieldDataTypeName = 'd' FieldConstraintName = 'n' FieldFile = 'F' FieldLine = 'L' FieldRoutine = 'R' )
Field-type bytes (see the PostgreSQL protocol's Error and Notice Message Fields). These mirror PG::Result's PG_DIAG_* constants.
const SCRAMMechanism = "SCRAM-SHA-256"
SCRAMMechanism is the name of the SCRAM mechanism this package implements.
Variables ¶
This section is empty.
Functions ¶
func DecodeBinary ¶
DecodeBinary decodes a non-NULL binary-format value of the given OID. Unknown OIDs fall back to the raw bytes as a string.
func DecodeText ¶
DecodeText decodes a non-NULL text-format value of the given OID. Unknown OIDs fall back to the raw string, exactly as PG::TextDecoder::String would.
func EncodeBind ¶
EncodeBind builds a Bind message binding a prepared statement to a portal. The parameter formats are emitted per-parameter; the result-column formats request text or binary for each returned column (an empty slice means "all text", a single element means "apply to all").
func EncodeCancelRequest ¶
EncodeCancelRequest builds the untyped CancelRequest (magic 80877102) carrying the process ID and secret key from a prior BackendKeyData.
func EncodeClosePortal ¶
EncodeClosePortal builds a Close for a portal.
func EncodeCloseStatement ¶
EncodeCloseStatement builds a Close for a prepared statement.
func EncodeCopyData ¶
EncodeCopyData wraps a chunk of COPY payload.
func EncodeCopyFail ¶
EncodeCopyFail aborts a COPY-in with a diagnostic message.
func EncodeDescribePortal ¶
EncodeDescribePortal builds a Describe for a portal, eliciting a RowDescription (or NoData).
func EncodeDescribeStatement ¶
EncodeDescribeStatement builds a Describe for a prepared statement, eliciting a ParameterDescription and a RowDescription (or NoData).
func EncodeExecute ¶
EncodeExecute builds an Execute for a portal. maxRows == 0 means "fetch all"; a positive limit makes the server reply with PortalSuspended once reached.
func EncodeFlush ¶
func EncodeFlush() []byte
EncodeFlush builds a Flush message, forcing the server to send any buffered output without ending the transaction cycle.
func EncodeParam ¶
EncodeParam renders v as the text bytes of a query parameter. Supported Go types: nil, bool, all signed/unsigned integers, *big.Int, float32/float64, string, []byte (bytea, hex-encoded), time.Time, *big.Rat (numeric), and []any (a PostgreSQL array literal). A nil result means SQL NULL.
func EncodeParse ¶
EncodeParse builds a Parse message: the destination prepared-statement name (empty for the unnamed statement), the query text, and the OIDs of any parameter types the client wishes to pin (an OID of 0 lets the server infer).
func EncodePassword ¶
EncodePassword builds a PasswordMessage carrying a (possibly MD5- or cleartext-) password string. It is also the envelope PostgreSQL reuses for SASL; see EncodeSASLInitialResponse / EncodeSASLResponse for those.
func EncodeSASLInitialResponse ¶
EncodeSASLInitialResponse builds the first SASL message: the selected mechanism name, then an Int32 length-prefixed client-first message (or -1 when absent).
func EncodeSASLResponse ¶
EncodeSASLResponse builds a subsequent SASL message (the client-final message body, with no length prefix — the frame length delimits it).
func EncodeSSLRequest ¶
func EncodeSSLRequest() []byte
EncodeSSLRequest builds the untyped SSLRequest (magic 80877103). The server answers with a single byte 'S' (proceed with TLS) or 'N' (plaintext).
func EncodeStartup ¶
func EncodeStartup(params StartupParams) []byte
EncodeStartup builds an untyped StartupMessage: the protocol version followed by NUL-terminated key/value C strings, then a final NUL. "user" is always emitted first (PostgreSQL requires it and libpq places it first); the remaining keys follow in sorted order for a deterministic byte stream.
func EncodeSync ¶
func EncodeSync() []byte
EncodeSync builds a Sync message, closing an extended-query cycle so the server emits ReadyForQuery.
func EncodeTerminate ¶
func EncodeTerminate() []byte
EncodeTerminate builds a Terminate message, a graceful connection shutdown.
func EscapeIdentifier ¶
EscapeIdentifier wraps s in double quotes, doubling embedded double quotes, mirroring PG::Connection#escape_identifier. QuoteIdent is an alias for the same operation (PG::Connection.quote_ident).
func EscapeLiteral ¶
EscapeLiteral wraps s in single quotes, doubling embedded quotes, mirroring PG::Connection#escape_literal. If s contains a backslash, an E” escape-string prefix is emitted and backslashes are doubled, exactly as libpq does to remain correct regardless of the standard_conforming_strings setting.
func EscapeString ¶
EscapeString escapes a string for inclusion between existing single quotes, doubling embedded single quotes. With standard-conforming strings, backslashes are literal, so only the quote is doubled. This mirrors PG::Connection#escape_string / #escape.
func MD5Password ¶
MD5Password computes the "md5"+hex digest PostgreSQL's AuthenticationMD5Password expects: md5(md5(password + username) + salt), where salt is the 4-byte value from the Authentication message. The result is the string sent in a PasswordMessage.
func ParseBindComplete ¶
ParseBindComplete verifies a '2' message.
func ParseCloseComplete ¶
ParseCloseComplete verifies a '3' message.
func ParseCommandComplete ¶
ParseCommandComplete decodes a 'C' message body into its command tag (for example "INSERT 0 1" or "SELECT 3").
func ParseCopyData ¶
ParseCopyData decodes a 'd' message body, returning its raw payload.
func ParseEmptyQueryResponse ¶
ParseEmptyQueryResponse verifies an 'I' message.
func ParseParseComplete ¶
ParseParseComplete verifies a '1' message.
func ParsePortalSuspended ¶
ParsePortalSuspended verifies an 's' message.
func QuoteIdent ¶
QuoteIdent quotes a possibly-qualified identifier. A dotted name like "schema.table" is quoted segment-by-segment ("schema"."table"), matching PG::Connection.quote_ident's handling of the array form only loosely; the scalar form here quotes the whole string as one identifier unless it contains a dot, in which case each dotted segment is quoted independently.
Types ¶
type Authentication ¶
type Authentication struct {
Kind AuthType
// Salt holds the 4-byte MD5 salt when Kind == AuthMD5Password.
Salt []byte
// Mechanisms lists the offered SASL mechanisms when Kind == AuthSASL.
Mechanisms []string
// Data holds the SASL server payload for AuthSASLContinue / AuthSASLFinal.
Data []byte
}
Authentication is a decoded 'R' message. Kind selects the variant; the remaining fields are populated as relevant.
func ParseAuthentication ¶
func ParseAuthentication(m Message) (*Authentication, error)
ParseAuthentication decodes an 'R' message body.
type Authenticator ¶
type Authenticator interface {
// Handle reacts to a single Authentication message, writing any response.
// For SCRAM it is invoked once per challenge (SASL, SASLContinue).
Handle(c *Conn, a *Authentication) error
}
Authenticator responds to an Authentication challenge during Startup, writing the appropriate frontend message(s) to the connection. It is a seam: a host can plug in its own (GSS/SSPI) scheme; PasswordAuthenticator covers the cleartext, MD5, and SCRAM-SHA-256 methods that need only pure crypto.
type BackendKeyData ¶
BackendKeyData is a decoded 'K' message: the cancellation key for this connection.
func ParseBackendKeyData ¶
func ParseBackendKeyData(m Message) (*BackendKeyData, error)
ParseBackendKeyData decodes a 'K' message body.
type BindParam ¶
BindParam is a single Bind parameter: a value and its wire format. A nil Value encodes as SQL NULL.
type Conn ¶
type Conn struct {
// RW is the transport the protocol runs over. Required.
RW io.ReadWriter
// contains filtered or unexported fields
}
Conn is the PG::Connection-like surface, driving the v3 protocol over an injected transport. The socket is a *host seam*: Conn never dials — the host supplies an already-connected (and, if needed, TLS-wrapped and authenticated) io.ReadWriter as RW. This mirrors the go-ruby net-* libraries, keeping the codec fully testable against in-memory pipes and canned byte streams.
func (*Conn) BackendKey ¶
func (c *Conn) BackendKey() (*BackendKeyData, bool)
BackendKey returns the connection's cancellation key, if BackendKeyData was seen.
func (*Conn) CancelRequest ¶
CancelRequest returns the bytes of a CancelRequest for this connection's backend key, to be sent on a *fresh* connection (never the query connection).
func (*Conn) EscapeIdentifier ¶
EscapeIdentifier is the connection method form of the package EscapeIdentifier.
func (*Conn) EscapeLiteral ¶
EscapeLiteral is the connection method form of the package EscapeLiteral.
func (*Conn) EscapeString ¶
EscapeString is the connection method form of the package EscapeString.
func (*Conn) Exec ¶
Exec runs a simple query and returns its Result, then resynchronises to ReadyForQuery (PG::Connection#exec / #query). Only the first result of a multi-statement string is returned; the rest are drained.
func (*Conn) ExecParams ¶
ExecParams runs a one-shot parameterised query over the extended protocol (Parse/Bind/Describe/Execute/Sync on the unnamed statement + portal), requesting text results (PG::Connection#exec_params). Parameters are encoded with EncodeParam.
func (*Conn) ExecPrepared ¶
ExecPrepared binds and executes a previously prepared statement (PG::Connection#exec_prepared).
func (*Conn) OnNotice ¶
func (c *Conn) OnNotice(fn func(*ErrorFields))
OnNotice registers a callback for NoticeResponse messages.
func (*Conn) OnNotification ¶
func (c *Conn) OnNotification(fn func(*NotificationResponse))
OnNotification registers a callback for NotificationResponse messages.
func (*Conn) Parameter ¶
Parameter returns a server ParameterStatus value captured during the session.
func (*Conn) Prepare ¶
Prepare issues a Parse for a named statement and waits for ParseComplete (PG::Connection#prepare). paramOIDs may pin parameter types (nil to infer).
func (*Conn) QuoteIdent ¶
QuoteIdent is the connection method form of the package QuoteIdent.
func (*Conn) Startup ¶
func (c *Conn) Startup(auth Authenticator) error
Startup performs the post-StartupMessage handshake read loop up to ReadyForQuery, capturing ParameterStatus and BackendKeyData and driving any authentication via the supplied Authenticator. The StartupMessage itself must already have been written by the caller (it owns the parameter set).
func (*Conn) Terminate ¶
Terminate sends a Terminate message (PG::Connection#finish's protocol half).
func (*Conn) TransactionStatus ¶
func (c *Conn) TransactionStatus() TransactionStatus
TransactionStatus returns the status from the last ReadyForQuery.
type CopyResponse ¶
CopyResponse is a decoded CopyInResponse ('G') / CopyOutResponse ('H') / CopyBothResponse ('W'). OverallFormat is 0 for text COPY, 1 for binary; ColumnFormats gives the per-column format codes.
func ParseCopyResponse ¶
func ParseCopyResponse(m Message) (*CopyResponse, error)
ParseCopyResponse decodes a CopyInResponse / CopyOutResponse / CopyBothResponse body.
type DataRow ¶
type DataRow struct {
Values [][]byte
}
DataRow is a decoded 'D' message: the raw column values of one row. A nil element is SQL NULL.
func ParseDataRow ¶
ParseDataRow decodes a 'D' message body.
type Error ¶
type Error struct {
*ErrorFields
}
Error is a PG::Error-like view of an ErrorResponse; it satisfies the Go error interface, formatting as "SEVERITY: message (SQLSTATE)".
type ErrorFields ¶
type ErrorFields struct {
// Fields maps a field-type byte to its value, preserving every field the
// server sent (including ones without a named accessor).
Fields map[byte]string
}
ErrorFields holds every field of an ErrorResponse / NoticeResponse, keyed by the single-byte field identifier PostgreSQL uses on the wire. The named accessors below expose the common ones; PG::Result#error_field(fieldcode) and PG::Error map onto exactly this set.
func ParseErrorResponse ¶
func ParseErrorResponse(m Message) (*ErrorFields, error)
ParseErrorResponse decodes an 'E' message body into its fields.
func ParseNoticeResponse ¶
func ParseNoticeResponse(m Message) (*ErrorFields, error)
ParseNoticeResponse decodes an 'N' message body into its fields.
func (*ErrorFields) AsError ¶
func (e *ErrorFields) AsError() *Error
AsError wraps the fields as a Go error.
func (*ErrorFields) Detail ¶
func (e *ErrorFields) Detail() string
Detail returns the optional secondary detail message.
func (*ErrorFields) Get ¶
func (e *ErrorFields) Get(code byte) (string, bool)
Get returns the value of a field and whether it was present.
func (*ErrorFields) Message ¶
func (e *ErrorFields) Message() string
Message returns the primary human-readable error message.
func (*ErrorFields) SQLState ¶
func (e *ErrorFields) SQLState() string
SQLState returns the five-character SQLSTATE code.
func (*ErrorFields) Severity ¶
func (e *ErrorFields) Severity() string
Severity returns the localized severity (ERROR, FATAL, WARNING, NOTICE, ...).
type FieldDescription ¶
type FieldDescription struct {
Name string
TableOID uint32
AttrNumber int16
DataTypeOID uint32
DataTypeSize int16
TypeModifier int32
Format Format
}
FieldDescription describes one column of a RowDescription.
type Message ¶
Message is a framed, undecoded backend message: its type byte and body (the bytes after the length prefix). The length prefix itself is not retained.
type NotificationResponse ¶
NotificationResponse is a decoded 'A' message from LISTEN/NOTIFY.
func ParseNotificationResponse ¶
func ParseNotificationResponse(m Message) (*NotificationResponse, error)
ParseNotificationResponse decodes an 'A' message body.
type OID ¶
type OID uint32
OID is a PostgreSQL type object identifier. The constants below are the stable, built-in OIDs (from pg_type.dat) the type decoders dispatch on.
const ( OIDBool OID = 16 OIDBytea OID = 17 OIDChar OID = 18 OIDName OID = 19 OIDInt8 OID = 20 OIDInt2 OID = 21 OIDInt4 OID = 23 OIDRegProc OID = 24 OIDText OID = 25 OIDOID OID = 26 OIDTID OID = 27 OIDXID OID = 28 OIDCID OID = 29 OIDJSON OID = 114 OIDXML OID = 142 OIDFloat4 OID = 700 OIDFloat8 OID = 701 OIDUnknown OID = 705 OIDMoney OID = 790 OIDMacaddr OID = 829 OIDInet OID = 869 OIDCIDR OID = 650 OIDBPChar OID = 1042 OIDVarchar OID = 1043 OIDDate OID = 1082 OIDTime OID = 1083 OIDTimestamp OID = 1114 OIDTimestamptz OID = 1184 OIDInterval OID = 1186 OIDTimetz OID = 1266 OIDBit OID = 1560 OIDVarbit OID = 1562 OIDNumeric OID = 1700 OIDUUID OID = 2950 OIDJSONB OID = 3802 )
Built-in scalar type OIDs.
const ( OIDBoolArray OID = 1000 OIDByteaArray OID = 1001 OIDInt2Array OID = 1005 OIDInt4Array OID = 1007 OIDTextArray OID = 1009 OIDVarcharArray OID = 1015 OIDInt8Array OID = 1016 OIDFloat4Array OID = 1021 OIDFloat8Array OID = 1022 OIDOIDArray OID = 1028 OIDNumericArray OID = 1231 OIDTimestampArray OID = 1115 OIDDateArray OID = 1182 OIDTimestamptzArray OID = 1185 OIDUUIDArray OID = 2951 OIDJSONArray OID = 199 OIDJSONBArray OID = 3807 )
Built-in array type OIDs (the array-of-T alongside its element T).
type ParameterDescription ¶
type ParameterDescription struct {
ParamOIDs []uint32
}
ParameterDescription is a decoded 't' message: the OIDs a prepared statement's parameters were inferred (or pinned) to.
func ParseParameterDescription ¶
func ParseParameterDescription(m Message) (*ParameterDescription, error)
ParseParameterDescription decodes a 't' message body.
type ParameterStatus ¶
type ParameterStatus struct {
Name, Value string
}
ParameterStatus is a decoded 'S' message: a runtime parameter and its value.
func ParseParameterStatus ¶
func ParseParameterStatus(m Message) (*ParameterStatus, error)
ParseParameterStatus decodes an 'S' message body.
type PasswordAuthenticator ¶
type PasswordAuthenticator struct {
User string
Password string
// contains filtered or unexported fields
}
PasswordAuthenticator answers cleartext, MD5, and SCRAM-SHA-256 challenges with the given username and password. It keeps the SCRAM exchange state across the SASL / SASLContinue / SASLFinal round trips.
func NewPasswordAuthenticator ¶
func NewPasswordAuthenticator(user, password string) *PasswordAuthenticator
NewPasswordAuthenticator builds a PasswordAuthenticator.
func (*PasswordAuthenticator) Handle ¶
func (p *PasswordAuthenticator) Handle(c *Conn, a *Authentication) error
Handle dispatches on the challenge kind.
type Result ¶
type Result struct {
// contains filtered or unexported fields
}
Result is the pure value view of a query outcome, mirroring PG::Result. It bundles the RowDescription (column metadata), the decoded rows, and the command tag, and offers the ntuples / nfields / fields / getvalue / values / [] surface PG::Result exposes. Values are decoded per column format/OID via DecodeText / DecodeBinary; a NULL cell is nil.
func NewResult ¶
func NewResult(desc *RowDescription, rows []*DataRow, tag string) (*Result, error)
NewResult assembles a Result from a RowDescription and the raw DataRows, decoding every cell using its column's OID and format. A nil desc (a command with no row description, e.g. INSERT) yields a zero-column Result.
func (*Result) CmdTuples ¶
CmdTuples parses the affected-row count from the command tag (PG::Result#cmd_tuples): the last integer of "INSERT 0 N" / "UPDATE N" / "DELETE N" / "SELECT N". A tag without a count returns 0.
func (*Result) Fnumber ¶
Fnumber returns the index of the named column, or -1 if absent (PG::Result#fnumber returns nil; -1 is the Go-idiomatic not-found).
func (*Result) Getisnull ¶
Getisnull reports whether the cell at (row, col) is SQL NULL (PG::Result#getisnull).
func (*Result) Getvalue ¶
Getvalue returns the decoded value at (row, col) (PG::Result#getvalue). A NULL is nil.
func (*Result) GetvalueRaw ¶
GetvalueRaw returns the raw wire bytes at (row, col), or nil for NULL.
type RoundTripper ¶
type RoundTripper interface {
// RoundTrip writes the frontend messages and returns the backend messages up
// to the next synchronisation point.
RoundTrip(frontend [][]byte) ([]Message, error)
}
RoundTripper is the minimal seam for a caller that wants to intercept the raw frontend/backend byte exchange (for logging, a test double, or a non-socket transport). A Conn built over an io.ReadWriter satisfies the common case; RoundTrip lets a host substitute its own request/response transport.
type RowDescription ¶
type RowDescription struct {
Fields []FieldDescription
}
RowDescription is a decoded 'T' message.
func ParseRowDescription ¶
func ParseRowDescription(m Message) (*RowDescription, error)
ParseRowDescription decodes a 'T' message body.
type SCRAMClient ¶
type SCRAMClient struct {
// contains filtered or unexported fields
}
SCRAMClient drives the client half of a SCRAM-SHA-256 exchange. Construct it with NewSCRAMClient, send FirstMessage in a SASLInitialResponse, feed the server-first message to Final to obtain the client-final message (SASLResponse), then verify the server-final message with Verify.
func NewSCRAMClient ¶
func NewSCRAMClient(user, password string) (*SCRAMClient, error)
NewSCRAMClient builds a client with a random 24-byte base64 client nonce. Use NewSCRAMClientWithNonce to pin the nonce for deterministic tests.
func NewSCRAMClientWithNonce ¶
func NewSCRAMClientWithNonce(user, password, clientNonce string) *SCRAMClient
NewSCRAMClientWithNonce builds a client with a caller-supplied client nonce.
func (*SCRAMClient) Final ¶
func (c *SCRAMClient) Final(serverFirst []byte) ([]byte, error)
Final consumes the server-first message and returns the client-final message (the SASLResponse payload). It rejects a server nonce that does not extend the client nonce (a MITM guard).
func (*SCRAMClient) FirstMessage ¶
func (c *SCRAMClient) FirstMessage() []byte
FirstMessage returns the client-first message (the SASLInitialResponse payload). PostgreSQL always uses an empty SCRAM username (the startup "user" carries it), so the n= field is empty.
func (*SCRAMClient) Verify ¶
func (c *SCRAMClient) Verify(serverFinal []byte) error
Verify checks the server-final message's v= signature against the value Final computed. It must be called after Final.
type StartupParams ¶
StartupParams are the key/value pairs of a StartupMessage. "user" is mandatory; "database", "application_name", "client_encoding", etc. are optional. PostgreSQL terminates the list with an empty key.
type TransactionStatus ¶
type TransactionStatus byte
TransactionStatus is the single byte a ReadyForQuery message carries.
const ( // TxnIdle means not in a transaction block ('I'). TxnIdle TransactionStatus = 'I' // TxnActive means in a transaction block ('T'). TxnActive TransactionStatus = 'T' // TxnError means in a failed transaction block ('E'); queries are rejected // until the block ends. TxnError TransactionStatus = 'E' )
func ParseReadyForQuery ¶
func ParseReadyForQuery(m Message) (TransactionStatus, error)
ParseReadyForQuery decodes a 'Z' message body into its transaction status.
func (TransactionStatus) String ¶
func (t TransactionStatus) String() string
String makes TransactionStatus printable for diagnostics.