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

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