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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package migrations
  5. import (
  6. "context"
  7. "fmt"
  8. "code.gitea.io/gitea/models/migrations/v1_10"
  9. "code.gitea.io/gitea/models/migrations/v1_11"
  10. "code.gitea.io/gitea/models/migrations/v1_12"
  11. "code.gitea.io/gitea/models/migrations/v1_13"
  12. "code.gitea.io/gitea/models/migrations/v1_14"
  13. "code.gitea.io/gitea/models/migrations/v1_15"
  14. "code.gitea.io/gitea/models/migrations/v1_16"
  15. "code.gitea.io/gitea/models/migrations/v1_17"
  16. "code.gitea.io/gitea/models/migrations/v1_18"
  17. "code.gitea.io/gitea/models/migrations/v1_19"
  18. "code.gitea.io/gitea/models/migrations/v1_20"
  19. "code.gitea.io/gitea/models/migrations/v1_21"
  20. "code.gitea.io/gitea/models/migrations/v1_22"
  21. "code.gitea.io/gitea/models/migrations/v1_6"
  22. "code.gitea.io/gitea/models/migrations/v1_7"
  23. "code.gitea.io/gitea/models/migrations/v1_8"
  24. "code.gitea.io/gitea/models/migrations/v1_9"
  25. "code.gitea.io/gitea/modules/git"
  26. "code.gitea.io/gitea/modules/log"
  27. "code.gitea.io/gitea/modules/setting"
  28. "xorm.io/xorm"
  29. "xorm.io/xorm/names"
  30. )
  31. const minDBVersion = 70 // Gitea 1.5.3
  32. // Migration describes on migration from lower version to high version
  33. type Migration interface {
  34. Description() string
  35. Migrate(*xorm.Engine) error
  36. }
  37. type migration struct {
  38. description string
  39. migrate func(*xorm.Engine) error
  40. }
  41. // NewMigration creates a new migration
  42. func NewMigration(desc string, fn func(*xorm.Engine) error) Migration {
  43. return &migration{desc, fn}
  44. }
  45. // Description returns the migration's description
  46. func (m *migration) Description() string {
  47. return m.description
  48. }
  49. // Migrate executes the migration
  50. func (m *migration) Migrate(x *xorm.Engine) error {
  51. return m.migrate(x)
  52. }
  53. // Version describes the version table. Should have only one row with id==1
  54. type Version struct {
  55. ID int64 `xorm:"pk autoincr"`
  56. Version int64
  57. }
  58. // Use noopMigration when there is a migration that has been no-oped
  59. var noopMigration = func(_ *xorm.Engine) error { return nil }
  60. // This is a sequence of migrations. Add new migrations to the bottom of the list.
  61. // If you want to "retire" a migration, remove it from the top of the list and
  62. // update minDBVersion accordingly
  63. var migrations = []Migration{
  64. // Gitea 1.5.0 ends at v69
  65. // v70 -> v71
  66. NewMigration("add issue_dependencies", v1_6.AddIssueDependencies),
  67. // v71 -> v72
  68. NewMigration("protect each scratch token", v1_6.AddScratchHash),
  69. // v72 -> v73
  70. NewMigration("add review", v1_6.AddReview),
  71. // Gitea 1.6.0 ends at v73
  72. // v73 -> v74
  73. NewMigration("add must_change_password column for users table", v1_7.AddMustChangePassword),
  74. // v74 -> v75
  75. NewMigration("add approval whitelists to protected branches", v1_7.AddApprovalWhitelistsToProtectedBranches),
  76. // v75 -> v76
  77. NewMigration("clear nonused data which not deleted when user was deleted", v1_7.ClearNonusedData),
  78. // Gitea 1.7.0 ends at v76
  79. // v76 -> v77
  80. NewMigration("add pull request rebase with merge commit", v1_8.AddPullRequestRebaseWithMerge),
  81. // v77 -> v78
  82. NewMigration("add theme to users", v1_8.AddUserDefaultTheme),
  83. // v78 -> v79
  84. NewMigration("rename repo is_bare to repo is_empty", v1_8.RenameRepoIsBareToIsEmpty),
  85. // v79 -> v80
  86. NewMigration("add can close issues via commit in any branch", v1_8.AddCanCloseIssuesViaCommitInAnyBranch),
  87. // v80 -> v81
  88. NewMigration("add is locked to issues", v1_8.AddIsLockedToIssues),
  89. // v81 -> v82
  90. NewMigration("update U2F counter type", v1_8.ChangeU2FCounterType),
  91. // Gitea 1.8.0 ends at v82
  92. // v82 -> v83
  93. NewMigration("hot fix for wrong release sha1 on release table", v1_9.FixReleaseSha1OnReleaseTable),
  94. // v83 -> v84
  95. NewMigration("add uploader id for table attachment", v1_9.AddUploaderIDForAttachment),
  96. // v84 -> v85
  97. NewMigration("add table to store original imported gpg keys", v1_9.AddGPGKeyImport),
  98. // v85 -> v86
  99. NewMigration("hash application token", v1_9.HashAppToken),
  100. // v86 -> v87
  101. NewMigration("add http method to webhook", v1_9.AddHTTPMethodToWebhook),
  102. // v87 -> v88
  103. NewMigration("add avatar field to repository", v1_9.AddAvatarFieldToRepository),
  104. // Gitea 1.9.0 ends at v88
  105. // v88 -> v89
  106. NewMigration("add commit status context field to commit_status", v1_10.AddCommitStatusContext),
  107. // v89 -> v90
  108. NewMigration("add original author/url migration info to issues, comments, and repo ", v1_10.AddOriginalMigrationInfo),
  109. // v90 -> v91
  110. NewMigration("change length of some repository columns", v1_10.ChangeSomeColumnsLengthOfRepo),
  111. // v91 -> v92
  112. NewMigration("add index on owner_id of repository and type, review_id of comment", v1_10.AddIndexOnRepositoryAndComment),
  113. // v92 -> v93
  114. NewMigration("remove orphaned repository index statuses", v1_10.RemoveLingeringIndexStatus),
  115. // v93 -> v94
  116. NewMigration("add email notification enabled preference to user", v1_10.AddEmailNotificationEnabledToUser),
  117. // v94 -> v95
  118. NewMigration("add enable_status_check, status_check_contexts to protected_branch", v1_10.AddStatusCheckColumnsForProtectedBranches),
  119. // v95 -> v96
  120. NewMigration("add table columns for cross referencing issues", v1_10.AddCrossReferenceColumns),
  121. // v96 -> v97
  122. NewMigration("delete orphaned attachments", v1_10.DeleteOrphanedAttachments),
  123. // v97 -> v98
  124. NewMigration("add repo_admin_change_team_access to user", v1_10.AddRepoAdminChangeTeamAccessColumnForUser),
  125. // v98 -> v99
  126. NewMigration("add original author name and id on migrated release", v1_10.AddOriginalAuthorOnMigratedReleases),
  127. // v99 -> v100
  128. NewMigration("add task table and status column for repository table", v1_10.AddTaskTable),
  129. // v100 -> v101
  130. NewMigration("update migration repositories' service type", v1_10.UpdateMigrationServiceTypes),
  131. // v101 -> v102
  132. NewMigration("change length of some external login users columns", v1_10.ChangeSomeColumnsLengthOfExternalLoginUser),
  133. // Gitea 1.10.0 ends at v102
  134. // v102 -> v103
  135. NewMigration("update migration repositories' service type", v1_11.DropColumnHeadUserNameOnPullRequest),
  136. // v103 -> v104
  137. NewMigration("Add WhitelistDeployKeys to protected branch", v1_11.AddWhitelistDeployKeysToBranches),
  138. // v104 -> v105
  139. NewMigration("remove unnecessary columns from label", v1_11.RemoveLabelUneededCols),
  140. // v105 -> v106
  141. NewMigration("add includes_all_repositories to teams", v1_11.AddTeamIncludesAllRepositories),
  142. // v106 -> v107
  143. NewMigration("add column `mode` to table watch", v1_11.AddModeColumnToWatch),
  144. // v107 -> v108
  145. NewMigration("Add template options to repository", v1_11.AddTemplateToRepo),
  146. // v108 -> v109
  147. NewMigration("Add comment_id on table notification", v1_11.AddCommentIDOnNotification),
  148. // v109 -> v110
  149. NewMigration("add can_create_org_repo to team", v1_11.AddCanCreateOrgRepoColumnForTeam),
  150. // v110 -> v111
  151. NewMigration("change review content type to text", v1_11.ChangeReviewContentToText),
  152. // v111 -> v112
  153. NewMigration("update branch protection for can push and whitelist enable", v1_11.AddBranchProtectionCanPushAndEnableWhitelist),
  154. // v112 -> v113
  155. NewMigration("remove release attachments which repository deleted", v1_11.RemoveAttachmentMissedRepo),
  156. // v113 -> v114
  157. NewMigration("new feature: change target branch of pull requests", v1_11.FeatureChangeTargetBranch),
  158. // v114 -> v115
  159. NewMigration("Remove authentication credentials from stored URL", v1_11.SanitizeOriginalURL),
  160. // v115 -> v116
  161. NewMigration("add user_id prefix to existing user avatar name", v1_11.RenameExistingUserAvatarName),
  162. // v116 -> v117
  163. NewMigration("Extend TrackedTimes", v1_11.ExtendTrackedTimes),
  164. // Gitea 1.11.0 ends at v117
  165. // v117 -> v118
  166. NewMigration("Add block on rejected reviews branch protection", v1_12.AddBlockOnRejectedReviews),
  167. // v118 -> v119
  168. NewMigration("Add commit id and stale to reviews", v1_12.AddReviewCommitAndStale),
  169. // v119 -> v120
  170. NewMigration("Fix migrated repositories' git service type", v1_12.FixMigratedRepositoryServiceType),
  171. // v120 -> v121
  172. NewMigration("Add owner_name on table repository", v1_12.AddOwnerNameOnRepository),
  173. // v121 -> v122
  174. NewMigration("add is_restricted column for users table", v1_12.AddIsRestricted),
  175. // v122 -> v123
  176. NewMigration("Add Require Signed Commits to ProtectedBranch", v1_12.AddRequireSignedCommits),
  177. // v123 -> v124
  178. NewMigration("Add original information for reactions", v1_12.AddReactionOriginals),
  179. // v124 -> v125
  180. NewMigration("Add columns to user and repository", v1_12.AddUserRepoMissingColumns),
  181. // v125 -> v126
  182. NewMigration("Add some columns on review for migration", v1_12.AddReviewMigrateInfo),
  183. // v126 -> v127
  184. NewMigration("Fix topic repository count", v1_12.FixTopicRepositoryCount),
  185. // v127 -> v128
  186. NewMigration("add repository code language statistics", v1_12.AddLanguageStats),
  187. // v128 -> v129
  188. NewMigration("fix merge base for pull requests", v1_12.FixMergeBase),
  189. // v129 -> v130
  190. NewMigration("remove dependencies from deleted repositories", v1_12.PurgeUnusedDependencies),
  191. // v130 -> v131
  192. NewMigration("Expand webhooks for more granularity", v1_12.ExpandWebhooks),
  193. // v131 -> v132
  194. NewMigration("Add IsSystemWebhook column to webhooks table", v1_12.AddSystemWebhookColumn),
  195. // v132 -> v133
  196. NewMigration("Add Branch Protection Protected Files Column", v1_12.AddBranchProtectionProtectedFilesColumn),
  197. // v133 -> v134
  198. NewMigration("Add EmailHash Table", v1_12.AddEmailHashTable),
  199. // v134 -> v135
  200. NewMigration("Refix merge base for merged pull requests", v1_12.RefixMergeBase),
  201. // v135 -> v136
  202. NewMigration("Add OrgID column to Labels table", v1_12.AddOrgIDLabelColumn),
  203. // v136 -> v137
  204. NewMigration("Add CommitsAhead and CommitsBehind Column to PullRequest Table", v1_12.AddCommitDivergenceToPulls),
  205. // v137 -> v138
  206. NewMigration("Add Branch Protection Block Outdated Branch", v1_12.AddBlockOnOutdatedBranch),
  207. // v138 -> v139
  208. NewMigration("Add ResolveDoerID to Comment table", v1_12.AddResolveDoerIDCommentColumn),
  209. // v139 -> v140
  210. NewMigration("prepend refs/heads/ to issue refs", v1_12.PrependRefsHeadsToIssueRefs),
  211. // Gitea 1.12.0 ends at v140
  212. // v140 -> v141
  213. NewMigration("Save detected language file size to database instead of percent", v1_13.FixLanguageStatsToSaveSize),
  214. // v141 -> v142
  215. NewMigration("Add KeepActivityPrivate to User table", v1_13.AddKeepActivityPrivateUserColumn),
  216. // v142 -> v143
  217. NewMigration("Ensure Repository.IsArchived is not null", v1_13.SetIsArchivedToFalse),
  218. // v143 -> v144
  219. NewMigration("recalculate Stars number for all user", v1_13.RecalculateStars),
  220. // v144 -> v145
  221. NewMigration("update Matrix Webhook http method to 'PUT'", v1_13.UpdateMatrixWebhookHTTPMethod),
  222. // v145 -> v146
  223. NewMigration("Increase Language field to 50 in LanguageStats", v1_13.IncreaseLanguageField),
  224. // v146 -> v147
  225. NewMigration("Add projects info to repository table", v1_13.AddProjectsInfo),
  226. // v147 -> v148
  227. NewMigration("create review for 0 review id code comments", v1_13.CreateReviewsForCodeComments),
  228. // v148 -> v149
  229. NewMigration("remove issue dependency comments who refer to non existing issues", v1_13.PurgeInvalidDependenciesComments),
  230. // v149 -> v150
  231. NewMigration("Add Created and Updated to Milestone table", v1_13.AddCreatedAndUpdatedToMilestones),
  232. // v150 -> v151
  233. NewMigration("add primary key to repo_topic", v1_13.AddPrimaryKeyToRepoTopic),
  234. // v151 -> v152
  235. NewMigration("set default password algorithm to Argon2", v1_13.SetDefaultPasswordToArgon2),
  236. // v152 -> v153
  237. NewMigration("add TrustModel field to Repository", v1_13.AddTrustModelToRepository),
  238. // v153 > v154
  239. NewMigration("add Team review request support", v1_13.AddTeamReviewRequestSupport),
  240. // v154 > v155
  241. NewMigration("add timestamps to Star, Label, Follow, Watch and Collaboration", v1_13.AddTimeStamps),
  242. // Gitea 1.13.0 ends at v155
  243. // v155 -> v156
  244. NewMigration("add changed_protected_files column for pull_request table", v1_14.AddChangedProtectedFilesPullRequestColumn),
  245. // v156 -> v157
  246. NewMigration("fix publisher ID for tag releases", v1_14.FixPublisherIDforTagReleases),
  247. // v157 -> v158
  248. NewMigration("ensure repo topics are up-to-date", v1_14.FixRepoTopics),
  249. // v158 -> v159
  250. NewMigration("code comment replies should have the commitID of the review they are replying to", v1_14.UpdateCodeCommentReplies),
  251. // v159 -> v160
  252. NewMigration("update reactions constraint", v1_14.UpdateReactionConstraint),
  253. // v160 -> v161
  254. NewMigration("Add block on official review requests branch protection", v1_14.AddBlockOnOfficialReviewRequests),
  255. // v161 -> v162
  256. NewMigration("Convert task type from int to string", v1_14.ConvertTaskTypeToString),
  257. // v162 -> v163
  258. NewMigration("Convert webhook task type from int to string", v1_14.ConvertWebhookTaskTypeToString),
  259. // v163 -> v164
  260. NewMigration("Convert topic name from 25 to 50", v1_14.ConvertTopicNameFrom25To50),
  261. // v164 -> v165
  262. NewMigration("Add scope and nonce columns to oauth2_grant table", v1_14.AddScopeAndNonceColumnsToOAuth2Grant),
  263. // v165 -> v166
  264. NewMigration("Convert hook task type from char(16) to varchar(16) and trim the column", v1_14.ConvertHookTaskTypeToVarcharAndTrim),
  265. // v166 -> v167
  266. NewMigration("Where Password is Valid with Empty String delete it", v1_14.RecalculateUserEmptyPWD),
  267. // v167 -> v168
  268. NewMigration("Add user redirect", v1_14.AddUserRedirect),
  269. // v168 -> v169
  270. NewMigration("Recreate user table to fix default values", v1_14.RecreateUserTableToFixDefaultValues),
  271. // v169 -> v170
  272. NewMigration("Update DeleteBranch comments to set the old_ref to the commit_sha", v1_14.CommentTypeDeleteBranchUseOldRef),
  273. // v170 -> v171
  274. NewMigration("Add Dismissed to Review table", v1_14.AddDismissedReviewColumn),
  275. // v171 -> v172
  276. NewMigration("Add Sorting to ProjectBoard table", v1_14.AddSortingColToProjectBoard),
  277. // v172 -> v173
  278. NewMigration("Add sessions table for go-chi/session", v1_14.AddSessionTable),
  279. // v173 -> v174
  280. NewMigration("Add time_id column to Comment", v1_14.AddTimeIDCommentColumn),
  281. // v174 -> v175
  282. NewMigration("Create repo transfer table", v1_14.AddRepoTransfer),
  283. // v175 -> v176
  284. NewMigration("Fix Postgres ID Sequences broken by recreate-table", v1_14.FixPostgresIDSequences),
  285. // v176 -> v177
  286. NewMigration("Remove invalid labels from comments", v1_14.RemoveInvalidLabels),
  287. // v177 -> v178
  288. NewMigration("Delete orphaned IssueLabels", v1_14.DeleteOrphanedIssueLabels),
  289. // Gitea 1.14.0 ends at v178
  290. // v178 -> v179
  291. NewMigration("Add LFS columns to Mirror", v1_15.AddLFSMirrorColumns),
  292. // v179 -> v180
  293. NewMigration("Convert avatar url to text", v1_15.ConvertAvatarURLToText),
  294. // v180 -> v181
  295. NewMigration("Delete credentials from past migrations", v1_15.DeleteMigrationCredentials),
  296. // v181 -> v182
  297. NewMigration("Always save primary email on email address table", v1_15.AddPrimaryEmail2EmailAddress),
  298. // v182 -> v183
  299. NewMigration("Add issue resource index table", v1_15.AddIssueResourceIndexTable),
  300. // v183 -> v184
  301. NewMigration("Create PushMirror table", v1_15.CreatePushMirrorTable),
  302. // v184 -> v185
  303. NewMigration("Rename Task errors to message", v1_15.RenameTaskErrorsToMessage),
  304. // v185 -> v186
  305. NewMigration("Add new table repo_archiver", v1_15.AddRepoArchiver),
  306. // v186 -> v187
  307. NewMigration("Create protected tag table", v1_15.CreateProtectedTagTable),
  308. // v187 -> v188
  309. NewMigration("Drop unneeded webhook related columns", v1_15.DropWebhookColumns),
  310. // v188 -> v189
  311. NewMigration("Add key is verified to gpg key", v1_15.AddKeyIsVerified),
  312. // Gitea 1.15.0 ends at v189
  313. // v189 -> v190
  314. NewMigration("Unwrap ldap.Sources", v1_16.UnwrapLDAPSourceCfg),
  315. // v190 -> v191
  316. NewMigration("Add agit flow pull request support", v1_16.AddAgitFlowPullRequest),
  317. // v191 -> v192
  318. NewMigration("Alter issue/comment table TEXT fields to LONGTEXT", v1_16.AlterIssueAndCommentTextFieldsToLongText),
  319. // v192 -> v193
  320. NewMigration("RecreateIssueResourceIndexTable to have a primary key instead of an unique index", v1_16.RecreateIssueResourceIndexTable),
  321. // v193 -> v194
  322. NewMigration("Add repo id column for attachment table", v1_16.AddRepoIDForAttachment),
  323. // v194 -> v195
  324. NewMigration("Add Branch Protection Unprotected Files Column", v1_16.AddBranchProtectionUnprotectedFilesColumn),
  325. // v195 -> v196
  326. NewMigration("Add table commit_status_index", v1_16.AddTableCommitStatusIndex),
  327. // v196 -> v197
  328. NewMigration("Add Color to ProjectBoard table", v1_16.AddColorColToProjectBoard),
  329. // v197 -> v198
  330. NewMigration("Add renamed_branch table", v1_16.AddRenamedBranchTable),
  331. // v198 -> v199
  332. NewMigration("Add issue content history table", v1_16.AddTableIssueContentHistory),
  333. // v199 -> v200
  334. NewMigration("No-op (remote version is using AppState now)", noopMigration),
  335. // v200 -> v201
  336. NewMigration("Add table app_state", v1_16.AddTableAppState),
  337. // v201 -> v202
  338. NewMigration("Drop table remote_version (if exists)", v1_16.DropTableRemoteVersion),
  339. // v202 -> v203
  340. NewMigration("Create key/value table for user settings", v1_16.CreateUserSettingsTable),
  341. // v203 -> v204
  342. NewMigration("Add Sorting to ProjectIssue table", v1_16.AddProjectIssueSorting),
  343. // v204 -> v205
  344. NewMigration("Add key is verified to ssh key", v1_16.AddSSHKeyIsVerified),
  345. // v205 -> v206
  346. NewMigration("Migrate to higher varchar on user struct", v1_16.MigrateUserPasswordSalt),
  347. // v206 -> v207
  348. NewMigration("Add authorize column to team_unit table", v1_16.AddAuthorizeColForTeamUnit),
  349. // v207 -> v208
  350. NewMigration("Add webauthn table and migrate u2f data to webauthn - NO-OPED", v1_16.AddWebAuthnCred),
  351. // v208 -> v209
  352. NewMigration("Use base32.HexEncoding instead of base64 encoding for cred ID as it is case insensitive - NO-OPED", v1_16.UseBase32HexForCredIDInWebAuthnCredential),
  353. // v209 -> v210
  354. NewMigration("Increase WebAuthentication CredentialID size to 410 - NO-OPED", v1_16.IncreaseCredentialIDTo410),
  355. // v210 -> v211
  356. NewMigration("v208 was completely broken - remigrate", v1_16.RemigrateU2FCredentials),
  357. // Gitea 1.16.2 ends at v211
  358. // v211 -> v212
  359. NewMigration("Create ForeignReference table", v1_17.CreateForeignReferenceTable),
  360. // v212 -> v213
  361. NewMigration("Add package tables", v1_17.AddPackageTables),
  362. // v213 -> v214
  363. NewMigration("Add allow edits from maintainers to PullRequest table", v1_17.AddAllowMaintainerEdit),
  364. // v214 -> v215
  365. NewMigration("Add auto merge table", v1_17.AddAutoMergeTable),
  366. // v215 -> v216
  367. NewMigration("allow to view files in PRs", v1_17.AddReviewViewedFiles),
  368. // v216 -> v217
  369. NewMigration("No-op (Improve Action table indices v1)", noopMigration),
  370. // v217 -> v218
  371. NewMigration("Alter hook_task table TEXT fields to LONGTEXT", v1_17.AlterHookTaskTextFieldsToLongText),
  372. // v218 -> v219
  373. NewMigration("Improve Action table indices v2", v1_17.ImproveActionTableIndices),
  374. // v219 -> v220
  375. NewMigration("Add sync_on_commit column to push_mirror table", v1_17.AddSyncOnCommitColForPushMirror),
  376. // v220 -> v221
  377. NewMigration("Add container repository property", v1_17.AddContainerRepositoryProperty),
  378. // v221 -> v222
  379. NewMigration("Store WebAuthentication CredentialID as bytes and increase size to at least 1024", v1_17.StoreWebauthnCredentialIDAsBytes),
  380. // v222 -> v223
  381. NewMigration("Drop old CredentialID column", v1_17.DropOldCredentialIDColumn),
  382. // v223 -> v224
  383. NewMigration("Rename CredentialIDBytes column to CredentialID", v1_17.RenameCredentialIDBytes),
  384. // Gitea 1.17.0 ends at v224
  385. // v224 -> v225
  386. NewMigration("Add badges to users", v1_18.CreateUserBadgesTable),
  387. // v225 -> v226
  388. NewMigration("Alter gpg_key/public_key content TEXT fields to MEDIUMTEXT", v1_18.AlterPublicGPGKeyContentFieldsToMediumText),
  389. // v226 -> v227
  390. NewMigration("Conan and generic packages do not need to be semantically versioned", v1_18.FixPackageSemverField),
  391. // v227 -> v228
  392. NewMigration("Create key/value table for system settings", v1_18.CreateSystemSettingsTable),
  393. // v228 -> v229
  394. NewMigration("Add TeamInvite table", v1_18.AddTeamInviteTable),
  395. // v229 -> v230
  396. NewMigration("Update counts of all open milestones", v1_18.UpdateOpenMilestoneCounts),
  397. // v230 -> v231
  398. NewMigration("Add ConfidentialClient column (default true) to OAuth2Application table", v1_18.AddConfidentialClientColumnToOAuth2ApplicationTable),
  399. // Gitea 1.18.0 ends at v231
  400. // v231 -> v232
  401. NewMigration("Add index for hook_task", v1_19.AddIndexForHookTask),
  402. // v232 -> v233
  403. NewMigration("Alter package_version.metadata_json to LONGTEXT", v1_19.AlterPackageVersionMetadataToLongText),
  404. // v233 -> v234
  405. NewMigration("Add header_authorization_encrypted column to webhook table", v1_19.AddHeaderAuthorizationEncryptedColWebhook),
  406. // v234 -> v235
  407. NewMigration("Add package cleanup rule table", v1_19.CreatePackageCleanupRuleTable),
  408. // v235 -> v236
  409. NewMigration("Add index for access_token", v1_19.AddIndexForAccessToken),
  410. // v236 -> v237
  411. NewMigration("Create secrets table", v1_19.CreateSecretsTable),
  412. // v237 -> v238
  413. NewMigration("Drop ForeignReference table", v1_19.DropForeignReferenceTable),
  414. // v238 -> v239
  415. NewMigration("Add updated unix to LFSMetaObject", v1_19.AddUpdatedUnixToLFSMetaObject),
  416. // v239 -> v240
  417. NewMigration("Add scope for access_token", v1_19.AddScopeForAccessTokens),
  418. // v240 -> v241
  419. NewMigration("Add actions tables", v1_19.AddActionsTables),
  420. // v241 -> v242
  421. NewMigration("Add card_type column to project table", v1_19.AddCardTypeToProjectTable),
  422. // v242 -> v243
  423. NewMigration("Alter gpg_key_import content TEXT field to MEDIUMTEXT", v1_19.AlterPublicGPGKeyImportContentFieldToMediumText),
  424. // v243 -> v244
  425. NewMigration("Add exclusive label", v1_19.AddExclusiveLabel),
  426. // Gitea 1.19.0 ends at v244
  427. // v244 -> v245
  428. NewMigration("Add NeedApproval to actions tables", v1_20.AddNeedApprovalToActionRun),
  429. // v245 -> v246
  430. NewMigration("Rename Webhook org_id to owner_id", v1_20.RenameWebhookOrgToOwner),
  431. // v246 -> v247
  432. NewMigration("Add missed column owner_id for project table", v1_20.AddNewColumnForProject),
  433. // v247 -> v248
  434. NewMigration("Fix incorrect project type", v1_20.FixIncorrectProjectType),
  435. // v248 -> v249
  436. NewMigration("Add version column to action_runner table", v1_20.AddVersionToActionRunner),
  437. // v249 -> v250
  438. NewMigration("Improve Action table indices v3", v1_20.ImproveActionTableIndices),
  439. // v250 -> v251
  440. NewMigration("Change Container Metadata", v1_20.ChangeContainerMetadataMultiArch),
  441. // v251 -> v252
  442. NewMigration("Fix incorrect owner team unit access mode", v1_20.FixIncorrectOwnerTeamUnitAccessMode),
  443. // v252 -> v253
  444. NewMigration("Fix incorrect admin team unit access mode", v1_20.FixIncorrectAdminTeamUnitAccessMode),
  445. // v253 -> v254
  446. NewMigration("Fix ExternalTracker and ExternalWiki accessMode in owner and admin team", v1_20.FixExternalTrackerAndExternalWikiAccessModeInOwnerAndAdminTeam),
  447. // v254 -> v255
  448. NewMigration("Add ActionTaskOutput table", v1_20.AddActionTaskOutputTable),
  449. // v255 -> v256
  450. NewMigration("Add ArchivedUnix Column", v1_20.AddArchivedUnixToRepository),
  451. // v256 -> v257
  452. NewMigration("Add is_internal column to package", v1_20.AddIsInternalColumnToPackage),
  453. // v257 -> v258
  454. NewMigration("Add Actions Artifact table", v1_20.CreateActionArtifactTable),
  455. // v258 -> v259
  456. NewMigration("Add PinOrder Column", v1_20.AddPinOrderToIssue),
  457. // v259 -> v260
  458. NewMigration("Convert scoped access tokens", v1_20.ConvertScopedAccessTokens),
  459. // Gitea 1.20.0 ends at 260
  460. // v260 -> v261
  461. NewMigration("Drop custom_labels column of action_runner table", v1_21.DropCustomLabelsColumnOfActionRunner),
  462. // v261 -> v262
  463. NewMigration("Add variable table", v1_21.CreateVariableTable),
  464. // v262 -> v263
  465. NewMigration("Add TriggerEvent to action_run table", v1_21.AddTriggerEventToActionRun),
  466. // v263 -> v264
  467. NewMigration("Add git_size and lfs_size columns to repository table", v1_21.AddGitSizeAndLFSSizeToRepositoryTable),
  468. // v264 -> v265
  469. NewMigration("Add branch table", v1_21.AddBranchTable),
  470. // v265 -> v266
  471. NewMigration("Alter Actions Artifact table", v1_21.AlterActionArtifactTable),
  472. // v266 -> v267
  473. NewMigration("Reduce commit status", v1_21.ReduceCommitStatus),
  474. // v267 -> v268
  475. NewMigration("Add action_tasks_version table", v1_21.CreateActionTasksVersionTable),
  476. // v268 -> v269
  477. NewMigration("Update Action Ref", v1_21.UpdateActionsRefIndex),
  478. // v269 -> v270
  479. NewMigration("Drop deleted branch table", v1_21.DropDeletedBranchTable),
  480. // v270 -> v271
  481. NewMigration("Fix PackageProperty typo", v1_21.FixPackagePropertyTypo),
  482. // v271 -> v272
  483. NewMigration("Allow archiving labels", v1_21.AddArchivedUnixColumInLabelTable),
  484. // v272 -> v273
  485. NewMigration("Add Version to ActionRun table", v1_21.AddVersionToActionRunTable),
  486. // v273 -> v274
  487. NewMigration("Add Action Schedule Table", v1_21.AddActionScheduleTable),
  488. // v274 -> v275
  489. NewMigration("Add Actions artifacts expiration date", v1_21.AddExpiredUnixColumnInActionArtifactTable),
  490. // v275 -> v276
  491. NewMigration("Add ScheduleID for ActionRun", v1_21.AddScheduleIDForActionRun),
  492. // v276 -> v277
  493. NewMigration("Add RemoteAddress to mirrors", v1_21.AddRemoteAddressToMirrors),
  494. // v277 -> v278
  495. NewMigration("Add Index to issue_user.issue_id", v1_21.AddIndexToIssueUserIssueID),
  496. // v278 -> v279
  497. NewMigration("Add Index to comment.dependent_issue_id", v1_21.AddIndexToCommentDependentIssueID),
  498. // v279 -> v280
  499. NewMigration("Add Index to action.user_id", v1_21.AddIndexToActionUserID),
  500. // Gitea 1.21.0 ends at 280
  501. // v280 -> v281
  502. NewMigration("Rename user themes", v1_22.RenameUserThemes),
  503. // v281 -> v282
  504. NewMigration("Add auth_token table", v1_22.CreateAuthTokenTable),
  505. // v282 -> v283
  506. NewMigration("Add Index to pull_auto_merge.doer_id", v1_22.AddIndexToPullAutoMergeDoerID),
  507. // v283 -> v284
  508. NewMigration("Add combined Index to issue_user.uid and issue_id", v1_22.AddCombinedIndexToIssueUser),
  509. // v284 -> v285
  510. NewMigration("Add ignore stale approval column on branch table", v1_22.AddIgnoreStaleApprovalsColumnToProtectedBranchTable),
  511. // v285 -> v286
  512. NewMigration("Add PreviousDuration to ActionRun", v1_22.AddPreviousDurationToActionRun),
  513. // v286 -> v287
  514. NewMigration("Add support for SHA256 git repositories", v1_22.AdjustDBForSha256),
  515. // v287 -> v288
  516. NewMigration("Use Slug instead of ID for Badges", v1_22.UseSlugInsteadOfIDForBadges),
  517. // v288 -> v289
  518. NewMigration("Add user_blocking table", v1_22.AddUserBlockingTable),
  519. // v289 -> v290
  520. NewMigration("Add default_wiki_branch to repository table", v1_22.AddDefaultWikiBranch),
  521. // v290 -> v291
  522. NewMigration("Add PayloadVersion to HookTask", v1_22.AddPayloadVersionToHookTaskTable),
  523. // v291 -> v292
  524. NewMigration("Add Index to attachment.comment_id", v1_22.AddCommentIDIndexofAttachment),
  525. // v292 -> v293
  526. NewMigration("Ensure every project has exactly one default column", v1_22.CheckProjectColumnsConsistency),
  527. }
  528. // GetCurrentDBVersion returns the current db version
  529. func GetCurrentDBVersion(x *xorm.Engine) (int64, error) {
  530. if err := x.Sync(new(Version)); err != nil {
  531. return -1, fmt.Errorf("sync: %w", err)
  532. }
  533. currentVersion := &Version{ID: 1}
  534. has, err := x.Get(currentVersion)
  535. if err != nil {
  536. return -1, fmt.Errorf("get: %w", err)
  537. }
  538. if !has {
  539. return -1, nil
  540. }
  541. return currentVersion.Version, nil
  542. }
  543. // ExpectedVersion returns the expected db version
  544. func ExpectedVersion() int64 {
  545. return int64(minDBVersion + len(migrations))
  546. }
  547. // EnsureUpToDate will check if the db is at the correct version
  548. func EnsureUpToDate(x *xorm.Engine) error {
  549. currentDB, err := GetCurrentDBVersion(x)
  550. if err != nil {
  551. return err
  552. }
  553. if currentDB < 0 {
  554. return fmt.Errorf("Database has not been initialized")
  555. }
  556. if minDBVersion > currentDB {
  557. 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)
  558. }
  559. expected := ExpectedVersion()
  560. if currentDB != expected {
  561. 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)
  562. }
  563. return nil
  564. }
  565. // Migrate database to current version
  566. func Migrate(x *xorm.Engine) error {
  567. // Set a new clean the default mapper to GonicMapper as that is the default for Gitea.
  568. x.SetMapper(names.GonicMapper{})
  569. if err := x.Sync(new(Version)); err != nil {
  570. return fmt.Errorf("sync: %w", err)
  571. }
  572. currentVersion := &Version{ID: 1}
  573. has, err := x.Get(currentVersion)
  574. if err != nil {
  575. return fmt.Errorf("get: %w", err)
  576. } else if !has {
  577. // If the version record does not exist we think
  578. // it is a fresh installation and we can skip all migrations.
  579. currentVersion.ID = 0
  580. currentVersion.Version = int64(minDBVersion + len(migrations))
  581. if _, err = x.InsertOne(currentVersion); err != nil {
  582. return fmt.Errorf("insert: %w", err)
  583. }
  584. }
  585. v := currentVersion.Version
  586. if minDBVersion > v {
  587. log.Fatal(`Gitea no longer supports auto-migration from your previously installed version.
  588. Please try upgrading to a lower version first (suggested v1.6.4), then upgrade to this version.`)
  589. return nil
  590. }
  591. // Downgrading Gitea's database version not supported
  592. if int(v-minDBVersion) > len(migrations) {
  593. msg := fmt.Sprintf("Your database (migration version: %d) is for a newer Gitea, you can not use the newer database for this old Gitea release (%d).", v, minDBVersion+len(migrations))
  594. msg += "\nGitea will exit to keep your database safe and unchanged. Please use the correct Gitea release, do not change the migration version manually (incorrect manual operation may lose data)."
  595. if !setting.IsProd {
  596. msg += fmt.Sprintf("\nIf you are in development and really know what you're doing, you can force changing the migration version by executing: UPDATE version SET version=%d WHERE id=1;", minDBVersion+len(migrations))
  597. }
  598. log.Fatal("Migration Error: %s", msg)
  599. return nil
  600. }
  601. // Some migration tasks depend on the git command
  602. if git.DefaultContext == nil {
  603. if err = git.InitSimple(context.Background()); err != nil {
  604. return err
  605. }
  606. }
  607. // Migrate
  608. for i, m := range migrations[v-minDBVersion:] {
  609. log.Info("Migration[%d]: %s", v+int64(i), m.Description())
  610. // Reset the mapper between each migration - migrations are not supposed to depend on each other
  611. x.SetMapper(names.GonicMapper{})
  612. if err = m.Migrate(x); err != nil {
  613. return fmt.Errorf("migration[%d]: %s failed: %w", v+int64(i), m.Description(), err)
  614. }
  615. currentVersion.Version = v + int64(i) + 1
  616. if _, err = x.ID(1).Update(currentVersion); err != nil {
  617. return err
  618. }
  619. }
  620. return nil
  621. }