polite

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 24 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

polite

Documentation: https://blake.io/polite

Documentation

Overview

Package polite is a small, robust PostgreSQL client for Go. The API surface is narrow by design: PostgreSQL and its wire protocol are built for the heavy lifting, and polite is the Go handle that exposes them. It does this by providing scalar row decoders for common PostgreSQL types and raw wire bytes for the rest. Custom decoders are plain Go functions over those bytes.

The package centers on Conn. Dial a connection, call Conn.Query to range over rows, call Conn.Exec for commands whose rows you do not need, and use Pool when multiple goroutines need to share connections. A Conn is not safe for concurrent use. A Pool is safe and preserves warm per-connection state such as prepared statements.

Queries

Query is the main operation. It executes SQL and yields a sequence of rows and errors. Exec is a thin convenience wrapper for commands such as INSERT, UPDATE, and DELETE.

Polite prepares SQL on first use and caches prepared statements per connection by exact SQL text. Reusing the same SQL on the same connection reuses the prepared statement as well. The cache is bounded; the server-side prepared statement for an evicted entry is not freed until the connection closes, so workloads that rotate through unbounded SQL text accumulate dead prepared statements on the backend.

Arguments

Query and Exec bind variadic arguments to placeholders ($1, $2, ...) in the SQL. Polite pins each parameter's PostgreSQL type from the Go argument's type and sends that OID in the Parse message. PostgreSQL casts from there to whatever the column or expression actually wants, so a Go int can drive an int4 column and a Go string can drive an inet, uuid, or numeric without an intermediate ::text hop.

The encoding rules are:

  • nil, and a nil []byte, become NULL.
  • []byte pins bytea; string pins text. Both pass through as raw parameter bytes, since the binary format for text and bytea is the bytes themselves.
  • Fixed-width integers pin the matching PostgreSQL integer type: int2 for int8, int16, and uint8; int4 for int32 and uint16; int8 for int, int64, uint, uint32, and uint64. uint and uint64 values above the int64 maximum wrap to a negative int8; pass them as a Go string for the full unsigned range.
  • float32 pins float4; float64 pins float8.
  • time.Time pins timestamptz. SQL casts (e.g. $1::timestamp, $1::date) coerce to other temporal types on the server.

Every other Go type, including bool, is rejected with an "unsupported argument type" error. To pass a boolean, use a SQL literal (TRUE / FALSE) or a string parameter with an explicit cast such as $1::bool. The same trick works for any type polite does not encode directly: pass the value as a string and cast in SQL.

From there, the row API defines how results are read.

Rows and Columns

A Row is a view of the current result row. Polite requests every column in PostgreSQL's binary format, so Column values arrive as raw wire bytes rather than decimal strings. Each Column reports its name, width, PostgreSQL type OID, and those bytes. Column.DecodeInt, Column.DecodeFloat, and Column.DecodeTime read the binary format directly; for types without a built-in decoder, call Column.Bytes and decode the wire bytes yourself. Raw column bytes refer to storage owned by the current row and remain valid only until the next row is determined.

Rows reuse storage across iterations. In steady-state query paths, that lets polite avoid per-row allocation. The same column metadata also makes it straightforward to fill Go structs by matching column names in a single pass, without reflection or per-row lookup tables.

NULL

Column.Bytes reports SQL NULL as a nil slice with a nil error; a non-null empty value returns a non-nil zero-length slice. The typed decoders treat NULL as an error, because their return types cannot represent "missing."

NULL often goes away in the query. COALESCE supplies a default, NULLIF reverses it, and IS NOT NULL filters at the source. Pushing the question to PostgreSQL is usually clearer than a client-side branch, and reuses the database's NULL semantics instead of re-deriving them in Go.

COPY

Query supports COPY TO and COPY FROM in PostgreSQL's binary format; text COPY returns ErrCopyFormat. COPY FROM is entered through Query: while the iterator yields rows whose columns report ErrCopyFrom, send each data row with Conn.Exec using an empty SQL string and the row's column values as arguments. A nil argument is sent as SQL NULL.

See Column for details on reading binary values and Conn.Query for examples.

Errors

*febe.Error is the decoded form of a PostgreSQL ErrorResponse. Conn.Query and Conn.Exec surface one whenever the backend replies with an error. An *Error carries the SQLSTATE Code, Message, Severity, Detail, and Hint, along with Schema, Table, Column, DataType, and Constraint when the backend attaches them.

To match a specific code, use errors.Is with febe.ErrorCode:

if errors.Is(err, febe.ErrorCode("23505")) {
    // unique violation
}

Use febe.Error.IsFatal to tell a recoverable backend error — one where a ReadyForQuery will follow — from a FATAL or PANIC that has closed the connection. A non-fatal *Error is returned only by the call that observed it; the underlying febe.Conn keeps it out of its sticky-error state so subsequent calls work normally. A fatal *Error or transport error becomes sticky and is returned by every subsequent call on the connection.

Polite's own `Err*` sentinels, such as ErrBusy, are produced by polite or Pool when they detect a local condition — not decoded from a backend message.

Pooling

A Conn is intentionally single-user. Use Pool when callers need shared access. The zero value of Pool is ready to use. Waiters are served in FIFO order, and the most recently returned connection is handed out first so prepared statements and other per-connection state stay warm.

Failed dials retry with exponential backoff until the pool is closed; see Pool.Dial for the retry contract and Pool.Logger for redirecting or silencing the retry warnings.

Pool scheduling

A pool has two queues: waiters blocked in Pool.Get and idle connections waiting to be handed out. Polite serves waiters in FIFO order and idle connections in LIFO order. The asymmetry is deliberate.

  • Bounded waiter latency. Under FIFO, the kth queued waiter is served after at most k/μ time, where μ is the rate at which Pool.Put returns connections to the idle set. Under LIFO no such bound exists: sustained overload keeps new arrivals on top of the stack and the early waiter never reaches the front.

  • Concentrated reuse. Let N be the maximum pool size, λ the arrival rate of Pool.Get calls, D the mean time a connection is checked out, and A = λD the steady-state active set (Little's law). Pools are normally sized so A is well below N. Under LIFO the same A connections sit at the top of the idle set and serve nearly all requests; the other N − A stay dormant until demand rises. Under FIFO every connection rotates through use regardless of demand.

Concentration matters because polite caches prepared statements per connection: the first execution of a SQL on a fresh connection pays one extra round trip for Parse. With M distinct SQL texts in the workload, the server-side prepared-statement footprint is roughly A × M under LIFO and N × M under FIFO, and first-use Parse round trips scale the same way. For N = 100, A = 10, M = 50 — a typical web app at off-peak load — that is 500 prepared statements versus 5,000.

The two choices are independent. FIFO on waiters is about fairness on a rate-limited resource; LIFO on connections is about reuse of stateful per-connection caches.

Testing and Time

When a Config's Now function is set, unqualified SQL calls to now(), clock_timestamp(), statement_timestamp(), and transaction_timestamp() use the returned clock on that connection. If Now is nil, polite leaves PostgreSQL's default time behavior unchanged. This is useful in tests, including tests run under testing/synctest, because SQL that calls those functions can observe the same clock as the Go test.

The override is implemented by creating SQL functions in a "polite" schema and prepending that schema to the connection's search_path. Tests that read pg_proc or inspect the search_path will see those functions; the original PostgreSQL versions remain reachable via their fully qualified names (e.g. pg_catalog.now()).

Index

Examples

Constants

View Source
const (
	DefaultPoolMaxConns   = 100 // Postgres default
	DefaultPoolMaxWaiters = 1000

	DefaultDSN = "dbname=postgres host=localhost port=5432 sslmode=verify-full"
)

Defaults

Variables

View Source
var (
	ErrTLSRefused     = errors.New("polite: TLS refused by backend")
	ErrCopyFormat     = errors.New("polite: unsupported COPY format: must use `... WITH (FORMAT binary)`")
	ErrCopyFrom       = errors.New("polite: COPY FROM is active; the Query iterator yields a Row whose columns report this; use Exec(ctx, \"\", args...) to send each data row")
	ErrBusy           = errors.New("polite: a Query range is active; complete or break it before calling Query or Exec")
	ErrClosed         = errors.New("polite: closed")
	ErrTooManyWaiters = errors.New("polite: pool: too many waiters")
)

Errors

Functions

func Notifications

func Notifications(ctx context.Context, cn *Conn) iter.Seq[*febe.Notification]

Notifications returns an iterator over the [febe.Notification]s received on cn. Only channels the connection has subscribed to with LISTEN produce notifications; issue LISTEN via Conn.Exec before ranging.

Notifications returns only when the caller breaks out of the range loop or when the connection becomes terminal (protocol or transport error). No error is returned directly; both cases look the same from the caller's side. To distinguish them, attach a febe.Trace with a ReceivedError callback via febe.WithTrace.

While a Notifications range is active, further calls to Conn.Query or Conn.Exec on the same Conn return ErrBusy; end the range before calling either again. Calling Notifications on a Conn that is already busy yields nothing and returns immediately, leaving the in-flight activity untouched.

Typical usage with LISTEN:

cn.Exec(ctx, "LISTEN chat")
for n := range polite.Notifications(ctx, cn) {
	fmt.Printf("%s: %s\n", n.Channel(nil), n.Payload(nil))
}
Example (ListenNotify)

LISTEN on a channel and range over Notifications. The range ends only when the caller breaks or the connection becomes terminal; attach a febe.Trace if you need to tell the two apart.

package main

import (
	"context"
	"fmt"

	"blake.io/polite"
)

func main() {
	ctx := context.Background()

	cn, _ := polite.Dial(ctx, "postgres://localhost/mydb", nil)
	defer cn.Close()

	cn.Exec(ctx, "LISTEN chat")

	for n := range polite.Notifications(ctx, cn) {
		fmt.Printf("channel=%s payload=%s\n", n.Channel(nil), n.Payload(nil))
	}
}

func Quote

func Quote[T ~string | ~[]byte](v T) string

Quote returns v as a SQL string literal: wrapped in apostrophes, with each interior apostrophe doubled. PostgreSQL with the default standard_conforming_strings=on treats backslash as a literal byte inside '...', so the apostrophe is the only character that needs escaping. Quote is byte-oriented and safe for any UTF-8 input.

Quote is for SQL string literals, not identifiers. Pass user data as a $N parameter when possible; reach for Quote only when a literal must appear directly in the SQL text.

Types

type Column

type Column struct {
	// contains filtered or unexported fields
}

Column is one column of the current Row.

Values arrive in PostgreSQL's binary wire format. Column.DecodeInt, Column.DecodeFloat, and Column.DecodeTime decode that format directly. For types without a built-in decoder, Column.Bytes returns a view of the raw wire bytes, borrowed from the row's storage.

func (Column) Bytes

func (c Column) Bytes() ([]byte, error)

Bytes returns the raw wire bytes. The slice borrows the row's storage and is valid only while that row is current.

A SQL NULL column returns a nil slice and a nil error; a non-null empty value returns a non-nil zero-length slice.

Example (NullCheck)

NULL columns are detected by the contract on Column.Bytes: a SQL NULL returns a nil slice with a nil error; a non-NULL value returns a non-nil slice. The error must be checked first; only then does b == nil mean NULL.

This example handles the error explicitly because the error is what distinguishes NULL from "could not read."

package main

import (
	"context"
	"fmt"

	"blake.io/polite"
)

func main() {
	ctx := context.Background()
	cn, _ := polite.Dial(ctx, "", nil)
	defer cn.Close()

	for row := range cn.Query(ctx, "SELECT n FROM t WHERE id = $1", 42) {
		col := row.Column(0)
		b, err := col.Bytes()
		if err != nil {
			panic(err)
		}
		if b == nil {
			fmt.Println("NULL")
			continue
		}
		n, _ := col.DecodeInt() // bytes confirmed non-nil
		fmt.Println(n)
	}
}

func (Column) DecodeFloat

func (c Column) DecodeFloat() (float64, error)

DecodeFloat decodes the column as an IEEE-754 floating-point value from PostgreSQL's binary wire format. It accepts the two fixed widths, 4 bytes (float4) and 8 bytes (float8), and returns the value as float64. Any other width is reported as an error.

SQL NULL has a zero-length payload, so DecodeFloat reports it as "invalid length: 0". The package's "NULL" section covers the rationale and the SQL-side alternatives.

func (Column) DecodeInt

func (c Column) DecodeInt() (int64, error)

DecodeInt decodes the column as a signed integer from PostgreSQL's binary wire format. It accepts the four fixed integer widths — 1, 2, 4, or 8 bytes — and returns the value as int64. Any other width is reported as an error rather than guessed at.

PostgreSQL's bool is one byte (0x00 or 0x01), so DecodeInt reads a bool column directly: 0 is false, 1 is true.

SQL NULL has a zero-length payload, so DecodeInt reports it as "invalid length: 0". The package's "NULL" section covers the rationale and the SQL-side alternatives.

func (Column) DecodeText

func (c Column) DecodeText() (string, error)

DecodeText returns the column bytes as a string. Unlike Column.Bytes, the returned string is a copy and remains valid after the row advances.

SQL NULL is returned as ("", nil) — indistinguishable from an empty string column. The package's "NULL" section covers the rationale and the SQL-side alternatives.

func (Column) DecodeTime

func (c Column) DecodeTime() (time.Time, error)

DecodeTime decodes the column as a microsecond-precision timestamp.

A timestamptz is returned in UTC. A timestamp (without time zone) is returned with time.UTC as a placeholder location: PostgreSQL's timestamp type carries no zone, so attaching one would require inventing information the value does not have. Use timestamptz when you need an instant.

PostgreSQL's positive and negative infinity sentinels are reported as an error rather than mapped to a Go time value.

SQL NULL has a zero-length payload, so DecodeTime reports it as "invalid length: 0". The package's "NULL" section covers the rationale and the SQL-side alternatives.

func (Column) Name

func (c Column) Name() string

Name returns the column name.

func (Column) Ordinal

func (c Column) Ordinal() int

Ordinal returns the column's zero-based position in the row.

func (Column) Size

func (c Column) Size() int

Size returns the column's type width in bytes, as reported by the backend from pg_type.typlen. Fixed-width types return their byte width (e.g. 4 for int4, 8 for int8). Variable-width types (text, bytea, numeric, all array types, and other varlena types) return -1.

func (Column) Type

func (c Column) Type() oids.ID

Type returns the column's PostgreSQL type OID.

type Config

type Config struct {
	// Dial is used to open the connection to postgres. If nil, a net.Dialer is used.
	Dial func(ctx context.Context, network, addr string) (net.Conn, error)

	// TLSConfig is cloned and used as the base TLS config for handshakes.
	// Set Time there to override the clock used by crypto/tls.
	TLSConfig *tls.Config

	// Now returns the time polite uses for unqualified calls to now(),
	// transaction_timestamp(), statement_timestamp(), and clock_timestamp()
	// on the connection.
	// If Now is nil, polite leaves PostgreSQL's default time behavior
	// unchanged.
	//
	// Now is captured by the package-level Dial function and used for
	// the lifetime of the returned Conn; mutating Config.Now afterwards
	// has no effect on existing connections.
	Now func() time.Time
}

Config configures a Dial. All fields are optional; a nil *Config is equivalent to a zero-value Config.

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

Conn is a PostgreSQL connection. Obtain one from Dial or Pool.Get; the zero value is not usable.

Conn is not safe for concurrent use by multiple goroutines. Use Pool for concurrent access from multiple goroutines.

Conn prepares SQL on first use and caches up to a fixed number of prepared statements per connection by exact SQL text, evicting older entries when the cache is full. Calls with the same SQL reuse the cached statement. Server-side prepared statements created for evicted entries are not freed until the connection closes.

This statement cache is used by Conn.Query and Conn.Exec.

If the context passed to Conn.Query or Conn.Exec is canceled or times out while a query is in flight, Conn opens a separate connection to the backend and sends a CancelRequest authenticated with the BackendKeyData captured at startup. The original connection drains the resulting ErrorResponse (SQLSTATE 57014) and ReadyForQuery and remains usable. The error returned from Query/Exec satisfies errors.Is for the context's error (context.Canceled or context.DeadlineExceeded).

func Dial

func Dial(ctx context.Context, dsnOrURL string, cfg *Config) (*Conn, error)

Dial opens a connection to postgres using the parameters in dsnOrURL, which is a DSN or URL. The defaults are host=/tmp (Unix socket), port=5432, user=$(current OS user, falling back to "postgres"), and sslmode=verify-full. See blake.io/polite/dsn for the full set of recognized connection parameters and their defaults.

The supported sslmode values are "disable", "require", and "verify-full". An unset sslmode is treated as "verify-full". Any other value, including libpq's "allow", "prefer", and "verify-ca", is rejected.

Polite's default differs from libpq, which defaults to "prefer" and falls back to plaintext if the server refuses TLS. Polite never falls back: if TLS is requested and the server refuses, Dial returns ErrTLSRefused.

Polite's "require" is stricter than libpq's. Both require TLS, but libpq performs no hostname verification under "require"; polite verifies the server name against the certificate, the same as "verify-full".

The sslrootcert option selects the trust roots for verification. An absolute path loads PEM-encoded certificates from that file; the special value "system" (case-insensitive) loads the host's system trust roots via crypto/x509.SystemCertPool. If sslrootcert is unset, the standard crypto/tls defaults apply. A relative path is rejected: trust-root resolution must not depend on the process working directory. The file is read through os.OpenRoot rooted at its containing directory, so symlinks that escape that directory are refused.

Dial honors ctx through the entire connect path: the dial itself, the TLS handshake, and the startup/auth round-trips. If ctx is canceled mid-handshake, Dial returns ctx.Err(); the partially-opened socket is closed before the call returns. The ctx does not stick to the returned Conn: once Dial succeeds, its cancellation no longer affects the connection, and subsequent Query and Exec calls take their own ctx.

Example

Dial opens a connection using the default DSN, runs a single command, and closes. The shape every other example builds on.

package main

import (
	"context"

	"blake.io/polite"
)

func main() {
	ctx := context.Background()

	cn, _ := polite.Dial(ctx, "", nil)
	defer cn.Close()

	cn.Exec(ctx, "SELECT 1")
}

func (*Conn) Close

func (c *Conn) Close() error

Close sends Terminate, flushes, and closes the underlying connection. It closes the connection even if Terminate cannot be sent.

Close may block briefly. If a Query is in flight, Close waits on a small internal lock for the cancel watcher goroutine to finish before proceeding; the wait is bounded by the in-flight Query's own teardown. Close then sets a 100ms read deadline so the Terminate write cannot hang the caller, and closes the connection regardless of whether the Terminate reached the backend.

After Close, all Conn methods return ErrClosed. A Terminate received from the backend surfaces as febe.ErrTerminated; transport failures and FATAL backend errors surface their own error.

Close returns the error from closing the underlying connection.

func (*Conn) Exec

func (c *Conn) Exec(ctx context.Context, sql string, args ...any) error

Exec executes a query that is not intended to return rows, such as an INSERT, UPDATE, or DELETE. It returns only an error. Any rows the server does return are still read from the connection and discarded.

When a COPY FROM is in progress, calling Exec with an empty sql string sends a single COPY data row encoded from args.

func (*Conn) Idle

func (c *Conn) Idle() bool

Idle reports whether the connection is ready for the next query: the transport is healthy, no COPY is in progress, and the backend is at ReadyForQuery outside any transaction block. It returns false in every other state (mid-query, in a transaction, failed transaction, or terminal transport error).

func (*Conn) Query

func (c *Conn) Query(ctx context.Context, sql string, args ...any) iter.Seq[*Row]

Query executes sql and returns an iterator over its result rows. Each yielded Row carries either column data or an error. Errors are surfaced through Column methods: calling Column.Bytes, Column.DecodeText, Column.DecodeInt, Column.DecodeFloat, or Column.DecodeTime on a column from an error row returns the underlying error. Reading column 0 with Column.Bytes is the canonical zero-allocation error check:

for row := range cn.Query(ctx, sql) {
	if _, err := row.Column(0).Bytes(); err != nil {
		return err
	}
	// ... read remaining columns ...
}

A Query range is active until the loop ends or the caller breaks. While a range is active, further calls to Conn.Query or Conn.Exec on the same Conn return ErrBusy; end the range before calling either again.

The iterator is single-use. A second range yields an error row; call Query again to re-execute.

When COPY FROM enters copy mode, Query yields a Row whose columns report ErrCopyFrom.

When Config.Now is set, Query updates the per-connection clock by running an internal SET before sending sql. If that SET fails, Query yields a single Row carrying the failure and stops without sending sql.

Example (CopyFrom)

COPY ... FROM STDIN is the inverse: bulk-load rows into a table without a round-trip per row. Query starts the COPY and the loop body sends each tuple with Exec and an empty SQL string, which the driver recognizes as a COPY data message. The outer range runs once; the row value is unused.

package main

import (
	"context"

	"blake.io/polite"
)

func main() {
	ctx := context.Background()
	cn, _ := polite.Dial(ctx, "postgres://localhost/mydb", nil)
	defer cn.Close()

	items := []struct {
		ID   int32
		Name string
	}{
		{1, "alice"},
		{2, "bob"},
	}

	for range cn.Query(ctx, "COPY foo FROM STDIN WITH (FORMAT binary)") {
		for _, item := range items {
			cn.Exec(ctx, "", item.ID, item.Name)
		}
	}
}
Example (CopyTo)

COPY ... TO STDOUT streams rows out of the server without going back through the executor for each row, which is the fastest way to read a lot of data. The binary format skips text conversion on both sides. Columns have no names in the COPY stream, so access is by index.

package main

import (
	"context"
	"fmt"

	"blake.io/polite"
)

func main() {
	ctx := context.Background()
	cn, _ := polite.Dial(ctx, "postgres://localhost/mydb", nil)
	defer cn.Close()

	var (
		id   int64
		name string
	)
	for row := range cn.Query(ctx, "COPY foo TO STDOUT WITH (FORMAT binary)") {
		id, _ = row.Column(0).DecodeInt()
		name, _ = row.Column(1).DecodeText()
		fmt.Println(id, name)
	}
}
Example (SqlCast)

SQL casts let the placeholder's encoded type differ from the column's. Polite tells PostgreSQL each parameter's type up front, so a cast in the SQL is a server-side coercion rather than a workaround for the wire format.

Pass a Go int into a text column with $1::text. Pass a Go string into an int4 column with $1::int4. The same pattern reaches types polite does not encode directly — uuid, inet, numeric, jsonb — because PostgreSQL accepts a text representation for each.

package main

import (
	"context"
	"fmt"

	"blake.io/polite"
)

func main() {
	ctx := context.Background()
	cn, _ := polite.Dial(ctx, "", nil)
	defer cn.Close()

	// Go int -> text.
	for row := range cn.Query(ctx, `SELECT $1::text`, 42) {
		s, _ := row.Column(0).DecodeText()
		fmt.Println(s)
	}

	// Go string -> int4.
	for row := range cn.Query(ctx, `SELECT $1::int4`, "42") {
		n, _ := row.Column(0).DecodeInt()
		fmt.Println(n)
	}
}

type Pool

type Pool struct {
	// Dial opens a new connection when the pool needs one. If Dial is
	// nil, the package-level Dial function is used with DefaultDSN and
	// nil config.
	//
	// Dial is invoked with the pool's lifetime context, not the
	// caller's Get context, so canceling a Get does not cancel
	// an in-flight dial.
	//
	// Errors returned by Dial trigger an exponential-backoff retry
	// (sleep capped at 5s) that continues until Close. Permanent
	// errors such as bad credentials, an unknown database, or TLS
	// failures are not surfaced to callers and will retry forever;
	// they are logged through the Logger field. Callers cancel by
	// closing the pool.
	Dial func(ctx context.Context) (*Conn, error)

	// MaxItems is the maximum number of connections that can be open at
	// once. If MaxItems is zero, then DefaultPoolMaxConns is used.
	MaxItems int

	// MaxWaiters is the maximum number of waiters that can be waiting
	// for a connection. If this number is exceeded, Get returns
	// ErrTooManyWaiters. If MaxWaiters is zero, then
	// DefaultPoolMaxWaiters is used.
	MaxWaiters int

	// Logger receives the pool's "error opening new connection;
	// retrying" warnings emitted by the Dial field's retry loop. If
	// Logger is nil, slog.Default is used. To silence these
	// warnings, pass a logger backed by slog.DiscardHandler.
	Logger *slog.Logger
	// contains filtered or unexported fields
}

Pool is a pool of connections, safe for concurrent use by multiple goroutines. See the package documentation for the scheduling discipline.

func (*Pool) Close

func (p *Pool) Close() error

Close closes the pool and every idle connection in it. After Close, Pool.Get returns ErrClosed, and waiters already blocked in Get wake with the same error. Connections checked out via Get keep running and are the caller's to use; Pool.Put closes them when they come back rather than returning them to the pool.

Close does not wait for in-flight operations, checked-out connections, or the Pool.Dial retry loop to unwind, and returns once it has signaled the closure and drained the idle set. The first call returns nil; subsequent calls return context.Canceled.

As a known limitation, an open attempt already in flight when Close runs may complete after Close returns and leak its connection, since Close does not wait for the Pool.Dial retry loop to unwind.

func (*Pool) Exec

func (p *Pool) Exec(ctx context.Context, sql string, args ...any) error

Exec checks a connection out of the pool, runs sql, and returns the connection to the pool. It is the Pool analogue of Conn.Exec for the common one-shot case where the caller does not need to thread a *Conn through several calls.

If the pool cannot supply a connection, Exec returns the error from Pool.Get without running sql. Otherwise it returns whatever Conn.Exec returns. The connection is always returned to the pool; Pool.Put decides whether the connection is still healthy enough to keep.

func (*Pool) Get

func (p *Pool) Get(ctx context.Context) (*Conn, error)

Get returns a connection from the pool.

Get returns ErrTooManyWaiters when the waiting limit is exceeded and ErrClosed when the pool is closed (including waiters woken by a concurrent Pool.Close). If ctx is canceled or times out while waiting, Get returns an error that wraps context.Canceled or context.DeadlineExceeded. No cancel request is sent to PostgreSQL because no operation has started on a connection.

Canceling a Get wait does not cancel an in-flight open attempt started for that wait. If the open later succeeds, a later caller to Pool.Get may receive that connection.

Example
package main

import (
	"context"

	"blake.io/polite"
)

func main() {
	ctx := context.Background()

	p := new(polite.Pool) // use default settings
	defer p.Close()

	cn, _ := p.Get(ctx)
	defer p.Put(cn)

	cn.Exec(ctx, "SELECT 1")
}

func (*Pool) Put

func (p *Pool) Put(cn *Conn)

Put returns cn to the pool. If the pool is closed or cn is not idle, Put closes cn instead. A connection returned in a non-ready state is retired, freeing its slot so the next Pool.Get may dial a fresh connection.

A connection is idle when its transport is healthy, no COPY is in progress, and the backend is at ReadyForQuery outside any transaction block. Callers that leave a connection in any other state must clean it up before calling Put, or accept that Put will close and discard it.

func (*Pool) Query

func (p *Pool) Query(ctx context.Context, sql string, args ...any) iter.Seq[*Row]

Query checks a connection out of the pool, runs sql, and returns the connection to the pool when the iterator finishes. It is the Pool analogue of Conn.Query; the iterator owns the connection for its lifetime, so callers must let the loop run to completion (or break) before issuing another pool operation that depends on the released connection.

If Pool.Get fails, Query yields a single error Row carrying that error and stops. Errors from Conn.Query are surfaced through columns the same way Conn.Query surfaces them; see that method for the iteration contract.

type Row

type Row struct {
	// contains filtered or unexported fields
}

Row is a view of the current result row.

Use Row.Column to read a single column, or Row.Columns to range over all of them. A row may carry an error instead of data; the error surfaces through the Column decoders. Columns borrow the row's storage and are valid only while that row is current.

Row values are reused across iterations on the same Conn. A *Row stashed past the iterator's next yield will see the next row's data, not the original. Copy out anything you need before yielding to the next row.

func (*Row) Column

func (r *Row) Column(i int) Column

Column returns the column at index i. If the row carries an error, the returned Column carries the same error regardless of i. Otherwise Column panics if i is out of range.

The returned Column borrows the row's storage and is valid only while that row is current.

Example

Row.Column(i) addresses a column by position. It fits a tight query with a small, fixed column list, and it is also the way to read columns out of order or more than once without reshaping the SELECT. The column order in the query is load-bearing: swap two columns in the SELECT and the decode silently reads the wrong field. SELECT * is a bad fit here for the same reason; see the Row.Columns example or the struct variant of this example.

package main

import (
	"context"
	"fmt"

	"blake.io/polite"
)

func main() {
	ctx := context.Background()

	cn, _ := polite.Dial(ctx, "", nil)
	defer cn.Close()

	const q = `
		SELECT id, street, city
		FROM addresses
		ORDER BY id
	`
	for row := range cn.Query(ctx, q) {
		var address struct {
			ID     int64
			Street string
			City   string
		}
		address.ID, _ = row.Column(0).DecodeInt()
		address.Street, _ = row.Column(1).DecodeText()
		address.City, _ = row.Column(2).DecodeText()
		fmt.Printf("%#v\n", address)
	}
}
Example (ToStruct)

This is the columns-by-name example in a different shape. The work is the same: pull values out of a row and put them into a struct. Here we let the server assemble the row as JSON and let encoding/json do the field dispatch, so the client code does not spell out a switch over column names. It is a convenience, not a feature. The cost is a JSON round-trip; the benefit is less code when the schema is wide or changes often. Use the Row.Columns example when you want to avoid the encode/decode.

package main

import (
	"context"
	"encoding/json"
	"fmt"

	"blake.io/polite"
)

func main() {
	ctx := context.Background()

	cn, _ := polite.Dial(ctx, "", nil)
	defer cn.Close()

	type User struct {
		ID   int32  `json:"id"`
		Name string `json:"name"`
	}

	const q = `
		SELECT row_to_json(t)
		FROM (
			SELECT 1::int4 AS id, 'alice'::text AS name
			UNION ALL
			SELECT 2::int4, 'bob'::text
		) AS t
	`
	for row := range cn.Query(ctx, q) {
		b, _ := row.Column(0).Bytes()
		var user User
		json.Unmarshal(b, &user)
		fmt.Printf("%#v\n", user)
	}
}

func (*Row) Columns

func (r *Row) Columns() iter.Seq[Column]

Columns returns an iterator over the columns of the row. If the row carries an error, Columns yields a single Column whose decoders all return that error.

Example

Ranging over Columns and switching on Name reads each value by the name it has in the row. Pick this when the column positions in the query might shift, or when the query is SELECT * against a table whose column list can grow. Reordering the SELECT, or adding a column to the table, does not miswire fields here.

package main

import (
	"context"
	"fmt"

	"blake.io/polite"
)

func main() {
	ctx := context.Background()

	cn, _ := polite.Dial(ctx, "", nil)
	defer cn.Close()

	const q = `
		SELECT id, street, city
		FROM addresses
		ORDER BY id
	`
	for row := range cn.Query(ctx, q) {
		var address struct {
			ID     int64
			Street string
			City   string
		}
		for col := range row.Columns() {
			switch col.Name() {
			case "id":
				address.ID, _ = col.DecodeInt()
			case "street":
				address.Street, _ = col.DecodeText()
			case "city":
				address.City, _ = col.DecodeText()
			}
		}
		fmt.Printf("%#v\n", address)
	}
}

Directories

Path Synopsis
cmd
todo command
Command todo is a single-binary to-do list demo for the polite PostgreSQL client.
Command todo is a single-binary to-do list demo for the polite PostgreSQL client.
todo/list
Package list is a tiny, polite-only data layer for the to-do demo.
Package list is a tiny, polite-only data layer for the to-do demo.
Package dsn provides utilities for parsing DSN strings and URLs into a structured Options struct.
Package dsn provides utilities for parsing DSN strings and URLs into a structured Options struct.
Package febe implements the encoding and decoding of Frontend/Backend (FE/BE) messages.
Package febe implements the encoding and decoding of Frontend/Backend (FE/BE) messages.
febeio
This is https://github.com/pkg/json/blob/main/reader.go
This is https://github.com/pkg/json/blob/main/reader.go
internal
backoff
Package backoff yields a retry loop with exponential backoff and jitter.
Package backoff yields a retry loop with exponential backoff and jitter.
scram
Package scram implements the client side of PostgreSQL SCRAM SASL authentication over febe connections.
Package scram implements the client side of PostgreSQL SCRAM SASL authentication over febe connections.
testutil
Package testutil provides utilities for testing with a focus on catching common mistakes, such as using non-idiomatic logging.
Package testutil provides utilities for testing with a focus on catching common mistakes, such as using non-idiomatic logging.
Package lru implements a fixed-capacity cache keyed by K with values of type V.
Package lru implements a fixed-capacity cache keyed by K with values of type V.
Package oids provides OID constants for PostgreSQL's built-in base types.
Package oids provides OID constants for PostgreSQL's built-in base types.
Package potest fetches PostgreSQL binaries from the embedded-postgres Maven Central artifacts and exposes them as an fs.FS rooted at the install.
Package potest fetches PostgreSQL binaries from the embedded-postgres Maven Central artifacts and exposes them as an fs.FS rooted at the install.
xz
Package xz decodes XZ streams whose only filter is LZMA2.
Package xz decodes XZ streams whose only filter is LZMA2.

Jump to

Keyboard shortcuts

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