74 lines
1.8 KiB
Go
74 lines
1.8 KiB
Go
package database
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log/slog"
|
|
"time"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
"rill/internal/model"
|
|
)
|
|
|
|
// Migration 描述一次数据库结构变更,Version 必须唯一且递增。
|
|
type Migration struct {
|
|
Version int
|
|
Name string
|
|
Up func(*gorm.DB) error
|
|
}
|
|
|
|
// migrations 按 Version 升序登记所有迁移,新增迁移只能追加。
|
|
var migrations = []Migration{
|
|
{
|
|
Version: 1,
|
|
Name: "create_notes",
|
|
Up: func(tx *gorm.DB) error {
|
|
return tx.AutoMigrate(&model.Note{})
|
|
},
|
|
},
|
|
}
|
|
|
|
// schemaMigration 记录已应用的迁移版本。
|
|
type schemaMigration struct {
|
|
Version int `gorm:"primaryKey"`
|
|
Name string
|
|
AppliedAt time.Time
|
|
}
|
|
|
|
func (schemaMigration) TableName() string { return "schema_migrations" }
|
|
|
|
// Migrate 依次执行未应用的迁移,每个迁移在独立事务中完成并记录版本,可重复调用。
|
|
func Migrate(ctx context.Context, db *gorm.DB) error {
|
|
tx := db.WithContext(ctx)
|
|
if err := tx.AutoMigrate(&schemaMigration{}); err != nil {
|
|
return fmt.Errorf("初始化迁移记录表失败: %w", err)
|
|
}
|
|
|
|
var applied []int
|
|
if err := tx.Model(&schemaMigration{}).Pluck("version", &applied).Error; err != nil {
|
|
return fmt.Errorf("读取迁移记录失败: %w", err)
|
|
}
|
|
done := make(map[int]bool, len(applied))
|
|
for _, version := range applied {
|
|
done[version] = true
|
|
}
|
|
|
|
for _, m := range migrations {
|
|
if done[m.Version] {
|
|
continue
|
|
}
|
|
err := tx.Transaction(func(tx *gorm.DB) error {
|
|
if err := m.Up(tx); err != nil {
|
|
return err
|
|
}
|
|
return tx.Create(&schemaMigration{Version: m.Version, Name: m.Name, AppliedAt: time.Now()}).Error
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("执行迁移 %d_%s 失败: %w", m.Version, m.Name, err)
|
|
}
|
|
slog.Info("数据库迁移已应用", "version", m.Version, "name", m.Name)
|
|
}
|
|
return nil
|
|
}
|