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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. "fmt"
  8. "regexp"
  9. "strings"
  10. "code.gitea.io/gitea/modules/log"
  11. "code.gitea.io/gitea/modules/setting"
  12. "xorm.io/xorm"
  13. )
  14. const minDBVersion = 70 // Gitea 1.5.3
  15. // Migration describes on migration from lower version to high version
  16. type Migration interface {
  17. Description() string
  18. Migrate(*xorm.Engine) error
  19. }
  20. type migration struct {
  21. description string
  22. migrate func(*xorm.Engine) error
  23. }
  24. // NewMigration creates a new migration
  25. func NewMigration(desc string, fn func(*xorm.Engine) error) Migration {
  26. return &migration{desc, fn}
  27. }
  28. // Description returns the migration's description
  29. func (m *migration) Description() string {
  30. return m.description
  31. }
  32. // Migrate executes the migration
  33. func (m *migration) Migrate(x *xorm.Engine) error {
  34. return m.migrate(x)
  35. }
  36. // Version describes the version table. Should have only one row with id==1
  37. type Version struct {
  38. ID int64 `xorm:"pk autoincr"`
  39. Version int64
  40. }
  41. // This is a sequence of migrations. Add new migrations to the bottom of the list.
  42. // If you want to "retire" a migration, remove it from the top of the list and
  43. // update minDBVersion accordingly
  44. var migrations = []Migration{
  45. // Gitea 1.5.3 ends at v70
  46. // v70 -> v71
  47. NewMigration("add issue_dependencies", addIssueDependencies),
  48. // v71 -> v72
  49. NewMigration("protect each scratch token", addScratchHash),
  50. // v72 -> v73
  51. NewMigration("add review", addReview),
  52. // Gitea 1.6.4 ends at v73
  53. // v73 -> v74
  54. NewMigration("add must_change_password column for users table", addMustChangePassword),
  55. // v74 -> v75
  56. NewMigration("add approval whitelists to protected branches", addApprovalWhitelistsToProtectedBranches),
  57. // v75 -> v76
  58. NewMigration("clear nonused data which not deleted when user was deleted", clearNonusedData),
  59. // Gitea 1.7.6 ends at v76
  60. // v76 -> v77
  61. NewMigration("add pull request rebase with merge commit", addPullRequestRebaseWithMerge),
  62. // v77 -> v78
  63. NewMigration("add theme to users", addUserDefaultTheme),
  64. // v78 -> v79
  65. NewMigration("rename repo is_bare to repo is_empty", renameRepoIsBareToIsEmpty),
  66. // v79 -> v80
  67. NewMigration("add can close issues via commit in any branch", addCanCloseIssuesViaCommitInAnyBranch),
  68. // v80 -> v81
  69. NewMigration("add is locked to issues", addIsLockedToIssues),
  70. // v81 -> v82
  71. NewMigration("update U2F counter type", changeU2FCounterType),
  72. // Gitea 1.8.3 ends at v82
  73. // v82 -> v83
  74. NewMigration("hot fix for wrong release sha1 on release table", fixReleaseSha1OnReleaseTable),
  75. // v83 -> v84
  76. NewMigration("add uploader id for table attachment", addUploaderIDForAttachment),
  77. // v84 -> v85
  78. NewMigration("add table to store original imported gpg keys", addGPGKeyImport),
  79. // v85 -> v86
  80. NewMigration("hash application token", hashAppToken),
  81. // v86 -> v87
  82. NewMigration("add http method to webhook", addHTTPMethodToWebhook),
  83. // v87 -> v88
  84. NewMigration("add avatar field to repository", addAvatarFieldToRepository),
  85. // Gitea 1.9.6 ends at v88
  86. // v88 -> v89
  87. NewMigration("add commit status context field to commit_status", addCommitStatusContext),
  88. // v89 -> v90
  89. NewMigration("add original author/url migration info to issues, comments, and repo ", addOriginalMigrationInfo),
  90. // v90 -> v91
  91. NewMigration("change length of some repository columns", changeSomeColumnsLengthOfRepo),
  92. // v91 -> v92
  93. NewMigration("add index on owner_id of repository and type, review_id of comment", addIndexOnRepositoryAndComment),
  94. // v92 -> v93
  95. NewMigration("remove orphaned repository index statuses", removeLingeringIndexStatus),
  96. // v93 -> v94
  97. NewMigration("add email notification enabled preference to user", addEmailNotificationEnabledToUser),
  98. // v94 -> v95
  99. NewMigration("add enable_status_check, status_check_contexts to protected_branch", addStatusCheckColumnsForProtectedBranches),
  100. // v95 -> v96
  101. NewMigration("add table columns for cross referencing issues", addCrossReferenceColumns),
  102. // v96 -> v97
  103. NewMigration("delete orphaned attachments", deleteOrphanedAttachments),
  104. // v97 -> v98
  105. NewMigration("add repo_admin_change_team_access to user", addRepoAdminChangeTeamAccessColumnForUser),
  106. // v98 -> v99
  107. NewMigration("add original author name and id on migrated release", addOriginalAuthorOnMigratedReleases),
  108. // Gitea 1.10.3 ends at v99
  109. // v99 -> v100
  110. NewMigration("add task table and status column for repository table", addTaskTable),
  111. // v100 -> v101
  112. NewMigration("update migration repositories' service type", updateMigrationServiceTypes),
  113. // v101 -> v102
  114. NewMigration("change length of some external login users columns", changeSomeColumnsLengthOfExternalLoginUser),
  115. // v102 -> v103
  116. NewMigration("update migration repositories' service type", dropColumnHeadUserNameOnPullRequest),
  117. // v103 -> v104
  118. NewMigration("Add WhitelistDeployKeys to protected branch", addWhitelistDeployKeysToBranches),
  119. // v104 -> v105
  120. NewMigration("remove unnecessary columns from label", removeLabelUneededCols),
  121. // v105 -> v106
  122. NewMigration("add includes_all_repositories to teams", addTeamIncludesAllRepositories),
  123. // v106 -> v107
  124. NewMigration("add column `mode` to table watch", addModeColumnToWatch),
  125. // v107 -> v108
  126. NewMigration("Add template options to repository", addTemplateToRepo),
  127. // v108 -> v109
  128. NewMigration("Add comment_id on table notification", addCommentIDOnNotification),
  129. // v109 -> v110
  130. NewMigration("add can_create_org_repo to team", addCanCreateOrgRepoColumnForTeam),
  131. // v110 -> v111
  132. NewMigration("change review content type to text", changeReviewContentToText),
  133. // v111 -> v112
  134. NewMigration("update branch protection for can push and whitelist enable", addBranchProtectionCanPushAndEnableWhitelist),
  135. // v112 -> v113
  136. NewMigration("remove release attachments which repository deleted", removeAttachmentMissedRepo),
  137. // v113 -> v114
  138. NewMigration("new feature: change target branch of pull requests", featureChangeTargetBranch),
  139. // v114 -> v115
  140. NewMigration("Remove authentication credentials from stored URL", sanitizeOriginalURL),
  141. // v115 -> v116
  142. NewMigration("add user_id prefix to existing user avatar name", renameExistingUserAvatarName),
  143. // v116 -> v117
  144. NewMigration("Extend TrackedTimes", extendTrackedTimes),
  145. // v117 -> v118
  146. NewMigration("Add block on rejected reviews branch protection", addBlockOnRejectedReviews),
  147. // v118 -> v119
  148. NewMigration("Add commit id and stale to reviews", addReviewCommitAndStale),
  149. // v119 -> v120
  150. NewMigration("Fix migrated repositories' git service type", fixMigratedRepositoryServiceType),
  151. // v120 -> v121
  152. NewMigration("Add owner_name on table repository", addOwnerNameOnRepository),
  153. // v121 -> v122
  154. NewMigration("add is_restricted column for users table", addIsRestricted),
  155. // v122 -> v123
  156. NewMigration("Add Require Signed Commits to ProtectedBranch", addRequireSignedCommits),
  157. // v123 -> v124
  158. NewMigration("Add original informations for reactions", addReactionOriginals),
  159. // v124 -> v125
  160. NewMigration("Add columns to user and repository", addUserRepoMissingColumns),
  161. // v125 -> v126
  162. NewMigration("Add some columns on review for migration", addReviewMigrateInfo),
  163. // v126 -> v127
  164. NewMigration("Fix topic repository count", fixTopicRepositoryCount),
  165. // v127 -> v128
  166. NewMigration("add repository code language statistics", addLanguageStats),
  167. // v128 -> v129
  168. NewMigration("fix merge base for pull requests", fixMergeBase),
  169. // v129 -> v130
  170. NewMigration("remove dependencies from deleted repositories", purgeUnusedDependencies),
  171. // v130 -> v131
  172. NewMigration("Expand webhooks for more granularity", expandWebhooks),
  173. // v131 -> v132
  174. NewMigration("Add IsSystemWebhook column to webhooks table", addSystemWebhookColumn),
  175. // v132 -> v133
  176. NewMigration("Add Branch Protection Protected Files Column", addBranchProtectionProtectedFilesColumn),
  177. // v133 -> v134
  178. NewMigration("Add EmailHash Table", addEmailHashTable),
  179. // v134 -> v135
  180. NewMigration("Refix merge base for merged pull requests", refixMergeBase),
  181. // v135 -> v136
  182. NewMigration("Add OrgID column to Labels table", addOrgIDLabelColumn),
  183. // v136 -> v137
  184. NewMigration("Add CommitsAhead and CommitsBehind Column to PullRequest Table", addCommitDivergenceToPulls),
  185. // v137 -> v138
  186. NewMigration("Add Branch Protection Block Outdated Branch", addBlockOnOutdatedBranch),
  187. // v138 -> v139
  188. NewMigration("Add ResolveDoerID to Comment table", addResolveDoerIDCommentColumn),
  189. // v139 -> v140
  190. NewMigration("prepend refs/heads/ to issue refs", prependRefsHeadsToIssueRefs),
  191. }
  192. // GetCurrentDBVersion returns the current db version
  193. func GetCurrentDBVersion(x *xorm.Engine) (int64, error) {
  194. if err := x.Sync(new(Version)); err != nil {
  195. return -1, fmt.Errorf("sync: %v", err)
  196. }
  197. currentVersion := &Version{ID: 1}
  198. has, err := x.Get(currentVersion)
  199. if err != nil {
  200. return -1, fmt.Errorf("get: %v", err)
  201. }
  202. if !has {
  203. return -1, nil
  204. }
  205. return currentVersion.Version, nil
  206. }
  207. // ExpectedVersion returns the expected db version
  208. func ExpectedVersion() int64 {
  209. return int64(minDBVersion + len(migrations))
  210. }
  211. // EnsureUpToDate will check if the db is at the correct version
  212. func EnsureUpToDate(x *xorm.Engine) error {
  213. currentDB, err := GetCurrentDBVersion(x)
  214. if err != nil {
  215. return err
  216. }
  217. if currentDB < 0 {
  218. return fmt.Errorf("Database has not been initialised")
  219. }
  220. if minDBVersion > currentDB {
  221. return fmt.Errorf("DB version %d (<= %d) is too old for auto-migration. Upgrade to Gitea 1.6.4 first then upgrade to this version", currentDB, minDBVersion)
  222. }
  223. expected := ExpectedVersion()
  224. if currentDB != expected {
  225. return fmt.Errorf(`Current database version %d is not equal to the expected version %d. Please run "gitea [--config /path/to/app.ini] migrate" to update the database version`, currentDB, expected)
  226. }
  227. return nil
  228. }
  229. // Migrate database to current version
  230. func Migrate(x *xorm.Engine) error {
  231. if err := x.Sync(new(Version)); err != nil {
  232. return fmt.Errorf("sync: %v", err)
  233. }
  234. currentVersion := &Version{ID: 1}
  235. has, err := x.Get(currentVersion)
  236. if err != nil {
  237. return fmt.Errorf("get: %v", err)
  238. } else if !has {
  239. // If the version record does not exist we think
  240. // it is a fresh installation and we can skip all migrations.
  241. currentVersion.ID = 0
  242. currentVersion.Version = int64(minDBVersion + len(migrations))
  243. if _, err = x.InsertOne(currentVersion); err != nil {
  244. return fmt.Errorf("insert: %v", err)
  245. }
  246. }
  247. v := currentVersion.Version
  248. if minDBVersion > v {
  249. log.Fatal(`Gitea no longer supports auto-migration from your previously installed version.
  250. Please try upgrading to a lower version first (suggested v1.6.4), then upgrade to this version.`)
  251. return nil
  252. }
  253. if int(v-minDBVersion) > len(migrations) {
  254. // User downgraded Gitea.
  255. currentVersion.Version = int64(len(migrations) + minDBVersion)
  256. _, err = x.ID(1).Update(currentVersion)
  257. return err
  258. }
  259. for i, m := range migrations[v-minDBVersion:] {
  260. log.Info("Migration[%d]: %s", v+int64(i), m.Description())
  261. if err = m.Migrate(x); err != nil {
  262. return fmt.Errorf("do migrate: %v", err)
  263. }
  264. currentVersion.Version = v + int64(i) + 1
  265. if _, err = x.ID(1).Update(currentVersion); err != nil {
  266. return err
  267. }
  268. }
  269. return nil
  270. }
  271. func dropTableColumns(sess *xorm.Session, tableName string, columnNames ...string) (err error) {
  272. if tableName == "" || len(columnNames) == 0 {
  273. return nil
  274. }
  275. // TODO: This will not work if there are foreign keys
  276. switch {
  277. case setting.Database.UseSQLite3:
  278. // First drop the indexes on the columns
  279. res, errIndex := sess.Query(fmt.Sprintf("PRAGMA index_list(`%s`)", tableName))
  280. if errIndex != nil {
  281. return errIndex
  282. }
  283. for _, row := range res {
  284. indexName := row["name"]
  285. indexRes, err := sess.Query(fmt.Sprintf("PRAGMA index_info(`%s`)", indexName))
  286. if err != nil {
  287. return err
  288. }
  289. if len(indexRes) != 1 {
  290. continue
  291. }
  292. indexColumn := string(indexRes[0]["name"])
  293. for _, name := range columnNames {
  294. if name == indexColumn {
  295. _, err := sess.Exec(fmt.Sprintf("DROP INDEX `%s`", indexName))
  296. if err != nil {
  297. return err
  298. }
  299. }
  300. }
  301. }
  302. // Here we need to get the columns from the original table
  303. sql := fmt.Sprintf("SELECT sql FROM sqlite_master WHERE tbl_name='%s' and type='table'", tableName)
  304. res, err := sess.Query(sql)
  305. if err != nil {
  306. return err
  307. }
  308. tableSQL := string(res[0]["sql"])
  309. // Separate out the column definitions
  310. tableSQL = tableSQL[strings.Index(tableSQL, "("):]
  311. // Remove the required columnNames
  312. for _, name := range columnNames {
  313. tableSQL = regexp.MustCompile(regexp.QuoteMeta("`"+name+"`")+"[^`,)]*?[,)]").ReplaceAllString(tableSQL, "")
  314. }
  315. // Ensure the query is ended properly
  316. tableSQL = strings.TrimSpace(tableSQL)
  317. if tableSQL[len(tableSQL)-1] != ')' {
  318. if tableSQL[len(tableSQL)-1] == ',' {
  319. tableSQL = tableSQL[:len(tableSQL)-1]
  320. }
  321. tableSQL += ")"
  322. }
  323. // Find all the columns in the table
  324. columns := regexp.MustCompile("`([^`]*)`").FindAllString(tableSQL, -1)
  325. tableSQL = fmt.Sprintf("CREATE TABLE `new_%s_new` ", tableName) + tableSQL
  326. if _, err := sess.Exec(tableSQL); err != nil {
  327. return err
  328. }
  329. // Now restore the data
  330. columnsSeparated := strings.Join(columns, ",")
  331. insertSQL := fmt.Sprintf("INSERT INTO `new_%s_new` (%s) SELECT %s FROM %s", tableName, columnsSeparated, columnsSeparated, tableName)
  332. if _, err := sess.Exec(insertSQL); err != nil {
  333. return err
  334. }
  335. // Now drop the old table
  336. if _, err := sess.Exec(fmt.Sprintf("DROP TABLE `%s`", tableName)); err != nil {
  337. return err
  338. }
  339. // Rename the table
  340. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `new_%s_new` RENAME TO `%s`", tableName, tableName)); err != nil {
  341. return err
  342. }
  343. case setting.Database.UsePostgreSQL:
  344. cols := ""
  345. for _, col := range columnNames {
  346. if cols != "" {
  347. cols += ", "
  348. }
  349. cols += "DROP COLUMN `" + col + "` CASCADE"
  350. }
  351. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` %s", tableName, cols)); err != nil {
  352. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  353. }
  354. case setting.Database.UseMySQL:
  355. // Drop indexes on columns first
  356. sql := fmt.Sprintf("SHOW INDEX FROM %s WHERE column_name IN ('%s')", tableName, strings.Join(columnNames, "','"))
  357. res, err := sess.Query(sql)
  358. if err != nil {
  359. return err
  360. }
  361. for _, index := range res {
  362. indexName := index["column_name"]
  363. if len(indexName) > 0 {
  364. _, err := sess.Exec(fmt.Sprintf("DROP INDEX `%s` ON `%s`", indexName, tableName))
  365. if err != nil {
  366. return err
  367. }
  368. }
  369. }
  370. // Now drop the columns
  371. cols := ""
  372. for _, col := range columnNames {
  373. if cols != "" {
  374. cols += ", "
  375. }
  376. cols += "DROP COLUMN `" + col + "`"
  377. }
  378. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` %s", tableName, cols)); err != nil {
  379. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  380. }
  381. case setting.Database.UseMSSQL:
  382. cols := ""
  383. for _, col := range columnNames {
  384. if cols != "" {
  385. cols += ", "
  386. }
  387. cols += "`" + strings.ToLower(col) + "`"
  388. }
  389. 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'))",
  390. tableName, strings.Replace(cols, "`", "'", -1))
  391. constraints := make([]string, 0)
  392. if err := sess.SQL(sql).Find(&constraints); err != nil {
  393. sess.Rollback()
  394. return fmt.Errorf("Find constraints: %v", err)
  395. }
  396. for _, constraint := range constraints {
  397. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` DROP CONSTRAINT `%s`", tableName, constraint)); err != nil {
  398. sess.Rollback()
  399. return fmt.Errorf("Drop table `%s` constraint `%s`: %v", tableName, constraint, err)
  400. }
  401. }
  402. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` DROP COLUMN %s", tableName, cols)); err != nil {
  403. sess.Rollback()
  404. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  405. }
  406. return sess.Commit()
  407. default:
  408. log.Fatal("Unrecognized DB")
  409. }
  410. return nil
  411. }