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

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