mysqlengine

package
v1.10.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 25 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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 (
	// ErrInvalidVariable reports a server variable name or value the engine refuses to put into SQL.
	ErrInvalidVariable = errors.New("mysqlengine: invalid server variable")
	// ErrUnsupported reports an operation the server's version cannot perform.
	ErrUnsupported = errors.New("mysqlengine: unsupported by this server version")
	// ErrExecUnsupported is returned when the container runtime cannot relay standard input to a command.
	ErrExecUnsupported = errors.New("mysqlengine: the container runtime cannot run commands with standard input")
	// ErrInvalidPassword is returned when the root password cannot be handed to a client tool on standard input.
	ErrInvalidPassword = errors.New("mysqlengine: the root password cannot be passed to a client tool")
)
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 CheckVariable

func CheckVariable(name string) error

CheckVariable reports whether SetVariable would accept the name, without touching a server.

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 ChannelSpec

type ChannelSpec struct {
	Name     string
	Host     string
	User     string
	Password string
	// SSL requires an encrypted connection to the source.
	SSL   bool
	Port  int
	Delay int
}

ChannelSpec configures an inbound replication channel on a server.

type ChannelState

type ChannelState struct {
	IOError   string
	SQLError  string
	Running   bool
	IORunning bool
	SQLActive bool
	Lag       int
}

ChannelState is the health of one replication channel.

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

func (s *Server) AddChannel(ctx context.Context, c ChannelSpec, start bool) error

AddChannel (re)configures a channel from the source in spec and starts it when start is set. GTID auto-positioning is used, so the source must run with GTIDs.

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

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

ChannelStatus reads SHOW REPLICA STATUS of one channel.

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

func (s *Server) DumpTo(ctx context.Context, dbs []string, w io.Writer) error

DumpTo streams a logical dump of dbs to w; accounts are not included. Standard error is discarded.

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

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

JoinNetwork attaches the server to the replication network of a source so it can reach it by container name.

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

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

RemoveChannel stops a channel and forgets its source; an unknown channel is not an error.

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

func (s *Server) RestoreFrom(ctx context.Context, r io.Reader) error

RestoreFrom runs a SQL stream such as DumpTo's output.

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

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

Seed resets the server's binary log state and loads seed (a ReplicaSeed dump), so a channel can continue from the seed's GTID set.

func (*Server) SetChannel

func (s *Server) SetChannel(ctx context.Context, name string, on bool) error

SetChannel starts (true) or stops (false) a channel.

func (*Server) SetReadOnly

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

SetReadOnly turns super_read_only (and read_only) on or off, persisted across restarts except on MySQL 5.7.

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

func (s *Server) SetVariable(ctx context.Context, name, value string, reset, static bool) error

SetVariable persists a global system variable (SET PERSIST). static variables use SET PERSIST_ONLY and take effect after the next restart; reset restores the default. name is matched against an identifier pattern and the value is bound as a parameter. MySQL 5.7 has no SET PERSIST, so it only supports dynamic variables, set for the life of the server.

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.

func (*Server) XEndpoint

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

XEndpoint is the host and published port of the X protocol; the port is 0 unless Spec.PublishX is set.

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
	// PublishX also publishes the X protocol port (see Server.XEndpoint).
	PublishX bool
	// 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