migrations.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. "bytes"
  7. "encoding/json"
  8. "fmt"
  9. "io/ioutil"
  10. "os"
  11. "path"
  12. "path/filepath"
  13. "strings"
  14. "github.com/Unknwon/com"
  15. "github.com/go-xorm/xorm"
  16. "gopkg.in/ini.v1"
  17. "github.com/gogits/gogs/modules/log"
  18. "github.com/gogits/gogs/modules/setting"
  19. gouuid "github.com/gogits/gogs/modules/uuid"
  20. )
  21. const _MIN_DB_VER = 4
  22. type Migration interface {
  23. Description() string
  24. Migrate(*xorm.Engine) error
  25. }
  26. type migration struct {
  27. description string
  28. migrate func(*xorm.Engine) error
  29. }
  30. func NewMigration(desc string, fn func(*xorm.Engine) error) Migration {
  31. return &migration{desc, fn}
  32. }
  33. func (m *migration) Description() string {
  34. return m.description
  35. }
  36. func (m *migration) Migrate(x *xorm.Engine) error {
  37. return m.migrate(x)
  38. }
  39. // The version table. Should have only one row with id==1
  40. type Version struct {
  41. Id int64
  42. Version int64
  43. }
  44. // This is a sequence of migrations. Add new migrations to the bottom of the list.
  45. // If you want to "retire" a migration, remove it from the top of the list and
  46. // update _MIN_VER_DB accordingly
  47. var migrations = []Migration{
  48. NewMigration("fix locale file load panic", fixLocaleFileLoadPanic), // V4 -> V5:v0.6.0
  49. NewMigration("trim action compare URL prefix", trimCommitActionAppUrlPrefix), // V5 -> V6:v0.6.3
  50. NewMigration("generate issue-label from issue", issueToIssueLabel), // V6 -> V7:v0.6.4
  51. NewMigration("refactor attachment table", attachmentRefactor), // V7 -> V8:v0.6.4
  52. NewMigration("rename pull request fields", renamePullRequestFields), // V8 -> V9:v0.6.16
  53. NewMigration("clean up migrate repo info", cleanUpMigrateRepoInfo), // V9 -> V10:v0.6.20
  54. }
  55. // Migrate database to current version
  56. func Migrate(x *xorm.Engine) error {
  57. if err := x.Sync(new(Version)); err != nil {
  58. return fmt.Errorf("sync: %v", err)
  59. }
  60. currentVersion := &Version{Id: 1}
  61. has, err := x.Get(currentVersion)
  62. if err != nil {
  63. return fmt.Errorf("get: %v", err)
  64. } else if !has {
  65. // If the version record does not exist we think
  66. // it is a fresh installation and we can skip all migrations.
  67. currentVersion.Version = int64(_MIN_DB_VER + len(migrations))
  68. if _, err = x.InsertOne(currentVersion); err != nil {
  69. return fmt.Errorf("insert: %v", err)
  70. }
  71. }
  72. v := currentVersion.Version
  73. if _MIN_DB_VER > v {
  74. log.Fatal(4, `Gogs no longer supports auto-migration from your previously installed version.
  75. Please try to upgrade to a lower version (>= v0.6.0) first, then upgrade to current version.`)
  76. return nil
  77. }
  78. if int(v-_MIN_DB_VER) > len(migrations) {
  79. // User downgraded Gogs.
  80. currentVersion.Version = int64(len(migrations) + _MIN_DB_VER)
  81. _, err = x.Id(1).Update(currentVersion)
  82. return err
  83. }
  84. for i, m := range migrations[v-_MIN_DB_VER:] {
  85. log.Info("Migration: %s", m.Description())
  86. if err = m.Migrate(x); err != nil {
  87. return fmt.Errorf("do migrate: %v", err)
  88. }
  89. currentVersion.Version = v + int64(i) + 1
  90. if _, err = x.Id(1).Update(currentVersion); err != nil {
  91. return err
  92. }
  93. }
  94. return nil
  95. }
  96. func sessionRelease(sess *xorm.Session) {
  97. if !sess.IsCommitedOrRollbacked {
  98. sess.Rollback()
  99. }
  100. sess.Close()
  101. }
  102. func fixLocaleFileLoadPanic(_ *xorm.Engine) error {
  103. cfg, err := ini.Load(setting.CustomConf)
  104. if err != nil {
  105. return fmt.Errorf("load custom config: %v", err)
  106. }
  107. cfg.DeleteSection("i18n")
  108. if err = cfg.SaveTo(setting.CustomConf); err != nil {
  109. return fmt.Errorf("save custom config: %v", err)
  110. }
  111. setting.Langs = strings.Split(strings.Replace(strings.Join(setting.Langs, ","), "fr-CA", "fr-FR", 1), ",")
  112. return nil
  113. }
  114. func trimCommitActionAppUrlPrefix(x *xorm.Engine) error {
  115. type PushCommit struct {
  116. Sha1 string
  117. Message string
  118. AuthorEmail string
  119. AuthorName string
  120. }
  121. type PushCommits struct {
  122. Len int
  123. Commits []*PushCommit
  124. CompareUrl string
  125. }
  126. type Action struct {
  127. ID int64 `xorm:"pk autoincr"`
  128. Content string `xorm:"TEXT"`
  129. }
  130. results, err := x.Query("SELECT `id`,`content` FROM `action` WHERE `op_type`=?", 5)
  131. if err != nil {
  132. return fmt.Errorf("select commit actions: %v", err)
  133. }
  134. sess := x.NewSession()
  135. defer sessionRelease(sess)
  136. if err = sess.Begin(); err != nil {
  137. return err
  138. }
  139. var pushCommits *PushCommits
  140. for _, action := range results {
  141. actID := com.StrTo(string(action["id"])).MustInt64()
  142. if actID == 0 {
  143. continue
  144. }
  145. pushCommits = new(PushCommits)
  146. if err = json.Unmarshal(action["content"], pushCommits); err != nil {
  147. return fmt.Errorf("unmarshal action content[%d]: %v", actID, err)
  148. }
  149. infos := strings.Split(pushCommits.CompareUrl, "/")
  150. if len(infos) <= 4 {
  151. continue
  152. }
  153. pushCommits.CompareUrl = strings.Join(infos[len(infos)-4:], "/")
  154. p, err := json.Marshal(pushCommits)
  155. if err != nil {
  156. return fmt.Errorf("marshal action content[%d]: %v", actID, err)
  157. }
  158. if _, err = sess.Id(actID).Update(&Action{
  159. Content: string(p),
  160. }); err != nil {
  161. return fmt.Errorf("update action[%d]: %v", actID, err)
  162. }
  163. }
  164. return sess.Commit()
  165. }
  166. func issueToIssueLabel(x *xorm.Engine) error {
  167. type IssueLabel struct {
  168. ID int64 `xorm:"pk autoincr"`
  169. IssueID int64 `xorm:"UNIQUE(s)"`
  170. LabelID int64 `xorm:"UNIQUE(s)"`
  171. }
  172. issueLabels := make([]*IssueLabel, 0, 50)
  173. results, err := x.Query("SELECT `id`,`label_ids` FROM `issue`")
  174. if err != nil {
  175. if strings.Contains(err.Error(), "no such column") ||
  176. strings.Contains(err.Error(), "Unknown column") {
  177. return nil
  178. }
  179. return fmt.Errorf("select issues: %v", err)
  180. }
  181. for _, issue := range results {
  182. issueID := com.StrTo(issue["id"]).MustInt64()
  183. // Just in case legacy code can have duplicated IDs for same label.
  184. mark := make(map[int64]bool)
  185. for _, idStr := range strings.Split(string(issue["label_ids"]), "|") {
  186. labelID := com.StrTo(strings.TrimPrefix(idStr, "$")).MustInt64()
  187. if labelID == 0 || mark[labelID] {
  188. continue
  189. }
  190. mark[labelID] = true
  191. issueLabels = append(issueLabels, &IssueLabel{
  192. IssueID: issueID,
  193. LabelID: labelID,
  194. })
  195. }
  196. }
  197. sess := x.NewSession()
  198. defer sessionRelease(sess)
  199. if err = sess.Begin(); err != nil {
  200. return err
  201. }
  202. if err = sess.Sync2(new(IssueLabel)); err != nil {
  203. return fmt.Errorf("sync2: %v", err)
  204. } else if _, err = sess.Insert(issueLabels); err != nil {
  205. return fmt.Errorf("insert issue-labels: %v", err)
  206. }
  207. return sess.Commit()
  208. }
  209. func attachmentRefactor(x *xorm.Engine) error {
  210. type Attachment struct {
  211. ID int64 `xorm:"pk autoincr"`
  212. UUID string `xorm:"uuid INDEX"`
  213. // For rename purpose.
  214. Path string `xorm:"-"`
  215. NewPath string `xorm:"-"`
  216. }
  217. results, err := x.Query("SELECT * FROM `attachment`")
  218. if err != nil {
  219. return fmt.Errorf("select attachments: %v", err)
  220. }
  221. attachments := make([]*Attachment, 0, len(results))
  222. for _, attach := range results {
  223. if !com.IsExist(string(attach["path"])) {
  224. // If the attachment is already missing, there is no point to update it.
  225. continue
  226. }
  227. attachments = append(attachments, &Attachment{
  228. ID: com.StrTo(attach["id"]).MustInt64(),
  229. UUID: gouuid.NewV4().String(),
  230. Path: string(attach["path"]),
  231. })
  232. }
  233. sess := x.NewSession()
  234. defer sessionRelease(sess)
  235. if err = sess.Begin(); err != nil {
  236. return err
  237. }
  238. if err = sess.Sync2(new(Attachment)); err != nil {
  239. return fmt.Errorf("Sync2: %v", err)
  240. }
  241. // Note: Roll back for rename can be a dead loop,
  242. // so produces a backup file.
  243. var buf bytes.Buffer
  244. buf.WriteString("# old path -> new path\n")
  245. // Update database first because this is where error happens the most often.
  246. for _, attach := range attachments {
  247. if _, err = sess.Id(attach.ID).Update(attach); err != nil {
  248. return err
  249. }
  250. attach.NewPath = path.Join(setting.AttachmentPath, attach.UUID[0:1], attach.UUID[1:2], attach.UUID)
  251. buf.WriteString(attach.Path)
  252. buf.WriteString("\t")
  253. buf.WriteString(attach.NewPath)
  254. buf.WriteString("\n")
  255. }
  256. // Then rename attachments.
  257. isSucceed := true
  258. defer func() {
  259. if isSucceed {
  260. return
  261. }
  262. dumpPath := path.Join(setting.LogRootPath, "attachment_path.dump")
  263. ioutil.WriteFile(dumpPath, buf.Bytes(), 0666)
  264. fmt.Println("Fail to rename some attachments, old and new paths are saved into:", dumpPath)
  265. }()
  266. for _, attach := range attachments {
  267. if err = os.MkdirAll(path.Dir(attach.NewPath), os.ModePerm); err != nil {
  268. isSucceed = false
  269. return err
  270. }
  271. if err = os.Rename(attach.Path, attach.NewPath); err != nil {
  272. isSucceed = false
  273. return err
  274. }
  275. }
  276. return sess.Commit()
  277. }
  278. func renamePullRequestFields(x *xorm.Engine) (err error) {
  279. type PullRequest struct {
  280. ID int64 `xorm:"pk autoincr"`
  281. PullID int64 `xorm:"INDEX"`
  282. PullIndex int64
  283. HeadBarcnh string
  284. IssueID int64 `xorm:"INDEX"`
  285. Index int64
  286. HeadBranch string
  287. }
  288. if err = x.Sync(new(PullRequest)); err != nil {
  289. return fmt.Errorf("sync: %v", err)
  290. }
  291. results, err := x.Query("SELECT `id`,`pull_id`,`pull_index`,`head_barcnh` FROM `pull_request`")
  292. if err != nil {
  293. if strings.Contains(err.Error(), "no such column") {
  294. return nil
  295. }
  296. return fmt.Errorf("select pull requests: %v", err)
  297. }
  298. sess := x.NewSession()
  299. defer sessionRelease(sess)
  300. if err = sess.Begin(); err != nil {
  301. return err
  302. }
  303. var pull *PullRequest
  304. for _, pr := range results {
  305. pull = &PullRequest{
  306. ID: com.StrTo(pr["id"]).MustInt64(),
  307. IssueID: com.StrTo(pr["pull_id"]).MustInt64(),
  308. Index: com.StrTo(pr["pull_index"]).MustInt64(),
  309. HeadBranch: string(pr["head_barcnh"]),
  310. }
  311. if pull.Index == 0 {
  312. continue
  313. }
  314. if _, err = sess.Id(pull.ID).Update(pull); err != nil {
  315. return err
  316. }
  317. }
  318. return sess.Commit()
  319. }
  320. func cleanUpMigrateRepoInfo(x *xorm.Engine) (err error) {
  321. type (
  322. User struct {
  323. ID int64 `xorm:"pk autoincr"`
  324. LowerName string
  325. }
  326. Repository struct {
  327. ID int64 `xorm:"pk autoincr"`
  328. OwnerID int64
  329. LowerName string
  330. }
  331. )
  332. repos := make([]*Repository, 0, 25)
  333. if err = x.Where("is_mirror=?", false).Find(&repos); err != nil {
  334. return fmt.Errorf("select all non-mirror repositories: %v", err)
  335. }
  336. var user *User
  337. for _, repo := range repos {
  338. user = &User{ID: repo.OwnerID}
  339. has, err := x.Get(user)
  340. if err != nil {
  341. return fmt.Errorf("get owner of repository[%d - %d]: %v", repo.ID, repo.OwnerID, err)
  342. } else if !has {
  343. continue
  344. }
  345. configPath := filepath.Join(setting.RepoRootPath, user.LowerName, repo.LowerName+".git/config")
  346. // In case repository file is somehow missing.
  347. if !com.IsFile(configPath) {
  348. continue
  349. }
  350. cfg, err := ini.Load(configPath)
  351. if err != nil {
  352. return fmt.Errorf("open config file: %v", err)
  353. }
  354. cfg.DeleteSection("remote \"origin\"")
  355. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  356. return fmt.Errorf("save config file: %v", err)
  357. }
  358. }
  359. return nil
  360. }