forked from vmware-archive/atc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
136_add_source_hash_to_resources.go
74 lines (60 loc) · 1.47 KB
/
136_add_source_hash_to_resources.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
package migrations
import (
"crypto/sha256"
"encoding/json"
"fmt"
"github.com/concourse/atc"
"github.com/concourse/atc/db/migration"
)
func AddSourceHashToResources(tx migration.LimitedTx) error {
_, err := tx.Exec(`
ALTER TABLE resources
ADD COLUMN source_hash text
`)
if err != nil {
return err
}
rows, err := tx.Query(`SELECT id, config FROM resources`)
if err != nil {
return err
}
defer rows.Close()
resourceSourceHashes := map[int]string{}
for rows.Next() {
var resourceID int
var resourceConfigJSON string
err = rows.Scan(&resourceID, &resourceConfigJSON)
if err != nil {
return fmt.Errorf("failed to scan resource ID and resource config: %s", err)
}
var resourceConfig atc.ResourceConfig
err = json.Unmarshal([]byte(resourceConfigJSON), &resourceConfig)
if err != nil {
return fmt.Errorf("failed to unmarshal resource config: %s", err)
}
sourceJSON, err := json.Marshal(resourceConfig.Source)
if err != nil {
return fmt.Errorf("failed to marshal resource source: %s", err)
}
sourceHash := fmt.Sprintf("%x", sha256.Sum256(sourceJSON))
resourceSourceHashes[resourceID] = sourceHash
}
for resourceID, sourceHash := range resourceSourceHashes {
_, err = tx.Exec(`
UPDATE resources
SET source_hash = $1
WHERE id = $2
`, sourceHash, resourceID)
if err != nil {
return err
}
}
_, err = tx.Exec(`
ALTER TABLE resources
ALTER COLUMN source_hash SET NOT NULL
`)
if err != nil {
return err
}
return nil
}