Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  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. "bytes"
  8. "encoding/json"
  9. "fmt"
  10. "io/ioutil"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "regexp"
  15. "strings"
  16. "time"
  17. "code.gitea.io/gitea/modules/generate"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/setting"
  20. gouuid "github.com/satori/go.uuid"
  21. "github.com/unknwon/com"
  22. ini "gopkg.in/ini.v1"
  23. "xorm.io/xorm"
  24. )
  25. const minDBVersion = 4
  26. // Migration describes on migration from lower version to high version
  27. type Migration interface {
  28. Description() string
  29. Migrate(*xorm.Engine) error
  30. }
  31. type migration struct {
  32. description string
  33. migrate func(*xorm.Engine) error
  34. }
  35. // NewMigration creates a new migration
  36. func NewMigration(desc string, fn func(*xorm.Engine) error) Migration {
  37. return &migration{desc, fn}
  38. }
  39. // Description returns the migration's description
  40. func (m *migration) Description() string {
  41. return m.description
  42. }
  43. // Migrate executes the migration
  44. func (m *migration) Migrate(x *xorm.Engine) error {
  45. return m.migrate(x)
  46. }
  47. // Version describes the version table. Should have only one row with id==1
  48. type Version struct {
  49. ID int64 `xorm:"pk autoincr"`
  50. Version int64
  51. }
  52. func emptyMigration(x *xorm.Engine) error {
  53. return nil
  54. }
  55. // This is a sequence of migrations. Add new migrations to the bottom of the list.
  56. // If you want to "retire" a migration, remove it from the top of the list and
  57. // update minDBVersion accordingly
  58. var migrations = []Migration{
  59. // v0 -> v4: before 0.6.0 -> 0.7.33
  60. NewMigration("fix locale file load panic", fixLocaleFileLoadPanic), // V4 -> V5:v0.6.0
  61. NewMigration("trim action compare URL prefix", trimCommitActionAppURLPrefix), // V5 -> V6:v0.6.3
  62. NewMigration("generate issue-label from issue", issueToIssueLabel), // V6 -> V7:v0.6.4
  63. NewMigration("refactor attachment table", attachmentRefactor), // V7 -> V8:v0.6.4
  64. NewMigration("rename pull request fields", renamePullRequestFields), // V8 -> V9:v0.6.16
  65. NewMigration("clean up migrate repo info", cleanUpMigrateRepoInfo), // V9 -> V10:v0.6.20
  66. NewMigration("generate rands and salt for organizations", generateOrgRandsAndSalt), // V10 -> V11:v0.8.5
  67. NewMigration("convert date to unix timestamp", convertDateToUnix), // V11 -> V12:v0.9.2
  68. NewMigration("convert LDAP UseSSL option to SecurityProtocol", ldapUseSSLToSecurityProtocol), // V12 -> V13:v0.9.37
  69. // v13 -> v14:v0.9.87
  70. NewMigration("set comment updated with created", setCommentUpdatedWithCreated),
  71. // v14 -> v15
  72. NewMigration("create user column diff view style", createUserColumnDiffViewStyle),
  73. // v15 -> v16
  74. NewMigration("create user column allow create organization", createAllowCreateOrganizationColumn),
  75. // V16 -> v17
  76. NewMigration("create repo unit table and add units for all repos", addUnitsToTables),
  77. // v17 -> v18
  78. NewMigration("set protect branches updated with created", setProtectedBranchUpdatedWithCreated),
  79. // v18 -> v19
  80. NewMigration("add external login user", addExternalLoginUser),
  81. // v19 -> v20
  82. NewMigration("generate and migrate Git hooks", generateAndMigrateGitHooks),
  83. // v20 -> v21
  84. NewMigration("use new avatar path name for security reason", useNewNameAvatars),
  85. // v21 -> v22
  86. NewMigration("rewrite authorized_keys file via new format", useNewPublickeyFormat),
  87. // v22 -> v23
  88. NewMigration("generate and migrate wiki Git hooks", generateAndMigrateWikiGitHooks),
  89. // v23 -> v24
  90. NewMigration("add user openid table", addUserOpenID),
  91. // v24 -> v25
  92. NewMigration("change the key_id and primary_key_id type", changeGPGKeysColumns),
  93. // v25 -> v26
  94. NewMigration("add show field in user openid table", addUserOpenIDShow),
  95. // v26 -> v27
  96. NewMigration("generate and migrate repo and wiki Git hooks", generateAndMigrateGitHookChains),
  97. // v27 -> v28
  98. NewMigration("change mirror interval from hours to time.Duration", convertIntervalToDuration),
  99. // v28 -> v29
  100. NewMigration("add field for repo size", addRepoSize),
  101. // v29 -> v30
  102. NewMigration("add commit status table", addCommitStatus),
  103. // v30 -> 31
  104. NewMigration("add primary key to external login user", addExternalLoginUserPK),
  105. // v31 -> 32
  106. NewMigration("add field for login source synchronization", addLoginSourceSyncEnabledColumn),
  107. // v32 -> v33
  108. NewMigration("add units for team", addUnitsToRepoTeam),
  109. // v33 -> v34
  110. NewMigration("remove columns from action", removeActionColumns),
  111. // v34 -> v35
  112. NewMigration("give all units to owner teams", giveAllUnitsToOwnerTeams),
  113. // v35 -> v36
  114. NewMigration("adds comment to an action", addCommentIDToAction),
  115. // v36 -> v37
  116. NewMigration("regenerate git hooks", regenerateGitHooks36),
  117. // v37 -> v38
  118. NewMigration("unescape user full names", unescapeUserFullNames),
  119. // v38 -> v39
  120. NewMigration("remove commits and settings unit types", removeCommitsUnitType),
  121. // v39 -> v40
  122. NewMigration("add tags to releases and sync existing repositories", releaseAddColumnIsTagAndSyncTags),
  123. // v40 -> v41
  124. NewMigration("fix protected branch can push value to false", fixProtectedBranchCanPushValue),
  125. // v41 -> v42
  126. NewMigration("remove duplicate unit types", removeDuplicateUnitTypes),
  127. // v42 -> v43
  128. NewMigration("empty step", emptyMigration),
  129. // v43 -> v44
  130. NewMigration("empty step", emptyMigration),
  131. // v44 -> v45
  132. NewMigration("empty step", emptyMigration),
  133. // v45 -> v46
  134. NewMigration("remove index column from repo_unit table", removeIndexColumnFromRepoUnitTable),
  135. // v46 -> v47
  136. NewMigration("remove organization watch repositories", removeOrganizationWatchRepo),
  137. // v47 -> v48
  138. NewMigration("add deleted branches", addDeletedBranch),
  139. // v48 -> v49
  140. NewMigration("add repo indexer status", addRepoIndexerStatus),
  141. // v49 -> v50
  142. NewMigration("adds time tracking and stopwatches", addTimetracking),
  143. // v50 -> v51
  144. NewMigration("migrate protected branch struct", migrateProtectedBranchStruct),
  145. // v51 -> v52
  146. NewMigration("add default value to user prohibit_login", addDefaultValueToUserProhibitLogin),
  147. // v52 -> v53
  148. NewMigration("add lfs lock table", addLFSLock),
  149. // v53 -> v54
  150. NewMigration("add reactions", addReactions),
  151. // v54 -> v55
  152. NewMigration("add pull request options", addPullRequestOptions),
  153. // v55 -> v56
  154. NewMigration("add writable deploy keys", addModeToDeploKeys),
  155. // v56 -> v57
  156. NewMigration("remove is_owner, num_teams columns from org_user", removeIsOwnerColumnFromOrgUser),
  157. // v57 -> v58
  158. NewMigration("add closed_unix column for issues", addIssueClosedTime),
  159. // v58 -> v59
  160. NewMigration("add label descriptions", addLabelsDescriptions),
  161. // v59 -> v60
  162. NewMigration("add merge whitelist for protected branches", addProtectedBranchMergeWhitelist),
  163. // v60 -> v61
  164. NewMigration("add is_fsck_enabled column for repos", addFsckEnabledToRepo),
  165. // v61 -> v62
  166. NewMigration("add size column for attachments", addSizeToAttachment),
  167. // v62 -> v63
  168. NewMigration("add last used passcode column for TOTP", addLastUsedPasscodeTOTP),
  169. // v63 -> v64
  170. NewMigration("add language column for user setting", addLanguageSetting),
  171. // v64 -> v65
  172. NewMigration("add multiple assignees", addMultipleAssignees),
  173. // v65 -> v66
  174. NewMigration("add u2f", addU2FReg),
  175. // v66 -> v67
  176. NewMigration("add login source id column for public_key table", addLoginSourceIDToPublicKeyTable),
  177. // v67 -> v68
  178. NewMigration("remove stale watches", removeStaleWatches),
  179. // v68 -> V69
  180. NewMigration("Reformat and remove incorrect topics", reformatAndRemoveIncorrectTopics),
  181. // v69 -> v70
  182. NewMigration("move team units to team_unit table", moveTeamUnitsToTeamUnitTable),
  183. // v70 -> v71
  184. NewMigration("add issue_dependencies", addIssueDependencies),
  185. // v71 -> v72
  186. NewMigration("protect each scratch token", addScratchHash),
  187. // v72 -> v73
  188. NewMigration("add review", addReview),
  189. // v73 -> v74
  190. NewMigration("add must_change_password column for users table", addMustChangePassword),
  191. // v74 -> v75
  192. NewMigration("add approval whitelists to protected branches", addApprovalWhitelistsToProtectedBranches),
  193. // v75 -> v76
  194. NewMigration("clear nonused data which not deleted when user was deleted", clearNonusedData),
  195. // v76 -> v77
  196. NewMigration("add pull request rebase with merge commit", addPullRequestRebaseWithMerge),
  197. // v77 -> v78
  198. NewMigration("add theme to users", addUserDefaultTheme),
  199. // v78 -> v79
  200. NewMigration("rename repo is_bare to repo is_empty", renameRepoIsBareToIsEmpty),
  201. // v79 -> v80
  202. NewMigration("add can close issues via commit in any branch", addCanCloseIssuesViaCommitInAnyBranch),
  203. // v80 -> v81
  204. NewMigration("add is locked to issues", addIsLockedToIssues),
  205. // v81 -> v82
  206. NewMigration("update U2F counter type", changeU2FCounterType),
  207. // v82 -> v83
  208. NewMigration("hot fix for wrong release sha1 on release table", fixReleaseSha1OnReleaseTable),
  209. // v83 -> v84
  210. NewMigration("add uploader id for table attachment", addUploaderIDForAttachment),
  211. // v84 -> v85
  212. NewMigration("add table to store original imported gpg keys", addGPGKeyImport),
  213. // v85 -> v86
  214. NewMigration("hash application token", hashAppToken),
  215. // v86 -> v87
  216. NewMigration("add http method to webhook", addHTTPMethodToWebhook),
  217. // v87 -> v88
  218. NewMigration("add avatar field to repository", addAvatarFieldToRepository),
  219. // v88 -> v89
  220. NewMigration("add commit status context field to commit_status", addCommitStatusContext),
  221. // v89 -> v90
  222. NewMigration("add original author/url migration info to issues, comments, and repo ", addOriginalMigrationInfo),
  223. // v90 -> v91
  224. NewMigration("change length of some repository columns", changeSomeColumnsLengthOfRepo),
  225. // v91 -> v92
  226. NewMigration("add index on owner_id of repository and type, review_id of comment", addIndexOnRepositoryAndComment),
  227. // v92 -> v93
  228. NewMigration("remove orphaned repository index statuses", removeLingeringIndexStatus),
  229. // v93 -> v94
  230. NewMigration("add email notification enabled preference to user", addEmailNotificationEnabledToUser),
  231. // v94 -> v95
  232. NewMigration("add enable_status_check, status_check_contexts to protected_branch", addStatusCheckColumnsForProtectedBranches),
  233. // v95 -> v96
  234. NewMigration("add table columns for cross referencing issues", addCrossReferenceColumns),
  235. // v96 -> v97
  236. NewMigration("delete orphaned attachments", deleteOrphanedAttachments),
  237. // v97 -> v98
  238. NewMigration("add repo_admin_change_team_access to user", addRepoAdminChangeTeamAccessColumnForUser),
  239. // v98 -> v99
  240. NewMigration("add original author name and id on migrated release", addOriginalAuthorOnMigratedReleases),
  241. // v99 -> v100
  242. NewMigration("add task table and status column for repository table", addTaskTable),
  243. // v100 -> v101
  244. NewMigration("update migration repositories' service type", updateMigrationServiceTypes),
  245. // v101 -> v102
  246. NewMigration("change length of some external login users columns", changeSomeColumnsLengthOfExternalLoginUser),
  247. // v102 -> v103
  248. NewMigration("update migration repositories' service type", dropColumnHeadUserNameOnPullRequest),
  249. // v103 -> v104
  250. NewMigration("Add WhitelistDeployKeys to protected branch", addWhitelistDeployKeysToBranches),
  251. // v104 -> v105
  252. NewMigration("remove unnecessary columns from label", removeLabelUneededCols),
  253. // v105 -> v106
  254. NewMigration("add includes_all_repositories to teams", addTeamIncludesAllRepositories),
  255. // v106 -> v107
  256. NewMigration("add column `mode` to table watch", addModeColumnToWatch),
  257. // v107 -> v108
  258. NewMigration("Add template options to repository", addTemplateToRepo),
  259. // v108 -> v109
  260. NewMigration("Add comment_id on table notification", addCommentIDOnNotification),
  261. // v109 -> v110
  262. NewMigration("add can_create_org_repo to team", addCanCreateOrgRepoColumnForTeam),
  263. // v110 -> v111
  264. NewMigration("change review content type to text", changeReviewContentToText),
  265. // v111 -> v112
  266. NewMigration("update branch protection for can push and whitelist enable", addBranchProtectionCanPushAndEnableWhitelist),
  267. // v112 -> v113
  268. NewMigration("remove release attachments which repository deleted", removeAttachmentMissedRepo),
  269. // v113 -> v114
  270. NewMigration("new feature: change target branch of pull requests", featureChangeTargetBranch),
  271. // v114 -> v115
  272. NewMigration("Remove authentication credentials from stored URL", sanitizeOriginalURL),
  273. // v115 -> v116
  274. NewMigration("add user_id prefix to existing user avatar name", renameExistingUserAvatarName),
  275. // v116 -> v117
  276. NewMigration("Extend TrackedTimes", extendTrackedTimes),
  277. // v117 -> v118
  278. NewMigration("Add block on rejected reviews branch protection", addBlockOnRejectedReviews),
  279. // v118 -> v119
  280. NewMigration("Add commit id and stale to reviews", addReviewCommitAndStale),
  281. // v119 -> v120
  282. NewMigration("Fix migrated repositories' git service type", fixMigratedRepositoryServiceType),
  283. // v120 -> v121
  284. NewMigration("Add owner_name on table repository", addOwnerNameOnRepository),
  285. // v121 -> v122
  286. NewMigration("add is_restricted column for users table", addIsRestricted),
  287. }
  288. // Migrate database to current version
  289. func Migrate(x *xorm.Engine) error {
  290. if err := x.Sync(new(Version)); err != nil {
  291. return fmt.Errorf("sync: %v", err)
  292. }
  293. currentVersion := &Version{ID: 1}
  294. has, err := x.Get(currentVersion)
  295. if err != nil {
  296. return fmt.Errorf("get: %v", err)
  297. } else if !has {
  298. // If the version record does not exist we think
  299. // it is a fresh installation and we can skip all migrations.
  300. currentVersion.ID = 0
  301. currentVersion.Version = int64(minDBVersion + len(migrations))
  302. if _, err = x.InsertOne(currentVersion); err != nil {
  303. return fmt.Errorf("insert: %v", err)
  304. }
  305. }
  306. v := currentVersion.Version
  307. if minDBVersion > v {
  308. log.Fatal(`Gitea no longer supports auto-migration from your previously installed version.
  309. Please try to upgrade to a lower version (>= v0.6.0) first, then upgrade to current version.`)
  310. return nil
  311. }
  312. if int(v-minDBVersion) > len(migrations) {
  313. // User downgraded Gitea.
  314. currentVersion.Version = int64(len(migrations) + minDBVersion)
  315. _, err = x.ID(1).Update(currentVersion)
  316. return err
  317. }
  318. for i, m := range migrations[v-minDBVersion:] {
  319. log.Info("Migration[%d]: %s", v+int64(i), m.Description())
  320. if err = m.Migrate(x); err != nil {
  321. return fmt.Errorf("do migrate: %v", err)
  322. }
  323. currentVersion.Version = v + int64(i) + 1
  324. if _, err = x.ID(1).Update(currentVersion); err != nil {
  325. return err
  326. }
  327. }
  328. return nil
  329. }
  330. func dropTableColumns(sess *xorm.Session, tableName string, columnNames ...string) (err error) {
  331. if tableName == "" || len(columnNames) == 0 {
  332. return nil
  333. }
  334. // TODO: This will not work if there are foreign keys
  335. switch {
  336. case setting.Database.UseSQLite3:
  337. // First drop the indexes on the columns
  338. res, errIndex := sess.Query(fmt.Sprintf("PRAGMA index_list(`%s`)", tableName))
  339. if errIndex != nil {
  340. return errIndex
  341. }
  342. for _, row := range res {
  343. indexName := row["name"]
  344. indexRes, err := sess.Query(fmt.Sprintf("PRAGMA index_info(`%s`)", indexName))
  345. if err != nil {
  346. return err
  347. }
  348. if len(indexRes) != 1 {
  349. continue
  350. }
  351. indexColumn := string(indexRes[0]["name"])
  352. for _, name := range columnNames {
  353. if name == indexColumn {
  354. _, err := sess.Exec(fmt.Sprintf("DROP INDEX `%s`", indexName))
  355. if err != nil {
  356. return err
  357. }
  358. }
  359. }
  360. }
  361. // Here we need to get the columns from the original table
  362. sql := fmt.Sprintf("SELECT sql FROM sqlite_master WHERE tbl_name='%s' and type='table'", tableName)
  363. res, err := sess.Query(sql)
  364. if err != nil {
  365. return err
  366. }
  367. tableSQL := string(res[0]["sql"])
  368. // Separate out the column definitions
  369. tableSQL = tableSQL[strings.Index(tableSQL, "("):]
  370. // Remove the required columnNames
  371. for _, name := range columnNames {
  372. tableSQL = regexp.MustCompile(regexp.QuoteMeta("`"+name+"`")+"[^`,)]*?[,)]").ReplaceAllString(tableSQL, "")
  373. }
  374. // Ensure the query is ended properly
  375. tableSQL = strings.TrimSpace(tableSQL)
  376. if tableSQL[len(tableSQL)-1] != ')' {
  377. if tableSQL[len(tableSQL)-1] == ',' {
  378. tableSQL = tableSQL[:len(tableSQL)-1]
  379. }
  380. tableSQL += ")"
  381. }
  382. // Find all the columns in the table
  383. columns := regexp.MustCompile("`([^`]*)`").FindAllString(tableSQL, -1)
  384. tableSQL = fmt.Sprintf("CREATE TABLE `new_%s_new` ", tableName) + tableSQL
  385. if _, err := sess.Exec(tableSQL); err != nil {
  386. return err
  387. }
  388. // Now restore the data
  389. columnsSeparated := strings.Join(columns, ",")
  390. insertSQL := fmt.Sprintf("INSERT INTO `new_%s_new` (%s) SELECT %s FROM %s", tableName, columnsSeparated, columnsSeparated, tableName)
  391. if _, err := sess.Exec(insertSQL); err != nil {
  392. return err
  393. }
  394. // Now drop the old table
  395. if _, err := sess.Exec(fmt.Sprintf("DROP TABLE `%s`", tableName)); err != nil {
  396. return err
  397. }
  398. // Rename the table
  399. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `new_%s_new` RENAME TO `%s`", tableName, tableName)); err != nil {
  400. return err
  401. }
  402. case setting.Database.UsePostgreSQL:
  403. cols := ""
  404. for _, col := range columnNames {
  405. if cols != "" {
  406. cols += ", "
  407. }
  408. cols += "DROP COLUMN `" + col + "` CASCADE"
  409. }
  410. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` %s", tableName, cols)); err != nil {
  411. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  412. }
  413. case setting.Database.UseMySQL:
  414. // Drop indexes on columns first
  415. sql := fmt.Sprintf("SHOW INDEX FROM %s WHERE column_name IN ('%s')", tableName, strings.Join(columnNames, "','"))
  416. res, err := sess.Query(sql)
  417. if err != nil {
  418. return err
  419. }
  420. for _, index := range res {
  421. indexName := index["column_name"]
  422. if len(indexName) > 0 {
  423. _, err := sess.Exec(fmt.Sprintf("DROP INDEX `%s` ON `%s`", indexName, tableName))
  424. if err != nil {
  425. return err
  426. }
  427. }
  428. }
  429. // Now drop the columns
  430. cols := ""
  431. for _, col := range columnNames {
  432. if cols != "" {
  433. cols += ", "
  434. }
  435. cols += "DROP COLUMN `" + col + "`"
  436. }
  437. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` %s", tableName, cols)); err != nil {
  438. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  439. }
  440. case setting.Database.UseMSSQL:
  441. cols := ""
  442. for _, col := range columnNames {
  443. if cols != "" {
  444. cols += ", "
  445. }
  446. cols += "`" + strings.ToLower(col) + "`"
  447. }
  448. 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'))",
  449. tableName, strings.Replace(cols, "`", "'", -1))
  450. constraints := make([]string, 0)
  451. if err := sess.SQL(sql).Find(&constraints); err != nil {
  452. sess.Rollback()
  453. return fmt.Errorf("Find constraints: %v", err)
  454. }
  455. for _, constraint := range constraints {
  456. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` DROP CONSTRAINT `%s`", tableName, constraint)); err != nil {
  457. sess.Rollback()
  458. return fmt.Errorf("Drop table `%s` constraint `%s`: %v", tableName, constraint, err)
  459. }
  460. }
  461. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` DROP COLUMN %s", tableName, cols)); err != nil {
  462. sess.Rollback()
  463. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  464. }
  465. return sess.Commit()
  466. default:
  467. log.Fatal("Unrecognized DB")
  468. }
  469. return nil
  470. }
  471. func fixLocaleFileLoadPanic(_ *xorm.Engine) error {
  472. cfg, err := ini.Load(setting.CustomConf)
  473. if err != nil {
  474. return fmt.Errorf("load custom config: %v", err)
  475. }
  476. cfg.DeleteSection("i18n")
  477. if err = cfg.SaveTo(setting.CustomConf); err != nil {
  478. return fmt.Errorf("save custom config: %v", err)
  479. }
  480. setting.Langs = strings.Split(strings.Replace(strings.Join(setting.Langs, ","), "fr-CA", "fr-FR", 1), ",")
  481. return nil
  482. }
  483. func trimCommitActionAppURLPrefix(x *xorm.Engine) error {
  484. type PushCommit struct {
  485. Sha1 string
  486. Message string
  487. AuthorEmail string
  488. AuthorName string
  489. }
  490. type PushCommits struct {
  491. Len int
  492. Commits []*PushCommit
  493. CompareURL string `json:"CompareUrl"`
  494. }
  495. type Action struct {
  496. ID int64 `xorm:"pk autoincr"`
  497. Content string `xorm:"TEXT"`
  498. }
  499. results, err := x.Query("SELECT `id`,`content` FROM `action` WHERE `op_type`=?", 5)
  500. if err != nil {
  501. return fmt.Errorf("select commit actions: %v", err)
  502. }
  503. sess := x.NewSession()
  504. defer sess.Close()
  505. if err = sess.Begin(); err != nil {
  506. return err
  507. }
  508. var pushCommits *PushCommits
  509. for _, action := range results {
  510. actID := com.StrTo(string(action["id"])).MustInt64()
  511. if actID == 0 {
  512. continue
  513. }
  514. pushCommits = new(PushCommits)
  515. if err = json.Unmarshal(action["content"], pushCommits); err != nil {
  516. return fmt.Errorf("unmarshal action content[%d]: %v", actID, err)
  517. }
  518. infos := strings.Split(pushCommits.CompareURL, "/")
  519. if len(infos) <= 4 {
  520. continue
  521. }
  522. pushCommits.CompareURL = strings.Join(infos[len(infos)-4:], "/")
  523. p, err := json.Marshal(pushCommits)
  524. if err != nil {
  525. return fmt.Errorf("marshal action content[%d]: %v", actID, err)
  526. }
  527. if _, err = sess.ID(actID).Update(&Action{
  528. Content: string(p),
  529. }); err != nil {
  530. return fmt.Errorf("update action[%d]: %v", actID, err)
  531. }
  532. }
  533. return sess.Commit()
  534. }
  535. func issueToIssueLabel(x *xorm.Engine) error {
  536. type IssueLabel struct {
  537. ID int64 `xorm:"pk autoincr"`
  538. IssueID int64 `xorm:"UNIQUE(s)"`
  539. LabelID int64 `xorm:"UNIQUE(s)"`
  540. }
  541. issueLabels := make([]*IssueLabel, 0, 50)
  542. results, err := x.Query("SELECT `id`,`label_ids` FROM `issue`")
  543. if err != nil {
  544. if strings.Contains(err.Error(), "no such column") ||
  545. strings.Contains(err.Error(), "Unknown column") {
  546. return nil
  547. }
  548. return fmt.Errorf("select issues: %v", err)
  549. }
  550. for _, issue := range results {
  551. issueID := com.StrTo(issue["id"]).MustInt64()
  552. // Just in case legacy code can have duplicated IDs for same label.
  553. mark := make(map[int64]bool)
  554. for _, idStr := range strings.Split(string(issue["label_ids"]), "|") {
  555. labelID := com.StrTo(strings.TrimPrefix(idStr, "$")).MustInt64()
  556. if labelID == 0 || mark[labelID] {
  557. continue
  558. }
  559. mark[labelID] = true
  560. issueLabels = append(issueLabels, &IssueLabel{
  561. IssueID: issueID,
  562. LabelID: labelID,
  563. })
  564. }
  565. }
  566. sess := x.NewSession()
  567. defer sess.Close()
  568. if err = sess.Begin(); err != nil {
  569. return err
  570. }
  571. if err = sess.Sync2(new(IssueLabel)); err != nil {
  572. return fmt.Errorf("Sync2: %v", err)
  573. } else if _, err = sess.Insert(issueLabels); err != nil {
  574. return fmt.Errorf("insert issue-labels: %v", err)
  575. }
  576. return sess.Commit()
  577. }
  578. func attachmentRefactor(x *xorm.Engine) error {
  579. type Attachment struct {
  580. ID int64 `xorm:"pk autoincr"`
  581. UUID string `xorm:"uuid INDEX"`
  582. // For rename purpose.
  583. Path string `xorm:"-"`
  584. NewPath string `xorm:"-"`
  585. }
  586. results, err := x.Query("SELECT * FROM `attachment`")
  587. if err != nil {
  588. return fmt.Errorf("select attachments: %v", err)
  589. }
  590. attachments := make([]*Attachment, 0, len(results))
  591. for _, attach := range results {
  592. if !com.IsExist(string(attach["path"])) {
  593. // If the attachment is already missing, there is no point to update it.
  594. continue
  595. }
  596. attachments = append(attachments, &Attachment{
  597. ID: com.StrTo(attach["id"]).MustInt64(),
  598. UUID: gouuid.NewV4().String(),
  599. Path: string(attach["path"]),
  600. })
  601. }
  602. sess := x.NewSession()
  603. defer sess.Close()
  604. if err = sess.Begin(); err != nil {
  605. return err
  606. }
  607. if err = sess.Sync2(new(Attachment)); err != nil {
  608. return fmt.Errorf("Sync2: %v", err)
  609. }
  610. // Note: Roll back for rename can be a dead loop,
  611. // so produces a backup file.
  612. var buf bytes.Buffer
  613. buf.WriteString("# old path -> new path\n")
  614. // Update database first because this is where error happens the most often.
  615. for _, attach := range attachments {
  616. if _, err = sess.ID(attach.ID).Update(attach); err != nil {
  617. return err
  618. }
  619. attach.NewPath = path.Join(setting.AttachmentPath, attach.UUID[0:1], attach.UUID[1:2], attach.UUID)
  620. buf.WriteString(attach.Path)
  621. buf.WriteString("\t")
  622. buf.WriteString(attach.NewPath)
  623. buf.WriteString("\n")
  624. }
  625. // Then rename attachments.
  626. isSucceed := true
  627. defer func() {
  628. if isSucceed {
  629. return
  630. }
  631. dumpPath := path.Join(setting.LogRootPath, "attachment_path.dump")
  632. ioutil.WriteFile(dumpPath, buf.Bytes(), 0666)
  633. log.Info("Failed to rename some attachments, old and new paths are saved into: %s", dumpPath)
  634. }()
  635. for _, attach := range attachments {
  636. if err = os.MkdirAll(path.Dir(attach.NewPath), os.ModePerm); err != nil {
  637. isSucceed = false
  638. return err
  639. }
  640. if err = os.Rename(attach.Path, attach.NewPath); err != nil {
  641. isSucceed = false
  642. return err
  643. }
  644. }
  645. return sess.Commit()
  646. }
  647. func renamePullRequestFields(x *xorm.Engine) (err error) {
  648. type PullRequest struct {
  649. ID int64 `xorm:"pk autoincr"`
  650. PullID int64 `xorm:"INDEX"`
  651. PullIndex int64
  652. HeadBarcnh string
  653. IssueID int64 `xorm:"INDEX"`
  654. Index int64
  655. HeadBranch string
  656. }
  657. if err = x.Sync(new(PullRequest)); err != nil {
  658. return fmt.Errorf("sync: %v", err)
  659. }
  660. results, err := x.Query("SELECT `id`,`pull_id`,`pull_index`,`head_barcnh` FROM `pull_request`")
  661. if err != nil {
  662. if strings.Contains(err.Error(), "no such column") {
  663. return nil
  664. }
  665. return fmt.Errorf("select pull requests: %v", err)
  666. }
  667. sess := x.NewSession()
  668. defer sess.Close()
  669. if err = sess.Begin(); err != nil {
  670. return err
  671. }
  672. var pull *PullRequest
  673. for _, pr := range results {
  674. pull = &PullRequest{
  675. ID: com.StrTo(pr["id"]).MustInt64(),
  676. IssueID: com.StrTo(pr["pull_id"]).MustInt64(),
  677. Index: com.StrTo(pr["pull_index"]).MustInt64(),
  678. HeadBranch: string(pr["head_barcnh"]),
  679. }
  680. if pull.Index == 0 {
  681. continue
  682. }
  683. if _, err = sess.ID(pull.ID).Update(pull); err != nil {
  684. return err
  685. }
  686. }
  687. return sess.Commit()
  688. }
  689. func cleanUpMigrateRepoInfo(x *xorm.Engine) (err error) {
  690. type (
  691. User struct {
  692. ID int64 `xorm:"pk autoincr"`
  693. LowerName string
  694. }
  695. Repository struct {
  696. ID int64 `xorm:"pk autoincr"`
  697. OwnerID int64
  698. LowerName string
  699. }
  700. )
  701. repos := make([]*Repository, 0, 25)
  702. if err = x.Where("is_mirror=?", false).Find(&repos); err != nil {
  703. return fmt.Errorf("select all non-mirror repositories: %v", err)
  704. }
  705. var user *User
  706. for _, repo := range repos {
  707. user = &User{ID: repo.OwnerID}
  708. has, err := x.Get(user)
  709. if err != nil {
  710. return fmt.Errorf("get owner of repository[%d - %d]: %v", repo.ID, repo.OwnerID, err)
  711. } else if !has {
  712. continue
  713. }
  714. configPath := filepath.Join(setting.RepoRootPath, user.LowerName, repo.LowerName+".git/config")
  715. // In case repository file is somehow missing.
  716. if !com.IsFile(configPath) {
  717. continue
  718. }
  719. cfg, err := ini.Load(configPath)
  720. if err != nil {
  721. return fmt.Errorf("open config file: %v", err)
  722. }
  723. cfg.DeleteSection("remote \"origin\"")
  724. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  725. return fmt.Errorf("save config file: %v", err)
  726. }
  727. }
  728. return nil
  729. }
  730. func generateOrgRandsAndSalt(x *xorm.Engine) (err error) {
  731. type User struct {
  732. ID int64 `xorm:"pk autoincr"`
  733. Rands string `xorm:"VARCHAR(10)"`
  734. Salt string `xorm:"VARCHAR(10)"`
  735. }
  736. orgs := make([]*User, 0, 10)
  737. if err = x.Where("type=1").And("rands=''").Find(&orgs); err != nil {
  738. return fmt.Errorf("select all organizations: %v", err)
  739. }
  740. sess := x.NewSession()
  741. defer sess.Close()
  742. if err = sess.Begin(); err != nil {
  743. return err
  744. }
  745. for _, org := range orgs {
  746. if org.Rands, err = generate.GetRandomString(10); err != nil {
  747. return err
  748. }
  749. if org.Salt, err = generate.GetRandomString(10); err != nil {
  750. return err
  751. }
  752. if _, err = sess.ID(org.ID).Update(org); err != nil {
  753. return err
  754. }
  755. }
  756. return sess.Commit()
  757. }
  758. // TAction defines the struct for migrating table action
  759. type TAction struct {
  760. ID int64 `xorm:"pk autoincr"`
  761. CreatedUnix int64
  762. }
  763. // TableName will be invoked by XORM to customrize the table name
  764. func (t *TAction) TableName() string { return "action" }
  765. // TNotice defines the struct for migrating table notice
  766. type TNotice struct {
  767. ID int64 `xorm:"pk autoincr"`
  768. CreatedUnix int64
  769. }
  770. // TableName will be invoked by XORM to customrize the table name
  771. func (t *TNotice) TableName() string { return "notice" }
  772. // TComment defines the struct for migrating table comment
  773. type TComment struct {
  774. ID int64 `xorm:"pk autoincr"`
  775. CreatedUnix int64
  776. }
  777. // TableName will be invoked by XORM to customrize the table name
  778. func (t *TComment) TableName() string { return "comment" }
  779. // TIssue defines the struct for migrating table issue
  780. type TIssue struct {
  781. ID int64 `xorm:"pk autoincr"`
  782. DeadlineUnix int64
  783. CreatedUnix int64
  784. UpdatedUnix int64
  785. }
  786. // TableName will be invoked by XORM to customrize the table name
  787. func (t *TIssue) TableName() string { return "issue" }
  788. // TMilestone defines the struct for migrating table milestone
  789. type TMilestone struct {
  790. ID int64 `xorm:"pk autoincr"`
  791. DeadlineUnix int64
  792. ClosedDateUnix int64
  793. }
  794. // TableName will be invoked by XORM to customrize the table name
  795. func (t *TMilestone) TableName() string { return "milestone" }
  796. // TAttachment defines the struct for migrating table attachment
  797. type TAttachment struct {
  798. ID int64 `xorm:"pk autoincr"`
  799. CreatedUnix int64
  800. }
  801. // TableName will be invoked by XORM to customrize the table name
  802. func (t *TAttachment) TableName() string { return "attachment" }
  803. // TLoginSource defines the struct for migrating table login_source
  804. type TLoginSource struct {
  805. ID int64 `xorm:"pk autoincr"`
  806. CreatedUnix int64
  807. UpdatedUnix int64
  808. }
  809. // TableName will be invoked by XORM to customrize the table name
  810. func (t *TLoginSource) TableName() string { return "login_source" }
  811. // TPull defines the struct for migrating table pull_request
  812. type TPull struct {
  813. ID int64 `xorm:"pk autoincr"`
  814. MergedUnix int64
  815. }
  816. // TableName will be invoked by XORM to customrize the table name
  817. func (t *TPull) TableName() string { return "pull_request" }
  818. // TRelease defines the struct for migrating table release
  819. type TRelease struct {
  820. ID int64 `xorm:"pk autoincr"`
  821. CreatedUnix int64
  822. }
  823. // TableName will be invoked by XORM to customrize the table name
  824. func (t *TRelease) TableName() string { return "release" }
  825. // TRepo defines the struct for migrating table repository
  826. type TRepo struct {
  827. ID int64 `xorm:"pk autoincr"`
  828. CreatedUnix int64
  829. UpdatedUnix int64
  830. }
  831. // TableName will be invoked by XORM to customrize the table name
  832. func (t *TRepo) TableName() string { return "repository" }
  833. // TMirror defines the struct for migrating table mirror
  834. type TMirror struct {
  835. ID int64 `xorm:"pk autoincr"`
  836. UpdatedUnix int64
  837. NextUpdateUnix int64
  838. }
  839. // TableName will be invoked by XORM to customrize the table name
  840. func (t *TMirror) TableName() string { return "mirror" }
  841. // TPublicKey defines the struct for migrating table public_key
  842. type TPublicKey struct {
  843. ID int64 `xorm:"pk autoincr"`
  844. CreatedUnix int64
  845. UpdatedUnix int64
  846. }
  847. // TableName will be invoked by XORM to customrize the table name
  848. func (t *TPublicKey) TableName() string { return "public_key" }
  849. // TDeployKey defines the struct for migrating table deploy_key
  850. type TDeployKey struct {
  851. ID int64 `xorm:"pk autoincr"`
  852. CreatedUnix int64
  853. UpdatedUnix int64
  854. }
  855. // TableName will be invoked by XORM to customrize the table name
  856. func (t *TDeployKey) TableName() string { return "deploy_key" }
  857. // TAccessToken defines the struct for migrating table access_token
  858. type TAccessToken struct {
  859. ID int64 `xorm:"pk autoincr"`
  860. CreatedUnix int64
  861. UpdatedUnix int64
  862. }
  863. // TableName will be invoked by XORM to customrize the table name
  864. func (t *TAccessToken) TableName() string { return "access_token" }
  865. // TUser defines the struct for migrating table user
  866. type TUser struct {
  867. ID int64 `xorm:"pk autoincr"`
  868. CreatedUnix int64
  869. UpdatedUnix int64
  870. }
  871. // TableName will be invoked by XORM to customrize the table name
  872. func (t *TUser) TableName() string { return "user" }
  873. // TWebhook defines the struct for migrating table webhook
  874. type TWebhook struct {
  875. ID int64 `xorm:"pk autoincr"`
  876. CreatedUnix int64
  877. UpdatedUnix int64
  878. }
  879. // TableName will be invoked by XORM to customrize the table name
  880. func (t *TWebhook) TableName() string { return "webhook" }
  881. func convertDateToUnix(x *xorm.Engine) (err error) {
  882. log.Info("This migration could take up to minutes, please be patient.")
  883. type Bean struct {
  884. ID int64 `xorm:"pk autoincr"`
  885. Created time.Time
  886. Updated time.Time
  887. Merged time.Time
  888. Deadline time.Time
  889. ClosedDate time.Time
  890. NextUpdate time.Time
  891. }
  892. var tables = []struct {
  893. name string
  894. cols []string
  895. bean interface{}
  896. }{
  897. {"action", []string{"created"}, new(TAction)},
  898. {"notice", []string{"created"}, new(TNotice)},
  899. {"comment", []string{"created"}, new(TComment)},
  900. {"issue", []string{"deadline", "created", "updated"}, new(TIssue)},
  901. {"milestone", []string{"deadline", "closed_date"}, new(TMilestone)},
  902. {"attachment", []string{"created"}, new(TAttachment)},
  903. {"login_source", []string{"created", "updated"}, new(TLoginSource)},
  904. {"pull_request", []string{"merged"}, new(TPull)},
  905. {"release", []string{"created"}, new(TRelease)},
  906. {"repository", []string{"created", "updated"}, new(TRepo)},
  907. {"mirror", []string{"updated", "next_update"}, new(TMirror)},
  908. {"public_key", []string{"created", "updated"}, new(TPublicKey)},
  909. {"deploy_key", []string{"created", "updated"}, new(TDeployKey)},
  910. {"access_token", []string{"created", "updated"}, new(TAccessToken)},
  911. {"user", []string{"created", "updated"}, new(TUser)},
  912. {"webhook", []string{"created", "updated"}, new(TWebhook)},
  913. }
  914. for _, table := range tables {
  915. log.Info("Converting table: %s", table.name)
  916. if err = x.Sync2(table.bean); err != nil {
  917. return fmt.Errorf("Sync [table: %s]: %v", table.name, err)
  918. }
  919. offset := 0
  920. for {
  921. beans := make([]*Bean, 0, 100)
  922. if err = x.Table(table.name).Asc("id").Limit(100, offset).Find(&beans); err != nil {
  923. return fmt.Errorf("select beans [table: %s, offset: %d]: %v", table.name, offset, err)
  924. }
  925. log.Trace("Table [%s]: offset: %d, beans: %d", table.name, offset, len(beans))
  926. if len(beans) == 0 {
  927. break
  928. }
  929. offset += 100
  930. baseSQL := "UPDATE `" + table.name + "` SET "
  931. for _, bean := range beans {
  932. valSQLs := make([]string, 0, len(table.cols))
  933. for _, col := range table.cols {
  934. fieldSQL := ""
  935. fieldSQL += col + "_unix = "
  936. switch col {
  937. case "deadline":
  938. if bean.Deadline.IsZero() {
  939. continue
  940. }
  941. fieldSQL += com.ToStr(bean.Deadline.Unix())
  942. case "created":
  943. fieldSQL += com.ToStr(bean.Created.Unix())
  944. case "updated":
  945. fieldSQL += com.ToStr(bean.Updated.Unix())
  946. case "closed_date":
  947. fieldSQL += com.ToStr(bean.ClosedDate.Unix())
  948. case "merged":
  949. fieldSQL += com.ToStr(bean.Merged.Unix())
  950. case "next_update":
  951. fieldSQL += com.ToStr(bean.NextUpdate.Unix())
  952. }
  953. valSQLs = append(valSQLs, fieldSQL)
  954. }
  955. if len(valSQLs) == 0 {
  956. continue
  957. }
  958. if _, err = x.Exec(baseSQL + strings.Join(valSQLs, ",") + " WHERE id = " + com.ToStr(bean.ID)); err != nil {
  959. return fmt.Errorf("update bean [table: %s, id: %d]: %v", table.name, bean.ID, err)
  960. }
  961. }
  962. }
  963. }
  964. return nil
  965. }