Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

migrations.go 26KB

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