db

package
v0.1.0 Latest Latest
Warning

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

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

Documentation

Overview

Package db provides internal-only database infrastructure: opening managed connections, wrapping *sql.DB with Bun for supported dialects, connection pool tuning, and secret-safe DSN and error redaction.

This package is not a business or domain layer. It does not define continuity, secure-session, or other application ports or use-case contracts. Callers that may import it are limited to runtime composition roots and concrete store adapters under internal/core; public packages (pkg/lipapi, pkg/lipsdk) and protocol plugins must not depend on it.

Index

Constants

View Source
const DefaultPostgresOpenMigrateTimeout = 2 * time.Minute

DefaultPostgresOpenMigrateTimeout bounds composition-root PostgreSQL open (ping, pool apply) and initial schema migration when callers wrap I/O in context.WithTimeout.

View Source
const DefaultSqliteOpenMigrateTimeout = 30 * time.Second

DefaultSqliteOpenMigrateTimeout bounds composition-root SQLite open and initial schema migration. SQLite open is a local file operation, so the bound is tighter than the Postgres default.

Variables

View Source
var (
	ErrEmptyDSN   = errors.New("db: empty dsn")
	ErrNilDB      = errors.New("db: nil *sql.DB")
	ErrNilContext = errors.New("db: nil context")
)

Sentinel errors for database infrastructure helpers.

Functions

func ApplyPoolSettings

func ApplyPoolSettings(sqldb *sql.DB, s PoolSettings) error

ApplyPoolSettings sets connection pool options on sqldb. Only non-zero fields are applied, preserving driver defaults elsewhere. Fails for nil *sql.DB or invalid settings.

func NewBunDB

func NewBunDB(sqldb *sql.DB, dialect Dialect) (*bun.DB, error)

NewBunDB returns a bun.DB for the given dialect. sqldb must be non-nil; dialect must be DialectPostgres or DialectSQLite.

func OpenPostgres

func OpenPostgres(ctx context.Context, dsn string) (*sql.DB, error)

OpenPostgres opens a PostgreSQL *sql.DB using the Bun pgdriver connector, pings with ctx, and returns an owned handle. Empty DSN is rejected. Errors do not include raw credentials. Common libpq DSN parameters that pgdriver does not honor (for example channel_binding=require emitted by Neon) are stripped before the connector is built so operators can paste managed-provider DSNs directly into config.

func OpenPostgresBun

func OpenPostgresBun(ctx context.Context, dsn string, pool PoolSettings) (*bun.DB, error)

OpenPostgresBun opens PostgreSQL, applies pool settings, and returns an owned *bun.DB (Close closes the underlying sql.DB). dsn must be non-empty after trim.

func OpenSQLiteBun

func OpenSQLiteBun(ctx context.Context, path string) (*bun.DB, error)

OpenSQLiteBun opens (creating if needed) a SQLite file as an owned *bun.DB. ctx bounds ping; Close on the returned *bun.DB closes the underlying sql.DB.

func RedactDSN

func RedactDSN(dsn string) string

RedactDSN returns a string safe to show in operator-facing messages: passwords and similar secrets are elided. Non-URL DSNs are heuristically scrubbed.

func SQLiteFileDSN

func SQLiteFileDSN(path string) (string, error)

SQLiteFileDSN builds a modernc.org/sqlite driver URI with pragma query parameters.

func SanitizePostgresDSN

func SanitizePostgresDSN(dsn string) (string, error)

SanitizePostgresDSN returns dsn with libpq-only query parameters that Bun pgdriver cannot apply removed. Non-URL DSNs are returned unchanged (pgdriver only accepts URL-style DSNs, so a non-URL DSN will fail later with a clear "invalid scheme" error). The function does not log or expose DSN secrets.

func ValidatePoolSettings

func ValidatePoolSettings(s PoolSettings) error

ValidatePoolSettings returns an error if any field is out of the accepted range (negative integers or negative durations). Zero values are valid and mean "unset" for the corresponding setter.

func ValidateTransactionPoolDSN

func ValidateTransactionPoolDSN(dsn string) error

ValidateTransactionPoolDSN rejects connection parameters whose behavior depends on preserving PostgreSQL session state across transactions.

func VerifyPostgresQueryRowContains

func VerifyPostgresQueryRowContains(ctx context.Context, bunDB *bun.DB, description, query string, args []any, fragments ...string) error

VerifyPostgresQueryRowContains runs a read-only PostgreSQL metadata query and checks that the returned text contains every required fragment.

Types

type Dialect

type Dialect string

Dialect names supported by NewBunDB.

const (
	DialectSQLite   Dialect = "sqlite"
	DialectPostgres Dialect = "postgres"
)

type PoolOpener

type PoolOpener func(context.Context, string, PoolSettings) (*bun.DB, error)

type PoolRegistry

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

PoolRegistry owns pools created during one runtime build. It is not a global registry and is only used by the composition root during startup.

Runtime construction opens pools sequentially. openGate keeps that invariant if a caller does invoke Open concurrently, while still allowing a waiting caller's context to cancel. The mutex protects the registry map so Stats and Close can safely run concurrently with callers that inspect it.

func NewPoolRegistry

func NewPoolRegistry(opener PoolOpener) *PoolRegistry

func (*PoolRegistry) Claim

func (r *PoolRegistry) Claim(db *bun.DB) error

Claim marks a successfully bound store against a registry-owned pool so [PruneUnclaimed] will retain it. Open does not claim.

func (*PoolRegistry) Close

func (r *PoolRegistry) Close(ctx context.Context) error

Close marks the registry closed, waits for any in-flight Open (honoring ctx), then closes every pool in the snapshot taken at mark time. Cancellation still closes that snapshot and does not steal the open gate: an in-flight opener observes closed, closes any pool it created, and releases the gate.

func (*PoolRegistry) Len

func (r *PoolRegistry) Len() int

func (*PoolRegistry) Open

func (r *PoolRegistry) Open(ctx context.Context, dsn string, pool PoolSettings) (*bun.DB, error)

Open returns the pool for a sanitized DSN and pool-settings key, creating it on the first request. The caller's context is passed directly to the opener so cancellation and deadlines stop a pending connection attempt.

func (*PoolRegistry) PruneUnclaimed

func (r *PoolRegistry) PruneUnclaimed() error

PruneUnclaimed closes and removes pools that were opened but never [Claim]ed. Claimed pools are retained for later [Close]. Safe to call when closed (no-op).

PruneUnclaimed is a build-phase barrier: the composition root calls it after all Open/Claim operations have completed, so no pool can become claimable while this method is selecting the unclaimed set. Callers must not invoke Open or Claim concurrently with PruneUnclaimed.

func (*PoolRegistry) Stats

func (r *PoolRegistry) Stats() []sql.DBStats

Stats returns a snapshot of database/sql pool statistics for every registry-owned pool, aggregated for observability. Handles are copied under the registry mutex; Stats() is called outside the lock so scrapes do not hold the mutex across driver reads. Safe for concurrent use; order of entries is unspecified.

type PoolSettings

type PoolSettings struct {
	MaxOpenConns    int
	MaxIdleConns    int
	ConnMaxLifetime time.Duration
	ConnMaxIdleTime time.Duration
}

PoolSettings are optional *sql.DB pool fields. Zero values are ignored so driver defaults are preserved. Invalid (negative) values are rejected.

Jump to

Keyboard shortcuts

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