You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

migrations.go 21 kB

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