forked from OpenBazaar/openbazaar-go
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Migration009.go
386 lines (334 loc) · 12.5 KB
/
Migration009.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
package migrations
import (
"database/sql"
"encoding/json"
"io/ioutil"
"os"
"path"
"github.com/OpenBazaar/jsonpb"
"github.com/OpenBazaar/openbazaar-go/pb"
_ "github.com/mutecomm/go-sqlcipher"
)
type Migration009 struct{}
type Migration009_price struct {
CurrencyCode string `json:"currencyCode"`
Amount uint64 `json:"amount"`
}
type Migration009_thumbnail struct {
Tiny string `json:"tiny"`
Small string `json:"small"`
Medium string `json:"medium"`
}
type Migration009_listingDataBeforeMigration struct {
Hash string `json:"hash"`
Slug string `json:"slug"`
Title string `json:"title"`
Categories []string `json:"categories"`
NSFW bool `json:"nsfw"`
CoinType string `json:"coinType"`
ContractType string `json:"contractType"`
Description string `json:"description"`
Thumbnail Migration009_thumbnail `json:"thumbnail"`
Price Migration009_price `json:"price"`
ShipsTo []string `json:"shipsTo"`
FreeShipping []string `json:"freeShipping"`
Language string `json:"language"`
AverageRating float32 `json:"averageRating"`
RatingCount uint32 `json:"ratingCount"`
ModeratorIDs []string `json:"moderators"`
}
type Migration009_listingDataAfterMigration struct {
Hash string `json:"hash"`
Slug string `json:"slug"`
Title string `json:"title"`
Categories []string `json:"categories"`
NSFW bool `json:"nsfw"`
CoinType string `json:"coinType"`
ContractType string `json:"contractType"`
Description string `json:"description"`
Thumbnail Migration009_thumbnail `json:"thumbnail"`
Price Migration009_price `json:"price"`
ShipsTo []string `json:"shipsTo"`
FreeShipping []string `json:"freeShipping"`
Language string `json:"language"`
AverageRating float32 `json:"averageRating"`
RatingCount uint32 `json:"ratingCount"`
ModeratorIDs []string `json:"moderators"`
// Adding AcceptedCurrencies
AcceptedCurrencies []string `json:"acceptedCurrencies"`
}
type Migration009_listing struct {
Listing Migration009_listing_listing `json:"listing"`
}
type Migration009_listing_listing struct {
Metadata Migration009_listing_listing_metadata `json:"metadata"`
}
type Migration009_listing_listing_metadata struct {
AcceptedCurrencies []string `json:"acceptedCurrencies"`
}
const (
Migration009CreatePreviousCasesTable = "create table cases (caseID text primary key not null, buyerContract blob, vendorContract blob, buyerValidationErrors blob, vendorValidationErrors blob, buyerPayoutAddress text, vendorPayoutAddress text, buyerOutpoints blob, vendorOutpoints blob, state integer, read integer, timestamp integer, buyerOpened integer, claim text, disputeResolution blob, lastDisputeExpiryNotifiedAt integer not null default 0);"
Migration009CreatePreviousSalesTable = "create table sales (orderID text primary key not null, contract blob, state integer, read integer, timestamp integer, total integer, thumbnail text, buyerID text, buyerHandle text, title text, shippingName text, shippingAddress text, paymentAddr text, funded integer, transactions blob, needsSync integer, lastDisputeTimeoutNotifiedAt integer not null default 0);"
Migration009CreatePreviousSalesIndex = "create index index_sales on sales (paymentAddr, timestamp);"
Migration009CreatePreviousPurchasesTable = "create table purchases (orderID text primary key not null, contract blob, state integer, read integer, timestamp integer, total integer, thumbnail text, vendorID text, vendorHandle text, title text, shippingName text, shippingAddress text, paymentAddr text, funded integer, transactions blob, lastDisputeTimeoutNotifiedAt integer not null default 0, lastDisputeExpiryNotifiedAt integer not null default 0, disputedAt integer not null default 0);"
)
func (Migration009) Up(repoPath string, dbPassword string, testnet bool) (err error) {
db, err := OpenDB(repoPath, dbPassword, testnet)
if err != nil {
return err
}
// Update DB schema
err = withTransaction(db, func(tx *sql.Tx) error {
for _, stmt := range []string{
"ALTER TABLE cases ADD COLUMN coinType text NOT NULL DEFAULT '';",
"ALTER TABLE sales ADD COLUMN coinType text NOT NULL DEFAULT '';",
"ALTER TABLE purchases ADD COLUMN coinType text NOT NULL DEFAULT '';",
"ALTER TABLE cases ADD COLUMN paymentCoin text NOT NULL DEFAULT '';",
"ALTER TABLE sales ADD COLUMN paymentCoin text NOT NULL DEFAULT '';",
"ALTER TABLE purchases ADD COLUMN paymentCoin text NOT NULL DEFAULT '';",
} {
_, err := tx.Exec(stmt)
if err != nil {
return err
}
}
return nil
})
if err != nil {
return err
}
// Update repover now that the schema is changed
err = writeRepoVer(repoPath, 10)
if err != nil {
return err
}
// Update DB data on a best effort basis
err = migration009UpdateTablesCoins(db, "cases", "caseID", "COALESCE(buyerContract, vendorContract) AS contract")
if err != nil {
return err
}
err = migration009UpdateTablesCoins(db, "sales", "orderID", "contract")
if err != nil {
return err
}
err = migration009UpdateTablesCoins(db, "purchases", "orderID", "contract")
if err != nil {
return err
}
err = migration009MigrateListingsIndexUp(repoPath)
if err != nil {
return err
}
return nil
}
func (Migration009) Down(repoPath string, dbPassword string, testnet bool) error {
db, err := OpenDB(repoPath, dbPassword, testnet)
if err != nil {
return err
}
err = withTransaction(db, func(tx *sql.Tx) error {
for _, stmt := range []string{
"ALTER TABLE cases RENAME TO temp_cases;",
Migration009CreatePreviousCasesTable,
"INSERT INTO cases SELECT caseID, buyerContract, vendorContract, buyerValidationErrors, vendorValidationErrors, buyerPayoutAddress, vendorPayoutAddress, buyerOutpoints, vendorOutpoints, state, read, timestamp, buyerOpened, claim, disputeResolution, lastDisputeExpiryNotifiedAt FROM temp_cases;",
"DROP TABLE temp_cases;",
"ALTER TABLE sales RENAME TO temp_sales;",
Migration009CreatePreviousSalesTable,
Migration009CreatePreviousSalesIndex,
"INSERT INTO sales SELECT orderID, contract, state, read, timestamp, total, thumbnail, buyerID, buyerHandle, title, shippingName, shippingAddress, paymentAddr, funded, transactions, needsSync, lastDisputeTimeoutNotifiedAt FROM temp_sales;",
"DROP TABLE temp_sales;",
"ALTER TABLE purchases RENAME TO temp_purchases;",
Migration009CreatePreviousPurchasesTable,
"INSERT INTO purchases SELECT orderID, contract, state, read, timestamp, total, thumbnail, vendorID, vendorHandle, title, shippingName, shippingAddress, paymentAddr, funded, transactions, lastDisputeTimeoutNotifiedAt, lastDisputeExpiryNotifiedAt, disputedAt FROM temp_purchases;",
"DROP TABLE temp_purchases;",
} {
_, err := tx.Exec(stmt)
if err != nil {
return err
}
}
return nil
})
if err != nil {
return err
}
err = writeRepoVer(repoPath, 9)
if err != nil {
return err
}
err = migration009MigrateListingsIndexDown(repoPath)
if err != nil {
return err
}
return nil
}
func migration009UpdateTablesCoins(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 + ";")
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
}
func paymentCoinForContract(contract *pb.RicardianContract) string {
paymentCoin := contract.BuyerOrder.Payment.Coin
if paymentCoin != "" {
return paymentCoin
}
if len(contract.VendorListings[0].Metadata.AcceptedCurrencies) > 0 {
paymentCoin = contract.VendorListings[0].Metadata.AcceptedCurrencies[0]
}
return paymentCoin
}
func coinTypeForContract(contract *pb.RicardianContract) string {
coinType := ""
if len(contract.VendorListings) > 0 {
coinType = contract.VendorListings[0].Metadata.CoinType
}
return coinType
}
func migration009MigrateListingsIndexUp(repoPath string) error {
listingsFilePath := path.Join(repoPath, "root", "listings.json")
if _, err := os.Stat(listingsFilePath); os.IsNotExist(err) {
return nil
}
var (
err error
paymentCoin string
listingJSON []byte
listingsJSON []byte
listingRecord Migration009_listing
listingRecords []Migration009_listingDataBeforeMigration
migratedRecords []Migration009_listingDataAfterMigration
)
listingsJSON, err = ioutil.ReadFile(listingsFilePath)
if err != nil {
return err
}
if err = json.Unmarshal(listingsJSON, &listingRecords); err != nil {
return err
}
for _, listing := range listingRecords {
if paymentCoin == "" {
listingFilePath := path.Join(repoPath, "root", "listings", listing.Slug+".json")
listingJSON, err = ioutil.ReadFile(listingFilePath)
if err != nil {
return err
}
if err = json.Unmarshal(listingJSON, &listingRecord); err != nil {
return err
}
paymentCoin = listingRecord.Listing.Metadata.AcceptedCurrencies[0]
}
migratedRecords = append(migratedRecords, Migration009_listingDataAfterMigration{
Hash: listing.Hash,
Slug: listing.Slug,
Title: listing.Title,
Categories: listing.Categories,
NSFW: listing.NSFW,
ContractType: listing.ContractType,
Description: listing.Description,
Thumbnail: listing.Thumbnail,
Price: listing.Price,
ShipsTo: listing.ShipsTo,
FreeShipping: listing.FreeShipping,
Language: listing.Language,
AverageRating: listing.AverageRating,
RatingCount: listing.RatingCount,
CoinType: listing.CoinType,
AcceptedCurrencies: []string{paymentCoin},
})
}
if listingsJSON, err = json.MarshalIndent(migratedRecords, "", " "); err != nil {
return err
}
err = ioutil.WriteFile(listingsFilePath, listingsJSON, os.ModePerm)
if err != nil {
return err
}
return nil
}
func migration009MigrateListingsIndexDown(repoPath string) error {
listingsFilePath := path.Join(repoPath, "root", "listings.json")
if _, err := os.Stat(listingsFilePath); os.IsNotExist(err) {
return nil
}
var (
err error
listingsJSON []byte
listingRecords []Migration009_listingDataAfterMigration
migratedRecords []Migration009_listingDataBeforeMigration
)
listingsJSON, err = ioutil.ReadFile(listingsFilePath)
if err != nil {
return err
}
if err = json.Unmarshal(listingsJSON, &listingRecords); err != nil {
return err
}
for _, listing := range listingRecords {
migratedRecords = append(migratedRecords, Migration009_listingDataBeforeMigration{
Hash: listing.Hash,
Slug: listing.Slug,
Title: listing.Title,
Categories: listing.Categories,
NSFW: listing.NSFW,
ContractType: listing.ContractType,
Description: listing.Description,
Thumbnail: listing.Thumbnail,
Price: listing.Price,
ShipsTo: listing.ShipsTo,
FreeShipping: listing.FreeShipping,
Language: listing.Language,
AverageRating: listing.AverageRating,
RatingCount: listing.RatingCount,
CoinType: listing.CoinType,
})
}
if listingsJSON, err = json.MarshalIndent(migratedRecords, "", " "); err != nil {
return err
}
err = ioutil.WriteFile(listingsFilePath, listingsJSON, os.ModePerm)
if err != nil {
return err
}
return nil
}