bunorm

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: MIT Imports: 16 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

Install

Core
go get github.com/precision-soft/melody/integrations/bunorm@latest
MySQL provider
go get github.com/precision-soft/melody/integrations/bunorm/mysql@latest
PostgreSQL provider
go get github.com/precision-soft/melody/integrations/bunorm/pgsql@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 (
	"time"

	"github.com/precision-soft/melody/application"
	"github.com/precision-soft/melody/container"
	containercontract "github.com/precision-soft/melody/container/contract"

	"github.com/precision-soft/melody/integrations/bunorm"
	bunmysql "github.com/precision-soft/melody/integrations/bunorm/mysql"
)

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) {
			providers := []bunorm.ProviderDefinition{
				{
					Name: ManagerPrimaryName,
					Provider: bunmysql.NewProvider(
						"DB_HOST",
						"DB_PORT",
						"DB_DATABASE",
						"DB_USER",
						"DB_PASSWORD",
					).
						WithPoolConfig(
							bunmysql.NewPoolConfig(
								25,
								5,
								300*time.Second,
								60*time.Second,
							),
						).
						WithTimeoutConfig(
							bunmysql.NewTimeoutConfig(
								10*time.Second,
								30*time.Second,
								30*time.Second,
							),
						),
					IsDefault: true,
				},
				{
					Name: ManagerAdminName,
					Provider: bunmysql.NewProvider(
						"ADMIN_DB_HOST",
						"ADMIN_DB_PORT",
						"ADMIN_DB_DATABASE",
						"ADMIN_DB_USER",
						"ADMIN_DB_PASSWORD",
					),
				},
			}

			return bunorm.NewManagerRegistry(
				resolver,
				providers...,
			)
		},
	)

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

			return registry.DefaultManager()
		},
	)
}

NewManagerRegistry takes a container/contract.Resolver as its first argument, then the provider definitions as variadic values. It fails with ErrResolverIsRequired on a nil resolver and ErrNoProviderDefinitions when no definition is given. The resolver is what a lazy open replays through long after the construction-time resolution has ended, so the registry keeps the container behind it where the value implements container/contract.ContainerCarrier — a resolution context is single-threaded and dies with its scope, while the pools this registry hands out outlive both.

Consuming the default database
package main

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

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:

  • Reading connection parameters.
  • Building the driver connector.
  • Constructing a Bun database handle with the correct dialect.
  • Performing an initial PingContext, failing fast on an error unless a RetryConfig retries a transient one with backoff.

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 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")
View Source
var ErrResolverIsRequired = errors.New("resolver is required")

Functions

func RouteDiagnostics added in v1.1.0

func RouteDiagnostics(logger loggingcontract.Logger)

RouteDiagnostics sends bun's own diagnostic channel, which reports declaration mistakes such as an unknown struct tag option, an unknown on_update or on_delete rule or a query with arguments and no placeholders, to the application's journal as warning records instead of standard error. Bun's logger is one variable for the process, so the first provider to open wins it for the process's whole life and later calls are ignored: in a process that rebuilds its application, a test binary above all, a later lifecycle's diagnostics go to the first lifecycle's logger and are dropped if that logger is closed. It is called from the providers, so a binary that never opens a database takes no setting. 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 ContextOpener added in v1.1.0

type ContextOpener interface {
	OpenContext(ctx context.Context, resolver containercontract.Resolver) (*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(resolver containercontract.Resolver, 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. The lazy opens replay through the container behind the given resolver (asked via the ContainerCarrier door), never through the resolution context that built the registry.

func NewManagerRegistryWithContext added in v1.1.0

func NewManagerRegistryWithContext(ctx context.Context, resolver containercontract.Resolver, 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, its dial and handshake bounded by the connect timeout under the context. 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) MigrationDatabase added in v1.1.0

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

MigrationDatabase answers the connection the migration commands run on: a dedicated one with the driver deadlines lifted when the provider implements MigrationProvider, reported through the second return, and the pooled connection otherwise, since a DDL statement cut by a request deadline is not rolled back by MySQL. 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 v1.1.0

type MigrationContextOpener interface {
	OpenForMigrationContext(ctx context.Context, resolver containercontract.Resolver) (*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 v1.1.0

type MigrationProvider interface {
	OpenForMigration(resolver containercontract.Resolver) (*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(resolver containercontract.Resolver) (*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
	IsDefault bool
}

type SecretParameterProvider added in v1.1.0

type SecretParameterProvider interface {
	SecretParameterNames() []string
}

SecretParameterProvider is the optional capability of naming the configuration parameters that hold this provider's credentials. The registry asks every definition at construction and marks each through the configuration's MarkSecret, so a process that never dials, a debug:parameters run above all, still redacts the password; a provider without it is not asked.

Directories

Path Synopsis
migrate module
mysql module
pgsql module

Jump to

Keyboard shortcuts

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