migrate

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 13 Imported by: 1 module, 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 migrate 提供基于 golang-migrate 的版本化数据库迁移能力:

  • Create:在迁移目录中生成一对带时间戳版本的 up/down SQL 文件;
  • Up / Down / Version:对 MySQL 执行迁移。

迁移文件位于项目的 migrations 目录,命名格式为:

<版本号>_<名称>.up.sql / <版本号>_<名称>.down.sql

版本号是创建时间戳(14 位数字),保证与 golang-migrate 的版本语义兼容。

使用示例:

if err := migrate.Up(migrate.Options{DSN: dsn, Dir: "migrations"}); err != nil {
    log.Fatalf("migrate up failed: %v", err)
}

注意:MySQL 驱动默认不允许多语句迁移文件,如需在单个 .sql 中写多条语句, DSN 必须包含 multiStatements=true 参数。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Create

func Create(dir, name string) (string, error)

Create 在 dir 目录中生成一对迁移文件,返回 up 文件路径. 目录不存在时自动创建;名称校验失败或文件已存在时返回错误.

func Down

func Down(opts *Options, steps int) error

Down 回滚迁移:steps > 0 时回滚最近 steps 个版本,否则回滚到最初状态. 回滚步数超过当前版本序号时,一次性回滚到最初状态.

func Up

func Up(opts *Options) error

Up 将所有未应用的迁移按版本顺序执行到最新. 没有任何待执行的迁移时不视为错误.

func Version

func Version(opts *Options) (uint, bool, error)

Version 返回当前数据库的迁移版本号与 dirty 状态. 尚未执行过任何迁移时版本号为 0.

Types

type Options

type Options struct {
	// Dir 迁移 SQL 文件所在目录,默认 "migrations"
	Dir string
	// DSN go-sql-driver/mysql 格式的 DSN(必填),
	// 多语句迁移文件需要额外包含 multiStatements=true
	DSN string
}

Options 迁移执行选项.

Jump to

Keyboard shortcuts

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