migrations.go 12 KB

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