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 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package migrations
  6. import (
  7. "bytes"
  8. "encoding/json"
  9. "fmt"
  10. "io/ioutil"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "strings"
  15. "time"
  16. "github.com/Unknwon/com"
  17. "github.com/go-xorm/xorm"
  18. gouuid "github.com/satori/go.uuid"
  19. ini "gopkg.in/ini.v1"
  20. "code.gitea.io/gitea/modules/generate"
  21. "code.gitea.io/gitea/modules/log"
  22. "code.gitea.io/gitea/modules/setting"
  23. )
  24. const minDBVersion = 4
  25. // Migration describes on migration from lower version to high version
  26. type Migration interface {
  27. Description() string
  28. Migrate(*xorm.Engine) error
  29. }
  30. type migration struct {
  31. description string
  32. migrate func(*xorm.Engine) error
  33. }
  34. // NewMigration creates a new migration
  35. func NewMigration(desc string, fn func(*xorm.Engine) error) Migration {
  36. return &migration{desc, fn}
  37. }
  38. // Description returns the migration's description
  39. func (m *migration) Description() string {
  40. return m.description
  41. }
  42. // Migrate executes the migration
  43. func (m *migration) Migrate(x *xorm.Engine) error {
  44. return m.migrate(x)
  45. }
  46. // Version describes the version table. Should have only one row with id==1
  47. type Version struct {
  48. ID int64 `xorm:"pk autoincr"`
  49. Version int64
  50. }
  51. func emptyMigration(x *xorm.Engine) error {
  52. return nil
  53. }
  54. // This is a sequence of migrations. Add new migrations to the bottom of the list.
  55. // If you want to "retire" a migration, remove it from the top of the list and
  56. // update minDBVersion accordingly
  57. var migrations = []Migration{
  58. // v0 -> v4: before 0.6.0 -> 0.7.33
  59. NewMigration("fix locale file load panic", fixLocaleFileLoadPanic), // V4 -> V5:v0.6.0
  60. NewMigration("trim action compare URL prefix", trimCommitActionAppURLPrefix), // V5 -> V6:v0.6.3
  61. NewMigration("generate issue-label from issue", issueToIssueLabel), // V6 -> V7:v0.6.4
  62. NewMigration("refactor attachment table", attachmentRefactor), // V7 -> V8:v0.6.4
  63. NewMigration("rename pull request fields", renamePullRequestFields), // V8 -> V9:v0.6.16
  64. NewMigration("clean up migrate repo info", cleanUpMigrateRepoInfo), // V9 -> V10:v0.6.20
  65. NewMigration("generate rands and salt for organizations", generateOrgRandsAndSalt), // V10 -> V11:v0.8.5
  66. NewMigration("convert date to unix timestamp", convertDateToUnix), // V11 -> V12:v0.9.2
  67. NewMigration("convert LDAP UseSSL option to SecurityProtocol", ldapUseSSLToSecurityProtocol), // V12 -> V13:v0.9.37
  68. // v13 -> v14:v0.9.87
  69. NewMigration("set comment updated with created", setCommentUpdatedWithCreated),
  70. // v14 -> v15
  71. NewMigration("create user column diff view style", createUserColumnDiffViewStyle),
  72. // v15 -> v16
  73. NewMigration("create user column allow create organization", createAllowCreateOrganizationColumn),
  74. // V16 -> v17
  75. NewMigration("create repo unit table and add units for all repos", addUnitsToTables),
  76. // v17 -> v18
  77. NewMigration("set protect branches updated with created", setProtectedBranchUpdatedWithCreated),
  78. // v18 -> v19
  79. NewMigration("add external login user", addExternalLoginUser),
  80. // v19 -> v20
  81. NewMigration("generate and migrate Git hooks", generateAndMigrateGitHooks),
  82. // v20 -> v21
  83. NewMigration("use new avatar path name for security reason", useNewNameAvatars),
  84. // v21 -> v22
  85. NewMigration("rewrite authorized_keys file via new format", useNewPublickeyFormat),
  86. // v22 -> v23
  87. NewMigration("generate and migrate wiki Git hooks", generateAndMigrateWikiGitHooks),
  88. // v23 -> v24
  89. NewMigration("add user openid table", addUserOpenID),
  90. // v24 -> v25
  91. NewMigration("change the key_id and primary_key_id type", changeGPGKeysColumns),
  92. // v25 -> v26
  93. NewMigration("add show field in user openid table", addUserOpenIDShow),
  94. // v26 -> v27
  95. NewMigration("generate and migrate repo and wiki Git hooks", generateAndMigrateGitHookChains),
  96. // v27 -> v28
  97. NewMigration("change mirror interval from hours to time.Duration", convertIntervalToDuration),
  98. // v28 -> v29
  99. NewMigration("add field for repo size", addRepoSize),
  100. // v29 -> v30
  101. NewMigration("add commit status table", addCommitStatus),
  102. // v30 -> 31
  103. NewMigration("add primary key to external login user", addExternalLoginUserPK),
  104. // v31 -> 32
  105. NewMigration("add field for login source synchronization", addLoginSourceSyncEnabledColumn),
  106. // v32 -> v33
  107. NewMigration("add units for team", addUnitsToRepoTeam),
  108. // v33 -> v34
  109. NewMigration("remove columns from action", removeActionColumns),
  110. // v34 -> v35
  111. NewMigration("give all units to owner teams", giveAllUnitsToOwnerTeams),
  112. // v35 -> v36
  113. NewMigration("adds comment to an action", addCommentIDToAction),
  114. // v36 -> v37
  115. NewMigration("regenerate git hooks", regenerateGitHooks36),
  116. // v37 -> v38
  117. NewMigration("unescape user full names", unescapeUserFullNames),
  118. // v38 -> v39
  119. NewMigration("remove commits and settings unit types", removeCommitsUnitType),
  120. // v39 -> v40
  121. NewMigration("add tags to releases and sync existing repositories", releaseAddColumnIsTagAndSyncTags),
  122. // v40 -> v41
  123. NewMigration("fix protected branch can push value to false", fixProtectedBranchCanPushValue),
  124. // v41 -> v42
  125. NewMigration("remove duplicate unit types", removeDuplicateUnitTypes),
  126. // v42 -> v43
  127. NewMigration("empty step", emptyMigration),
  128. // v43 -> v44
  129. NewMigration("empty step", emptyMigration),
  130. // v44 -> v45
  131. NewMigration("empty step", emptyMigration),
  132. // v45 -> v46
  133. NewMigration("remove index column from repo_unit table", removeIndexColumnFromRepoUnitTable),
  134. // v46 -> v47
  135. NewMigration("remove organization watch repositories", removeOrganizationWatchRepo),
  136. // v47 -> v48
  137. NewMigration("add deleted branches", addDeletedBranch),
  138. // v48 -> v49
  139. NewMigration("add repo indexer status", addRepoIndexerStatus),
  140. // v49 -> v50
  141. NewMigration("adds time tracking and stopwatches", addTimetracking),
  142. // v50 -> v51
  143. NewMigration("migrate protected branch struct", migrateProtectedBranchStruct),
  144. // v51 -> v52
  145. NewMigration("add default value to user prohibit_login", addDefaultValueToUserProhibitLogin),
  146. // v52 -> v53
  147. NewMigration("add lfs lock table", addLFSLock),
  148. // v53 -> v54
  149. NewMigration("add reactions", addReactions),
  150. // v54 -> v55
  151. NewMigration("add pull request options", addPullRequestOptions),
  152. // v55 -> v56
  153. NewMigration("add writable deploy keys", addModeToDeploKeys),
  154. // v56 -> v57
  155. NewMigration("remove is_owner, num_teams columns from org_user", removeIsOwnerColumnFromOrgUser),
  156. // v57 -> v58
  157. NewMigration("add closed_unix column for issues", addIssueClosedTime),
  158. // v58 -> v59
  159. NewMigration("add label descriptions", addLabelsDescriptions),
  160. // v59 -> v60
  161. NewMigration("add merge whitelist for protected branches", addProtectedBranchMergeWhitelist),
  162. // v60 -> v61
  163. NewMigration("add is_fsck_enabled column for repos", addFsckEnabledToRepo),
  164. // v61 -> v62
  165. NewMigration("add size column for attachments", addSizeToAttachment),
  166. // v62 -> v63
  167. NewMigration("add last used passcode column for TOTP", addLastUsedPasscodeTOTP),
  168. // v63 -> v64
  169. NewMigration("add language column for user setting", addLanguageSetting),
  170. // v64 -> v65
  171. NewMigration("add multiple assignees", addMultipleAssignees),
  172. // v65 -> v66
  173. NewMigration("add u2f", addU2FReg),
  174. // v66 -> v67
  175. NewMigration("add login source id column for public_key table", addLoginSourceIDToPublicKeyTable),
  176. // v67 -> v68
  177. NewMigration("remove stale watches", removeStaleWatches),
  178. // v68 -> V69
  179. NewMigration("Reformat and remove incorrect topics", reformatAndRemoveIncorrectTopics),
  180. // v69 -> v70
  181. NewMigration("move team units to team_unit table", moveTeamUnitsToTeamUnitTable),
  182. // v70 -> v71
  183. NewMigration("add issue_dependencies", addIssueDependencies),
  184. // v71 -> v72
  185. NewMigration("protect each scratch token", addScratchHash),
  186. // v72 -> v73
  187. NewMigration("add review", addReview),
  188. // v73 -> v74
  189. NewMigration("add must_change_password column for users table", addMustChangePassword),
  190. // v74 -> v75
  191. NewMigration("add approval whitelists to protected branches", addApprovalWhitelistsToProtectedBranches),
  192. // v75 -> v76
  193. NewMigration("clear nonused data which not deleted when user was deleted", clearNonusedData),
  194. // v76 -> v77
  195. NewMigration("add pull request rebase with merge commit", addPullRequestRebaseWithMerge),
  196. // v77 -> v78
  197. NewMigration("add theme to users", addUserDefaultTheme),
  198. // v78 -> v79
  199. NewMigration("rename repo is_bare to repo is_empty", renameRepoIsBareToIsEmpty),
  200. // v79 -> v80
  201. NewMigration("add can close issues via commit in any branch", addCanCloseIssuesViaCommitInAnyBranch),
  202. }
  203. // Migrate database to current version
  204. func Migrate(x *xorm.Engine) error {
  205. if err := x.Sync(new(Version)); err != nil {
  206. return fmt.Errorf("sync: %v", err)
  207. }
  208. currentVersion := &Version{ID: 1}
  209. has, err := x.Get(currentVersion)
  210. if err != nil {
  211. return fmt.Errorf("get: %v", err)
  212. } else if !has {
  213. // If the version record does not exist we think
  214. // it is a fresh installation and we can skip all migrations.
  215. currentVersion.ID = 0
  216. currentVersion.Version = int64(minDBVersion + len(migrations))
  217. if _, err = x.InsertOne(currentVersion); err != nil {
  218. return fmt.Errorf("insert: %v", err)
  219. }
  220. }
  221. v := currentVersion.Version
  222. if minDBVersion > v {
  223. log.Fatal(4, `Gitea no longer supports auto-migration from your previously installed version.
  224. Please try to upgrade to a lower version (>= v0.6.0) first, then upgrade to current version.`)
  225. return nil
  226. }
  227. if int(v-minDBVersion) > len(migrations) {
  228. // User downgraded Gitea.
  229. currentVersion.Version = int64(len(migrations) + minDBVersion)
  230. _, err = x.ID(1).Update(currentVersion)
  231. return err
  232. }
  233. for i, m := range migrations[v-minDBVersion:] {
  234. log.Info("Migration: %s", m.Description())
  235. if err = m.Migrate(x); err != nil {
  236. return fmt.Errorf("do migrate: %v", err)
  237. }
  238. currentVersion.Version = v + int64(i) + 1
  239. if _, err = x.ID(1).Update(currentVersion); err != nil {
  240. return err
  241. }
  242. }
  243. return nil
  244. }
  245. func dropTableColumns(sess *xorm.Session, tableName string, columnNames ...string) (err error) {
  246. if tableName == "" || len(columnNames) == 0 {
  247. return nil
  248. }
  249. switch {
  250. case setting.UseSQLite3:
  251. log.Warn("Unable to drop columns in SQLite")
  252. case setting.UseMySQL, setting.UseTiDB, setting.UsePostgreSQL:
  253. cols := ""
  254. for _, col := range columnNames {
  255. if cols != "" {
  256. cols += ", "
  257. }
  258. cols += "DROP COLUMN `" + col + "`"
  259. }
  260. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` %s", tableName, cols)); err != nil {
  261. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  262. }
  263. case setting.UseMSSQL:
  264. cols := ""
  265. for _, col := range columnNames {
  266. if cols != "" {
  267. cols += ", "
  268. }
  269. cols += "`" + strings.ToLower(col) + "`"
  270. }
  271. sql := fmt.Sprintf("SELECT Name FROM SYS.DEFAULT_CONSTRAINTS WHERE PARENT_OBJECT_ID = OBJECT_ID('%[1]s') AND PARENT_COLUMN_ID IN (SELECT column_id FROM sys.columns WHERE lower(NAME) IN (%[2]s) AND object_id = OBJECT_ID('%[1]s'))",
  272. tableName, strings.Replace(cols, "`", "'", -1))
  273. constraints := make([]string, 0)
  274. if err := sess.SQL(sql).Find(&constraints); err != nil {
  275. sess.Rollback()
  276. return fmt.Errorf("Find constraints: %v", err)
  277. }
  278. for _, constraint := range constraints {
  279. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` DROP CONSTRAINT `%s`", tableName, constraint)); err != nil {
  280. sess.Rollback()
  281. return fmt.Errorf("Drop table `%s` constraint `%s`: %v", tableName, constraint, err)
  282. }
  283. }
  284. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` DROP COLUMN %s", tableName, cols)); err != nil {
  285. sess.Rollback()
  286. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  287. }
  288. return sess.Commit()
  289. default:
  290. log.Fatal(4, "Unrecognized DB")
  291. }
  292. return nil
  293. }
  294. func fixLocaleFileLoadPanic(_ *xorm.Engine) error {
  295. cfg, err := ini.Load(setting.CustomConf)
  296. if err != nil {
  297. return fmt.Errorf("load custom config: %v", err)
  298. }
  299. cfg.DeleteSection("i18n")
  300. if err = cfg.SaveTo(setting.CustomConf); err != nil {
  301. return fmt.Errorf("save custom config: %v", err)
  302. }
  303. setting.Langs = strings.Split(strings.Replace(strings.Join(setting.Langs, ","), "fr-CA", "fr-FR", 1), ",")
  304. return nil
  305. }
  306. func trimCommitActionAppURLPrefix(x *xorm.Engine) error {
  307. type PushCommit struct {
  308. Sha1 string
  309. Message string
  310. AuthorEmail string
  311. AuthorName string
  312. }
  313. type PushCommits struct {
  314. Len int
  315. Commits []*PushCommit
  316. CompareURL string `json:"CompareUrl"`
  317. }
  318. type Action struct {
  319. ID int64 `xorm:"pk autoincr"`
  320. Content string `xorm:"TEXT"`
  321. }
  322. results, err := x.Query("SELECT `id`,`content` FROM `action` WHERE `op_type`=?", 5)
  323. if err != nil {
  324. return fmt.Errorf("select commit actions: %v", err)
  325. }
  326. sess := x.NewSession()
  327. defer sess.Close()
  328. if err = sess.Begin(); err != nil {
  329. return err
  330. }
  331. var pushCommits *PushCommits
  332. for _, action := range results {
  333. actID := com.StrTo(string(action["id"])).MustInt64()
  334. if actID == 0 {
  335. continue
  336. }
  337. pushCommits = new(PushCommits)
  338. if err = json.Unmarshal(action["content"], pushCommits); err != nil {
  339. return fmt.Errorf("unmarshal action content[%d]: %v", actID, err)
  340. }
  341. infos := strings.Split(pushCommits.CompareURL, "/")
  342. if len(infos) <= 4 {
  343. continue
  344. }
  345. pushCommits.CompareURL = strings.Join(infos[len(infos)-4:], "/")
  346. p, err := json.Marshal(pushCommits)
  347. if err != nil {
  348. return fmt.Errorf("marshal action content[%d]: %v", actID, err)
  349. }
  350. if _, err = sess.Id(actID).Update(&Action{
  351. Content: string(p),
  352. }); err != nil {
  353. return fmt.Errorf("update action[%d]: %v", actID, err)
  354. }
  355. }
  356. return sess.Commit()
  357. }
  358. func issueToIssueLabel(x *xorm.Engine) error {
  359. type IssueLabel struct {
  360. ID int64 `xorm:"pk autoincr"`
  361. IssueID int64 `xorm:"UNIQUE(s)"`
  362. LabelID int64 `xorm:"UNIQUE(s)"`
  363. }
  364. issueLabels := make([]*IssueLabel, 0, 50)
  365. results, err := x.Query("SELECT `id`,`label_ids` FROM `issue`")
  366. if err != nil {
  367. if strings.Contains(err.Error(), "no such column") ||
  368. strings.Contains(err.Error(), "Unknown column") {
  369. return nil
  370. }
  371. return fmt.Errorf("select issues: %v", err)
  372. }
  373. for _, issue := range results {
  374. issueID := com.StrTo(issue["id"]).MustInt64()
  375. // Just in case legacy code can have duplicated IDs for same label.
  376. mark := make(map[int64]bool)
  377. for _, idStr := range strings.Split(string(issue["label_ids"]), "|") {
  378. labelID := com.StrTo(strings.TrimPrefix(idStr, "$")).MustInt64()
  379. if labelID == 0 || mark[labelID] {
  380. continue
  381. }
  382. mark[labelID] = true
  383. issueLabels = append(issueLabels, &IssueLabel{
  384. IssueID: issueID,
  385. LabelID: labelID,
  386. })
  387. }
  388. }
  389. sess := x.NewSession()
  390. defer sess.Close()
  391. if err = sess.Begin(); err != nil {
  392. return err
  393. }
  394. if err = sess.Sync2(new(IssueLabel)); err != nil {
  395. return fmt.Errorf("Sync2: %v", err)
  396. } else if _, err = sess.Insert(issueLabels); err != nil {
  397. return fmt.Errorf("insert issue-labels: %v", err)
  398. }
  399. return sess.Commit()
  400. }
  401. func attachmentRefactor(x *xorm.Engine) error {
  402. type Attachment struct {
  403. ID int64 `xorm:"pk autoincr"`
  404. UUID string `xorm:"uuid INDEX"`
  405. // For rename purpose.
  406. Path string `xorm:"-"`
  407. NewPath string `xorm:"-"`
  408. }
  409. results, err := x.Query("SELECT * FROM `attachment`")
  410. if err != nil {
  411. return fmt.Errorf("select attachments: %v", err)
  412. }
  413. attachments := make([]*Attachment, 0, len(results))
  414. for _, attach := range results {
  415. if !com.IsExist(string(attach["path"])) {
  416. // If the attachment is already missing, there is no point to update it.
  417. continue
  418. }
  419. attachments = append(attachments, &Attachment{
  420. ID: com.StrTo(attach["id"]).MustInt64(),
  421. UUID: gouuid.NewV4().String(),
  422. Path: string(attach["path"]),
  423. })
  424. }
  425. sess := x.NewSession()
  426. defer sess.Close()
  427. if err = sess.Begin(); err != nil {
  428. return err
  429. }
  430. if err = sess.Sync2(new(Attachment)); err != nil {
  431. return fmt.Errorf("Sync2: %v", err)
  432. }
  433. // Note: Roll back for rename can be a dead loop,
  434. // so produces a backup file.
  435. var buf bytes.Buffer
  436. buf.WriteString("# old path -> new path\n")
  437. // Update database first because this is where error happens the most often.
  438. for _, attach := range attachments {
  439. if _, err = sess.Id(attach.ID).Update(attach); err != nil {
  440. return err
  441. }
  442. attach.NewPath = path.Join(setting.AttachmentPath, attach.UUID[0:1], attach.UUID[1:2], attach.UUID)
  443. buf.WriteString(attach.Path)
  444. buf.WriteString("\t")
  445. buf.WriteString(attach.NewPath)
  446. buf.WriteString("\n")
  447. }
  448. // Then rename attachments.
  449. isSucceed := true
  450. defer func() {
  451. if isSucceed {
  452. return
  453. }
  454. dumpPath := path.Join(setting.LogRootPath, "attachment_path.dump")
  455. ioutil.WriteFile(dumpPath, buf.Bytes(), 0666)
  456. log.Info("Failed to rename some attachments, old and new paths are saved into: %s", dumpPath)
  457. }()
  458. for _, attach := range attachments {
  459. if err = os.MkdirAll(path.Dir(attach.NewPath), os.ModePerm); err != nil {
  460. isSucceed = false
  461. return err
  462. }
  463. if err = os.Rename(attach.Path, attach.NewPath); err != nil {
  464. isSucceed = false
  465. return err
  466. }
  467. }
  468. return sess.Commit()
  469. }
  470. func renamePullRequestFields(x *xorm.Engine) (err error) {
  471. type PullRequest struct {
  472. ID int64 `xorm:"pk autoincr"`
  473. PullID int64 `xorm:"INDEX"`
  474. PullIndex int64
  475. HeadBarcnh string
  476. IssueID int64 `xorm:"INDEX"`
  477. Index int64
  478. HeadBranch string
  479. }
  480. if err = x.Sync(new(PullRequest)); err != nil {
  481. return fmt.Errorf("sync: %v", err)
  482. }
  483. results, err := x.Query("SELECT `id`,`pull_id`,`pull_index`,`head_barcnh` FROM `pull_request`")
  484. if err != nil {
  485. if strings.Contains(err.Error(), "no such column") {
  486. return nil
  487. }
  488. return fmt.Errorf("select pull requests: %v", err)
  489. }
  490. sess := x.NewSession()
  491. defer sess.Close()
  492. if err = sess.Begin(); err != nil {
  493. return err
  494. }
  495. var pull *PullRequest
  496. for _, pr := range results {
  497. pull = &PullRequest{
  498. ID: com.StrTo(pr["id"]).MustInt64(),
  499. IssueID: com.StrTo(pr["pull_id"]).MustInt64(),
  500. Index: com.StrTo(pr["pull_index"]).MustInt64(),
  501. HeadBranch: string(pr["head_barcnh"]),
  502. }
  503. if pull.Index == 0 {
  504. continue
  505. }
  506. if _, err = sess.Id(pull.ID).Update(pull); err != nil {
  507. return err
  508. }
  509. }
  510. return sess.Commit()
  511. }
  512. func cleanUpMigrateRepoInfo(x *xorm.Engine) (err error) {
  513. type (
  514. User struct {
  515. ID int64 `xorm:"pk autoincr"`
  516. LowerName string
  517. }
  518. Repository struct {
  519. ID int64 `xorm:"pk autoincr"`
  520. OwnerID int64
  521. LowerName string
  522. }
  523. )
  524. repos := make([]*Repository, 0, 25)
  525. if err = x.Where("is_mirror=?", false).Find(&repos); err != nil {
  526. return fmt.Errorf("select all non-mirror repositories: %v", err)
  527. }
  528. var user *User
  529. for _, repo := range repos {
  530. user = &User{ID: repo.OwnerID}
  531. has, err := x.Get(user)
  532. if err != nil {
  533. return fmt.Errorf("get owner of repository[%d - %d]: %v", repo.ID, repo.OwnerID, err)
  534. } else if !has {
  535. continue
  536. }
  537. configPath := filepath.Join(setting.RepoRootPath, user.LowerName, repo.LowerName+".git/config")
  538. // In case repository file is somehow missing.
  539. if !com.IsFile(configPath) {
  540. continue
  541. }
  542. cfg, err := ini.Load(configPath)
  543. if err != nil {
  544. return fmt.Errorf("open config file: %v", err)
  545. }
  546. cfg.DeleteSection("remote \"origin\"")
  547. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  548. return fmt.Errorf("save config file: %v", err)
  549. }
  550. }
  551. return nil
  552. }
  553. func generateOrgRandsAndSalt(x *xorm.Engine) (err error) {
  554. type User struct {
  555. ID int64 `xorm:"pk autoincr"`
  556. Rands string `xorm:"VARCHAR(10)"`
  557. Salt string `xorm:"VARCHAR(10)"`
  558. }
  559. orgs := make([]*User, 0, 10)
  560. if err = x.Where("type=1").And("rands=''").Find(&orgs); err != nil {
  561. return fmt.Errorf("select all organizations: %v", err)
  562. }
  563. sess := x.NewSession()
  564. defer sess.Close()
  565. if err = sess.Begin(); err != nil {
  566. return err
  567. }
  568. for _, org := range orgs {
  569. if org.Rands, err = generate.GetRandomString(10); err != nil {
  570. return err
  571. }
  572. if org.Salt, err = generate.GetRandomString(10); err != nil {
  573. return err
  574. }
  575. if _, err = sess.Id(org.ID).Update(org); err != nil {
  576. return err
  577. }
  578. }
  579. return sess.Commit()
  580. }
  581. // TAction defines the struct for migrating table action
  582. type TAction struct {
  583. ID int64 `xorm:"pk autoincr"`
  584. CreatedUnix int64
  585. }
  586. // TableName will be invoked by XORM to customrize the table name
  587. func (t *TAction) TableName() string { return "action" }
  588. // TNotice defines the struct for migrating table notice
  589. type TNotice struct {
  590. ID int64 `xorm:"pk autoincr"`
  591. CreatedUnix int64
  592. }
  593. // TableName will be invoked by XORM to customrize the table name
  594. func (t *TNotice) TableName() string { return "notice" }
  595. // TComment defines the struct for migrating table comment
  596. type TComment struct {
  597. ID int64 `xorm:"pk autoincr"`
  598. CreatedUnix int64
  599. }
  600. // TableName will be invoked by XORM to customrize the table name
  601. func (t *TComment) TableName() string { return "comment" }
  602. // TIssue defines the struct for migrating table issue
  603. type TIssue struct {
  604. ID int64 `xorm:"pk autoincr"`
  605. DeadlineUnix int64
  606. CreatedUnix int64
  607. UpdatedUnix int64
  608. }
  609. // TableName will be invoked by XORM to customrize the table name
  610. func (t *TIssue) TableName() string { return "issue" }
  611. // TMilestone defines the struct for migrating table milestone
  612. type TMilestone struct {
  613. ID int64 `xorm:"pk autoincr"`
  614. DeadlineUnix int64
  615. ClosedDateUnix int64
  616. }
  617. // TableName will be invoked by XORM to customrize the table name
  618. func (t *TMilestone) TableName() string { return "milestone" }
  619. // TAttachment defines the struct for migrating table attachment
  620. type TAttachment struct {
  621. ID int64 `xorm:"pk autoincr"`
  622. CreatedUnix int64
  623. }
  624. // TableName will be invoked by XORM to customrize the table name
  625. func (t *TAttachment) TableName() string { return "attachment" }
  626. // TLoginSource defines the struct for migrating table login_source
  627. type TLoginSource struct {
  628. ID int64 `xorm:"pk autoincr"`
  629. CreatedUnix int64
  630. UpdatedUnix int64
  631. }
  632. // TableName will be invoked by XORM to customrize the table name
  633. func (t *TLoginSource) TableName() string { return "login_source" }
  634. // TPull defines the struct for migrating table pull_request
  635. type TPull struct {
  636. ID int64 `xorm:"pk autoincr"`
  637. MergedUnix int64
  638. }
  639. // TableName will be invoked by XORM to customrize the table name
  640. func (t *TPull) TableName() string { return "pull_request" }
  641. // TRelease defines the struct for migrating table release
  642. type TRelease struct {
  643. ID int64 `xorm:"pk autoincr"`
  644. CreatedUnix int64
  645. }
  646. // TableName will be invoked by XORM to customrize the table name
  647. func (t *TRelease) TableName() string { return "release" }
  648. // TRepo defines the struct for migrating table repository
  649. type TRepo struct {
  650. ID int64 `xorm:"pk autoincr"`
  651. CreatedUnix int64
  652. UpdatedUnix int64
  653. }
  654. // TableName will be invoked by XORM to customrize the table name
  655. func (t *TRepo) TableName() string { return "repository" }
  656. // TMirror defines the struct for migrating table mirror
  657. type TMirror struct {
  658. ID int64 `xorm:"pk autoincr"`
  659. UpdatedUnix int64
  660. NextUpdateUnix int64
  661. }
  662. // TableName will be invoked by XORM to customrize the table name
  663. func (t *TMirror) TableName() string { return "mirror" }
  664. // TPublicKey defines the struct for migrating table public_key
  665. type TPublicKey struct {
  666. ID int64 `xorm:"pk autoincr"`
  667. CreatedUnix int64
  668. UpdatedUnix int64
  669. }
  670. // TableName will be invoked by XORM to customrize the table name
  671. func (t *TPublicKey) TableName() string { return "public_key" }
  672. // TDeployKey defines the struct for migrating table deploy_key
  673. type TDeployKey struct {
  674. ID int64 `xorm:"pk autoincr"`
  675. CreatedUnix int64
  676. UpdatedUnix int64
  677. }
  678. // TableName will be invoked by XORM to customrize the table name
  679. func (t *TDeployKey) TableName() string { return "deploy_key" }
  680. // TAccessToken defines the struct for migrating table access_token
  681. type TAccessToken struct {
  682. ID int64 `xorm:"pk autoincr"`
  683. CreatedUnix int64
  684. UpdatedUnix int64
  685. }
  686. // TableName will be invoked by XORM to customrize the table name
  687. func (t *TAccessToken) TableName() string { return "access_token" }
  688. // TUser defines the struct for migrating table user
  689. type TUser struct {
  690. ID int64 `xorm:"pk autoincr"`
  691. CreatedUnix int64
  692. UpdatedUnix int64
  693. }
  694. // TableName will be invoked by XORM to customrize the table name
  695. func (t *TUser) TableName() string { return "user" }
  696. // TWebhook defines the struct for migrating table webhook
  697. type TWebhook struct {
  698. ID int64 `xorm:"pk autoincr"`
  699. CreatedUnix int64
  700. UpdatedUnix int64
  701. }
  702. // TableName will be invoked by XORM to customrize the table name
  703. func (t *TWebhook) TableName() string { return "webhook" }
  704. func convertDateToUnix(x *xorm.Engine) (err error) {
  705. log.Info("This migration could take up to minutes, please be patient.")
  706. type Bean struct {
  707. ID int64 `xorm:"pk autoincr"`
  708. Created time.Time
  709. Updated time.Time
  710. Merged time.Time
  711. Deadline time.Time
  712. ClosedDate time.Time
  713. NextUpdate time.Time
  714. }
  715. var tables = []struct {
  716. name string
  717. cols []string
  718. bean interface{}
  719. }{
  720. {"action", []string{"created"}, new(TAction)},
  721. {"notice", []string{"created"}, new(TNotice)},
  722. {"comment", []string{"created"}, new(TComment)},
  723. {"issue", []string{"deadline", "created", "updated"}, new(TIssue)},
  724. {"milestone", []string{"deadline", "closed_date"}, new(TMilestone)},
  725. {"attachment", []string{"created"}, new(TAttachment)},
  726. {"login_source", []string{"created", "updated"}, new(TLoginSource)},
  727. {"pull_request", []string{"merged"}, new(TPull)},
  728. {"release", []string{"created"}, new(TRelease)},
  729. {"repository", []string{"created", "updated"}, new(TRepo)},
  730. {"mirror", []string{"updated", "next_update"}, new(TMirror)},
  731. {"public_key", []string{"created", "updated"}, new(TPublicKey)},
  732. {"deploy_key", []string{"created", "updated"}, new(TDeployKey)},
  733. {"access_token", []string{"created", "updated"}, new(TAccessToken)},
  734. {"user", []string{"created", "updated"}, new(TUser)},
  735. {"webhook", []string{"created", "updated"}, new(TWebhook)},
  736. }
  737. for _, table := range tables {
  738. log.Info("Converting table: %s", table.name)
  739. if err = x.Sync2(table.bean); err != nil {
  740. return fmt.Errorf("Sync [table: %s]: %v", table.name, err)
  741. }
  742. offset := 0
  743. for {
  744. beans := make([]*Bean, 0, 100)
  745. if err = x.Table(table.name).Asc("id").Limit(100, offset).Find(&beans); err != nil {
  746. return fmt.Errorf("select beans [table: %s, offset: %d]: %v", table.name, offset, err)
  747. }
  748. log.Trace("Table [%s]: offset: %d, beans: %d", table.name, offset, len(beans))
  749. if len(beans) == 0 {
  750. break
  751. }
  752. offset += 100
  753. baseSQL := "UPDATE `" + table.name + "` SET "
  754. for _, bean := range beans {
  755. valSQLs := make([]string, 0, len(table.cols))
  756. for _, col := range table.cols {
  757. fieldSQL := ""
  758. fieldSQL += col + "_unix = "
  759. switch col {
  760. case "deadline":
  761. if bean.Deadline.IsZero() {
  762. continue
  763. }
  764. fieldSQL += com.ToStr(bean.Deadline.Unix())
  765. case "created":
  766. fieldSQL += com.ToStr(bean.Created.Unix())
  767. case "updated":
  768. fieldSQL += com.ToStr(bean.Updated.Unix())
  769. case "closed_date":
  770. fieldSQL += com.ToStr(bean.ClosedDate.Unix())
  771. case "merged":
  772. fieldSQL += com.ToStr(bean.Merged.Unix())
  773. case "next_update":
  774. fieldSQL += com.ToStr(bean.NextUpdate.Unix())
  775. }
  776. valSQLs = append(valSQLs, fieldSQL)
  777. }
  778. if len(valSQLs) == 0 {
  779. continue
  780. }
  781. if _, err = x.Exec(baseSQL + strings.Join(valSQLs, ",") + " WHERE id = " + com.ToStr(bean.ID)); err != nil {
  782. return fmt.Errorf("update bean [table: %s, id: %d]: %v", table.name, bean.ID, err)
  783. }
  784. }
  785. }
  786. }
  787. return nil
  788. }