migrations.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. if err := x.Sync(new(Version)); err != nil {
  18. return err
  19. }
  20. currentVersion := &Version{Id: 1}
  21. has, err := x.Get(currentVersion)
  22. if err != nil {
  23. return err
  24. } else if !has {
  25. if _, err = x.InsertOne(currentVersion); err != nil {
  26. return err
  27. }
  28. }
  29. v := currentVersion.Version
  30. for i, migration := range migrations[v:] {
  31. if err = migration(x); err != nil {
  32. return err
  33. }
  34. currentVersion.Version = v + int64(i) + 1
  35. if _, err = x.Id(1).Update(currentVersion); err != nil {
  36. return err
  37. }
  38. }
  39. return nil
  40. }
  41. func expiredMigration(x *xorm.Engine) error {
  42. return errors.New("You are migrating from a too old gogs version")
  43. }