Help us shape the future of Go! Take the 2026 Go Developer Survey

mysqlengine

package
v1.9.1 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package mysqlengine runs real MySQL servers in containers for emulators of managed MySQL services: a named data volume, a published loopback port, SQL access as root, logical dump and restore, and stop/start that keep data.

Index

Constants

View Source
const (
	// RootUser is the container's superuser; emulators keep its password to themselves.
	RootUser = "root"
)

Variables

View Source
var (
	// ErrNoPITR is returned when point-in-time recovery has no persistent volume to keep its base in.
	ErrNoPITR = errors.New("mysqlengine: point-in-time recovery needs a persistent volume")
	// ErrPITRNotOn is returned when recovery is prepared on a server that never enabled it.
	ErrPITRNotOn = errors.New("mysqlengine: point-in-time recovery is not enabled on the source engine")
)
View Source
var (
	// ErrRuntimeUnavailable is returned when no container runtime can exec in and stop containers.
	ErrRuntimeUnavailable = errors.New("mysqlengine: container runtime unavailable")

	// ErrTooLarge is returned when a dump or query result exceeds its size limit.
	ErrTooLarge = errors.New("mysqlengine: result is too large")
)
View Source
var ErrInvalidIdentifier = errors.New("mysqlengine: invalid identifier")

ErrInvalidIdentifier reports a database name, charset or collation outside the allowed character set.

View Source
var ErrNoReplication = errors.New("mysqlengine: the container runtime cannot run replication")

ErrNoReplication is returned when the container runtime cannot manage the network replication needs.

Functions

func CreateDatabaseSQL

func CreateDatabaseSQL(name, charset, collation string) (string, error)

CreateDatabaseSQL builds CREATE DATABASE from identifiers rebuilt out of a fixed alphabet.

func DropDatabaseSQL

func DropDatabaseSQL(name string) (string, error)

DropDatabaseSQL builds DROP DATABASE from a name rebuilt out of a fixed alphabet.

Types

type Config

type Config struct {
	Runtime      Runtime
	Volumes      container.VolumeRuntime
	Ports        *portalloc.Allocator
	Logger       *slog.Logger
	Prefix       string
	Service      string
	ReplUser     string
	StartTimeout time.Duration
}

Config configures an Engine. Prefix names containers and volumes ("<prefix>-..."); Service owns ports and orphan labels (default Prefix); ReplUser is the replication account created on a source.

type Engine

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

Engine launches MySQL servers.

func New

func New(cfg Config) (*Engine, error)

New validates cfg and returns an Engine.

func (*Engine) Launch

func (e *Engine) Launch(ctx context.Context, spec Spec) (*Server, error)

Launch starts a server and waits until it accepts root connections.

func (*Engine) RemoveVolume

func (e *Engine) RemoveVolume(ctx context.Context, id string)

RemoveVolume deletes the data volume of server id.

func (*Engine) SweepVolumes

func (e *Engine) SweepVolumes(ctx context.Context, keep map[string]bool, olderThan time.Duration)

SweepVolumes deletes unused volumes of this engine that keep does not list.

func (*Engine) VolumeName

func (e *Engine) VolumeName(id string) string

VolumeName is the data volume of server id.

type Recovery

type Recovery struct {
	At        time.Time
	Source    *ReplSource
	FromFile  string
	UntilFile string
	Script    []byte
	FromPos   uint64
	UntilPos  uint64
}

Recovery describes a binary log replay: a clone loads Script, then follows Source from FromFile/FromPos up to UntilFile/UntilPos.

type ReplSource

type ReplSource struct {
	Network   string
	NetworkID string
	Host      string
	Password  string
	Port      int
}

ReplSource tells a replica how to reach its source.

type Runtime

type Runtime interface {
	CreateAndStart(ctx context.Context, spec container.Spec) (string, error)
	StopAndRemove(ctx context.Context, containerID string) error
	StopContainer(ctx context.Context, containerID string) error
	StartContainer(ctx context.Context, containerID string) error
	Exec(ctx context.Context, containerID string, cmd []string) (container.ExecResult, error)
}

Runtime is the slice of the container runtime the engine uses.

type Server

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

Server is one running MySQL container.

func (*Server) ApplyRecovery

func (s *Server) ApplyRecovery(ctx context.Context, rec Recovery) error

ApplyRecovery replays rec on a freshly launched server and detaches it from the source.

func (*Server) AttachReplica

func (s *Server) AttachReplica(ctx context.Context, src ReplSource, seed []byte) error

AttachReplica makes the server follow src; seed, when present, is loaded first.

func (*Server) Close

func (s *Server) Close(ctx context.Context, purge bool)

Close removes the container and releases its port; purge also deletes the data volume.

func (*Server) ContainerName

func (s *Server) ContainerName() string

ContainerName is the name replicas use to reach this server on a shared network.

func (*Server) CopyOut

func (s *Server) CopyOut(ctx context.Context, path string) ([]byte, error)

CopyOut returns a file inside the container through the dump mount.

func (*Server) CreateDatabase

func (s *Server) CreateDatabase(ctx context.Context, name, charset, collation string) error

CreateDatabase creates a database with the given charset and collation.

func (*Server) DB

func (s *Server) DB(db string) (*sql.DB, error)

DB opens a root connection to db ("" for none); the caller closes it.

func (*Server) DisablePITR

func (s *Server) DisablePITR(ctx context.Context) error

DisablePITR discards the base so no recovery can target this server.

func (*Server) DropDatabase

func (s *Server) DropDatabase(ctx context.Context, name string) error

DropDatabase removes a database; a missing one is not an error.

func (*Server) DropUser

func (s *Server) DropUser(ctx context.Context, user string) error

DropUser removes an account; a missing one is not an error.

func (*Server) Dump

func (s *Server) Dump(ctx context.Context) ([]byte, error)

Dump returns a logical dump of every user schema; accounts are not included.

func (*Server) DumpDatabases

func (s *Server) DumpDatabases(ctx context.Context, dbs []string) ([]byte, error)

DumpDatabases returns a logical dump of dbs; accounts are not included.

func (*Server) EnablePITR

func (s *Server) EnablePITR(ctx context.Context, dbs []string) (time.Time, error)

EnablePITR takes a base dump of dbs (or just the log coordinates) and returns the earliest recoverable time.

func (*Server) Endpoint

func (s *Server) Endpoint() (string, int)

Endpoint is the host and published port clients connect to.

func (*Server) EnsureAdmin

func (s *Server) EnsureAdmin(ctx context.Context, user, password string) error

EnsureAdmin creates or updates a full-privilege account reachable from any host.

func (*Server) Persistent

func (s *Server) Persistent() bool

Persistent reports whether the data lives in a volume that survives the container.

func (*Server) PrepareRecovery

func (s *Server) PrepareRecovery(ctx context.Context, at time.Time) (Recovery, error)

PrepareRecovery locates the binary log range that reaches at, and readies the server as a replication source.

func (*Server) Promote

func (s *Server) Promote(ctx context.Context) error

Promote detaches a replica from its source and makes it writable.

func (*Server) Query

func (s *Server) Query(ctx context.Context, db, query string) ([][]string, error)

Query runs a query as root and returns the rows as strings; the first row holds the column names.

func (*Server) QueryMax

func (s *Server) QueryMax(ctx context.Context, db, query string, maxCells int) ([][]string, error)

QueryMax is Query that fails with ErrTooLarge once the result exceeds maxCells values (zero is unlimited).

func (*Server) ReadFile

func (s *Server) ReadFile(ctx context.Context, path string) (string, error)

ReadFile returns a file inside the container.

func (*Server) RemoveVolume

func (s *Server) RemoveVolume(ctx context.Context) error

RemoveVolume deletes this server's data volume; the server must be closed first.

func (*Server) ReplicaSeed

func (s *Server) ReplicaSeed(ctx context.Context, dbs []string) ([]byte, error)

ReplicaSeed returns what a replica of this server starts from: a dump of dbs with the GTID set, or just the executed GTID set when dbs is empty.

func (*Server) ReplicationSource

func (s *Server) ReplicationSource(ctx context.Context) (ReplSource, error)

ReplicationSource creates the replication account and puts the server on a network its replicas can join.

func (*Server) ReplicationStatus

func (s *Server) ReplicationStatus(ctx context.Context) (dbrepl.Status, error)

ReplicationStatus reports the replica's lag and thread state.

func (*Server) Restore

func (s *Server) Restore(ctx context.Context, data []byte) error

Restore runs a dump produced by Dump.

func (*Server) RestoreInto

func (s *Server) RestoreInto(ctx context.Context, db string, data []byte) error

RestoreInto runs a SQL file with db as the default database when db is not empty.

func (*Server) Run

func (s *Server) Run(ctx context.Context, cmd []string) (string, error)

Run executes cmd in the container and returns its stdout.

func (*Server) RunAuth

func (s *Server) RunAuth(ctx context.Context, cmd []string) (string, error)

RunAuth is Run with the root password in the process environment, for the mysql client tools.

func (*Server) SetReplication

func (s *Server) SetReplication(ctx context.Context, on bool) error

SetReplication pauses (false) or resumes (true) replication.

func (*Server) SetRootPassword

func (s *Server) SetRootPassword(pw string)

SetRootPassword records a root password changed through SQL so later connections use it.

func (*Server) Start

func (s *Server) Start(ctx context.Context) error

Start starts a stopped server and waits until it accepts connections.

func (*Server) Statement

func (s *Server) Statement(ctx context.Context, stmt string) (string, error)

Statement runs SQL through the mysql client and returns its tab-separated output.

func (*Server) Stop

func (s *Server) Stop(ctx context.Context) error

Stop stops the container, keeping its data and published port.

func (*Server) UserDatabases

func (s *Server) UserDatabases(ctx context.Context) ([]string, error)

UserDatabases lists the non-system schemas.

func (*Server) Volume

func (s *Server) Volume() string

Volume is the data volume name, empty without persistence.

func (*Server) WriteFile

func (s *Server) WriteFile(ctx context.Context, path, content string) error

WriteFile replaces a file inside the container.

type Spec

type Spec struct {
	VolumeLabels map[string]string
	// Labels are added to the container. Resource, when set, labels the container as owned by that key so a
	// restarted gopherstack can find it; Adopt then lets Launch take over such an orphan of an earlier run.
	Labels map[string]string
	// ID names the container and, unless Volume is set, the data volume.
	ID string
	// Image is the container image, e.g. mysql:8.4.
	Image string
	// RootPassword is applied on first initialisation and must match an existing volume.
	RootPassword string
	// Volume overrides the data volume name; VolumeLabels are added to the volume's labels.
	Volume   string
	Resource string
	// Network and NetworkID place the container on an existing replication network.
	Network   string
	NetworkID string
	// MemoryBytes and NanoCPUs limit the container.
	MemoryBytes int64
	NanoCPUs    int64
	// ServerID, when non-zero, starts the server replication-ready (GTID mode).
	ServerID uint32
	// Persist keeps data in a named volume; Fresh discards an existing one first.
	Persist bool
	Fresh   bool
	Adopt   bool
}

Spec describes one server.

Jump to

Keyboard shortcuts

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