migrations.go 16 KB

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