postgres

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package postgres provides pgxpool-backed PostgreSQL access without requiring driver imports.

Index

Constants

View Source
const IdempotencySchema = `` /* 346-byte string literal not displayed */

IdempotencySchema must be applied explicitly by the application's migration system. No constructor runs DDL.

Variables

This section is empty.

Functions

func Classify

func Classify(err error) error

Classify maps supported native error codes while preserving the original cause.

func ConstraintError added in v1.1.0

func ConstraintError(err error) (code, constraint string, ok bool)

ConstraintError exposes PostgreSQL constraint details without exposing pgx.

func IsNoRows added in v1.1.0

func IsNoRows(err error) bool

IsNoRows reports whether the driver returned the no-row condition.

Types

type Client

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

Client owns its configured infrastructure client and supports concurrent operations.

func New

func New(ctx context.Context, c Config) (*Client, error)

New constructs and validates an explicitly owned instance. See package documentation for defaults and cleanup.

func (*Client) AdvisoryLock

func (c *Client) AdvisoryLock(ctx context.Context, key int64) (func(context.Context) error, error)

AdvisoryLock holds a session-level lock on a dedicated connection. Release is mandatory.

func (*Client) Batch

func (c *Client) Batch(ctx context.Context, ops []Operation) (out []Result, err error)

Batch sends commands in one protocol batch; all commands execute in an implicit transaction.

func (*Client) BeginTx

func (c *Client) BeginTx(ctx context.Context, o TxOptions) (*Tx, error)

BeginTx opens a transaction that the caller must commit or roll back.

func (*Client) Close

func (c *Client) Close()

Close releases owned resources. See package documentation for shutdown ordering.

func (*Client) CopyFrom

func (c *Client) CopyFrom(ctx context.Context, table []string, columns []string, values [][]any) (int64, error)

CopyFrom performs PostgreSQL COPY ingestion with safely quoted identifiers.

func (*Client) Exec

func (c *Client) Exec(ctx context.Context, q string, args ...any) (Result, error)

Exec executes a parameterized SQL command and returns its result.

func (*Client) Get

func (c *Client) Get(ctx context.Context, dst any, q string, args ...any) error

Get reads one value into the requested representation.

func (*Client) Listen

func (c *Client) Listen(ctx context.Context, channel string, handler func(string) error) error

Listen owns a dedicated pool connection until ctx ends. The callback must return promptly.

func (*Client) Native

func (c *Client) Native() *pgxpool.Pool

Native provides an explicit advanced driver escape hatch; preserve SDK ownership rules.

func (*Client) Notify

func (c *Client) Notify(ctx context.Context, channel, payload string) error

Notify sends a bound PostgreSQL notification payload.

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) error

Ping checks connectivity using the supplied context.

func (*Client) Prepare

func (c *Client) Prepare(ctx context.Context, query string) (*Statement, error)

Prepare validates and prepares SQL on a pgx-backed connection. Normal queries also retain pgx's native statement cache.

func (*Client) Query

func (c *Client) Query(ctx context.Context, q string, args ...any) (db.Rows, error)

Query opens a row stream; the caller must close it.

func (*Client) QueryRow

func (c *Client) QueryRow(ctx context.Context, q string, args ...any) db.Row

QueryRow returns a single-row scanner; call Scan to execute or observe its error.

func (*Client) SQLDB

func (c *Client) SQLDB() *sql.DB

SQLDB exposes a database/sql bridge for advanced SQL integrations. Close the bridge before closing this Client.

func (*Client) Select

func (c *Client) Select(ctx context.Context, dst any, q string, args ...any) error

Select scans all result rows into a slice pointer.

func (*Client) Stats

func (c *Client) Stats() Stats

Stats returns a concurrency-safe statistics snapshot.

func (*Client) WithinTx

func (c *Client) WithinTx(ctx context.Context, o TxOptions, fn func(*Tx) error) error

WithinTx runs a callback transactionally, rolling back on failure or panic.

type Cluster

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

Cluster owns all configured clients. Writes/transactions belong on Writer; Reader is an explicit consistency choice.

func NewCluster

func NewCluster(ctx context.Context, cfg ClusterConfig) (*Cluster, error)

NewCluster opens pools atomically, cleaning up previously opened pools on any initialization failure.

func (*Cluster) Close

func (c *Cluster) Close()

Close closes replicas in reverse order, then the primary. Drain callers before closing.

func (*Cluster) Reader

func (c *Cluster) Reader(consistency Consistency) (*Client, error)

Reader rotates replicas for Eventual, falling back to primary when none are configured. Strong always uses primary. Replication lag, concurrent writes and failover can invalidate read-after-write assumptions on replicas.

func (*Cluster) Writer

func (c *Cluster) Writer() *Client

Writer returns the primary client for writes and read-after-write consistency.

type ClusterConfig

type ClusterConfig struct {
	Primary  Config
	Replicas []Config
}

ClusterConfig configures independently owned primary/replica pools. Replicas are explicit and are never guessed from SQL.

type Config

type Config struct {
	Hooks                                                  db.Hooks
	QueryLogger                                            *slog.Logger
	ReadOnly                                               bool
	AllowPlaintext                                         bool
	Observer                                               instrument.Hook
	URL                                                    string
	MaxConnections, MinConnections                         int32
	MaxLifetime, MaxIdleTime, ConnectTimeout, QueryTimeout time.Duration
	TLS                                                    *tls.Config
	ApplicationName                                        string
	StatementTimeout                                       time.Duration
	AfterConnect                                           func(context.Context) error
}

Config contains explicit constructor settings; see package documentation for defaults.

type Consistency

type Consistency int

Consistency selects primary freshness or potentially stale replica reads.

const (
	Strong Consistency = iota
	Eventual
)

type Executor added in v1.1.0

type Executor interface {
	Exec(context.Context, string, ...any) (Result, error)
	Query(context.Context, string, ...any) (Rows, error)
	QueryRow(context.Context, string, ...any) Row
}

Executor is the SQL surface shared by Client and Tx.

type IdempotencyStore

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

IdempotencyStore implements atomic durable ownership leases using the database server clock. Expired owners cannot complete; external effects still require authoritative unique business keys or fencing.

func NewIdempotencyStore

func NewIdempotencyStore(c *Client) (*IdempotencyStore, error)

NewIdempotencyStore borrows an existing client. Close the client only after all operations have drained.

func (*IdempotencyStore) Begin

func (s *IdempotencyStore) Begin(ctx context.Context, key, fingerprint string, lease time.Duration) (idempotency.Record, error)

Begin acquires a new/expired/failed lease using one conditional UPSERT. Active/completed conflicts retain their fingerprint.

func (*IdempotencyStore) CleanupExpired

func (s *IdempotencyStore) CleanupExpired(ctx context.Context, limit int) (int64, error)

CleanupExpired deletes at most limit expired records without blocking active owners or other cleanup workers.

func (*IdempotencyStore) Complete

func (s *IdempotencyStore) Complete(ctx context.Context, key, token string, status int, ttl time.Duration) error

Complete persists status metadata only for the current unexpired owner.

func (*IdempotencyStore) Fail

func (s *IdempotencyStore) Fail(ctx context.Context, key, token string, ttl time.Duration) error

Fail allows a matching fingerprint to retry with a new ownership token.

func (*IdempotencyStore) Renew

func (s *IdempotencyStore) Renew(ctx context.Context, key, token string, ttl time.Duration) error

Renew extends an unexpired processing owner using the authoritative server clock.

type NamedArgs

type NamedArgs map[string]any

NamedArgs explicitly opts into pgx's SQL-aware @name parameter binding. No SQL literals or comments are rewritten by the SDK. Do not mutate this map while an operation using it is running.

type Operation

type Operation struct {
	SQL  string
	Args []any
}

Operation contains a parameterized SQL command and its arguments.

type Result

type Result struct {
	RowsAffected int64
	Command      string
}

Result contains operation status without exposing a native driver.

type Row added in v1.1.0

type Row = db.Row

Row and Rows are the driver-neutral database result contracts exposed to consumers. Driver types remain private to this package.

type Rows added in v1.1.0

type Rows = db.Rows

type Statement

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

Statement owns a database/sql prepared statement and a pgxpool bridge. It supports concurrent operations. Close it before closing the Client. PostgreSQL positional placeholders are used in prepared SQL.

func (*Statement) Close

func (s *Statement) Close() error

Close releases the prepared handle and its bridge exactly once.

func (*Statement) Exec

func (s *Statement) Exec(ctx context.Context, args ...any) (Result, error)

Exec executes bound arguments. Command is empty because database/sql does not expose PostgreSQL command tags.

func (*Statement) Get

func (s *Statement) Get(ctx context.Context, dest any, args ...any) error

Get scans exactly one record, returning sql.ErrNoRows when absent.

func (*Statement) Native

func (s *Statement) Native() *sql.Stmt

Native is an explicit escape hatch; the statement remains owned by this handle.

func (*Statement) Query

func (s *Statement) Query(ctx context.Context, args ...any) (db.Rows, error)

Query opens a stream whose deadline ends on Close or exhaustion.

func (*Statement) QueryRow

func (s *Statement) QueryRow(ctx context.Context, args ...any) db.Row

QueryRow defers execution until Scan so resources cannot be acquired by an unconsumed row handle.

func (*Statement) Select

func (s *Statement) Select(ctx context.Context, dest any, args ...any) error

Select replaces the destination slice with all rows on success.

type Stats

type Stats struct {
	Total, Idle, Acquired, Maximum int32
	AcquireCount                   int64
	AcquireDuration                time.Duration
}

Stats contains a snapshot of operational counters.

type Tx

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

Tx owns a transaction; do not share it concurrently.

func (*Tx) Commit

func (t *Tx) Commit(ctx context.Context) error

Commit commits the transaction and reports commit errors.

func (*Tx) Exec

func (t *Tx) Exec(ctx context.Context, q string, a ...any) (Result, error)

Exec executes a parameterized SQL command and returns its result.

func (*Tx) Get

func (t *Tx) Get(ctx context.Context, d any, q string, a ...any) error

Get reads one value into the requested representation.

func (*Tx) Native

func (t *Tx) Native() pgx.Tx

Native provides an explicit advanced driver escape hatch; preserve SDK ownership rules.

func (*Tx) Query

func (t *Tx) Query(ctx context.Context, q string, a ...any) (db.Rows, error)

Query opens a row stream; the caller must close it.

func (*Tx) QueryRow

func (t *Tx) QueryRow(ctx context.Context, q string, a ...any) db.Row

QueryRow returns a single-row scanner; call Scan to execute or observe its error.

func (*Tx) Rollback

func (t *Tx) Rollback(ctx context.Context) error

Rollback rolls back the transaction.

func (*Tx) Select

func (t *Tx) Select(ctx context.Context, d any, q string, a ...any) error

Select scans all result rows into a slice pointer.

func (*Tx) WithinTx

func (t *Tx) WithinTx(ctx context.Context, fn func(*Tx) error) error

WithinTx opens a nested savepoint, using pgx logical transactions.

type TxOptions

type TxOptions struct {
	Isolation string
	ReadOnly  bool
}

TxOptions configures transaction isolation and access.

Jump to

Keyboard shortcuts

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