This repository has been archived by the owner on Mar 28, 2023. It is now read-only.
/
Migration010.go
100 lines (83 loc) · 2.32 KB
/
Migration010.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
package migrations
import (
"database/sql"
"github.com/OpenBazaar/jsonpb"
"github.com/OpenBazaar/openbazaar-go/pb"
_ "github.com/mutecomm/go-sqlcipher"
)
type Migration010 struct{}
func (Migration010) Up(repoPath string, dbPassword string, testnet bool) (err error) {
db, err := OpenDB(repoPath, dbPassword, testnet)
if err != nil {
return err
}
err = migration010UpdateTablesCoins(db, "cases", "caseID", "COALESCE(buyerContract, vendorContract) AS contract")
if err != nil {
return err
}
err = migration010UpdateTablesCoins(db, "sales", "orderID", "contract")
if err != nil {
return err
}
err = migration010UpdateTablesCoins(db, "purchases", "orderID", "contract")
if err != nil {
return err
}
err = writeRepoVer(repoPath, 11)
if err != nil {
return err
}
return nil
}
func (Migration010) Down(repoPath string, dbPassword string, testnet bool) error {
// Down migration is a no-op (outsie of updating the version)
// We can't know which entries columns used to be blank so we can't blank only
// those entries
return writeRepoVer(repoPath, 10)
}
func migration010UpdateTablesCoins(db *sql.DB, table string, idColumn string, contractColumn string) error {
type coinset struct {
paymentCoin string
coinType string
}
// Get all records for table and store the coinset for each entry
rows, err := db.Query("SELECT " + idColumn + ", " + contractColumn + " FROM " + table + " WHERE paymentCoin = '' or coinType = '';")
if err != nil {
return err
}
defer rows.Close()
coinsToSet := map[string]coinset{}
for rows.Next() {
var orderID, marshaledContract string
err = rows.Scan(&orderID, &marshaledContract)
if err != nil {
return err
}
if marshaledContract == "" {
continue
}
contract := &pb.RicardianContract{}
if err := jsonpb.UnmarshalString(marshaledContract, contract); err != nil {
return err
}
coinsToSet[orderID] = coinset{
coinType: coinTypeForContract(contract),
paymentCoin: paymentCoinForContract(contract),
}
}
// Update each row with the coins
err = withTransaction(db, func(tx *sql.Tx) error {
for id, coins := range coinsToSet {
_, err := tx.Exec(
"UPDATE "+table+" SET coinType = ?, paymentCoin = ? WHERE "+idColumn+" = ?",
coins.coinType,
coins.paymentCoin,
id)
if err != nil {
return err
}
}
return nil
})
return err
}