migrations.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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 sessionRelease(sess *xorm.Session) {
  90. if !sess.IsCommitedOrRollbacked {
  91. sess.Rollback()
  92. }
  93. sess.Close()
  94. }
  95. func accessToCollaboration(x *xorm.Engine) error {
  96. type Collaboration struct {
  97. ID int64 `xorm:"pk autoincr"`
  98. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  99. UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  100. Created time.Time
  101. }
  102. x.Sync(new(Collaboration))
  103. 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")
  104. if err != nil {
  105. return err
  106. }
  107. sess := x.NewSession()
  108. defer sessionRelease(sess)
  109. if err = sess.Begin(); err != nil {
  110. return err
  111. }
  112. offset := strings.Split(time.Now().String(), " ")[2]
  113. for _, result := range results {
  114. mode := com.StrTo(result["mode"]).MustInt64()
  115. // Collaborators must have write access.
  116. if mode < 2 {
  117. continue
  118. }
  119. userID := com.StrTo(result["uid"]).MustInt64()
  120. repoRefName := string(result["repo"])
  121. var created time.Time
  122. switch {
  123. case setting.UseSQLite3:
  124. created, _ = time.Parse(time.RFC3339, string(result["created"]))
  125. case setting.UseMySQL:
  126. created, _ = time.Parse("2006-01-02 15:04:05-0700", string(result["created"])+offset)
  127. case setting.UsePostgreSQL:
  128. created, _ = time.Parse("2006-01-02T15:04:05Z-0700", string(result["created"])+offset)
  129. }
  130. // find owner of repository
  131. parts := strings.SplitN(repoRefName, "/", 2)
  132. ownerName := parts[0]
  133. repoName := parts[1]
  134. 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)
  135. if err != nil {
  136. return err
  137. }
  138. if len(results) < 1 {
  139. continue
  140. }
  141. ownerID := com.StrTo(results[0]["uid"]).MustInt64()
  142. if ownerID == userID {
  143. continue
  144. }
  145. // test if user is member of owning organization
  146. isMember := false
  147. for _, member := range results {
  148. memberID := com.StrTo(member["memberid"]).MustInt64()
  149. // We can skip all cases that a user is member of the owning organization
  150. if memberID == userID {
  151. isMember = true
  152. }
  153. }
  154. if isMember {
  155. continue
  156. }
  157. results, err = sess.Query("SELECT id FROM `repository` WHERE owner_id=? AND lower_name=?", ownerID, repoName)
  158. if err != nil {
  159. return err
  160. } else if len(results) < 1 {
  161. continue
  162. }
  163. collaboration := &Collaboration{
  164. UserID: userID,
  165. RepoID: com.StrTo(results[0]["id"]).MustInt64(),
  166. }
  167. has, err := sess.Get(collaboration)
  168. if err != nil {
  169. return err
  170. } else if has {
  171. continue
  172. }
  173. collaboration.Created = created
  174. if _, err = sess.InsertOne(collaboration); err != nil {
  175. return err
  176. }
  177. }
  178. return sess.Commit()
  179. }
  180. func accessRefactor(x *xorm.Engine) error {
  181. //TODO
  182. return nil
  183. }