bunorm

package module
v3.6.7 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 17 Imported by: 3

README

Bun ORM integration (v3)

This directory contains the optional Bun ORM integration for Melody v3.

The integration is split into independent Go modules so consumers depend only on what they need:

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

What you get

  • A dialect-agnostic manager registry (bunorm.ManagerRegistry) that:
    • Caches one bunorm.Manager 1:1 per provider definition (bunorm.ProviderDefinition).
    • Supports exactly one default provider (error if multiple defaults).
    • Falls back to the first provider as default if none is marked.
  • A bunorm.Manager that owns a single Bun database handle and exposes DefinitionName(), Database() *bun.DB, and Close() error.
  • A bunorm.ReadWriteSplitter that routes writes to a primary manager and reads to one or more replica managers held in the same registry.

Connection parameters

A provider opens a database from an explicit bunorm.ConnectionParameters value (Host, Port, Database, User, Password) — the caller reads these from config/environment and passes them in. SafeContext() returns the parameters with the password omitted, suitable for logging.

The bunorm.Provider contract is a single method:

Open(params ConnectionParameters, logger loggingcontract.Logger) (*bun.DB, error)

Usage

The pattern is:

  1. Register a *bunorm.ManagerRegistry service (explicit id), built from one ProviderDefinition per database.
  2. Register the default *bunorm.Manager as a service that can be autowired by type.
  3. Consume *bunorm.Manager (default) in your services/handlers.
  4. Optionally, resolve the registry and request a named manager for a non-default database.
Service registration example
package main

import (
    "os"

    melodybunorm "github.com/precision-soft/melody/integrations/bunorm/v3"
    melodymysql "github.com/precision-soft/melody/integrations/bunorm/mysql/v3"
    applicationcontract "github.com/precision-soft/melody/v3/application/contract"
    "github.com/precision-soft/melody/v3/container"
    containercontract "github.com/precision-soft/melody/v3/container/contract"
    "github.com/precision-soft/melody/v3/logging"
)

const (
    ServiceManagerRegistryId = "service.database.manager.registry"
    ServiceManagerDefaultId  = "service.database.manager.default"

    ManagerPrimaryName = "primary"
    ManagerAdminName   = "admin"
)

func RegisterDatabaseServices(registrar applicationcontract.ServiceRegistrar) {
    registrar.RegisterService(
        ServiceManagerRegistryId,
        func(resolver containercontract.Resolver) (*melodybunorm.ManagerRegistry, error) {
            return melodybunorm.NewManagerRegistry(
                logging.LoggerMustFromResolver(resolver),
                melodybunorm.ProviderDefinition{
                    Name:     ManagerPrimaryName,
                    Provider: melodymysql.NewProvider(),
                    Params: melodybunorm.ConnectionParameters{
                        Host:     os.Getenv("DB_HOST"),
                        Port:     os.Getenv("DB_PORT"),
                        Database: os.Getenv("DB_DATABASE"),
                        User:     os.Getenv("DB_USER"),
                        Password: os.Getenv("DB_PASSWORD"),
                    },
                    IsDefault: true,
                },
                melodybunorm.ProviderDefinition{
                    Name:     ManagerAdminName,
                    Provider: melodymysql.NewProvider(),
                    Params: melodybunorm.ConnectionParameters{
                        Host:     os.Getenv("ADMIN_DB_HOST"),
                        Port:     os.Getenv("ADMIN_DB_PORT"),
                        Database: os.Getenv("ADMIN_DB_DATABASE"),
                        User:     os.Getenv("ADMIN_DB_USER"),
                        Password: os.Getenv("ADMIN_DB_PASSWORD"),
                    },
                },
            )
        },
    )

    registrar.RegisterService(
        ServiceManagerDefaultId,
        func(resolver containercontract.Resolver) (*melodybunorm.Manager, error) {
            registry := container.MustFromResolver[*melodybunorm.ManagerRegistry](resolver, ServiceManagerRegistryId)

            return registry.DefaultManager()
        },
    )
}

NewManagerRegistry takes a logging/contract.Logger as its first argument (it is handed to every Provider.Open), then the provider definitions as variadic values. It fails with ErrLoggerIsRequired on a nil logger and ErrNoProviderDefinitions when no definition is given. NewManagerRegistryWithContext additionally binds the registry to a context its lazy opens run under: a provider that implements ContextOpener refuses an open the context already cancelled and has its retry sleeps watch the context alongside the clock, and the same preference reaches the migration open through MigrationContextOpener. Because this major hands providers the connection values rather than the configuration keys they came from, this registry declares no credential of its own and carries no marking door: arming the framework's redaction is the application's call, through the parameter registrar's own RegisterSecretParameter for a parameter the application declares and MarkParameterSecret for one melody registered from the .env artifacts. The mark propagates to every parameter whose template reads the secret, so the assembled dsn is redacted with it and debug:parameters masks the password in a process that never opens a connection. Opening a connection also routes bun's own diagnostic channel into the application's journal through RouteDiagnostics.

Bun's logger is one variable for the whole process, so it is SET once — but what is set is a forwarder onto a destination RouteDiagnostics replaces whenever it is called with a different logger, and the destination is what decides where a record goes; a routing on the logger already installed changes nothing, so the providers routing on every open allocate nothing. A process that builds, closes and rebuilds its application therefore has each lifecycle take the channel back, where the first one used to keep it for the life of the process and every later lifecycle's diagnostics were dropped into a logger that was closed. ResetDiagnostics() hands the channel back to standard error, which is where bun writes when nobody routes it at all; it is the door for a host process that keeps its own reporting for bun. The registry's own Close hands the channel back only when it is its own — routed to the registry's logger — so a second registry in the same process keeps its channel through the first one's teardown. Two registries built on one logger are two owners, not one: each hands its providers the logger under an identity of its own, so whichever opened last holds the channel, and a close hands it back only while that registry's own routing is the live one — the survivor's routing is left in place, and its next open takes the channel again.

SetLogger replaces the logger a registry reports through, and takes bun's diagnostic channel with it, so the two cannot drift apart. It exists for the wiring window an application cannot avoid: a registry assembled while the modules are still being wired has no application logger to be handed — the framework's own does not exist yet — so it is built on the emergency logger, and without this door every later open, every retry warning and every terminal connection failure would keep bypassing the journal. A nil logger, and a typed nil holding no value, are refused with ErrLoggerIsRequired.

A provider receives the registry's own logger, which carries the application's under an identity the registry owns: read it through loggingcontract.Logger and do not assert its concrete type. It forwards the logger's level threshold, and it is how the registry recognises a routing made through it whatever the logger's own comparability — a logger held by value, carrying a slice, a map or a func, is recognised at the registry's Close like any other. SetLogger and Close retire the logger handed out before, and a routing through a retired logger routes nothing, so an open still in flight when the logger was replaced or the registry closed cannot take bun's channel back onto it.

Register the registry with a provider that RESOLVES the logging service rather than one that captures a pre-built registry. The container records a teardown dependency at the moment one service resolves another and closes dependents before their dependencies, so a resolving provider gets the registry closed ahead of the journal for free — which is what lets its Close tear down the pools and hand bun's channel back while the journal is still open. A capturing provider resolves nothing, declares nothing, and leaves the two closes ordered by coincidence; where a provider genuinely has nothing to resolve, the container's WithTeardownDependency writes the same edge declaratively.

Close ends every pool the registry memoized, then WAITS for the opens that were still in flight when it published its refusal — and it ENDS them: the refusal cancels the registry's own open context, which every provider of this repository honours in its retry sleeps and its dials, so an open in flight returns instead of dialling on, an open that returns ends its own freshly opened database against the closed flag, and nothing leaks. Close used to leave them running under the registry's context, each further attempt routing bun's diagnostics back onto the logger the teardown had just handed back, and to return while a dial was still in the air — a process exiting on that answer left the connection outstanding, its server-side session to be reaped by a timeout rather than ended. The wait is unbounded on Close and ends with the caller's deadline on CloseWithContext, which is the door the framework container's ordered teardown prefers: a dial a driver does not cut on cancellation ends when the driver gives up, which can outlive a teardown, so the answer then names the opens it stopped waiting for rather than having ended them.

CloseMigrationDatabase(name) releases one hold on the dedicated migration connection for one definition — every MigrationDatabase takes a hold, so two migration commands in one process share the connection — and with the last hold ends it and forgets it, so the next MigrationDatabase for that name opens a fresh one. That connection is not a request pool and must not live like one: it deliberately lifts the driver's read and write deadlines and recycles nothing, which is right for a DDL statement that runs for minutes and wrong for anything that then sits idle. The migration commands call it on their way out; the registry's Close stays the net underneath for whatever did not. An empty name selects the default definition, a name with no migration connection is not an error, and a closed registry refuses it.

HasProviderDefinition(name) answers whether a definition is registered under the name, without opening anything — the question of a command that only labels a manager. The migrate module's db:create asks it, since it writes its file from the migrations collection alone and no longer opens the database that used to validate --manager.

Consuming the default database
package main

import melodybunorm "github.com/precision-soft/melody/integrations/bunorm/v3"

type ApiService struct {
    databaseManager *melodybunorm.Manager
}

func NewApiService(databaseManager *melodybunorm.Manager) *ApiService {
    return &ApiService{databaseManager: databaseManager}
}

func (instance *ApiService) Database() {
    database := instance.databaseManager.Database()
    _ = database
}
Consuming a non-default database
adminManager := registry.MustManager(ManagerAdminName)
adminDatabase := adminManager.Database()
Read/write splitting
splitter := melodybunorm.NewReadWriteSplitter(registry, ManagerPrimaryName, "replica-1", "replica-2")

writer, _ := splitter.Writer()  // always the primary
reader, _ := splitter.Reader()  // a replica (or the primary if none configured)

Reader round-robins the replicas and falls back to the primary only when a replica is unreachable — an open failure its provider classified as transient and could not get past, answered by ErrDatabaseUnreachable: the outage where reading from the primary is the availability trade the splitter exists to make. Every other failure is refused instead of absorbed — a replica name the registry does not know, an empty name, a closed registry, a provider that answered neither a database nor an error, and every refusal the provider or the server gave by name (a parameter left empty, a password the server refused, a database that does not exist): each is a wiring error, permanent by nature, and folding it into the fallback routed every read to the primary forever with no signal. The pgsql and mysql providers file an outage under the class through DatabaseUnreachable; a provider of your own that files nothing has every failure read as a refusal, the direction that surfaces a misconfiguration. When the primary then fails too, the error carries the primary failure as its cause and names the replica failure beside it. An empty replica name is refused at construction.

An unreachable replica is remembered for a retry interval, five seconds by default: inside it the replica's share of the reads goes to the primary without dialling it again, so a dead replica no longer costs every read a connect timeout, and the first read after it dials the replica again. The move is journaled once each way through the registry's logger, a warning naming the replica, the primary and the interval when reads move to the primary, and an info when the replica takes them back. The interval is set through the options constructor:

splitter := melodybunorm.NewReadWriteSplitterWithOptions(
    registry,
    ManagerPrimaryName,
    []string{"replica-1", "replica-2"},
    melodybunorm.WithReplicaRetryInterval(30*time.Second),
)

Dialect providers

Each dialect module implements bunorm.Provider: it builds the driver connector, constructs a Bun database handle with the correct dialect, and performs an initial PingContext, failing fast on an error unless a RetryConfig retries a transient one with backoff. Both expose typed PoolConfig/TimeoutConfig and an optional post-build hook for driver options not surfaced by the typed configs.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrDatabaseUnreachable = errors.New("database unreachable")

ErrDatabaseUnreachable is the class of an open failure the provider classified as TRANSIENT — a dial refused, a name that would not resolve, a timeout — and could not get past: the outage a ReadWriteSplitter absorbs by reading from the primary. Every other open failure is terminal by nature — a parameter the provider refused, a password the server refused, a database that does not exist — and reaches the caller as it is, so a replica whose configuration is wrong is refused instead of served silently from the primary. A provider that does not mark its failures has them read as terminal, which is the direction that surfaces a misconfiguration.

View Source
var ErrLoggerIsRequired = errors.New("logger is required")
View Source
var ErrManagerRegistryClosed = errors.New("manager registry is closed")
View Source
var ErrMultipleDefaultProviderDefinitions = errors.New("multiple provider definitions are marked as default")
View Source
var ErrNoProviderDefinitions = errors.New("no provider definitions are registered")
View Source
var ErrProviderDefinitionNameIsRequired = errors.New("provider definition name is required")
View Source
var ErrProviderDefinitionNameMustBeUnique = errors.New("provider definition name must be unique")
View Source
var ErrProviderDefinitionNotFound = errors.New("provider definition not found")
View Source
var ErrProviderIsRequired = errors.New("provider is required")
View Source
var ErrProviderReturnedNilDatabase = errors.New("provider returned neither a database nor an error")

Functions

func DatabaseUnreachable added in v3.6.0

func DatabaseUnreachable(openErr error) error

DatabaseUnreachable files an open failure under ErrDatabaseUnreachable. The link sits under the provider's exception as its cause — the exception keeps its message and its context — and unwraps to the failure the provider saw, so errors.Is answers the class, errors.As still reaches the driver error, and a journal that renders the cause chain reads the class once, where the driver failure stood.

func ResetDiagnostics added in v3.6.0

func ResetDiagnostics()

ResetDiagnostics hands bun's diagnostic channel back to standard error, whoever routed it, so a teardown writes nothing into a journal that is closing and a process hosting melody can take the channel for its own logger. Calling it when nothing is routed changes nothing. A registry's own teardown does not call it: the registry retires its logger and hands the channel back only when the live routing is that logger's, so one registry closing does not take the channel from another.

func RouteDiagnostics added in v3.6.0

func RouteDiagnostics(logger loggingcontract.Logger)

RouteDiagnostics sends bun's own diagnostic channel, which reports declaration mistakes such as an unknown struct tag option, to the application's journal as warning records. Bun's logger is set once for the process, to a forwarder whose destination each routing on a different logger replaces, so a rebuilt application takes the channel back; a routing on the logger already installed changes nothing, and a nil or typed-nil logger routes nothing. The mysql dialect's server-version line goes through the standard library's default logger and is not reached; see the mysql readme.

Types

type ConnectionParameters added in v3.5.0

type ConnectionParameters struct {
	Host     string
	Port     string
	Database string
	User     string
	Password string
}

func (*ConnectionParameters) SafeContext added in v3.5.0

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

type ConnectionParams deprecated

type ConnectionParams = ConnectionParameters

Deprecated: use ConnectionParameters.

type ContextOpener added in v3.6.0

type ContextOpener interface {
	OpenContext(ctx context.Context, params ConnectionParameters, logger loggingcontract.Logger) (*bun.DB, error)
}

ContextOpener is the optional capability of opening under a caller's context: the retry loop between attempts sleeps on the context as well as the clock, so a shutdown that cancels it reaches a dial in flight instead of sleeping through the whole retry budget — the exact window in which supervisors send their signals. The registry prefers it whenever the provider implements it, handing a child of the context it was constructed with, which CloseWithContext also cancels, so no open goes on dialling after the registry is gone.

type Manager

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

func NewManager

func NewManager(definitionName string, database *bun.DB) *Manager

func (*Manager) Close

func (instance *Manager) Close() error

func (*Manager) Database

func (instance *Manager) Database() *bun.DB

func (*Manager) DefinitionName

func (instance *Manager) DefinitionName() string

type ManagerRegistry

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

func NewManagerRegistry

func NewManagerRegistry(logger loggingcontract.Logger, providerDefinitions ...ProviderDefinition) (*ManagerRegistry, error)

NewManagerRegistry is container-level deliberately: a *bun.DB is a process-lifetime pool, not a pool per scope.

func NewManagerRegistryWithContext added in v3.6.0

func NewManagerRegistryWithContext(ctx context.Context, logger loggingcontract.Logger, providerDefinitions ...ProviderDefinition) (*ManagerRegistry, error)

func (*ManagerRegistry) Close

func (instance *ManagerRegistry) Close() error

func (*ManagerRegistry) CloseMigrationDatabase added in v3.6.0

func (instance *ManagerRegistry) CloseMigrationDatabase(name string) error

func (*ManagerRegistry) CloseWithContext added in v3.6.0

func (instance *ManagerRegistry) CloseWithContext(closeContext context.Context) error

CloseWithContext tears the pools down whatever the deadline says; the deadline bounds only the wait for opens in flight.

func (*ManagerRegistry) Database

func (instance *ManagerRegistry) Database(name string) (*bun.DB, error)

func (*ManagerRegistry) DefaultDatabase

func (instance *ManagerRegistry) DefaultDatabase() (*bun.DB, error)

func (*ManagerRegistry) DefaultManager

func (instance *ManagerRegistry) DefaultManager() (*Manager, error)

func (*ManagerRegistry) HasProviderDefinition added in v3.6.0

func (instance *ManagerRegistry) HasProviderDefinition(name string) bool

func (*ManagerRegistry) Manager

func (instance *ManagerRegistry) Manager(name string) (*Manager, error)

func (*ManagerRegistry) MigrationDatabase added in v3.6.0

func (instance *ManagerRegistry) MigrationDatabase(name string) (*bun.DB, bool, error)

MigrationDatabase takes a hold when it answers the dedicated connection; CloseMigrationDatabase releases the hold.

func (*ManagerRegistry) MustDatabase

func (instance *ManagerRegistry) MustDatabase(name string) *bun.DB

func (*ManagerRegistry) MustDefaultDatabase

func (instance *ManagerRegistry) MustDefaultDatabase() *bun.DB

func (*ManagerRegistry) MustDefaultManager

func (instance *ManagerRegistry) MustDefaultManager() *Manager

func (*ManagerRegistry) MustManager

func (instance *ManagerRegistry) MustManager(name string) *Manager

func (*ManagerRegistry) SetLogger added in v3.6.0

func (instance *ManagerRegistry) SetLogger(logger loggingcontract.Logger) error

type MigrationContextOpener added in v3.6.0

type MigrationContextOpener interface {
	OpenForMigrationContext(ctx context.Context, params ConnectionParameters, logger loggingcontract.Logger) (*bun.DB, error)
}

MigrationContextOpener is what ContextOpener is to Open: the migration open under the caller's context, so a db:migrate that receives SIGTERM against a down database refuses at the first cancellable step. The registry asks for it only of a provider that also implements MigrationProvider, and prefers it there; implemented alone it is never called, the migration commands running on the pooled connection.

type MigrationProvider added in v3.6.0

type MigrationProvider interface {
	OpenForMigration(params ConnectionParameters, logger loggingcontract.Logger) (*bun.DB, error)
}

MigrationProvider is the optional capability of opening a connection tuned for migrations: the pool a provider opens for request traffic carries driver-level read and write deadlines sized for requests, and a legitimate DDL statement that runs past them — an ALTER TABLE adding constraints on a large table — is cut mid-statement with "invalid connection", outside any transaction MySQL would roll back. A provider that implements this opens the same database with those deadlines lifted; the migration commands prefer it and fall back to the ordinary connection when the capability is absent.

type Provider

type Provider interface {
	Open(params ConnectionParameters, logger loggingcontract.Logger) (*bun.DB, error)
}

Provider opens the connection pool a definition names. Open answers a fresh pool whose ownership transfers to the caller: the registry closes every database it decides not to keep — one handed back beside an error, one that loses a duplicate migration open, one that lands after Close — so an implementation handing out a shared or memoized *bun.DB would have its live pool closed underneath it.

type ProviderDefinition

type ProviderDefinition struct {
	Name      string
	Provider  Provider
	Params    ConnectionParameters
	IsDefault bool
}

type ReadWriteSplitter added in v3.1.0

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

func NewReadWriteSplitter added in v3.1.0

func NewReadWriteSplitter(registry *ManagerRegistry, primaryName string, replicaNames ...string) *ReadWriteSplitter

NewReadWriteSplitter routes writes to the primary and reads round-robin over the replicas.

func NewReadWriteSplitterWithOptions added in v3.6.0

func NewReadWriteSplitterWithOptions(registry *ManagerRegistry, primaryName string, replicaNames []string, options ...ReadWriteSplitterOption) *ReadWriteSplitter

func (*ReadWriteSplitter) Reader added in v3.1.0

func (instance *ReadWriteSplitter) Reader() (*bun.DB, error)

Reader falls back to the primary only for an unreachable replica; every other failure is refused.

func (*ReadWriteSplitter) ReaderName added in v3.1.0

func (instance *ReadWriteSplitter) ReaderName() string

func (*ReadWriteSplitter) Writer added in v3.1.0

func (instance *ReadWriteSplitter) Writer() (*bun.DB, error)

func (*ReadWriteSplitter) WriterName added in v3.1.0

func (instance *ReadWriteSplitter) WriterName() string

type ReadWriteSplitterOption added in v3.6.0

type ReadWriteSplitterOption func(splitter *ReadWriteSplitter)

func WithReplicaRetryInterval added in v3.6.0

func WithReplicaRetryInterval(interval time.Duration) ReadWriteSplitterOption

WithReplicaRetryInterval: a zero interval keeps the default of five seconds; a negative one is a wiring error.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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