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

88 lines
1.8 KiB

  1. // Copyright 2018 The Gitea 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. "fmt"
  7. "github.com/go-xorm/xorm"
  8. )
  9. func moveTeamUnitsToTeamUnitTable(x *xorm.Engine) error {
  10. // Team see models/team.go
  11. type Team struct {
  12. ID int64
  13. OrgID int64
  14. UnitTypes []int `xorm:"json"`
  15. }
  16. // TeamUnit see models/org_team.go
  17. type TeamUnit struct {
  18. ID int64 `xorm:"pk autoincr"`
  19. OrgID int64 `xorm:"INDEX"`
  20. TeamID int64 `xorm:"UNIQUE(s)"`
  21. Type int `xorm:"UNIQUE(s)"`
  22. }
  23. if err := x.Sync2(new(TeamUnit)); err != nil {
  24. return fmt.Errorf("Sync2: %v", err)
  25. }
  26. sess := x.NewSession()
  27. defer sess.Close()
  28. if err := sess.Begin(); err != nil {
  29. return err
  30. }
  31. // Update team unit types
  32. const batchSize = 100
  33. for start := 0; ; start += batchSize {
  34. teams := make([]*Team, 0, batchSize)
  35. if err := x.Limit(batchSize, start).Find(&teams); err != nil {
  36. return err
  37. }
  38. if len(teams) == 0 {
  39. break
  40. }
  41. for _, team := range teams {
  42. var unitTypes []int
  43. if len(team.UnitTypes) == 0 {
  44. unitTypes = allUnitTypes
  45. } else {
  46. unitTypes = team.UnitTypes
  47. }
  48. // insert units for team
  49. var units = make([]TeamUnit, 0, len(unitTypes))
  50. for _, tp := range unitTypes {
  51. units = append(units, TeamUnit{
  52. OrgID: team.OrgID,
  53. TeamID: team.ID,
  54. Type: tp,
  55. })
  56. }
  57. if _, err := sess.Insert(&units); err != nil {
  58. return fmt.Errorf("Insert team units: %v", err)
  59. }
  60. }
  61. }
  62. // Commit and begin new transaction for dropping columns
  63. if err := sess.Commit(); err != nil {
  64. return err
  65. }
  66. if err := sess.Begin(); err != nil {
  67. return err
  68. }
  69. if err := dropTableColumns(sess, "team", "unit_types"); err != nil {
  70. return err
  71. }
  72. return sess.Commit()
  73. }