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

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