数据库迁移
ling-base common/migration 模块文档
在线 Playground
在浏览器中直接体验本页相关 API,无需本地安装 Go 环境。
migration
Database schema migration framework with versioned SQL files, up/down directions, and pluggable migrator backends.
Features
- Versioned SQL migrations with
.up.sql/.down.sqlfile pairs - Sources: embedded filesystem (
EmbedSource), OS directory (FileSource), programmatic (StaticSource) - Migrator interface for database-specific execution (e.g.
gormmigratorsubpackage) - Up, down, step, and version-targeted migration
- Status inspection (applied, pending, current version)
Key types
Migration-- single migration (Version, Description, UpSQL, DownSQL)MigrationStatus-- migration with applied state and timestampSource-- interface providing migration filesEmbedSource/FileSource/StaticSource-- source implementationsMigrator-- interface for executing migrations (Up, Down, Step, Version, Status)
Key functions
NewEmbedSource(fsys, root)-- source fromgo:embedfilesystemNewFileSource(dir)-- source from OS directoryNewStaticSource(migrations...)-- source from explicit listMigrator.Up(ctx),Migrator.Down(ctx),Migrator.Step(ctx, n)Migrator.Version()-- current applied versionMigrator.Status(ctx)-- list all migrations with applied state
Quick start
import (
"embed"
"github.com/LingByte/ling-base/common/migration"
"github.com/LingByte/ling-base/common/migration/gormmigrator"
)
//go:embed migrations/*.sql
var migrationFS embed.FS
src := migration.NewEmbedSource(migrationFS, "migrations")
migrator := gormmigrator.New(db, src)
if err := migrator.Up(context.Background()); err != nil {
log.Fatal(err)
}License
MIT