migrate

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2026 License: AGPL-3.0 Imports: 10 Imported by: 0

Documentation

Overview

Package migrate 封装 goose 迁移的执行与并发保护。

两条关键设计:

  1. 启动自动迁移必须带锁。多实例同时启动时,无锁会让两个进程 并发执行同一批 DDL,轻则报错、重则留下半成品 schema。这里用 PostgreSQL 的 会话级 advisory lock 做互斥:拿不到锁的实例等待,而不是跳过迁移(跳过会让 实例在旧 schema 上运行,问题更隐蔽)。
  2. 核心与每个模块是独立的迁移来源,各有自己的版本表。插件生态里不可能协调 全局唯一的迁移编号,模块只需在自己的序列内递增。

实现基于 goose 的 Provider(实例级、无包级全局状态),并发构造多个 Migrator 也安全。

Index

Constants

View Source
const CoreName = "core"

CoreName 是核心迁移来源的名称。

它的版本表沿用 goose 默认名 goose_db_version,以兼容阶段 1、2 已迁移过的库。

View Source
const DefaultLockTimeout = 2 * time.Minute

DefaultLockTimeout 是未显式配置时等待迁移锁的上限。

等待是必要语义(多实例并发迁移必须串行),但必须有上限:数据库黑洞或 遗留会话会让 pg_advisory_lock 永久挂起,进而卡死整个启动流程。

Variables

This section is empty.

Functions

func TableName

func TableName(source string) string

TableName 返回来源对应的版本表名。

Types

type Migrator

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

Migrator 按来源顺序执行迁移。

func New

func New(db *sql.DB, sources []Source, logger *slog.Logger, opts ...Option) (*Migrator, error)

New 构造 Migrator。sources 按给定顺序执行,核心应放在最前;logger 可为 nil。

func (*Migrator) Down

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

Down 回滚指定来源的最后一个迁移;source 为空时取核心。仅供开发排错,生产不应使用。

func (*Migrator) Sources

func (m *Migrator) Sources() []string

Sources 返回来源名列表,顺序即执行顺序。

func (*Migrator) Status

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

Status 返回全部来源中每个迁移的应用状态,按来源顺序、版本升序排列。

func (*Migrator) Up

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

Up 按来源顺序应用所有待执行的迁移,全程持有互斥锁。

func (*Migrator) Version

func (m *Migrator) Version(ctx context.Context, source string) (int64, error)

Version 返回指定来源当前已应用的最新迁移版本号;source 为空时取核心。 版本表尚不存在时返回 0。

type Option

type Option func(*Migrator)

Option 是 Migrator 的可选配置。

func WithLockDB

func WithLockDB(db *sql.DB) Option

WithLockDB 指定一个仅用于持有迁移 advisory lock 的独立连接池(容量 1 即可)。

goose 的 Provider 只接受 *sql.DB,无法让锁与迁移共用同一条会话;锁与迁移 若从同一池取连接,池容量为 1 时会互相等待。独立池把两者彻底隔开, 是单连接池部署的首选解法。

func WithLockTimeout

func WithLockTimeout(d time.Duration) Option

WithLockTimeout 覆盖等待迁移锁的上限;d <= 0 时保持默认值。

type Source

type Source struct {
	Name string
	FS   fs.FS
}

Source 是一个迁移来源:核心或某个模块。

FS 的根目录直接包含 goose SQL 文件(goose 不递归子目录,需要时用 fs.Sub 定位)。

type Status

type Status struct {
	Source    string
	Version   int64
	Path      string
	Applied   bool
	AppliedAt time.Time
}

Status 是一条迁移的应用状态。

Jump to

Keyboard shortcuts

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