-
Notifications
You must be signed in to change notification settings - Fork 11
/
builds.go
119 lines (103 loc) · 2.78 KB
/
builds.go
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package migrate
import (
"database/sql"
"fmt"
"github.com/russross/meddler"
"github.com/sirupsen/logrus"
)
// MigrateBuilds migrates the builds from the V0
// database to the V1 database.
func MigrateBuilds(source, target *sql.DB) error {
buildsV0 := []*BuildV0{}
// 1. load all repos from the V0 database.
err := meddler.QueryAll(source, &buildsV0, "select * from builds")
if err != nil {
return err
}
logrus.Infof("migrating %d builds", len(buildsV0))
// 2. create a database transaction so that we
// can rollback if the data migration fails.
tx, err := target.Begin()
if err != nil {
return err
}
defer tx.Rollback()
// 3. iterate through the list and convert from
// the 0.x to the 1.x structure and insert.
var sequence int64
for _, buildV0 := range buildsV0 {
if buildV0.ID > sequence {
sequence = buildV0.ID
}
log := logrus.
WithField("repository", buildV0.RepoID).
WithField("build", buildV0.Number)
log.Debugln("migrate build")
buildV1 := &BuildV1{
ID: buildV0.ID,
RepoID: buildV0.RepoID,
Trigger: "@hook",
Number: buildV0.Number,
Parent: buildV0.Parent,
Status: buildV0.Status,
Error: buildV0.Error,
Event: buildV0.Event,
Action: "",
Link: buildV0.Link,
Timestamp: buildV0.Timestamp,
Title: buildV0.Title,
Message: buildV0.Message,
Before: buildV0.Commit,
After: buildV0.Commit,
Ref: buildV0.Ref,
Fork: "",
Source: buildV0.Branch,
Target: buildV0.Branch,
Author: buildV0.Author,
AuthorName: buildV0.Author,
AuthorEmail: buildV0.Email,
AuthorAvatar: buildV0.Avatar,
Sender: buildV0.Sender,
Params: map[string]string{},
Deploy: buildV0.Deploy,
Started: buildV0.Started,
Finished: buildV0.Finished,
Created: buildV0.Created,
Updated: buildV0.Created,
Version: 1,
}
if len(buildV1.Message) > 1000 {
buildV1.Message = buildV1.Message[:1000]
}
if len(buildV1.Title) > 1000 {
buildV1.Title = buildV1.Title[:1000]
}
err = meddler.Insert(tx, "builds", buildV1)
if err != nil {
log.WithError(err).Errorln("migration failed")
return err
}
//
// migrate stages.
//
log.Debugln("build migration complete")
}
if meddler.Default == meddler.PostgreSQL {
_, err = tx.Exec(fmt.Sprintf(updateBuildSeq, sequence+1))
if err != nil {
logrus.WithError(err).Errorln("failed to reset sequence")
return err
}
}
logrus.Infof("migration complete")
return tx.Commit()
}
const buildListQuery = `
SELECT builds.*
FROM builds INNER JOIN repos ON build.build_repo_id = repos.repo_id
WHERE repos.repo_user_id > 0
`
const updateBuildSeq = `
ALTER SEQUENCE builds_build_id_seq
RESTART WITH %d
`