bunorm

package module
v2.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2026 License: MIT Imports: 12 Imported by: 3

README

Bun ORM integration

This directory contains optional Bun ORM integrations for Melody.

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

What you get

  • A dialect-agnostic manager registry (bunorm.ManagerRegistry) that:

    • Caches managers 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:

    • Database() *bun.DB
    • Close() error

Connection parameters

A provider opens a database from an explicit bunorm.ConnectionParameters value (Host, Port, Database, User, Password) carried on the bunorm.ProviderDefinition as its Params field — the caller reads those values from config/environment and passes them in, rather than handing the provider parameter names to resolve for itself. 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)

ConnectionParams remains as a deprecated alias of ConnectionParameters.

Install

Core
go get github.com/precision-soft/melody/integrations/bunorm/v2@latest
MySQL provider
go get github.com/precision-soft/melody/integrations/bunorm/mysql/v2@latest
PostgreSQL provider
go get github.com/precision-soft/melody/integrations/bunorm/pgsql/v2@latest

Usage

The pattern is:

  1. Register a *bunorm.ManagerRegistry service (explicit id).
  2. Register only 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 when you need a non-default database.
Service registration example
package main

import (
    "os"
    "time"

    bunmysql "github.com/precision-soft/melody/integrations/bunorm/mysql/v2"
    "github.com/precision-soft/melody/integrations/bunorm/v2"
    "github.com/precision-soft/melody/v2/application"
    "github.com/precision-soft/melody/v2/container"
    containercontract "github.com/precision-soft/melody/v2/container/contract"
    "github.com/precision-soft/melody/v2/logging"
)

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

    ManagerPrimaryName = "primary"
    ManagerAdminName   = "admin"
)

func RegisterDatabaseServices(app *application.Application) {
    app.RegisterService(
        ServiceManagerRegistryId,
        func(resolver containercontract.Resolver) (*bunorm.ManagerRegistry, error) {
            return bunorm.NewManagerRegistry(
                logging.LoggerMustFromResolver(resolver),
                bunorm.ProviderDefinition{
                    Name: ManagerPrimaryName,
                    Provider: bunmysql.NewProvider().
                        WithPoolConfig(
                            bunmysql.NewPoolConfig(
                                25,
                                5,
                                300*time.Second,
                                60*time.Second,
                            ),
                        ).
                        WithTimeoutConfig(
                            bunmysql.NewTimeoutConfig(
                                10*time.Second,
                                30*time.Second,
                                30*time.Second,
                            ),
                        ),
                    Params: bunorm.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,
                },
                bunorm.ProviderDefinition{
                    Name:     ManagerAdminName,
                    Provider: bunmysql.NewProvider(),
                    Params: bunorm.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"),
                    },
                },
            )
        },
    )

    app.RegisterService(
        ServiceManagerDefaultId,
        func(resolver containercontract.Resolver) (*bunorm.Manager, error) {
            registry := container.MustFromResolver[*bunorm.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.

Consuming the default database
package main

import (
	"github.com/precision-soft/melody/integrations/bunorm/v2"
)

type ApiService struct {
	databaseManager *bunorm.Manager
}

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

func (instance *ApiService) Database() {
	database := instance.databaseManager.Database()
	_ = database
}
Consuming a non-default database
package main

func main() {
	registry := container.MustFromResolver[*bunorm.ManagerRegistry](resolver, ServiceManagerRegistryId)
	adminManager := registry.MustManager(ManagerAdminName)
	adminDatabase := adminManager.Database()
	_ = adminDatabase
}

Dialect providers

Each dialect module implements bunorm.Provider and is responsible for:

  • Applying the bunorm.ConnectionParameters the registry hands it.
  • Building the driver connector.
  • Constructing a Bun database handle with the correct dialect.
  • Performing an initial PingContext and failing fast on errors.

Advanced connector customization

The dialect providers expose an optional post-build hook that allows userland to alter driver configuration beyond what the provider exposes via typed config structs.

The hook is configured via a provider option passed to the provider constructor:

The hook is executed during provider open, after Melody defaults and typed configs are applied, and before establishing the SQL connection.

Enhancements

Read/write splitting, encrypted columns and an audit trail ship in the v3 binding alone — no split.go, encrypt/ or audit/ exists outside integrations/bunorm/v3, so nothing here can be reached from this module. They are documented where they live: read/write splitting in v3/README.md, field encryption in v3/encrypt/README.md, and the audit trail in v3/audit/README.md.

Documentation

Index

Constants

This section is empty.

Variables

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 RouteDiagnostics added in v2.2.0

func RouteDiagnostics(logger loggingcontract.Logger)
RouteDiagnostics sends bun's own diagnostic channel to the application's journal. Bun reports the developer's declaration mistakes through a package-level logger of its own — an unknown struct tag option, an unknown on_update or on_delete rule on a relation, a query carrying arguments and no placeholders — and unrouted they are written to standard error as unstructured text, invisible to a deployment whose journal is a json file. They arrive as warning records carrying the line, the shape NewStandardErrorLogger already gives net/http's own reporting.

Bun's logger is one variable for the whole process, so the first provider to open wins it and later calls are ignored: an application with two managers has one journal anyway. The once outlives every registry: in a process that builds, closes and rebuilds its application — a test binary above all — the first lifecycle's logger keeps the channel for the process's whole life, and if that logger is closed (or was the emergency fallback of a resolver without a logging service) the later lifecycles' bun diagnostics are dropped silently. It is called from the providers rather than from a module hook because a binary that never opens a database has no reason to take the setting at all.

It does not reach the one line the mysql dialect writes when it cannot read the server version. That line goes through the standard library's own default logger, not through bun's, so routing it means taking log.SetOutput for the whole process — every dependency and the application's own log calls with it — which is the application's decision to make and not this package's. See the mysql readme.

Types

type ConnectionParameters added in v2.1.0

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

func (*ConnectionParameters) SafeContext added in v2.1.0

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

type ConnectionParams deprecated

type ConnectionParams = ConnectionParameters

Deprecated: use ConnectionParameters.

type ContextOpener added in v2.2.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 the context it was constructed with.

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 builds a container-level registry over lazily-dialed pools. Container-level deliberately: a *bun.DB is a connection pool — the process-lifetime shape of database/sql — and per-unit work takes a transaction or a Conn from the pool, not a pool per scope.

func NewManagerRegistryWithContext added in v2.2.0

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

NewManagerRegistryWithContext additionally binds the registry to the given context: a provider that implements ContextOpener has its lazy opens run under it, so a shutdown that cancels the context refuses an open not yet started, reaches the attempt's cancellable steps — the configuration hook, the boot ping, a retry sleep — in flight, and pays at most the dialect handshake bun bounds by the connect timeout. A nil context reads as context.Background(), the exact behaviour of NewManagerRegistry.

func (*ManagerRegistry) Close

func (instance *ManagerRegistry) Close() error

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) Manager

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

func (*ManagerRegistry) MarkSecretParameters added in v2.2.0

func (instance *ManagerRegistry) MarkSecretParameters(configuration configcontract.Configuration, parameterNames ...string)
MarkSecretParameters arms the framework's redaction for the configuration parameters that hold this registry's credentials: those the caller names here, and those any definition's provider declares through SecretParameterProvider. It is a setter rather than a constructor argument because this major hands the connection values to the provider instead of the names it would read them under, so the application — the party that resolved the values — is the party that knows the keys, and because MarkSecret propagates to a parameter the configuration has already read, arming after construction redacts exactly as much as arming during it would.

Marking here rather than inside an open is what covers a process that never dials: a console run, a boot that fails before the first query, a debug:parameters invocation. A nil configuration, an empty name, or a name no parameter answers to leaves the marking undone, the same way MarkSecret leaves an absent parameter alone.

func (*ManagerRegistry) MigrationDatabase added in v2.2.0

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

MigrationDatabase answers the connection the migration commands should run on: a dedicated one with the driver deadlines lifted when the provider implements MigrationProvider — reported through the second return — and the ordinary pooled connection otherwise. A request pool carries read and write deadlines sized for requests, and a DDL statement that legitimately runs past them is cut mid-statement with "invalid connection", outside any transaction MySQL would roll back; the dedicated connection exists so a long migration finishes instead. An empty name selects the default definition. The dedicated database is opened once per name, cached, and closed by Close.

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

type MigrationContextOpener added in v2.2.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 the context the registry was constructed with reaches this door too. Without it the registry's promise held on the Manager path alone — the migration open took no context at all — and a db:migrate that received SIGTERM against a down database slept through the whole retry budget instead of refusing at the first cancellable step, which is the exact window a supervisor's signal lands in. The registry prefers it whenever the provider implements it; a provider carrying only MigrationProvider is unaffected.

type MigrationProvider added in v2.2.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 SecretParameterProvider added in v2.2.0

type SecretParameterProvider interface {
	SecretParameterNames() []string
}

SecretParameterProvider is the optional capability of naming the configuration parameters that hold this provider's credentials. This major hands the connection values to the provider rather than the names it would read them under, so the application is ordinarily the party that knows the keys and names them to MarkSecretParameters; a provider that does know its own — one built around parameter names of its own — declares them here and is asked by the same door. A provider without the capability is not asked and is unaffected.

Jump to

Keyboard shortcuts

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