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 23KB

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