pgsql

package module
v2.1.2 Latest Latest
Warning

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

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

README

Bun ORM PostgreSQL provider

PostgreSQL provider module for Bun ORM integration with Melody.

This module implements bunorm.Provider and produces a Bun database handle configured with the PostgreSQL dialect.

Import

  • github.com/precision-soft/melody/integrations/bunorm/v2
  • github.com/precision-soft/melody/integrations/bunorm/pgsql/v2

Provider

pgsql.NewProvider builds a pgsql.Provider from optional ProviderOption values. Connection details (Host, Port, Database, User, Password) are supplied at open time through the bunorm.ConnectionParameters the registry hands to Open — the provider itself holds only dialect, transport and driver tuning. Because the provider is given values rather than the configuration keys they came from, arming the framework's credential redaction is the application's call: name the parameters to bunorm.ManagerRegistry.MarkSecretParameters.

Pool, timeout and retry defaults can be overridden via the chainable WithPoolConfig, WithTimeoutConfig and WithRetryConfig methods using PoolConfig, TimeoutConfig and RetryConfig. TimeoutConfig names every deadline the driver applies — NewTimeoutConfig takes the connect, read and write timeouts — because without explicit read and write deadlines pgdriver applies its own defaults, 10 seconds per read and 5 per write, which cut long statements with nothing in this configuration to mention they exist. For statements that must outlive even the configured deadlines, OpenForMigration opens a dedicated connection with the read and write deadlines lifted, which is what the migration commands run on.

Defaults

All three configurations fill in field by field: a supplied PoolConfig or TimeoutConfig has every non-positive field replaced by the listed default, so passing zeros to NewPoolConfig yields the defaults rather than the zeros — on database/sql a zero maximum means unlimited, which is not a sizing anyone asks for by omission. An absent PoolConfig or TimeoutConfig is the whole default (DefaultPoolConfig, DefaultTimeoutConfig). What makes RetryConfig different is absence alone: an absent RetryConfig means no retry at all rather than the defaults, while a supplied one fills in field by field like the other two — except BackoffMultiplier, whose floor is 1: any supplied value below it, NaN included, falls back to the default, while exactly 1 stays a valid constant backoff (NewRetryConfig builds one field by field, and DefaultRetryConfig builds the same shape for callers who want it whole):

Config Field Default
PoolConfig MaxOpenConnections 50
PoolConfig MaxIdleConnections 25
PoolConfig ConnectionMaxLifetime 5m
PoolConfig ConnectionMaxIdleTime 1m
TimeoutConfig ConnectTimeout 5s
TimeoutConfig ReadTimeout 30s
TimeoutConfig WriteTimeout 30s
RetryConfig MaxAttempts 3
RetryConfig InitialDelay 500ms
RetryConfig MaxDelay 5s
RetryConfig BackoffMultiplier 2.0

Retrying is opt-in: without a RetryConfig, Open makes a single attempt.

Opening under a context, and opening for migrations

The host may be an IPv6 literal, bare (::1) or in brackets ([::1]), with the port configured separately: a bare literal is bracketed before the port is joined, a bracketed one is kept as written, and a scoped literal such as fe80::1%eth0 is joined the same way without its zone changing. The default verifying TLS config checks the server certificate against the host without the brackets and without the zone, since no certificate carries either.

TLS

Starting with integrations/bunorm/pgsql v2.0.4 the provider is secure-by-default: pgdriver negotiates a verified TLS handshake on every Postgres connection. Earlier releases of this module called pgdriver.WithInsecure(false), which — despite the name — negotiated TLS with InsecureSkipVerify: true, so the server certificate was never checked.

Two provider options expose the TLS knobs:

  • pgsql.WithInsecure(bool) — default false. Pass true to disable TLS entirely and connect over plain TCP (for local development or non-TLS endpoints). It does not restore an earlier default: before the verifying handshake landed, this provider connected through pgdriver's own insecure mode, which despite its name negotiates TLS with InsecureSkipVerify: true — encrypted but unauthenticated, never plain TCP. true here is a deliberate step further out than that.
  • pgsql.WithTlsConfig(*tls.Config) — forwards a caller-built *crypto/tls.Config to pgdriver.WithTLSConfig(...). When set, it takes precedence over WithInsecure(...).

Example — connect against a local Postgres that does not expose TLS:

provider := pgsql.NewProvider(pgsql.WithInsecure(true))

Example — force TLS with a pinned root CA:

rootCaPool := x509.NewCertPool()
rootCaPool.AppendCertsFromPEM(rootCaPem)

provider := pgsql.NewProvider(pgsql.WithTlsConfig(&tls.Config{
    ServerName: "db.example.com",
    RootCAs:    rootCaPool,
    MinVersion: tls.VersionTLS12,
}))

Advanced connector customization

If you need driver options that are not exposed by TimeoutConfig or other typed configs, use a post-build hook.

The provider constructor accepts optional provider options:

Configure a hook via pgsql.WithPostBuildHook using the pgsql.PostBuildHook signature.

The hook is executed during open, after Melody defaults and typed configs are applied, and before opening the SQL database.

Example:

package main

func main() {
    provider := pgsql.NewProvider(
        pgsql.WithPostBuildHook(func(ctx context.Context, connector *pgdriver.Connector) error {
            _ = ctx

            /* WithInsecure(true) leaves TLSConfig nil, so the hook must not assume one is there */
            tlsConfig := connector.Config().TLSConfig
            if nil == tlsConfig {
                return nil
            }

            tlsConfig.InsecureSkipVerify = true

            return nil
        }),
    )
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsDuplicateKey

func IsDuplicateKey(err error) bool

IsDuplicateKey answers on the typed SQLSTATE alone — 23505, unique_violation — read through whichever of the two driver shapes the chain carries. A rendered message is no identity: any error whose text happens to contain those digits (a quoted value, a constraint name) would pass a substring probe, while a driver error wrapped in an exception whose message hides its cause would fail one; errors.As sees through the wrapping either way.

Types

type ConnectionConfig

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

func NewConnectionConfig

func NewConnectionConfig(host string, port string, database string, user string, password string) *ConnectionConfig

func (*ConnectionConfig) Database

func (instance *ConnectionConfig) Database() string

func (*ConnectionConfig) Host

func (instance *ConnectionConfig) Host() string

func (*ConnectionConfig) Password

func (instance *ConnectionConfig) Password() string

func (*ConnectionConfig) Port

func (instance *ConnectionConfig) Port() string

func (*ConnectionConfig) SafeContext

func (instance *ConnectionConfig) SafeContext() map[string]any

func (*ConnectionConfig) User

func (instance *ConnectionConfig) User() string

type PoolConfig

type PoolConfig struct {
	MaxOpenConnections    int
	MaxIdleConnections    int
	ConnectionMaxLifetime time.Duration
	ConnectionMaxIdleTime time.Duration
}

func DefaultPoolConfig

func DefaultPoolConfig() *PoolConfig

func NewPoolConfig

func NewPoolConfig(
	maxOpenConnections int,
	maxIdleConnections int,
	connectionMaxLifetime time.Duration,
	connectionMaxIdleTime time.Duration,
) *PoolConfig

type PostBuildHook

type PostBuildHook func(
	ctx context.Context,
	connector *pgdriver.Connector,
) error

type Provider

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

func NewProvider

func NewProvider(
	providerOptions ...ProviderOption,
) *Provider

func (*Provider) Open

func (instance *Provider) Open(params bunorm.ConnectionParameters, logger loggingcontract.Logger) (*bun.DB, error)

func (*Provider) OpenContext added in v2.1.0

func (instance *Provider) OpenContext(ctx context.Context, params bunorm.ConnectionParameters, logger loggingcontract.Logger) (*bun.DB, error)

OpenContext opens under the caller's context: an already-cancelled context is refused before the attempt, the retry sleeps watch it beside the clock, and the configuration hook and the boot ping derive their budgets from it; pgdialect makes no server round trip at construction, so the first packet is the boot ping's dial under the caller's context. A nil context reads as context.Background(), which is exactly Open. A nil logger reads as the emergency logger, since the terminal branches mark the returned error as logged and the diagnostics routing consumes a process-lifetime once, so both need a sink that writes.

func (*Provider) OpenForMigration added in v2.1.0

func (instance *Provider) OpenForMigration(params bunorm.ConnectionParameters, logger loggingcontract.Logger) (*bun.DB, error)

OpenForMigration opens the same database with the driver deadlines lifted: ReadTimeout and WriteTimeout are per-operation socket deadlines baked into the connector, sized for request traffic, and a DDL statement that legitimately runs past them — an ALTER TABLE adding constraints on a large table, a long CREATE INDEX — is cut mid-statement with an i/o timeout. The connect timeout stays armed (a down database must still fail fast), the pool is kept to the two connections a sequential migration run needs, and no connection is recycled mid-run — a lifetime rotation under a running statement is the same cut by another name.

func (*Provider) OpenForMigrationContext added in v2.1.0

func (instance *Provider) OpenForMigrationContext(ctx context.Context, params bunorm.ConnectionParameters, logger loggingcontract.Logger) (*bun.DB, error)

OpenForMigrationContext is OpenForMigration under the caller's context, the way OpenContext is Open under it: the registry hands the context it was constructed with, so an already-cancelled migration is refused before the attempt and a cancellation arriving mid-attempt is honoured at the next cancellable step instead of sleeping out the retry budget. A nil context reads as context.Background(), which is exactly OpenForMigration.

func (*Provider) WithPoolConfig

func (instance *Provider) WithPoolConfig(poolConfig *PoolConfig) *Provider

func (*Provider) WithRetryConfig

func (instance *Provider) WithRetryConfig(retryConfig *RetryConfig) *Provider

func (*Provider) WithTimeoutConfig

func (instance *Provider) WithTimeoutConfig(timeoutConfig *TimeoutConfig) *Provider

type ProviderOption

type ProviderOption func(provider *Provider)

func WithInsecure added in v2.0.1

func WithInsecure(insecure bool) ProviderOption

func WithPostBuildHook

func WithPostBuildHook(hook PostBuildHook) ProviderOption

func WithTlsConfig added in v2.0.1

func WithTlsConfig(tlsConfig *tls.Config) ProviderOption

type RetryConfig

type RetryConfig struct {
	MaxAttempts       uint32
	InitialDelay      time.Duration
	MaxDelay          time.Duration
	BackoffMultiplier float64
}

func DefaultRetryConfig

func DefaultRetryConfig() *RetryConfig

func NewRetryConfig

func NewRetryConfig(
	maxAttempts uint32,
	initialDelay time.Duration,
	maxDelay time.Duration,
	backoffMultiplier float64,
) *RetryConfig

type TimeoutConfig

type TimeoutConfig struct {
	ConnectTimeout time.Duration
	ReadTimeout    time.Duration
	WriteTimeout   time.Duration
}

TimeoutConfig names every deadline the driver applies, so none governs invisibly: left out, pgdriver's own defaults of 10 seconds per read and 5 per write would cut every query that runs past them.

func DefaultTimeoutConfig

func DefaultTimeoutConfig() *TimeoutConfig

func NewTimeoutConfig

func NewTimeoutConfig(
	connectTimeout time.Duration,
	readTimeout time.Duration,
	writeTimeout time.Duration,
) *TimeoutConfig

Jump to

Keyboard shortcuts

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