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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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. // v105 -> v106
  254. NewMigration("add includes_all_repositories to teams", addTeamIncludesAllRepositories),
  255. // v106 -> v107
  256. NewMigration("add column `mode` to table watch", addModeColumnToWatch),
  257. // v107 -> v108
  258. NewMigration("Add template options to repository", addTemplateToRepo),
  259. }
  260. // Migrate database to current version
  261. func Migrate(x *xorm.Engine) error {
  262. if err := x.Sync(new(Version)); err != nil {
  263. return fmt.Errorf("sync: %v", err)
  264. }
  265. currentVersion := &Version{ID: 1}
  266. has, err := x.Get(currentVersion)
  267. if err != nil {
  268. return fmt.Errorf("get: %v", err)
  269. } else if !has {
  270. // If the version record does not exist we think
  271. // it is a fresh installation and we can skip all migrations.
  272. currentVersion.ID = 0
  273. currentVersion.Version = int64(minDBVersion + len(migrations))
  274. if _, err = x.InsertOne(currentVersion); err != nil {
  275. return fmt.Errorf("insert: %v", err)
  276. }
  277. }
  278. v := currentVersion.Version
  279. if minDBVersion > v {
  280. log.Fatal(`Gitea no longer supports auto-migration from your previously installed version.
  281. Please try to upgrade to a lower version (>= v0.6.0) first, then upgrade to current version.`)
  282. return nil
  283. }
  284. if int(v-minDBVersion) > len(migrations) {
  285. // User downgraded Gitea.
  286. currentVersion.Version = int64(len(migrations) + minDBVersion)
  287. _, err = x.ID(1).Update(currentVersion)
  288. return err
  289. }
  290. for i, m := range migrations[v-minDBVersion:] {
  291. log.Info("Migration[%d]: %s", v+int64(i), m.Description())
  292. if err = m.Migrate(x); err != nil {
  293. return fmt.Errorf("do migrate: %v", err)
  294. }
  295. currentVersion.Version = v + int64(i) + 1
  296. if _, err = x.ID(1).Update(currentVersion); err != nil {
  297. return err
  298. }
  299. }
  300. return nil
  301. }
  302. func dropTableColumns(sess *xorm.Session, tableName string, columnNames ...string) (err error) {
  303. if tableName == "" || len(columnNames) == 0 {
  304. return nil
  305. }
  306. // TODO: This will not work if there are foreign keys
  307. switch {
  308. case setting.Database.UseSQLite3:
  309. // First drop the indexes on the columns
  310. res, errIndex := sess.Query(fmt.Sprintf("PRAGMA index_list(`%s`)", tableName))
  311. if errIndex != nil {
  312. return errIndex
  313. }
  314. for _, row := range res {
  315. indexName := row["name"]
  316. indexRes, err := sess.Query(fmt.Sprintf("PRAGMA index_info(`%s`)", indexName))
  317. if err != nil {
  318. return err
  319. }
  320. if len(indexRes) != 1 {
  321. continue
  322. }
  323. indexColumn := string(indexRes[0]["name"])
  324. for _, name := range columnNames {
  325. if name == indexColumn {
  326. _, err := sess.Exec(fmt.Sprintf("DROP INDEX `%s`", indexName))
  327. if err != nil {
  328. return err
  329. }
  330. }
  331. }
  332. }
  333. // Here we need to get the columns from the original table
  334. sql := fmt.Sprintf("SELECT sql FROM sqlite_master WHERE tbl_name='%s' and type='table'", tableName)
  335. res, err := sess.Query(sql)
  336. if err != nil {
  337. return err
  338. }
  339. tableSQL := string(res[0]["sql"])
  340. // Separate out the column definitions
  341. tableSQL = tableSQL[strings.Index(tableSQL, "("):]
  342. // Remove the required columnNames
  343. for _, name := range columnNames {
  344. tableSQL = regexp.MustCompile(regexp.QuoteMeta("`"+name+"`")+"[^`,)]*?[,)]").ReplaceAllString(tableSQL, "")
  345. }
  346. // Ensure the query is ended properly
  347. tableSQL = strings.TrimSpace(tableSQL)
  348. if tableSQL[len(tableSQL)-1] != ')' {
  349. if tableSQL[len(tableSQL)-1] == ',' {
  350. tableSQL = tableSQL[:len(tableSQL)-1]
  351. }
  352. tableSQL += ")"
  353. }
  354. // Find all the columns in the table
  355. columns := regexp.MustCompile("`([^`]*)`").FindAllString(tableSQL, -1)
  356. tableSQL = fmt.Sprintf("CREATE TABLE `new_%s_new` ", tableName) + tableSQL
  357. if _, err := sess.Exec(tableSQL); err != nil {
  358. return err
  359. }
  360. // Now restore the data
  361. columnsSeparated := strings.Join(columns, ",")
  362. insertSQL := fmt.Sprintf("INSERT INTO `new_%s_new` (%s) SELECT %s FROM %s", tableName, columnsSeparated, columnsSeparated, tableName)
  363. if _, err := sess.Exec(insertSQL); err != nil {
  364. return err
  365. }
  366. // Now drop the old table
  367. if _, err := sess.Exec(fmt.Sprintf("DROP TABLE `%s`", tableName)); err != nil {
  368. return err
  369. }
  370. // Rename the table
  371. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `new_%s_new` RENAME TO `%s`", tableName, tableName)); err != nil {
  372. return err
  373. }
  374. case setting.Database.UsePostgreSQL:
  375. cols := ""
  376. for _, col := range columnNames {
  377. if cols != "" {
  378. cols += ", "
  379. }
  380. cols += "DROP COLUMN `" + col + "` CASCADE"
  381. }
  382. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` %s", tableName, cols)); err != nil {
  383. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  384. }
  385. case setting.Database.UseMySQL:
  386. // Drop indexes on columns first
  387. sql := fmt.Sprintf("SHOW INDEX FROM %s WHERE column_name IN ('%s')", tableName, strings.Join(columnNames, "','"))
  388. res, err := sess.Query(sql)
  389. if err != nil {
  390. return err
  391. }
  392. for _, index := range res {
  393. indexName := index["column_name"]
  394. if len(indexName) > 0 {
  395. _, err := sess.Exec(fmt.Sprintf("DROP INDEX `%s` ON `%s`", indexName, tableName))
  396. if err != nil {
  397. return err
  398. }
  399. }
  400. }
  401. // Now drop the columns
  402. cols := ""
  403. for _, col := range columnNames {
  404. if cols != "" {
  405. cols += ", "
  406. }
  407. cols += "DROP COLUMN `" + col + "`"
  408. }
  409. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` %s", tableName, cols)); err != nil {
  410. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  411. }
  412. case setting.Database.UseMSSQL:
  413. cols := ""
  414. for _, col := range columnNames {
  415. if cols != "" {
  416. cols += ", "
  417. }
  418. cols += "`" + strings.ToLower(col) + "`"
  419. }
  420. 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'))",
  421. tableName, strings.Replace(cols, "`", "'", -1))
  422. constraints := make([]string, 0)
  423. if err := sess.SQL(sql).Find(&constraints); err != nil {
  424. sess.Rollback()
  425. return fmt.Errorf("Find constraints: %v", err)
  426. }
  427. for _, constraint := range constraints {
  428. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` DROP CONSTRAINT `%s`", tableName, constraint)); err != nil {
  429. sess.Rollback()
  430. return fmt.Errorf("Drop table `%s` constraint `%s`: %v", tableName, constraint, err)
  431. }
  432. }
  433. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` DROP COLUMN %s", tableName, cols)); err != nil {
  434. sess.Rollback()
  435. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  436. }
  437. return sess.Commit()
  438. default:
  439. log.Fatal("Unrecognized DB")
  440. }
  441. return nil
  442. }
  443. func fixLocaleFileLoadPanic(_ *xorm.Engine) error {
  444. cfg, err := ini.Load(setting.CustomConf)
  445. if err != nil {
  446. return fmt.Errorf("load custom config: %v", err)
  447. }
  448. cfg.DeleteSection("i18n")
  449. if err = cfg.SaveTo(setting.CustomConf); err != nil {
  450. return fmt.Errorf("save custom config: %v", err)
  451. }
  452. setting.Langs = strings.Split(strings.Replace(strings.Join(setting.Langs, ","), "fr-CA", "fr-FR", 1), ",")
  453. return nil
  454. }
  455. func trimCommitActionAppURLPrefix(x *xorm.Engine) error {
  456. type PushCommit struct {
  457. Sha1 string
  458. Message string
  459. AuthorEmail string
  460. AuthorName string
  461. }
  462. type PushCommits struct {
  463. Len int
  464. Commits []*PushCommit
  465. CompareURL string `json:"CompareUrl"`
  466. }
  467. type Action struct {
  468. ID int64 `xorm:"pk autoincr"`
  469. Content string `xorm:"TEXT"`
  470. }
  471. results, err := x.Query("SELECT `id`,`content` FROM `action` WHERE `op_type`=?", 5)
  472. if err != nil {
  473. return fmt.Errorf("select commit actions: %v", err)
  474. }
  475. sess := x.NewSession()
  476. defer sess.Close()
  477. if err = sess.Begin(); err != nil {
  478. return err
  479. }
  480. var pushCommits *PushCommits
  481. for _, action := range results {
  482. actID := com.StrTo(string(action["id"])).MustInt64()
  483. if actID == 0 {
  484. continue
  485. }
  486. pushCommits = new(PushCommits)
  487. if err = json.Unmarshal(action["content"], pushCommits); err != nil {
  488. return fmt.Errorf("unmarshal action content[%d]: %v", actID, err)
  489. }
  490. infos := strings.Split(pushCommits.CompareURL, "/")
  491. if len(infos) <= 4 {
  492. continue
  493. }
  494. pushCommits.CompareURL = strings.Join(infos[len(infos)-4:], "/")
  495. p, err := json.Marshal(pushCommits)
  496. if err != nil {
  497. return fmt.Errorf("marshal action content[%d]: %v", actID, err)
  498. }
  499. if _, err = sess.ID(actID).Update(&Action{
  500. Content: string(p),
  501. }); err != nil {
  502. return fmt.Errorf("update action[%d]: %v", actID, err)
  503. }
  504. }
  505. return sess.Commit()
  506. }
  507. func issueToIssueLabel(x *xorm.Engine) error {
  508. type IssueLabel struct {
  509. ID int64 `xorm:"pk autoincr"`
  510. IssueID int64 `xorm:"UNIQUE(s)"`
  511. LabelID int64 `xorm:"UNIQUE(s)"`
  512. }
  513. issueLabels := make([]*IssueLabel, 0, 50)
  514. results, err := x.Query("SELECT `id`,`label_ids` FROM `issue`")
  515. if err != nil {
  516. if strings.Contains(err.Error(), "no such column") ||
  517. strings.Contains(err.Error(), "Unknown column") {
  518. return nil
  519. }
  520. return fmt.Errorf("select issues: %v", err)
  521. }
  522. for _, issue := range results {
  523. issueID := com.StrTo(issue["id"]).MustInt64()
  524. // Just in case legacy code can have duplicated IDs for same label.
  525. mark := make(map[int64]bool)
  526. for _, idStr := range strings.Split(string(issue["label_ids"]), "|") {
  527. labelID := com.StrTo(strings.TrimPrefix(idStr, "$")).MustInt64()
  528. if labelID == 0 || mark[labelID] {
  529. continue
  530. }
  531. mark[labelID] = true
  532. issueLabels = append(issueLabels, &IssueLabel{
  533. IssueID: issueID,
  534. LabelID: labelID,
  535. })
  536. }
  537. }
  538. sess := x.NewSession()
  539. defer sess.Close()
  540. if err = sess.Begin(); err != nil {
  541. return err
  542. }
  543. if err = sess.Sync2(new(IssueLabel)); err != nil {
  544. return fmt.Errorf("Sync2: %v", err)
  545. } else if _, err = sess.Insert(issueLabels); err != nil {
  546. return fmt.Errorf("insert issue-labels: %v", err)
  547. }
  548. return sess.Commit()
  549. }
  550. func attachmentRefactor(x *xorm.Engine) error {
  551. type Attachment struct {
  552. ID int64 `xorm:"pk autoincr"`
  553. UUID string `xorm:"uuid INDEX"`
  554. // For rename purpose.
  555. Path string `xorm:"-"`
  556. NewPath string `xorm:"-"`
  557. }
  558. results, err := x.Query("SELECT * FROM `attachment`")
  559. if err != nil {
  560. return fmt.Errorf("select attachments: %v", err)
  561. }
  562. attachments := make([]*Attachment, 0, len(results))
  563. for _, attach := range results {
  564. if !com.IsExist(string(attach["path"])) {
  565. // If the attachment is already missing, there is no point to update it.
  566. continue
  567. }
  568. attachments = append(attachments, &Attachment{
  569. ID: com.StrTo(attach["id"]).MustInt64(),
  570. UUID: gouuid.NewV4().String(),
  571. Path: string(attach["path"]),
  572. })
  573. }
  574. sess := x.NewSession()
  575. defer sess.Close()
  576. if err = sess.Begin(); err != nil {
  577. return err
  578. }
  579. if err = sess.Sync2(new(Attachment)); err != nil {
  580. return fmt.Errorf("Sync2: %v", err)
  581. }
  582. // Note: Roll back for rename can be a dead loop,
  583. // so produces a backup file.
  584. var buf bytes.Buffer
  585. buf.WriteString("# old path -> new path\n")
  586. // Update database first because this is where error happens the most often.
  587. for _, attach := range attachments {
  588. if _, err = sess.ID(attach.ID).Update(attach); err != nil {
  589. return err
  590. }
  591. attach.NewPath = path.Join(setting.AttachmentPath, attach.UUID[0:1], attach.UUID[1:2], attach.UUID)
  592. buf.WriteString(attach.Path)
  593. buf.WriteString("\t")
  594. buf.WriteString(attach.NewPath)
  595. buf.WriteString("\n")
  596. }
  597. // Then rename attachments.
  598. isSucceed := true
  599. defer func() {
  600. if isSucceed {
  601. return
  602. }
  603. dumpPath := path.Join(setting.LogRootPath, "attachment_path.dump")
  604. ioutil.WriteFile(dumpPath, buf.Bytes(), 0666)
  605. log.Info("Failed to rename some attachments, old and new paths are saved into: %s", dumpPath)
  606. }()
  607. for _, attach := range attachments {
  608. if err = os.MkdirAll(path.Dir(attach.NewPath), os.ModePerm); err != nil {
  609. isSucceed = false
  610. return err
  611. }
  612. if err = os.Rename(attach.Path, attach.NewPath); err != nil {
  613. isSucceed = false
  614. return err
  615. }
  616. }
  617. return sess.Commit()
  618. }
  619. func renamePullRequestFields(x *xorm.Engine) (err error) {
  620. type PullRequest struct {
  621. ID int64 `xorm:"pk autoincr"`
  622. PullID int64 `xorm:"INDEX"`
  623. PullIndex int64
  624. HeadBarcnh string
  625. IssueID int64 `xorm:"INDEX"`
  626. Index int64
  627. HeadBranch string
  628. }
  629. if err = x.Sync(new(PullRequest)); err != nil {
  630. return fmt.Errorf("sync: %v", err)
  631. }
  632. results, err := x.Query("SELECT `id`,`pull_id`,`pull_index`,`head_barcnh` FROM `pull_request`")
  633. if err != nil {
  634. if strings.Contains(err.Error(), "no such column") {
  635. return nil
  636. }
  637. return fmt.Errorf("select pull requests: %v", err)
  638. }
  639. sess := x.NewSession()
  640. defer sess.Close()
  641. if err = sess.Begin(); err != nil {
  642. return err
  643. }
  644. var pull *PullRequest
  645. for _, pr := range results {
  646. pull = &PullRequest{
  647. ID: com.StrTo(pr["id"]).MustInt64(),
  648. IssueID: com.StrTo(pr["pull_id"]).MustInt64(),
  649. Index: com.StrTo(pr["pull_index"]).MustInt64(),
  650. HeadBranch: string(pr["head_barcnh"]),
  651. }
  652. if pull.Index == 0 {
  653. continue
  654. }
  655. if _, err = sess.ID(pull.ID).Update(pull); err != nil {
  656. return err
  657. }
  658. }
  659. return sess.Commit()
  660. }
  661. func cleanUpMigrateRepoInfo(x *xorm.Engine) (err error) {
  662. type (
  663. User struct {
  664. ID int64 `xorm:"pk autoincr"`
  665. LowerName string
  666. }
  667. Repository struct {
  668. ID int64 `xorm:"pk autoincr"`
  669. OwnerID int64
  670. LowerName string
  671. }
  672. )
  673. repos := make([]*Repository, 0, 25)
  674. if err = x.Where("is_mirror=?", false).Find(&repos); err != nil {
  675. return fmt.Errorf("select all non-mirror repositories: %v", err)
  676. }
  677. var user *User
  678. for _, repo := range repos {
  679. user = &User{ID: repo.OwnerID}
  680. has, err := x.Get(user)
  681. if err != nil {
  682. return fmt.Errorf("get owner of repository[%d - %d]: %v", repo.ID, repo.OwnerID, err)
  683. } else if !has {
  684. continue
  685. }
  686. configPath := filepath.Join(setting.RepoRootPath, user.LowerName, repo.LowerName+".git/config")
  687. // In case repository file is somehow missing.
  688. if !com.IsFile(configPath) {
  689. continue
  690. }
  691. cfg, err := ini.Load(configPath)
  692. if err != nil {
  693. return fmt.Errorf("open config file: %v", err)
  694. }
  695. cfg.DeleteSection("remote \"origin\"")
  696. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  697. return fmt.Errorf("save config file: %v", err)
  698. }
  699. }
  700. return nil
  701. }
  702. func generateOrgRandsAndSalt(x *xorm.Engine) (err error) {
  703. type User struct {
  704. ID int64 `xorm:"pk autoincr"`
  705. Rands string `xorm:"VARCHAR(10)"`
  706. Salt string `xorm:"VARCHAR(10)"`
  707. }
  708. orgs := make([]*User, 0, 10)
  709. if err = x.Where("type=1").And("rands=''").Find(&orgs); err != nil {
  710. return fmt.Errorf("select all organizations: %v", err)
  711. }
  712. sess := x.NewSession()
  713. defer sess.Close()
  714. if err = sess.Begin(); err != nil {
  715. return err
  716. }
  717. for _, org := range orgs {
  718. if org.Rands, err = generate.GetRandomString(10); err != nil {
  719. return err
  720. }
  721. if org.Salt, err = generate.GetRandomString(10); err != nil {
  722. return err
  723. }
  724. if _, err = sess.ID(org.ID).Update(org); err != nil {
  725. return err
  726. }
  727. }
  728. return sess.Commit()
  729. }
  730. // TAction defines the struct for migrating table action
  731. type TAction struct {
  732. ID int64 `xorm:"pk autoincr"`
  733. CreatedUnix int64
  734. }
  735. // TableName will be invoked by XORM to customrize the table name
  736. func (t *TAction) TableName() string { return "action" }
  737. // TNotice defines the struct for migrating table notice
  738. type TNotice struct {
  739. ID int64 `xorm:"pk autoincr"`
  740. CreatedUnix int64
  741. }
  742. // TableName will be invoked by XORM to customrize the table name
  743. func (t *TNotice) TableName() string { return "notice" }
  744. // TComment defines the struct for migrating table comment
  745. type TComment struct {
  746. ID int64 `xorm:"pk autoincr"`
  747. CreatedUnix int64
  748. }
  749. // TableName will be invoked by XORM to customrize the table name
  750. func (t *TComment) TableName() string { return "comment" }
  751. // TIssue defines the struct for migrating table issue
  752. type TIssue struct {
  753. ID int64 `xorm:"pk autoincr"`
  754. DeadlineUnix int64
  755. CreatedUnix int64
  756. UpdatedUnix int64
  757. }
  758. // TableName will be invoked by XORM to customrize the table name
  759. func (t *TIssue) TableName() string { return "issue" }
  760. // TMilestone defines the struct for migrating table milestone
  761. type TMilestone struct {
  762. ID int64 `xorm:"pk autoincr"`
  763. DeadlineUnix int64
  764. ClosedDateUnix int64
  765. }
  766. // TableName will be invoked by XORM to customrize the table name
  767. func (t *TMilestone) TableName() string { return "milestone" }
  768. // TAttachment defines the struct for migrating table attachment
  769. type TAttachment struct {
  770. ID int64 `xorm:"pk autoincr"`
  771. CreatedUnix int64
  772. }
  773. // TableName will be invoked by XORM to customrize the table name
  774. func (t *TAttachment) TableName() string { return "attachment" }
  775. // TLoginSource defines the struct for migrating table login_source
  776. type TLoginSource struct {
  777. ID int64 `xorm:"pk autoincr"`
  778. CreatedUnix int64
  779. UpdatedUnix int64
  780. }
  781. // TableName will be invoked by XORM to customrize the table name
  782. func (t *TLoginSource) TableName() string { return "login_source" }
  783. // TPull defines the struct for migrating table pull_request
  784. type TPull struct {
  785. ID int64 `xorm:"pk autoincr"`
  786. MergedUnix int64
  787. }
  788. // TableName will be invoked by XORM to customrize the table name
  789. func (t *TPull) TableName() string { return "pull_request" }
  790. // TRelease defines the struct for migrating table release
  791. type TRelease struct {
  792. ID int64 `xorm:"pk autoincr"`
  793. CreatedUnix int64
  794. }
  795. // TableName will be invoked by XORM to customrize the table name
  796. func (t *TRelease) TableName() string { return "release" }
  797. // TRepo defines the struct for migrating table repository
  798. type TRepo struct {
  799. ID int64 `xorm:"pk autoincr"`
  800. CreatedUnix int64
  801. UpdatedUnix int64
  802. }
  803. // TableName will be invoked by XORM to customrize the table name
  804. func (t *TRepo) TableName() string { return "repository" }
  805. // TMirror defines the struct for migrating table mirror
  806. type TMirror struct {
  807. ID int64 `xorm:"pk autoincr"`
  808. UpdatedUnix int64
  809. NextUpdateUnix int64
  810. }
  811. // TableName will be invoked by XORM to customrize the table name
  812. func (t *TMirror) TableName() string { return "mirror" }
  813. // TPublicKey defines the struct for migrating table public_key
  814. type TPublicKey struct {
  815. ID int64 `xorm:"pk autoincr"`
  816. CreatedUnix int64
  817. UpdatedUnix int64
  818. }
  819. // TableName will be invoked by XORM to customrize the table name
  820. func (t *TPublicKey) TableName() string { return "public_key" }
  821. // TDeployKey defines the struct for migrating table deploy_key
  822. type TDeployKey struct {
  823. ID int64 `xorm:"pk autoincr"`
  824. CreatedUnix int64
  825. UpdatedUnix int64
  826. }
  827. // TableName will be invoked by XORM to customrize the table name
  828. func (t *TDeployKey) TableName() string { return "deploy_key" }
  829. // TAccessToken defines the struct for migrating table access_token
  830. type TAccessToken struct {
  831. ID int64 `xorm:"pk autoincr"`
  832. CreatedUnix int64
  833. UpdatedUnix int64
  834. }
  835. // TableName will be invoked by XORM to customrize the table name
  836. func (t *TAccessToken) TableName() string { return "access_token" }
  837. // TUser defines the struct for migrating table user
  838. type TUser struct {
  839. ID int64 `xorm:"pk autoincr"`
  840. CreatedUnix int64
  841. UpdatedUnix int64
  842. }
  843. // TableName will be invoked by XORM to customrize the table name
  844. func (t *TUser) TableName() string { return "user" }
  845. // TWebhook defines the struct for migrating table webhook
  846. type TWebhook struct {
  847. ID int64 `xorm:"pk autoincr"`
  848. CreatedUnix int64
  849. UpdatedUnix int64
  850. }
  851. // TableName will be invoked by XORM to customrize the table name
  852. func (t *TWebhook) TableName() string { return "webhook" }
  853. func convertDateToUnix(x *xorm.Engine) (err error) {
  854. log.Info("This migration could take up to minutes, please be patient.")
  855. type Bean struct {
  856. ID int64 `xorm:"pk autoincr"`
  857. Created time.Time
  858. Updated time.Time
  859. Merged time.Time
  860. Deadline time.Time
  861. ClosedDate time.Time
  862. NextUpdate time.Time
  863. }
  864. var tables = []struct {
  865. name string
  866. cols []string
  867. bean interface{}
  868. }{
  869. {"action", []string{"created"}, new(TAction)},
  870. {"notice", []string{"created"}, new(TNotice)},
  871. {"comment", []string{"created"}, new(TComment)},
  872. {"issue", []string{"deadline", "created", "updated"}, new(TIssue)},
  873. {"milestone", []string{"deadline", "closed_date"}, new(TMilestone)},
  874. {"attachment", []string{"created"}, new(TAttachment)},
  875. {"login_source", []string{"created", "updated"}, new(TLoginSource)},
  876. {"pull_request", []string{"merged"}, new(TPull)},
  877. {"release", []string{"created"}, new(TRelease)},
  878. {"repository", []string{"created", "updated"}, new(TRepo)},
  879. {"mirror", []string{"updated", "next_update"}, new(TMirror)},
  880. {"public_key", []string{"created", "updated"}, new(TPublicKey)},
  881. {"deploy_key", []string{"created", "updated"}, new(TDeployKey)},
  882. {"access_token", []string{"created", "updated"}, new(TAccessToken)},
  883. {"user", []string{"created", "updated"}, new(TUser)},
  884. {"webhook", []string{"created", "updated"}, new(TWebhook)},
  885. }
  886. for _, table := range tables {
  887. log.Info("Converting table: %s", table.name)
  888. if err = x.Sync2(table.bean); err != nil {
  889. return fmt.Errorf("Sync [table: %s]: %v", table.name, err)
  890. }
  891. offset := 0
  892. for {
  893. beans := make([]*Bean, 0, 100)
  894. if err = x.Table(table.name).Asc("id").Limit(100, offset).Find(&beans); err != nil {
  895. return fmt.Errorf("select beans [table: %s, offset: %d]: %v", table.name, offset, err)
  896. }
  897. log.Trace("Table [%s]: offset: %d, beans: %d", table.name, offset, len(beans))
  898. if len(beans) == 0 {
  899. break
  900. }
  901. offset += 100
  902. baseSQL := "UPDATE `" + table.name + "` SET "
  903. for _, bean := range beans {
  904. valSQLs := make([]string, 0, len(table.cols))
  905. for _, col := range table.cols {
  906. fieldSQL := ""
  907. fieldSQL += col + "_unix = "
  908. switch col {
  909. case "deadline":
  910. if bean.Deadline.IsZero() {
  911. continue
  912. }
  913. fieldSQL += com.ToStr(bean.Deadline.Unix())
  914. case "created":
  915. fieldSQL += com.ToStr(bean.Created.Unix())
  916. case "updated":
  917. fieldSQL += com.ToStr(bean.Updated.Unix())
  918. case "closed_date":
  919. fieldSQL += com.ToStr(bean.ClosedDate.Unix())
  920. case "merged":
  921. fieldSQL += com.ToStr(bean.Merged.Unix())
  922. case "next_update":
  923. fieldSQL += com.ToStr(bean.NextUpdate.Unix())
  924. }
  925. valSQLs = append(valSQLs, fieldSQL)
  926. }
  927. if len(valSQLs) == 0 {
  928. continue
  929. }
  930. if _, err = x.Exec(baseSQL + strings.Join(valSQLs, ",") + " WHERE id = " + com.ToStr(bean.ID)); err != nil {
  931. return fmt.Errorf("update bean [table: %s, id: %d]: %v", table.name, bean.ID, err)
  932. }
  933. }
  934. }
  935. }
  936. return nil
  937. }