migrations.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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. }
  43. // Migrate database to current version
  44. func Migrate(x *xorm.Engine) error {
  45. if err := x.Sync(new(Version)); err != nil {
  46. return fmt.Errorf("sync: %v", err)
  47. }
  48. currentVersion := &Version{Id: 1}
  49. has, err := x.Get(currentVersion)
  50. if err != nil {
  51. return fmt.Errorf("get: %v", err)
  52. } else if !has {
  53. // If the user table does not exist it is a fresh installation and we
  54. // can skip all migrations
  55. needsMigration, err := x.IsTableExist("user")
  56. if err != nil {
  57. return err
  58. }
  59. if needsMigration {
  60. isEmpty, err := x.IsTableEmpty("user")
  61. if err != nil {
  62. return err
  63. }
  64. // If the user table is empty it is a fresh installation and we can
  65. // skip all migrations
  66. needsMigration = !isEmpty
  67. }
  68. if !needsMigration {
  69. currentVersion.Version = int64(_MIN_DB_VER + len(migrations))
  70. }
  71. if _, err = x.InsertOne(currentVersion); err != nil {
  72. return fmt.Errorf("insert: %v", err)
  73. }
  74. }
  75. v := currentVersion.Version
  76. for i, m := range migrations[v-_MIN_DB_VER:] {
  77. log.Info("Migration: %s", m.Description())
  78. if err = m.Migrate(x); err != nil {
  79. return fmt.Errorf("do migrate: %v", err)
  80. }
  81. currentVersion.Version = v + int64(i) + 1
  82. if _, err = x.Id(1).Update(currentVersion); err != nil {
  83. return err
  84. }
  85. }
  86. return nil
  87. }
  88. func accessToCollaboration(x *xorm.Engine) error {
  89. type Collaboration struct {
  90. ID int64 `xorm:"pk autoincr"`
  91. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  92. UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  93. Created time.Time
  94. }
  95. x.Sync(new(Collaboration))
  96. 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")
  97. if err != nil {
  98. return err
  99. }
  100. sess := x.NewSession()
  101. defer func() {
  102. if sess.IsCommitedOrRollbacked {
  103. sess.Rollback()
  104. }
  105. sess.Close()
  106. }()
  107. if err = sess.Begin(); err != nil {
  108. return err
  109. }
  110. offset := strings.Split(time.Now().String(), " ")[2]
  111. for _, result := range results {
  112. mode := com.StrTo(result["mode"]).MustInt64()
  113. // Collaborators must have write access.
  114. if mode < 2 {
  115. continue
  116. }
  117. userID := com.StrTo(result["uid"]).MustInt64()
  118. repoRefName := string(result["repo"])
  119. var created time.Time
  120. switch {
  121. case setting.UseSQLite3:
  122. created, _ = time.Parse(time.RFC3339, string(result["created"]))
  123. case setting.UseMySQL:
  124. created, _ = time.Parse("2006-01-02 15:04:05-0700", string(result["created"])+offset)
  125. case setting.UsePostgreSQL:
  126. created, _ = time.Parse("2006-01-02T15:04:05Z-0700", string(result["created"])+offset)
  127. }
  128. // find owner of repository
  129. parts := strings.SplitN(repoRefName, "/", 2)
  130. ownerName := parts[0]
  131. repoName := parts[1]
  132. 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)
  133. if err != nil {
  134. return err
  135. }
  136. if len(results) < 1 {
  137. continue
  138. }
  139. ownerID := com.StrTo(results[0]["uid"]).MustInt64()
  140. if ownerID == userID {
  141. continue
  142. }
  143. // test if user is member of owning organization
  144. isMember := false
  145. for _, member := range results {
  146. memberID := com.StrTo(member["memberid"]).MustInt64()
  147. // We can skip all cases that a user is member of the owning organization
  148. if memberID == userID {
  149. isMember = true
  150. }
  151. }
  152. if isMember {
  153. continue
  154. }
  155. results, err = sess.Query("SELECT id FROM `repository` WHERE owner_id=? AND lower_name=?", ownerID, repoName)
  156. if err != nil {
  157. return err
  158. } else if len(results) < 1 {
  159. continue
  160. }
  161. collaboration := &Collaboration{
  162. UserID: userID,
  163. RepoID: com.StrTo(results[0]["id"]).MustInt64(),
  164. }
  165. has, err := sess.Get(collaboration)
  166. if err != nil {
  167. return err
  168. } else if has {
  169. continue
  170. }
  171. collaboration.Created = created
  172. if _, err = sess.InsertOne(collaboration); err != nil {
  173. return err
  174. }
  175. }
  176. return sess.Commit()
  177. }