postgres

package
v0.28.0 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: Apache-2.0 Imports: 41 Imported by: 5

Documentation

Index

Constants

View Source
const DefaultStartupConnectTimeout = 60 * time.Second

DefaultStartupConnectTimeout is how long Open waits for the database to become reachable when Opts.StartupConnectTimeout is not set.

View Source
const (
	Persistence cdriver.PersistenceType = "postgres"
)

Variables

IsolationLevels maps the isolation levels the pgx driver can begin a transaction with. Postgres has no WRITE COMMITTED or LINEARIZABLE level and pgx rejects both, so Map rejects LevelWriteCommitted and LevelLinearizable before a transaction is opened. pgx runs LevelSnapshot as REPEATABLE READ.

Functions

func EnableTLS added in v0.27.0

func EnableTLS(c *ContainerConfig, dir string) (caPath string, err error)

EnableTLS makes the container c serve TLS. It writes a new CA, a server key pair for c.Host signed by it, and an init script into dir, and binds them into c. It returns the path of the CA certificate a client verifies the server with. dir must stay in place until the container has started. Plaintext connections keep working, as Postgres accepts both.

func NewNamedDriver

func NewNamedDriver(config driver.Config, dbProvider DbProvider) driver.NamedDriver

func NewPersistenceWithOpts

func NewPersistenceWithOpts[V drivercommon.DBObject](cfg *ConfigProvider, dbProvider DbProvider, name driver.PersistenceName, constructor sqlcommon.PersistenceConstructor[V], params ...string) (V, error)

NewPersistenceWithOpts constructs a V backed by the postgres persistence configured under name and params: it resolves the connection options and table names, opens the database, and invokes constructor to build the store, preparing its schema with migrate.CreateSchema. With skipCreateTable it runs no schema step and fails with migrate.ErrPending if the store has steps pending.

func Open

func Open(opts Opts) (*common.RWDB, error)

Open opens a connection pool for opts.DataSource and waits until the database answers a ping, so a node that starts together with its database does not fail. It retries with jittered exponential backoff for opts.StartupConnectTimeout (DefaultStartupConnectTimeout if zero or negative), logs each failed attempt, and then returns an error. Logs and the error identify the database by its data-source label, never by the DSN. ReadDB and WriteDB share the same pool.

func PrimaryKey added in v0.27.0

func PrimaryKey(q rowQuerier, table string) (constraint, cols string, err error)

PrimaryKey returns table's primary-key constraint name, quoted for use in DDL, and its columns in key order, joined by commas.

func RegisterTLSConnection added in v0.17.0

func RegisterTLSConnection(dataSource string, tlsCfg TLSConfig) (string, error)

RegisterTLSConnection maps the sslmode onto a pgx connection config and registers it with the stdlib driver, returning the datasource name to use with sql.Open. For sslmode=disable it returns the original datasource unchanged, avoiding both the registration and any certificate file access.

Registration is memoized per (dataSource, tlsCfg): identical inputs return the same stdlib name on every call. This keeps the returned name stable so the DB provider's connection-pool cache (keyed on the datasource) still deduplicates stores that share a database, and bounds the number of registered configs to one per distinct configuration.

func ReorderPrimaryKey added in v0.27.0

func ReorderPrimaryKey(writeDB *sql.DB, table string) error

ReorderPrimaryKey changes table's primary key from (pkey, ns) to (ns, pkey). Every query that uses this key filters on one namespace, and (ns, pkey) lets that scan start at the namespace. The order is read once without a lock, so a table that already has (ns, pkey) never blocks, and again under ACCESS EXCLUSIVE, so replicas sharing the database reorder the table once. The constraint name comes from pg_constraint, because the table name is configurable. Any other column order is an error and the table is left unchanged.

func ReorderPrimaryKeyTx added in v0.28.0

func ReorderPrimaryKeyTx(ctx context.Context, q migrate.Execer, table string) error

ReorderPrimaryKeyTx is ReorderPrimaryKey inside the caller's transaction q. It reads the key order without a lock, so a table keyed (ns, pkey) is never locked; otherwise it locks table in ACCESS EXCLUSIVE mode until q ends, reads the order again and replaces a (pkey, ns) key, so a node running ReorderPrimaryKey on the same table at the same time waits and then finds the key reordered. Any order other than (ns, pkey) or (pkey, ns) is an error.

func StartPostgres

func StartPostgres(ctx context.Context, c *ContainerConfig, logger Logger) (func(), string, error)

StartPostgres spawns a Postgres container with the given ContainerConfig and Logger. It returns a function to terminate and cleanup the spawned Postgres container, a datasource string that allows to connect to the database. If an error occurs, the closeF is nil and the datasource string is empty.

func WithBinds added in v0.17.0

func WithBinds(binds ...string) option

WithBinds sets the Docker container binds.

func WithContainerImage added in v0.7.0

func WithContainerImage(name string) option

WithContainerImage sets the Postgres dbname.

func WithContainerName added in v0.7.0

func WithContainerName(name string) option

WithContainerName sets the Postgres dbname.

func WithDBName added in v0.7.0

func WithDBName(name string) option

WithDBName sets the Postgres dbname.

func WithHost added in v0.7.0

func WithHost(host string) option

WithHost sets the Postgres port.

func WithPassword added in v0.7.0

func WithPassword(pw string) option

WithPassword sets the Postgres port.

func WithPort added in v0.7.0

func WithPort(port string) option

WithPort sets the Postgres port.

func WithUser added in v0.7.0

func WithUser(user string) option

WithUser sets the Postgres port.

Types

type AuditInfoStore

type AuditInfoStore struct {
	*sqlcommon.AuditInfoStore
}

func NewAuditInfoStore

func NewAuditInfoStore(dbs *drivercommon.RWDB, tables sqlcommon.TableNames) (*AuditInfoStore, error)

type BindingStore

type BindingStore struct {
	*sqlcommon.BindingStore
	// contains filtered or unexported fields
}

func NewBindingStore

func NewBindingStore(dbs *drivercommon.RWDB, tables sqlcommon.TableNames) (*BindingStore, error)

type Config

type Config struct {
	TablePrefix     string
	DataSource      string
	MaxOpenConns    int
	MaxIdleConns    *int
	MaxIdleTime     *time.Duration
	SkipCreateTable bool
	TableNameParams []string
	Tracing         *sqlcommon.TracingConfig
	TLSConfig       *TLSConfig `yaml:"tls" mapstructure:"tls"`
	// StartupConnectTimeout bounds how long opening the database waits for it to become
	// reachable; zero or negative means DefaultStartupConnectTimeout.
	StartupConnectTimeout time.Duration
	// QueryTimeout bounds each statement, and each write transaction as a whole;
	// zero adds no deadline.
	QueryTimeout time.Duration
}

Config is the Postgres persistence configuration read from the persistence opts.

func (*Config) Opts added in v0.27.0

func (c *Config) Opts() Opts

Opts returns the connection options for Open. c must come from ConfigProvider.GetOpts, which fills in the pool defaults.

type ConfigProvider

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

func NewConfigProvider

func NewConfigProvider(config config) *ConfigProvider

func (*ConfigProvider) GetOpts

func (r *ConfigProvider) GetOpts(name driver.PersistenceName, params ...string) (*Config, error)

func (*ConfigProvider) MigrateOptions added in v0.28.0

func (r *ConfigProvider) MigrateOptions(skipCreateTable bool) ([]migrate.Option, error)

MigrateOptions returns the migrate options of a persistence with the given skipCreateTable; see sqlcommon.MigrateOptions.

type ContainerConfig

type ContainerConfig struct {
	Image     string
	Container string
	*DbConfig
	Binds []string
}

ContainerConfig contains the configuration data about a postgres container.

func ConfigFromDataSource added in v0.7.0

func ConfigFromDataSource(s string) (*ContainerConfig, error)

ConfigFromDataSource returns a Postgres container configuration based on a given postgres connection string.

func ConfigFromEnv added in v0.7.0

func ConfigFromEnv() *ContainerConfig

ConfigFromEnv returns a Postgres container configuration based environment variables.

func DefaultConfig

func DefaultConfig(opts ...option) *ContainerConfig

DefaultConfig returns a Postgres container configuration. The configuration entries can be set via option parameters.

type DbConfig

type DbConfig struct {
	DBName string
	User   string
	Pass   string
	Host   string
	Port   string
}

DbConfig contains the configuration data about a postgres database.

func (*DbConfig) DataSource

func (c *DbConfig) DataSource() string

DataSource returns the contents of the DbConfig as data source string.

type DbProvider

type DbProvider interface {
	Get(Opts) (*common.RWDB, error)
}

DbProvider returns the connection pool for a set of Opts. Implementations share one pool among all callers that pass the same DataSource.

func NewDbProvider

func NewDbProvider() DbProvider

NewDbProvider returns a DbProvider that opens each pool with Open and reports no metrics.

func NewDbProviderWithMetrics added in v0.26.0

func NewDbProviderWithMetrics(m *connstate.Metrics, p metrics.Provider) DbProvider

NewDbProviderWithMetrics returns a DbProvider that opens each pool with Open and then monitors it for the lifetime of the process: it reports the pool's reachability as the database component of the connection-state metrics and exports its pool statistics.

type Driver

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

func NewDriver

func NewDriver(config driver.Config) *Driver

func NewDriverWithDbProvider

func NewDriverWithDbProvider(config driver.Config, dbProvider DbProvider) *Driver

func (*Driver) NewAuditInfo

func (d *Driver) NewAuditInfo(name driver.PersistenceName, params ...string) (driver.AuditInfoStore, error)

func (*Driver) NewBinding

func (d *Driver) NewBinding(name driver.PersistenceName, params ...string) (driver.BindingStore, error)

func (*Driver) NewKVS

func (d *Driver) NewKVS(name driver.PersistenceName, params ...string) (driver.KeyValueStore, error)

func (*Driver) NewSignerInfo

func (d *Driver) NewSignerInfo(name driver.PersistenceName, params ...string) (driver.SignerInfoStore, error)

type ErrorMapper

type ErrorMapper struct{}

ErrorMapper maps pgx errors onto the sentinels of the storage driver package, so that callers match them with errors.Is independently of the backend.

func (*ErrorMapper) WrapError

func (*ErrorMapper) WrapError(err error) error

WrapError returns err wrapped around the matching sentinel, or err unchanged when none matches.

A server error is matched by its SQLSTATE. An error the server did not report is driver.ErrConnectionLost when it is a failed connect, a closed or bad connection, a network error or an EOF on the socket; a failed connect includes DNS and TLS failures, which a retry clears only if their cause is transient.

A failed connect joins the errors of every connect attempt, one or two per host of a multi-host data source. It is driver.ErrConnectionLost when any attempt reported a SQLSTATE that maps to driver.ErrConnectionLost, such as too_many_connections, because a later connect can reach the server that reported it. Otherwise its first SQLSTATE decides, so that a rejected password or a missing database is returned unchanged, because retrying it cannot succeed. An attempt without a SQLSTATE does not override another attempt's SQLSTATE: under sslmode=prefer, pgx records one for a TLS handshake the server refused before it retries the same host in plaintext.

A cancelled context is returned unchanged, so that a caller shutting down is not told to retry. A failed connect is a lost connection even when it ended with context.DeadlineExceeded: pgx reports a connect_timeout that way, and because the connect_timeout context derives from the caller's, a caller deadline that expires while connecting produces the same error. A caller that owns a deadline checks its own context before retrying. Any other context.DeadlineExceeded is returned unchanged, although it is a net.Error, because the context expired and not the connection.

type KeyValueStore

type KeyValueStore struct {
	*sqlcommon.KeyValueStore
	// contains filtered or unexported fields
}

KeyValueStore is the Postgres key-value store. Its schema reorders a primary key of (pkey, ns) to (ns, pkey) after the table exists.

func NewKeyValueStore

func NewKeyValueStore(dbs *drivercommon.RWDB, tables sqlcommon.TableNames) (*KeyValueStore, error)

func (*KeyValueStore) CreateSchema added in v0.27.0

func (db *KeyValueStore) CreateSchema() error

func (*KeyValueStore) Steps added in v0.28.0

func (db *KeyValueStore) Steps() []migrate.Step

Steps returns the store's schema steps. Step 1 creates the table if it does not exist and reorders a primary key of (pkey, ns) to (ns, pkey).

type Logger

type Logger interface {
	Debugf(format string, args ...any)
	Errorf(format string, args ...any)
}

type Opts

type Opts struct {
	DataSource      string
	MaxOpenConns    int
	MaxIdleConns    int
	MaxIdleTime     time.Duration
	TablePrefix     string
	TableNameParams []string
	Tracing         *sqlcommon.TracingConfig
	// StartupConnectTimeout bounds how long Open waits for the database; zero or negative
	// means DefaultStartupConnectTimeout.
	StartupConnectTimeout time.Duration
}

Opts are the connection options Open uses for one pool.

type SignerInfoStore

type SignerInfoStore struct {
	*sqlcommon.SignerInfoStore
}

func NewSignerInfoStore

func NewSignerInfoStore(dbs *drivercommon.RWDB, tables sqlcommon.TableNames) (*SignerInfoStore, error)

type TLSConfig added in v0.17.0

type TLSConfig struct {
	Enabled      bool   `json:"enabled"        mapstructure:"enabled"        yaml:"enabled"`
	ServerName   string `json:"server_name"    mapstructure:"server_name"    yaml:"server_name"`
	CertPath     string `json:"cert_path"      mapstructure:"cert_path"      yaml:"cert_path"`
	KeyPath      string `json:"key_path"       mapstructure:"key_path"       yaml:"key_path"`
	RootCertPath string `json:"root_cert_path" mapstructure:"root_cert_path" yaml:"root_cert_path"`
	SSLMode      string `json:"ssl_mode"       mapstructure:"ssl_mode"       yaml:"ssl_mode"`
}

TLSConfig defines the configuration parameters for securing database connections.

Jump to

Keyboard shortcuts

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