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

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