41 lines
1.0 KiB
Go
41 lines
1.0 KiB
Go
// Package migration owns the application database migration runner. Each data
|
|
// module declares its own steps; the root data package only orders and runs
|
|
// them.
|
|
package migration
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"github.com/go-gormigrate/gormigrate/v2"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
const TableName = "sys_schema_migrations"
|
|
|
|
type Step struct {
|
|
ID string
|
|
Migrate func(*gorm.DB) error
|
|
}
|
|
|
|
func Run(db *gorm.DB, steps []Step) error {
|
|
if db == nil {
|
|
return fmt.Errorf("database is nil")
|
|
}
|
|
migrations := make([]*gormigrate.Migration, 0, len(steps))
|
|
for _, step := range steps {
|
|
current := step
|
|
migrations = append(migrations, &gormigrate.Migration{ID: current.ID, Migrate: current.Migrate})
|
|
}
|
|
manager := gormigrate.New(db, &gormigrate.Options{
|
|
TableName: TableName,
|
|
IDColumnName: "id",
|
|
IDColumnSize: 255,
|
|
UseTransaction: false,
|
|
ValidateUnknownMigrations: true,
|
|
}, migrations)
|
|
if err := manager.Migrate(); err != nil {
|
|
return fmt.Errorf("apply database migrations: %w", err)
|
|
}
|
|
return nil
|
|
}
|