summaryrefslogtreecommitdiffstats
path: root/models/migrations/v41.go
blob: 928bb1cd3fcbfd5494c5e1c1463f1273aad3f6d2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Copyright 2017 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package migrations

import (
	"fmt"

	"xorm.io/xorm"
)

func removeDuplicateUnitTypes(x *xorm.Engine) error {
	// RepoUnit describes all units of a repository
	type RepoUnit struct {
		RepoID int64
		Type   int
	}

	// Enumerate all the unit types
	const (
		UnitTypeCode            = iota + 1 // 1 code
		UnitTypeIssues                     // 2 issues
		UnitTypePullRequests               // 3 PRs
		UnitTypeReleases                   // 4 Releases
		UnitTypeWiki                       // 5 Wiki
		UnitTypeExternalWiki               // 6 ExternalWiki
		UnitTypeExternalTracker            // 7 ExternalTracker
	)

	var externalIssueRepoUnits []RepoUnit
	err := x.Where("type = ?", UnitTypeExternalTracker).Find(&externalIssueRepoUnits)
	if err != nil {
		return fmt.Errorf("Query repositories: %v", err)
	}

	var externalWikiRepoUnits []RepoUnit
	err = x.Where("type = ?", UnitTypeExternalWiki).Find(&externalWikiRepoUnits)
	if err != nil {
		return fmt.Errorf("Query repositories: %v", err)
	}

	sess := x.NewSession()
	defer sess.Close()

	if err := sess.Begin(); err != nil {
		return err
	}

	for _, repoUnit := range externalIssueRepoUnits {
		if _, err = sess.Delete(&RepoUnit{
			RepoID: repoUnit.RepoID,
			Type:   UnitTypeIssues,
		}); err != nil {
			return fmt.Errorf("Delete repo unit: %v", err)
		}
	}

	for _, repoUnit := range externalWikiRepoUnits {
		if _, err = sess.Delete(&RepoUnit{
			RepoID: repoUnit.RepoID,
			Type:   UnitTypeWiki,
		}); err != nil {
			return fmt.Errorf("Delete repo unit: %v", err)
		}
	}

	return sess.Commit()
}