migrate

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package migrate runs versioned schema migrations in batches, Knex-style.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DropAllTables

func DropAllTables(ctx context.Context, db *migro.DB) error

DropAllTables removes every table, retrying so foreign-key order does not matter.

func Register

func Register(d Definition)

Register records a migration whose name is taken from the calling file's name. Invalid or duplicate names are reported by Registered / AddRegistered, never by panicking in init().

func RegisterAs

func RegisterAs(name string, d Definition)

RegisterAs registers a migration under an explicit name.

func ResetRegistry

func ResetRegistry()

ResetRegistry clears the registry (for tests).

func SplitStatements

func SplitStatements(src string) []string

SplitStatements splits SQL on semicolons, ignoring those in quotes and -- comments.

Types

type ConnectionPinned

type ConnectionPinned interface{ Connection() string }

ConnectionPinned pins a migration to a named connection (Lucid's `connection`).

type Definition

type Definition interface {
	Up(ctx context.Context, s *schema.Builder) error
	Down(ctx context.Context, s *schema.Builder) error
}

Definition is a Lucid-style migration class: put one in each file named <yyyymmddhhmmss>_<snake_case_name>.go and register it from init().

func init() { migrate.Register(&CreateUsersTable{}) }

type Dump

type Dump struct {
	Dialect    string
	Migrations []string
	Statements []string
}

Dump is a squashed schema: the SQL every migration would run on an empty database, plus the names of those migrations. Loading it into a fresh database replaces running them one by one, so old migration files can be retired without losing the ability to build a new database.

A dump is built by running each migration in pretend mode, so it needs no external tool (no pg_dump or mysqldump) and is portable only within the dialect it was generated for.

func ParseDump

func ParseDump(src string) (Dump, error)

ParseDump reads what Dump.String wrote.

func (Dump) String

func (d Dump) String() string

String renders the dump as a SQL file ParseDump reads back.

type Event

type Event struct {
	Kind     EventKind
	Name     string
	Duration time.Duration
}

Event reports progress; Duration is set on Migrated/Reverted.

type EventKind

type EventKind string

EventKind identifies a progress event.

const (
	Migrating EventKind = "migrating"
	Migrated  EventKind = "migrated"
	Reverting EventKind = "reverting"
	Reverted  EventKind = "reverted"
)

type Func

type Func func(ctx context.Context, s *schema.Builder) error

Func is one direction of a migration. It receives a schema builder bound to the migration's transaction (when the dialect supports transactional DDL).

type Migration

type Migration struct {
	Name string
	Up   Func
	Down Func
	// DisableTransaction runs the migration without a wrapping transaction.
	DisableTransaction bool
	// Checksum is optional; when set, edits to an applied migration are detected.
	Checksum string
	// Connection pins the migration to a named connection; "" means the default one.
	Connection string
}

Migration is a named, ordered unit of change. Names sort lexicographically (use a timestamp prefix such as 20240101120000_create_users).

func FromFS

func FromFS(fsys fs.FS, dir string) ([]Migration, error)

FromFS loads "<name>.up.sql" / "<name>.down.sql" pairs from dir in fsys. Statements are split on ";" (outside quotes and -- comments); stored procedures with inner semicolons need a Go migration instead.

func Registered

func Registered() ([]Migration, error)

Registered returns every registered migration sorted by name, or the registration errors.

func (Migration) String

func (m Migration) String() string

type Migrator

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

Migrator applies and rolls back migrations, recording them in a table.

func New

func New(db *migro.DB, opts ...Option) *Migrator

func (*Migrator) Add

func (m *Migrator) Add(ms ...Migration) error

Add registers migrations; names must be unique.

func (*Migrator) AddRegistered

func (m *Migrator) AddRegistered() error

AddRegistered adds every migration registered through Register.

func (*Migrator) DB

func (m *Migrator) DB() *migro.DB

DB returns the database the migrator works on.

func (*Migrator) Dump

func (m *Migrator) Dump(ctx context.Context) (Dump, error)

Dump squashes the migrator's migrations. Nothing is written to the database. Run it against an empty database: a migration that inspects the existing schema (HasTable, ...) would otherwise record a different history.

func (*Migrator) Fresh

func (m *Migrator) Fresh(ctx context.Context) (Result, error)

Fresh drops every table in the database (not just migrated ones), then applies all migrations. It is destructive: callers decide whether it is allowed.

func (*Migrator) Install

func (m *Migrator) Install(ctx context.Context) error

Install creates the migration bookkeeping tables. Every other method does this on demand; call Install to do it explicitly (migration:install).

func (*Migrator) Latest

func (m *Migrator) Latest(ctx context.Context) (Result, error)

Latest applies every pending migration as one batch.

func (*Migrator) LoadDump

func (m *Migrator) LoadDump(ctx context.Context, d Dump) error

LoadDump executes the dump and records its migrations as applied in one batch.

func (*Migrator) Refresh

func (m *Migrator) Refresh(ctx context.Context) (Result, error)

Refresh reverts everything, then applies everything again.

func (*Migrator) Reset

func (m *Migrator) Reset(ctx context.Context) (Result, error)

Reset reverts every applied migration, newest first.

func (*Migrator) Revert

func (m *Migrator) Revert(ctx context.Context, opts RevertOptions) (Result, error)

Revert rolls migrations back according to opts.

func (*Migrator) Rollback

func (m *Migrator) Rollback(ctx context.Context) (Result, error)

Rollback reverts the most recent batch.

func (*Migrator) RollbackSteps

func (m *Migrator) RollbackSteps(ctx context.Context, n int) (Result, error)

RollbackSteps reverts the n most recently applied migrations.

func (*Migrator) RollbackToBatch

func (m *Migrator) RollbackToBatch(ctx context.Context, batch int) (Result, error)

RollbackToBatch reverts every migration applied after batch.

func (*Migrator) Run

func (m *Migrator) Run(ctx context.Context, opts RunOptions) (Result, error)

Run applies every pending migration.

func (*Migrator) Status

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

Status reports every registered migration and whether it is applied.

func (*Migrator) Unlock

func (m *Migrator) Unlock(ctx context.Context) error

Unlock force-releases a stale lock.

type Option

type Option func(*Migrator)

Option customises a Migrator.

func WithConnection

func WithConnection(selected, defaultName string) Option

WithConnection restricts the Migrator to migrations pinned to connection selected, plus unpinned ones when selected is the default connection.

func WithDump

func WithDump(d Dump) Option

WithDump makes Run load the dump into a database that has no applied migrations, then run only the migrations the dump does not cover.

func WithObserver

func WithObserver(fn func(Event)) Option

WithObserver receives an Event before and after every migration step.

func WithTable

func WithTable(name string) Option

WithTable overrides the migrations table (default "migro_migrations").

type Result

type Result struct {
	Batch int
	Names []string
	// SQL holds, per migration, the statements that would run. Only set by pretend runs.
	SQL map[string][]string
}

Result lists the migrations a call applied or reverted.

type RevertOptions

type RevertOptions struct {
	// Steps reverts the N most recently applied migrations (Laravel's --step).
	Steps int
	// ToBatch reverts every migration applied after the given batch; 0 reverts everything (Adonis' --batch).
	ToBatch *int
	All     bool
	Pretend bool
}

RevertOptions select what to roll back. Set at most one of Steps, ToBatch, All; with none set the most recent batch is reverted.

type RunOptions

type RunOptions struct {
	// Step puts every migration in its own batch so each can be rolled back on its own.
	Step bool
	// Pretend returns the SQL each migration would run and changes nothing.
	Pretend bool
}

RunOptions tune Run.

type Status

type Status struct {
	Name      string
	Applied   bool
	Batch     int
	AppliedAt time.Time
}

Status describes one registered migration.

type TransactionOptOut

type TransactionOptOut interface{ DisableTransaction() bool }

TransactionOptOut opts a migration out of the wrapping transaction.

Directories

Path Synopsis
Package diff compares GORM models with a live database and writes the difference as migration files (the same .up.sql / .down.sql format migrate.FromFS reads).
Package diff compares GORM models with a live database and writes the difference as migration files (the same .up.sql / .down.sql format migrate.FromFS reads).

Jump to

Keyboard shortcuts

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