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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  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. // This is a sequence of migrations. Add new migrations to the bottom of the list.
  51. // If you want to "retire" a migration, remove it from the top of the list and
  52. // update minDBVersion accordingly
  53. var migrations = []Migration{
  54. // v0 -> v4: before 0.6.0 -> 0.7.33
  55. NewMigration("fix locale file load panic", fixLocaleFileLoadPanic), // V4 -> V5:v0.6.0
  56. NewMigration("trim action compare URL prefix", trimCommitActionAppURLPrefix), // V5 -> V6:v0.6.3
  57. NewMigration("generate issue-label from issue", issueToIssueLabel), // V6 -> V7:v0.6.4
  58. NewMigration("refactor attachment table", attachmentRefactor), // V7 -> V8:v0.6.4
  59. NewMigration("rename pull request fields", renamePullRequestFields), // V8 -> V9:v0.6.16
  60. NewMigration("clean up migrate repo info", cleanUpMigrateRepoInfo), // V9 -> V10:v0.6.20
  61. NewMigration("generate rands and salt for organizations", generateOrgRandsAndSalt), // V10 -> V11:v0.8.5
  62. NewMigration("convert date to unix timestamp", convertDateToUnix), // V11 -> V12:v0.9.2
  63. NewMigration("convert LDAP UseSSL option to SecurityProtocol", ldapUseSSLToSecurityProtocol), // V12 -> V13:v0.9.37
  64. // v13 -> v14:v0.9.87
  65. NewMigration("set comment updated with created", setCommentUpdatedWithCreated),
  66. // v14 -> v15
  67. NewMigration("create user column diff view style", createUserColumnDiffViewStyle),
  68. // v15 -> v16
  69. NewMigration("create user column allow create organization", createAllowCreateOrganizationColumn),
  70. // V16 -> v17
  71. NewMigration("create repo unit table and add units for all repos", addUnitsToTables),
  72. // v17 -> v18
  73. NewMigration("set protect branches updated with created", setProtectedBranchUpdatedWithCreated),
  74. // v18 -> v19
  75. NewMigration("add external login user", addExternalLoginUser),
  76. // v19 -> v20
  77. NewMigration("generate and migrate Git hooks", generateAndMigrateGitHooks),
  78. // v20 -> v21
  79. NewMigration("use new avatar path name for security reason", useNewNameAvatars),
  80. // v21 -> v22
  81. NewMigration("rewrite authorized_keys file via new format", useNewPublickeyFormat),
  82. // v22 -> v23
  83. NewMigration("generate and migrate wiki Git hooks", generateAndMigrateWikiGitHooks),
  84. // v23 -> v24
  85. NewMigration("add user openid table", addUserOpenID),
  86. // v24 -> v25
  87. NewMigration("change the key_id and primary_key_id type", changeGPGKeysColumns),
  88. // v25 -> v26
  89. NewMigration("add show field in user openid table", addUserOpenIDShow),
  90. // v26 -> v27
  91. NewMigration("generate and migrate repo and wiki Git hooks", generateAndMigrateGitHookChains),
  92. // v27 -> v28
  93. NewMigration("change mirror interval from hours to time.Duration", convertIntervalToDuration),
  94. // v28 -> v29
  95. NewMigration("add field for repo size", addRepoSize),
  96. // v29 -> v30
  97. NewMigration("add commit status table", addCommitStatus),
  98. // v30 -> 31
  99. NewMigration("add primary key to external login user", addExternalLoginUserPK),
  100. // 31 -> 32
  101. NewMigration("add field for login source synchronization", addLoginSourceSyncEnabledColumn),
  102. // v32 -> v33
  103. NewMigration("add units for team", addUnitsToRepoTeam),
  104. // v33 -> v34
  105. NewMigration("remove columns from action", removeActionColumns),
  106. // v34 -> v35
  107. NewMigration("give all units to owner teams", giveAllUnitsToOwnerTeams),
  108. // v35 -> v36
  109. NewMigration("adds comment to an action", addCommentIDToAction),
  110. // v36 -> v37
  111. NewMigration("regenerate git hooks", regenerateGitHooks36),
  112. // v37 -> v38
  113. NewMigration("unescape user full names", unescapeUserFullNames),
  114. // v38 -> v39
  115. NewMigration("remove commits and settings unit types", removeCommitsUnitType),
  116. }
  117. // Migrate database to current version
  118. func Migrate(x *xorm.Engine) error {
  119. if err := x.Sync(new(Version)); err != nil {
  120. return fmt.Errorf("sync: %v", err)
  121. }
  122. currentVersion := &Version{ID: 1}
  123. has, err := x.Get(currentVersion)
  124. if err != nil {
  125. return fmt.Errorf("get: %v", err)
  126. } else if !has {
  127. // If the version record does not exist we think
  128. // it is a fresh installation and we can skip all migrations.
  129. currentVersion.ID = 0
  130. currentVersion.Version = int64(minDBVersion + len(migrations))
  131. if _, err = x.InsertOne(currentVersion); err != nil {
  132. return fmt.Errorf("insert: %v", err)
  133. }
  134. }
  135. v := currentVersion.Version
  136. if minDBVersion > v {
  137. log.Fatal(4, `Gitea no longer supports auto-migration from your previously installed version.
  138. Please try to upgrade to a lower version (>= v0.6.0) first, then upgrade to current version.`)
  139. return nil
  140. }
  141. if int(v-minDBVersion) > len(migrations) {
  142. // User downgraded Gitea.
  143. currentVersion.Version = int64(len(migrations) + minDBVersion)
  144. _, err = x.Id(1).Update(currentVersion)
  145. return err
  146. }
  147. for i, m := range migrations[v-minDBVersion:] {
  148. log.Info("Migration: %s", m.Description())
  149. if err = m.Migrate(x); err != nil {
  150. return fmt.Errorf("do migrate: %v", err)
  151. }
  152. currentVersion.Version = v + int64(i) + 1
  153. if _, err = x.Id(1).Update(currentVersion); err != nil {
  154. return err
  155. }
  156. }
  157. return nil
  158. }
  159. func fixLocaleFileLoadPanic(_ *xorm.Engine) error {
  160. cfg, err := ini.Load(setting.CustomConf)
  161. if err != nil {
  162. return fmt.Errorf("load custom config: %v", err)
  163. }
  164. cfg.DeleteSection("i18n")
  165. if err = cfg.SaveTo(setting.CustomConf); err != nil {
  166. return fmt.Errorf("save custom config: %v", err)
  167. }
  168. setting.Langs = strings.Split(strings.Replace(strings.Join(setting.Langs, ","), "fr-CA", "fr-FR", 1), ",")
  169. return nil
  170. }
  171. func trimCommitActionAppURLPrefix(x *xorm.Engine) error {
  172. type PushCommit struct {
  173. Sha1 string
  174. Message string
  175. AuthorEmail string
  176. AuthorName string
  177. }
  178. type PushCommits struct {
  179. Len int
  180. Commits []*PushCommit
  181. CompareURL string `json:"CompareUrl"`
  182. }
  183. type Action struct {
  184. ID int64 `xorm:"pk autoincr"`
  185. Content string `xorm:"TEXT"`
  186. }
  187. results, err := x.Query("SELECT `id`,`content` FROM `action` WHERE `op_type`=?", 5)
  188. if err != nil {
  189. return fmt.Errorf("select commit actions: %v", err)
  190. }
  191. sess := x.NewSession()
  192. defer sess.Close()
  193. if err = sess.Begin(); err != nil {
  194. return err
  195. }
  196. var pushCommits *PushCommits
  197. for _, action := range results {
  198. actID := com.StrTo(string(action["id"])).MustInt64()
  199. if actID == 0 {
  200. continue
  201. }
  202. pushCommits = new(PushCommits)
  203. if err = json.Unmarshal(action["content"], pushCommits); err != nil {
  204. return fmt.Errorf("unmarshal action content[%d]: %v", actID, err)
  205. }
  206. infos := strings.Split(pushCommits.CompareURL, "/")
  207. if len(infos) <= 4 {
  208. continue
  209. }
  210. pushCommits.CompareURL = strings.Join(infos[len(infos)-4:], "/")
  211. p, err := json.Marshal(pushCommits)
  212. if err != nil {
  213. return fmt.Errorf("marshal action content[%d]: %v", actID, err)
  214. }
  215. if _, err = sess.Id(actID).Update(&Action{
  216. Content: string(p),
  217. }); err != nil {
  218. return fmt.Errorf("update action[%d]: %v", actID, err)
  219. }
  220. }
  221. return sess.Commit()
  222. }
  223. func issueToIssueLabel(x *xorm.Engine) error {
  224. type IssueLabel struct {
  225. ID int64 `xorm:"pk autoincr"`
  226. IssueID int64 `xorm:"UNIQUE(s)"`
  227. LabelID int64 `xorm:"UNIQUE(s)"`
  228. }
  229. issueLabels := make([]*IssueLabel, 0, 50)
  230. results, err := x.Query("SELECT `id`,`label_ids` FROM `issue`")
  231. if err != nil {
  232. if strings.Contains(err.Error(), "no such column") ||
  233. strings.Contains(err.Error(), "Unknown column") {
  234. return nil
  235. }
  236. return fmt.Errorf("select issues: %v", err)
  237. }
  238. for _, issue := range results {
  239. issueID := com.StrTo(issue["id"]).MustInt64()
  240. // Just in case legacy code can have duplicated IDs for same label.
  241. mark := make(map[int64]bool)
  242. for _, idStr := range strings.Split(string(issue["label_ids"]), "|") {
  243. labelID := com.StrTo(strings.TrimPrefix(idStr, "$")).MustInt64()
  244. if labelID == 0 || mark[labelID] {
  245. continue
  246. }
  247. mark[labelID] = true
  248. issueLabels = append(issueLabels, &IssueLabel{
  249. IssueID: issueID,
  250. LabelID: labelID,
  251. })
  252. }
  253. }
  254. sess := x.NewSession()
  255. defer sess.Close()
  256. if err = sess.Begin(); err != nil {
  257. return err
  258. }
  259. if err = sess.Sync2(new(IssueLabel)); err != nil {
  260. return fmt.Errorf("Sync2: %v", err)
  261. } else if _, err = sess.Insert(issueLabels); err != nil {
  262. return fmt.Errorf("insert issue-labels: %v", err)
  263. }
  264. return sess.Commit()
  265. }
  266. func attachmentRefactor(x *xorm.Engine) error {
  267. type Attachment struct {
  268. ID int64 `xorm:"pk autoincr"`
  269. UUID string `xorm:"uuid INDEX"`
  270. // For rename purpose.
  271. Path string `xorm:"-"`
  272. NewPath string `xorm:"-"`
  273. }
  274. results, err := x.Query("SELECT * FROM `attachment`")
  275. if err != nil {
  276. return fmt.Errorf("select attachments: %v", err)
  277. }
  278. attachments := make([]*Attachment, 0, len(results))
  279. for _, attach := range results {
  280. if !com.IsExist(string(attach["path"])) {
  281. // If the attachment is already missing, there is no point to update it.
  282. continue
  283. }
  284. attachments = append(attachments, &Attachment{
  285. ID: com.StrTo(attach["id"]).MustInt64(),
  286. UUID: gouuid.NewV4().String(),
  287. Path: string(attach["path"]),
  288. })
  289. }
  290. sess := x.NewSession()
  291. defer sess.Close()
  292. if err = sess.Begin(); err != nil {
  293. return err
  294. }
  295. if err = sess.Sync2(new(Attachment)); err != nil {
  296. return fmt.Errorf("Sync2: %v", err)
  297. }
  298. // Note: Roll back for rename can be a dead loop,
  299. // so produces a backup file.
  300. var buf bytes.Buffer
  301. buf.WriteString("# old path -> new path\n")
  302. // Update database first because this is where error happens the most often.
  303. for _, attach := range attachments {
  304. if _, err = sess.Id(attach.ID).Update(attach); err != nil {
  305. return err
  306. }
  307. attach.NewPath = path.Join(setting.AttachmentPath, attach.UUID[0:1], attach.UUID[1:2], attach.UUID)
  308. buf.WriteString(attach.Path)
  309. buf.WriteString("\t")
  310. buf.WriteString(attach.NewPath)
  311. buf.WriteString("\n")
  312. }
  313. // Then rename attachments.
  314. isSucceed := true
  315. defer func() {
  316. if isSucceed {
  317. return
  318. }
  319. dumpPath := path.Join(setting.LogRootPath, "attachment_path.dump")
  320. ioutil.WriteFile(dumpPath, buf.Bytes(), 0666)
  321. log.Info("Failed to rename some attachments, old and new paths are saved into: %s", dumpPath)
  322. }()
  323. for _, attach := range attachments {
  324. if err = os.MkdirAll(path.Dir(attach.NewPath), os.ModePerm); err != nil {
  325. isSucceed = false
  326. return err
  327. }
  328. if err = os.Rename(attach.Path, attach.NewPath); err != nil {
  329. isSucceed = false
  330. return err
  331. }
  332. }
  333. return sess.Commit()
  334. }
  335. func renamePullRequestFields(x *xorm.Engine) (err error) {
  336. type PullRequest struct {
  337. ID int64 `xorm:"pk autoincr"`
  338. PullID int64 `xorm:"INDEX"`
  339. PullIndex int64
  340. HeadBarcnh string
  341. IssueID int64 `xorm:"INDEX"`
  342. Index int64
  343. HeadBranch string
  344. }
  345. if err = x.Sync(new(PullRequest)); err != nil {
  346. return fmt.Errorf("sync: %v", err)
  347. }
  348. results, err := x.Query("SELECT `id`,`pull_id`,`pull_index`,`head_barcnh` FROM `pull_request`")
  349. if err != nil {
  350. if strings.Contains(err.Error(), "no such column") {
  351. return nil
  352. }
  353. return fmt.Errorf("select pull requests: %v", err)
  354. }
  355. sess := x.NewSession()
  356. defer sess.Close()
  357. if err = sess.Begin(); err != nil {
  358. return err
  359. }
  360. var pull *PullRequest
  361. for _, pr := range results {
  362. pull = &PullRequest{
  363. ID: com.StrTo(pr["id"]).MustInt64(),
  364. IssueID: com.StrTo(pr["pull_id"]).MustInt64(),
  365. Index: com.StrTo(pr["pull_index"]).MustInt64(),
  366. HeadBranch: string(pr["head_barcnh"]),
  367. }
  368. if pull.Index == 0 {
  369. continue
  370. }
  371. if _, err = sess.Id(pull.ID).Update(pull); err != nil {
  372. return err
  373. }
  374. }
  375. return sess.Commit()
  376. }
  377. func cleanUpMigrateRepoInfo(x *xorm.Engine) (err error) {
  378. type (
  379. User struct {
  380. ID int64 `xorm:"pk autoincr"`
  381. LowerName string
  382. }
  383. Repository struct {
  384. ID int64 `xorm:"pk autoincr"`
  385. OwnerID int64
  386. LowerName string
  387. }
  388. )
  389. repos := make([]*Repository, 0, 25)
  390. if err = x.Where("is_mirror=?", false).Find(&repos); err != nil {
  391. return fmt.Errorf("select all non-mirror repositories: %v", err)
  392. }
  393. var user *User
  394. for _, repo := range repos {
  395. user = &User{ID: repo.OwnerID}
  396. has, err := x.Get(user)
  397. if err != nil {
  398. return fmt.Errorf("get owner of repository[%d - %d]: %v", repo.ID, repo.OwnerID, err)
  399. } else if !has {
  400. continue
  401. }
  402. configPath := filepath.Join(setting.RepoRootPath, user.LowerName, repo.LowerName+".git/config")
  403. // In case repository file is somehow missing.
  404. if !com.IsFile(configPath) {
  405. continue
  406. }
  407. cfg, err := ini.Load(configPath)
  408. if err != nil {
  409. return fmt.Errorf("open config file: %v", err)
  410. }
  411. cfg.DeleteSection("remote \"origin\"")
  412. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  413. return fmt.Errorf("save config file: %v", err)
  414. }
  415. }
  416. return nil
  417. }
  418. func generateOrgRandsAndSalt(x *xorm.Engine) (err error) {
  419. type User struct {
  420. ID int64 `xorm:"pk autoincr"`
  421. Rands string `xorm:"VARCHAR(10)"`
  422. Salt string `xorm:"VARCHAR(10)"`
  423. }
  424. orgs := make([]*User, 0, 10)
  425. if err = x.Where("type=1").And("rands=''").Find(&orgs); err != nil {
  426. return fmt.Errorf("select all organizations: %v", err)
  427. }
  428. sess := x.NewSession()
  429. defer sess.Close()
  430. if err = sess.Begin(); err != nil {
  431. return err
  432. }
  433. for _, org := range orgs {
  434. if org.Rands, err = base.GetRandomString(10); err != nil {
  435. return err
  436. }
  437. if org.Salt, err = base.GetRandomString(10); err != nil {
  438. return err
  439. }
  440. if _, err = sess.Id(org.ID).Update(org); err != nil {
  441. return err
  442. }
  443. }
  444. return sess.Commit()
  445. }
  446. // TAction defines the struct for migrating table action
  447. type TAction struct {
  448. ID int64 `xorm:"pk autoincr"`
  449. CreatedUnix int64
  450. }
  451. // TableName will be invoked by XORM to customrize the table name
  452. func (t *TAction) TableName() string { return "action" }
  453. // TNotice defines the struct for migrating table notice
  454. type TNotice struct {
  455. ID int64 `xorm:"pk autoincr"`
  456. CreatedUnix int64
  457. }
  458. // TableName will be invoked by XORM to customrize the table name
  459. func (t *TNotice) TableName() string { return "notice" }
  460. // TComment defines the struct for migrating table comment
  461. type TComment struct {
  462. ID int64 `xorm:"pk autoincr"`
  463. CreatedUnix int64
  464. }
  465. // TableName will be invoked by XORM to customrize the table name
  466. func (t *TComment) TableName() string { return "comment" }
  467. // TIssue defines the struct for migrating table issue
  468. type TIssue struct {
  469. ID int64 `xorm:"pk autoincr"`
  470. DeadlineUnix int64
  471. CreatedUnix int64
  472. UpdatedUnix int64
  473. }
  474. // TableName will be invoked by XORM to customrize the table name
  475. func (t *TIssue) TableName() string { return "issue" }
  476. // TMilestone defines the struct for migrating table milestone
  477. type TMilestone struct {
  478. ID int64 `xorm:"pk autoincr"`
  479. DeadlineUnix int64
  480. ClosedDateUnix int64
  481. }
  482. // TableName will be invoked by XORM to customrize the table name
  483. func (t *TMilestone) TableName() string { return "milestone" }
  484. // TAttachment defines the struct for migrating table attachment
  485. type TAttachment struct {
  486. ID int64 `xorm:"pk autoincr"`
  487. CreatedUnix int64
  488. }
  489. // TableName will be invoked by XORM to customrize the table name
  490. func (t *TAttachment) TableName() string { return "attachment" }
  491. // TLoginSource defines the struct for migrating table login_source
  492. type TLoginSource struct {
  493. ID int64 `xorm:"pk autoincr"`
  494. CreatedUnix int64
  495. UpdatedUnix int64
  496. }
  497. // TableName will be invoked by XORM to customrize the table name
  498. func (t *TLoginSource) TableName() string { return "login_source" }
  499. // TPull defines the struct for migrating table pull_request
  500. type TPull struct {
  501. ID int64 `xorm:"pk autoincr"`
  502. MergedUnix int64
  503. }
  504. // TableName will be invoked by XORM to customrize the table name
  505. func (t *TPull) TableName() string { return "pull_request" }
  506. // TRelease defines the struct for migrating table release
  507. type TRelease struct {
  508. ID int64 `xorm:"pk autoincr"`
  509. CreatedUnix int64
  510. }
  511. // TableName will be invoked by XORM to customrize the table name
  512. func (t *TRelease) TableName() string { return "release" }
  513. // TRepo defines the struct for migrating table repository
  514. type TRepo struct {
  515. ID int64 `xorm:"pk autoincr"`
  516. CreatedUnix int64
  517. UpdatedUnix int64
  518. }
  519. // TableName will be invoked by XORM to customrize the table name
  520. func (t *TRepo) TableName() string { return "repository" }
  521. // TMirror defines the struct for migrating table mirror
  522. type TMirror struct {
  523. ID int64 `xorm:"pk autoincr"`
  524. UpdatedUnix int64
  525. NextUpdateUnix int64
  526. }
  527. // TableName will be invoked by XORM to customrize the table name
  528. func (t *TMirror) TableName() string { return "mirror" }
  529. // TPublicKey defines the struct for migrating table public_key
  530. type TPublicKey struct {
  531. ID int64 `xorm:"pk autoincr"`
  532. CreatedUnix int64
  533. UpdatedUnix int64
  534. }
  535. // TableName will be invoked by XORM to customrize the table name
  536. func (t *TPublicKey) TableName() string { return "public_key" }
  537. // TDeployKey defines the struct for migrating table deploy_key
  538. type TDeployKey struct {
  539. ID int64 `xorm:"pk autoincr"`
  540. CreatedUnix int64
  541. UpdatedUnix int64
  542. }
  543. // TableName will be invoked by XORM to customrize the table name
  544. func (t *TDeployKey) TableName() string { return "deploy_key" }
  545. // TAccessToken defines the struct for migrating table access_token
  546. type TAccessToken struct {
  547. ID int64 `xorm:"pk autoincr"`
  548. CreatedUnix int64
  549. UpdatedUnix int64
  550. }
  551. // TableName will be invoked by XORM to customrize the table name
  552. func (t *TAccessToken) TableName() string { return "access_token" }
  553. // TUser defines the struct for migrating table user
  554. type TUser struct {
  555. ID int64 `xorm:"pk autoincr"`
  556. CreatedUnix int64
  557. UpdatedUnix int64
  558. }
  559. // TableName will be invoked by XORM to customrize the table name
  560. func (t *TUser) TableName() string { return "user" }
  561. // TWebhook defines the struct for migrating table webhook
  562. type TWebhook struct {
  563. ID int64 `xorm:"pk autoincr"`
  564. CreatedUnix int64
  565. UpdatedUnix int64
  566. }
  567. // TableName will be invoked by XORM to customrize the table name
  568. func (t *TWebhook) TableName() string { return "webhook" }
  569. func convertDateToUnix(x *xorm.Engine) (err error) {
  570. log.Info("This migration could take up to minutes, please be patient.")
  571. type Bean struct {
  572. ID int64 `xorm:"pk autoincr"`
  573. Created time.Time
  574. Updated time.Time
  575. Merged time.Time
  576. Deadline time.Time
  577. ClosedDate time.Time
  578. NextUpdate time.Time
  579. }
  580. var tables = []struct {
  581. name string
  582. cols []string
  583. bean interface{}
  584. }{
  585. {"action", []string{"created"}, new(TAction)},
  586. {"notice", []string{"created"}, new(TNotice)},
  587. {"comment", []string{"created"}, new(TComment)},
  588. {"issue", []string{"deadline", "created", "updated"}, new(TIssue)},
  589. {"milestone", []string{"deadline", "closed_date"}, new(TMilestone)},
  590. {"attachment", []string{"created"}, new(TAttachment)},
  591. {"login_source", []string{"created", "updated"}, new(TLoginSource)},
  592. {"pull_request", []string{"merged"}, new(TPull)},
  593. {"release", []string{"created"}, new(TRelease)},
  594. {"repository", []string{"created", "updated"}, new(TRepo)},
  595. {"mirror", []string{"updated", "next_update"}, new(TMirror)},
  596. {"public_key", []string{"created", "updated"}, new(TPublicKey)},
  597. {"deploy_key", []string{"created", "updated"}, new(TDeployKey)},
  598. {"access_token", []string{"created", "updated"}, new(TAccessToken)},
  599. {"user", []string{"created", "updated"}, new(TUser)},
  600. {"webhook", []string{"created", "updated"}, new(TWebhook)},
  601. }
  602. for _, table := range tables {
  603. log.Info("Converting table: %s", table.name)
  604. if err = x.Sync2(table.bean); err != nil {
  605. return fmt.Errorf("Sync [table: %s]: %v", table.name, err)
  606. }
  607. offset := 0
  608. for {
  609. beans := make([]*Bean, 0, 100)
  610. if err = x.Table(table.name).Asc("id").Limit(100, offset).Find(&beans); err != nil {
  611. return fmt.Errorf("select beans [table: %s, offset: %d]: %v", table.name, offset, err)
  612. }
  613. log.Trace("Table [%s]: offset: %d, beans: %d", table.name, offset, len(beans))
  614. if len(beans) == 0 {
  615. break
  616. }
  617. offset += 100
  618. baseSQL := "UPDATE `" + table.name + "` SET "
  619. for _, bean := range beans {
  620. valSQLs := make([]string, 0, len(table.cols))
  621. for _, col := range table.cols {
  622. fieldSQL := ""
  623. fieldSQL += col + "_unix = "
  624. switch col {
  625. case "deadline":
  626. if bean.Deadline.IsZero() {
  627. continue
  628. }
  629. fieldSQL += com.ToStr(bean.Deadline.Unix())
  630. case "created":
  631. fieldSQL += com.ToStr(bean.Created.Unix())
  632. case "updated":
  633. fieldSQL += com.ToStr(bean.Updated.Unix())
  634. case "closed_date":
  635. fieldSQL += com.ToStr(bean.ClosedDate.Unix())
  636. case "merged":
  637. fieldSQL += com.ToStr(bean.Merged.Unix())
  638. case "next_update":
  639. fieldSQL += com.ToStr(bean.NextUpdate.Unix())
  640. }
  641. valSQLs = append(valSQLs, fieldSQL)
  642. }
  643. if len(valSQLs) == 0 {
  644. continue
  645. }
  646. if _, err = x.Exec(baseSQL + strings.Join(valSQLs, ",") + " WHERE id = " + com.ToStr(bean.ID)); err != nil {
  647. return fmt.Errorf("update bean [table: %s, id: %d]: %v", table.name, bean.ID, err)
  648. }
  649. }
  650. }
  651. }
  652. return nil
  653. }