migrations.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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) (err 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. if err = x.Sync(new(Collaboration)); err != nil {
  103. return fmt.Errorf("sync: %v", err)
  104. }
  105. 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")
  106. if err != nil {
  107. return err
  108. }
  109. sess := x.NewSession()
  110. defer sessionRelease(sess)
  111. if err = sess.Begin(); err != nil {
  112. return err
  113. }
  114. offset := strings.Split(time.Now().String(), " ")[2]
  115. for _, result := range results {
  116. mode := com.StrTo(result["mode"]).MustInt64()
  117. // Collaborators must have write access.
  118. if mode < 2 {
  119. continue
  120. }
  121. userID := com.StrTo(result["uid"]).MustInt64()
  122. repoRefName := string(result["repo"])
  123. var created time.Time
  124. switch {
  125. case setting.UseSQLite3:
  126. created, _ = time.Parse(time.RFC3339, string(result["created"]))
  127. case setting.UseMySQL:
  128. created, _ = time.Parse("2006-01-02 15:04:05-0700", string(result["created"])+offset)
  129. case setting.UsePostgreSQL:
  130. created, _ = time.Parse("2006-01-02T15:04:05Z-0700", string(result["created"])+offset)
  131. }
  132. // find owner of repository
  133. parts := strings.SplitN(repoRefName, "/", 2)
  134. ownerName := parts[0]
  135. repoName := parts[1]
  136. 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)
  137. if err != nil {
  138. return err
  139. }
  140. if len(results) < 1 {
  141. continue
  142. }
  143. ownerID := com.StrTo(results[0]["uid"]).MustInt64()
  144. if ownerID == userID {
  145. continue
  146. }
  147. // test if user is member of owning organization
  148. isMember := false
  149. for _, member := range results {
  150. memberID := com.StrTo(member["memberid"]).MustInt64()
  151. // We can skip all cases that a user is member of the owning organization
  152. if memberID == userID {
  153. isMember = true
  154. }
  155. }
  156. if isMember {
  157. continue
  158. }
  159. results, err = sess.Query("SELECT id FROM `repository` WHERE owner_id=? AND lower_name=?", ownerID, repoName)
  160. if err != nil {
  161. return err
  162. } else if len(results) < 1 {
  163. continue
  164. }
  165. collaboration := &Collaboration{
  166. UserID: userID,
  167. RepoID: com.StrTo(results[0]["id"]).MustInt64(),
  168. }
  169. has, err := sess.Get(collaboration)
  170. if err != nil {
  171. return err
  172. } else if has {
  173. continue
  174. }
  175. collaboration.Created = created
  176. if _, err = sess.InsertOne(collaboration); err != nil {
  177. return err
  178. }
  179. }
  180. return sess.Commit()
  181. }
  182. func accessRefactor(x *xorm.Engine) (err error) {
  183. type (
  184. AccessMode int
  185. Access struct {
  186. ID int64 `xorm:"pk autoincr"`
  187. UserName string
  188. RepoName string
  189. UserID int64 `xorm:"UNIQUE(s)"`
  190. RepoID int64 `xorm:"UNIQUE(s)"`
  191. Mode AccessMode
  192. }
  193. )
  194. var rawSQL string
  195. switch {
  196. case setting.UseSQLite3, setting.UsePostgreSQL:
  197. rawSQL = "DROP INDEX IF EXISTS `UQE_access_S`"
  198. case setting.UseMySQL:
  199. rawSQL = "DROP INDEX `UQE_access_S` ON `access`"
  200. }
  201. if _, err = x.Exec(rawSQL); err != nil &&
  202. !strings.Contains(err.Error(), "check that column/key exists") {
  203. return fmt.Errorf("drop index: %v", err)
  204. }
  205. sess := x.NewSession()
  206. defer sessionRelease(sess)
  207. if err = sess.Begin(); err != nil {
  208. return err
  209. }
  210. if err = sess.Sync2(new(Access)); err != nil {
  211. return fmt.Errorf("sync: %v", err)
  212. }
  213. accesses := make([]*Access, 0, 50)
  214. if err = sess.Iterate(new(Access), func(idx int, bean interface{}) error {
  215. a := bean.(*Access)
  216. // Update username to user ID.
  217. users, err := sess.Query("SELECT `id` FROM `user` WHERE lower_name=?", a.UserName)
  218. if err != nil {
  219. return fmt.Errorf("query user: %v", err)
  220. } else if len(users) < 1 {
  221. return nil
  222. }
  223. a.UserID = com.StrTo(users[0]["id"]).MustInt64()
  224. // Update repository name(username/reponame) to repository ID.
  225. names := strings.Split(a.RepoName, "/")
  226. ownerName := names[0]
  227. repoName := names[1]
  228. // Check if user is the owner of the repository.
  229. ownerID := a.UserID
  230. if ownerName != a.UserName {
  231. users, err := sess.Query("SELECT `id` FROM `user` WHERE lower_name=?", ownerName)
  232. if err != nil {
  233. return fmt.Errorf("query owner: %v", err)
  234. } else if len(users) < 1 {
  235. return nil
  236. }
  237. ownerID = com.StrTo(users[0]["id"]).MustInt64()
  238. }
  239. repos, err := sess.Query("SELECT `id` FROM `repository` WHERE owner_id=? AND lower_name=?", ownerID, repoName)
  240. if err != nil {
  241. return fmt.Errorf("query repository: %v", err)
  242. } else if len(repos) < 1 {
  243. return nil
  244. }
  245. a.RepoID = com.StrTo(repos[0]["id"]).MustInt64()
  246. accesses = append(accesses, a)
  247. return nil
  248. }); err != nil {
  249. return fmt.Errorf("iterate: %v", err)
  250. }
  251. for i := range accesses {
  252. if _, err = sess.Id(accesses[i].ID).Update(accesses[i]); err != nil {
  253. return fmt.Errorf("update: %v", err)
  254. }
  255. }
  256. return sess.Commit()
  257. }