diff options
author | 无闻 <u@gogs.io> | 2015-01-22 21:07:11 +0800 |
---|---|---|
committer | 无闻 <u@gogs.io> | 2015-01-22 21:07:11 +0800 |
commit | 61608f13a04d6fb7b3f947dc98294640f3d243ac (patch) | |
tree | 19a7172e1781ccbebe6e40051d0c06cf7f37e6e6 /models/migrations/migrations.go | |
parent | 161774d4fb61d1c2b28a90812b15d077312083f3 (diff) | |
parent | 4ef32454138a40c8b3cc5334c8980e71bd431825 (diff) |
Merge pull request #870 from phsmit/migrations
Create db migrations framework
Diffstat (limited to 'models/migrations/migrations.go')
-rw-r--r-- | models/migrations/migrations.go | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/models/migrations/migrations.go b/models/migrations/migrations.go new file mode 100644 index 00000000..3586e5d0 --- /dev/null +++ b/models/migrations/migrations.go @@ -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") +} |