pg

package module
v0.0.0-...-60f97fa Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 17, 2026 License: BSD-3-Clause Imports: 19 Imported by: 0

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

View Source
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.

View Source
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.

View Source
const SCRAMMechanism = "SCRAM-SHA-256"

SCRAMMechanism is the name of the SCRAM mechanism this package implements.

Variables

This section is empty.

Functions

func DecodeBinary

func DecodeBinary(oid OID, raw []byte) (any, error)

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

func DecodeText(oid OID, raw []byte) (any, error)

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

func EncodeBind(portal, stmt string, params []BindParam, resultFormats []Format) []byte

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

func EncodeCancelRequest(processID, secretKey int32) []byte

EncodeCancelRequest builds the untyped CancelRequest (magic 80877102) carrying the process ID and secret key from a prior BackendKeyData.

func EncodeClosePortal

func EncodeClosePortal(name string) []byte

EncodeClosePortal builds a Close for a portal.

func EncodeCloseStatement

func EncodeCloseStatement(name string) []byte

EncodeCloseStatement builds a Close for a prepared statement.

func EncodeCopyData

func EncodeCopyData(data []byte) []byte

EncodeCopyData wraps a chunk of COPY payload.

func EncodeCopyDone

func EncodeCopyDone() []byte

EncodeCopyDone signals the end of COPY-in data.

func EncodeCopyFail

func EncodeCopyFail(reason string) []byte

EncodeCopyFail aborts a COPY-in with a diagnostic message.

func EncodeDescribePortal

func EncodeDescribePortal(name string) []byte

EncodeDescribePortal builds a Describe for a portal, eliciting a RowDescription (or NoData).

func EncodeDescribeStatement

func EncodeDescribeStatement(name string) []byte

EncodeDescribeStatement builds a Describe for a prepared statement, eliciting a ParameterDescription and a RowDescription (or NoData).

func EncodeExecute

func EncodeExecute(portal string, maxRows int32) []byte

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

func EncodeParam(v any) ([]byte, error)

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

func EncodeParse(name, sql string, paramOIDs []uint32) []byte

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

func EncodePassword(password string) []byte

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 EncodeQuery

func EncodeQuery(sql string) []byte

EncodeQuery builds a simple-query message.

func EncodeSASLInitialResponse

func EncodeSASLInitialResponse(mechanism string, initial []byte) []byte

EncodeSASLInitialResponse builds the first SASL message: the selected mechanism name, then an Int32 length-prefixed client-first message (or -1 when absent).

func EncodeSASLResponse

func EncodeSASLResponse(data []byte) []byte

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

func EscapeIdentifier(s string) string

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

func EscapeLiteral(s string) string

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

func EscapeString(s string) string

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

func MD5Password(user, password string, salt []byte) string

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

func ParseBindComplete(m Message) error

ParseBindComplete verifies a '2' message.

func ParseCloseComplete

func ParseCloseComplete(m Message) error

ParseCloseComplete verifies a '3' message.

func ParseCommandComplete

func ParseCommandComplete(m Message) (string, error)

ParseCommandComplete decodes a 'C' message body into its command tag (for example "INSERT 0 1" or "SELECT 3").

func ParseCopyData

func ParseCopyData(m Message) ([]byte, error)

ParseCopyData decodes a 'd' message body, returning its raw payload.

func ParseCopyDone

func ParseCopyDone(m Message) error

ParseCopyDone verifies a 'c' message.

func ParseEmptyQueryResponse

func ParseEmptyQueryResponse(m Message) error

ParseEmptyQueryResponse verifies an 'I' message.

func ParseNoData

func ParseNoData(m Message) error

ParseNoData verifies an 'n' message.

func ParseParseComplete

func ParseParseComplete(m Message) error

ParseParseComplete verifies a '1' message.

func ParsePortalSuspended

func ParsePortalSuspended(m Message) error

ParsePortalSuspended verifies an 's' message.

func QuoteIdent

func QuoteIdent(s string) string

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 AuthType

type AuthType int32

AuthType classifies an Authentication message.

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

type BackendKeyData struct {
	ProcessID int32
	SecretKey int32
}

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

type BindParam struct {
	Value  []byte
	Format Format
}

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 NewConn

func NewConn(rw io.ReadWriter) *Conn

NewConn wraps a transport as a Conn.

func (*Conn) BackendKey

func (c *Conn) BackendKey() (*BackendKeyData, bool)

BackendKey returns the connection's cancellation key, if BackendKeyData was seen.

func (*Conn) CancelRequest

func (c *Conn) CancelRequest() ([]byte, error)

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

func (c *Conn) EscapeIdentifier(s string) string

EscapeIdentifier is the connection method form of the package EscapeIdentifier.

func (*Conn) EscapeLiteral

func (c *Conn) EscapeLiteral(s string) string

EscapeLiteral is the connection method form of the package EscapeLiteral.

func (*Conn) EscapeString

func (c *Conn) EscapeString(s string) string

EscapeString is the connection method form of the package EscapeString.

func (*Conn) Exec

func (c *Conn) Exec(sql string) (*Result, error)

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

func (c *Conn) ExecParams(sql string, args ...any) (*Result, error)

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

func (c *Conn) ExecPrepared(name string, args ...any) (*Result, error)

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

func (c *Conn) Parameter(name string) (string, bool)

Parameter returns a server ParameterStatus value captured during the session.

func (*Conn) Prepare

func (c *Conn) Prepare(name, sql string, paramOIDs []uint32) error

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

func (c *Conn) QuoteIdent(s string) string

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

func (c *Conn) Terminate() error

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

type CopyResponse struct {
	Type          byte
	OverallFormat int8
	ColumnFormats []Format
}

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

func ParseDataRow(m Message) (*DataRow, error)

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)".

func (*Error) Error

func (e *Error) Error() string

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) Hint

func (e *ErrorFields) Hint() string

Hint returns the optional hint.

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 Format

type Format int16

Format is the wire format of a parameter or column: text or binary.

const (
	// TextFormat (0) is PostgreSQL's default human-readable representation.
	TextFormat Format = 0
	// BinaryFormat (1) is the type's binary representation.
	BinaryFormat Format = 1
)

type Message

type Message struct {
	Type byte
	Body []byte
}

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.

func ReadMessage

func ReadMessage(r io.Reader) (Message, error)

ReadMessage reads one framed backend message from r. It returns io.EOF only when r is at a clean message boundary; a truncated header or body yields io.ErrUnexpectedEOF.

type NotificationResponse

type NotificationResponse struct {
	ProcessID int32
	Channel   string
	Payload   string
}

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) CmdStatus

func (r *Result) CmdStatus() string

CmdStatus returns the raw command tag (PG::Result#cmd_status).

func (*Result) CmdTuples

func (r *Result) CmdTuples() int

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) Each

func (r *Result) Each(fn func(map[string]any) error) error

Each applies fn to every row as a name→value map (PG::Result#each).

func (*Result) Fields

func (r *Result) Fields() []string

Fields returns the column names (PG::Result#fields).

func (*Result) Fmod

func (r *Result) Fmod(i int) (int32, error)

Fmod returns the type modifier of column i (PG::Result#fmod).

func (*Result) Fname

func (r *Result) Fname(i int) (string, error)

Fname returns the name of column i (PG::Result#fname).

func (*Result) Fnumber

func (r *Result) Fnumber(name string) int

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) Ftype

func (r *Result) Ftype(i int) (OID, error)

Ftype returns the type OID of column i (PG::Result#ftype).

func (*Result) Getisnull

func (r *Result) Getisnull(row, col int) (bool, error)

Getisnull reports whether the cell at (row, col) is SQL NULL (PG::Result#getisnull).

func (*Result) Getvalue

func (r *Result) Getvalue(row, col int) (any, error)

Getvalue returns the decoded value at (row, col) (PG::Result#getvalue). A NULL is nil.

func (*Result) GetvalueRaw

func (r *Result) GetvalueRaw(row, col int) ([]byte, error)

GetvalueRaw returns the raw wire bytes at (row, col), or nil for NULL.

func (*Result) Nfields

func (r *Result) Nfields() int

Nfields returns the number of columns (PG::Result#nfields / #num_fields).

func (*Result) Ntuples

func (r *Result) Ntuples() int

Ntuples returns the number of rows (PG::Result#ntuples / #num_tuples).

func (*Result) Tuple

func (r *Result) Tuple(i int) (map[string]any, error)

Tuple returns row i as a name→value map (PG::Result#[] / #tuple). Duplicate column names collapse to the last occurrence, matching Ruby's Hash.

func (*Result) Values

func (r *Result) Values() [][]any

Values returns every row as a slice of decoded value slices (PG::Result#values).

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

type StartupParams map[string]string

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL