summaryrefslogtreecommitdiffstats
path: root/models/migrations/v1_10/v88.go
blob: 32659006ea9d4c7b8182f9ea237f6759992c74e6 (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
// Copyright 2019 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 v1_10 //nolint

import (
	"crypto/sha1"
	"fmt"

	"xorm.io/xorm"
)

func hashContext(context string) string {
	return fmt.Sprintf("%x", sha1.Sum([]byte(context)))
}

func AddCommitStatusContext(x *xorm.Engine) error {
	type CommitStatus struct {
		ID          int64  `xorm:"pk autoincr"`
		ContextHash string `xorm:"char(40) index"`
		Context     string `xorm:"TEXT"`
	}

	if err := x.Sync2(new(CommitStatus)); err != nil {
		return err
	}

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

	start := 0
	for {
		statuses := make([]*CommitStatus, 0, 100)
		err := sess.OrderBy("id").Limit(100, start).Find(&statuses)
		if err != nil {
			return err
		}
		if len(statuses) == 0 {
			break
		}

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

		for _, status := range statuses {
			status.ContextHash = hashContext(status.Context)
			if _, err := sess.ID(status.ID).Cols("context_hash").Update(status); err != nil {
				return err
			}
		}

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

		if len(statuses) < 100 {
			break
		}

		start += len(statuses)
	}

	return nil
}