Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

migrations.go 20KB

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