migrations.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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. "encoding/json"
  7. "fmt"
  8. "strings"
  9. "time"
  10. "github.com/Unknwon/com"
  11. "github.com/go-xorm/xorm"
  12. "gopkg.in/ini.v1"
  13. "github.com/gogits/gogs/modules/log"
  14. "github.com/gogits/gogs/modules/setting"
  15. )
  16. const _MIN_DB_VER = 0
  17. type Migration interface {
  18. Description() string
  19. Migrate(*xorm.Engine) error
  20. }
  21. type migration struct {
  22. description string
  23. migrate func(*xorm.Engine) error
  24. }
  25. func NewMigration(desc string, fn func(*xorm.Engine) error) Migration {
  26. return &migration{desc, fn}
  27. }
  28. func (m *migration) Description() string {
  29. return m.description
  30. }
  31. func (m *migration) Migrate(x *xorm.Engine) error {
  32. return m.migrate(x)
  33. }
  34. // The version table. Should have only one row with id==1
  35. type Version struct {
  36. Id int64
  37. Version int64
  38. }
  39. // This is a sequence of migrations. Add new migrations to the bottom of the list.
  40. // If you want to "retire" a migration, remove it from the top of the list and
  41. // update _MIN_VER_DB accordingly
  42. var migrations = []Migration{
  43. NewMigration("generate collaboration from access", accessToCollaboration), // V0 -> V1:v0.5.13
  44. NewMigration("make authorize 4 if team is owners", ownerTeamUpdate), // V1 -> V2:v0.5.13
  45. NewMigration("refactor access table to use id's", accessRefactor), // V2 -> V3:v0.5.13
  46. NewMigration("generate team-repo from team", teamToTeamRepo), // V3 -> V4:v0.5.13
  47. NewMigration("fix locale file load panic", fixLocaleFileLoadPanic), // V4 -> V5:v0.6.0
  48. NewMigration("trim action compare URL prefix", trimCommitActionAppUrlPrefix), // V5 -> V6:v0.6.3
  49. NewMigration("generate issue-label from issue", issueToIssueLabel), // V6 -> V7:v0.6.4
  50. }
  51. // Migrate database to current version
  52. func Migrate(x *xorm.Engine) error {
  53. if err := x.Sync(new(Version)); err != nil {
  54. return fmt.Errorf("sync: %v", err)
  55. }
  56. currentVersion := &Version{Id: 1}
  57. has, err := x.Get(currentVersion)
  58. if err != nil {
  59. return fmt.Errorf("get: %v", err)
  60. } else if !has {
  61. // If the user table does not exist it is a fresh installation and we
  62. // can skip all migrations.
  63. needsMigration, err := x.IsTableExist("user")
  64. if err != nil {
  65. return err
  66. }
  67. if needsMigration {
  68. isEmpty, err := x.IsTableEmpty("user")
  69. if err != nil {
  70. return err
  71. }
  72. // If the user table is empty it is a fresh installation and we can
  73. // skip all migrations.
  74. needsMigration = !isEmpty
  75. }
  76. if !needsMigration {
  77. currentVersion.Version = int64(_MIN_DB_VER + len(migrations))
  78. }
  79. if _, err = x.InsertOne(currentVersion); err != nil {
  80. return fmt.Errorf("insert: %v", err)
  81. }
  82. }
  83. v := currentVersion.Version
  84. if int(v) > len(migrations) {
  85. return nil
  86. }
  87. for i, m := range migrations[v-_MIN_DB_VER:] {
  88. log.Info("Migration: %s", m.Description())
  89. if err = m.Migrate(x); err != nil {
  90. return fmt.Errorf("do migrate: %v", err)
  91. }
  92. currentVersion.Version = v + int64(i) + 1
  93. if _, err = x.Id(1).Update(currentVersion); err != nil {
  94. return err
  95. }
  96. }
  97. return nil
  98. }
  99. func sessionRelease(sess *xorm.Session) {
  100. if !sess.IsCommitedOrRollbacked {
  101. sess.Rollback()
  102. }
  103. sess.Close()
  104. }
  105. func accessToCollaboration(x *xorm.Engine) (err error) {
  106. type Collaboration struct {
  107. ID int64 `xorm:"pk autoincr"`
  108. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  109. UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  110. Created time.Time
  111. }
  112. if err = x.Sync(new(Collaboration)); err != nil {
  113. return fmt.Errorf("sync: %v", err)
  114. }
  115. 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")
  116. if err != nil {
  117. if strings.Contains(err.Error(), "no such column") {
  118. return nil
  119. }
  120. return err
  121. }
  122. sess := x.NewSession()
  123. defer sessionRelease(sess)
  124. if err = sess.Begin(); err != nil {
  125. return err
  126. }
  127. offset := strings.Split(time.Now().String(), " ")[2]
  128. for _, result := range results {
  129. mode := com.StrTo(result["mode"]).MustInt64()
  130. // Collaborators must have write access.
  131. if mode < 2 {
  132. continue
  133. }
  134. userID := com.StrTo(result["uid"]).MustInt64()
  135. repoRefName := string(result["repo"])
  136. var created time.Time
  137. switch {
  138. case setting.UseSQLite3:
  139. created, _ = time.Parse(time.RFC3339, string(result["created"]))
  140. case setting.UseMySQL:
  141. created, _ = time.Parse("2006-01-02 15:04:05-0700", string(result["created"])+offset)
  142. case setting.UsePostgreSQL:
  143. created, _ = time.Parse("2006-01-02T15:04:05Z-0700", string(result["created"])+offset)
  144. }
  145. // find owner of repository
  146. parts := strings.SplitN(repoRefName, "/", 2)
  147. ownerName := parts[0]
  148. repoName := parts[1]
  149. 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)
  150. if err != nil {
  151. return err
  152. }
  153. if len(results) < 1 {
  154. continue
  155. }
  156. ownerID := com.StrTo(results[0]["uid"]).MustInt64()
  157. if ownerID == userID {
  158. continue
  159. }
  160. // test if user is member of owning organization
  161. isMember := false
  162. for _, member := range results {
  163. memberID := com.StrTo(member["memberid"]).MustInt64()
  164. // We can skip all cases that a user is member of the owning organization
  165. if memberID == userID {
  166. isMember = true
  167. }
  168. }
  169. if isMember {
  170. continue
  171. }
  172. results, err = sess.Query("SELECT id FROM `repository` WHERE owner_id=? AND lower_name=?", ownerID, repoName)
  173. if err != nil {
  174. return err
  175. } else if len(results) < 1 {
  176. continue
  177. }
  178. collaboration := &Collaboration{
  179. UserID: userID,
  180. RepoID: com.StrTo(results[0]["id"]).MustInt64(),
  181. }
  182. has, err := sess.Get(collaboration)
  183. if err != nil {
  184. return err
  185. } else if has {
  186. continue
  187. }
  188. collaboration.Created = created
  189. if _, err = sess.InsertOne(collaboration); err != nil {
  190. return err
  191. }
  192. }
  193. return sess.Commit()
  194. }
  195. func ownerTeamUpdate(x *xorm.Engine) (err error) {
  196. if _, err := x.Exec("UPDATE `team` SET authorize=4 WHERE lower_name=?", "owners"); err != nil {
  197. return fmt.Errorf("update owner team table: %v", err)
  198. }
  199. return nil
  200. }
  201. func accessRefactor(x *xorm.Engine) (err error) {
  202. type (
  203. AccessMode int
  204. Access struct {
  205. ID int64 `xorm:"pk autoincr"`
  206. UserID int64 `xorm:"UNIQUE(s)"`
  207. RepoID int64 `xorm:"UNIQUE(s)"`
  208. Mode AccessMode
  209. }
  210. UserRepo struct {
  211. UserID int64
  212. RepoID int64
  213. }
  214. )
  215. // We consiously don't start a session yet as we make only reads for now, no writes
  216. accessMap := make(map[UserRepo]AccessMode, 50)
  217. 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")
  218. if err != nil {
  219. return fmt.Errorf("select repositories: %v", err)
  220. }
  221. for _, repo := range results {
  222. repoID := com.StrTo(repo["repo_id"]).MustInt64()
  223. isPrivate := com.StrTo(repo["is_private"]).MustInt() > 0
  224. ownerID := com.StrTo(repo["owner_id"]).MustInt64()
  225. ownerIsOrganization := com.StrTo(repo["owner_type"]).MustInt() > 0
  226. results, err := x.Query("SELECT `user_id` FROM `collaboration` WHERE repo_id=?", repoID)
  227. if err != nil {
  228. return fmt.Errorf("select collaborators: %v", err)
  229. }
  230. for _, user := range results {
  231. userID := com.StrTo(user["user_id"]).MustInt64()
  232. accessMap[UserRepo{userID, repoID}] = 2 // WRITE ACCESS
  233. }
  234. if !ownerIsOrganization {
  235. continue
  236. }
  237. // The minimum level to add a new access record,
  238. // because public repository has implicit open access.
  239. minAccessLevel := AccessMode(0)
  240. if !isPrivate {
  241. minAccessLevel = 1
  242. }
  243. repoString := "$" + string(repo["repo_id"]) + "|"
  244. results, err = x.Query("SELECT `id`,`authorize`,`repo_ids` FROM `team` WHERE org_id=? AND authorize>? ORDER BY `authorize` ASC", ownerID, int(minAccessLevel))
  245. if err != nil {
  246. if strings.Contains(err.Error(), "no such column") {
  247. return nil
  248. }
  249. return fmt.Errorf("select teams from org: %v", err)
  250. }
  251. for _, team := range results {
  252. if !strings.Contains(string(team["repo_ids"]), repoString) {
  253. continue
  254. }
  255. teamID := com.StrTo(team["id"]).MustInt64()
  256. mode := AccessMode(com.StrTo(team["authorize"]).MustInt())
  257. results, err := x.Query("SELECT `uid` FROM `team_user` WHERE team_id=?", teamID)
  258. if err != nil {
  259. return fmt.Errorf("select users from team: %v", err)
  260. }
  261. for _, user := range results {
  262. userID := com.StrTo(user["uid"]).MustInt64()
  263. accessMap[UserRepo{userID, repoID}] = mode
  264. }
  265. }
  266. }
  267. // Drop table can't be in a session (at least not in sqlite)
  268. if _, err = x.Exec("DROP TABLE `access`"); err != nil {
  269. return fmt.Errorf("drop access table: %v", err)
  270. }
  271. // Now we start writing so we make a session
  272. sess := x.NewSession()
  273. defer sessionRelease(sess)
  274. if err = sess.Begin(); err != nil {
  275. return err
  276. }
  277. if err = sess.Sync2(new(Access)); err != nil {
  278. return fmt.Errorf("sync: %v", err)
  279. }
  280. accesses := make([]*Access, 0, len(accessMap))
  281. for ur, mode := range accessMap {
  282. accesses = append(accesses, &Access{UserID: ur.UserID, RepoID: ur.RepoID, Mode: mode})
  283. }
  284. if _, err = sess.Insert(accesses); err != nil {
  285. return fmt.Errorf("insert accesses: %v", err)
  286. }
  287. return sess.Commit()
  288. }
  289. func teamToTeamRepo(x *xorm.Engine) error {
  290. type TeamRepo struct {
  291. ID int64 `xorm:"pk autoincr"`
  292. OrgID int64 `xorm:"INDEX"`
  293. TeamID int64 `xorm:"UNIQUE(s)"`
  294. RepoID int64 `xorm:"UNIQUE(s)"`
  295. }
  296. teamRepos := make([]*TeamRepo, 0, 50)
  297. results, err := x.Query("SELECT `id`,`org_id`,`repo_ids` FROM `team`")
  298. if err != nil {
  299. if strings.Contains(err.Error(), "no such column") {
  300. return nil
  301. }
  302. return fmt.Errorf("select teams: %v", err)
  303. }
  304. for _, team := range results {
  305. orgID := com.StrTo(team["org_id"]).MustInt64()
  306. teamID := com.StrTo(team["id"]).MustInt64()
  307. // #1032: legacy code can have duplicated IDs for same repository.
  308. mark := make(map[int64]bool)
  309. for _, idStr := range strings.Split(string(team["repo_ids"]), "|") {
  310. repoID := com.StrTo(strings.TrimPrefix(idStr, "$")).MustInt64()
  311. if repoID == 0 || mark[repoID] {
  312. continue
  313. }
  314. mark[repoID] = true
  315. teamRepos = append(teamRepos, &TeamRepo{
  316. OrgID: orgID,
  317. TeamID: teamID,
  318. RepoID: repoID,
  319. })
  320. }
  321. }
  322. sess := x.NewSession()
  323. defer sessionRelease(sess)
  324. if err = sess.Begin(); err != nil {
  325. return err
  326. }
  327. if err = sess.Sync2(new(TeamRepo)); err != nil {
  328. return fmt.Errorf("sync2: %v", err)
  329. } else if _, err = sess.Insert(teamRepos); err != nil {
  330. return fmt.Errorf("insert team-repos: %v", err)
  331. }
  332. return sess.Commit()
  333. }
  334. func fixLocaleFileLoadPanic(_ *xorm.Engine) error {
  335. cfg, err := ini.Load(setting.CustomConf)
  336. if err != nil {
  337. return fmt.Errorf("load custom config: %v", err)
  338. }
  339. cfg.DeleteSection("i18n")
  340. if err = cfg.SaveTo(setting.CustomConf); err != nil {
  341. return fmt.Errorf("save custom config: %v", err)
  342. }
  343. setting.Langs = strings.Split(strings.Replace(strings.Join(setting.Langs, ","), "fr-CA", "fr-FR", 1), ",")
  344. return nil
  345. }
  346. func trimCommitActionAppUrlPrefix(x *xorm.Engine) error {
  347. type PushCommit struct {
  348. Sha1 string
  349. Message string
  350. AuthorEmail string
  351. AuthorName string
  352. }
  353. type PushCommits struct {
  354. Len int
  355. Commits []*PushCommit
  356. CompareUrl string
  357. }
  358. type Action struct {
  359. ID int64 `xorm:"pk autoincr"`
  360. Content string `xorm:"TEXT"`
  361. }
  362. results, err := x.Query("SELECT `id`,`content` FROM `action` WHERE `op_type`=?", 5)
  363. if err != nil {
  364. return fmt.Errorf("select commit actions: %v", err)
  365. }
  366. sess := x.NewSession()
  367. defer sessionRelease(sess)
  368. if err = sess.Begin(); err != nil {
  369. return err
  370. }
  371. var pushCommits *PushCommits
  372. for _, action := range results {
  373. actID := com.StrTo(string(action["id"])).MustInt64()
  374. if actID == 0 {
  375. continue
  376. }
  377. pushCommits = new(PushCommits)
  378. if err = json.Unmarshal(action["content"], pushCommits); err != nil {
  379. return fmt.Errorf("unmarshal action content[%s]: %v", actID, err)
  380. }
  381. infos := strings.Split(pushCommits.CompareUrl, "/")
  382. if len(infos) <= 4 {
  383. continue
  384. }
  385. pushCommits.CompareUrl = strings.Join(infos[len(infos)-4:], "/")
  386. p, err := json.Marshal(pushCommits)
  387. if err != nil {
  388. return fmt.Errorf("marshal action content[%s]: %v", actID, err)
  389. }
  390. if _, err = sess.Id(actID).Update(&Action{
  391. Content: string(p),
  392. }); err != nil {
  393. return fmt.Errorf("update action[%s]: %v", actID, err)
  394. }
  395. }
  396. return sess.Commit()
  397. }
  398. func issueToIssueLabel(x *xorm.Engine) error {
  399. type IssueLabel struct {
  400. ID int64 `xorm:"pk autoincr"`
  401. IssueID int64 `xorm:"UNIQUE(s)"`
  402. LabelID int64 `xorm:"UNIQUE(s)"`
  403. }
  404. issueLabels := make([]*IssueLabel, 0, 50)
  405. results, err := x.Query("SELECT `id`,`label_ids` FROM `issue`")
  406. if err != nil {
  407. if strings.Contains(err.Error(), "no such column") {
  408. return nil
  409. }
  410. return fmt.Errorf("select issues: %v", err)
  411. }
  412. for _, issue := range results {
  413. issueID := com.StrTo(issue["id"]).MustInt64()
  414. // Just in case legacy code can have duplicated IDs for same label.
  415. mark := make(map[int64]bool)
  416. for _, idStr := range strings.Split(string(issue["label_ids"]), "|") {
  417. labelID := com.StrTo(strings.TrimPrefix(idStr, "$")).MustInt64()
  418. if labelID == 0 || mark[labelID] {
  419. continue
  420. }
  421. mark[labelID] = true
  422. issueLabels = append(issueLabels, &IssueLabel{
  423. IssueID: issueID,
  424. LabelID: labelID,
  425. })
  426. }
  427. }
  428. sess := x.NewSession()
  429. defer sessionRelease(sess)
  430. if err = sess.Begin(); err != nil {
  431. return err
  432. }
  433. if err = sess.Sync2(new(IssueLabel)); err != nil {
  434. return fmt.Errorf("sync2: %v", err)
  435. } else if _, err = sess.Insert(issueLabels); err != nil {
  436. return fmt.Errorf("insert issue-labels: %v", err)
  437. }
  438. return sess.Commit()
  439. }