migrations

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: May 15, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package migrations implements a Laravel-style migration engine. A migration is any type that implements the Migration interface; the engine applies them in lexical name order (timestamp-prefixed by convention) and records each application in a repository table.

Migrations interact with the database through schema.Definition values returned via the Context API, so they remain driver-agnostic.

Index

Constants

This section is empty.

Variables

View Source
var Default = NewRegistry()

Default is the process-wide registry.

View Source
var ErrChecksumMismatch = errors.New("migrations: checksum mismatch — migration source changed after being applied")

ErrChecksumMismatch is returned when a recorded migration's checksum disagrees with the one computed from current source.

View Source
var Now = func() time.Time { return time.Now().UTC() }

Now returns the current wall clock; abstracted so tests can stub it.

Functions

func Checksum

func Checksum(conn *database.Connection, m Migration) (string, error)

Checksum computes a stable checksum for a migration by hashing the SQL it emits in preview mode. This lets the engine detect when a migration was edited after being applied.

func Register

func Register(m Migration)

Register is a package-level convenience that registers on Default.

Types

type Context

type Context struct {
	Conn *database.Connection
	Tx   *database.Tx
	Ctx  context.Context
	// contains filtered or unexported fields
}

Context is the value passed to migration callbacks. It exposes the underlying connection plus convenience helpers for applying schema definitions and executing raw SQL.

func (*Context) CollectedSQL

func (c *Context) CollectedSQL() []string

CollectedSQL returns the SQL accumulated during a preview run.

func (*Context) Executor

func (c *Context) Executor() database.Executor

Executor returns the active executor (transaction if open, else connection).

func (*Context) IsPreview

func (c *Context) IsPreview() bool

IsPreview reports whether this is a SQL-preview run (no execution).

func (*Context) Raw

func (c *Context) Raw(sqlStr string, args ...any) error

Raw executes a raw SQL statement.

func (*Context) Schema

func (c *Context) Schema(def *schema.Definition) error

Schema applies a schema.Definition to the database (or records its SQL in preview mode). It is the primary API used inside Up/Down.

type FuncMigration

type FuncMigration struct {
	N    string
	UpFn func(ctx *Context) error
	DnFn func(ctx *Context) error
}

FuncMigration adapts up/down callbacks into a Migration. It is the most common way to declare a migration in user code.

func (*FuncMigration) Down

func (m *FuncMigration) Down(ctx *Context) error

Down runs the down callback.

func (*FuncMigration) Name

func (m *FuncMigration) Name() string

Name returns the migration name.

func (*FuncMigration) Up

func (m *FuncMigration) Up(ctx *Context) error

Up runs the up callback.

type Lock

type Lock struct {
	Conn     *database.Connection
	Table    string
	HolderID string
	// contains filtered or unexported fields
}

Lock prevents two migrators from running concurrently against the same database. The implementation uses a row in a dedicated `migrations_lock` table; on databases that support advisory locks (Postgres) we use those instead transparently.

func NewLock

func NewLock(conn *database.Connection, holder string) *Lock

NewLock builds a Lock against conn.

func (*Lock) Acquire

func (l *Lock) Acquire(ctx context.Context, timeout time.Duration) error

Acquire blocks until the lock is held or ctx expires.

func (*Lock) Release

func (l *Lock) Release(ctx context.Context) error

Release frees the lock.

type Migration

type Migration interface {
	Name() string
	Up(ctx *Context) error
	Down(ctx *Context) error
}

Migration is the canonical interface migrations implement. The Name() must be globally unique within a registry and is the migration's primary identifier in the migrations table.

func Define

func Define(name string, up, down func(ctx *Context) error) Migration

Define builds a FuncMigration with the given name and callbacks. Use this in init() to register an inline migration without writing a type.

type Migrator

type Migrator struct {
	Conn     *database.Connection
	Registry *Registry
	Opts     Options
	Repo     *Repository
}

Migrator orchestrates migrations against a connection.

func New

func New(conn *database.Connection, registry *Registry, opts Options) *Migrator

New creates a Migrator. registry may be nil to use the package Default.

func (*Migrator) Fresh

func (m *Migrator) Fresh(ctx context.Context) ([]string, error)

Fresh drops all tables and re-applies all migrations from scratch. The list of tables is enumerated from each driver — sqlite_master / information_schema / pg_catalog — and excludes the migrations table.

func (*Migrator) Refresh

func (m *Migrator) Refresh(ctx context.Context) ([]string, error)

Refresh: reset + up.

func (*Migrator) Reset

func (m *Migrator) Reset(ctx context.Context) ([]string, error)

Reset rolls back every applied migration in reverse order.

func (*Migrator) Rollback

func (m *Migrator) Rollback(ctx context.Context, step int) ([]string, error)

Rollback reverses the last batch of migrations (or step) and returns the names reverted in application order.

func (*Migrator) Status

func (m *Migrator) Status(ctx context.Context) ([]StatusRow, error)

Status returns one StatusRow per known migration.

func (*Migrator) Step

func (m *Migrator) Step(ctx context.Context, n int) ([]string, error)

Step applies up to n pending migrations.

func (*Migrator) Up

func (m *Migrator) Up(ctx context.Context) ([]string, error)

Up applies all pending migrations in a new batch. Returns the names applied.

type Options

type Options struct {
	// Table overrides the migrations record table (default "migrations").
	Table string
	// Pretend renders SQL but does not execute it.
	Pretend bool
	// AllowOutOfOrder permits applying migrations whose names sort before a
	// previously applied migration. Off by default to mirror Laravel.
	AllowOutOfOrder bool
	// EnforceChecksums causes the migrator to refuse to run when a recorded
	// migration's checksum has drifted from current source.
	EnforceChecksums bool
	// LockTimeout for acquiring the migrations lock.
	LockTimeout time.Duration
	// Logger receives status messages.
	Logger *logger.Logger
}

Options configures Migrator behavior.

type Record

type Record struct {
	Migration string
	Batch     int
	Checksum  string
	AppliedAt time.Time
}

Record is a row in the migrations tracking table.

type Registry

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

Registry collects migrations and returns them in deterministic order. Applications normally have one global registry (Default) that migration files populate via Register() in their init().

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates an empty registry.

func (*Registry) All

func (r *Registry) All() []Migration

All returns migrations in lexical name order.

func (*Registry) Get

func (r *Registry) Get(name string) (Migration, bool)

Get returns a migration by name.

func (*Registry) Names

func (r *Registry) Names() []string

Names returns all registered names (sorted).

func (*Registry) Register

func (r *Registry) Register(m Migration)

Register adds m. Panics on duplicate name to fail fast at startup.

func (*Registry) Reset

func (r *Registry) Reset()

Reset clears the registry. Intended for tests.

type Repository

type Repository struct {
	Conn  *database.Connection
	Table string
}

Repository persists migration history.

func NewRepository

func NewRepository(conn *database.Connection, table string) *Repository

NewRepository builds a Repository targeting the given table.

func (*Repository) All

func (r *Repository) All(ctx context.Context) ([]Record, error)

All returns every record sorted by application order (batch asc, migration asc).

func (*Repository) Delete

func (r *Repository) Delete(ctx context.Context, exec database.Executor, name string) error

Delete removes a record by migration name.

func (*Repository) Ensure

func (r *Repository) Ensure(ctx context.Context) error

Ensure creates the migrations table if it does not already exist.

func (*Repository) Insert

func (r *Repository) Insert(ctx context.Context, exec database.Executor, rec Record) error

Insert records a successful migration application.

func (*Repository) LastBatch

func (r *Repository) LastBatch(ctx context.Context) (int, error)

LastBatch returns the highest batch number currently recorded, or 0.

func (*Repository) Names

func (r *Repository) Names(ctx context.Context) (map[string]Record, error)

Names returns the set of applied migration names as a map for O(1) lookup.

type StatusRow

type StatusRow struct {
	Name      string
	Applied   bool
	Stale     bool
	Batch     int
	AppliedAt time.Time
	Checksum  string
}

StatusRow describes one entry in the status report.

Jump to

Keyboard shortcuts

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