41 lines
1.1 KiB
Go
41 lines
1.1 KiB
Go
// Package migration owns the application database migration runner. Schema
|
|
// steps remain in internal/data because they need that package's private POs;
|
|
// this package contains only the reusable versioning mechanism.
|
|
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
|
|
}
|