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

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