forked from OpenBazaar/openbazaar-go
-
Notifications
You must be signed in to change notification settings - Fork 3
/
coupons.go
62 lines (56 loc) · 1.22 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
package db
import (
"database/sql"
"sync"
"github.com/OpenBazaar/openbazaar-go/repo"
)
type CouponDB struct {
db *sql.DB
lock sync.RWMutex
}
func (c *CouponDB) Put(coupons []repo.Coupon) error {
c.lock.Lock()
defer c.lock.Unlock()
tx, _ := c.db.Begin()
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 {
tx.Rollback()
return err
}
}
tx.Commit()
return nil
}
func (c *CouponDB) Get(slug string) ([]repo.Coupon, error) {
c.lock.RLock()
defer c.lock.RUnlock()
var stm string
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
rows.Scan(&slug, &code, &hash)
ret = append(ret, repo.Coupon{slug, code, 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
}