mysql

package module
v0.9.1 Latest Latest
Warning

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

Go to latest
Published: Mar 20, 2026 License: MIT Imports: 12 Imported by: 0

README

mysql

database/sql-backed MySQL client with launcher lifecycle and health check integration.

Install

go get code.nochebuena.dev/go/mysql

Usage

db := mysql.New(logger, cfg)
lc.Append(db)
r.Get("/health", health.NewHandler(logger, db))

Unit of Work

uow := mysql.NewUnitOfWork(logger, db)

err := uow.Do(ctx, func(ctx context.Context) error {
    exec := db.GetExecutor(ctx) // returns the active Tx
    _, err := exec.ExecContext(ctx, "INSERT INTO orders ...")
    return err
})

Error mapping

if err := db.HandleError(err); err != nil { ... }
MySQL error xerrors code
1062 (ER_DUP_ENTRY) ErrAlreadyExists
1216/1217/1451/1452 (foreign key) ErrInvalidInput
sql.ErrNoRows ErrNotFound
anything else ErrInternal

Configuration

Env var Default Description
MYSQL_HOST required Database host
MYSQL_PORT 3306 Database port
MYSQL_USER required Username
MYSQL_PASSWORD required Password
MYSQL_NAME required Database name
MYSQL_MAX_CONNS 5 Max open connections
MYSQL_MIN_CONNS 2 Max idle connections

Documentation

Overview

Package mysql provides a database/sql-backed MySQL client with launcher and health integration.

Usage:

db := mysql.New(logger, cfg)
lc.Append(db)
r.Get("/health", health.NewHandler(logger, db))

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func HandleError

func HandleError(err error) error

HandleError maps MySQL and database/sql errors to xerrors types. Also available as client.HandleError(err).

Types

type Client

type Client interface {
	GetExecutor(ctx context.Context) Executor
	Begin(ctx context.Context) (Tx, error)
	Ping(ctx context.Context) error
	HandleError(err error) error
}

Client is the database access interface.

type Component

type Component interface {
	launcher.Component
	health.Checkable
	Client
}

Component bundles launcher lifecycle, health check, and database client.

func New

func New(logger logz.Logger, cfg Config) Component

New returns a mysql Component. Call lc.Append(db) to manage its lifecycle.

type Config

type Config struct {
	Host            string `env:"MYSQL_HOST,required"`
	Port            int    `env:"MYSQL_PORT"               envDefault:"3306"`
	User            string `env:"MYSQL_USER,required"`
	Password        string `env:"MYSQL_PASSWORD,required"`
	Name            string `env:"MYSQL_NAME,required"`
	MaxConns        int    `env:"MYSQL_MAX_CONNS"          envDefault:"5"`
	MinConns        int    `env:"MYSQL_MIN_CONNS"          envDefault:"2"`
	MaxConnLifetime string `env:"MYSQL_MAX_CONN_LIFETIME"  envDefault:"1h"`
	MaxConnIdleTime string `env:"MYSQL_MAX_CONN_IDLE_TIME" envDefault:"30m"`
	// Charset is the connection character set sent as SET NAMES <charset>.
	// Defaults to "utf8mb4" when empty.
	Charset string `env:"MYSQL_CHARSET" envDefault:"utf8mb4"`
	// Loc is the IANA timezone name used for time.Time ↔ MySQL DATETIME
	// conversion. Defaults to "UTC" when empty.
	Loc string `env:"MYSQL_LOC" envDefault:"UTC"`
	// ParseTime controls whether the driver maps DATE/DATETIME columns to
	// time.Time. Valid values: "true", "false". Defaults to "true" when empty.
	ParseTime string `env:"MYSQL_PARSE_TIME" envDefault:"true"`
}

Config holds MySQL connection settings.

DSN parameters Charset, Loc, and ParseTime default to "utf8mb4", "UTC", and "true" respectively when left empty, preserving the behaviour of v0.9.0. Set them explicitly when you need non-default values (e.g. Loc="Local").

Note on Collation: go-sql-driver v1.8.x negotiates the connection collation via a 1-byte handshake ID (max 255). MariaDB 11.4+ collations such as utf8mb4_uca1400_as_cs carry IDs > 255 and cannot be set through the DSN collation parameter. Set the desired collation at the database/table level in your schema migrations instead.

func (Config) DSN

func (c Config) DSN() string

DSN constructs a MySQL DSN from the configuration. Empty Charset, Loc, and ParseTime fields fall back to their safe defaults ("utf8mb4", "UTC", "true"), matching the behaviour of v0.9.0.

type Executor

type Executor interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}

Executor defines operations shared by pool and transaction.

type Tx

type Tx interface {
	Executor
	Commit() error
	Rollback() error
}

Tx extends Executor with commit/rollback (no ctx — sql.Tx limitation).

type UnitOfWork

type UnitOfWork interface {
	Do(ctx context.Context, fn func(ctx context.Context) error) error
}

UnitOfWork wraps operations in a single database transaction.

func NewUnitOfWork

func NewUnitOfWork(logger logz.Logger, client Client) UnitOfWork

NewUnitOfWork returns a UnitOfWork backed by the given client.

Jump to

Keyboard shortcuts

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