You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

migrations.go 24 kB

9 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
7 years ago
9 years ago
9 years ago
9 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package migrations
  5. import (
  6. "bytes"
  7. "encoding/json"
  8. "fmt"
  9. "io/ioutil"
  10. "os"
  11. "path"
  12. "path/filepath"
  13. "strings"
  14. "time"
  15. "github.com/Unknwon/com"
  16. "github.com/go-xorm/xorm"
  17. gouuid "github.com/satori/go.uuid"
  18. "gopkg.in/ini.v1"
  19. "code.gitea.io/gitea/modules/generate"
  20. "code.gitea.io/gitea/modules/log"
  21. "code.gitea.io/gitea/modules/setting"
  22. )
  23. const minDBVersion = 4
  24. // Migration describes on migration from lower version to high version
  25. type Migration interface {
  26. Description() string
  27. Migrate(*xorm.Engine) error
  28. }
  29. type migration struct {
  30. description string
  31. migrate func(*xorm.Engine) error
  32. }
  33. // NewMigration creates a new migration
  34. func NewMigration(desc string, fn func(*xorm.Engine) error) Migration {
  35. return &migration{desc, fn}
  36. }
  37. // Description returns the migration's description
  38. func (m *migration) Description() string {
  39. return m.description
  40. }
  41. // Migrate executes the migration
  42. func (m *migration) Migrate(x *xorm.Engine) error {
  43. return m.migrate(x)
  44. }
  45. // Version describes the version table. Should have only one row with id==1
  46. type Version struct {
  47. ID int64 `xorm:"pk autoincr"`
  48. Version int64
  49. }
  50. func emptyMigration(x *xorm.Engine) error {
  51. return nil
  52. }
  53. // This is a sequence of migrations. Add new migrations to the bottom of the list.
  54. // If you want to "retire" a migration, remove it from the top of the list and
  55. // update minDBVersion accordingly
  56. var migrations = []Migration{
  57. // v0 -> v4: before 0.6.0 -> 0.7.33
  58. NewMigration("fix locale file load panic", fixLocaleFileLoadPanic), // V4 -> V5:v0.6.0
  59. NewMigration("trim action compare URL prefix", trimCommitActionAppURLPrefix), // V5 -> V6:v0.6.3
  60. NewMigration("generate issue-label from issue", issueToIssueLabel), // V6 -> V7:v0.6.4
  61. NewMigration("refactor attachment table", attachmentRefactor), // V7 -> V8:v0.6.4
  62. NewMigration("rename pull request fields", renamePullRequestFields), // V8 -> V9:v0.6.16
  63. NewMigration("clean up migrate repo info", cleanUpMigrateRepoInfo), // V9 -> V10:v0.6.20
  64. NewMigration("generate rands and salt for organizations", generateOrgRandsAndSalt), // V10 -> V11:v0.8.5
  65. NewMigration("convert date to unix timestamp", convertDateToUnix), // V11 -> V12:v0.9.2
  66. NewMigration("convert LDAP UseSSL option to SecurityProtocol", ldapUseSSLToSecurityProtocol), // V12 -> V13:v0.9.37
  67. // v13 -> v14:v0.9.87
  68. NewMigration("set comment updated with created", setCommentUpdatedWithCreated),
  69. // v14 -> v15
  70. NewMigration("create user column diff view style", createUserColumnDiffViewStyle),
  71. // v15 -> v16
  72. NewMigration("create user column allow create organization", createAllowCreateOrganizationColumn),
  73. // V16 -> v17
  74. NewMigration("create repo unit table and add units for all repos", addUnitsToTables),
  75. // v17 -> v18
  76. NewMigration("set protect branches updated with created", setProtectedBranchUpdatedWithCreated),
  77. // v18 -> v19
  78. NewMigration("add external login user", addExternalLoginUser),
  79. // v19 -> v20
  80. NewMigration("generate and migrate Git hooks", generateAndMigrateGitHooks),
  81. // v20 -> v21
  82. NewMigration("use new avatar path name for security reason", useNewNameAvatars),
  83. // v21 -> v22
  84. NewMigration("rewrite authorized_keys file via new format", useNewPublickeyFormat),
  85. // v22 -> v23
  86. NewMigration("generate and migrate wiki Git hooks", generateAndMigrateWikiGitHooks),
  87. // v23 -> v24
  88. NewMigration("add user openid table", addUserOpenID),
  89. // v24 -> v25
  90. NewMigration("change the key_id and primary_key_id type", changeGPGKeysColumns),
  91. // v25 -> v26
  92. NewMigration("add show field in user openid table", addUserOpenIDShow),
  93. // v26 -> v27
  94. NewMigration("generate and migrate repo and wiki Git hooks", generateAndMigrateGitHookChains),
  95. // v27 -> v28
  96. NewMigration("change mirror interval from hours to time.Duration", convertIntervalToDuration),
  97. // v28 -> v29
  98. NewMigration("add field for repo size", addRepoSize),
  99. // v29 -> v30
  100. NewMigration("add commit status table", addCommitStatus),
  101. // v30 -> 31
  102. NewMigration("add primary key to external login user", addExternalLoginUserPK),
  103. // v31 -> 32
  104. NewMigration("add field for login source synchronization", addLoginSourceSyncEnabledColumn),
  105. // v32 -> v33
  106. NewMigration("add units for team", addUnitsToRepoTeam),
  107. // v33 -> v34
  108. NewMigration("remove columns from action", removeActionColumns),
  109. // v34 -> v35
  110. NewMigration("give all units to owner teams", giveAllUnitsToOwnerTeams),
  111. // v35 -> v36
  112. NewMigration("adds comment to an action", addCommentIDToAction),
  113. // v36 -> v37
  114. NewMigration("regenerate git hooks", regenerateGitHooks36),
  115. // v37 -> v38
  116. NewMigration("unescape user full names", unescapeUserFullNames),
  117. // v38 -> v39
  118. NewMigration("remove commits and settings unit types", removeCommitsUnitType),
  119. // v39 -> v40
  120. NewMigration("add tags to releases and sync existing repositories", releaseAddColumnIsTagAndSyncTags),
  121. // v40 -> v41
  122. NewMigration("fix protected branch can push value to false", fixProtectedBranchCanPushValue),
  123. // v41 -> v42
  124. NewMigration("remove duplicate unit types", removeDuplicateUnitTypes),
  125. // v42 -> v43
  126. NewMigration("empty step", emptyMigration),
  127. // v43 -> v44
  128. NewMigration("empty step", emptyMigration),
  129. // v44 -> v45
  130. NewMigration("empty step", emptyMigration),
  131. // v45 -> v46
  132. NewMigration("remove index column from repo_unit table", removeIndexColumnFromRepoUnitTable),
  133. // v46 -> v47
  134. NewMigration("remove organization watch repositories", removeOrganizationWatchRepo),
  135. // v47 -> v48
  136. NewMigration("add deleted branches", addDeletedBranch),
  137. // v48 -> v49
  138. NewMigration("add repo indexer status", addRepoIndexerStatus),
  139. // v49 -> v50
  140. NewMigration("adds time tracking and stopwatches", addTimetracking),
  141. // v50 -> v51
  142. NewMigration("migrate protected branch struct", migrateProtectedBranchStruct),
  143. // v51 -> v52
  144. NewMigration("add default value to user prohibit_login", addDefaultValueToUserProhibitLogin),
  145. // v52 -> v53
  146. NewMigration("add lfs lock table", addLFSLock),
  147. // v53 -> v54
  148. NewMigration("add reactions", addReactions),
  149. // v54 -> v55
  150. NewMigration("add pull request options", addPullRequestOptions),
  151. // v55 -> v56
  152. NewMigration("add writable deploy keys", addModeToDeploKeys),
  153. // v56 -> v57
  154. NewMigration("remove is_owner, num_teams columns from org_user", removeIsOwnerColumnFromOrgUser),
  155. // v57 -> v58
  156. NewMigration("add closed_unix column for issues", addIssueClosedTime),
  157. }
  158. // Migrate database to current version
  159. func Migrate(x *xorm.Engine) error {
  160. if err := x.Sync(new(Version)); err != nil {
  161. return fmt.Errorf("sync: %v", err)
  162. }
  163. currentVersion := &Version{ID: 1}
  164. has, err := x.Get(currentVersion)
  165. if err != nil {
  166. return fmt.Errorf("get: %v", err)
  167. } else if !has {
  168. // If the version record does not exist we think
  169. // it is a fresh installation and we can skip all migrations.
  170. currentVersion.ID = 0
  171. currentVersion.Version = int64(minDBVersion + len(migrations))
  172. if _, err = x.InsertOne(currentVersion); err != nil {
  173. return fmt.Errorf("insert: %v", err)
  174. }
  175. }
  176. v := currentVersion.Version
  177. if minDBVersion > v {
  178. log.Fatal(4, `Gitea no longer supports auto-migration from your previously installed version.
  179. Please try to upgrade to a lower version (>= v0.6.0) first, then upgrade to current version.`)
  180. return nil
  181. }
  182. if int(v-minDBVersion) > len(migrations) {
  183. // User downgraded Gitea.
  184. currentVersion.Version = int64(len(migrations) + minDBVersion)
  185. _, err = x.ID(1).Update(currentVersion)
  186. return err
  187. }
  188. for i, m := range migrations[v-minDBVersion:] {
  189. log.Info("Migration: %s", m.Description())
  190. if err = m.Migrate(x); err != nil {
  191. return fmt.Errorf("do migrate: %v", err)
  192. }
  193. currentVersion.Version = v + int64(i) + 1
  194. if _, err = x.ID(1).Update(currentVersion); err != nil {
  195. return err
  196. }
  197. }
  198. return nil
  199. }
  200. func fixLocaleFileLoadPanic(_ *xorm.Engine) error {
  201. cfg, err := ini.Load(setting.CustomConf)
  202. if err != nil {
  203. return fmt.Errorf("load custom config: %v", err)
  204. }
  205. cfg.DeleteSection("i18n")
  206. if err = cfg.SaveTo(setting.CustomConf); err != nil {
  207. return fmt.Errorf("save custom config: %v", err)
  208. }
  209. setting.Langs = strings.Split(strings.Replace(strings.Join(setting.Langs, ","), "fr-CA", "fr-FR", 1), ",")
  210. return nil
  211. }
  212. func trimCommitActionAppURLPrefix(x *xorm.Engine) error {
  213. type PushCommit struct {
  214. Sha1 string
  215. Message string
  216. AuthorEmail string
  217. AuthorName string
  218. }
  219. type PushCommits struct {
  220. Len int
  221. Commits []*PushCommit
  222. CompareURL string `json:"CompareUrl"`
  223. }
  224. type Action struct {
  225. ID int64 `xorm:"pk autoincr"`
  226. Content string `xorm:"TEXT"`
  227. }
  228. results, err := x.Query("SELECT `id`,`content` FROM `action` WHERE `op_type`=?", 5)
  229. if err != nil {
  230. return fmt.Errorf("select commit actions: %v", err)
  231. }
  232. sess := x.NewSession()
  233. defer sess.Close()
  234. if err = sess.Begin(); err != nil {
  235. return err
  236. }
  237. var pushCommits *PushCommits
  238. for _, action := range results {
  239. actID := com.StrTo(string(action["id"])).MustInt64()
  240. if actID == 0 {
  241. continue
  242. }
  243. pushCommits = new(PushCommits)
  244. if err = json.Unmarshal(action["content"], pushCommits); err != nil {
  245. return fmt.Errorf("unmarshal action content[%d]: %v", actID, err)
  246. }
  247. infos := strings.Split(pushCommits.CompareURL, "/")
  248. if len(infos) <= 4 {
  249. continue
  250. }
  251. pushCommits.CompareURL = strings.Join(infos[len(infos)-4:], "/")
  252. p, err := json.Marshal(pushCommits)
  253. if err != nil {
  254. return fmt.Errorf("marshal action content[%d]: %v", actID, err)
  255. }
  256. if _, err = sess.Id(actID).Update(&Action{
  257. Content: string(p),
  258. }); err != nil {
  259. return fmt.Errorf("update action[%d]: %v", actID, err)
  260. }
  261. }
  262. return sess.Commit()
  263. }
  264. func issueToIssueLabel(x *xorm.Engine) error {
  265. type IssueLabel struct {
  266. ID int64 `xorm:"pk autoincr"`
  267. IssueID int64 `xorm:"UNIQUE(s)"`
  268. LabelID int64 `xorm:"UNIQUE(s)"`
  269. }
  270. issueLabels := make([]*IssueLabel, 0, 50)
  271. results, err := x.Query("SELECT `id`,`label_ids` FROM `issue`")
  272. if err != nil {
  273. if strings.Contains(err.Error(), "no such column") ||
  274. strings.Contains(err.Error(), "Unknown column") {
  275. return nil
  276. }
  277. return fmt.Errorf("select issues: %v", err)
  278. }
  279. for _, issue := range results {
  280. issueID := com.StrTo(issue["id"]).MustInt64()
  281. // Just in case legacy code can have duplicated IDs for same label.
  282. mark := make(map[int64]bool)
  283. for _, idStr := range strings.Split(string(issue["label_ids"]), "|") {
  284. labelID := com.StrTo(strings.TrimPrefix(idStr, "$")).MustInt64()
  285. if labelID == 0 || mark[labelID] {
  286. continue
  287. }
  288. mark[labelID] = true
  289. issueLabels = append(issueLabels, &IssueLabel{
  290. IssueID: issueID,
  291. LabelID: labelID,
  292. })
  293. }
  294. }
  295. sess := x.NewSession()
  296. defer sess.Close()
  297. if err = sess.Begin(); err != nil {
  298. return err
  299. }
  300. if err = sess.Sync2(new(IssueLabel)); err != nil {
  301. return fmt.Errorf("Sync2: %v", err)
  302. } else if _, err = sess.Insert(issueLabels); err != nil {
  303. return fmt.Errorf("insert issue-labels: %v", err)
  304. }
  305. return sess.Commit()
  306. }
  307. func attachmentRefactor(x *xorm.Engine) error {
  308. type Attachment struct {
  309. ID int64 `xorm:"pk autoincr"`
  310. UUID string `xorm:"uuid INDEX"`
  311. // For rename purpose.
  312. Path string `xorm:"-"`
  313. NewPath string `xorm:"-"`
  314. }
  315. results, err := x.Query("SELECT * FROM `attachment`")
  316. if err != nil {
  317. return fmt.Errorf("select attachments: %v", err)
  318. }
  319. attachments := make([]*Attachment, 0, len(results))
  320. for _, attach := range results {
  321. if !com.IsExist(string(attach["path"])) {
  322. // If the attachment is already missing, there is no point to update it.
  323. continue
  324. }
  325. attachments = append(attachments, &Attachment{
  326. ID: com.StrTo(attach["id"]).MustInt64(),
  327. UUID: gouuid.NewV4().String(),
  328. Path: string(attach["path"]),
  329. })
  330. }
  331. sess := x.NewSession()
  332. defer sess.Close()
  333. if err = sess.Begin(); err != nil {
  334. return err
  335. }
  336. if err = sess.Sync2(new(Attachment)); err != nil {
  337. return fmt.Errorf("Sync2: %v", err)
  338. }
  339. // Note: Roll back for rename can be a dead loop,
  340. // so produces a backup file.
  341. var buf bytes.Buffer
  342. buf.WriteString("# old path -> new path\n")
  343. // Update database first because this is where error happens the most often.
  344. for _, attach := range attachments {
  345. if _, err = sess.Id(attach.ID).Update(attach); err != nil {
  346. return err
  347. }
  348. attach.NewPath = path.Join(setting.AttachmentPath, attach.UUID[0:1], attach.UUID[1:2], attach.UUID)
  349. buf.WriteString(attach.Path)
  350. buf.WriteString("\t")
  351. buf.WriteString(attach.NewPath)
  352. buf.WriteString("\n")
  353. }
  354. // Then rename attachments.
  355. isSucceed := true
  356. defer func() {
  357. if isSucceed {
  358. return
  359. }
  360. dumpPath := path.Join(setting.LogRootPath, "attachment_path.dump")
  361. ioutil.WriteFile(dumpPath, buf.Bytes(), 0666)
  362. log.Info("Failed to rename some attachments, old and new paths are saved into: %s", dumpPath)
  363. }()
  364. for _, attach := range attachments {
  365. if err = os.MkdirAll(path.Dir(attach.NewPath), os.ModePerm); err != nil {
  366. isSucceed = false
  367. return err
  368. }
  369. if err = os.Rename(attach.Path, attach.NewPath); err != nil {
  370. isSucceed = false
  371. return err
  372. }
  373. }
  374. return sess.Commit()
  375. }
  376. func renamePullRequestFields(x *xorm.Engine) (err error) {
  377. type PullRequest struct {
  378. ID int64 `xorm:"pk autoincr"`
  379. PullID int64 `xorm:"INDEX"`
  380. PullIndex int64
  381. HeadBarcnh string
  382. IssueID int64 `xorm:"INDEX"`
  383. Index int64
  384. HeadBranch string
  385. }
  386. if err = x.Sync(new(PullRequest)); err != nil {
  387. return fmt.Errorf("sync: %v", err)
  388. }
  389. results, err := x.Query("SELECT `id`,`pull_id`,`pull_index`,`head_barcnh` FROM `pull_request`")
  390. if err != nil {
  391. if strings.Contains(err.Error(), "no such column") {
  392. return nil
  393. }
  394. return fmt.Errorf("select pull requests: %v", err)
  395. }
  396. sess := x.NewSession()
  397. defer sess.Close()
  398. if err = sess.Begin(); err != nil {
  399. return err
  400. }
  401. var pull *PullRequest
  402. for _, pr := range results {
  403. pull = &PullRequest{
  404. ID: com.StrTo(pr["id"]).MustInt64(),
  405. IssueID: com.StrTo(pr["pull_id"]).MustInt64(),
  406. Index: com.StrTo(pr["pull_index"]).MustInt64(),
  407. HeadBranch: string(pr["head_barcnh"]),
  408. }
  409. if pull.Index == 0 {
  410. continue
  411. }
  412. if _, err = sess.Id(pull.ID).Update(pull); err != nil {
  413. return err
  414. }
  415. }
  416. return sess.Commit()
  417. }
  418. func cleanUpMigrateRepoInfo(x *xorm.Engine) (err error) {
  419. type (
  420. User struct {
  421. ID int64 `xorm:"pk autoincr"`
  422. LowerName string
  423. }
  424. Repository struct {
  425. ID int64 `xorm:"pk autoincr"`
  426. OwnerID int64
  427. LowerName string
  428. }
  429. )
  430. repos := make([]*Repository, 0, 25)
  431. if err = x.Where("is_mirror=?", false).Find(&repos); err != nil {
  432. return fmt.Errorf("select all non-mirror repositories: %v", err)
  433. }
  434. var user *User
  435. for _, repo := range repos {
  436. user = &User{ID: repo.OwnerID}
  437. has, err := x.Get(user)
  438. if err != nil {
  439. return fmt.Errorf("get owner of repository[%d - %d]: %v", repo.ID, repo.OwnerID, err)
  440. } else if !has {
  441. continue
  442. }
  443. configPath := filepath.Join(setting.RepoRootPath, user.LowerName, repo.LowerName+".git/config")
  444. // In case repository file is somehow missing.
  445. if !com.IsFile(configPath) {
  446. continue
  447. }
  448. cfg, err := ini.Load(configPath)
  449. if err != nil {
  450. return fmt.Errorf("open config file: %v", err)
  451. }
  452. cfg.DeleteSection("remote \"origin\"")
  453. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  454. return fmt.Errorf("save config file: %v", err)
  455. }
  456. }
  457. return nil
  458. }
  459. func generateOrgRandsAndSalt(x *xorm.Engine) (err error) {
  460. type User struct {
  461. ID int64 `xorm:"pk autoincr"`
  462. Rands string `xorm:"VARCHAR(10)"`
  463. Salt string `xorm:"VARCHAR(10)"`
  464. }
  465. orgs := make([]*User, 0, 10)
  466. if err = x.Where("type=1").And("rands=''").Find(&orgs); err != nil {
  467. return fmt.Errorf("select all organizations: %v", err)
  468. }
  469. sess := x.NewSession()
  470. defer sess.Close()
  471. if err = sess.Begin(); err != nil {
  472. return err
  473. }
  474. for _, org := range orgs {
  475. if org.Rands, err = generate.GetRandomString(10); err != nil {
  476. return err
  477. }
  478. if org.Salt, err = generate.GetRandomString(10); err != nil {
  479. return err
  480. }
  481. if _, err = sess.Id(org.ID).Update(org); err != nil {
  482. return err
  483. }
  484. }
  485. return sess.Commit()
  486. }
  487. // TAction defines the struct for migrating table action
  488. type TAction struct {
  489. ID int64 `xorm:"pk autoincr"`
  490. CreatedUnix int64
  491. }
  492. // TableName will be invoked by XORM to customrize the table name
  493. func (t *TAction) TableName() string { return "action" }
  494. // TNotice defines the struct for migrating table notice
  495. type TNotice struct {
  496. ID int64 `xorm:"pk autoincr"`
  497. CreatedUnix int64
  498. }
  499. // TableName will be invoked by XORM to customrize the table name
  500. func (t *TNotice) TableName() string { return "notice" }
  501. // TComment defines the struct for migrating table comment
  502. type TComment struct {
  503. ID int64 `xorm:"pk autoincr"`
  504. CreatedUnix int64
  505. }
  506. // TableName will be invoked by XORM to customrize the table name
  507. func (t *TComment) TableName() string { return "comment" }
  508. // TIssue defines the struct for migrating table issue
  509. type TIssue struct {
  510. ID int64 `xorm:"pk autoincr"`
  511. DeadlineUnix int64
  512. CreatedUnix int64
  513. UpdatedUnix int64
  514. }
  515. // TableName will be invoked by XORM to customrize the table name
  516. func (t *TIssue) TableName() string { return "issue" }
  517. // TMilestone defines the struct for migrating table milestone
  518. type TMilestone struct {
  519. ID int64 `xorm:"pk autoincr"`
  520. DeadlineUnix int64
  521. ClosedDateUnix int64
  522. }
  523. // TableName will be invoked by XORM to customrize the table name
  524. func (t *TMilestone) TableName() string { return "milestone" }
  525. // TAttachment defines the struct for migrating table attachment
  526. type TAttachment struct {
  527. ID int64 `xorm:"pk autoincr"`
  528. CreatedUnix int64
  529. }
  530. // TableName will be invoked by XORM to customrize the table name
  531. func (t *TAttachment) TableName() string { return "attachment" }
  532. // TLoginSource defines the struct for migrating table login_source
  533. type TLoginSource struct {
  534. ID int64 `xorm:"pk autoincr"`
  535. CreatedUnix int64
  536. UpdatedUnix int64
  537. }
  538. // TableName will be invoked by XORM to customrize the table name
  539. func (t *TLoginSource) TableName() string { return "login_source" }
  540. // TPull defines the struct for migrating table pull_request
  541. type TPull struct {
  542. ID int64 `xorm:"pk autoincr"`
  543. MergedUnix int64
  544. }
  545. // TableName will be invoked by XORM to customrize the table name
  546. func (t *TPull) TableName() string { return "pull_request" }
  547. // TRelease defines the struct for migrating table release
  548. type TRelease struct {
  549. ID int64 `xorm:"pk autoincr"`
  550. CreatedUnix int64
  551. }
  552. // TableName will be invoked by XORM to customrize the table name
  553. func (t *TRelease) TableName() string { return "release" }
  554. // TRepo defines the struct for migrating table repository
  555. type TRepo struct {
  556. ID int64 `xorm:"pk autoincr"`
  557. CreatedUnix int64
  558. UpdatedUnix int64
  559. }
  560. // TableName will be invoked by XORM to customrize the table name
  561. func (t *TRepo) TableName() string { return "repository" }
  562. // TMirror defines the struct for migrating table mirror
  563. type TMirror struct {
  564. ID int64 `xorm:"pk autoincr"`
  565. UpdatedUnix int64
  566. NextUpdateUnix int64
  567. }
  568. // TableName will be invoked by XORM to customrize the table name
  569. func (t *TMirror) TableName() string { return "mirror" }
  570. // TPublicKey defines the struct for migrating table public_key
  571. type TPublicKey struct {
  572. ID int64 `xorm:"pk autoincr"`
  573. CreatedUnix int64
  574. UpdatedUnix int64
  575. }
  576. // TableName will be invoked by XORM to customrize the table name
  577. func (t *TPublicKey) TableName() string { return "public_key" }
  578. // TDeployKey defines the struct for migrating table deploy_key
  579. type TDeployKey struct {
  580. ID int64 `xorm:"pk autoincr"`
  581. CreatedUnix int64
  582. UpdatedUnix int64
  583. }
  584. // TableName will be invoked by XORM to customrize the table name
  585. func (t *TDeployKey) TableName() string { return "deploy_key" }
  586. // TAccessToken defines the struct for migrating table access_token
  587. type TAccessToken struct {
  588. ID int64 `xorm:"pk autoincr"`
  589. CreatedUnix int64
  590. UpdatedUnix int64
  591. }
  592. // TableName will be invoked by XORM to customrize the table name
  593. func (t *TAccessToken) TableName() string { return "access_token" }
  594. // TUser defines the struct for migrating table user
  595. type TUser struct {
  596. ID int64 `xorm:"pk autoincr"`
  597. CreatedUnix int64
  598. UpdatedUnix int64
  599. }
  600. // TableName will be invoked by XORM to customrize the table name
  601. func (t *TUser) TableName() string { return "user" }
  602. // TWebhook defines the struct for migrating table webhook
  603. type TWebhook struct {
  604. ID int64 `xorm:"pk autoincr"`
  605. CreatedUnix int64
  606. UpdatedUnix int64
  607. }
  608. // TableName will be invoked by XORM to customrize the table name
  609. func (t *TWebhook) TableName() string { return "webhook" }
  610. func convertDateToUnix(x *xorm.Engine) (err error) {
  611. log.Info("This migration could take up to minutes, please be patient.")
  612. type Bean struct {
  613. ID int64 `xorm:"pk autoincr"`
  614. Created time.Time
  615. Updated time.Time
  616. Merged time.Time
  617. Deadline time.Time
  618. ClosedDate time.Time
  619. NextUpdate time.Time
  620. }
  621. var tables = []struct {
  622. name string
  623. cols []string
  624. bean interface{}
  625. }{
  626. {"action", []string{"created"}, new(TAction)},
  627. {"notice", []string{"created"}, new(TNotice)},
  628. {"comment", []string{"created"}, new(TComment)},
  629. {"issue", []string{"deadline", "created", "updated"}, new(TIssue)},
  630. {"milestone", []string{"deadline", "closed_date"}, new(TMilestone)},
  631. {"attachment", []string{"created"}, new(TAttachment)},
  632. {"login_source", []string{"created", "updated"}, new(TLoginSource)},
  633. {"pull_request", []string{"merged"}, new(TPull)},
  634. {"release", []string{"created"}, new(TRelease)},
  635. {"repository", []string{"created", "updated"}, new(TRepo)},
  636. {"mirror", []string{"updated", "next_update"}, new(TMirror)},
  637. {"public_key", []string{"created", "updated"}, new(TPublicKey)},
  638. {"deploy_key", []string{"created", "updated"}, new(TDeployKey)},
  639. {"access_token", []string{"created", "updated"}, new(TAccessToken)},
  640. {"user", []string{"created", "updated"}, new(TUser)},
  641. {"webhook", []string{"created", "updated"}, new(TWebhook)},
  642. }
  643. for _, table := range tables {
  644. log.Info("Converting table: %s", table.name)
  645. if err = x.Sync2(table.bean); err != nil {
  646. return fmt.Errorf("Sync [table: %s]: %v", table.name, err)
  647. }
  648. offset := 0
  649. for {
  650. beans := make([]*Bean, 0, 100)
  651. if err = x.Table(table.name).Asc("id").Limit(100, offset).Find(&beans); err != nil {
  652. return fmt.Errorf("select beans [table: %s, offset: %d]: %v", table.name, offset, err)
  653. }
  654. log.Trace("Table [%s]: offset: %d, beans: %d", table.name, offset, len(beans))
  655. if len(beans) == 0 {
  656. break
  657. }
  658. offset += 100
  659. baseSQL := "UPDATE `" + table.name + "` SET "
  660. for _, bean := range beans {
  661. valSQLs := make([]string, 0, len(table.cols))
  662. for _, col := range table.cols {
  663. fieldSQL := ""
  664. fieldSQL += col + "_unix = "
  665. switch col {
  666. case "deadline":
  667. if bean.Deadline.IsZero() {
  668. continue
  669. }
  670. fieldSQL += com.ToStr(bean.Deadline.Unix())
  671. case "created":
  672. fieldSQL += com.ToStr(bean.Created.Unix())
  673. case "updated":
  674. fieldSQL += com.ToStr(bean.Updated.Unix())
  675. case "closed_date":
  676. fieldSQL += com.ToStr(bean.ClosedDate.Unix())
  677. case "merged":
  678. fieldSQL += com.ToStr(bean.Merged.Unix())
  679. case "next_update":
  680. fieldSQL += com.ToStr(bean.NextUpdate.Unix())
  681. }
  682. valSQLs = append(valSQLs, fieldSQL)
  683. }
  684. if len(valSQLs) == 0 {
  685. continue
  686. }
  687. if _, err = x.Exec(baseSQL + strings.Join(valSQLs, ",") + " WHERE id = " + com.ToStr(bean.ID)); err != nil {
  688. return fmt.Errorf("update bean [table: %s, id: %d]: %v", table.name, bean.ID, err)
  689. }
  690. }
  691. }
  692. }
  693. return nil
  694. }