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

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