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

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