0
0
Fork 0
mirror of https://github.com/go-gitea/gitea synced 2024-11-26 15:02:56 +01:00

Merge pull request #870 from phsmit/migrations

Create db migrations framework
This commit is contained in:
无闻 2015-01-22 21:07:11 +08:00
commit 61608f13a0
2 changed files with 59 additions and 0 deletions

View file

@ -0,0 +1,53 @@
package migrations
import (
"errors"
"github.com/go-xorm/xorm"
)
type migration func(*xorm.Engine) error
// The version table. Should have only one row with id==1
type Version struct {
Id int64
Version int64
}
// This is a sequence of migrations. Add new migrations to the bottom of the list.
// If you want to "retire" a migration, replace it with "expiredMigration"
var migrations = []migration{}
// Migrate database to current version
func Migrate(x *xorm.Engine) error {
if err := x.Sync(new(Version)); err != nil {
return err
}
currentVersion := &Version{Id: 1}
has, err := x.Get(currentVersion)
if err != nil {
return err
} else if !has {
if _, err = x.InsertOne(currentVersion); err != nil {
return err
}
}
v := currentVersion.Version
for i, migration := range migrations[v:] {
if err = migration(x); err != nil {
return err
}
currentVersion.Version = v + int64(i) + 1
if _, err = x.Id(1).Update(currentVersion); err != nil {
return err
}
}
return nil
}
func expiredMigration(x *xorm.Engine) error {
return errors.New("You are migrating from a too old gogs version")
}

View file

@ -15,6 +15,7 @@ import (
"github.com/go-xorm/xorm"
_ "github.com/lib/pq"
"github.com/gogits/gogs/models/migrations"
"github.com/gogits/gogs/modules/setting"
)
@ -131,6 +132,11 @@ func NewEngine() (err error) {
if err = SetEngine(); err != nil {
return err
}
if err = migrations.Migrate(x); err != nil {
return err
}
if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
return fmt.Errorf("sync database struct error: %v\n", err)
}