2022-07-06 23:19:05 +02:00
|
|
|
package migrate
|
|
|
|
|
|
|
|
import (
|
|
|
|
"path/filepath"
|
|
|
|
"runtime"
|
|
|
|
"sort"
|
|
|
|
|
|
|
|
"github.com/pocketbase/dbx"
|
|
|
|
)
|
|
|
|
|
2022-11-26 09:05:52 +02:00
|
|
|
type Migration struct {
|
|
|
|
File string
|
|
|
|
Up func(db dbx.Builder) error
|
|
|
|
Down func(db dbx.Builder) error
|
2022-07-06 23:19:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// MigrationsList defines a list with migration definitions
|
|
|
|
type MigrationsList struct {
|
2022-11-26 09:05:52 +02:00
|
|
|
list []*Migration
|
2022-07-06 23:19:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Item returns a single migration from the list by its index.
|
2022-11-26 09:05:52 +02:00
|
|
|
func (l *MigrationsList) Item(index int) *Migration {
|
2022-07-06 23:19:05 +02:00
|
|
|
return l.list[index]
|
|
|
|
}
|
|
|
|
|
|
|
|
// Items returns the internal migrations list slice.
|
2022-11-26 09:05:52 +02:00
|
|
|
func (l *MigrationsList) Items() []*Migration {
|
2022-07-06 23:19:05 +02:00
|
|
|
return l.list
|
|
|
|
}
|
|
|
|
|
|
|
|
// Register adds new migration definition to the list.
|
|
|
|
//
|
|
|
|
// If `optFilename` is not provided, it will try to get the name from its .go file.
|
|
|
|
//
|
|
|
|
// The list will be sorted automatically based on the migrations file name.
|
|
|
|
func (l *MigrationsList) Register(
|
|
|
|
up func(db dbx.Builder) error,
|
|
|
|
down func(db dbx.Builder) error,
|
|
|
|
optFilename ...string,
|
|
|
|
) {
|
|
|
|
var file string
|
|
|
|
if len(optFilename) > 0 {
|
|
|
|
file = optFilename[0]
|
|
|
|
} else {
|
|
|
|
_, path, _, _ := runtime.Caller(1)
|
|
|
|
file = filepath.Base(path)
|
|
|
|
}
|
|
|
|
|
2022-11-26 09:05:52 +02:00
|
|
|
l.list = append(l.list, &Migration{
|
|
|
|
File: file,
|
|
|
|
Up: up,
|
|
|
|
Down: down,
|
2022-07-06 23:19:05 +02:00
|
|
|
})
|
|
|
|
|
|
|
|
sort.Slice(l.list, func(i int, j int) bool {
|
2022-11-26 09:05:52 +02:00
|
|
|
return l.list[i].File < l.list[j].File
|
2022-07-06 23:19:05 +02:00
|
|
|
})
|
|
|
|
}
|