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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. }
  176. // Migrate database to current version
  177. func Migrate(x *xorm.Engine) error {
  178. if err := x.Sync(new(Version)); err != nil {
  179. return fmt.Errorf("sync: %v", err)
  180. }
  181. currentVersion := &Version{ID: 1}
  182. has, err := x.Get(currentVersion)
  183. if err != nil {
  184. return fmt.Errorf("get: %v", err)
  185. } else if !has {
  186. // If the version record does not exist we think
  187. // it is a fresh installation and we can skip all migrations.
  188. currentVersion.ID = 0
  189. currentVersion.Version = int64(minDBVersion + len(migrations))
  190. if _, err = x.InsertOne(currentVersion); err != nil {
  191. return fmt.Errorf("insert: %v", err)
  192. }
  193. }
  194. v := currentVersion.Version
  195. if minDBVersion > v {
  196. log.Fatal(`Gitea no longer supports auto-migration from your previously installed version.
  197. Please try upgrading to a lower version first (suggested v1.6.4), then upgrade to this version.`)
  198. return nil
  199. }
  200. if int(v-minDBVersion) > len(migrations) {
  201. // User downgraded Gitea.
  202. currentVersion.Version = int64(len(migrations) + minDBVersion)
  203. _, err = x.ID(1).Update(currentVersion)
  204. return err
  205. }
  206. for i, m := range migrations[v-minDBVersion:] {
  207. log.Info("Migration[%d]: %s", v+int64(i), m.Description())
  208. if err = m.Migrate(x); err != nil {
  209. return fmt.Errorf("do migrate: %v", err)
  210. }
  211. currentVersion.Version = v + int64(i) + 1
  212. if _, err = x.ID(1).Update(currentVersion); err != nil {
  213. return err
  214. }
  215. }
  216. return nil
  217. }
  218. func dropTableColumns(sess *xorm.Session, tableName string, columnNames ...string) (err error) {
  219. if tableName == "" || len(columnNames) == 0 {
  220. return nil
  221. }
  222. // TODO: This will not work if there are foreign keys
  223. switch {
  224. case setting.Database.UseSQLite3:
  225. // First drop the indexes on the columns
  226. res, errIndex := sess.Query(fmt.Sprintf("PRAGMA index_list(`%s`)", tableName))
  227. if errIndex != nil {
  228. return errIndex
  229. }
  230. for _, row := range res {
  231. indexName := row["name"]
  232. indexRes, err := sess.Query(fmt.Sprintf("PRAGMA index_info(`%s`)", indexName))
  233. if err != nil {
  234. return err
  235. }
  236. if len(indexRes) != 1 {
  237. continue
  238. }
  239. indexColumn := string(indexRes[0]["name"])
  240. for _, name := range columnNames {
  241. if name == indexColumn {
  242. _, err := sess.Exec(fmt.Sprintf("DROP INDEX `%s`", indexName))
  243. if err != nil {
  244. return err
  245. }
  246. }
  247. }
  248. }
  249. // Here we need to get the columns from the original table
  250. sql := fmt.Sprintf("SELECT sql FROM sqlite_master WHERE tbl_name='%s' and type='table'", tableName)
  251. res, err := sess.Query(sql)
  252. if err != nil {
  253. return err
  254. }
  255. tableSQL := string(res[0]["sql"])
  256. // Separate out the column definitions
  257. tableSQL = tableSQL[strings.Index(tableSQL, "("):]
  258. // Remove the required columnNames
  259. for _, name := range columnNames {
  260. tableSQL = regexp.MustCompile(regexp.QuoteMeta("`"+name+"`")+"[^`,)]*?[,)]").ReplaceAllString(tableSQL, "")
  261. }
  262. // Ensure the query is ended properly
  263. tableSQL = strings.TrimSpace(tableSQL)
  264. if tableSQL[len(tableSQL)-1] != ')' {
  265. if tableSQL[len(tableSQL)-1] == ',' {
  266. tableSQL = tableSQL[:len(tableSQL)-1]
  267. }
  268. tableSQL += ")"
  269. }
  270. // Find all the columns in the table
  271. columns := regexp.MustCompile("`([^`]*)`").FindAllString(tableSQL, -1)
  272. tableSQL = fmt.Sprintf("CREATE TABLE `new_%s_new` ", tableName) + tableSQL
  273. if _, err := sess.Exec(tableSQL); err != nil {
  274. return err
  275. }
  276. // Now restore the data
  277. columnsSeparated := strings.Join(columns, ",")
  278. insertSQL := fmt.Sprintf("INSERT INTO `new_%s_new` (%s) SELECT %s FROM %s", tableName, columnsSeparated, columnsSeparated, tableName)
  279. if _, err := sess.Exec(insertSQL); err != nil {
  280. return err
  281. }
  282. // Now drop the old table
  283. if _, err := sess.Exec(fmt.Sprintf("DROP TABLE `%s`", tableName)); err != nil {
  284. return err
  285. }
  286. // Rename the table
  287. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `new_%s_new` RENAME TO `%s`", tableName, tableName)); err != nil {
  288. return err
  289. }
  290. case setting.Database.UsePostgreSQL:
  291. cols := ""
  292. for _, col := range columnNames {
  293. if cols != "" {
  294. cols += ", "
  295. }
  296. cols += "DROP COLUMN `" + col + "` CASCADE"
  297. }
  298. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` %s", tableName, cols)); err != nil {
  299. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  300. }
  301. case setting.Database.UseMySQL:
  302. // Drop indexes on columns first
  303. sql := fmt.Sprintf("SHOW INDEX FROM %s WHERE column_name IN ('%s')", tableName, strings.Join(columnNames, "','"))
  304. res, err := sess.Query(sql)
  305. if err != nil {
  306. return err
  307. }
  308. for _, index := range res {
  309. indexName := index["column_name"]
  310. if len(indexName) > 0 {
  311. _, err := sess.Exec(fmt.Sprintf("DROP INDEX `%s` ON `%s`", indexName, tableName))
  312. if err != nil {
  313. return err
  314. }
  315. }
  316. }
  317. // Now drop the columns
  318. cols := ""
  319. for _, col := range columnNames {
  320. if cols != "" {
  321. cols += ", "
  322. }
  323. cols += "DROP COLUMN `" + col + "`"
  324. }
  325. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` %s", tableName, cols)); err != nil {
  326. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  327. }
  328. case setting.Database.UseMSSQL:
  329. cols := ""
  330. for _, col := range columnNames {
  331. if cols != "" {
  332. cols += ", "
  333. }
  334. cols += "`" + strings.ToLower(col) + "`"
  335. }
  336. 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'))",
  337. tableName, strings.Replace(cols, "`", "'", -1))
  338. constraints := make([]string, 0)
  339. if err := sess.SQL(sql).Find(&constraints); err != nil {
  340. sess.Rollback()
  341. return fmt.Errorf("Find constraints: %v", err)
  342. }
  343. for _, constraint := range constraints {
  344. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` DROP CONSTRAINT `%s`", tableName, constraint)); err != nil {
  345. sess.Rollback()
  346. return fmt.Errorf("Drop table `%s` constraint `%s`: %v", tableName, constraint, err)
  347. }
  348. }
  349. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` DROP COLUMN %s", tableName, cols)); err != nil {
  350. sess.Rollback()
  351. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  352. }
  353. return sess.Commit()
  354. default:
  355. log.Fatal("Unrecognized DB")
  356. }
  357. return nil
  358. }