You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

migrations.go 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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. 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 accessToCollaboration(x *xorm.Engine) (err error) {
  103. type Collaboration struct {
  104. ID int64 `xorm:"pk autoincr"`
  105. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  106. UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  107. Created time.Time
  108. }
  109. if err = x.Sync(new(Collaboration)); err != nil {
  110. return fmt.Errorf("sync: %v", err)
  111. }
  112. 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")
  113. if err != nil {
  114. if strings.Contains(err.Error(), "no such column") {
  115. return nil
  116. }
  117. return err
  118. }
  119. sess := x.NewSession()
  120. defer sessionRelease(sess)
  121. if err = sess.Begin(); err != nil {
  122. return err
  123. }
  124. offset := strings.Split(time.Now().String(), " ")[2]
  125. for _, result := range results {
  126. mode := com.StrTo(result["mode"]).MustInt64()
  127. // Collaborators must have write access.
  128. if mode < 2 {
  129. continue
  130. }
  131. userID := com.StrTo(result["uid"]).MustInt64()
  132. repoRefName := string(result["repo"])
  133. var created time.Time
  134. switch {
  135. case setting.UseSQLite3:
  136. created, _ = time.Parse(time.RFC3339, string(result["created"]))
  137. case setting.UseMySQL:
  138. created, _ = time.Parse("2006-01-02 15:04:05-0700", string(result["created"])+offset)
  139. case setting.UsePostgreSQL:
  140. created, _ = time.Parse("2006-01-02T15:04:05Z-0700", string(result["created"])+offset)
  141. }
  142. // find owner of repository
  143. parts := strings.SplitN(repoRefName, "/", 2)
  144. ownerName := parts[0]
  145. repoName := parts[1]
  146. 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)
  147. if err != nil {
  148. return err
  149. }
  150. if len(results) < 1 {
  151. continue
  152. }
  153. ownerID := com.StrTo(results[0]["uid"]).MustInt64()
  154. if ownerID == userID {
  155. continue
  156. }
  157. // test if user is member of owning organization
  158. isMember := false
  159. for _, member := range results {
  160. memberID := com.StrTo(member["memberid"]).MustInt64()
  161. // We can skip all cases that a user is member of the owning organization
  162. if memberID == userID {
  163. isMember = true
  164. }
  165. }
  166. if isMember {
  167. continue
  168. }
  169. results, err = sess.Query("SELECT id FROM `repository` WHERE owner_id=? AND lower_name=?", ownerID, repoName)
  170. if err != nil {
  171. return err
  172. } else if len(results) < 1 {
  173. continue
  174. }
  175. collaboration := &Collaboration{
  176. UserID: userID,
  177. RepoID: com.StrTo(results[0]["id"]).MustInt64(),
  178. }
  179. has, err := sess.Get(collaboration)
  180. if err != nil {
  181. return err
  182. } else if has {
  183. continue
  184. }
  185. collaboration.Created = created
  186. if _, err = sess.InsertOne(collaboration); err != nil {
  187. return err
  188. }
  189. }
  190. return sess.Commit()
  191. }
  192. func ownerTeamUpdate(x *xorm.Engine) (err error) {
  193. if _, err := x.Exec("UPDATE `team` SET authorize=4 WHERE lower_name=?", "owners"); err != nil {
  194. return fmt.Errorf("update owner team table: %v", err)
  195. }
  196. return nil
  197. }
  198. func accessRefactor(x *xorm.Engine) (err error) {
  199. type (
  200. AccessMode int
  201. Access struct {
  202. ID int64 `xorm:"pk autoincr"`
  203. UserID int64 `xorm:"UNIQUE(s)"`
  204. RepoID int64 `xorm:"UNIQUE(s)"`
  205. Mode AccessMode
  206. }
  207. UserRepo struct {
  208. UserID int64
  209. RepoID int64
  210. }
  211. )
  212. // We consiously don't start a session yet as we make only reads for now, no writes
  213. accessMap := make(map[UserRepo]AccessMode, 50)
  214. 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")
  215. if err != nil {
  216. return fmt.Errorf("select repositories: %v", err)
  217. }
  218. for _, repo := range results {
  219. repoID := com.StrTo(repo["repo_id"]).MustInt64()
  220. isPrivate := com.StrTo(repo["is_private"]).MustInt() > 0
  221. ownerID := com.StrTo(repo["owner_id"]).MustInt64()
  222. ownerIsOrganization := com.StrTo(repo["owner_type"]).MustInt() > 0
  223. results, err := x.Query("SELECT `user_id` FROM `collaboration` WHERE repo_id=?", repoID)
  224. if err != nil {
  225. return fmt.Errorf("select collaborators: %v", err)
  226. }
  227. for _, user := range results {
  228. userID := com.StrTo(user["user_id"]).MustInt64()
  229. accessMap[UserRepo{userID, repoID}] = 2 // WRITE ACCESS
  230. }
  231. if !ownerIsOrganization {
  232. continue
  233. }
  234. // The minimum level to add a new access record,
  235. // because public repository has implicit open access.
  236. minAccessLevel := AccessMode(0)
  237. if !isPrivate {
  238. minAccessLevel = 1
  239. }
  240. repoString := "$" + string(repo["repo_id"]) + "|"
  241. results, err = x.Query("SELECT `id`,`authorize`,`repo_ids` FROM `team` WHERE org_id=? AND authorize>? ORDER BY `authorize` ASC", ownerID, int(minAccessLevel))
  242. if err != nil {
  243. if strings.Contains(err.Error(), "no such column") {
  244. return nil
  245. }
  246. return fmt.Errorf("select teams from org: %v", err)
  247. }
  248. for _, team := range results {
  249. if !strings.Contains(string(team["repo_ids"]), repoString) {
  250. continue
  251. }
  252. teamID := com.StrTo(team["id"]).MustInt64()
  253. mode := AccessMode(com.StrTo(team["authorize"]).MustInt())
  254. results, err := x.Query("SELECT `uid` FROM `team_user` WHERE team_id=?", teamID)
  255. if err != nil {
  256. return fmt.Errorf("select users from team: %v", err)
  257. }
  258. for _, user := range results {
  259. userID := com.StrTo(user["uid"]).MustInt64()
  260. accessMap[UserRepo{userID, repoID}] = mode
  261. }
  262. }
  263. }
  264. // Drop table can't be in a session (at least not in sqlite)
  265. if _, err = x.Exec("DROP TABLE `access`"); err != nil {
  266. return fmt.Errorf("drop access table: %v", err)
  267. }
  268. // Now we start writing so we make a session
  269. sess := x.NewSession()
  270. defer sessionRelease(sess)
  271. if err = sess.Begin(); err != nil {
  272. return err
  273. }
  274. if err = sess.Sync2(new(Access)); err != nil {
  275. return fmt.Errorf("sync: %v", err)
  276. }
  277. accesses := make([]*Access, 0, len(accessMap))
  278. for ur, mode := range accessMap {
  279. accesses = append(accesses, &Access{UserID: ur.UserID, RepoID: ur.RepoID, Mode: mode})
  280. }
  281. if _, err = sess.Insert(accesses); err != nil {
  282. return fmt.Errorf("insert accesses: %v", err)
  283. }
  284. return sess.Commit()
  285. }
  286. func teamToTeamRepo(x *xorm.Engine) error {
  287. type TeamRepo struct {
  288. ID int64 `xorm:"pk autoincr"`
  289. OrgID int64 `xorm:"INDEX"`
  290. TeamID int64 `xorm:"UNIQUE(s)"`
  291. RepoID int64 `xorm:"UNIQUE(s)"`
  292. }
  293. teamRepos := make([]*TeamRepo, 0, 50)
  294. results, err := x.Query("SELECT `id`,`org_id`,`repo_ids` FROM `team`")
  295. if err != nil {
  296. if strings.Contains(err.Error(), "no such column") {
  297. return nil
  298. }
  299. return fmt.Errorf("select teams: %v", err)
  300. }
  301. for _, team := range results {
  302. orgID := com.StrTo(team["org_id"]).MustInt64()
  303. teamID := com.StrTo(team["id"]).MustInt64()
  304. // #1032: legacy code can have duplicated IDs for same repository.
  305. mark := make(map[int64]bool)
  306. for _, idStr := range strings.Split(string(team["repo_ids"]), "|") {
  307. repoID := com.StrTo(strings.TrimPrefix(idStr, "$")).MustInt64()
  308. if repoID == 0 || mark[repoID] {
  309. continue
  310. }
  311. mark[repoID] = true
  312. teamRepos = append(teamRepos, &TeamRepo{
  313. OrgID: orgID,
  314. TeamID: teamID,
  315. RepoID: repoID,
  316. })
  317. }
  318. }
  319. sess := x.NewSession()
  320. defer sessionRelease(sess)
  321. if err = sess.Begin(); err != nil {
  322. return err
  323. }
  324. if err = sess.Sync2(new(TeamRepo)); err != nil {
  325. return fmt.Errorf("sync2: %v", err)
  326. } else if _, err = sess.Insert(teamRepos); err != nil {
  327. return fmt.Errorf("insert team-repos: %v", err)
  328. }
  329. return sess.Commit()
  330. }
  331. func fixLocaleFileLoadPanic(_ *xorm.Engine) error {
  332. cfg, err := ini.Load(setting.CustomConf)
  333. if err != nil {
  334. return fmt.Errorf("load custom config: %v", err)
  335. }
  336. cfg.DeleteSection("i18n")
  337. if err = cfg.SaveTo(setting.CustomConf); err != nil {
  338. return fmt.Errorf("save custom config: %v", err)
  339. }
  340. setting.Langs = strings.Split(strings.Replace(strings.Join(setting.Langs, ","), "fr-CA", "fr-FR", 1), ",")
  341. return nil
  342. }
  343. func trimCommitActionAppUrlPrefix(x *xorm.Engine) error {
  344. type PushCommit struct {
  345. Sha1 string
  346. Message string
  347. AuthorEmail string
  348. AuthorName string
  349. }
  350. type PushCommits struct {
  351. Len int
  352. Commits []*PushCommit
  353. CompareUrl string
  354. }
  355. type Action struct {
  356. ID int64 `xorm:"pk autoincr"`
  357. Content string `xorm:"TEXT"`
  358. }
  359. results, err := x.Query("SELECT `id`,`content` FROM `action` WHERE `op_type`=?", 5)
  360. if err != nil {
  361. return fmt.Errorf("select commit actions: %v", err)
  362. }
  363. sess := x.NewSession()
  364. defer sessionRelease(sess)
  365. if err = sess.Begin(); err != nil {
  366. return err
  367. }
  368. var pushCommits *PushCommits
  369. for _, action := range results {
  370. actID := com.StrTo(string(action["id"])).MustInt64()
  371. if actID == 0 {
  372. continue
  373. }
  374. pushCommits = new(PushCommits)
  375. if err = json.Unmarshal(action["content"], pushCommits); err != nil {
  376. return fmt.Errorf("unmarshal action content[%s]: %v", actID, err)
  377. }
  378. infos := strings.Split(pushCommits.CompareUrl, "/")
  379. if len(infos) <= 4 {
  380. continue
  381. }
  382. pushCommits.CompareUrl = strings.Join(infos[len(infos)-4:], "/")
  383. p, err := json.Marshal(pushCommits)
  384. if err != nil {
  385. return fmt.Errorf("marshal action content[%s]: %v", actID, err)
  386. }
  387. if _, err = sess.Id(actID).Update(&Action{
  388. Content: string(p),
  389. }); err != nil {
  390. return fmt.Errorf("update action[%s]: %v", actID, err)
  391. }
  392. }
  393. return sess.Commit()
  394. }
  395. func issueToIssueLabel(x *xorm.Engine) error {
  396. type IssueLabel struct {
  397. ID int64 `xorm:"pk autoincr"`
  398. IssueID int64 `xorm:"UNIQUE(s)"`
  399. LabelID int64 `xorm:"UNIQUE(s)"`
  400. }
  401. issueLabels := make([]*IssueLabel, 0, 50)
  402. results, err := x.Query("SELECT `id`,`label_ids` FROM `issue`")
  403. if err != nil {
  404. if strings.Contains(err.Error(), "no such column") {
  405. return nil
  406. }
  407. return fmt.Errorf("select issues: %v", err)
  408. }
  409. for _, issue := range results {
  410. issueID := com.StrTo(issue["id"]).MustInt64()
  411. // Just in case legacy code can have duplicated IDs for same label.
  412. mark := make(map[int64]bool)
  413. for _, idStr := range strings.Split(string(issue["label_ids"]), "|") {
  414. labelID := com.StrTo(strings.TrimPrefix(idStr, "$")).MustInt64()
  415. if labelID == 0 || mark[labelID] {
  416. continue
  417. }
  418. mark[labelID] = true
  419. issueLabels = append(issueLabels, &IssueLabel{
  420. IssueID: issueID,
  421. LabelID: labelID,
  422. })
  423. }
  424. }
  425. sess := x.NewSession()
  426. defer sessionRelease(sess)
  427. if err = sess.Begin(); err != nil {
  428. return err
  429. }
  430. if err = sess.Sync2(new(IssueLabel)); err != nil {
  431. return fmt.Errorf("sync2: %v", err)
  432. } else if _, err = sess.Insert(issueLabels); err != nil {
  433. return fmt.Errorf("insert issue-labels: %v", err)
  434. }
  435. return sess.Commit()
  436. }