]> source.dussan.org Git - gitea.git/commitdiff
Create db migrations framework
authorPeter Smit <peter@smitmail.eu>
Thu, 22 Jan 2015 12:49:52 +0000 (14:49 +0200)
committerPeter Smit <peter@smitmail.eu>
Thu, 22 Jan 2015 12:52:58 +0000 (14:52 +0200)
models/migrations/migrations.go [new file with mode: 0644]
models/models.go

diff --git a/models/migrations/migrations.go b/models/migrations/migrations.go
new file mode 100644 (file)
index 0000000..0b52708
--- /dev/null
@@ -0,0 +1,47 @@
+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 `xorm:"pk"`
+       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 {
+       x.Sync(new(Version))
+
+       currentVersion := &Version{Id: 1}
+       has, err := x.Get(currentVersion)
+       if err != nil {
+               return err
+       }
+       if !has {
+               _, err = x.InsertOne(currentVersion)
+       }
+
+       v := currentVersion.Version
+
+       for i, migration := range migrations[v:] {
+               if err = migration(x); err != nil {
+                       return err
+               }
+               currentVersion.Version = v + int64(i) + 1
+               x.Id(1).Update(currentVersion)
+       }
+       return nil
+}
+
+func expiredMigration(x *xorm.Engine) error {
+       return errors.New("You are migrating from a too old gogs version")
+}
index cf2124417af94b84bdfa0d5dd8e047188d9ba6dc..55e7bf582285f95901b694bab9461b1a60e71c2f 100644 (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)
        }