postgresconn

package
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplyMigrationPoolTuning added in v1.5.5

func ApplyMigrationPoolTuning(db *gorm.DB) error

ApplyMigrationPoolTuning pins a throwaway migration pool to a minimal size. Migration pools are opened, used for serial DDL, and closed; without this they inherit database/sql's defaults, where MaxOpenConns is unlimited.

func ApplyPoolTuning

func ApplyPoolTuning(db *gorm.DB, config *Config, logger ...schemas.Logger) error

ApplyPoolTuning applies MaxIdleConns, MaxOpenConns, ConnMaxLifetime, and ConnMaxIdleTime. When a logger is supplied the effective pool shape is logged once, so operators can size against the server's max_connections without reading source — note that logstore and configstore open separate pools, so a pod's ceiling is the sum across them.

func BuildDSN

func BuildDSN(config *Config) string

BuildDSN assembles a libpq-style DSN from the validated config.

func Close

func Close(db *gorm.DB, logger schemas.Logger)

Close closes the *sql.DB backing a *gorm.DB, logging any error.

func ConnectUnpooled added in v1.9.0

func ConnectUnpooled(ctx context.Context, sqlDB *sql.DB) (conn *pgx.Conn, ok bool, err error)

ConnectUnpooled opens a connection that sqlDB does not manage, the same way sqlDB opens its own: the password command runs again and the session settings apply. The caller closes it. ok is false when sqlDB was not opened that way; its connections then need nothing beyond the settings an existing one was opened with.

func DisableStatementTimeout added in v1.9.0

func DisableStatementTimeout(ctx context.Context, conn sqlExecQueryer) (func(context.Context) error, error)

DisableStatementTimeout lifts statement_timeout on one dedicated connection for runtime work that legitimately runs long (index builds, materialized view creation and refresh). It returns a function that restores the connection's previous value; call it before the connection goes back to the pool, or close the connection instead. RESET is not a substitute: the pool's timeout is set after connect, so RESET would drop the connection to the server default.

func Open

func Open(dsn string, config *Config, logger gormlogger.Interface) (*gorm.DB, error)

Open opens a *gorm.DB against the configured Postgres instance.

A runtime pool gets the configured statement_timeout and idle_in_transaction_session_timeout on every physical connection. A migration pool does not: configstore and logstore build their migration DSN by forcing default_query_exec_mode=simple_protocol, and that is how Open tells the two apart (see runtimeSessionSettingsSQL).

func RestoreStatementTimeoutOrDiscard added in v1.9.0

func RestoreStatementTimeoutOrDiscard(ctx context.Context, conn rawConn, restore func(context.Context) error, timeout time.Duration) error

RestoreStatementTimeoutOrDiscard runs restore, the function returned by DisableStatementTimeout, and enforces that function's contract: when the restore fails, conn is dropped (a Raw callback returning driver.ErrBadConn) so database/sql closes the physical connection instead of pooling it with statement_timeout lifted. The restore runs under timeout and ignores the cancellation of ctx, which is often already done when cleanup runs.

func RunPasswordCommand

func RunPasswordCommand(ctx context.Context, config *PasswordCommandConfig) (string, error)

RunPasswordCommand executes a configured password command and returns stdout.

func Validate

func Validate(config *Config, requireStaticPassword bool) error

Validate checks required Postgres connection fields.

Types

type Config

type Config struct {
	Host            *schemas.SecretVar     `json:"host"`
	Port            *schemas.SecretVar     `json:"port"`
	User            *schemas.SecretVar     `json:"user"`
	Password        *schemas.SecretVar     `json:"password"`
	PasswordCommand *PasswordCommandConfig `json:"password_command,omitempty"`
	DBName          *schemas.SecretVar     `json:"db_name"`
	SSLMode         *schemas.SecretVar     `json:"ssl_mode"`
	MaxIdleConns    int                    `json:"max_idle_conns"`
	MaxOpenConns    int                    `json:"max_open_conns"`
	ConnMaxLifetime string                 `json:"conn_max_lifetime,omitempty"`
	// ConnMaxIdleTime bounds how long an idle physical connection is kept before
	// being closed. Without it, the idle cap is the only thing controlling pool
	// size, so every burst above MaxIdleConns closes connections on return and
	// reopens them on the next query — each reopen forks a Postgres backend.
	ConnMaxIdleTime string `json:"conn_max_idle_time,omitempty"`
	// StatementTimeout is the server-side statement_timeout set on every runtime
	// pool connection (Go duration string, default 120s; "0" or a negative value
	// leaves the server default). It bounds a runaway query so it cannot hold a
	// pooled connection and its locks indefinitely. Migration pools never get it:
	// they run long index builds and backfills.
	StatementTimeout string `json:"statement_timeout,omitempty"`
	// IdleInTransactionSessionTimeout is the server-side
	// idle_in_transaction_session_timeout set on every runtime pool connection
	// (Go duration string, default 120s; "0" or a negative value leaves the server
	// default). It ends a session left idle inside an open transaction, which
	// otherwise holds row locks and blocks vacuum for as long as it stays open.
	IdleInTransactionSessionTimeout string `json:"idle_in_transaction_session_timeout,omitempty"`
}

Config is the shared Postgres connection configuration used by framework stores.

type PasswordCommandConfig

type PasswordCommandConfig struct {
	Command string   `json:"command"`
	Args    []string `json:"args,omitempty"`
	Timeout string   `json:"timeout,omitempty"`
	// CacheTTL is how long a successfully resolved password is reused across new
	// physical connections (Go duration string, default 60s). Set it below the
	// credential's validity window; a rotation shorter than the TTL will fail
	// connections until the cached value expires.
	CacheTTL string `json:"cache_ttl,omitempty"`
}

PasswordCommandConfig describes a command that prints a Postgres password to stdout.

Jump to

Keyboard shortcuts

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