-
Notifications
You must be signed in to change notification settings - Fork 249
/
currency_db.go
73 lines (60 loc) · 1.41 KB
/
currency_db.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
package currency
import (
"context"
"database/sql"
)
type DB struct {
db *sql.DB
}
func NewCurrencyDB(sqlDb *sql.DB) *DB {
return &DB{
db: sqlDb,
}
}
func getCachedFormatsFromDBRows(rows *sql.Rows) (FormatPerSymbol, error) {
formats := make(FormatPerSymbol)
for rows.Next() {
var format Format
if err := rows.Scan(&format.Symbol, &format.DisplayDecimals, &format.StripTrailingZeroes); err != nil {
return nil, err
}
formats[format.Symbol] = format
}
return formats, nil
}
func (cdb *DB) GetCachedFormats() (FormatPerSymbol, error) {
rows, err := cdb.db.Query("SELECT symbol, display_decimals, strip_trailing_zeroes FROM currency_format_cache")
if err != nil {
return nil, err
}
defer rows.Close()
return getCachedFormatsFromDBRows(rows)
}
func (cdb *DB) UpdateCachedFormats(formats FormatPerSymbol) error {
tx, err := cdb.db.BeginTx(context.Background(), &sql.TxOptions{})
if err != nil {
return err
}
defer func() {
if err == nil {
err = tx.Commit()
return
}
// don't shadow original error
_ = tx.Rollback()
}()
insert, err := tx.Prepare(`INSERT OR REPLACE INTO currency_format_cache
(symbol, display_decimals, strip_trailing_zeroes)
VALUES
(?, ?, ?)`)
if err != nil {
return err
}
for _, format := range formats {
_, err = insert.Exec(format.Symbol, format.DisplayDecimals, format.StripTrailingZeroes)
if err != nil {
return err
}
}
return nil
}