Feat: migration DB support custom upgrade scripts
This commit is contained in:
37
models/scripts/invoker/invoker.go
Normal file
37
models/scripts/invoker/invoker.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package invoker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/cloudreve/Cloudreve/v3/pkg/util"
|
||||
)
|
||||
|
||||
type DBScript interface {
|
||||
Run(ctx context.Context)
|
||||
}
|
||||
|
||||
var availableScripts = make(map[string]DBScript)
|
||||
|
||||
func RunDBScript(name string, ctx context.Context) error {
|
||||
if script, ok := availableScripts[name]; ok {
|
||||
util.Log().Info("开始执行数据库脚本 [%s]", name)
|
||||
script.Run(ctx)
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf("数据库脚本 [%s] 不存在", name)
|
||||
}
|
||||
|
||||
func Register(name string, script DBScript) {
|
||||
availableScripts[name] = script
|
||||
}
|
||||
|
||||
func ListPrefix(prefix string) []string {
|
||||
var scripts []string
|
||||
for name := range availableScripts {
|
||||
if name[:len(prefix)] == prefix {
|
||||
scripts = append(scripts, name)
|
||||
}
|
||||
}
|
||||
return scripts
|
||||
}
|
||||
60
models/scripts/invoker/invoker_test.go
Normal file
60
models/scripts/invoker/invoker_test.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package invoker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
model "github.com/cloudreve/Cloudreve/v3/models"
|
||||
"github.com/jinzhu/gorm"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var mock sqlmock.Sqlmock
|
||||
var mockDB *gorm.DB
|
||||
|
||||
type TestScript int
|
||||
|
||||
func (script TestScript) Run(ctx context.Context) {
|
||||
|
||||
}
|
||||
|
||||
// TestMain 初始化数据库Mock
|
||||
func TestMain(m *testing.M) {
|
||||
var db *sql.DB
|
||||
var err error
|
||||
db, mock, err = sqlmock.New()
|
||||
if err != nil {
|
||||
panic("An error was not expected when opening a stub database connection")
|
||||
}
|
||||
model.DB, _ = gorm.Open("mysql", db)
|
||||
mockDB = model.DB
|
||||
defer db.Close()
|
||||
m.Run()
|
||||
}
|
||||
|
||||
func TestRunDBScript(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
Register("test", TestScript(0))
|
||||
|
||||
// 不存在
|
||||
{
|
||||
asserts.Error(RunDBScript("else", context.Background()))
|
||||
}
|
||||
|
||||
// 存在
|
||||
{
|
||||
asserts.NoError(RunDBScript("test", context.Background()))
|
||||
}
|
||||
}
|
||||
|
||||
func TestListPrefix(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
Register("U1", TestScript(0))
|
||||
Register("U2", TestScript(0))
|
||||
Register("U3", TestScript(0))
|
||||
Register("P1", TestScript(0))
|
||||
|
||||
res := ListPrefix("U")
|
||||
asserts.Len(res, 3)
|
||||
}
|
||||
Reference in New Issue
Block a user