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

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