bbgo_origin/pkg/migrations/sqlite3/migration_api.go

88 lines
2.3 KiB
Go
Raw Normal View History

2021-02-17 09:28:05 +00:00
package sqlite3
import (
"fmt"
2022-04-26 10:48:27 +00:00
"log"
2021-02-17 09:28:05 +00:00
"runtime"
"strings"
2021-02-17 09:35:11 +00:00
"github.com/c9s/rockhopper"
2021-02-17 09:28:05 +00:00
)
var registeredGoMigrations map[int64]*rockhopper.Migration
2022-04-26 10:48:27 +00:00
func MergeMigrationsMap(ms map[int64]*rockhopper.Migration) {
for k, m := range ms {
if _, ok := registeredGoMigrations[k]; !ok {
registeredGoMigrations[k] = m
} else {
log.Printf("the migration key %d is duplicated: %+v", k, m)
}
}
}
func GetMigrationsMap() map[int64]*rockhopper.Migration {
return registeredGoMigrations
}
// SortedMigrations builds up the migration objects, sort them by timestamp and return as a slice
func SortedMigrations() rockhopper.MigrationSlice {
return Migrations()
}
// Migrations builds up the migration objects, sort them by timestamp and return as a slice
2021-02-17 09:35:11 +00:00
func Migrations() rockhopper.MigrationSlice {
var migrations = rockhopper.MigrationSlice{}
for _, migration := range registeredGoMigrations {
migrations = append(migrations, migration)
}
return migrations.SortAndConnect()
}
2022-04-26 10:48:27 +00:00
// AddMigration adds a migration with its runtime caller information
2021-02-17 09:28:05 +00:00
func AddMigration(up, down rockhopper.TransactionHandler) {
pc, filename, _, _ := runtime.Caller(1)
funcName := runtime.FuncForPC(pc).Name()
2022-04-26 10:48:27 +00:00
packageName := _parseFuncPackageName(funcName)
AddNamedMigration(packageName, filename, up, down)
}
// parseFuncPackageName parses the package name from a given runtime caller function name
func _parseFuncPackageName(funcName string) string {
2021-02-17 09:28:05 +00:00
lastSlash := strings.LastIndexByte(funcName, '/')
if lastSlash < 0 {
lastSlash = 0
}
2022-04-26 10:48:27 +00:00
2021-02-17 09:28:05 +00:00
lastDot := strings.LastIndexByte(funcName[lastSlash:], '.') + lastSlash
packageName := funcName[:lastDot]
2022-04-26 10:48:27 +00:00
return packageName
2021-02-17 09:28:05 +00:00
}
2022-04-26 10:48:27 +00:00
// AddNamedMigration adds a named migration to the registered go migration map
2021-02-17 09:28:05 +00:00
func AddNamedMigration(packageName, filename string, up, down rockhopper.TransactionHandler) {
if registeredGoMigrations == nil {
registeredGoMigrations = make(map[int64]*rockhopper.Migration)
}
v, _ := rockhopper.FileNumericComponent(filename)
migration := &rockhopper.Migration{
Package: packageName,
Registered: true,
Version: v,
UpFn: up,
DownFn: down,
Source: filename,
UseTx: true,
}
if existing, ok := registeredGoMigrations[v]; ok {
panic(fmt.Sprintf("failed to add migration %q: version conflicts with %q", filename, existing.Source))
}
registeredGoMigrations[v] = migration
}