migrations.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  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. "strings"
  13. "time"
  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 = 0
  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("generate collaboration from access", accessToCollaboration), // V0 -> V1:v0.5.13
  49. NewMigration("make authorize 4 if team is owners", ownerTeamUpdate), // V1 -> V2:v0.5.13
  50. NewMigration("refactor access table to use id's", accessRefactor), // V2 -> V3:v0.5.13
  51. NewMigration("generate team-repo from team", teamToTeamRepo), // V3 -> V4:v0.5.13
  52. NewMigration("fix locale file load panic", fixLocaleFileLoadPanic), // V4 -> V5:v0.6.0
  53. NewMigration("trim action compare URL prefix", trimCommitActionAppUrlPrefix), // V5 -> V6:v0.6.3
  54. NewMigration("generate issue-label from issue", issueToIssueLabel), // V6 -> V7:v0.6.4
  55. NewMigration("refactor attachment table", attachmentRefactor), // V7 -> V8:v0.6.4
  56. NewMigration("rename pull request fields", renamePullRequestFields), // V8 -> V9:v0.6.16
  57. }
  58. // Migrate database to current version
  59. func Migrate(x *xorm.Engine) error {
  60. if err := x.Sync(new(Version)); err != nil {
  61. return fmt.Errorf("sync: %v", err)
  62. }
  63. currentVersion := &Version{Id: 1}
  64. has, err := x.Get(currentVersion)
  65. if err != nil {
  66. return fmt.Errorf("get: %v", err)
  67. } else if !has {
  68. // If the user table does not exist it is a fresh installation and we
  69. // can skip all migrations.
  70. needsMigration, err := x.IsTableExist("user")
  71. if err != nil {
  72. return err
  73. }
  74. if needsMigration {
  75. isEmpty, err := x.IsTableEmpty("user")
  76. if err != nil {
  77. return err
  78. }
  79. // If the user table is empty it is a fresh installation and we can
  80. // skip all migrations.
  81. needsMigration = !isEmpty
  82. }
  83. if !needsMigration {
  84. currentVersion.Version = int64(_MIN_DB_VER + len(migrations))
  85. }
  86. if _, err = x.InsertOne(currentVersion); err != nil {
  87. return fmt.Errorf("insert: %v", err)
  88. }
  89. }
  90. v := currentVersion.Version
  91. if int(v-_MIN_DB_VER) > len(migrations) {
  92. // User downgraded Gogs.
  93. currentVersion.Version = int64(len(migrations) + _MIN_DB_VER)
  94. _, err = x.Id(1).Update(currentVersion)
  95. return err
  96. }
  97. for i, m := range migrations[v-_MIN_DB_VER:] {
  98. log.Info("Migration: %s", m.Description())
  99. if err = m.Migrate(x); err != nil {
  100. return fmt.Errorf("do migrate: %v", err)
  101. }
  102. currentVersion.Version = v + int64(i) + 1
  103. if _, err = x.Id(1).Update(currentVersion); err != nil {
  104. return err
  105. }
  106. }
  107. return nil
  108. }
  109. func sessionRelease(sess *xorm.Session) {
  110. if !sess.IsCommitedOrRollbacked {
  111. sess.Rollback()
  112. }
  113. sess.Close()
  114. }
  115. func accessToCollaboration(x *xorm.Engine) (err error) {
  116. type Collaboration struct {
  117. ID int64 `xorm:"pk autoincr"`
  118. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  119. UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  120. Created time.Time
  121. }
  122. if err = x.Sync(new(Collaboration)); err != nil {
  123. return fmt.Errorf("sync: %v", err)
  124. }
  125. 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")
  126. if err != nil {
  127. if strings.Contains(err.Error(), "no such column") {
  128. return nil
  129. }
  130. return err
  131. }
  132. sess := x.NewSession()
  133. defer sessionRelease(sess)
  134. if err = sess.Begin(); err != nil {
  135. return err
  136. }
  137. offset := strings.Split(time.Now().String(), " ")[2]
  138. for _, result := range results {
  139. mode := com.StrTo(result["mode"]).MustInt64()
  140. // Collaborators must have write access.
  141. if mode < 2 {
  142. continue
  143. }
  144. userID := com.StrTo(result["uid"]).MustInt64()
  145. repoRefName := string(result["repo"])
  146. var created time.Time
  147. switch {
  148. case setting.UseSQLite3:
  149. created, _ = time.Parse(time.RFC3339, string(result["created"]))
  150. case setting.UseMySQL:
  151. created, _ = time.Parse("2006-01-02 15:04:05-0700", string(result["created"])+offset)
  152. case setting.UsePostgreSQL:
  153. created, _ = time.Parse("2006-01-02T15:04:05Z-0700", string(result["created"])+offset)
  154. }
  155. // find owner of repository
  156. parts := strings.SplitN(repoRefName, "/", 2)
  157. ownerName := parts[0]
  158. repoName := parts[1]
  159. 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)
  160. if err != nil {
  161. return err
  162. }
  163. if len(results) < 1 {
  164. continue
  165. }
  166. ownerID := com.StrTo(results[0]["uid"]).MustInt64()
  167. if ownerID == userID {
  168. continue
  169. }
  170. // test if user is member of owning organization
  171. isMember := false
  172. for _, member := range results {
  173. memberID := com.StrTo(member["memberid"]).MustInt64()
  174. // We can skip all cases that a user is member of the owning organization
  175. if memberID == userID {
  176. isMember = true
  177. }
  178. }
  179. if isMember {
  180. continue
  181. }
  182. results, err = sess.Query("SELECT id FROM `repository` WHERE owner_id=? AND lower_name=?", ownerID, repoName)
  183. if err != nil {
  184. return err
  185. } else if len(results) < 1 {
  186. continue
  187. }
  188. collaboration := &Collaboration{
  189. UserID: userID,
  190. RepoID: com.StrTo(results[0]["id"]).MustInt64(),
  191. }
  192. has, err := sess.Get(collaboration)
  193. if err != nil {
  194. return err
  195. } else if has {
  196. continue
  197. }
  198. collaboration.Created = created
  199. if _, err = sess.InsertOne(collaboration); err != nil {
  200. return err
  201. }
  202. }
  203. return sess.Commit()
  204. }
  205. func ownerTeamUpdate(x *xorm.Engine) (err error) {
  206. if _, err := x.Exec("UPDATE `team` SET authorize=4 WHERE lower_name=?", "owners"); err != nil {
  207. return fmt.Errorf("update owner team table: %v", err)
  208. }
  209. return nil
  210. }
  211. func accessRefactor(x *xorm.Engine) (err error) {
  212. type (
  213. AccessMode int
  214. Access struct {
  215. ID int64 `xorm:"pk autoincr"`
  216. UserID int64 `xorm:"UNIQUE(s)"`
  217. RepoID int64 `xorm:"UNIQUE(s)"`
  218. Mode AccessMode
  219. }
  220. UserRepo struct {
  221. UserID int64
  222. RepoID int64
  223. }
  224. )
  225. // We consiously don't start a session yet as we make only reads for now, no writes
  226. accessMap := make(map[UserRepo]AccessMode, 50)
  227. results, err := x.Query("SELECT r.id AS `repo_id`, r.is_private AS `is_private`, r.owner_id AS `owner_id`, u.type AS `owner_type` FROM `repository` r LEFT JOIN `user` u ON r.owner_id=u.id")
  228. if err != nil {
  229. return fmt.Errorf("select repositories: %v", err)
  230. }
  231. for _, repo := range results {
  232. repoID := com.StrTo(repo["repo_id"]).MustInt64()
  233. isPrivate := com.StrTo(repo["is_private"]).MustInt() > 0
  234. ownerID := com.StrTo(repo["owner_id"]).MustInt64()
  235. ownerIsOrganization := com.StrTo(repo["owner_type"]).MustInt() > 0
  236. results, err := x.Query("SELECT `user_id` FROM `collaboration` WHERE repo_id=?", repoID)
  237. if err != nil {
  238. return fmt.Errorf("select collaborators: %v", err)
  239. }
  240. for _, user := range results {
  241. userID := com.StrTo(user["user_id"]).MustInt64()
  242. accessMap[UserRepo{userID, repoID}] = 2 // WRITE ACCESS
  243. }
  244. if !ownerIsOrganization {
  245. continue
  246. }
  247. // The minimum level to add a new access record,
  248. // because public repository has implicit open access.
  249. minAccessLevel := AccessMode(0)
  250. if !isPrivate {
  251. minAccessLevel = 1
  252. }
  253. repoString := "$" + string(repo["repo_id"]) + "|"
  254. results, err = x.Query("SELECT `id`,`authorize`,`repo_ids` FROM `team` WHERE org_id=? AND authorize>? ORDER BY `authorize` ASC", ownerID, int(minAccessLevel))
  255. if err != nil {
  256. if strings.Contains(err.Error(), "no such column") {
  257. return nil
  258. }
  259. return fmt.Errorf("select teams from org: %v", err)
  260. }
  261. for _, team := range results {
  262. if !strings.Contains(string(team["repo_ids"]), repoString) {
  263. continue
  264. }
  265. teamID := com.StrTo(team["id"]).MustInt64()
  266. mode := AccessMode(com.StrTo(team["authorize"]).MustInt())
  267. results, err := x.Query("SELECT `uid` FROM `team_user` WHERE team_id=?", teamID)
  268. if err != nil {
  269. return fmt.Errorf("select users from team: %v", err)
  270. }
  271. for _, user := range results {
  272. userID := com.StrTo(user["uid"]).MustInt64()
  273. accessMap[UserRepo{userID, repoID}] = mode
  274. }
  275. }
  276. }
  277. // Drop table can't be in a session (at least not in sqlite)
  278. if _, err = x.Exec("DROP TABLE `access`"); err != nil {
  279. return fmt.Errorf("drop access table: %v", err)
  280. }
  281. // Now we start writing so we make a session
  282. sess := x.NewSession()
  283. defer sessionRelease(sess)
  284. if err = sess.Begin(); err != nil {
  285. return err
  286. }
  287. if err = sess.Sync2(new(Access)); err != nil {
  288. return fmt.Errorf("sync: %v", err)
  289. }
  290. accesses := make([]*Access, 0, len(accessMap))
  291. for ur, mode := range accessMap {
  292. accesses = append(accesses, &Access{UserID: ur.UserID, RepoID: ur.RepoID, Mode: mode})
  293. }
  294. if _, err = sess.Insert(accesses); err != nil {
  295. return fmt.Errorf("insert accesses: %v", err)
  296. }
  297. return sess.Commit()
  298. }
  299. func teamToTeamRepo(x *xorm.Engine) error {
  300. type TeamRepo struct {
  301. ID int64 `xorm:"pk autoincr"`
  302. OrgID int64 `xorm:"INDEX"`
  303. TeamID int64 `xorm:"UNIQUE(s)"`
  304. RepoID int64 `xorm:"UNIQUE(s)"`
  305. }
  306. teamRepos := make([]*TeamRepo, 0, 50)
  307. results, err := x.Query("SELECT `id`,`org_id`,`repo_ids` FROM `team`")
  308. if err != nil {
  309. if strings.Contains(err.Error(), "no such column") {
  310. return nil
  311. }
  312. return fmt.Errorf("select teams: %v", err)
  313. }
  314. for _, team := range results {
  315. orgID := com.StrTo(team["org_id"]).MustInt64()
  316. teamID := com.StrTo(team["id"]).MustInt64()
  317. // #1032: legacy code can have duplicated IDs for same repository.
  318. mark := make(map[int64]bool)
  319. for _, idStr := range strings.Split(string(team["repo_ids"]), "|") {
  320. repoID := com.StrTo(strings.TrimPrefix(idStr, "$")).MustInt64()
  321. if repoID == 0 || mark[repoID] {
  322. continue
  323. }
  324. mark[repoID] = true
  325. teamRepos = append(teamRepos, &TeamRepo{
  326. OrgID: orgID,
  327. TeamID: teamID,
  328. RepoID: repoID,
  329. })
  330. }
  331. }
  332. sess := x.NewSession()
  333. defer sessionRelease(sess)
  334. if err = sess.Begin(); err != nil {
  335. return err
  336. }
  337. if err = sess.Sync2(new(TeamRepo)); err != nil {
  338. return fmt.Errorf("sync2: %v", err)
  339. } else if _, err = sess.Insert(teamRepos); err != nil {
  340. return fmt.Errorf("insert team-repos: %v", err)
  341. }
  342. return sess.Commit()
  343. }
  344. func fixLocaleFileLoadPanic(_ *xorm.Engine) error {
  345. cfg, err := ini.Load(setting.CustomConf)
  346. if err != nil {
  347. return fmt.Errorf("load custom config: %v", err)
  348. }
  349. cfg.DeleteSection("i18n")
  350. if err = cfg.SaveTo(setting.CustomConf); err != nil {
  351. return fmt.Errorf("save custom config: %v", err)
  352. }
  353. setting.Langs = strings.Split(strings.Replace(strings.Join(setting.Langs, ","), "fr-CA", "fr-FR", 1), ",")
  354. return nil
  355. }
  356. func trimCommitActionAppUrlPrefix(x *xorm.Engine) error {
  357. type PushCommit struct {
  358. Sha1 string
  359. Message string
  360. AuthorEmail string
  361. AuthorName string
  362. }
  363. type PushCommits struct {
  364. Len int
  365. Commits []*PushCommit
  366. CompareUrl string
  367. }
  368. type Action struct {
  369. ID int64 `xorm:"pk autoincr"`
  370. Content string `xorm:"TEXT"`
  371. }
  372. results, err := x.Query("SELECT `id`,`content` FROM `action` WHERE `op_type`=?", 5)
  373. if err != nil {
  374. return fmt.Errorf("select commit actions: %v", err)
  375. }
  376. sess := x.NewSession()
  377. defer sessionRelease(sess)
  378. if err = sess.Begin(); err != nil {
  379. return err
  380. }
  381. var pushCommits *PushCommits
  382. for _, action := range results {
  383. actID := com.StrTo(string(action["id"])).MustInt64()
  384. if actID == 0 {
  385. continue
  386. }
  387. pushCommits = new(PushCommits)
  388. if err = json.Unmarshal(action["content"], pushCommits); err != nil {
  389. return fmt.Errorf("unmarshal action content[%s]: %v", actID, err)
  390. }
  391. infos := strings.Split(pushCommits.CompareUrl, "/")
  392. if len(infos) <= 4 {
  393. continue
  394. }
  395. pushCommits.CompareUrl = strings.Join(infos[len(infos)-4:], "/")
  396. p, err := json.Marshal(pushCommits)
  397. if err != nil {
  398. return fmt.Errorf("marshal action content[%s]: %v", actID, err)
  399. }
  400. if _, err = sess.Id(actID).Update(&Action{
  401. Content: string(p),
  402. }); err != nil {
  403. return fmt.Errorf("update action[%d]: %v", actID, err)
  404. }
  405. }
  406. return sess.Commit()
  407. }
  408. func issueToIssueLabel(x *xorm.Engine) error {
  409. type IssueLabel struct {
  410. ID int64 `xorm:"pk autoincr"`
  411. IssueID int64 `xorm:"UNIQUE(s)"`
  412. LabelID int64 `xorm:"UNIQUE(s)"`
  413. }
  414. issueLabels := make([]*IssueLabel, 0, 50)
  415. results, err := x.Query("SELECT `id`,`label_ids` FROM `issue`")
  416. if err != nil {
  417. if strings.Contains(err.Error(), "no such column") {
  418. return nil
  419. }
  420. return fmt.Errorf("select issues: %v", err)
  421. }
  422. for _, issue := range results {
  423. issueID := com.StrTo(issue["id"]).MustInt64()
  424. // Just in case legacy code can have duplicated IDs for same label.
  425. mark := make(map[int64]bool)
  426. for _, idStr := range strings.Split(string(issue["label_ids"]), "|") {
  427. labelID := com.StrTo(strings.TrimPrefix(idStr, "$")).MustInt64()
  428. if labelID == 0 || mark[labelID] {
  429. continue
  430. }
  431. mark[labelID] = true
  432. issueLabels = append(issueLabels, &IssueLabel{
  433. IssueID: issueID,
  434. LabelID: labelID,
  435. })
  436. }
  437. }
  438. sess := x.NewSession()
  439. defer sessionRelease(sess)
  440. if err = sess.Begin(); err != nil {
  441. return err
  442. }
  443. if err = sess.Sync2(new(IssueLabel)); err != nil {
  444. return fmt.Errorf("sync2: %v", err)
  445. } else if _, err = sess.Insert(issueLabels); err != nil {
  446. return fmt.Errorf("insert issue-labels: %v", err)
  447. }
  448. return sess.Commit()
  449. }
  450. func attachmentRefactor(x *xorm.Engine) error {
  451. type Attachment struct {
  452. ID int64 `xorm:"pk autoincr"`
  453. UUID string `xorm:"uuid INDEX"`
  454. // For rename purpose.
  455. Path string `xorm:"-"`
  456. NewPath string `xorm:"-"`
  457. }
  458. results, err := x.Query("SELECT * FROM `attachment`")
  459. if err != nil {
  460. return fmt.Errorf("select attachments: %v", err)
  461. }
  462. attachments := make([]*Attachment, 0, len(results))
  463. for _, attach := range results {
  464. if !com.IsExist(string(attach["path"])) {
  465. // If the attachment is already missing, there is no point to update it.
  466. continue
  467. }
  468. attachments = append(attachments, &Attachment{
  469. ID: com.StrTo(attach["id"]).MustInt64(),
  470. UUID: gouuid.NewV4().String(),
  471. Path: string(attach["path"]),
  472. })
  473. }
  474. sess := x.NewSession()
  475. defer sessionRelease(sess)
  476. if err = sess.Begin(); err != nil {
  477. return err
  478. }
  479. if err = sess.Sync2(new(Attachment)); err != nil {
  480. return fmt.Errorf("Sync2: %v", err)
  481. }
  482. // Note: Roll back for rename can be a dead loop,
  483. // so produces a backup file.
  484. var buf bytes.Buffer
  485. buf.WriteString("# old path -> new path\n")
  486. // Update database first because this is where error happens the most often.
  487. for _, attach := range attachments {
  488. if _, err = sess.Id(attach.ID).Update(attach); err != nil {
  489. return err
  490. }
  491. attach.NewPath = path.Join(setting.AttachmentPath, attach.UUID[0:1], attach.UUID[1:2], attach.UUID)
  492. buf.WriteString(attach.Path)
  493. buf.WriteString("\t")
  494. buf.WriteString(attach.NewPath)
  495. buf.WriteString("\n")
  496. }
  497. // Then rename attachments.
  498. isSucceed := true
  499. defer func() {
  500. if isSucceed {
  501. return
  502. }
  503. dumpPath := path.Join(setting.LogRootPath, "attachment_path.dump")
  504. ioutil.WriteFile(dumpPath, buf.Bytes(), 0666)
  505. fmt.Println("Fail to rename some attachments, old and new paths are saved into:", dumpPath)
  506. }()
  507. for _, attach := range attachments {
  508. if err = os.MkdirAll(path.Dir(attach.NewPath), os.ModePerm); err != nil {
  509. isSucceed = false
  510. return err
  511. }
  512. if err = os.Rename(attach.Path, attach.NewPath); err != nil {
  513. isSucceed = false
  514. return err
  515. }
  516. }
  517. return sess.Commit()
  518. }
  519. func renamePullRequestFields(x *xorm.Engine) (err error) {
  520. type PullRequest struct {
  521. ID int64 `xorm:"pk autoincr"`
  522. PullID int64 `xorm:"INDEX"`
  523. PullIndex int64
  524. HeadBarcnh string
  525. IssueID int64 `xorm:"INDEX"`
  526. Index int64
  527. HeadBranch string
  528. }
  529. if err = x.Sync(new(PullRequest)); err != nil {
  530. return fmt.Errorf("sync: %v", err)
  531. }
  532. results, err := x.Query("SELECT `id`,`pull_id`,`pull_index`,`head_barcnh` FROM `pull_request`")
  533. if err != nil {
  534. if strings.Contains(err.Error(), "no such column") {
  535. return nil
  536. }
  537. return fmt.Errorf("select pull requests: %v", err)
  538. }
  539. sess := x.NewSession()
  540. defer sessionRelease(sess)
  541. if err = sess.Begin(); err != nil {
  542. return err
  543. }
  544. var pull *PullRequest
  545. for _, pr := range results {
  546. pull = &PullRequest{
  547. ID: com.StrTo(pr["id"]).MustInt64(),
  548. IssueID: com.StrTo(pr["pull_id"]).MustInt64(),
  549. Index: com.StrTo(pr["pull_index"]).MustInt64(),
  550. HeadBranch: string(pr["head_barcnh"]),
  551. }
  552. if _, err = sess.Id(pull.ID).Update(pull); err != nil {
  553. return err
  554. }
  555. }
  556. return sess.Commit()
  557. }