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

migrations.go 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  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. // v58 -> v59
  158. NewMigration("add label descriptions", addLabelsDescriptions),
  159. // v59 -> v60
  160. NewMigration("add merge whitelist for protected branches", addProtectedBranchMergeWhitelist),
  161. // v60 -> v61
  162. NewMigration("add is_fsck_enabled column for repos", addFsckEnabledToRepo),
  163. // v61 -> v62
  164. NewMigration("add size column for attachments", addSizeToAttachment),
  165. // v62 -> v63
  166. NewMigration("add last used passcode column for TOTP", addLastUsedPasscodeTOTP),
  167. // v63 -> v64
  168. NewMigration("add language column for user setting", addLanguageSetting),
  169. // v64 -> v65
  170. NewMigration("add multiple assignees", addMultipleAssignees),
  171. // v65 -> v66
  172. NewMigration("add u2f", addU2FReg),
  173. // v66 -> v67
  174. NewMigration("add login source id column for public_key table", addLoginSourceIDToPublicKeyTable),
  175. // v67 -> v68
  176. NewMigration("remove stale watches", removeStaleWatches),
  177. // v68 -> V69
  178. NewMigration("Reformat and remove incorrect topics", reformatAndRemoveIncorrectTopics),
  179. // v69 -> v70
  180. NewMigration("move team units to team_unit table", moveTeamUnitsToTeamUnitTable),
  181. }
  182. // Migrate database to current version
  183. func Migrate(x *xorm.Engine) error {
  184. if err := x.Sync(new(Version)); err != nil {
  185. return fmt.Errorf("sync: %v", err)
  186. }
  187. currentVersion := &Version{ID: 1}
  188. has, err := x.Get(currentVersion)
  189. if err != nil {
  190. return fmt.Errorf("get: %v", err)
  191. } else if !has {
  192. // If the version record does not exist we think
  193. // it is a fresh installation and we can skip all migrations.
  194. currentVersion.ID = 0
  195. currentVersion.Version = int64(minDBVersion + len(migrations))
  196. if _, err = x.InsertOne(currentVersion); err != nil {
  197. return fmt.Errorf("insert: %v", err)
  198. }
  199. }
  200. v := currentVersion.Version
  201. if minDBVersion > v {
  202. log.Fatal(4, `Gitea no longer supports auto-migration from your previously installed version.
  203. Please try to upgrade to a lower version (>= v0.6.0) first, then upgrade to current version.`)
  204. return nil
  205. }
  206. if int(v-minDBVersion) > len(migrations) {
  207. // User downgraded Gitea.
  208. currentVersion.Version = int64(len(migrations) + minDBVersion)
  209. _, err = x.ID(1).Update(currentVersion)
  210. return err
  211. }
  212. for i, m := range migrations[v-minDBVersion:] {
  213. log.Info("Migration: %s", m.Description())
  214. if err = m.Migrate(x); err != nil {
  215. return fmt.Errorf("do migrate: %v", err)
  216. }
  217. currentVersion.Version = v + int64(i) + 1
  218. if _, err = x.ID(1).Update(currentVersion); err != nil {
  219. return err
  220. }
  221. }
  222. return nil
  223. }
  224. func dropTableColumns(sess *xorm.Session, tableName string, columnNames ...string) (err error) {
  225. if tableName == "" || len(columnNames) == 0 {
  226. return nil
  227. }
  228. switch {
  229. case setting.UseSQLite3:
  230. log.Warn("Unable to drop columns in SQLite")
  231. case setting.UseMySQL, setting.UseTiDB, setting.UsePostgreSQL:
  232. cols := ""
  233. for _, col := range columnNames {
  234. if cols != "" {
  235. cols += ", "
  236. }
  237. cols += "DROP COLUMN `" + col + "`"
  238. }
  239. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` %s", tableName, cols)); err != nil {
  240. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  241. }
  242. case setting.UseMSSQL:
  243. cols := ""
  244. for _, col := range columnNames {
  245. if cols != "" {
  246. cols += ", "
  247. }
  248. cols += "`" + strings.ToLower(col) + "`"
  249. }
  250. 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'))",
  251. tableName, strings.Replace(cols, "`", "'", -1))
  252. constraints := make([]string, 0)
  253. if err := sess.SQL(sql).Find(&constraints); err != nil {
  254. sess.Rollback()
  255. return fmt.Errorf("Find constraints: %v", err)
  256. }
  257. for _, constraint := range constraints {
  258. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` DROP CONSTRAINT `%s`", tableName, constraint)); err != nil {
  259. sess.Rollback()
  260. return fmt.Errorf("Drop table `%s` constraint `%s`: %v", tableName, constraint, err)
  261. }
  262. }
  263. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` DROP COLUMN %s", tableName, cols)); err != nil {
  264. sess.Rollback()
  265. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  266. }
  267. return sess.Commit()
  268. default:
  269. log.Fatal(4, "Unrecognized DB")
  270. }
  271. return nil
  272. }
  273. func fixLocaleFileLoadPanic(_ *xorm.Engine) error {
  274. cfg, err := ini.Load(setting.CustomConf)
  275. if err != nil {
  276. return fmt.Errorf("load custom config: %v", err)
  277. }
  278. cfg.DeleteSection("i18n")
  279. if err = cfg.SaveTo(setting.CustomConf); err != nil {
  280. return fmt.Errorf("save custom config: %v", err)
  281. }
  282. setting.Langs = strings.Split(strings.Replace(strings.Join(setting.Langs, ","), "fr-CA", "fr-FR", 1), ",")
  283. return nil
  284. }
  285. func trimCommitActionAppURLPrefix(x *xorm.Engine) error {
  286. type PushCommit struct {
  287. Sha1 string
  288. Message string
  289. AuthorEmail string
  290. AuthorName string
  291. }
  292. type PushCommits struct {
  293. Len int
  294. Commits []*PushCommit
  295. CompareURL string `json:"CompareUrl"`
  296. }
  297. type Action struct {
  298. ID int64 `xorm:"pk autoincr"`
  299. Content string `xorm:"TEXT"`
  300. }
  301. results, err := x.Query("SELECT `id`,`content` FROM `action` WHERE `op_type`=?", 5)
  302. if err != nil {
  303. return fmt.Errorf("select commit actions: %v", err)
  304. }
  305. sess := x.NewSession()
  306. defer sess.Close()
  307. if err = sess.Begin(); err != nil {
  308. return err
  309. }
  310. var pushCommits *PushCommits
  311. for _, action := range results {
  312. actID := com.StrTo(string(action["id"])).MustInt64()
  313. if actID == 0 {
  314. continue
  315. }
  316. pushCommits = new(PushCommits)
  317. if err = json.Unmarshal(action["content"], pushCommits); err != nil {
  318. return fmt.Errorf("unmarshal action content[%d]: %v", actID, err)
  319. }
  320. infos := strings.Split(pushCommits.CompareURL, "/")
  321. if len(infos) <= 4 {
  322. continue
  323. }
  324. pushCommits.CompareURL = strings.Join(infos[len(infos)-4:], "/")
  325. p, err := json.Marshal(pushCommits)
  326. if err != nil {
  327. return fmt.Errorf("marshal action content[%d]: %v", actID, err)
  328. }
  329. if _, err = sess.Id(actID).Update(&Action{
  330. Content: string(p),
  331. }); err != nil {
  332. return fmt.Errorf("update action[%d]: %v", actID, err)
  333. }
  334. }
  335. return sess.Commit()
  336. }
  337. func issueToIssueLabel(x *xorm.Engine) error {
  338. type IssueLabel struct {
  339. ID int64 `xorm:"pk autoincr"`
  340. IssueID int64 `xorm:"UNIQUE(s)"`
  341. LabelID int64 `xorm:"UNIQUE(s)"`
  342. }
  343. issueLabels := make([]*IssueLabel, 0, 50)
  344. results, err := x.Query("SELECT `id`,`label_ids` FROM `issue`")
  345. if err != nil {
  346. if strings.Contains(err.Error(), "no such column") ||
  347. strings.Contains(err.Error(), "Unknown column") {
  348. return nil
  349. }
  350. return fmt.Errorf("select issues: %v", err)
  351. }
  352. for _, issue := range results {
  353. issueID := com.StrTo(issue["id"]).MustInt64()
  354. // Just in case legacy code can have duplicated IDs for same label.
  355. mark := make(map[int64]bool)
  356. for _, idStr := range strings.Split(string(issue["label_ids"]), "|") {
  357. labelID := com.StrTo(strings.TrimPrefix(idStr, "$")).MustInt64()
  358. if labelID == 0 || mark[labelID] {
  359. continue
  360. }
  361. mark[labelID] = true
  362. issueLabels = append(issueLabels, &IssueLabel{
  363. IssueID: issueID,
  364. LabelID: labelID,
  365. })
  366. }
  367. }
  368. sess := x.NewSession()
  369. defer sess.Close()
  370. if err = sess.Begin(); err != nil {
  371. return err
  372. }
  373. if err = sess.Sync2(new(IssueLabel)); err != nil {
  374. return fmt.Errorf("Sync2: %v", err)
  375. } else if _, err = sess.Insert(issueLabels); err != nil {
  376. return fmt.Errorf("insert issue-labels: %v", err)
  377. }
  378. return sess.Commit()
  379. }
  380. func attachmentRefactor(x *xorm.Engine) error {
  381. type Attachment struct {
  382. ID int64 `xorm:"pk autoincr"`
  383. UUID string `xorm:"uuid INDEX"`
  384. // For rename purpose.
  385. Path string `xorm:"-"`
  386. NewPath string `xorm:"-"`
  387. }
  388. results, err := x.Query("SELECT * FROM `attachment`")
  389. if err != nil {
  390. return fmt.Errorf("select attachments: %v", err)
  391. }
  392. attachments := make([]*Attachment, 0, len(results))
  393. for _, attach := range results {
  394. if !com.IsExist(string(attach["path"])) {
  395. // If the attachment is already missing, there is no point to update it.
  396. continue
  397. }
  398. attachments = append(attachments, &Attachment{
  399. ID: com.StrTo(attach["id"]).MustInt64(),
  400. UUID: gouuid.NewV4().String(),
  401. Path: string(attach["path"]),
  402. })
  403. }
  404. sess := x.NewSession()
  405. defer sess.Close()
  406. if err = sess.Begin(); err != nil {
  407. return err
  408. }
  409. if err = sess.Sync2(new(Attachment)); err != nil {
  410. return fmt.Errorf("Sync2: %v", err)
  411. }
  412. // Note: Roll back for rename can be a dead loop,
  413. // so produces a backup file.
  414. var buf bytes.Buffer
  415. buf.WriteString("# old path -> new path\n")
  416. // Update database first because this is where error happens the most often.
  417. for _, attach := range attachments {
  418. if _, err = sess.Id(attach.ID).Update(attach); err != nil {
  419. return err
  420. }
  421. attach.NewPath = path.Join(setting.AttachmentPath, attach.UUID[0:1], attach.UUID[1:2], attach.UUID)
  422. buf.WriteString(attach.Path)
  423. buf.WriteString("\t")
  424. buf.WriteString(attach.NewPath)
  425. buf.WriteString("\n")
  426. }
  427. // Then rename attachments.
  428. isSucceed := true
  429. defer func() {
  430. if isSucceed {
  431. return
  432. }
  433. dumpPath := path.Join(setting.LogRootPath, "attachment_path.dump")
  434. ioutil.WriteFile(dumpPath, buf.Bytes(), 0666)
  435. log.Info("Failed to rename some attachments, old and new paths are saved into: %s", dumpPath)
  436. }()
  437. for _, attach := range attachments {
  438. if err = os.MkdirAll(path.Dir(attach.NewPath), os.ModePerm); err != nil {
  439. isSucceed = false
  440. return err
  441. }
  442. if err = os.Rename(attach.Path, attach.NewPath); err != nil {
  443. isSucceed = false
  444. return err
  445. }
  446. }
  447. return sess.Commit()
  448. }
  449. func renamePullRequestFields(x *xorm.Engine) (err error) {
  450. type PullRequest struct {
  451. ID int64 `xorm:"pk autoincr"`
  452. PullID int64 `xorm:"INDEX"`
  453. PullIndex int64
  454. HeadBarcnh string
  455. IssueID int64 `xorm:"INDEX"`
  456. Index int64
  457. HeadBranch string
  458. }
  459. if err = x.Sync(new(PullRequest)); err != nil {
  460. return fmt.Errorf("sync: %v", err)
  461. }
  462. results, err := x.Query("SELECT `id`,`pull_id`,`pull_index`,`head_barcnh` FROM `pull_request`")
  463. if err != nil {
  464. if strings.Contains(err.Error(), "no such column") {
  465. return nil
  466. }
  467. return fmt.Errorf("select pull requests: %v", err)
  468. }
  469. sess := x.NewSession()
  470. defer sess.Close()
  471. if err = sess.Begin(); err != nil {
  472. return err
  473. }
  474. var pull *PullRequest
  475. for _, pr := range results {
  476. pull = &PullRequest{
  477. ID: com.StrTo(pr["id"]).MustInt64(),
  478. IssueID: com.StrTo(pr["pull_id"]).MustInt64(),
  479. Index: com.StrTo(pr["pull_index"]).MustInt64(),
  480. HeadBranch: string(pr["head_barcnh"]),
  481. }
  482. if pull.Index == 0 {
  483. continue
  484. }
  485. if _, err = sess.Id(pull.ID).Update(pull); err != nil {
  486. return err
  487. }
  488. }
  489. return sess.Commit()
  490. }
  491. func cleanUpMigrateRepoInfo(x *xorm.Engine) (err error) {
  492. type (
  493. User struct {
  494. ID int64 `xorm:"pk autoincr"`
  495. LowerName string
  496. }
  497. Repository struct {
  498. ID int64 `xorm:"pk autoincr"`
  499. OwnerID int64
  500. LowerName string
  501. }
  502. )
  503. repos := make([]*Repository, 0, 25)
  504. if err = x.Where("is_mirror=?", false).Find(&repos); err != nil {
  505. return fmt.Errorf("select all non-mirror repositories: %v", err)
  506. }
  507. var user *User
  508. for _, repo := range repos {
  509. user = &User{ID: repo.OwnerID}
  510. has, err := x.Get(user)
  511. if err != nil {
  512. return fmt.Errorf("get owner of repository[%d - %d]: %v", repo.ID, repo.OwnerID, err)
  513. } else if !has {
  514. continue
  515. }
  516. configPath := filepath.Join(setting.RepoRootPath, user.LowerName, repo.LowerName+".git/config")
  517. // In case repository file is somehow missing.
  518. if !com.IsFile(configPath) {
  519. continue
  520. }
  521. cfg, err := ini.Load(configPath)
  522. if err != nil {
  523. return fmt.Errorf("open config file: %v", err)
  524. }
  525. cfg.DeleteSection("remote \"origin\"")
  526. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  527. return fmt.Errorf("save config file: %v", err)
  528. }
  529. }
  530. return nil
  531. }
  532. func generateOrgRandsAndSalt(x *xorm.Engine) (err error) {
  533. type User struct {
  534. ID int64 `xorm:"pk autoincr"`
  535. Rands string `xorm:"VARCHAR(10)"`
  536. Salt string `xorm:"VARCHAR(10)"`
  537. }
  538. orgs := make([]*User, 0, 10)
  539. if err = x.Where("type=1").And("rands=''").Find(&orgs); err != nil {
  540. return fmt.Errorf("select all organizations: %v", err)
  541. }
  542. sess := x.NewSession()
  543. defer sess.Close()
  544. if err = sess.Begin(); err != nil {
  545. return err
  546. }
  547. for _, org := range orgs {
  548. if org.Rands, err = generate.GetRandomString(10); err != nil {
  549. return err
  550. }
  551. if org.Salt, err = generate.GetRandomString(10); err != nil {
  552. return err
  553. }
  554. if _, err = sess.Id(org.ID).Update(org); err != nil {
  555. return err
  556. }
  557. }
  558. return sess.Commit()
  559. }
  560. // TAction defines the struct for migrating table action
  561. type TAction struct {
  562. ID int64 `xorm:"pk autoincr"`
  563. CreatedUnix int64
  564. }
  565. // TableName will be invoked by XORM to customrize the table name
  566. func (t *TAction) TableName() string { return "action" }
  567. // TNotice defines the struct for migrating table notice
  568. type TNotice struct {
  569. ID int64 `xorm:"pk autoincr"`
  570. CreatedUnix int64
  571. }
  572. // TableName will be invoked by XORM to customrize the table name
  573. func (t *TNotice) TableName() string { return "notice" }
  574. // TComment defines the struct for migrating table comment
  575. type TComment struct {
  576. ID int64 `xorm:"pk autoincr"`
  577. CreatedUnix int64
  578. }
  579. // TableName will be invoked by XORM to customrize the table name
  580. func (t *TComment) TableName() string { return "comment" }
  581. // TIssue defines the struct for migrating table issue
  582. type TIssue struct {
  583. ID int64 `xorm:"pk autoincr"`
  584. DeadlineUnix int64
  585. CreatedUnix int64
  586. UpdatedUnix int64
  587. }
  588. // TableName will be invoked by XORM to customrize the table name
  589. func (t *TIssue) TableName() string { return "issue" }
  590. // TMilestone defines the struct for migrating table milestone
  591. type TMilestone struct {
  592. ID int64 `xorm:"pk autoincr"`
  593. DeadlineUnix int64
  594. ClosedDateUnix int64
  595. }
  596. // TableName will be invoked by XORM to customrize the table name
  597. func (t *TMilestone) TableName() string { return "milestone" }
  598. // TAttachment defines the struct for migrating table attachment
  599. type TAttachment struct {
  600. ID int64 `xorm:"pk autoincr"`
  601. CreatedUnix int64
  602. }
  603. // TableName will be invoked by XORM to customrize the table name
  604. func (t *TAttachment) TableName() string { return "attachment" }
  605. // TLoginSource defines the struct for migrating table login_source
  606. type TLoginSource struct {
  607. ID int64 `xorm:"pk autoincr"`
  608. CreatedUnix int64
  609. UpdatedUnix int64
  610. }
  611. // TableName will be invoked by XORM to customrize the table name
  612. func (t *TLoginSource) TableName() string { return "login_source" }
  613. // TPull defines the struct for migrating table pull_request
  614. type TPull struct {
  615. ID int64 `xorm:"pk autoincr"`
  616. MergedUnix int64
  617. }
  618. // TableName will be invoked by XORM to customrize the table name
  619. func (t *TPull) TableName() string { return "pull_request" }
  620. // TRelease defines the struct for migrating table release
  621. type TRelease struct {
  622. ID int64 `xorm:"pk autoincr"`
  623. CreatedUnix int64
  624. }
  625. // TableName will be invoked by XORM to customrize the table name
  626. func (t *TRelease) TableName() string { return "release" }
  627. // TRepo defines the struct for migrating table repository
  628. type TRepo struct {
  629. ID int64 `xorm:"pk autoincr"`
  630. CreatedUnix int64
  631. UpdatedUnix int64
  632. }
  633. // TableName will be invoked by XORM to customrize the table name
  634. func (t *TRepo) TableName() string { return "repository" }
  635. // TMirror defines the struct for migrating table mirror
  636. type TMirror struct {
  637. ID int64 `xorm:"pk autoincr"`
  638. UpdatedUnix int64
  639. NextUpdateUnix int64
  640. }
  641. // TableName will be invoked by XORM to customrize the table name
  642. func (t *TMirror) TableName() string { return "mirror" }
  643. // TPublicKey defines the struct for migrating table public_key
  644. type TPublicKey struct {
  645. ID int64 `xorm:"pk autoincr"`
  646. CreatedUnix int64
  647. UpdatedUnix int64
  648. }
  649. // TableName will be invoked by XORM to customrize the table name
  650. func (t *TPublicKey) TableName() string { return "public_key" }
  651. // TDeployKey defines the struct for migrating table deploy_key
  652. type TDeployKey struct {
  653. ID int64 `xorm:"pk autoincr"`
  654. CreatedUnix int64
  655. UpdatedUnix int64
  656. }
  657. // TableName will be invoked by XORM to customrize the table name
  658. func (t *TDeployKey) TableName() string { return "deploy_key" }
  659. // TAccessToken defines the struct for migrating table access_token
  660. type TAccessToken struct {
  661. ID int64 `xorm:"pk autoincr"`
  662. CreatedUnix int64
  663. UpdatedUnix int64
  664. }
  665. // TableName will be invoked by XORM to customrize the table name
  666. func (t *TAccessToken) TableName() string { return "access_token" }
  667. // TUser defines the struct for migrating table user
  668. type TUser struct {
  669. ID int64 `xorm:"pk autoincr"`
  670. CreatedUnix int64
  671. UpdatedUnix int64
  672. }
  673. // TableName will be invoked by XORM to customrize the table name
  674. func (t *TUser) TableName() string { return "user" }
  675. // TWebhook defines the struct for migrating table webhook
  676. type TWebhook struct {
  677. ID int64 `xorm:"pk autoincr"`
  678. CreatedUnix int64
  679. UpdatedUnix int64
  680. }
  681. // TableName will be invoked by XORM to customrize the table name
  682. func (t *TWebhook) TableName() string { return "webhook" }
  683. func convertDateToUnix(x *xorm.Engine) (err error) {
  684. log.Info("This migration could take up to minutes, please be patient.")
  685. type Bean struct {
  686. ID int64 `xorm:"pk autoincr"`
  687. Created time.Time
  688. Updated time.Time
  689. Merged time.Time
  690. Deadline time.Time
  691. ClosedDate time.Time
  692. NextUpdate time.Time
  693. }
  694. var tables = []struct {
  695. name string
  696. cols []string
  697. bean interface{}
  698. }{
  699. {"action", []string{"created"}, new(TAction)},
  700. {"notice", []string{"created"}, new(TNotice)},
  701. {"comment", []string{"created"}, new(TComment)},
  702. {"issue", []string{"deadline", "created", "updated"}, new(TIssue)},
  703. {"milestone", []string{"deadline", "closed_date"}, new(TMilestone)},
  704. {"attachment", []string{"created"}, new(TAttachment)},
  705. {"login_source", []string{"created", "updated"}, new(TLoginSource)},
  706. {"pull_request", []string{"merged"}, new(TPull)},
  707. {"release", []string{"created"}, new(TRelease)},
  708. {"repository", []string{"created", "updated"}, new(TRepo)},
  709. {"mirror", []string{"updated", "next_update"}, new(TMirror)},
  710. {"public_key", []string{"created", "updated"}, new(TPublicKey)},
  711. {"deploy_key", []string{"created", "updated"}, new(TDeployKey)},
  712. {"access_token", []string{"created", "updated"}, new(TAccessToken)},
  713. {"user", []string{"created", "updated"}, new(TUser)},
  714. {"webhook", []string{"created", "updated"}, new(TWebhook)},
  715. }
  716. for _, table := range tables {
  717. log.Info("Converting table: %s", table.name)
  718. if err = x.Sync2(table.bean); err != nil {
  719. return fmt.Errorf("Sync [table: %s]: %v", table.name, err)
  720. }
  721. offset := 0
  722. for {
  723. beans := make([]*Bean, 0, 100)
  724. if err = x.Table(table.name).Asc("id").Limit(100, offset).Find(&beans); err != nil {
  725. return fmt.Errorf("select beans [table: %s, offset: %d]: %v", table.name, offset, err)
  726. }
  727. log.Trace("Table [%s]: offset: %d, beans: %d", table.name, offset, len(beans))
  728. if len(beans) == 0 {
  729. break
  730. }
  731. offset += 100
  732. baseSQL := "UPDATE `" + table.name + "` SET "
  733. for _, bean := range beans {
  734. valSQLs := make([]string, 0, len(table.cols))
  735. for _, col := range table.cols {
  736. fieldSQL := ""
  737. fieldSQL += col + "_unix = "
  738. switch col {
  739. case "deadline":
  740. if bean.Deadline.IsZero() {
  741. continue
  742. }
  743. fieldSQL += com.ToStr(bean.Deadline.Unix())
  744. case "created":
  745. fieldSQL += com.ToStr(bean.Created.Unix())
  746. case "updated":
  747. fieldSQL += com.ToStr(bean.Updated.Unix())
  748. case "closed_date":
  749. fieldSQL += com.ToStr(bean.ClosedDate.Unix())
  750. case "merged":
  751. fieldSQL += com.ToStr(bean.Merged.Unix())
  752. case "next_update":
  753. fieldSQL += com.ToStr(bean.NextUpdate.Unix())
  754. }
  755. valSQLs = append(valSQLs, fieldSQL)
  756. }
  757. if len(valSQLs) == 0 {
  758. continue
  759. }
  760. if _, err = x.Exec(baseSQL + strings.Join(valSQLs, ",") + " WHERE id = " + com.ToStr(bean.ID)); err != nil {
  761. return fmt.Errorf("update bean [table: %s, id: %d]: %v", table.name, bean.ID, err)
  762. }
  763. }
  764. }
  765. }
  766. return nil
  767. }