migrations.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package migrations
  2. import (
  3. "errors"
  4. "github.com/go-xorm/xorm"
  5. )
  6. type migration func(*xorm.Engine) error
  7. // The version table. Should have only one row with id==1
  8. type Version struct {
  9. Id int64
  10. Version int64
  11. }
  12. // This is a sequence of migrations. Add new migrations to the bottom of the list.
  13. // If you want to "retire" a migration, replace it with "expiredMigration"
  14. var migrations = []migration{}
  15. // Migrate database to current version
  16. func Migrate(x *xorm.Engine) error {
  17. x.Sync(new(Version))
  18. currentVersion := &Version{Id: 1}
  19. has, err := x.Get(currentVersion)
  20. if err != nil {
  21. return err
  22. } else if !has {
  23. if _, err = x.InsertOne(currentVersion); err != nil {
  24. return err
  25. }
  26. }
  27. v := currentVersion.Version
  28. for i, migration := range migrations[v:] {
  29. if err = migration(x); err != nil {
  30. return err
  31. }
  32. currentVersion.Version = v + int64(i) + 1
  33. x.Id(1).Update(currentVersion)
  34. }
  35. return nil
  36. }
  37. func expiredMigration(x *xorm.Engine) error {
  38. return errors.New("You are migrating from a too old gogs version")
  39. }