mysql

package module
v1.2.2 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: MIT Imports: 16 Imported by: 0

README

Bun ORM MySQL provider

This module provides a MySQL provider implementation for the generic Bun ORM integration.

Import paths

  • Generic integration: github.com/precision-soft/melody/integrations/bunorm
  • MySQL provider: github.com/precision-soft/melody/integrations/bunorm/mysql

Key types

Defaults

All three configurations fill in field by field: a supplied PoolConfig or TimeoutConfig has every non-positive field replaced by the listed default, so passing NewPoolConfig(0, 0, 0, 0) yields the defaults rather than the zeros — on database/sql a zero maximum means unlimited, which is not a sizing anyone asks for by omission. An absent PoolConfig or TimeoutConfig is the whole default (DefaultPoolConfig, DefaultTimeoutConfig). What makes RetryConfig different is absence alone: an absent RetryConfig means no retry at all rather than the defaults, while a supplied one fills in field by field like the other two — except BackoffMultiplier, whose floor is 1: any supplied value below it, NaN included, falls back to the default, while exactly 1 stays a valid constant backoff (DefaultRetryConfig builds the same shape for callers who want it whole):

Config Field Default
PoolConfig MaxOpenConnections 25
PoolConfig MaxIdleConnections 5
PoolConfig ConnectionMaxLifetime 5m
PoolConfig ConnectionMaxIdleTime 1m
TimeoutConfig ConnectTimeout 10s
TimeoutConfig ReadTimeout 30s
TimeoutConfig WriteTimeout 30s
RetryConfig MaxAttempts 3
RetryConfig InitialDelay 500ms
RetryConfig MaxDelay 5s
RetryConfig BackoffMultiplier 2.0

Retrying is opt-in: without a RetryConfig, Open makes a single attempt. Only transient failures are retried; a non-transient error fails immediately. ConnectTimeout also bounds the initial PingContext and the post-build hook; a non-positive value falls back to the 10s default before the connector is built, so the dial, ping and hook always run under a deadline.

Notes

  • Connection errors are returned as Melody exceptions with a safe context.
  • This module does not register services by itself; service registration is left to the consuming application.

Recognising a duplicate key, and the connection record

mysql.IsDuplicateKey(err) answers whether err, or any error it wraps, is the driver's *mysql.MySQLError with number 1062 (ER_DUP_ENTRY). A repository uses it to turn a unique key's refusal into its own domain error instead of a 500:

if _, insertErr := database.NewInsert().Model(row).Exec(ctx); nil != insertErr {
    if true == mysql.IsDuplicateKey(insertErr) {
        return ErrUsernameAlreadyExists
    }

    return insertErr
}

It says nothing about which key refused; read the key clause of the driver's message when a table carries more than one.

mysql.ConnectionConfig is the record the provider builds from the connection parameters at open time, through NewConnectionConfig. Its SafeContext names the host, the port, the database and the user, and leaves the password out. That is the shape the failed-open errors carry, so a diagnostic never prints the credential — but for the empty-host refusal, which names only the host parameter, and a cancellation before the attempt, which carries no context. An application does not need to build one to open a database.

Opening under a context, and opening for migrations

  • Provider.OpenContext implements bunorm.ContextOpener: the retry sleeps watch the caller's context alongside the clock, so a shutdown that cancels it reaches a retry loop in flight instead of sleeping through the whole remaining budget. The registry prefers it and hands the context it was constructed with.
  • Provider.OpenForMigration implements bunorm.MigrationProvider and opens the same database with the driver deadlines lifted: ReadTimeout and WriteTimeout are per-connection settings baked into the connector, sized for request traffic, and a DDL statement that legitimately runs past them is cut mid-statement with "invalid connection", outside any transaction MySQL would roll back. The connect timeout stays armed, the pool is kept to the two connections a sequential migration run needs, and no connection is recycled mid-run.
  • Provider.OpenForMigrationContext implements bunorm.MigrationContextOpener — the migration open under the caller's context, the way OpenContext is Open under it.

Transport security

The host may be an IPv6 literal, bare (::1) or in brackets ([::1]), with the port configured separately: a bare literal is bracketed before the port is joined, a bracketed one is kept as written, and a scoped literal such as fe80::1%eth0 is joined the same way without its zone changing. The default verifying TLS config checks the server certificate against the host without the brackets and without the zone, since no certificate carries either.

The provider negotiates a verified TLS handshake by default: it builds a tls.Config from the system roots, verifies the server certificate against the configured host, and requires TLS 1.2 or higher. A server that speaks no TLS fails the dial rather than falling back to plaintext, and the driver's skip-verify spelling — TLS negotiated but the certificate never checked — is not used, because it is trivially machine-in-the-middled.

Two options shape it:

  • mysql.WithInsecure(true) disables TLS entirely, leaving a plaintext connection. It is the deliberate opt-out for a database reached over a trusted network or one that speaks no TLS — the same option, spelled the same way, as the pgsql provider.
  • mysql.WithTlsConfig hands the connector an explicit *tls.Config — a pinned server certificate, a client certificate — taking precedence over both the default and WithInsecure.
provider := mysql.NewProvider(
    "DB_HOST", "DB_PORT", "DB_DATABASE", "DB_USER", "DB_PASSWORD",
    mysql.WithInsecure(true), // plaintext, for a trusted network or a server without TLS
)

Advanced connector customization

If you need driver options that are not exposed by mysql.TimeoutConfig, the TLS options above, or other typed configs, use a post-build hook.

Provider constructors take a variadic of mysql.ProviderOption — the shipped ones are WithPostBuildHook, WithInsecure and WithTlsConfig, and a caller can write their own, since the type is exported:

Configure a hook via mysql.WithPostBuildHook using the mysql.PostBuildHook signature.

The hook is executed during open, after Melody defaults and typed configs are applied, and before creating the SQL connector.

Example:

provider := mysql.NewProvider(
    "DB_HOST",
    "DB_PORT",
    "DB_DATABASE",
    "DB_USER",
    "DB_PASSWORD",
    mysql.WithPostBuildHook(func(ctx context.Context, resolver containercontract.Resolver, driverConfig *driver.Config) error {
        _ = ctx
        _ = resolver
        driverConfig.Collation = "utf8mb4_unicode_ci"
        return nil
    }),
)

Where bun's own diagnostics go

Bun reports the developer's declaration mistakes — an unknown struct tag option, an unknown on_update or on_delete rule on a relation, a query carrying arguments and no placeholders — through a package-level logger of its own. Opening a connection through this provider routes that logger into the application's journal, once per process, so those arrive as warning records under the message bun diagnostic with the line in the context. Without it they are written to standard error as unstructured text, which a deployment whose journal is a json file never sees. The pgsql provider does the same, and the setting is taken once for the whole process: the first open wins it and every later one is ignored, which is harmless while both providers found the same journal in the container. It is not harmless when the first open finds no logger in the container — the routing falls back to the emergency logger, a json logger on standard error, so that logger wins the process and the diagnostics of every provider opened afterwards go to standard error, outside the journal. Register the journal you want bun's diagnostics in before the first provider opens.

One line does not travel that way. When the mysql dialect cannot read the server version it writes

can't discover MySQL version: <error>

through the standard library's default logger, not through bun's, so nothing this provider sets can reach it. Routing it means log.SetOutput, which replaces the destination of the standard logger for the whole process — every dependency that logs through it, and your own log calls with it. That is the application's decision, not this package's, so if you want it, take it in your composition root:

log.SetOutput(logging.NewStandardErrorLogger(logger, "standard logger").Writer())

In practice the line is harmless: bun writes it only after the boot ping has succeeded, the open then returns the database without an error, and no melody record is written for it.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsDuplicateKey

func IsDuplicateKey(err error) bool

Types

type ConnectionConfig

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

func NewConnectionConfig

func NewConnectionConfig(host string, port string, database string, user string, password string) *ConnectionConfig

func (*ConnectionConfig) Database

func (instance *ConnectionConfig) Database() string

func (*ConnectionConfig) Host

func (instance *ConnectionConfig) Host() string

func (*ConnectionConfig) Password

func (instance *ConnectionConfig) Password() string

func (*ConnectionConfig) Port

func (instance *ConnectionConfig) Port() string

func (*ConnectionConfig) SafeContext

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

func (*ConnectionConfig) User

func (instance *ConnectionConfig) User() string

type PoolConfig

type PoolConfig struct {
	MaxOpenConnections    int
	MaxIdleConnections    int
	ConnectionMaxLifetime time.Duration
	ConnectionMaxIdleTime time.Duration
}

func DefaultPoolConfig

func DefaultPoolConfig() *PoolConfig

func NewPoolConfig

func NewPoolConfig(
	MaxOpenConnections int,
	MaxIdleConnections int,
	ConnectionMaxLifetime time.Duration,
	ConnectionMaxIdleTime time.Duration,
) *PoolConfig

type PostBuildHook added in v1.1.0

type PostBuildHook func(
	ctx context.Context,
	resolver containercontract.Resolver,
	driverConfig *driver.Config,
) error

type Provider

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

func NewProvider

func NewProvider(
	hostParameterName string,
	portParameterName string,
	databaseParameterName string,
	userParameterName string,
	passwordParameterName string,
	providerOptions ...ProviderOption,
) *Provider

func NewProviderWithConfig

func NewProviderWithConfig(
	hostParameterName string,
	portParameterName string,
	databaseParameterName string,
	userParameterName string,
	passwordParameterName string,
	poolConfig *PoolConfig,
	timeoutConfig *TimeoutConfig,
	retryConfig *RetryConfig,
	providerOptions ...ProviderOption,
) *Provider

func (*Provider) Open

func (instance *Provider) Open(resolver containercontract.Resolver) (*bun.DB, error)

func (*Provider) OpenContext added in v1.2.0

func (instance *Provider) OpenContext(ctx context.Context, resolver containercontract.Resolver) (*bun.DB, error)

OpenContext opens under the caller's context: an already-cancelled context is refused before the attempt, the retry sleeps watch it beside the clock, and the configuration hook and the boot ping derive their budgets from it; the dial and the handshake are bounded by the connect timeout under the caller's context, and the dialect query bun runs at construction goes over the connection the ping established, so a mid-attempt cancellation is honoured at the next cancellable step. A nil context reads as context.Background(), which is exactly Open.

func (*Provider) OpenForMigration added in v1.2.0

func (instance *Provider) OpenForMigration(resolver containercontract.Resolver) (*bun.DB, error)

OpenForMigration opens the same database with the driver deadlines lifted: ReadTimeout and WriteTimeout are per-connection settings baked into the connector, sized for request traffic, and a DDL statement that legitimately 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. The connect timeout stays armed (a down database must still fail fast), the pool is kept to the two connections a sequential migration run needs, and no connection is recycled mid-run — a lifetime rotation under a running statement is the same cut by another name.

func (*Provider) OpenForMigrationContext added in v1.2.0

func (instance *Provider) OpenForMigrationContext(ctx context.Context, resolver containercontract.Resolver) (*bun.DB, error)

OpenForMigrationContext is OpenForMigration under the caller's context, the way OpenContext is Open under it: the registry hands the context it was constructed with, so an already-cancelled migration is refused before the attempt and a cancellation arriving mid-attempt is honoured at the next cancellable step instead of sleeping out the retry budget. A nil context reads as context.Background(), which is exactly OpenForMigration.

func (*Provider) SecretParameterNames added in v1.2.0

func (instance *Provider) SecretParameterNames() []string

SecretParameterNames names the password parameter, so the registry arms the redaction at construction and a process that never dials, debug:parameters above all, masks it.

func (*Provider) WithPoolConfig

func (instance *Provider) WithPoolConfig(poolConfig *PoolConfig) *Provider

func (*Provider) WithRetryConfig added in v1.0.1

func (instance *Provider) WithRetryConfig(retryConfig *RetryConfig) *Provider

func (*Provider) WithTimeoutConfig

func (instance *Provider) WithTimeoutConfig(timeoutConfig *TimeoutConfig) *Provider

type ProviderOption added in v1.1.0

type ProviderOption func(provider *Provider)

func WithInsecure added in v1.2.0

func WithInsecure(insecure bool) ProviderOption

WithInsecure disables TLS when set, leaving a plaintext connection, unless WithTlsConfig hands an explicit configuration, which wins. It is the deliberate opt-out from the secure default the provider dials with — a verifying TLS session — for a database reached over a trusted network or one that speaks no TLS, spelled the same as its pgsql sibling.

func WithPostBuildHook added in v1.1.0

func WithPostBuildHook(hook PostBuildHook) ProviderOption

func WithTlsConfig added in v1.2.0

func WithTlsConfig(tlsConfig *tls.Config) ProviderOption

WithTlsConfig hands the connector an explicit TLS configuration, taking precedence over both the secure default and WithInsecure. A caller uses it to pin a server certificate, present a client certificate, or otherwise shape the session beyond the system-roots verification the default performs.

type RetryConfig added in v1.0.1

type RetryConfig struct {
	MaxAttempts       uint32
	InitialDelay      time.Duration
	MaxDelay          time.Duration
	BackoffMultiplier float64
}

func DefaultRetryConfig added in v1.0.1

func DefaultRetryConfig() *RetryConfig

func NewRetryConfig added in v1.1.0

func NewRetryConfig(
	maxAttempts uint32,
	initialDelay time.Duration,
	maxDelay time.Duration,
	backoffMultiplier float64,
) *RetryConfig

type TimeoutConfig

type TimeoutConfig struct {
	ConnectTimeout time.Duration
	ReadTimeout    time.Duration
	WriteTimeout   time.Duration
}

func DefaultTimeoutConfig

func DefaultTimeoutConfig() *TimeoutConfig

func NewTimeoutConfig

func NewTimeoutConfig(
	connectTimeout time.Duration,
	readTimeout time.Duration,
	writeTimeout time.Duration,
) *TimeoutConfig

Jump to

Keyboard shortcuts

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