Documentation
¶
Overview ¶
Package database configures SQL pools, Bun dialects, and transaction scopes. It never runs migrations or owns pools returned to callers.
Index ¶
- Variables
- func Executor(ctx context.Context, db *bun.DB) (bun.IDB, error)
- func Instrument(db *bun.DB, name string, tp trace.TracerProvider, mp metric.MeterProvider) (func() error, error)
- func Open(ctx context.Context, cfg Config) (*bun.DB, error)
- func OpenSQL(ctx context.Context, cfg Config) (*sql.DB, error)
- func RequireNoTransaction(ctx context.Context) error
- func TxFromContext(ctx context.Context, db *bun.DB) (bun.Tx, error)
- type Config
- type ConnectionError
- type Driver
- type TxManager
- func (m *TxManager) Begin(ctx context.Context) (context.Context, error)
- func (m *TxManager) Commit(ctx context.Context) error
- func (m *TxManager) Execute(ctx context.Context, fn func(context.Context) error) (err error)
- func (m *TxManager) Rollback(ctx context.Context) error
- func (m *TxManager) Savepoint(ctx context.Context, fn func(context.Context) error) (err error)
Constants ¶
This section is empty.
Variables ¶
var ( ErrNilDB = errors.New("database: nil database") ErrTxOptionsMismatch = errors.New("database: nested transaction options differ") ErrRollbackOnly = errors.New("transaction marked rollback-only") ErrDifferentDatabase = errors.New("transaction belongs to a different database") ErrNoTransaction = errors.New("context has no transaction") ErrTransactionActive = errors.New("transaction already active; use Execute to join it") ErrManagedTransaction = errors.New("Execute owns transaction completion") )
Functions ¶
func Instrument ¶
func Instrument(db *bun.DB, name string, tp trace.TracerProvider, mp metric.MeterProvider) (func() error, error)
Instrument installs telemetry once, before the borrowed DB is used concurrently. name is a fixed pool label, never a DSN. Providers must be non-nil (no-op is valid). The returned cleanup unregisters pool observation; call it before closing DB. Bun hooks cannot be removed. Raw database/sql calls bypass query instrumentation. Recorded query spans include sanitized SQL when supported; values are never captured.
func Open ¶
Open returns a ready-to-use Bun database. The caller owns Close. Its embedded DB is the same database/sql pool and can be shared with queues and migrations.
func OpenSQL ¶
OpenSQL opens the same configured pool without a Bun wrapper, for SQL-only consumers such as migration commands. The caller owns Close.
func RequireNoTransaction ¶
RequireNoTransaction rejects a transaction-bearing context before an operation performs nontransactional effects such as mail, queue submission or blob writes. Use transactional intent persistence when effects must follow a database commit.
Types ¶
type Config ¶
type Config struct {
Name string `json:"name,omitempty"`
Driver Driver `json:"driver"`
DSN string `json:"dsn,omitempty"`
MaxOpenConns int `json:"max_open_conns"`
MaxIdleConns int `json:"max_idle_conns"`
ConnMaxLifetime time.Duration `json:"conn_max_lifetime"`
ConnMaxIdleTime time.Duration `json:"conn_max_idle_time"`
ConnectTimeout time.Duration `json:"connect_timeout"`
PingTimeout time.Duration `json:"ping_timeout"`
SlowQueryThreshold time.Duration `json:"slow_query_threshold"`
}
Config describes one connection pool. DSN must not be logged. Zero durations and MaxOpenConns select bounded defaults; MaxIdleConns follows database/sql: zero disables idle connections. Use DefaultConfig for recommended idle pooling.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a PostgreSQL pool configuration. Supply DSN before Open.
func (Config) MarshalJSON ¶
MarshalJSON redacts the DSN while retaining normal JSON decoding support for configuration loaders. Serialized configuration is not a credential backup.
type ConnectionError ¶
type ConnectionError struct {
Op string
// contains filtered or unexported fields
}
ConnectionError preserves the driver error for errors.Is/As without putting DSN or server-supplied connection details in normal error output. Unwrapping deliberately exposes the original error; do not log it without redaction.
func (*ConnectionError) Error ¶
func (e *ConnectionError) Error() string
func (*ConnectionError) Unwrap ¶
func (e *ConnectionError) Unwrap() error
type Driver ¶
type Driver string
Driver identifies a supported database implementation. Validate at configuration boundaries.
type TxManager ¶
type TxManager struct {
// contains filtered or unexported fields
}
TxManager can be shared across requests. Each transaction context is owned by a single execution and must not be shared concurrently between goroutines.
func NewTxManager ¶
NewTxManager constructs a transaction manager using a caller-owned database. Options are copied. Nil options join the enclosing transaction's options; explicit options must match when joining an existing scope.
func (*TxManager) Execute ¶
Execute joins an existing scope. Nested errors/panics make the outer scope rollback-only, even when caught. Only the scope that began the transaction ends it.
func (*TxManager) Rollback ¶
Rollback remains usable after cancellation and is idempotent after completion.
func (*TxManager) Savepoint ¶
Savepoint runs fn in an isolated scope of the active transaction. It rolls back that scope on error or panic; successful work still depends on the outer commit. Unlike Execute's nested scopes, a rolled-back Savepoint does not mark its parent rollback-only unless savepoint cleanup fails. The caller must handle its error. An active transaction is required. The database must support SQL savepoints.