postgres

package
v0.6.91 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 24 Imported by: 2

Documentation

Overview

Package postgres is a PostgreSQL connection as a dependency: a configuration section, a pgx pool traced and measured through the service's OpenTelemetry providers, a query log, pgtx transactions, an optional schema and sqld migrations applied at start, a ping probe.

type Config struct {
    config.Backplane `json:"backplane"`
    DB postgres.Config `json:"db"` // GREETER_DB_DSN, GREETER_DB_POOL_MAX_CONNS, ...
}

//go:embed migrations/*.sql
var migrations embed.FS

db := deps.NewDependency(root, postgres.New(cfg.DB, postgres.Migrations(migrations)))
err := tx.DoSerializable(ctx, db.Get().Trm, func(ctx context.Context) error { ... })

Index

Constants

View Source
const (
	DefaultConnectTimeout           = 5 * time.Second
	DefaultExecMode                 = "cache_statement"
	DefaultStatementCacheCapacity   = 512
	DefaultDescriptionCacheCapacity = 512
	DefaultMaxConns                 = 10
	DefaultListenMaxConns           = 2
	DefaultMaxConnLifetime          = time.Hour
	DefaultMaxConnLifetimeJitter    = 5 * time.Minute
	DefaultMaxConnIdleTime          = 30 * time.Minute
	DefaultHealthCheckPeriod        = time.Minute
	DefaultAcquireTimeout           = 5 * time.Second
)

Defaults of the section: explicit, never derived from the node's CPUs. A zero field of a Config built by hand reads its default too.

Variables

View Source
var (
	// ErrNoDSN: the section has no connection string.
	ErrNoDSN = errors.New("postgres: dsn is required")
	// ErrDSN: the connection string does not parse (not quoted: it may
	// hold a password).
	ErrDSN = errors.New("postgres: dsn does not parse")
	// ErrExecMode: exec_mode names no pgx query execution mode.
	ErrExecMode = errors.New(
		"postgres: exec_mode: want cache_statement, cache_describe, describe_exec, exec or simple_protocol")
)

Errors of Config.

View Source
var ErrAcquireTimeout = errors.New("postgres: no free connection within acquire_timeout")

ErrAcquireTimeout: no connection of the pool came free within pool.acquire_timeout; the caller's own deadline had not passed.

Functions

func New

func New(cfg Config, opts ...Option) deps.Provider[*DB]

New is the provider of the connection: Provide opens it (Open), the probe pings, Close releases the pool.

Types

type Config

type Config struct {
	// DSN is a libpq URL or key=value string (secret: it may hold the
	// password).
	DSN config.Secret `desc:"libpq URL or key=value string." json:"dsn,omitempty"`
	// QueryLog is the lowest level of the per-query log: trace, debug,
	// info, warn, error or none. Arguments are never logged.
	QueryLog string `` /* 151-byte string literal not displayed */
	// ConnectTimeout bounds establishing one connection.
	ConnectTimeout time.Duration `desc:"Bound of establishing one connection." json:"connect_timeout" schemapb:"default=5s;gt=0"`
	// StatementTimeout and IdleInTransactionSessionTimeout are the server
	// settings every connection starts with; 0: the server's own.
	StatementTimeout                time.Duration `` /* 151-byte string literal not displayed */
	IdleInTransactionSessionTimeout time.Duration `` /* 151-byte string literal not displayed */
	// ExecMode is how queries run: cache_statement (prepared and cached),
	// cache_describe, describe_exec, exec or simple_protocol; the last
	// three, and cache_describe, work behind a transaction-mode pooler.
	ExecMode                 string `` /* 165-byte string literal not displayed */
	StatementCacheCapacity   int64  `` /* 159-byte string literal not displayed */
	DescriptionCacheCapacity int64  `` /* 159-byte string literal not displayed */
	Pool                     Pool   `desc:"Connection pool of the queries."                                                           json:"pool"`
	// Listen is the separate small pool of LISTEN/NOTIFY sessions
	// (DB.ListenPool): listeners never take the queries' connections.
	Listen Listen `desc:"Separate pool of LISTEN sessions." json:"listen"`
}

Config is the connection's section.

func (Config) Enabled

func (c Config) Enabled() bool

Enabled reports whether a connection string is set.

func (Config) Validate

func (c Config) Validate() error

Validate checks what the schema cannot: the connection strings are set and parse, the query log level and the exec mode are known.

type DB

type DB struct {
	// Pool for what DB does not cover (COPY, a raw connection). Its own
	// Acquire is not bounded by pool.acquire_timeout; DB's queries are.
	Pool *pgxpool.Pool
	// Trm owns transaction boundaries: tx.Do, tx.DoSerializable.
	Trm tx.Trm
	// DB routes to the context's transaction, else the pool; generated
	// queries run on it, waiting at most pool.acquire_timeout for a free
	// connection (ErrAcquireTimeout).
	DB tx.DB
	// contains filtered or unexported fields
}

DB is the pool with its transaction manager. It is shared by pointer: it holds the pools.

func Open

func Open(ctx context.Context, log *xlog.Logger, cfg Config, opts ...Option) (*DB, error)

Open connects, pings, creates the schema and applies the migrations.

func (*DB) Close

func (db *DB) Close()

Close releases the pools.

func (*DB) ListenPool added in v0.6.86

func (db *DB) ListenPool() *pgxpool.Pool

ListenPool is the separate small pool of LISTEN/NOTIFY sessions (on listen.dsn, else dsn): listeners never take the queries' connections. It connects on first use.

func (*DB) Ping

func (db *DB) Ping(ctx context.Context) error

Ping checks both pools.

type Listen added in v0.6.86

type Listen struct {
	// DSN is a direct connection that bypasses a transaction-mode pooler;
	// empty: the section's dsn.
	DSN                   config.Secret `desc:"Direct connection for LISTEN, bypassing a pooler; empty: dsn." json:"dsn,omitempty"`
	MaxConns              int64         `` /* 126-byte string literal not displayed */
	MaxConnLifetime       time.Duration `` /* 127-byte string literal not displayed */
	MaxConnLifetimeJitter time.Duration `` /* 128-byte string literal not displayed */
	MaxConnIdleTime       time.Duration `` /* 128-byte string literal not displayed */
	HealthCheckPeriod     time.Duration `` /* 127-byte string literal not displayed */
}

Listen is the LISTEN sessions' pool.

type Option

type Option func(o *options)

Option configures Open and New.

func Migrations

func Migrations(fsys ...fs.FS) Option

Migrations are applied at start in version order (sqld's migrate, under its advisory lock): directories of *.sql, e.g. an embed.FS.

func Name added in v0.6.86

func Name(name string) Option

Name labels the pools' metrics (attribute pool; the listen pool's is <name>.listen); New sets the dependency's name. Default "postgres".

func Schema

func Schema(name string) Option

Schema makes every connection run with search_path=name and creates the schema before migrating, so the migrations' bookkeeping lives there too.

func Serializable

func Serializable() Option

Serializable makes serializable the transaction manager's default isolation (read committed without it).

type Pool

type Pool struct {
	MaxConns              int64         `` /* 151-byte string literal not displayed */
	MinConns              int64         `` /* 151-byte string literal not displayed */
	MinIdleConns          int64         `` /* 151-byte string literal not displayed */
	MaxConnLifetime       time.Duration `` /* 151-byte string literal not displayed */
	MaxConnLifetimeJitter time.Duration `` /* 152-byte string literal not displayed */
	MaxConnIdleTime       time.Duration `` /* 152-byte string literal not displayed */
	HealthCheckPeriod     time.Duration `` /* 151-byte string literal not displayed */
	AcquireTimeout        time.Duration `` /* 152-byte string literal not displayed */
}

Pool bounds the queries' pool.

Jump to

Keyboard shortcuts

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