-
Notifications
You must be signed in to change notification settings - Fork 0
/
awards.go
82 lines (67 loc) · 1.84 KB
/
awards.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
package db
import "database/sql"
type AwardOperation int
const (
AwardIncrement AwardOperation = iota
AwardDecrement
)
type LeaderboardEntry struct {
AwardName string
EarnerId string
Count int
}
type AwardKV map[string]int
func QueryLeaderboard(db *sql.DB, guild_id string) ([]LeaderboardEntry, error) {
entries := []LeaderboardEntry{}
res, err := db.Query(`select award_name, earner_id, max(count) from award where guild_id = ? group by award_name`, guild_id)
if err != nil {
return nil, err
}
defer res.Close()
for res.Next() {
var leaderboardEntry LeaderboardEntry
res.Scan(&leaderboardEntry.AwardName, &leaderboardEntry.EarnerId, &leaderboardEntry.Count)
entries = append(entries, leaderboardEntry)
}
res.Close()
return entries, nil
}
func QueryAwardCounts(db *sql.DB, guild_id string, earner_id string) (AwardKV, error) {
kv := make(AwardKV)
res, err := db.Query(`SELECT award_name, count FROM award WHERE guild_id = ? AND earner_id = ?`, guild_id, earner_id)
if err != nil {
return nil, err
}
defer res.Close()
for res.Next() {
var award_name string
var count int
res.Scan(&award_name, &count)
kv[award_name] = count
}
res.Close()
return kv, nil
}
func MutateAwardCount(db *sql.DB, guild_id string, earner_id string, award_name string, op AwardOperation) error {
var err error
switch op {
case AwardIncrement:
_, err = db.Exec(`
INSERT INTO award(guild_id, earner_id, award_name)
VALUES (?, ?, ?)
ON CONFLICT(guild_id, earner_id, award_name)
DO UPDATE SET count = count+1
`, guild_id, earner_id, award_name)
case AwardDecrement:
_, err = db.Exec(`
INSERT INTO award(guild_id, earner_id, award_name)
VALUES (?, ?, ?)
ON CONFLICT(guild_id, earner_id, award_name)
DO UPDATE SET count = count-1
`, guild_id, earner_id, award_name)
}
if err != nil {
return err
}
return nil
}