Documentation
¶
Overview ¶
Package pggo is a small, dependency-free PostgreSQL client that speaks the wire protocol (v3) directly.
It provides connections, streaming queries with $N parameters, transactions, struct scanning, structured server errors, context cancellation (with a server-side cancel request), TLS, and SCRAM-SHA-256/MD5/cleartext auth. It intentionally does not try to be pgx: there is no statement cache, no binary format, no COPY or LISTEN/NOTIFY, and only a minimal pool.
Index ¶
- Constants
- Variables
- func CollectOneStruct[T any](rows *Rows) (T, error)
- func CollectStructs[T any](rows *Rows) ([]T, error)
- func CollectStructsByPos[T any](rows *Rows) ([]T, error)
- func QuoteIdentifier(parts ...string) string
- type AuthError
- type Column
- type CommandTag
- type Config
- type Conn
- func (c *Conn) Begin(ctx context.Context) (*Tx, error)
- func (c *Conn) BeginTx(ctx context.Context, opts TxOptions) (*Tx, error)
- func (c *Conn) Close() error
- func (c *Conn) Config() *Config
- func (c *Conn) Deallocate(ctx context.Context, name string) error
- func (c *Conn) Exec(ctx context.Context, sql string, args ...any) (CommandTag, error)
- func (c *Conn) IsClosed() bool
- func (c *Conn) PID() uint32
- func (c *Conn) ParameterStatus(name string) string
- func (c *Conn) Prepare(ctx context.Context, name, sql string) error
- func (c *Conn) Query(ctx context.Context, sql string, args ...any) (*Rows, error)
- func (c *Conn) QueryRow(ctx context.Context, sql string, args ...any) *Row
- func (c *Conn) ServerVersion() string
- func (c *Conn) SimpleQuery(ctx context.Context, sql string) ([]Result, error)
- func (c *Conn) TxStatus() byte
- type ConnectError
- type Format
- type Numeric
- type Option
- type PgError
- type Pool
- func (p *Pool) Acquire(ctx context.Context) (*PoolConn, error)
- func (p *Pool) BeginTx(ctx context.Context, opts TxOptions) (*Tx, error)
- func (p *Pool) Close()
- func (p *Pool) Config() *Config
- func (p *Pool) Exec(ctx context.Context, sql string, args ...any) (CommandTag, error)
- func (p *Pool) Query(ctx context.Context, sql string, args ...any) (*Rows, error)
- func (p *Pool) QueryRow(ctx context.Context, sql string, args ...any) *Row
- type PoolConfig
- type PoolConn
- type ProtocolError
- type QueryOption
- type RawValue
- type Result
- type Row
- type Rows
- type TLSError
- type Tx
- func (tx *Tx) Commit(ctx context.Context) error
- func (tx *Tx) Conn() *Conn
- func (tx *Tx) Exec(ctx context.Context, sql string, args ...any) (CommandTag, error)
- func (tx *Tx) Query(ctx context.Context, sql string, args ...any) (*Rows, error)
- func (tx *Tx) QueryRow(ctx context.Context, sql string, args ...any) *Row
- func (tx *Tx) Rollback(ctx context.Context) error
- type TxOptions
Constants ¶
const ( OIDBool = 16 OIDBytea = 17 OIDChar = 18 // "char" OIDName = 19 OIDInt8 = 20 OIDInt2 = 21 OIDInt2Vector = 22 OIDInt4 = 23 OIDText = 25 OIDOID = 26 OIDXID = 28 OIDCID = 29 OIDOIDVector = 30 OIDJSON = 114 OIDFloat4 = 700 OIDFloat8 = 701 OIDBoolArray = 1000 OIDInt2Array = 1005 OIDInt4Array = 1007 OIDTextArray = 1009 OIDBPChar = 1042 OIDVarchar = 1043 OIDInt8Array = 1016 OIDOIDArray = 1028 OIDVarcharArr = 1015 OIDNameArray = 1003 OIDFloat8Array = 1022 OIDDate = 1082 OIDTimestamp = 1114 OIDTimestampTZ = 1184 OIDInterval = 1186 OIDNumeric = 1700 OIDUUID = 2950 OIDJSONB = 3802 )
Type OIDs pggo decodes natively. Any other type can still be read as a string (its text representation) or as a RawValue.
Variables ¶
var ( // ErrNoRows is returned by Row.Scan and CollectOneStruct when the query returned no rows. ErrNoRows = errors.New("no rows in result set") // ErrTooManyRows is returned by CollectOneStruct when the query returned more than one row. ErrTooManyRows = errors.New("too many rows in result set") // ErrConnBusy means a previous Rows is still open on this connection. ErrConnBusy = errors.New("conn busy: close the previous Rows first") // ErrConnClosed means the connection was closed, either explicitly or because // an earlier operation was canceled or failed at the network level. ErrConnClosed = errors.New("conn closed") // ErrTxClosed means Commit or Rollback was already called. ErrTxClosed = errors.New("tx is closed") // ErrTxCommitRollback means COMMIT was answered with ROLLBACK because the // transaction had already failed. ErrTxCommitRollback = errors.New("commit unexpectedly resulted in rollback") )
Functions ¶
func CollectOneStruct ¶
CollectOneStruct is CollectStructs for exactly one row: it returns ErrNoRows or ErrTooManyRows otherwise.
func CollectStructs ¶
CollectStructs reads every row into a T, matching columns to struct fields by `db:"name"` tag, or by field name (case-insensitive) when untagged. Fields tagged `db:"-"` are ignored. Struct fields with no matching column keep their zero value; a column with no matching field is an error. Rows is closed when CollectStructs returns.
func CollectStructsByPos ¶
CollectStructsByPos reads every row into a T, assigning columns to the struct's exported fields in order. The counts must match.
func QuoteIdentifier ¶
QuoteIdentifier quotes each part as a SQL identifier and joins them with dots: QuoteIdentifier("my schema", "t") == `"my schema"."t"`.
Types ¶
type AuthError ¶
type AuthError struct{ Err error }
AuthError is a client-side authentication failure (the server's own rejections arrive as *PgError with SQLSTATE 28P01/28000).
type CommandTag ¶
type CommandTag string
CommandTag is the server's completion tag, e.g. "UPDATE 3" or "CREATE TABLE".
func (CommandTag) Command ¶
func (t CommandTag) Command() string
Command is the tag without its row counts, e.g. "INSERT" for "INSERT 0 3".
func (CommandTag) RowsAffected ¶
func (t CommandTag) RowsAffected() int64
RowsAffected is the trailing row count of the tag (0 if it has none).
func (CommandTag) String ¶
func (t CommandTag) String() string
type Config ¶
type Config struct {
Host string // hostname, IP, or unix socket directory (starts with "/")
Port int
User string
Password string
Database string
SSLMode string // disable | allow | prefer | require | verify-ca | verify-full
SSLRootCert string
// RuntimeParams are sent in the startup message as session settings
// (application_name, search_path, ...).
RuntimeParams map[string]string
// DialFunc, if set, opens the network connection instead of net.Dialer
// (e.g. through an SSH tunnel). TLS is negotiated on top of what it returns.
DialFunc func(ctx context.Context, network, addr string) (net.Conn, error)
// contains filtered or unexported fields
}
Config describes how to connect. Build one with ParseConfig and adjust fields before calling ConnectConfig.
func ParseConfig ¶
ParseConfig parses a postgres:// URL or a libpq keyword=value string. Unset fields come from the libpq environment (PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE, PGSSLMODE, PGSSLROOTCERT), a connection service file (service=name or PGSERVICE; PGSERVICEFILE or ~/.pg_service.conf), and the password file (PGPASSFILE or ~/.pgpass), in libpq's precedence order.
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn is a single PostgreSQL connection. It is not safe for concurrent use; use a Pool to share connections between goroutines.
func ConnectConfig ¶
ConnectConfig connects using cfg. The context bounds dialing, TLS, and authentication. Options are applied with SET after authentication, so a failure to apply one fails the connect.
func (*Conn) Close ¶
Close terminates the session. Any open transaction is rolled back by the server.
func (*Conn) Deallocate ¶
Deallocate drops a named prepared statement.
func (*Conn) ParameterStatus ¶
ParameterStatus returns a server-reported setting such as server_version, TimeZone, or in_hot_standby ("" if not reported).
func (*Conn) Query ¶
Query runs one statement with $1..$n parameters and streams its rows. The caller must Close the Rows (or read them to the end) before the next call.
func (*Conn) QueryRow ¶
QueryRow runs a query expected to return at most one row. Errors are deferred to Row.Scan, which returns ErrNoRows for an empty result.
func (*Conn) ServerVersion ¶
ServerVersion returns the server version without build details, e.g. "17.2".
func (*Conn) SimpleQuery ¶
SimpleQuery sends sql with the simple query protocol: no parameters, the text reaches the server byte for byte (so "$1" stays literal, as EXPLAIN (GENERIC_PLAN) needs), and it may contain several statements.
type ConnectError ¶
ConnectError wraps any failure while establishing a connection.
func (*ConnectError) Error ¶
func (e *ConnectError) Error() string
func (*ConnectError) Unwrap ¶
func (e *ConnectError) Unwrap() error
type Numeric ¶
type Numeric string
Numeric is a numeric value in its exact decimal text form. It marshals to JSON as a number (or as the string "NaN"/"Infinity").
func (Numeric) MarshalJSON ¶
type Option ¶
type Option func(*Config)
Option configures session behavior at connect time.
func LockTimeout ¶
LockTimeout sets the session's lock_timeout.
func ReadOnly ¶
func ReadOnly() Option
ReadOnly makes every transaction on the session read-only (SET default_transaction_read_only = on). PostgreSQL enforces it.
func StatementTimeout ¶
StatementTimeout sets the session's statement_timeout.
type PgError ¶
type PgError struct {
Severity string
Code string
Message string
Detail string
Hint string
Position int // 1-based character offset into the statement, 0 if unknown
Where string
}
PgError is an error reported by the PostgreSQL server. Code is the SQLSTATE; classify errors by Code, never by Message.
type Pool ¶
type Pool struct {
// contains filtered or unexported fields
}
Pool shares connections between goroutines.
func NewPool ¶
func NewPool(cfg PoolConfig) *Pool
NewPool creates a pool. No connection is opened until the first Acquire.
func (*Pool) Acquire ¶
Acquire checks out a connection, opening one if needed. It blocks while MaxConns connections are in use.
func (*Pool) BeginTx ¶
BeginTx starts a transaction on a pooled connection, which returns to the pool when the transaction commits or rolls back.
func (*Pool) Close ¶
func (p *Pool) Close()
Close closes idle connections and marks the pool closed; connections in use are closed when released.
type PoolConfig ¶
type PoolConfig struct {
Config *Config
MaxConns int // default 4
MaxConnLifetime time.Duration // 0 = unlimited
// AfterConnect runs on every new connection before first use; an error
// discards the connection and fails the Acquire.
AfterConnect func(ctx context.Context, c *Conn) error
// BeforeClose runs before the pool closes a connection.
BeforeClose func(c *Conn)
}
PoolConfig configures a Pool. The pool is deliberately minimal: a bounded set of connections, lazily opened, with per-connection setup and teardown hooks and a maximum lifetime.
type PoolConn ¶
type PoolConn struct {
// contains filtered or unexported fields
}
PoolConn is a connection checked out of a Pool.
type ProtocolError ¶
type ProtocolError struct{ Msg string }
ProtocolError means the server sent something pggo could not understand.
func (*ProtocolError) Error ¶
func (e *ProtocolError) Error() string
type QueryOption ¶
type QueryOption interface {
// contains filtered or unexported methods
}
QueryOption changes how a single Query runs. Pass it among the arguments; it is not sent as a parameter.
func MaxRows ¶
func MaxRows(n int) QueryOption
MaxRows asks the server to produce at most n rows (a portal row limit), so a large result is never computed or transmitted past n. Rows then reports Suspended() == true if the result had more.
type RawValue ¶
RawValue is a column value exactly as the server sent it. Scanning into *RawValue works for every type, including ones pggo has no decoder for.
type Result ¶
type Result struct {
Columns []Column
Rows [][][]byte
CommandTag CommandTag
}
Result is one statement's result from SimpleQuery. Values are text format.
type Row ¶
type Row struct {
// contains filtered or unexported fields
}
Row is the result of QueryRow.
type Rows ¶
type Rows struct {
// contains filtered or unexported fields
}
Rows streams the result of a query. It is not safe for concurrent use.
func (*Rows) Close ¶
func (r *Rows) Close()
Close reads any remaining rows and releases the connection. It is safe to call more than once.
func (*Rows) CommandTag ¶
func (r *Rows) CommandTag() CommandTag
CommandTag is available after the rows have been read to the end.
func (*Rows) Next ¶
Next advances to the next row. It returns false at the end or on error; check Err.
func (*Rows) RawValues ¶
RawValues returns the current row's values in PostgreSQL text format (nil for NULL). The slices are only valid until the next call to Next.
func (*Rows) Scan ¶
Scan copies the current row into dest, one destination per column. Destinations are pointers (see scanValue for the supported conversions); pass nil to skip a column.
func (*Rows) Values ¶
Values returns the current row as Go values. The types follow pgx, so code that marshals them (e.g. to JSON) sees the same shapes: bool, int16/int32/ int64, uint32 (oid), float32/float64, Numeric, string, int32 for "char", time.Time, []byte (bytea), decoded JSON, []any for arrays, nil for NULL. Types without a decoder come back as their text representation (string).
type TLSError ¶
type TLSError struct{ Err error }
TLSError is a failed TLS negotiation (refused by the server or verification failure).
type Tx ¶
type Tx struct {
// contains filtered or unexported fields
}
Tx is a transaction on one connection.
BEGIN is not sent on its own: it is pipelined with the transaction's first statement, in the same protocol sync, so a transaction costs no extra round trip and its first statement can never run outside it (if BEGIN fails, the server skips the statement).
func (*Tx) Commit ¶
Commit commits the transaction. If the transaction had already failed, the server rolls it back and Commit returns ErrTxCommitRollback.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
pggo
command
Command pggo is a tiny PostgreSQL adapter for LLMs and coding agents.
|
Command pggo is a tiny PostgreSQL adapter for LLMs and coding agents. |
|
examples
|
|
|
hello
command
Command hello connects to PostgreSQL with pggo and runs SELECT 1.
|
Command hello connects to PostgreSQL with pggo and runs SELECT 1. |
|
internal
|
|
|
bench
Package bench runs pgGo's tiny connectivity benchmark.
|
Package bench runs pgGo's tiny connectivity benchmark. |
|
errors
Package errors defines pgGo's stable, machine-readable error contract.
|
Package errors defines pgGo's stable, machine-readable error contract. |
|
output
Package output writes pgGo's JSON responses.
|
Package output writes pgGo's JSON responses. |