forked from OpenBazaar/openbazaar-go
/
coupons.go
76 lines (68 loc) · 1.74 KB
/
coupons.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
package db
import (
"database/sql"
"fmt"
"sync"
"github.com/phoreproject/pm-go/repo"
)
type CouponDB struct {
modelStore
}
func NewCouponStore(db *sql.DB, lock *sync.Mutex) repo.CouponStore {
return &CouponDB{modelStore{db, lock}}
}
func (c *CouponDB) Put(coupons []repo.Coupon) error {
c.lock.Lock()
defer c.lock.Unlock()
tx, _ := c.BeginTransaction()
for _, coupon := range coupons {
stmt, _ := tx.Prepare("insert or replace into coupons(slug, code, hash) values(?,?,?)")
defer stmt.Close()
_, err := stmt.Exec(coupon.Slug, coupon.Code, coupon.Hash)
if err != nil {
if rErr := tx.Rollback(); rErr != nil {
return fmt.Errorf("add coupon: (%s) w rollback error: (%s)", err.Error(), rErr.Error())
}
return fmt.Errorf("add coupon: %s", err.Error())
}
}
if err := tx.Commit(); err != nil {
if rErr := tx.Rollback(); rErr != nil {
return fmt.Errorf("commit coupon: (%s) w rollback error: (%s)", err.Error(), rErr.Error())
}
return fmt.Errorf("commit coupon: %s", err.Error())
}
return nil
}
func (c *CouponDB) Get(slug string) ([]repo.Coupon, error) {
c.lock.Lock()
defer c.lock.Unlock()
stm := "select slug, code, hash from coupons where slug='" + slug + "';"
rows, err := c.db.Query(stm)
if err != nil {
log.Error(err)
return nil, err
}
defer rows.Close()
var ret []repo.Coupon
for rows.Next() {
var slug string
var code string
var hash string
err = rows.Scan(&slug, &code, &hash)
if err != nil {
log.Error(err)
}
ret = append(ret, repo.Coupon{Slug: slug, Code: code, Hash: hash})
}
return ret, nil
}
func (c *CouponDB) Delete(slug string) error {
c.lock.Lock()
defer c.lock.Unlock()
_, err := c.db.Exec("delete from coupons where slug=?", slug)
if err != nil {
return err
}
return nil
}