Help us shape the future of Go! Take the 2026 Go Developer Survey

postgres

package
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 32 Imported by: 0

Documentation

Overview

Package postgres adapts pgx to Foundry's database contracts. Configuration is explicit and construction performs no connection or schema migration.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Module

func Module(name foundation.ProviderID, key foundation.Key[*database.DB], config Config, options ...database.Option) foundation.Module

Module binds a fresh prepared PostgreSQL pool per application. Boot verifies connectivity and shutdown drains its owners through database.Module.

func New

func New(config Config) (database.Adapter, error)

New constructs an application-owned adapter without connecting. Credential and session settings come only from Config. The pgx parser's ambient PGSERVICE setting is rejected because upstream resolves service files before returning.

func Open

func Open(ctx context.Context, config Config, options ...database.Option) (*database.DB, error)

func OpenRouted

func OpenRouted(ctx context.Context, config RoutingConfig, options ...database.Option) (*database.DB, error)

OpenRouted verifies both configured endpoints before returning an owned DB. A configured replica startup failure closes both pools and returns no DB.

func RoutedModule

func RoutedModule(name foundation.ProviderID, key foundation.Key[*database.DB], config RoutingConfig, options ...database.Option) foundation.Module

RoutedModule preserves the ordinary *database.DB service key, model observers and application clock. Both pools share the module's startup and shutdown. Construction is pure; dependency availability is checked during boot.

Types

type Config

type Config struct {
	// RegisterTypes configures each physical connection before it enters the pool.
	// Use the scoped registry for custom PostgreSQL codecs and Go type mappings.
	// The registry cannot be retained or used after this callback returns.
	RegisterTypes   func(context.Context, *TypeRegistry) error
	Host            string
	Port            uint16
	Database        string
	User            string
	Password        secret.String
	TLS             TLSMode
	TLSConfig       *tls.Config
	ApplicationName string
	// Schema selects one existing application schema with no public fallback.
	// Empty preserves the server default. Scoped pools restore this on checkout.
	Schema                  string
	Pool                    database.PoolConfig
	StatementCacheCapacity  int
	MaxProtocolMessageBytes int
	// Server-side session limits, set once per connection in whole
	// milliseconds. Zero keeps the server default. StatementTimeout cancels a
	// statement (QueryCanceled), LockTimeout bounds lock waits
	// (LockNotAvailable) and IdleInTransactionSessionTimeout terminates a
	// session left idle inside an open transaction.
	StatementTimeout                time.Duration
	LockTimeout                     time.Duration
	IdleInTransactionSessionTimeout time.Duration
}

Config owns explicit endpoint, credential and resource settings. TLSConfig is an optional standard TLS configuration; certificate/key material must remain immutable after handing it to the adapter, as required by crypto/tls.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig requires an explicit endpoint and user. It verifies TLS peers, sets UTC session time, and bounds both statement caching and protocol messages.

func ParseURL

func ParseURL(value secret.String) (Config, error)

ParseURL decodes an explicit postgres/postgresql URL without libpq environment fallback or credential-file access. It accepts only sslmode and application_name query keys. Other settings use typed Config fields. Unknown/repeated keys fail.

func (Config) Validate

func (c Config) Validate() error

type RoutingConfig

type RoutingConfig struct {
	Primary            Config
	Read               value.Optional[Config]
	MaxConnections     int
	SlowQueryThreshold time.Duration
	StickyReadWindow   time.Duration
}

RoutingConfig owns typed primary/read endpoints and their combined process connection ceiling. Read omission keeps single-pool behavior. Credentials and TLS configuration retain Config's explicit ownership and redaction rules.

SlowQueryThreshold, when positive, logs statements on either endpoint that take at least that long through the application logger (see database.WithSlowQueryThreshold); zero disables slow-statement logging.

StickyReadWindow, when positive with a read endpoint, routes reads in a database.StickyReads request scope to the primary for that long after a write (see database.WithStickyReads).

func (RoutingConfig) Validate

func (c RoutingConfig) Validate() error

type TLSMode

type TLSMode string

TLSMode selects a single transport policy without plaintext fallback.

const (
	VerifyFull TLSMode = "verify-full"
	RequireTLS TLSMode = "require" // Encrypts transport; does not verify server identity.
	DisableTLS TLSMode = "disable"
)

type TypeRegistry

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

TypeRegistry configures one physical connection during Config.RegisterTypes. Methods serialize registration and fail after that callback returns. Registered codecs and their application-owned state must remain immutable afterward.

func (*TypeRegistry) LoadType

func (r *TypeRegistry) LoadType(ctx context.Context, name string) (typ *pgtype.Type, err error)

LoadType discovers a server type during connection setup. Register its returned descriptor explicitly; load/register dependency types first as required by pgx.

func (*TypeRegistry) RegisterDefaultPgType

func (r *TypeRegistry) RegisterDefaultPgType(value any, name string) error

RegisterDefaultPgType maps exactly the Go type of value to a PostgreSQL type name, as pgx does. Register pointer, slice or array forms explicitly if needed.

func (*TypeRegistry) RegisterType

func (r *TypeRegistry) RegisterType(typ *pgtype.Type) error

RegisterType snapshots the descriptor and native container descriptors, preserving pgx's registration order and name/OID alias semantics. The codec itself is retained.

Jump to

Keyboard shortcuts

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