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