Documentation
¶
Overview ¶
Package migrate applies versioned SQL and Go migrations to PostgreSQL, MySQL/MariaDB, SQLite, SQL Server, Oracle Database, and IBM Db2 LUW.
A Migrator is built once from a *sql.DB and a migration source and is then immutable and safe for concurrent use. Runs that change the database (Up, Down, Repair, Baseline) hold a cross-process lock: a session advisory lock on PostgreSQL, MySQL, SQL Server, Oracle, and Db2 and a run-lifetime file lock with a lease on SQLite. In-memory SQLite databases coordinate within the process. Transactional migrations and their history row commit together. A failed nontransactional migration leaves a "dirty" row that blocks further runs. Restore the schema by hand before clearing that row with Repair or completing it with MarkApplied.
The package itself imports no SQL driver; register the one you use, e.g.
import _ "github.com/jackc/pgx/v5/stdlib" // "pgx" import _ "github.com/go-sql-driver/mysql" // "mysql" import _ "github.com/microsoft/go-mssqldb" // "sqlserver" import _ "github.com/oracle/go-oracledb/v26/oracle" // "oracledb" import _ "github.com/go-db2/go-db2" // "db2" import _ "modernc.org/sqlite" // "sqlite", pure Go
Example ¶
Apply the example migrations to an in-memory SQLite database. In an application, pass an embed.FS (via fs.Sub) instead of os.DirFS.
package main
import (
"context"
"database/sql"
"fmt"
"log"
"os"
migrate "github.com/go-gen-ecosystem/go-migrate"
_ "modernc.org/sqlite"
)
func main() {
db, err := sql.Open("sqlite", ":memory:")
if err != nil {
log.Fatal(err)
}
db.SetMaxOpenConns(1) // one shared in-memory database
m, err := migrate.New(db, "sqlite", migrate.WithFS(os.DirFS("examples/migrations")))
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
res, err := m.Up(ctx)
if err != nil {
log.Fatal(err)
}
for _, a := range res.Applied {
fmt.Println("applied", a.Source)
}
st, err := m.Status(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println("current version:", st.Current, "pending:", st.Pending)
plan, err := m.PlanDown(ctx, migrate.DownTarget{Steps: 1})
if err != nil {
log.Fatal(err)
}
fmt.Println("down 1 would revert:", plan[0].Version)
if err := db.Close(); err != nil {
log.Fatal(err)
}
}
Output: applied 0001_create_users.sql applied 0002_create_posts.up.sql | 0002_create_posts.down.sql applied 0003_add_users_active.sql applied R__user_post_counts.sql current version: 3 pending: 0 down 1 would revert: 3
Index ¶
- Constants
- Variables
- func ErrorCodes(err error) []string
- func LintRules() []string
- type Applied
- type Callback
- type Direction
- type DownTarget
- type Event
- type Executor
- type Finding
- type GoMigration
- type Hooks
- type Info
- type Migration
- type MigrationError
- type Migrator
- func (m *Migrator) Baseline(ctx context.Context, version, description string) error
- func (m *Migrator) Callbacks(dir Direction) []Callback
- func (m *Migrator) Down(ctx context.Context, t DownTarget, opts ...RunOption) (*Result, error)
- func (m *Migrator) Lint() []Finding
- func (m *Migrator) MarkApplied(ctx context.Context, version string) error
- func (m *Migrator) Migrations() []Migration
- func (m *Migrator) Plan(ctx context.Context, target string) ([]Migration, error)
- func (m *Migrator) PlanDown(ctx context.Context, t DownTarget) ([]Migration, error)
- func (m *Migrator) PlanDownWithID(ctx context.Context, t DownTarget) ([]Migration, string, error)
- func (m *Migrator) PlanID(dir Direction, plan []Migration) string
- func (m *Migrator) PlanRepair(ctx context.Context, target RepairTarget) (*RepairPlan, error)
- func (m *Migrator) PlanWithID(ctx context.Context, target string) ([]Migration, string, error)
- func (m *Migrator) Redo(ctx context.Context) (*Result, error)
- func (m *Migrator) Repair(ctx context.Context, targets ...RepairTarget) (*RepairResult, error)
- func (m *Migrator) Statements(mig Migration, dir Direction) []string
- func (m *Migrator) Status(ctx context.Context) (*Status, error)
- func (m *Migrator) Tag(ctx context.Context, tag string) error
- func (m *Migrator) Up(ctx context.Context, opts ...RunOption) (*Result, error)
- func (m *Migrator) UpTo(ctx context.Context, version string, opts ...RunOption) (*Result, error)
- func (m *Migrator) Validate(ctx context.Context) error
- type Option
- func WithAllowMissing(allow bool) Option
- func WithAllowOutOfOrder(allow bool) Option
- func WithApprovalEndpoint(endpoint string) Option
- func WithBaselineOnMigrate(version string) Option
- func WithContexts(contexts ...string) Option
- func WithFS(fsys fs.FS) Option
- func WithGoMigrations(ms ...GoMigration) Option
- func WithHooks(h Hooks) Option
- func WithInstalledBy(name string) Option
- func WithLabels(labels ...string) Option
- func WithLockWait(d time.Duration) Option
- func WithLogger(l halolog.Logger) Option
- func WithPlaceholders(values map[string]string) Option
- func WithTable(name string) Option
- type RepairAction
- type RepairPlan
- type RepairResult
- type RepairTarget
- type Result
- type RunOption
- type State
- type Status
Examples ¶
Constants ¶
const ( // DefaultTable is the default history table. It is deliberately distinct // from golang-migrate's schema_migrations so both tools can coexist. DefaultTable = "gomigrate_history" // DefaultLockWait is how long a run waits for another to finish. DefaultLockWait = 5 * time.Minute )
Defaults.
const RunCallbacksRepairKey = "C:run-callbacks"
RunCallbacksRepairKey is the repair target for an interrupted run-level SQL callback sequence. It is reserved and cannot be a migration version.
Variables ¶
var ( // ErrDirty means a non-transactional migration or run-level callback may // have changed the database. For a migration, bring the schema by hand to // either side, then use Repair with RepairClearFailed or MarkApplied. ErrDirty = errors.New("database is dirty: a migration failed part-way; " + dirtyGuidance) // ErrCallbackRecoveryRequired also matches ErrDirty. Inspect the callback // effects, then clear RunCallbacksRepairKey only when another run is safe. ErrCallbackRecoveryRequired error = callbackRecoveryError{} // ErrCommitOutcomeUnknown means a migration transaction may have committed // even though Commit returned an error. The migration and its history change // share that outcome. Inspect them on the writable database and make a // fresh plan before retrying. ErrCommitOutcomeUnknown = errors.New("transaction commit outcome unknown; reconnect to the writable database, inspect the schema and migration history, and generate a fresh plan before retrying") // ErrBelowBaseline means a rollback target lies below the baseline, // which cannot be rolled back. ErrBelowBaseline = errors.New("target version is below the baseline") // ErrChecksumMismatch means an applied migration file was edited. ErrChecksumMismatch = errors.New("applied migration was modified") // ErrMissingMigration means the database has a version that no longer // exists in the migration source. ErrMissingMigration = errors.New("applied migration is missing from the source") // ErrOutOfOrder means a pending migration has a lower version than the // latest applied one; enable WithAllowOutOfOrder to apply it anyway. ErrOutOfOrder = errors.New("pending migration is older than the latest applied version") // ErrTransactionControl means a migration that runs in a transaction // contains BEGIN/COMMIT/ROLLBACK; mark it "-- +migrate Up notransaction". ErrTransactionControl = errors.New("transaction control statement in a transactional migration (use notransaction)") // ErrUnresolvedPlaceholder means an SQL file references ${name} that was // not provided via WithPlaceholders. ErrUnresolvedPlaceholder = errors.New("unresolved placeholder") // ErrPreconditionFailed means a migration's precondition with // onFail=HALT did not hold; nothing of that migration ran. ErrPreconditionFailed = errors.New("precondition failed") // ErrTagNotFound means no applied migration carries the requested tag. ErrTagNotFound = errors.New("tag not found") // ErrInvalidArgument means a caller passed invalid or conflicting arguments. ErrInvalidArgument = errors.New("invalid argument") // ErrPlanChanged means the plan to execute no longer matches the one // approved with ExpectPlan or ExpectTargetPlan. ErrPlanChanged = errors.New("plan or target changed since it was approved") // ErrApprovalTarget means the resolved database and schema could not be // identified well enough to issue a target-bound approval. ErrApprovalTarget = dialect.ErrApprovalTarget // ErrInvalidVersion means a version is not numeric (digits, optionally dot-separated). ErrInvalidVersion = errors.New("invalid version") // ErrVersionNotFound means a requested target version does not exist. ErrVersionNotFound = errors.New("version not found") // ErrIrreversible means a migration that must be rolled back has no down section. ErrIrreversible = errors.New("migration has no down section") // ErrNotEnoughApplied means Down was asked to roll back more migrations than are applied. ErrNotEnoughApplied = errors.New("not enough applied migrations") // ErrBaselineNotEmpty means Baseline was called on a database with history. ErrBaselineNotEmpty = errors.New("baseline requires an empty history table") // ErrLockTimeout means another process held the migration lock for longer than the lock wait. ErrLockTimeout = dialect.ErrLockTimeout // ErrLockLost means the migration lock expired or was taken over while held. ErrLockLost = dialect.ErrLockLost )
Sentinel errors. Use errors.Is to test for them; most are wrapped with the offending version.
var ( ErrBadPrecondition = script.ErrBadPrecondition ErrBadFileName = source.ErrBadFileName ErrDuplicateVersion = source.ErrDuplicateVersion ErrMissingUp = source.ErrMissingUp ErrEmptyUp = source.ErrEmptyUp ErrUpInDownFile = source.ErrUpInDownFile ErrMisplacedDirective = source.ErrMisplacedDirective ErrContentBeforeMarker = script.ErrContentBeforeMarker ErrDuplicateMarker = script.ErrDuplicateMarker ErrUnbalancedBlock = script.ErrUnbalancedBlock ErrUnknownDirective = script.ErrUnknownDirective ErrTSQLBatch = script.ErrTSQLBatch ErrPLSQLBlock = script.ErrPLSQLBlock ErrSQLPLBlock = script.ErrSQLPLBlock ErrUnsupportedDialect = dialect.ErrUnsupported ErrInvalidIdentifier = dialect.ErrInvalidIdentifier ErrHistoryRowNotFound = history.ErrNotFound )
Errors from loading migrations (New) and from the database layer, re-exported so callers can test for them with errors.Is.
Functions ¶
func ErrorCodes ¶
ErrorCodes returns the stable codes of every known error in err's tree, in a fixed order, plus "migration_failed" when a migration's SQL or Go code failed. It returns nil for nil and ["error"] for anything unrecognised.
Types ¶
type Applied ¶
type Applied struct {
Migration
Duration time.Duration
// MarkedRan is true when a precondition with onFail=MARK_RAN failed: the
// migration was recorded as applied without running.
MarkedRan bool
}
Applied is one migration executed by a run.
type Callback ¶
Callback is an SQL callback file and the statements it runs, after placeholder substitution. Event is its Flyway event name.
type DownTarget ¶
type DownTarget struct {
// Steps rolls back the last Steps applied migrations, newest first.
Steps int
// To rolls back every migration with a version above To ("0": all).
To string
// Tag rolls back every migration applied after the one tagged Tag.
Tag string
}
DownTarget selects what a rollback undoes. Set at most one field; the zero value rolls back the most recently applied migration.
type Event ¶
type Event struct {
Migration Migration
Direction Direction
// Duration and Err are set only for the After hook.
Duration time.Duration
Err error
}
Event is passed to hooks around each migration.
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 runs SQL. It is satisfied by *sql.DB, *sql.Tx and *sql.Conn. Go migrations receive a *sql.Tx on databases with transactional DDL (PostgreSQL, SQLite) unless they set NoTx; on MySQL, or with NoTx, they receive the run's *sql.Conn and follow the dirty-row protocol (see ErrDirty).
type Finding ¶
type Finding struct {
Rule string
Severity string // "error", "warning" or "info"
Message string
Hint string
// Version is the migration's Label; Source its file. For a callback
// file, Version is empty and Event names the callback event.
Version string
Source string
Event string
// Statement is the 1-based Up statement, or 0 for the whole migration.
Statement int
SQL string
}
Finding is one lint result: a risky or unsupported operation in a migration. Rule IDs are stable and can be suppressed per file with "-- +migrate Lint ignore=<rule>[,<rule>]".
type GoMigration ¶
type GoMigration struct {
Version string
Description string
Up func(ctx context.Context, ex Executor) error
// Down is optional; without it the migration is irreversible.
Down func(ctx context.Context, ex Executor) error
// NoTx runs the migration outside a transaction.
NoTx bool
}
GoMigration is a migration written in Go, for changes SQL alone cannot express (data backfills that call application code, conditional logic).
type Hooks ¶
type Hooks struct {
Before func(ctx context.Context, e Event) error
After func(ctx context.Context, e Event)
}
Hooks are optional callbacks around each migration. Before may veto a migration by returning an error. Hooks run while the lock is held.
type Info ¶
type Info struct {
Migration
State State
// The following are set only for migrations with a history row.
InstalledOn time.Time
InstalledBy string
ExecutionTime time.Duration
// Tag is the release tag on this migration, if any (see Migrator.Tag).
Tag string
}
Info is a migration together with its state and history row (if any).
type Migration ¶
type Migration struct {
// Version is the canonical version ("" for repeatable migrations).
Version string
Description string
Repeatable bool
// Source is the file name(s), or "go" for a Go migration.
Source string
// Checksum is the SHA-256 of the normalized file content ("" for Go).
Checksum string
NoTx bool
Reversible bool
// Conditional is set when the migration has preconditions: a run may
// skip it or record it without executing its SQL.
Conditional bool
}
Migration describes one migration known to the Migrator.
type MigrationError ¶
type MigrationError struct {
Version string
Direction Direction
// Statement is the 1-based index of the failing statement, or 0 if the
// error is not tied to a statement (for example, during Commit).
Statement int
// SQL is the start of the failing statement, truncated.
SQL string
// Dirty is true when the failure left the database in a partial state
// (non-transactional migration); see ErrDirty.
Dirty bool
Err error
}
MigrationError identifies the migration and, when relevant, the statement associated with an error.
func (*MigrationError) Error ¶
func (e *MigrationError) Error() string
func (*MigrationError) Unwrap ¶
func (e *MigrationError) Unwrap() []error
Unwrap returns the underlying cause (and ErrDirty when Dirty is set).
type Migrator ¶
type Migrator struct {
// contains filtered or unexported fields
}
Migrator applies migrations to one database. Create it with New.
Migrator is a facade: each method validates its arguments and delegates to a focused component (catalog: what exists; planner: what to do; runner and maintenance: doing it under the lock; applier: one migration at a time).
func New ¶
New builds a Migrator for db. dialectName is "postgres", "mysql", "sqlite", "sqlserver", "oracle", or "db2". Common driver aliases are accepted. The migration source is loaded and validated immediately, so malformed files and duplicate versions fail here rather than mid-run.
func (*Migrator) Baseline ¶
Baseline marks an existing database as being at version, so migrations up to and including it are treated as already applied. It requires an empty history table.
func (*Migrator) Callbacks ¶
Callbacks returns the SQL callbacks a run in direction dir executes, in order: beforeMigrate once, beforeEachMigrate and afterEachMigrate around every migration, then afterMigrate on success or afterMigrateError on failure. They run even when no migration is pending. Rollbacks run none. PlanID covers them, so an edited callback invalidates an approval.
func (*Migrator) Down ¶
Down rolls back the migrations selected by t, newest application first. It fails before changing anything if the selection is invalid, a selected migration was edited or is irreversible, or fewer migrations are applied than requested.
func (*Migrator) MarkApplied ¶
MarkApplied records version as applied without running it: for a dirty row whose migration you completed by hand (see ErrDirty), or to adopt a single change that already exists in the database. It is idempotent.
func (*Migrator) Migrations ¶
Migrations returns every known migration in execution order.
func (*Migrator) Plan ¶
Plan returns what Up (target == "") or UpTo(target) would apply, without applying it, including the effect of WithBaselineOnMigrate. Use it for dry runs and bind an approval to it with PlanID and ExpectPlan.
func (*Migrator) PlanDownWithID ¶
PlanDownWithID returns the rollback plan and its target-bound approval ID on one session. Use the ID with ExpectTargetPlan.
func (*Migrator) PlanID ¶
PlanID fingerprints a plan returned by Plan or PlanDown: its direction and each migration's identity, checksum and exact statements. Pass it to ExpectPlan so the run fails with ErrPlanChanged unless it executes exactly what was approved. It returns an empty ID for an invalid direction.
func (*Migrator) PlanRepair ¶
func (m *Migrator) PlanRepair(ctx context.Context, target RepairTarget) (*RepairPlan, error)
PlanRepair previews the selected history repair without taking a migration lock or making any writes. Repair checks the current state again when run.
func (*Migrator) PlanWithID ¶
PlanWithID returns the dry run and its target-bound approval ID. Both the plan and target are read on one session. Use the ID with ExpectTargetPlan.
func (*Migrator) Redo ¶
Redo rolls back the most recently applied migration and applies it again, under a single lock so no other run can interleave. The Result lists the re-applied migration.
func (*Migrator) Repair ¶
func (m *Migrator) Repair(ctx context.Context, targets ...RepairTarget) (*RepairResult, error)
Repair applies exactly one explicit history change. Clear a failed row only after restoring the schema by hand; if you completed the migration, use MarkApplied instead. Clear RunCallbacksRepairKey only after inspecting callback effects and making another run safe. Repair never runs SQL from migrations or callbacks. A call without exactly one target returns ErrInvalidArgument without writing history.
func (*Migrator) Statements ¶
Statements returns the SQL that mig runs in direction dir, after placeholder substitution, exactly as it would be executed (Liquibase updateSQL). Go migrations and unknown migrations return nil.
func (*Migrator) Status ¶
Status reports every migration's state. It is read-only: it takes no lock and never creates the history table. Pending counts what Up would apply, excluding RunAlways repeatables (they run every time and are never "behind").
func (*Migrator) Tag ¶
Tag labels the most recently applied migration with tag (for example a release name), so DownToTag can return to this point later. Tags are unique: tagging again moves the tag.
func (*Migrator) Up ¶
Up applies every pending migration, then any new or changed repeatable migrations. Nothing pending is not an error: the Result is simply empty.
type Option ¶
type Option func(*options)
Option configures a Migrator.
func WithAllowMissing ¶
WithAllowMissing tolerates applied versions that no longer exist in the source instead of failing with ErrMissingMigration.
func WithAllowOutOfOrder ¶
WithAllowOutOfOrder applies pending migrations whose version is lower than the latest applied one (useful when feature branches merge late) instead of failing with ErrOutOfOrder.
func WithApprovalEndpoint ¶
WithApprovalEndpoint adds a credential-free network endpoint identifier to target-bound plan IDs. This distinguishes routes to servers with identical reported names. Use the same endpoint identifier for preview and execution. Never supply a DSN or authentication material.
func WithBaselineOnMigrate ¶
WithBaselineOnMigrate makes Up baseline at version first when the history table is empty but the schema already contains tables (Flyway baselineOnMigrate), so an existing database can adopt go-migrate in place.
func WithContexts ¶
WithContexts selects the active contexts (Liquibase contexts). A migration declaring "-- +migrate Context ..." runs only if one of its contexts is active; migrations without contexts always run. Without this option every migration runs.
func WithFS ¶
WithFS loads SQL migrations from fsys, e.g. os.DirFS("migrations") or an embed.FS (use fs.Sub to point at a subdirectory).
func WithGoMigrations ¶
func WithGoMigrations(ms ...GoMigration) Option
WithGoMigrations registers migrations written in Go. Their versions share one ordering with SQL migrations and must not collide with them.
Example ¶
Go migrations run in the same ordered sequence as SQL files.
package main
import (
"context"
"database/sql"
"fmt"
"log"
"os"
migrate "github.com/go-gen-ecosystem/go-migrate"
_ "modernc.org/sqlite"
)
func main() {
db, err := sql.Open("sqlite", ":memory:")
if err != nil {
log.Fatal(err)
}
db.SetMaxOpenConns(1)
backfill := migrate.GoMigration{
Version: "4",
Description: "seed admin user",
Up: func(ctx context.Context, ex migrate.Executor) error {
_, err := ex.ExecContext(ctx, "INSERT INTO users (id, email, name) VALUES (1, 'admin@example.com', 'Admin')")
return err
},
Down: func(ctx context.Context, ex migrate.Executor) error {
_, err := ex.ExecContext(ctx, "DELETE FROM users WHERE id = 1")
return err
},
}
m, err := migrate.New(db, "sqlite",
migrate.WithFS(os.DirFS("examples/migrations")),
migrate.WithGoMigrations(backfill))
if err != nil {
log.Fatal(err)
}
if _, err := m.Up(context.Background()); err != nil {
log.Fatal(err)
}
var posts int
if err := db.QueryRow("SELECT posts FROM user_post_counts WHERE id = 1").Scan(&posts); err != nil {
log.Fatal(err)
}
fmt.Println("admin has", posts, "posts")
if err := db.Close(); err != nil {
log.Fatal(err)
}
}
Output: admin has 0 posts
func WithInstalledBy ¶
WithInstalledBy sets the value recorded in installed_by (default: OS user).
func WithLabels ¶
WithLabels selects the active labels, with the same rules as WithContexts for migrations declaring "-- +migrate Labels ...".
func WithLockWait ¶
WithLockWait sets the lock acquisition budget, including reserving and setting up the session (default DefaultLockWait). Zero or negative makes one attempt using the caller's context and returns ErrLockTimeout if held.
func WithLogger ¶
WithLogger sets the halolog logger used for progress and diagnostics (default: a discarding logger). A nil logger keeps the default.
func WithPlaceholders ¶
WithPlaceholders enables ${name} substitution in SQL migrations, callbacks and preconditions (Flyway placeholders). Built-ins ${migrate:dialect}, ${migrate:table} and ${migrate:user} are available once enabled. An unresolved ${name} is a load error. Checksums are computed before substitution, so per-environment values never look like drift.
type RepairAction ¶
type RepairAction string
RepairAction selects one type of history repair.
const ( // RepairClearFailed removes a failed row after inspecting and reconciling // the database by hand. RepairClearFailed RepairAction = "clear-failed" // RepairAcceptChecksum accepts deliberate drift for an applied version. RepairAcceptChecksum RepairAction = "accept-checksum" )
type RepairPlan ¶
type RepairPlan struct {
RepairTarget
State State
StoredChecksum, NewChecksum string
StoredKind, NewKind string
}
RepairPlan describes a proposed history change. Migration is the canonical history key and State is the current state. Checksum and kind fields show the existing row and, for RepairAcceptChecksum, the proposed values.
type RepairResult ¶
type RepairResult struct {
// RemovedFailed is 1 when the selected failed row was removed.
RemovedFailed int64
// Realigned contains the selected version when its checksum was realigned.
Realigned []string
}
RepairResult reports what Repair changed.
type RepairTarget ¶
type RepairTarget struct {
// Migration is a version or, for RepairClearFailed, a repeatable label
// (R__<description>) or history key (R:<description>), or RunCallbacksRepairKey.
Migration string
Action RepairAction
}
RepairTarget identifies exactly one migration and action.
type RunOption ¶
type RunOption func(*runOptions)
RunOption adjusts one run (Up, UpTo, Down, Redo).
func ExpectPlan ¶
ExpectPlan makes the run verify, under the migration lock, that it is about to execute exactly the plan identified by id (see Migrator.PlanID) and to fail with ErrPlanChanged otherwise. It binds a human's or agent's approval of a dry run to what actually runs.
func ExpectTargetPlan ¶
ExpectTargetPlan only permits the SQL target and exact plan approved with PlanWithID or PlanDownWithID. Legacy content-only PlanID values are rejected.
type State ¶
type State string
State is the state of a migration relative to the database.
const ( StatePending State = "pending" StateApplied State = "applied" StateFailed State = "failed" // dirty: failed part-way, needs repair StateModified State = "modified" // applied, but the file changed since StateMissing State = "missing" // applied, but no longer in the source StateOutdated State = "outdated" // repeatable whose content changed StateBaseline State = "baseline" // the baseline marker row StateBelowBase State = "below baseline" StateOutOfOrder State = "out of order" // pending, older than the latest applied StateSkipped State = "skipped" // excluded by DBMS, Context or Labels StateMarkedRan State = "marked ran" // recorded by a MARK_RAN precondition, never executed StateRunAlways State = "run always" // RunAlways repeatable: re-applied on every Up )
Migration states reported by Status.
type Status ¶
type Status struct {
// Current is the highest applied version ("" if none).
Current string
// Dirty is true when a migration or run-level SQL callback needs recovery.
Dirty bool
// CallbackRecoveryRequired is true when a run-level callback may have
// changed the database. See ErrCallbackRecoveryRequired.
CallbackRecoveryRequired bool
// Pending counts migrations Up would apply.
Pending int
Migrations []Info
}
Status is a read-only snapshot of the database's migration state.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
gomigrate
command
Command gomigrate applies versioned SQL and Go migrations.
|
Command gomigrate applies versioned SQL and Go migrations. |
|
internal
|
|
|
actionrunner
command
The composite action runs this file with the Go toolchain it uses to install gomigrate.
|
The composite action runs this file with the Go toolchain it uses to install gomigrate. |
|
cli
Package cli implements the gomigrate command line.
|
Package cli implements the gomigrate command line. |
|
config
Package config loads the gomigrate CLI configuration and opens the database it describes.
|
Package config loads the gomigrate CLI configuration and opens the database it describes. |
|
dialect
Package dialect describes the SQL differences between supported databases: identifier quoting, bind placeholders, lexical rules for statement splitting, DDL transactionality, history-table DDL and migration locking.
|
Package dialect describes the SQL differences between supported databases: identifier quoting, bind placeholders, lexical rules for statement splitting, DDL transactionality, history-table DDL and migration locking. |
|
history
Package history persists which migrations have been applied.
|
Package history persists which migrations have been applied. |
|
lint
Package lint finds risky operations in migration SQL without a database: statements that take long exclusive locks, rewrite tables, lose data, break running application versions or are unsupported by the target dialect.
|
Package lint finds risky operations in migration SQL without a database: statements that take long exclusive locks, rewrite tables, lose data, break running application versions or are unsupported by the target dialect. |
|
nativecheck
command
nativecheck verifies the terminal events from a single engine's go test -json run.
|
nativecheck verifies the terminal events from a single engine's go test -json run. |
|
releasecheck
command
Command releasecheck verifies the source and archives used by the release workflow.
|
Command releasecheck verifies the source and archives used by the release workflow. |
|
script
Package script parses migration files and splits SQL into statements.
|
Package script parses migration files and splits SQL into statements. |
|
source
Package source discovers migration files in an fs.FS.
|
Package source discovers migration files in an fs.FS. |