code.gitea.io/gitea@v1.21.7/models/migrations/migrations.go (about)

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