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

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