migrate

package
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: Apache-2.0 Imports: 17 Imported by: 1

Documentation

Overview

Package migrate 提供带跨副本锁的有序 GORM 数据库迁移。

Index

Constants

View Source
const (
	TableName              = "_migrations"
	MinimumMySQLVersion    = "5.7"
	MinimumMariaDBVersion  = "10.5"
	MinimumPostgresVersion = "14"
	MinimumSQLiteVersion   = "3.35"
)

Variables

View Source
var (
	ErrDatabaseRequired    = errx.New("migrate: database is required")
	ErrDatabaseNotSelected = errx.New("migrate: database is not selected")
	ErrInvalidMigrationID  = errx.New("migrate: invalid migration ID")
	ErrDuplicatedID        = errx.New("migrate: duplicated migration ID")
	ErrUpRequired          = errx.New("migrate: migration Up is required")
	ErrUnknownMigration    = errx.New("migrate: database contains an unknown migration")
	ErrUnsupportedDriver   = errx.New("migrate: unsupported database driver")
	ErrInvalidLockTimeout  = errx.New("migrate: lock timeout must not be negative")
	ErrLockTimeout         = errx.New("migrate: lock timeout")
	ErrLockFailed          = errx.New("migrate: lock operation failed")
)

Functions

This section is empty.

Types

type Migration

type Migration struct {
	ID   string
	Up   func(*dbx.DB) error
	Down func(*dbx.DB) error
}

Migration 是一个可向前执行并可选回滚的数据库版本。

type Migrations

type Migrations []*Migration

Migrations 是按 ID 排序后执行的迁移集合。

func (*Migrations) Add

func (m *Migrations) Add(up, down func(*dbx.DB) error)

Add 从直接调用方的 Go 文件名生成迁移 ID,并追加一个迁移。 迁移文件发布后不得重命名,否则数据库会将其识别为新的迁移。

type Migrator

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

Migrator 管理一组固定且已排序的迁移。

func New

func New(db *dbx.DB, migrations Migrations, options ...Option) (*Migrator, error)

New 校验并复制迁移列表,调用方后续修改原切片不会影响执行顺序。

func (*Migrator) Down

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

Down 回滚最后一个已应用迁移。未定义 Down 时仅移除该迁移记录。

func (*Migrator) Reset

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

Reset 按逆序回滚全部已应用迁移。未定义 Down 的迁移直接跳过回滚逻辑并移除记录。

func (*Migrator) Up

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

Up 按 ID 顺序执行全部尚未应用的迁移。

type Option

type Option func(*config)

Option 调整迁移和锁行为。

func WithLockTimeout

func WithLockTimeout(timeout time.Duration) Option

WithLockTimeout 设置等待迁移锁的最长时间。

func WithTransaction

func WithTransaction(enabled bool) Option

WithTransaction 配置 gormigrate 是否为迁移批次开启事务。 SQLite 始终由 BEGIN IMMEDIATE 包裹,以同时提供锁和事务边界。

func WithValidateUnknownMigrations

func WithValidateUnknownMigrations(enabled bool) Option

WithValidateUnknownMigrations 配置是否拒绝数据库中未在当前代码声明的迁移。

Jump to

Keyboard shortcuts

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