1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- package migration
- import (
- "log"
- "path/filepath"
- "sort"
- "strconv"
- "sync"
- "github.com/spf13/cast"
- "gorm.io/gorm"
- )
- var Migrate = &Migration{
- version: make(map[int]func(db *gorm.DB, version string) error),
- }
- type Migration struct {
- db *gorm.DB
- version map[int]func(db *gorm.DB, version string) error
- mutex sync.Mutex
- }
- func (e *Migration) GetDb() *gorm.DB {
- return e.db
- }
- func (e *Migration) SetDb(db *gorm.DB) {
- e.db = db
- }
- func (e *Migration) SetVersion(k int, f func(db *gorm.DB, version string) error) {
- e.mutex.Lock()
- defer e.mutex.Unlock()
- e.version[k] = f
- }
- func (e *Migration) Migrate() {
- versions := make([]int, 0)
- for k := range e.version {
- versions = append(versions, k)
- }
- if !sort.IntsAreSorted(versions) {
- sort.Ints(versions)
- }
- var err error
- var count int64
- for _, v := range versions {
- err = e.db.Debug().Table("sys_migration").Where("version = ?", v).Count(&count).Error
- if err != nil {
- log.Fatalln(err)
- }
- if count > 0 {
- log.Println(count)
- count = 0
- continue
- }
- err = (e.version[v])(e.db.Debug(), strconv.Itoa(v))
- if err != nil {
- log.Fatalln(err)
- }
- }
- }
- func GetFilename(s string) int {
- s = filepath.Base(s)
- return cast.ToInt(s[:13])
- }
|