migrations.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package migrations
  5. import (
  6. "fmt"
  7. "strings"
  8. "time"
  9. "github.com/Unknwon/com"
  10. "github.com/go-xorm/xorm"
  11. "github.com/gogits/gogs/modules/log"
  12. "github.com/gogits/gogs/modules/setting"
  13. )
  14. const _MIN_DB_VER = 0
  15. type Migration interface {
  16. Description() string
  17. Migrate(*xorm.Engine) error
  18. }
  19. type migration struct {
  20. description string
  21. migrate func(*xorm.Engine) error
  22. }
  23. func NewMigration(desc string, fn func(*xorm.Engine) error) Migration {
  24. return &migration{desc, fn}
  25. }
  26. func (m *migration) Description() string {
  27. return m.description
  28. }
  29. func (m *migration) Migrate(x *xorm.Engine) error {
  30. return m.migrate(x)
  31. }
  32. // The version table. Should have only one row with id==1
  33. type Version struct {
  34. Id int64
  35. Version int64
  36. }
  37. // This is a sequence of migrations. Add new migrations to the bottom of the list.
  38. // If you want to "retire" a migration, remove it from the top of the list and
  39. // update _MIN_VER_DB accordingly
  40. var migrations = []Migration{
  41. NewMigration("generate collaboration from access", accessToCollaboration), // V0 -> V1
  42. NewMigration("refactor access table to use id's", accessRefactor), // V1 -> V2
  43. }
  44. // Migrate database to current version
  45. func Migrate(x *xorm.Engine) error {
  46. if err := x.Sync(new(Version)); err != nil {
  47. return fmt.Errorf("sync: %v", err)
  48. }
  49. currentVersion := &Version{Id: 1}
  50. has, err := x.Get(currentVersion)
  51. if err != nil {
  52. return fmt.Errorf("get: %v", err)
  53. } else if !has {
  54. // If the user table does not exist it is a fresh installation and we
  55. // can skip all migrations
  56. needsMigration, err := x.IsTableExist("user")
  57. if err != nil {
  58. return err
  59. }
  60. if needsMigration {
  61. isEmpty, err := x.IsTableEmpty("user")
  62. if err != nil {
  63. return err
  64. }
  65. // If the user table is empty it is a fresh installation and we can
  66. // skip all migrations
  67. needsMigration = !isEmpty
  68. }
  69. if !needsMigration {
  70. currentVersion.Version = int64(_MIN_DB_VER + len(migrations))
  71. }
  72. if _, err = x.InsertOne(currentVersion); err != nil {
  73. return fmt.Errorf("insert: %v", err)
  74. }
  75. }
  76. v := currentVersion.Version
  77. for i, m := range migrations[v-_MIN_DB_VER:] {
  78. log.Info("Migration: %s", m.Description())
  79. if err = m.Migrate(x); err != nil {
  80. return fmt.Errorf("do migrate: %v", err)
  81. }
  82. currentVersion.Version = v + int64(i) + 1
  83. if _, err = x.Id(1).Update(currentVersion); err != nil {
  84. return err
  85. }
  86. }
  87. return nil
  88. }
  89. func accessToCollaboration(x *xorm.Engine) error {
  90. type Collaboration struct {
  91. ID int64 `xorm:"pk autoincr"`
  92. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  93. UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  94. Created time.Time
  95. }
  96. x.Sync(new(Collaboration))
  97. results, err := x.Query("SELECT u.id AS `uid`, a.repo_name AS `repo`, a.mode AS `mode`, a.created as `created` FROM `access` a JOIN `user` u ON a.user_name=u.lower_name")
  98. if err != nil {
  99. return err
  100. }
  101. sess := x.NewSession()
  102. defer func() {
  103. if sess.IsCommitedOrRollbacked {
  104. sess.Rollback()
  105. }
  106. sess.Close()
  107. }()
  108. if err = sess.Begin(); err != nil {
  109. return err
  110. }
  111. offset := strings.Split(time.Now().String(), " ")[2]
  112. for _, result := range results {
  113. mode := com.StrTo(result["mode"]).MustInt64()
  114. // Collaborators must have write access.
  115. if mode < 2 {
  116. continue
  117. }
  118. userID := com.StrTo(result["uid"]).MustInt64()
  119. repoRefName := string(result["repo"])
  120. var created time.Time
  121. switch {
  122. case setting.UseSQLite3:
  123. created, _ = time.Parse(time.RFC3339, string(result["created"]))
  124. case setting.UseMySQL:
  125. created, _ = time.Parse("2006-01-02 15:04:05-0700", string(result["created"])+offset)
  126. case setting.UsePostgreSQL:
  127. created, _ = time.Parse("2006-01-02T15:04:05Z-0700", string(result["created"])+offset)
  128. }
  129. // find owner of repository
  130. parts := strings.SplitN(repoRefName, "/", 2)
  131. ownerName := parts[0]
  132. repoName := parts[1]
  133. results, err := sess.Query("SELECT u.id as `uid`, ou.uid as `memberid` FROM `user` u LEFT JOIN org_user ou ON ou.org_id=u.id WHERE u.lower_name=?", ownerName)
  134. if err != nil {
  135. return err
  136. }
  137. if len(results) < 1 {
  138. continue
  139. }
  140. ownerID := com.StrTo(results[0]["uid"]).MustInt64()
  141. if ownerID == userID {
  142. continue
  143. }
  144. // test if user is member of owning organization
  145. isMember := false
  146. for _, member := range results {
  147. memberID := com.StrTo(member["memberid"]).MustInt64()
  148. // We can skip all cases that a user is member of the owning organization
  149. if memberID == userID {
  150. isMember = true
  151. }
  152. }
  153. if isMember {
  154. continue
  155. }
  156. results, err = sess.Query("SELECT id FROM `repository` WHERE owner_id=? AND lower_name=?", ownerID, repoName)
  157. if err != nil {
  158. return err
  159. } else if len(results) < 1 {
  160. continue
  161. }
  162. collaboration := &Collaboration{
  163. UserID: userID,
  164. RepoID: com.StrTo(results[0]["id"]).MustInt64(),
  165. }
  166. has, err := sess.Get(collaboration)
  167. if err != nil {
  168. return err
  169. } else if has {
  170. continue
  171. }
  172. collaboration.Created = created
  173. if _, err = sess.InsertOne(collaboration); err != nil {
  174. return err
  175. }
  176. }
  177. return sess.Commit()
  178. }
  179. func accessRefactor(x *xorm.Engine) error {
  180. //TODO
  181. return nil
  182. }