pgsql

package module
v3.3.2 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 24 Imported by: 0

README

Bun ORM PostgreSQL provider (v3)

PostgreSQL provider for the Melody v3 bunorm integration. It implements bunorm.Provider and produces a Bun database handle configured with the PostgreSQL dialect.

Import path: github.com/precision-soft/melody/integrations/bunorm/pgsql/v3

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 manager registry passes 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: declare the parameter with the parameter registrar's RegisterSecretParameter, or mark one melody registered from the .env artifacts with MarkParameterSecret.

provider := pgsql.NewProvider()

Register it through the core registry by attaching it to a bunorm.ProviderDefinition (see the bunorm README).

The provider itself is registered through the core registry as shown above. Like the MySQL provider, the package also ships an application-level service, an advisory-lock Locker, with a registration helper and a self-registering application module for it (see Distributed lock below).

Options
  • WithPoolConfig — connection-pool sizing via a PoolConfig built with NewPoolConfig.
  • WithTimeoutConfig — every deadline the driver applies, via NewTimeoutConfig, which sets the connect timeout and leaves the read and write deadlines to their 30s defaults, or NewTimeoutConfigWithDeadlines, which sets all three: TimeoutConfig names 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.
  • WithRetryConfig — connection retry/backoff via a RetryConfig built with NewRetryConfig. Retrying is opt-in: without this option Open makes a single attempt.
  • WithPostBuildHook — advanced connector customization (see below).
  • WithInsecure / WithTlsConfig — TLS controls (see below).
Defaults

Applied when the matching option is not set (DefaultPoolConfig, DefaultTimeoutConfig, DefaultRetryConfig):

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

All three configurations fill in field by field: a supplied PoolConfig or TimeoutConfig has every zero field replaced by the listed default, so passing zeros to NewPoolConfig yields the defaults rather than the zeros — on database/sql a zero maximum of open connections means unlimited, which is not a sizing anyone asks for by omission. For the idle cap a zero would mean no idle connection, which PoolConfig cannot express, since a zero takes the default: call SetMaxIdleConns(0) on the *bun.DB the provider returns. A bound you do want lifted is asked for by name: Unlimited, or any negative value, means no deadline for a timeout, no cap on the open connections and none on the idle ones, and no recycling for a lifetime or an idle time. 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, so a partially-filled config cannot collapse the backoff into a re-dial storm.

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.

Where bun's own diagnostics go

Opening a connection through this provider routes bun's own diagnostic channel — the declaration mistakes bun reports through a package-level logger of its own — into the logger handed to the open, as warning records under the message bun diagnostic, exactly as the mysql provider does; see the mysql readme for the whole rule. The latest routing wins, and an open handed no logger, like one refused under an already-cancelled context, routes nothing and leaves the channel where the last routing put it.

TLS

The provider is secure-by-default: pgdriver negotiates a TLS handshake on every Postgres connection.

  • pgsql.WithInsecure(bool) — default false. Pass true to disable TLS entirely and connect over plain TCP (for local development or non-TLS endpoints).
  • pgsql.WithTlsConfig(*tls.Config) — forwards a caller-built *crypto/tls.Config to pgdriver.WithTLSConfig(...). When set, it takes precedence over WithInsecure(...).
// Connect against a local Postgres that does not expose TLS:
provider := pgsql.NewProvider(pgsql.WithInsecure(true))
// 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,
}))

Distributed lock

pgsql.NewLocker(database, options...) returns a lock/contract.Locker backed by PostgreSQL session advisory locks (pg_try_advisory_lock / pg_advisory_unlock) — the Postgres counterpart of the MySQL GET_LOCK locker. Lock names are hashed with FNV-1a (64-bit) into the two 32-bit halves of the advisory key.

locker := pgsql.NewLocker(database) // database is a *bun.DB

namedLock := locker.CreateLock("import:catalog", 30*time.Second)

acquired, err := namedLock.Acquire(runtime)
if err != nil {
    // connection or query error
}
if !acquired {
    // another holder owns the lock — do not proceed
    return
}
defer namedLock.Release(runtime)
  • Try-acquire only. Acquire issues SELECT pg_try_advisory_lock($1, $2) — a non-blocking attempt that returns immediately. A failed acquisition returns (false, nil), not an error.
  • Session-pinned. Each held lock pins a dedicated *sql.Conn for its lifetime; Release runs pg_advisory_unlock on that same connection — on a fresh context, bounded by WithLockReleaseTimeout (default 5s) — before returning it to the pool.
  • Reentrant within a Lock. Calling Acquire on a lock that is already held verifies ownership and returns (true, nil); if the lease was lost it re-acquires on a fresh connection.
  • No TTL. Session advisory locks do not auto-expire — the ttl passed to CreateLock is accepted only for interface compatibility. The lock is released by Release or when its connection drops (e.g. the process dies). For TTL-based auto-expiry, use the Redis backend in integrations/rueidis/v3.
  • Refresh is a liveness probe. Because there is nothing to extend, Refresh instead pings the pinned connection (PingContext, on a fresh context bounded by the release timeout) rather than introspecting pg_locks: a session advisory lock is held for exactly as long as its backend session lives, so a connection that still answers still holds the lock. Only a genuinely dead session fails the refresh — its connection is then discarded and a "lock is no longer held" error returned, matching the lost-lock signal of the other backends. A transient cause such as a cancelled or expired request context can never be mistaken for a lost lock, because the probe does not use the caller's context.
Registering it

Publish the locker under the core locker service name, so handlers resolve it through lock.LockerMustFromResolver without naming this package:

pgsql.RegisterLockerService(registrar, database)

Or bundle it as a self-registering application module — one RegisterModule call registers the locker (opt-in via AsLocker, skipped when the database is nil):

app.RegisterModule(pgsql.NewModule(pgsql.ModuleConfig{Database: database, AsLocker: true}))

A process that wires two lock backends registers the second under a name of its own rather than calling this twice: the door claims the framework's one locker name, and the point of that name is that an application asks for "the locker" and receives whichever backend it configured.

Advanced connector customization

For driver options not exposed by the typed configs, use a post-build hook configured via pgsql.WithPostBuildHook with the pgsql.PostBuildHook signature. The hook runs during Open, after Melody defaults and typed configs are applied and before the SQL database is opened.

provider := pgsql.NewProvider(
    pgsql.WithPostBuildHook(func(ctx context.Context, connector *pgdriver.Connector) error {
        /* 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

View Source
const Unlimited = -1

Unlimited lifts the bound of a PoolConfig or TimeoutConfig field: no deadline for a timeout, no cap on the open or idle connections, no recycling for a lifetime or an idle time. Every negative value reads the same, so a duration read from configuration as -1s lifts it too; a zero field is unset and takes the constructor default, so a configuration assembled from environment keys nobody set keeps the bounds.

Variables

This section is empty.

Functions

func IsDuplicateKey

func IsDuplicateKey(err error) bool

IsDuplicateKey answers on the typed SQLSTATE 23505 alone: a rendered message is no identity.

func RegisterLockerService added in v3.3.0

func RegisterLockerService(registrar ServiceRegistrar, database *bun.DB)

RegisterLockerService publishes the PostgreSQL advisory-lock Locker under the framework's own locker service name, the one lock.LockerMustFromContainer reads, so the backend is a matter of configuration. A process wiring two backends registers the second under a name of its own.

Types

type ConnectionConfig added in v3.3.0

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

func NewConnectionConfig added in v3.3.0

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

func (*ConnectionConfig) Database added in v3.3.0

func (instance *ConnectionConfig) Database() string

func (*ConnectionConfig) Host added in v3.3.0

func (instance *ConnectionConfig) Host() string

func (*ConnectionConfig) Password added in v3.3.0

func (instance *ConnectionConfig) Password() string

func (*ConnectionConfig) Port added in v3.3.0

func (instance *ConnectionConfig) Port() string

func (*ConnectionConfig) SafeContext added in v3.3.0

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

func (*ConnectionConfig) User added in v3.3.0

func (instance *ConnectionConfig) User() string

type Locker added in v3.2.0

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

Locker holds the database handle and the release timeout, both fixed at construction. An advisory lock lives in postgres, on the connection that took it, so one Locker serves concurrent callers without a lock of its own.

func NewLocker added in v3.2.0

func NewLocker(database *bun.DB, options ...LockerOption) *Locker

NewLocker returns a lockcontract.Locker backed by PostgreSQL session advisory locks (pg_try_advisory_lock / pg_advisory_unlock). A session advisory lock has no expiry: it is held by the backend session that took it until it is explicitly released or that session ends. Each lock therefore pins a dedicated *sql.Conn for its lifetime so the lock stays bound to one backend session, and every release runs on a fresh context so a canceled request context can never strand a held lock on a connection that is returning to the pool.

func (*Locker) CreateLock added in v3.2.0

func (instance *Locker) CreateLock(name string, ttl time.Duration) lockcontract.Lock

type LockerOption added in v3.2.0

type LockerOption func(*Locker)

func WithLockReleaseTimeout added in v3.2.0

func WithLockReleaseTimeout(releaseTimeout time.Duration) LockerOption

type Module added in v3.3.0

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

func NewModule added in v3.3.0

func NewModule(config ModuleConfig) *Module

func (*Module) Description added in v3.3.0

func (instance *Module) Description() string

func (*Module) Name added in v3.3.0

func (instance *Module) Name() string

func (*Module) RegisterServices added in v3.3.0

func (instance *Module) RegisterServices(registrar applicationcontract.ServiceRegistrar)

RegisterServices publishes nothing unless the application asked for the locker AND handed a database to take it on. Either half missing publishes nothing, silently, rather than a default: a module registered without a database would publish a provider whose NewLocker panics when the locker is first resolved, and one that registered the locker unasked would silently take the framework's locker name away from whatever backend the application meant to use.

type ModuleConfig added in v3.3.0

type ModuleConfig struct {
	Database *bun.DB
	AsLocker bool
}

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 v3.3.0

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

OpenContext reads a nil context as context.Background() and a nil logger as the emergency logger for its own records.

func (*Provider) OpenForMigration added in v3.3.0

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

OpenForMigration lifts the driver deadlines: a DDL statement past them is cut mid-statement with an i/o timeout.

func (*Provider) OpenForMigrationContext added in v3.3.0

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

type ProviderOption

type ProviderOption func(provider *Provider)

func WithInsecure added in v3.1.0

func WithInsecure(insecure bool) ProviderOption

func WithPoolConfig

func WithPoolConfig(poolConfig *PoolConfig) ProviderOption

func WithPostBuildHook

func WithPostBuildHook(hook PostBuildHook) ProviderOption

func WithRetryConfig

func WithRetryConfig(retryConfig *RetryConfig) ProviderOption

func WithTimeoutConfig

func WithTimeoutConfig(timeoutConfig *TimeoutConfig) ProviderOption

func WithTlsConfig added in v3.1.0

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 ServiceRegistrar added in v3.3.0

type ServiceRegistrar interface {
	RegisterService(serviceName string, provider any, options ...containercontract.RegisterOption)
}

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,
) *TimeoutConfig

NewTimeoutConfig sets the connect timeout and leaves the read and write deadlines zero, which the provider reads as their defaults; NewTimeoutConfigWithDeadlines sets all three.

func NewTimeoutConfigWithDeadlines added in v3.3.0

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

NewTimeoutConfigWithDeadlines sets the connect timeout and the driver's read and write deadlines; a zero field takes its default and a negative one reads as Unlimited.

Jump to

Keyboard shortcuts

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